From de96147c5a791a5d302365568bc610415e13dc90 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 08:30:26 +0000 Subject: [PATCH 01/17] feat(policy): add safedep policy commands for cloud policy management Admins had no CLI for the tenant policy of SafeDep Cloud. This change adds the safedep policy tree for safedep/control-tower#1590: - policy show, get and edit. Edit opens the policy settings document in the editor and saves it as a policy change. A file that does not parse opens again with the error at the top. - policy change list, show, edit, sync, delete and publish. Change create --from-revision makes a rollback change. - policy revision list and show. - policy rule create, list, show, update and delete. Rule create --block -f reads a bulk list. --scope all expands to every trust scope that the SDK knows, because the contract has no "all" value. A trust entry cannot use a prefix, and the CLI says so before the request. Duration flags accept a day unit, as in --expires 30d. Every data command writes table, plain and JSON output. The change bumps the API SDK to 20261031065119-dc85a10c2beb and adds the verb publish, which makes a policy change live as a new revision. The new package internal/cloudpolicy holds the YAML form of the policy, labels, label selectors and the policy of one subject, so the project and endpoint trees can use them too. The subscription tree now reads the error reason through the new internal/rpcerror package. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MhRi597EX9odoSDXbVBsxz --- .mockery.yml | 11 + README.md | 22 + docs/cmd/policy-change-create.md | 48 + docs/cmd/policy-change-delete.md | 30 + docs/cmd/policy-change-edit.md | 47 + docs/cmd/policy-change-list.md | 50 + docs/cmd/policy-change-publish.md | 48 + docs/cmd/policy-change-show.md | 62 + docs/cmd/policy-change-sync.md | 34 + docs/cmd/policy-edit.md | 75 + docs/cmd/policy-get.md | 74 + docs/cmd/policy-revision-list.md | 49 + docs/cmd/policy-revision-show.md | 45 + docs/cmd/policy-rule-create.md | 95 + docs/cmd/policy-rule-delete.md | 40 + docs/cmd/policy-rule-list.md | 59 + docs/cmd/policy-rule-show.md | 40 + docs/cmd/policy-rule-update.md | 45 + docs/cmd/policy-show.md | 66 + go.mod | 6 +- go.sum | 8 +- internal/app/app.go | 18 + internal/cloudpolicy/document.go | 174 ++ internal/cloudpolicy/document_test.go | 217 +++ internal/cloudpolicy/fields.go | 254 +++ internal/cloudpolicy/fields_test.go | 63 + internal/cloudpolicy/fixtures_test.go | 56 + internal/cloudpolicy/labels.go | 278 +++ internal/cloudpolicy/labels_test.go | 86 + internal/cloudpolicy/labelwriter.go | 91 + internal/cloudpolicy/labelwriter_test.go | 66 + .../mocks/LabelServiceClient_mock.go | 289 ++++ .../mocks/PolicyServiceClient_mock.go | 1534 +++++++++++++++++ internal/cloudpolicy/protoyaml.go | 564 ++++++ internal/cloudpolicy/render.go | 34 + internal/cloudpolicy/subject.go | 415 +++++ internal/cloudpolicy/subject_test.go | 163 ++ internal/cmd/policy/change_create.go | 141 ++ internal/cmd/policy/change_list.go | 213 +++ internal/cmd/policy/change_ops.go | 245 +++ internal/cmd/policy/change_show.go | 353 ++++ internal/cmd/policy/change_test.go | 302 ++++ internal/cmd/policy/cmd.go | 59 + internal/cmd/policy/edit.go | 251 +++ internal/cmd/policy/edit_test.go | 207 +++ internal/cmd/policy/editor.go | 127 ++ internal/cmd/policy/errors.go | 77 + internal/cmd/policy/fixtures_test.go | 105 ++ internal/cmd/policy/get.go | 124 ++ internal/cmd/policy/revision.go | 200 +++ internal/cmd/policy/revision_test.go | 59 + internal/cmd/policy/rule_create.go | 345 ++++ internal/cmd/policy/rule_list.go | 319 ++++ internal/cmd/policy/rule_ops.go | 263 +++ internal/cmd/policy/rule_test.go | 373 ++++ internal/cmd/policy/selector.go | 117 ++ internal/cmd/policy/show.go | 199 +++ internal/cmd/policy/show_test.go | 93 + internal/cmd/policy/view.go | 199 +++ internal/cmd/safedep.go | 2 + internal/cmd/subscription/service.go | 20 +- internal/cmd/verbs.go | 33 +- internal/config/config.go | 16 + internal/config/config_test.go | 8 + internal/duration/duration.go | 99 ++ internal/duration/duration_test.go | 73 + internal/rpcerror/rpcerror.go | 24 + internal/rpcerror/rpcerror_test.go | 32 + internal/tui/editor.go | 30 + internal/tui/editor_test.go | 18 + 70 files changed, 9943 insertions(+), 39 deletions(-) create mode 100644 docs/cmd/policy-change-create.md create mode 100644 docs/cmd/policy-change-delete.md create mode 100644 docs/cmd/policy-change-edit.md create mode 100644 docs/cmd/policy-change-list.md create mode 100644 docs/cmd/policy-change-publish.md create mode 100644 docs/cmd/policy-change-show.md create mode 100644 docs/cmd/policy-change-sync.md create mode 100644 docs/cmd/policy-edit.md create mode 100644 docs/cmd/policy-get.md create mode 100644 docs/cmd/policy-revision-list.md create mode 100644 docs/cmd/policy-revision-show.md create mode 100644 docs/cmd/policy-rule-create.md create mode 100644 docs/cmd/policy-rule-delete.md create mode 100644 docs/cmd/policy-rule-list.md create mode 100644 docs/cmd/policy-rule-show.md create mode 100644 docs/cmd/policy-rule-update.md create mode 100644 docs/cmd/policy-show.md create mode 100644 internal/cloudpolicy/document.go create mode 100644 internal/cloudpolicy/document_test.go create mode 100644 internal/cloudpolicy/fields.go create mode 100644 internal/cloudpolicy/fields_test.go create mode 100644 internal/cloudpolicy/fixtures_test.go create mode 100644 internal/cloudpolicy/labels.go create mode 100644 internal/cloudpolicy/labels_test.go create mode 100644 internal/cloudpolicy/labelwriter.go create mode 100644 internal/cloudpolicy/labelwriter_test.go create mode 100644 internal/cloudpolicy/mocks/LabelServiceClient_mock.go create mode 100644 internal/cloudpolicy/mocks/PolicyServiceClient_mock.go create mode 100644 internal/cloudpolicy/protoyaml.go create mode 100644 internal/cloudpolicy/render.go create mode 100644 internal/cloudpolicy/subject.go create mode 100644 internal/cloudpolicy/subject_test.go create mode 100644 internal/cmd/policy/change_create.go create mode 100644 internal/cmd/policy/change_list.go create mode 100644 internal/cmd/policy/change_ops.go create mode 100644 internal/cmd/policy/change_show.go create mode 100644 internal/cmd/policy/change_test.go create mode 100644 internal/cmd/policy/cmd.go create mode 100644 internal/cmd/policy/edit.go create mode 100644 internal/cmd/policy/edit_test.go create mode 100644 internal/cmd/policy/editor.go create mode 100644 internal/cmd/policy/errors.go create mode 100644 internal/cmd/policy/fixtures_test.go create mode 100644 internal/cmd/policy/get.go create mode 100644 internal/cmd/policy/revision.go create mode 100644 internal/cmd/policy/revision_test.go create mode 100644 internal/cmd/policy/rule_create.go create mode 100644 internal/cmd/policy/rule_list.go create mode 100644 internal/cmd/policy/rule_ops.go create mode 100644 internal/cmd/policy/rule_test.go create mode 100644 internal/cmd/policy/selector.go create mode 100644 internal/cmd/policy/show.go create mode 100644 internal/cmd/policy/show_test.go create mode 100644 internal/cmd/policy/view.go create mode 100644 internal/duration/duration.go create mode 100644 internal/duration/duration_test.go create mode 100644 internal/rpcerror/rpcerror.go create mode 100644 internal/rpcerror/rpcerror_test.go create mode 100644 internal/tui/editor.go create mode 100644 internal/tui/editor_test.go diff --git a/.mockery.yml b/.mockery.yml index 5993b29..5d0b56c 100644 --- a/.mockery.yml +++ b/.mockery.yml @@ -10,3 +10,14 @@ packages: filename: "{{.InterfaceName}}_mock.go" interfaces: CredentialStore: + buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc: + config: + # The gRPC clients are generated code, which mockery skips by default. + include-auto-generated: true + dir: "internal/cloudpolicy/mocks" + pkgname: "mocks" + structname: "{{.InterfaceName}}Mock" + filename: "{{.InterfaceName}}_mock.go" + interfaces: + PolicyServiceClient: + LabelServiceClient: diff --git a/README.md b/README.md index 77b9b70..edeef74 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,11 @@ Log in to SafeDep Cloud, manage credential profiles, and switch between tenants. Monitor the health of every endpoint reporting to your tenant, list active machines, and drill into package inventory and recent activity. +**Policy management**: `safedep policy` +Edit the one policy of your tenant: the policy base, policy overrides that select +endpoints and projects by label, and package rules that trust or block packages. +Review each policy change before you publish it, and roll back from any policy revision. + **Security telemetry queries**: `safedep query` Run SQL against SafeDep Cloud's query service. Inspect packages, events, and findings across your entire fleet. @@ -118,6 +123,23 @@ Push SafeDep malware findings to external security tools. JFrog XRay is supporte | [`safedep endpoint show`](./docs/cmd/endpoint-show.md) | Show endpoint detail | | [`safedep endpoint activity list`](./docs/cmd/endpoint-activity-list.md) | List recent endpoint activity | | [`safedep endpoint inventory list`](./docs/cmd/endpoint-inventory-list.md) | List current endpoint inventory | +| [`safedep policy show`](./docs/cmd/policy-show.md) | Show a summary of the tenant policy | +| [`safedep policy get`](./docs/cmd/policy-get.md) | Write the policy settings document as YAML | +| [`safedep policy edit`](./docs/cmd/policy-edit.md) | Edit the policy settings document in your editor | +| [`safedep policy change list`](./docs/cmd/policy-change-list.md) | List policy changes | +| [`safedep policy change show`](./docs/cmd/policy-change-show.md) | Show what a policy change does | +| [`safedep policy change edit`](./docs/cmd/policy-change-edit.md) | Edit the policy settings of an open policy change | +| [`safedep policy change sync`](./docs/cmd/policy-change-sync.md) | Move the base of a policy change to the head revision | +| [`safedep policy change publish`](./docs/cmd/policy-change-publish.md) | Publish a policy change as a new policy revision | +| [`safedep policy change delete`](./docs/cmd/policy-change-delete.md) | Delete an open policy change | +| [`safedep policy change create`](./docs/cmd/policy-change-create.md) | Create a policy change that restores an old revision | +| [`safedep policy revision list`](./docs/cmd/policy-revision-list.md) | List policy revisions | +| [`safedep policy revision show`](./docs/cmd/policy-revision-show.md) | Show one policy revision with its policy settings | +| [`safedep policy rule create`](./docs/cmd/policy-rule-create.md) | Create a trust entry or block entries | +| [`safedep policy rule list`](./docs/cmd/policy-rule-list.md) | List package rules | +| [`safedep policy rule show`](./docs/cmd/policy-rule-show.md) | Show one package rule | +| [`safedep policy rule update`](./docs/cmd/policy-rule-update.md) | Change the reason, expiry, ticket or requester of a package rule | +| [`safedep policy rule delete`](./docs/cmd/policy-rule-delete.md) | Delete a package rule | | [`safedep query exec`](./docs/cmd/query-exec.md) | Execute a SQL query against SafeDep Cloud | | [`safedep query schema list`](./docs/cmd/query-schema-list.md) | List tables in the query schema | | [`safedep query schema show`](./docs/cmd/query-schema-show.md) | Show one table from the query schema | diff --git a/docs/cmd/policy-change-create.md b/docs/cmd/policy-change-create.md new file mode 100644 index 0000000..3d2d235 --- /dev/null +++ b/docs/cmd/policy-change-create.md @@ -0,0 +1,48 @@ +# safedep policy change create + +Create a policy change that restores capabilities from an old policy revision, +for a rollback. + +## Synopsis + +``` +safedep policy change create --from-revision N [--capability NAME]... + [--package-rules head|revision] [-m TITLE] +``` + +## Flags + +| Flag | Description | +|------|-------------| +| `--from-revision ` | The revision to restore from. Required. | +| `--capability ` | A capability to restore, as in `scan_gate` or `package_admission`. Repeatable. Every capability when absent. | +| `--package-rules ` | `head` (default) keeps the package rules at head. `revision` restores the set of `--from-revision`. | +| `-m`, `--message ` | The title of the change. | + +For each restored capability, the policy base and every policy override take +their values from that revision. The change is a draft. Revision numbers only go +up, so its publish makes a new revision. + +## Examples + +```bash +safedep policy change create --from-revision 46 --capability scan_gate -m "revert fail_on to high" +``` + +``` +✓ change 20 restores scan_gate from revision 46 · package rules stay at head +! It loosens scan_gate.fail_on (medium -> high) in override "payments" + Review it: safedep policy change show 20 + Publish it: safedep policy change publish 20 +``` + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The change was created. | +| non-zero | Validation or the request failed. | diff --git a/docs/cmd/policy-change-delete.md b/docs/cmd/policy-change-delete.md new file mode 100644 index 0000000..299ed12 --- /dev/null +++ b/docs/cmd/policy-change-delete.md @@ -0,0 +1,30 @@ +# safedep policy change delete + +Delete an open policy change. The policy does not change. + +## Synopsis + +``` +safedep policy change delete CHANGE +``` + +## Examples + +```bash +safedep policy change delete 19 +``` + +``` +✓ change 19 deleted +``` + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The change was deleted. | +| non-zero | The request failed. | diff --git a/docs/cmd/policy-change-edit.md b/docs/cmd/policy-change-edit.md new file mode 100644 index 0000000..9ab0b8b --- /dev/null +++ b/docs/cmd/policy-change-edit.md @@ -0,0 +1,47 @@ +# safedep policy change edit + +Open the policy settings of an open policy change in your editor. Saving updates +the change on the server. + +## Synopsis + +``` +safedep policy change edit CHANGE [-m TITLE] [--override NAME] +``` + +## Flags + +| Flag | Description | +|------|-------------| +| `-m`, `--message <title>` | A new title for the change. | +| `--override <name>` | Edit only the policy override with this name. | + +A change that does not edit the settings yet starts from the head settings. For a +change that restores a revision, saving replaces the settings that the restore +made, and the command warns first. The editor behaves as in +[`safedep policy edit`](./policy-edit.md). + +## Examples + +```bash +safedep policy change edit 18 +``` + +``` +✓ change 18 updated + Review it: safedep policy change show 18 +``` + +When another admin updated the change after the command read it, the update +stops. Run `safedep policy change show 18` and edit again. + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The change was updated, or nothing changed. | +| non-zero | The edit or the request failed. | diff --git a/docs/cmd/policy-change-list.md b/docs/cmd/policy-change-list.md new file mode 100644 index 0000000..806e030 --- /dev/null +++ b/docs/cmd/policy-change-list.md @@ -0,0 +1,50 @@ +# safedep policy change list + +List the policy changes of the tenant, newest first. + +## Synopsis + +``` +safedep policy change list [--state open|published|deleted] + [--limit N] [--page-token TOKEN] + [--output table|plain|json] +``` + +## Flags + +| Flag | Description | +|------|-------------| +| `--state <state>` | Filter: `open`, `published` or `deleted`. | +| `--limit <n>` | Page size. The server default applies when 0. | +| `--page-token <token>` | Continuation token from a prior response. | + +Inherits root flags `--output` and `--profile`. + +## Examples + +```bash +safedep policy change list --state open +``` + +``` +Policy changes +CHANGE TITLE STATE BASE REV EDITS AUTHOR UPDATED +18 payments: medium + cooldown open 46 settings alice 2m ago +``` + +## Output + +`json` holds `changes` (id, title, state, base and published revision, author, +what the change edits, times) and `next_page_token`. `plain` writes a +tab-separated header and one row for each change. + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The page was read, also when it is empty. | +| non-zero | Validation, authentication or the request failed. | diff --git a/docs/cmd/policy-change-publish.md b/docs/cmd/policy-change-publish.md new file mode 100644 index 0000000..75ab3ec --- /dev/null +++ b/docs/cmd/policy-change-publish.md @@ -0,0 +1,48 @@ +# safedep policy change publish + +Publish an open policy change as a new policy revision for the whole tenant. + +## Synopsis + +``` +safedep policy change publish CHANGE [-m MESSAGE] +``` + +## Flags + +| Flag | Description | +|------|-------------| +| `-m`, `--message <text>` | The publish message. | + +## Examples + +```bash +safedep policy change publish 18 -m "payments: fail on medium, 7d cooldown (CUST-412)" +``` + +``` +✓ revision 47 published + Projects resolve it at their next check. Endpoints apply it after their next policy fetch + Endpoints that have not applied it yet: safedep endpoint list --applied-revision '<47' +``` + +When a part that the change edits moved since its base revision, the publish stops: + +``` +✗ The policy moved: a part that change 19 edits changed after its base revision + Sync it and review it again: safedep policy change sync 19 +``` + +In the MVP every publish needs the Admin role. A change that loosens the policy +sends a notice to every Admin and Owner of the tenant. + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The revision was published. | +| non-zero | The change is not open, it is stale, or the request failed. | diff --git a/docs/cmd/policy-change-show.md b/docs/cmd/policy-change-show.md new file mode 100644 index 0000000..7b8ccd1 --- /dev/null +++ b/docs/cmd/policy-change-show.md @@ -0,0 +1,62 @@ +# safedep policy change show + +Show a policy change. For an open change, the server previews it against head: +the changed fields and their change direction, the changes to policy overrides, +the package rule operations, the subjects that it reaches, how well they enforce +it, and warnings. + +## Synopsis + +``` +safedep policy change show CHANGE [--output table|plain|json] +``` + +## Examples + +```bash +safedep policy change show 18 +``` + +``` +Change 18 "payments: medium + cooldown" · open · base rev 46 · head rev 46 · no conflict + +Author alice +Updated 2m ago + +What changes +WHERE WHAT OLD -> NEW DIRECTION +override "payments" scan_gate.fail_on high -> medium TIGHTENS +override "payments" package_admission.cooldown.min_age - -> 7d TIGHTENS +override "payments" selector scm-property/criticality=high -> custom/criticality=high LOOSENS + +Impact · subjects matched: 3 projects, 0 endpoints +FIELD ENFORCED PARTIAL DETECT ONLY NOT SUPPORTED +scan_gate.fail_on = medium 2 1 0 0 + +Warnings +CODE SUBJECT MESSAGE +LOW_ENFORCED_COVERAGE scan_gate.fail_on 1 of 3 projects cannot enforce "medium" yet + +Direction LOOSENS. Only an Admin can publish it, and Admins and Owners get a notice +``` + +A stale change shows `STALE: sync it before you publish` in the first line. A +published or deleted change shows no preview. + +## Output + +`json` holds `change` and `preview` (head revision, stale, direction, changes, +matched counts, coverage, warnings). `plain` writes `key<TAB>value` lines and one +`change<TAB>where<TAB>what<TAB>old<TAB>new<TAB>direction` line for each change. +Values in `plain` and `json` are exact, as `168h`. The table humanizes them, as `7d`. + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The change was read. | +| non-zero | Authentication or the request failed. | diff --git a/docs/cmd/policy-change-sync.md b/docs/cmd/policy-change-sync.md new file mode 100644 index 0000000..230f87f --- /dev/null +++ b/docs/cmd/policy-change-sync.md @@ -0,0 +1,34 @@ +# safedep policy change sync + +Move the base of an open policy change to the head revision. The change keeps its +settings as you wrote them. The server never merges, so review the change again +before you publish it. + +## Synopsis + +``` +safedep policy change sync CHANGE +``` + +## Examples + +```bash +safedep policy change sync 19 +``` + +``` +✓ change 19 rebased on revision 51 · review it: safedep policy change show 19 +``` + +Sync a change when its publish stops because the policy moved. + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The change was synced. | +| non-zero | The change is not open, or the request failed. | diff --git a/docs/cmd/policy-edit.md b/docs/cmd/policy-edit.md new file mode 100644 index 0000000..8bcff7e --- /dev/null +++ b/docs/cmd/policy-edit.md @@ -0,0 +1,75 @@ +# safedep policy edit + +Open the policy settings document of the tenant in your editor. Saving creates a +policy change on the server. Nothing applies until you publish the change. + +## Synopsis + +``` +safedep policy edit [-m TITLE] [--override NAME] +``` + +## Flags + +| Flag | Description | +|------|-------------| +| `-m`, `--message <title>` | The title of the policy change. When empty, the publish message becomes the title. | +| `--override <name>` | Edit only the policy override with this name. | + +The editor is `$VISUAL`, then `$EDITOR`, then `vi` (`notepad` on Windows). The +command needs a terminal. + +## Examples + +```bash +safedep policy edit -m "payments: medium + cooldown" +``` + +The file starts with a header that shows the layers: + +```yaml +# Policy of platform-eng.acme.safedep.io · head revision 46 +# Saving creates a draft change. Nothing applies until you publish it. +# +# Layers, from low to high, for each subject: +# 1. SafeDep default policy (read-only, revision 12): +# scan_gate.fail_on: high +# 2. base - applies to every endpoint and project of this tenant +# 3. overrides - apply to the subjects that their selector matches. +# For each field, the highest priority that sets it wins. +# +# Package rules are not in this file: 211 rules (safedep policy rule list) +# The policy keeps no comments. Write the reason for a value in a description field. +``` + +``` +✓ change 18 saved from revision 46 + Review it: safedep policy change show 18 +``` + +Edit one policy override: + +```bash +safedep policy edit --override payments +``` + +## Behavior + +- When you close the editor with no change, the command saves nothing. +- When the file does not parse, or the server rejects it as invalid, the editor + opens again with the error at the top. Close it with no change to stop. +- The command warns when the file holds a comment other than its header. The + policy keeps no comments. +- When the save fails for another reason, the command keeps the file and prints + its path. + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The change was saved, or nothing changed. | +| non-zero | The edit or the request failed. | diff --git a/docs/cmd/policy-get.md b/docs/cmd/policy-get.md new file mode 100644 index 0000000..e5120c1 --- /dev/null +++ b/docs/cmd/policy-get.md @@ -0,0 +1,74 @@ +# safedep policy get + +Write the policy settings document of the tenant as YAML: the policy base and +every policy override. Package rules are not in the document. + +## Synopsis + +``` +safedep policy get [--revision N] [--output table|plain|json] +``` + +## Flags + +| Flag | Description | +|------|-------------| +| `--revision <n>` | The policy revision to write. The head revision when 0 or omitted. | + +Inherits root flags `--output` and `--profile`. + +## Examples + +Write the head settings to a file: + +```bash +safedep policy get > policy.yaml +``` + +```yaml +# Policy settings of platform-eng.acme.safedep.io · revision 46 +# Package rules are not in this file: safedep policy rule list + +base: + scan_gate: + fail_on: high +overrides: + - name: payments + description: Stricter gate for payment services (CUST-412) + priority: 200 + selector: + matchLabels: {custom/criticality: high} + spec: + scan_gate: + fail_on: medium +``` + +Read an old revision: + +```bash +safedep policy get --revision 40 +``` + +## Output + +`table` and `plain` write the YAML document. `json` writes +`{"revision": N, "policy": {...}}` with the same document. + +The document form: + +- Field names are the contract names, as in `scan_gate.fail_on`. +- An enum value is a short token, as in `medium` for `SEVERITY_MEDIUM`. +- A duration is a Go duration, as in `168h`. An edit also accepts days, as in `7d`. +- A selector has the Kubernetes form: `matchLabels` and `matchExpressions`. +- The server owns the id of a policy override, so the document leaves it out. + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The document was written. | +| non-zero | Authentication or the request failed. | diff --git a/docs/cmd/policy-revision-list.md b/docs/cmd/policy-revision-list.md new file mode 100644 index 0000000..01e323c --- /dev/null +++ b/docs/cmd/policy-revision-list.md @@ -0,0 +1,49 @@ +# safedep policy revision list + +List the policy revisions of the tenant, newest first. + +## Synopsis + +``` +safedep policy revision list [--limit N] [--page-token TOKEN] [--output table|plain|json] +``` + +## Flags + +| Flag | Description | +|------|-------------| +| `--limit <n>` | Page size. The server default applies when 0. | +| `--page-token <token>` | Continuation token from a prior response. | + +## Examples + +```bash +safedep policy revision list --limit 5 +``` + +``` +Policy revisions +REV PUBLISHED BY SOURCE DIRECTION MESSAGE +51 10m ago alice CLI LOOSENS delete r_80b +50 12m ago alice CLI LOOSENS extend r_77e +49 1d ago alice CLI LOOSENS trust pkg:pypi/foo@1.0.3 +48 1d ago carol CLI TIGHTENS block pkg:npm/evil (IR-2291) +47 2d ago alice CLI TIGHTENS payments: fail on medium, 7d cooldown (CUST-412) +``` + +## Output + +`json` holds `revisions` (revision, change id, author, message, source, change +direction, publish time) and `next_page_token`. `plain` writes a tab-separated +header and one row for each revision. + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The page was read. | +| non-zero | Authentication or the request failed. | diff --git a/docs/cmd/policy-revision-show.md b/docs/cmd/policy-revision-show.md new file mode 100644 index 0000000..07efd58 --- /dev/null +++ b/docs/cmd/policy-revision-show.md @@ -0,0 +1,45 @@ +# safedep policy revision show + +Show one policy revision: who published it, when, from which change, its change +direction, and the policy settings document at that revision. + +## Synopsis + +``` +safedep policy revision show REVISION [--output table|plain|json] +``` + +## Examples + +```bash +safedep policy revision show 47 +``` + +``` +Revision 47 · published 2d ago by alice · "payments: fail on medium, 7d cooldown (CUST-412)" +Source CLI +Direction TIGHTENS +Change 18 · safedep policy change show 18 + +Policy settings +base: + scan_gate: + fail_on: high +... +``` + +## Output + +`json` holds `revision` and `policy`, the document in the form of +[`safedep policy get`](./policy-get.md). + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The revision was read. | +| non-zero | Authentication or the request failed. | diff --git a/docs/cmd/policy-rule-create.md b/docs/cmd/policy-rule-create.md new file mode 100644 index 0000000..f759e0c --- /dev/null +++ b/docs/cmd/policy-rule-create.md @@ -0,0 +1,95 @@ +# safedep policy rule create + +Create a package rule and publish it at once as a new policy revision. A block +entry stops new installs of the packages that it selects. A trust entry waives +the verdicts of its trust scopes for one package, but never a verdict of +verified malware. + +## Synopsis + +``` +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] +``` + +## Flags + +| Flag | Description | +|------|-------------| +| `--block` | Create block entries. | +| `--trust` | Create a trust entry. | +| `-f`, `--file <path>` | 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 <range>` | 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 <scope>` | With `--trust`: `malware`, `cooldown`, `vulnerability` or `all`. Repeatable. Required. | +| `--expires <when>` | A duration from now, as `30d`, or a date, as `2027-01-26`. Required with `--trust`. | +| `--reason <text>` | Why the rule exists. Required. Tools show it in a block message. | +| `--ticket <ref>` | A ticket or incident reference, as `IR-2291`. | +| `--requested-by <who>` | The team or person that asked for the rule. | +| `--override <name>` | Attach the rule to this policy override. The policy base when empty. | +| `-m`, `--message <text>` | The publish message. The server writes one when it is empty. | + +Selector rules, which the CLI checks before the request: + +- A selector is a PURL, as `pkg:npm/evil` or `pkg:pypi/foo@1.0.3`. +- Only a block entry can use a prefix. A prefix ends with `/*` or `.*`, as + `pkg:npm/@acme/*`, `pkg:maven/org.apache.*` or `pkg:nuget/Microsoft.*`. A prefix + has no version, qualifiers or subpath. Use `--vers` for a range. +- A trust entry selects one package. +- Set a version in the PURL or a `--vers` range, not both. + +`--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. + +## Examples + +Block a malicious package at 2am: + +```bash +safedep policy rule create --block pkg:npm/evil --vers '>=1.2.0' \ + --reason "IR-2291 credential stealer" --ticket IR-2291 +``` + +``` +Applies to every endpoint and project of the tenant (base). Use --override NAME to narrow it. +A block stops new installs. It does not remove installed copies. +✓ rule r_9c1 created · revision 48 published + Each endpoint applies it after its next policy fetch. Pull request checks apply it at once. + Endpoints that have not applied it yet: safedep endpoint list --applied-revision '<48' +``` + +Trust a false positive: + +```bash +safedep policy rule create --trust pkg:pypi/foo@1.0.3 --scope malware \ + --reason "False positive, S-88" --expires 30d --requested-by data-eng +``` + +``` +Applies to every endpoint and project of the tenant (base). Use --override NAME to narrow it. +! This rule loosens the policy: it waives a malware verdict that is not verified for pkg:pypi/foo@1.0.3. +! Verified malware stays blocked +✓ rule r_a41 created · revision 49 published + The rule expires in 30d (2026-11-30) +``` + +Block a list of packages in one revision: + +```bash +safedep policy rule create --block -f iocs.txt --reason "IR-2300 campaign" +``` + +## Permissions + +In the MVP every rule change needs the Admin role. + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The rules were created and the revision was published. | +| non-zero | Validation, authentication or the request failed. Nothing was published. | diff --git a/docs/cmd/policy-rule-delete.md b/docs/cmd/policy-rule-delete.md new file mode 100644 index 0000000..5402e44 --- /dev/null +++ b/docs/cmd/policy-rule-delete.md @@ -0,0 +1,40 @@ +# safedep policy rule delete + +Delete a package rule and publish the change at once as a new policy revision. +The rule stays in the history of the revisions. + +## Synopsis + +``` +safedep policy rule delete RULE --reason TEXT [-m MESSAGE] +``` + +## Flags + +| Flag | Description | +|------|-------------| +| `--reason <text>` | Why the rule goes. Required. | +| `-m`, `--message <text>` | The publish message. | + +## Examples + +```bash +safedep policy rule delete r_80b --reason "no longer needed" +``` + +``` +✓ rule r_80b deleted · revision 51 published +``` + +The delete of a block entry loosens the policy. + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The rule was deleted and the revision was published. | +| non-zero | Validation or the request failed. | diff --git a/docs/cmd/policy-rule-list.md b/docs/cmd/policy-rule-list.md new file mode 100644 index 0000000..aaa1486 --- /dev/null +++ b/docs/cmd/policy-rule-list.md @@ -0,0 +1,59 @@ +# safedep policy rule list + +List the active package rules at head, or at an older policy revision. + +## Synopsis + +``` +safedep policy rule list [--effect trust|block] [--scope SCOPE] [--selector-prefix TEXT] + [--expiring DURATION] [--override NAME | --base] [--at-revision N] + [--limit N] [--page-token TOKEN] [--output table|plain|json] +``` + +## Flags + +| Flag | Description | +|------|-------------| +| `--effect <effect>` | `trust` or `block`. | +| `--scope <scope>` | Trust entries with this scope: `malware`, `cooldown` or `vulnerability`. | +| `--selector-prefix <text>` | Rules whose selector starts with this text, as `pkg:npm/`. | +| `--expiring <duration>` | Rules that expire within this time from now, as `7d`. | +| `--override <name>` | Rules that attach to this policy override. | +| `--base` | Rules that attach to the policy base. | +| `--at-revision <n>` | The rules that were active at this revision. | +| `--limit <n>` | Page size. The server default applies when 0. | +| `--page-token <token>` | Continuation token from a prior response. | + +## Examples + +Trust entries that expire this week: + +```bash +safedep policy rule list --effect trust --expiring 7d +``` + +``` +Package rules +RULE SELECTOR EFFECT SCOPE REASON REQUESTED BY ATTACHES TO EXPIRES +r_77e pkg:npm/@acme/x trust malware,cooldown internal scope platform-team base in 6d +r_80b pkg:npm/leftpad trust malware FP, S-71 web base in 2d +2 rules +``` + +## Output + +`json` holds `rules` (rule id, purl, vers, effect, scopes, reason, ticket, +requester, override id, `attaches_to`, author, added 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. + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The page was read. | +| non-zero | Validation, authentication or the request failed. | diff --git a/docs/cmd/policy-rule-show.md b/docs/cmd/policy-rule-show.md new file mode 100644 index 0000000..bbee260 --- /dev/null +++ b/docs/cmd/policy-rule-show.md @@ -0,0 +1,40 @@ +# safedep policy rule show + +Show one package rule. A block message of a tool cites the rule id. + +## Synopsis + +``` +safedep policy rule show RULE [--output table|plain|json] +``` + +## Examples + +```bash +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 +``` + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The rule was read. | +| non-zero | The rule does not exist, or the request failed. | diff --git a/docs/cmd/policy-rule-update.md b/docs/cmd/policy-rule-update.md new file mode 100644 index 0000000..8a7fdbc --- /dev/null +++ b/docs/cmd/policy-rule-update.md @@ -0,0 +1,45 @@ +# safedep policy rule update + +Change the reason, expiry, ticket or requester of a package rule, and publish the +change at once as a new policy revision. A rule never changes its selector, +effect or trust scopes: delete it and create another. + +## Synopsis + +``` +safedep policy rule update RULE [--reason TEXT] [--expires WHEN] [--ticket REF] + [--requested-by WHO] [-m MESSAGE] +``` + +## Flags + +| Flag | Description | +|------|-------------| +| `--reason <text>` | The new reason. | +| `--expires <when>` | The new expiry: a duration from now, as `90d`, or a date. | +| `--ticket <ref>` | The new ticket. An empty value clears it. | +| `--requested-by <who>` | The new requester. An empty value clears it. | +| `-m`, `--message <text>` | The publish message. | + +Give at least one of the fields. A later expiry of a trust entry loosens the policy. + +## Examples + +```bash +safedep policy rule update r_77e --expires 90d --reason "internal scope, renewed for Q1" +``` + +``` +✓ rule r_77e now expires on 2027-01-29 · revision 50 published +``` + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The rule was updated and the revision was published. | +| non-zero | Validation or the request failed. | diff --git a/docs/cmd/policy-show.md b/docs/cmd/policy-show.md new file mode 100644 index 0000000..4420b53 --- /dev/null +++ b/docs/cmd/policy-show.md @@ -0,0 +1,66 @@ +# safedep policy show + +Show a summary of the policy of the tenant: the head policy revision, the open +policy changes, the package rules, the SafeDep default policy and the policy +overrides in priority order. + +## Synopsis + +``` +safedep policy show [--output table|plain|json] +``` + +## Flags + +The command has no flags of its own. It inherits the root flags `--output` and +`--profile`. + +## Examples + +```bash +safedep policy show +``` + +``` +Policy platform-eng.acme.safedep.io +Head revision 46 · published 2d ago by alice · "cooldown 5d for laptops" +Open changes none +Package rules 211 (184 trust, 27 block) · 23 expire in 7d +Default policy revision 12 · scan_gate.fail_on: high + +Overrides (priority, highest first) +PRIORITY NAME SELECTOR EXPIRES DESCRIPTION +300 ci managed/deployment-kind=ci - - +200 payments custom/criticality=high - - +``` + +Read the policy settings document as JSON: + +```bash +safedep policy show -o json | jq '.policy' +``` + +## Output + +`json` holds `head_revision`, `head` (the revision record), `default_policy_revision`, +`default_policy` (path to value), `open_change_count`, `package_rule_counts`, +`overrides` (id, name, priority, selector, description, expiry) and `policy`, the +policy settings document in the same form as `safedep policy get`. + +`plain` writes one `key<TAB>value` line for each count, and one +`override<TAB>priority<TAB>name<TAB>selector<TAB>expires_at` line for each policy +override. + +The fleet rows of the design (delivery to endpoints, project counts, notices) +need the fleet view of a later milestone. The command does not show them yet. + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The policy was read. | +| non-zero | Authentication or the request failed. | diff --git a/go.mod b/go.mod index afc7c01..a431329 100644 --- a/go.mod +++ b/go.mod @@ -3,8 +3,8 @@ module github.com/safedep/cli go 1.26.2 require ( - buf.build/gen/go/safedep/api/grpc/go v1.6.2-20260924172335-b3803903c9fd.1 - buf.build/gen/go/safedep/api/protocolbuffers/go v1.36.12-20260924172335-b3803903c9fd.1 + buf.build/gen/go/safedep/api/grpc/go v1.6.2-20261031065119-dc85a10c2beb.1 + buf.build/gen/go/safedep/api/protocolbuffers/go v1.36.12-20261031065119-dc85a10c2beb.2 github.com/charmbracelet/huh v1.0.0 github.com/charmbracelet/lipgloss v1.1.0 github.com/cli/browser v1.3.0 @@ -16,6 +16,7 @@ require ( github.com/spf13/cobra v1.10.2 github.com/spf13/viper v1.21.0 github.com/stretchr/testify v1.11.1 + go.yaml.in/yaml/v3 v3.0.5 golang.org/x/oauth2 v0.36.0 golang.org/x/sync v0.22.0 golang.org/x/term v0.45.0 @@ -97,7 +98,6 @@ require ( go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.28.0 // indirect go.yaml.in/yaml/v2 v2.4.4 // indirect - go.yaml.in/yaml/v3 v3.0.5 // indirect golang.org/x/exp v0.0.0-20260212183809-81e46e3db34a // indirect golang.org/x/mod v0.37.0 // indirect golang.org/x/net v0.57.0 // indirect diff --git a/go.sum b/go.sum index 9dd978d..44bdf97 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-20260924172335-b3803903c9fd.1 h1:Fy4Xk2aWMpm8WLwKsQwjA87VPrMGTJGRIohrb6GhvW8= -buf.build/gen/go/safedep/api/grpc/go v1.6.2-20260924172335-b3803903c9fd.1/go.mod h1:it2WpgzfWPUpLsTRkdljp/MhkCXl2JEx7WpJSpnMhqM= -buf.build/gen/go/safedep/api/protocolbuffers/go v1.36.12-20260924172335-b3803903c9fd.1 h1:z40KvEn/45RsdH56f4V++o/3b7rYX1SgTRvdymgsWxk= -buf.build/gen/go/safedep/api/protocolbuffers/go v1.36.12-20260924172335-b3803903c9fd.1/go.mod h1:NugBwafT1reaWNql+nCCbiObpwyfyo+631WnRlO7Hqo= +buf.build/gen/go/safedep/api/grpc/go v1.6.2-20261031065119-dc85a10c2beb.1 h1:GFuHP+IKmox25L8V2EF4CR3rblReLuKjZCnuOuR7dc4= +buf.build/gen/go/safedep/api/grpc/go v1.6.2-20261031065119-dc85a10c2beb.1/go.mod h1:wVMcwuJdlWZbHcwPPepDJQR1zQDjh/ANlc7Zv0BDfiI= +buf.build/gen/go/safedep/api/protocolbuffers/go v1.36.12-20261031065119-dc85a10c2beb.2 h1:1p9CC/GyQ5POTKPtFvl+48Fk+37rQl/zbAOd1PDDabE= +buf.build/gen/go/safedep/api/protocolbuffers/go v1.36.12-20261031065119-dc85a10c2beb.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/app/app.go b/internal/app/app.go index d59a998..3f12b82 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -42,6 +42,7 @@ type App struct { dataPlane *cloud.Client controlPlane *cloud.Client + tenant string github *adapters.GithubClient storage storage.Storage @@ -240,10 +241,27 @@ func (a *App) ControlPlane() (*cloud.Client, error) { return nil, fmt.Errorf("app: control plane client: %w", err) } + // The tenant domain only labels output, so a credential without one + // does not stop the command. + if tenant, terr := creds.GetTenantDomain(); terr == nil { + a.tenant = tenant + } else { + log.Debugf("app: control plane tenant domain: %v", terr) + } + a.controlPlane = client return a.controlPlane, nil } +// Tenant returns the tenant domain of the control plane credentials, as in +// "platform-eng.acme.safedep.io". It is empty until ControlPlane succeeds, or +// when the credentials carry no tenant domain. +func (a *App) Tenant() string { + a.mu.Lock() + defer a.mu.Unlock() + return a.tenant +} + // ControlPlaneToken returns a valid OAuth access token for the active profile, // refreshing it silently if the stored token is expired. It returns the access // token only, never the refresh token. Intended for handing to an external tool diff --git a/internal/cloudpolicy/document.go b/internal/cloudpolicy/document.go new file mode 100644 index 0000000..5af0941 --- /dev/null +++ b/internal/cloudpolicy/document.go @@ -0,0 +1,174 @@ +// Package cloudpolicy holds the client side of SafeDep Cloud policy +// management that more than one command tree uses: the YAML form of the +// policy settings document, the display of contract values, labels and label +// selectors, and the policy of one subject. The policy, project and endpoint +// command packages read it, because sibling command packages must not import +// each other. +package cloudpolicy + +import ( + "bytes" + "errors" + "fmt" + "strings" + + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + yaml "go.yaml.in/yaml/v3" + "google.golang.org/protobuf/reflect/protoreflect" +) + +// documentCodec writes the policy settings document. It leaves out the +// package rules, because admins change them through rule operations, and the +// override ids, which the server owns. RestoreOverrideIDs puts the ids back +// by name before a save. +var documentCodec = &yamlCodec{skip: map[protoreflect.FullName]string{ + "safedep.policy.spec.v1.PolicySpec.core": "package rules are not in this file. " + + "Change them with: safedep policy rule", + "safedep.services.controltower.policy.v1.Override.override_id": "", +}} + +// ErrEmptyDocument is the error for a saved file with no content. +var ErrEmptyDocument = errors.New("the file is empty") + +// CommentBlock turns lines into YAML comment lines and ends the block with a +// blank line. An empty line becomes a bare "#". +func CommentBlock(lines []string) string { + var b strings.Builder + for _, line := range lines { + if line == "" { + b.WriteString("#\n") + continue + } + b.WriteString("# ") + b.WriteString(line) + b.WriteByte('\n') + } + if b.Len() > 0 { + b.WriteByte('\n') + } + return b.String() +} + +// MarshalPolicy writes the policy settings document as YAML, after the +// header. +func MarshalPolicy(p *policyv1.Policy, header string) ([]byte, error) { + if p == nil { + p = &policyv1.Policy{} + } + return marshalNode(documentCodec.encodeMessage(p.ProtoReflect()), header) +} + +// UnmarshalPolicy reads a policy settings document. +func UnmarshalPolicy(data []byte) (*policyv1.Policy, error) { + node, err := parseDocument(data) + if err != nil { + return nil, err + } + p := &policyv1.Policy{} + if err := documentCodec.decodeMessage(node, p.ProtoReflect(), ""); err != nil { + return nil, err + } + return p, nil +} + +// MarshalOverride writes one policy override as YAML, after the header. +func MarshalOverride(o *policyv1.Override, header string) ([]byte, error) { + return marshalNode(documentCodec.encodeMessage(o.ProtoReflect()), header) +} + +// UnmarshalOverride reads one policy override. +func UnmarshalOverride(data []byte) (*policyv1.Override, error) { + node, err := parseDocument(data) + if err != nil { + return nil, err + } + o := &policyv1.Override{} + if err := documentCodec.decodeMessage(node, o.ProtoReflect(), "override"); err != nil { + return nil, err + } + return o, nil +} + +// PolicyMap returns the policy settings document as plain maps and lists, in +// the same form as the YAML, for JSON output. +func PolicyMap(p *policyv1.Policy) (any, error) { + if p == nil { + p = &policyv1.Policy{} + } + var out any + if err := documentCodec.encodeMessage(p.ProtoReflect()).Decode(&out); err != nil { + return nil, fmt.Errorf("policy document: %w", err) + } + return out, nil +} + +// RestoreOverrideIDs gives each edited policy override with no id the id of +// the head policy override with the same name. The document leaves the ids +// out, so the server can tell an edit of a policy override from a new one. +func RestoreOverrideIDs(edited, head *policyv1.Policy) { + ids := make(map[string]string, len(head.GetOverrides())) + for _, o := range head.GetOverrides() { + ids[o.GetName()] = o.GetOverrideId() + } + for _, o := range edited.GetOverrides() { + if o.GetOverrideId() != "" { + continue + } + if id, ok := ids[o.GetName()]; ok { + o.SetOverrideId(id) + } + } +} + +// HasUserComments reports whether the saved file holds a comment other than +// the header that the CLI wrote. The policy keeps no comments, so a person +// loses them on save. +func HasUserComments(data []byte, header string) bool { + body := bytes.TrimPrefix(data, []byte(header)) + var root yaml.Node + if err := yaml.Unmarshal(body, &root); err != nil { + return false + } + return hasComment(&root) +} + +func hasComment(n *yaml.Node) bool { + if n.HeadComment != "" || n.LineComment != "" || n.FootComment != "" { + return true + } + for _, child := range n.Content { + if hasComment(child) { + return true + } + } + return false +} + +func marshalNode(node *yaml.Node, header string) ([]byte, error) { + var buf bytes.Buffer + buf.WriteString(header) + enc := yaml.NewEncoder(&buf) + enc.SetIndent(2) + if err := enc.Encode(node); err != nil { + return nil, fmt.Errorf("policy document: %w", err) + } + if err := enc.Close(); err != nil { + return nil, fmt.Errorf("policy document: %w", err) + } + return buf.Bytes(), nil +} + +func parseDocument(data []byte) (*yaml.Node, error) { + var root yaml.Node + if err := yaml.Unmarshal(data, &root); err != nil { + return nil, fmt.Errorf("the file is not valid YAML: %w", err) + } + if root.Kind == 0 || len(root.Content) == 0 { + return nil, ErrEmptyDocument + } + node := root.Content[0] + if isNull(node) { + return nil, ErrEmptyDocument + } + return node, nil +} diff --git a/internal/cloudpolicy/document_test.go b/internal/cloudpolicy/document_test.go new file mode 100644 index 0000000..db9e386 --- /dev/null +++ b/internal/cloudpolicy/document_test.go @@ -0,0 +1,217 @@ +package cloudpolicy + +import ( + "strings" + "testing" + "time" + + messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" + scangatev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/scangate/v1" + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/timestamppb" +) + +func TestMarshalPolicy_WritesTheWalkthroughForm(t *testing.T) { + header := CommentBlock([]string{"Policy of acme", "", "Saving creates a draft change."}) + b, err := MarshalPolicy(samplePolicy(), header) + require.NoError(t, err) + + want := header + `base: + package_admission: + cooldown: + min_age: 48h + scan_gate: + fail_on: high +overrides: + - name: ci + priority: 300 + selector: + matchLabels: {managed/deployment-kind: ci} + spec: + package_admission: + cooldown: + min_age: 168h + - name: payments + description: Stricter gate for payment services (CUST-412) + priority: 200 + selector: + matchLabels: {custom/criticality: high} + spec: + package_admission: + cooldown: + min_age: 168h + scan_gate: + fail_on: medium +` + assert.Equal(t, want, string(b)) + assert.NotContains(t, string(b), "override_id", "the server owns override ids") +} + +func TestUnmarshalPolicy_RoundTrips(t *testing.T) { + original := samplePolicy() + b, err := MarshalPolicy(original, "") + require.NoError(t, err) + + got, err := UnmarshalPolicy(b) + require.NoError(t, err) + RestoreOverrideIDs(got, original) + assert.True(t, proto.Equal(original, got), "got %v", got) +} + +func TestUnmarshalPolicy_AcceptsDaysAndFullEnumNames(t *testing.T) { + got, err := UnmarshalPolicy([]byte(` +base: + scan_gate: + fail_on: SEVERITY_CRITICAL + fail_on_attacks: report + package_admission: + cooldown: { min_age: 7d } +`)) + require.NoError(t, err) + assert.Equal(t, scangatev1.Severity_SEVERITY_CRITICAL, got.GetBase().GetScanGate().GetFailOn()) + assert.Equal(t, scangatev1.AttackGate_ATTACK_GATE_REPORT, got.GetBase().GetScanGate().GetFailOnAttacks()) + assert.Equal(t, 7*24*time.Hour, got.GetBase().GetPackageAdmission().GetCooldown().GetMinAge().AsDuration()) +} + +func TestUnmarshalPolicy_Errors(t *testing.T) { + tests := []struct { + name string + doc string + want string + }{ + { + name: "unknown field names the known ones", + doc: "base:\n scan_gates: {}\n", + want: "line 2: base.scan_gates: unknown field. Known fields: package_admission, scan_gate", + }, + { + name: "unknown enum value lists the values", + doc: "base:\n scan_gate:\n fail_on: mediun\n", + want: `line 3: base.scan_gate.fail_on: unknown value "mediun". Use one of: critical, high, medium, low, info`, + }, + { + name: "package rules are not in the document", + doc: "base:\n core: {}\n", + want: "base.core: package rules are not in this file", + }, + { + name: "bad duration", + doc: "base:\n package_admission:\n cooldown:\n min_age: soon\n", + want: "line 4: base.package_admission.cooldown.min_age: invalid duration", + }, + { + name: "bad priority", + doc: "overrides:\n - name: x\n priority: high\n", + want: "line 3: overrides[0].priority: expected a positive whole number", + }, + { + name: "bad selector operator", + doc: "overrides:\n - name: x\n selector:\n matchExpressions:\n - {key: custom/a, operator: Maybe}\n", + want: `unknown operator "Maybe"`, + }, + { + name: "duplicate field", + doc: "base_description: a\nbase_description: b\n", + want: "line 2: base_description: the field is set twice", + }, + { + name: "empty file", + doc: "# only a comment\n", + want: "the file is empty", + }, + { + name: "not YAML", + doc: "base: [\n", + want: "the file is not valid YAML", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := UnmarshalPolicy([]byte(tt.doc)) + require.Error(t, err) + assert.Contains(t, err.Error(), tt.want) + }) + } +} + +func TestSelectorExpressions_RoundTrip(t *testing.T) { + sel, err := ParseSelector("scm/forge=github, custom/tier in (a,b), !custom/legacy, custom/owner") + require.NoError(t, err) + o := &policyv1.Override{} + o.SetName("mixed") + o.SetPriority(10) + o.SetSelector(sel) + o.SetExpiresAt(timestamppb.New(time.Date(2027, 1, 26, 0, 0, 0, 0, time.UTC))) + + b, err := MarshalOverride(o, "") + require.NoError(t, err) + assert.Contains(t, string(b), "operator: In") + assert.Contains(t, string(b), "expires_at: 2027-01-26T00:00:00Z") + + got, err := UnmarshalOverride(b) + require.NoError(t, err) + assert.True(t, proto.Equal(o, got), "got %v", got) +} + +func TestEmptySelectorKeepsItsPresence(t *testing.T) { + o := &policyv1.Override{} + o.SetName("all") + o.SetPriority(1) + o.SetSelector(&messagescontroltowerv1.LabelSelector{}) + b, err := MarshalOverride(o, "") + require.NoError(t, err) + assert.Contains(t, string(b), "selector: {}") + + got, err := UnmarshalOverride(b) + require.NoError(t, err) + assert.True(t, got.HasSelector(), "selector: {} selects every subject and must stay set") +} + +func TestRestoreOverrideIDs(t *testing.T) { + head := samplePolicy() + edited := samplePolicy() + for _, o := range edited.GetOverrides() { + o.SetOverrideId("") + } + added := &policyv1.Override{} + added.SetName("new") + edited.SetOverrides(append(edited.GetOverrides(), added)) + + RestoreOverrideIDs(edited, head) + assert.Equal(t, "ov_2", edited.GetOverrides()[0].GetOverrideId()) + assert.Equal(t, "ov_1", edited.GetOverrides()[1].GetOverrideId()) + assert.Empty(t, edited.GetOverrides()[2].GetOverrideId(), "a new override gets its id from the server") +} + +func TestHasUserComments(t *testing.T) { + header := CommentBlock([]string{"Policy of acme"}) + body := "base:\n scan_gate:\n fail_on: high\n" + tests := []struct { + name string + text string + want bool + }{ + {"header only", header + body, false}, + {"line comment", header + strings.Replace(body, "high", "high # CUST-412", 1), true}, + {"comment between keys", header + "# why\n" + body, true}, + {"changed header", "# my own header\n" + body, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, HasUserComments([]byte(tt.text), header)) + }) + } +} + +func TestPolicyMap(t *testing.T) { + doc, err := PolicyMap(samplePolicy()) + require.NoError(t, err) + m, ok := doc.(map[string]any) + require.True(t, ok) + base, ok := m["base"].(map[string]any) + require.True(t, ok) + assert.Equal(t, map[string]any{"fail_on": "high"}, base["scan_gate"]) +} diff --git a/internal/cloudpolicy/fields.go b/internal/cloudpolicy/fields.go new file mode 100644 index 0000000..e4231ed --- /dev/null +++ b/internal/cloudpolicy/fields.go @@ -0,0 +1,254 @@ +package cloudpolicy + +import ( + "encoding/json" + "fmt" + "slices" + "strings" + "time" + + specv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/spec/v1" + "github.com/safedep/dry/tui/humanize" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/types/known/durationpb" + "google.golang.org/protobuf/types/known/timestamppb" + + "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" + +// FieldValue is one set field of a PolicySpec. +type FieldValue struct { + // Path is the contract path, as in "scan_gate.fail_on". + Path string + // Value is the exact value, in the form of the policy document, as + // "168h" or "medium". + Value string + // Human is the value for a table, as "7d". + Human string +} + +// Fields lists the set fields of a PolicySpec, other than package rules, in +// descriptor order. +func Fields(spec *specv1.PolicySpec) []FieldValue { + if spec == nil { + return nil + } + var out []FieldValue + collectFields(spec.ProtoReflect(), "", &out) + return out +} + +func collectFields(m protoreflect.Message, path string, out *[]FieldValue) { + fields := m.Descriptor().Fields() + for i := 0; i < fields.Len(); i++ { + fd := fields.Get(i) + if path == "" && string(fd.Name()) == coreCapability { + continue + } + if !m.Has(fd) { + continue + } + fieldPath := joinPath(path, string(fd.Name())) + if isLeaf(fd) { + value, human := formatFieldValue(fd, m.Get(fd)) + *out = append(*out, FieldValue{Path: fieldPath, Value: value, Human: human}) + continue + } + collectFields(m.Get(fd).Message(), fieldPath, out) + } +} + +// LeafPaths lists every settings path of the contract that the SDK knows, in +// descriptor order, as in "scan_gate.fail_on". +func LeafPaths() []string { + var out []string + collectPaths((&specv1.PolicySpec{}).ProtoReflect().Descriptor(), "", &out) + return out +} + +func collectPaths(md protoreflect.MessageDescriptor, path string, out *[]string) { + fields := md.Fields() + for i := 0; i < fields.Len(); i++ { + fd := fields.Get(i) + if path == "" && string(fd.Name()) == coreCapability { + continue + } + fieldPath := joinPath(path, string(fd.Name())) + if isLeaf(fd) { + *out = append(*out, fieldPath) + continue + } + collectPaths(fd.Message(), fieldPath, out) + } +} + +// Capabilities lists the settings capabilities of the contract: the fields of +// PolicySpec other than the package rules, as in "scan_gate". +func Capabilities() []string { + md := (&specv1.PolicySpec{}).ProtoReflect().Descriptor() + out := make([]string, 0, md.Fields().Len()) + for i := 0; i < md.Fields().Len(); i++ { + name := string(md.Fields().Get(i).Name()) + if name != coreCapability { + out = append(out, name) + } + } + return out +} + +// ValidateFieldPaths checks that each path is a settings path or a +// capability of the contract, so a typo fails before the RPC. +func ValidateFieldPaths(paths []string) error { + known := LeafPaths() + for _, p := range paths { + if slices.Contains(known, p) || MatchesFieldFilter(known, []string{p}) { + continue + } + return fmt.Errorf("unknown policy field %q: known fields are %s", p, strings.Join(known, ", ")) + } + return nil +} + +// MatchesFieldFilter reports whether any path in paths is selected by the +// filter. A filter entry selects its own path and every path below it. An +// empty filter selects every path. +func MatchesFieldFilter(paths, filter []string) bool { + if len(filter) == 0 { + return true + } + for _, p := range paths { + for _, f := range filter { + if p == f || strings.HasPrefix(p, f+".") { + return true + } + } + } + return false +} + +func isLeaf(fd protoreflect.FieldDescriptor) bool { + if fd.Kind() != protoreflect.MessageKind || fd.IsList() || fd.IsMap() { + return true + } + switch fd.Message().FullName() { + case durationFullName, timestampFullName: + return true + } + return false +} + +func formatFieldValue(fd protoreflect.FieldDescriptor, v protoreflect.Value) (string, string) { + switch { + case fd.IsList(): + list := v.List() + values := make([]string, 0, list.Len()) + humans := make([]string, 0, list.Len()) + for i := 0; i < list.Len(); i++ { + value, human := formatSingular(fd, list.Get(i)) + values = append(values, value) + humans = append(humans, human) + } + return strings.Join(values, ", "), strings.Join(humans, ", ") + case fd.IsMap(): + var pairs []string + v.Map().Range(func(k protoreflect.MapKey, mv protoreflect.Value) bool { + value, _ := formatSingular(fd.MapValue(), mv) + pairs = append(pairs, k.String()+"="+value) + return true + }) + slices.Sort(pairs) + joined := strings.Join(pairs, ", ") + return joined, joined + default: + return formatSingular(fd, v) + } +} + +func formatSingular(fd protoreflect.FieldDescriptor, v protoreflect.Value) (string, string) { + switch fd.Kind() { + case protoreflect.EnumKind: + token := enumValueToken(fd.Enum(), v.Enum()) + return token, token + case protoreflect.MessageKind, protoreflect.GroupKind: + switch msg := v.Message().Interface().(type) { + case *durationpb.Duration: + d := msg.AsDuration() + return duration.Format(d), humanDuration(d) + case *timestamppb.Timestamp: + t := msg.AsTime().UTC() + return t.Format(time.RFC3339), humanize.Time(t, time.Now()) + default: + text := fmt.Sprint(v.Message().Interface()) + return text, text + } + default: + text := v.String() + return text, text + } +} + +// humanDuration keeps a zero duration readable as "0s". A zero cooldown +// turns the cooldown off. +func humanDuration(d time.Duration) string { + if d <= 0 { + return duration.Format(d) + } + return humanize.Duration(d) +} + +// FormatJSONValue turns a value of a contract path in protojson form, as a +// preview returns it, into the document form and the table form. An empty +// raw value means that the layer did not set the field, and shows as "-". +func FormatJSONValue(path, raw string) (string, string) { + if raw == "" { + return "-", "-" + } + var value any + if err := json.Unmarshal([]byte(raw), &value); err != nil { + return raw, raw + } + + fd := fieldByPath(path) + text, isString := value.(string) + switch { + case fd != nil && isString && fd.Kind() == protoreflect.EnumKind: + if ev := fd.Enum().Values().ByName(protoreflect.Name(text)); ev != nil { + token := enumValueToken(fd.Enum(), ev.Number()) + return token, token + } + return text, text + case fd != nil && isString && fd.Kind() == protoreflect.MessageKind && fd.Message().FullName() == durationFullName: + if d, err := time.ParseDuration(text); err == nil { + return duration.Format(d), humanDuration(d) + } + return text, text + case isString: + return text, text + default: + compact, err := json.Marshal(value) + if err != nil { + return raw, raw + } + return string(compact), string(compact) + } +} + +func fieldByPath(path string) protoreflect.FieldDescriptor { + md := (&specv1.PolicySpec{}).ProtoReflect().Descriptor() + var fd protoreflect.FieldDescriptor + for _, segment := range strings.Split(path, ".") { + if md == nil { + return nil + } + fd = md.Fields().ByName(protoreflect.Name(segment)) + if fd == nil { + return nil + } + md = fd.Message() + } + return fd +} diff --git a/internal/cloudpolicy/fields_test.go b/internal/cloudpolicy/fields_test.go new file mode 100644 index 0000000..557e49e --- /dev/null +++ b/internal/cloudpolicy/fields_test.go @@ -0,0 +1,63 @@ +package cloudpolicy + +import ( + "testing" + "time" + + scangatev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/scangate/v1" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestFields(t *testing.T) { + got := Fields(specWith(scangatev1.Severity_SEVERITY_MEDIUM, 168*time.Hour)) + assert.Equal(t, []FieldValue{ + {Path: "package_admission.cooldown.min_age", Value: "168h", Human: "7d"}, + {Path: "scan_gate.fail_on", Value: "medium", Human: "medium"}, + }, got) + assert.Empty(t, Fields(nil)) +} + +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") + for _, p := range paths { + assert.NotContains(t, p, "core", "package rules are not settings") + } + assert.Equal(t, []string{"package_admission", "scan_gate"}, Capabilities()) +} + +func TestValidateFieldPaths(t *testing.T) { + require.NoError(t, ValidateFieldPaths(nil)) + require.NoError(t, ValidateFieldPaths([]string{"scan_gate.fail_on", "package_admission"})) + err := ValidateFieldPaths([]string{"scan_gate.fail"}) + require.Error(t, err) + assert.Contains(t, err.Error(), `unknown policy field "scan_gate.fail"`) +} + +func TestMatchesFieldFilter(t *testing.T) { + assert.True(t, MatchesFieldFilter([]string{"scan_gate.fail_on"}, nil)) + assert.True(t, MatchesFieldFilter([]string{"scan_gate.fail_on"}, []string{"scan_gate"})) + assert.False(t, MatchesFieldFilter([]string{"scan_gate.fail_on_attacks"}, []string{"scan_gate.fail_on"})) +} + +func TestFormatJSONValue(t *testing.T) { + tests := []struct { + path, raw, value, human string + }{ + {"scan_gate.fail_on", `"SEVERITY_MEDIUM"`, "medium", "medium"}, + {"package_admission.cooldown.min_age", `"604800s"`, "168h", "7d"}, + {"package_admission.cooldown.min_age", `"0s"`, "0s", "0s"}, + {"scan_gate.fail_on", "", "-", "-"}, + {"unknown.path", `"text"`, "text", "text"}, + {"unknown.path", `{"a":1}`, `{"a":1}`, `{"a":1}`}, + {"unknown.path", `not json`, "not json", "not json"}, + } + for _, tt := range tests { + value, human := FormatJSONValue(tt.path, tt.raw) + assert.Equal(t, tt.value, value, tt.raw) + assert.Equal(t, tt.human, human, tt.raw) + } +} diff --git a/internal/cloudpolicy/fixtures_test.go b/internal/cloudpolicy/fixtures_test.go new file mode 100644 index 0000000..7981a24 --- /dev/null +++ b/internal/cloudpolicy/fixtures_test.go @@ -0,0 +1,56 @@ +package cloudpolicy + +import ( + "time" + + 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" + "google.golang.org/protobuf/types/known/durationpb" +) + +func specWith(failOn scangatev1.Severity, cooldown time.Duration) *specv1.PolicySpec { + spec := &specv1.PolicySpec{} + if failOn != scangatev1.Severity_SEVERITY_UNSPECIFIED { + gate := &scangatev1.ScanGate{} + gate.SetFailOn(failOn) + spec.SetScanGate(gate) + } + if cooldown > 0 { + c := &packageadmissionv1.Cooldown{} + c.SetMinAge(durationpb.New(cooldown)) + pa := &packageadmissionv1.PackageAdmission{} + pa.SetCooldown(c) + spec.SetPackageAdmission(pa) + } + return spec +} + +func samplePolicy() *policyv1.Policy { + p := &policyv1.Policy{} + p.SetBase(specWith(scangatev1.Severity_SEVERITY_HIGH, 48*time.Hour)) + + sel := &messagescontroltowerv1.LabelSelector{} + sel.SetMatchLabels(map[string]string{"custom/criticality": "high"}) + o := &policyv1.Override{} + o.SetOverrideId("ov_1") + o.SetName("payments") + o.SetPriority(200) + o.SetDescription("Stricter gate for payment services (CUST-412)") + o.SetSelector(sel) + o.SetSpec(specWith(scangatev1.Severity_SEVERITY_MEDIUM, 168*time.Hour)) + + ci := &messagescontroltowerv1.LabelSelector{} + ci.SetMatchLabels(map[string]string{"managed/deployment-kind": "ci"}) + o2 := &policyv1.Override{} + o2.SetOverrideId("ov_2") + o2.SetName("ci") + o2.SetPriority(300) + o2.SetSelector(ci) + o2.SetSpec(specWith(scangatev1.Severity_SEVERITY_UNSPECIFIED, 168*time.Hour)) + + p.SetOverrides([]*policyv1.Override{o2, o}) + return p +} diff --git a/internal/cloudpolicy/labels.go b/internal/cloudpolicy/labels.go new file mode 100644 index 0000000..1a6b110 --- /dev/null +++ b/internal/cloudpolicy/labels.go @@ -0,0 +1,278 @@ +package cloudpolicy + +import ( + "fmt" + "regexp" + "sort" + "strings" + + messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" +) + +const ( + // CustomPrefix is the one label prefix that an admin writes. Each other + // prefix has its own write path, and LabelService rejects it. + CustomPrefix = "custom/" + + maxCustomValueLength = 63 + maxLabelsPerRequest = 32 + maxSelectorTerms = 32 +) + +// labelKeyPattern is the label key rule of the contract. +var labelKeyPattern = regexp.MustCompile(`^[a-z0-9.-]+/[A-Za-z0-9_.$#-]{1,75}$`) + +// ParseCustomLabels reads "custom/key=value" pairs. It rejects any other +// prefix before the RPC, with the reason. +func ParseCustomLabels(values []string) ([]*messagescontroltowerv1.Label, error) { + if len(values) == 0 { + return nil, fmt.Errorf("give at least one label, as in --label custom/team=release") + } + if len(values) > maxLabelsPerRequest { + return nil, fmt.Errorf("give at most %d labels in one command", maxLabelsPerRequest) + } + seen := make(map[string]struct{}, len(values)) + labels := make([]*messagescontroltowerv1.Label, 0, len(values)) + for _, raw := range values { + key, value, ok := strings.Cut(raw, "=") + if !ok { + return nil, fmt.Errorf("label %q has no value: write it as custom/key=value", raw) + } + key = strings.TrimSpace(key) + if err := ValidateCustomKey(key); err != nil { + return nil, err + } + if len(value) > maxCustomValueLength { + return nil, fmt.Errorf("the value of label %s has %d characters: the limit is %d", + key, len(value), maxCustomValueLength) + } + if _, dup := seen[key]; dup { + return nil, fmt.Errorf("label %s is given twice", key) + } + seen[key] = struct{}{} + label := &messagescontroltowerv1.Label{} + label.SetKey(key) + label.SetValue(value) + labels = append(labels, label) + } + return labels, nil +} + +// ValidateCustomKeys checks label keys for a delete. +func ValidateCustomKeys(keys []string) error { + if len(keys) == 0 { + return fmt.Errorf("give at least one label key, as in --key custom/team") + } + if len(keys) > maxLabelsPerRequest { + return fmt.Errorf("give at most %d label keys in one command", maxLabelsPerRequest) + } + for _, key := range keys { + if err := ValidateCustomKey(key); err != nil { + return err + } + } + return nil +} + +// ValidateCustomKey checks that an admin can write the label key. +func ValidateCustomKey(key string) error { + if !strings.HasPrefix(key, CustomPrefix) { + prefix, _, _ := strings.Cut(key, "/") + return fmt.Errorf("label key %q: an admin writes only %q labels. The source of %q labels sets them", + key, CustomPrefix, prefix+"/") + } + if !labelKeyPattern.MatchString(key) { + return fmt.Errorf("label key %q is not valid: use custom/ and a name of 1 to 75 letters, digits or _.$#-", key) + } + return nil +} + +// FormatLabels writes labels as sorted "key=value" items. +func FormatLabels(labels []*messagescontroltowerv1.Label) []string { + out := make([]string, 0, len(labels)) + for _, l := range labels { + out = append(out, l.GetKey()+"="+l.GetValue()) + } + sort.Strings(out) + return out +} + +// ParseSelector reads a label selector in the Kubernetes text form. The terms +// are separated by commas, and they AND together: +// +// key=value, key==value the key has the value +// key!=value the key does not have the value +// key in (a,b) the key has one of the values +// key notin (a,b) the key has none of the values +// key the key exists +// !key the key does not exist +func ParseSelector(text string) (*messagescontroltowerv1.LabelSelector, error) { + terms, err := splitSelectorTerms(text) + if err != nil { + return nil, err + } + if len(terms) == 0 { + return nil, fmt.Errorf("the selector is empty: write it as key=value, as in custom/team=release") + } + if len(terms) > maxSelectorTerms { + return nil, fmt.Errorf("the selector has %d terms: the limit is %d", len(terms), maxSelectorTerms) + } + + selector := &messagescontroltowerv1.LabelSelector{} + matchLabels := map[string]string{} + var exprs []*messagescontroltowerv1.LabelSelectorRequirement + for _, term := range terms { + expr, key, value, err := parseSelectorTerm(term) + if err != nil { + return nil, err + } + if expr != nil { + exprs = append(exprs, expr) + continue + } + if existing, dup := matchLabels[key]; dup && existing != value { + return nil, fmt.Errorf("selector term %q conflicts with %s=%s", term, key, existing) + } + matchLabels[key] = value + } + if len(matchLabels) > 0 { + selector.SetMatchLabels(matchLabels) + } + if len(exprs) > 0 { + selector.SetMatchExpressions(exprs) + } + return selector, nil +} + +func splitSelectorTerms(text string) ([]string, error) { + var terms []string + depth := 0 + start := 0 + for i, r := range text { + switch r { + case '(': + depth++ + case ')': + depth-- + if depth < 0 { + return nil, fmt.Errorf("selector %q has a ')' with no '('", text) + } + case ',': + if depth == 0 { + terms = appendTerm(terms, text[start:i]) + start = i + 1 + } + } + } + if depth != 0 { + return nil, fmt.Errorf("selector %q has a '(' with no ')'", text) + } + return appendTerm(terms, text[start:]), nil +} + +func appendTerm(terms []string, term string) []string { + if t := strings.TrimSpace(term); t != "" { + return append(terms, t) + } + return terms +} + +var setTermPattern = regexp.MustCompile(`^(\S+)\s+(in|notin)\s*\((.*)\)$`) + +func parseSelectorTerm(term string) (*messagescontroltowerv1.LabelSelectorRequirement, string, string, error) { + if m := setTermPattern.FindStringSubmatch(term); m != nil { + op := messagescontroltowerv1.LabelSelectorOperator_LABEL_SELECTOR_OPERATOR_IN + if m[2] == "notin" { + op = messagescontroltowerv1.LabelSelectorOperator_LABEL_SELECTOR_OPERATOR_NOT_IN + } + var values []string + for _, v := range strings.Split(m[3], ",") { + if v = strings.TrimSpace(v); v != "" { + values = append(values, v) + } + } + if len(values) == 0 { + return nil, "", "", fmt.Errorf("selector term %q needs at least one value", term) + } + expr, err := newRequirement(m[1], op, values) + return expr, "", "", err + } + + if key, value, ok := strings.Cut(term, "!="); ok { + expr, err := newRequirement(strings.TrimSpace(key), + messagescontroltowerv1.LabelSelectorOperator_LABEL_SELECTOR_OPERATOR_NOT_IN, + []string{strings.TrimSpace(value)}) + return expr, "", "", err + } + if key, value, ok := strings.Cut(term, "="); ok { + key = strings.TrimSpace(key) + value = strings.TrimPrefix(value, "=") + if err := validateSelectorKey(key); err != nil { + return nil, "", "", err + } + return nil, key, strings.TrimSpace(value), nil + } + if key, ok := strings.CutPrefix(term, "!"); ok { + expr, err := newRequirement(strings.TrimSpace(key), + messagescontroltowerv1.LabelSelectorOperator_LABEL_SELECTOR_OPERATOR_DOES_NOT_EXIST, nil) + return expr, "", "", err + } + expr, err := newRequirement(term, messagescontroltowerv1.LabelSelectorOperator_LABEL_SELECTOR_OPERATOR_EXISTS, nil) + return expr, "", "", err +} + +func newRequirement( + key string, + op messagescontroltowerv1.LabelSelectorOperator, + values []string, +) (*messagescontroltowerv1.LabelSelectorRequirement, error) { + if err := validateSelectorKey(key); err != nil { + return nil, err + } + expr := &messagescontroltowerv1.LabelSelectorRequirement{} + expr.SetKey(key) + expr.SetOperator(op) + if len(values) > 0 { + expr.SetValues(values) + } + return expr, nil +} + +func validateSelectorKey(key string) error { + if !labelKeyPattern.MatchString(key) { + return fmt.Errorf("selector label key %q is not valid: write it as prefix/name, as in custom/team or scm/forge", key) + } + return nil +} + +// FormatSelector writes a label selector in the text form that ParseSelector +// reads. An empty selector matches every subject. +func FormatSelector(selector *messagescontroltowerv1.LabelSelector) string { + if selector == nil { + return "(every subject)" + } + var terms []string + for key, value := range selector.GetMatchLabels() { + terms = append(terms, key+"="+value) + } + sort.Strings(terms) + for _, expr := range selector.GetMatchExpressions() { + values := strings.Join(expr.GetValues(), ",") + switch expr.GetOperator() { + case messagescontroltowerv1.LabelSelectorOperator_LABEL_SELECTOR_OPERATOR_IN: + terms = append(terms, fmt.Sprintf("%s in (%s)", expr.GetKey(), values)) + case messagescontroltowerv1.LabelSelectorOperator_LABEL_SELECTOR_OPERATOR_NOT_IN: + terms = append(terms, fmt.Sprintf("%s notin (%s)", expr.GetKey(), values)) + case messagescontroltowerv1.LabelSelectorOperator_LABEL_SELECTOR_OPERATOR_EXISTS: + terms = append(terms, expr.GetKey()) + case messagescontroltowerv1.LabelSelectorOperator_LABEL_SELECTOR_OPERATOR_DOES_NOT_EXIST: + terms = append(terms, "!"+expr.GetKey()) + default: + terms = append(terms, fmt.Sprintf("%s %s (%s)", expr.GetKey(), expr.GetOperator(), values)) + } + } + if len(terms) == 0 { + return "(every subject)" + } + return strings.Join(terms, ", ") +} diff --git a/internal/cloudpolicy/labels_test.go b/internal/cloudpolicy/labels_test.go new file mode 100644 index 0000000..dacf86b --- /dev/null +++ b/internal/cloudpolicy/labels_test.go @@ -0,0 +1,86 @@ +package cloudpolicy + +import ( + "strings" + "testing" + + messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestParseCustomLabels(t *testing.T) { + tests := []struct { + name string + in []string + want []string + wantErr string + }{ + {name: "one label", in: []string{"custom/criticality=high"}, want: []string{"custom/criticality=high"}}, + {name: "empty value", in: []string{"custom/flag="}, want: []string{"custom/flag="}}, + {name: "value keeps an equals sign", in: []string{"custom/expr=a=b"}, want: []string{"custom/expr=a=b"}}, + {name: "no labels", in: nil, wantErr: "at least one label"}, + {name: "no value", in: []string{"custom/team"}, wantErr: "has no value"}, + {name: "other prefix", in: []string{"scm/forge=github"}, wantErr: `an admin writes only "custom/" labels`}, + {name: "managed prefix", in: []string{"managed/department=x"}, wantErr: `"managed/" labels`}, + {name: "bad name", in: []string{"custom/a b=x"}, wantErr: "is not valid"}, + {name: "long value", in: []string{"custom/a=" + strings.Repeat("x", 64)}, wantErr: "the limit is 63"}, + {name: "duplicate", in: []string{"custom/a=1", "custom/a=2"}, wantErr: "given twice"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := ParseCustomLabels(tt.in) + if tt.wantErr != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantErr) + return + } + require.NoError(t, err) + assert.Equal(t, tt.want, FormatLabels(got)) + }) + } +} + +func TestValidateCustomKeys(t *testing.T) { + require.NoError(t, ValidateCustomKeys([]string{"custom/team", "custom/criticality"})) + assert.ErrorContains(t, ValidateCustomKeys(nil), "at least one label key") + assert.ErrorContains(t, ValidateCustomKeys([]string{"safedep.io/project-id"}), `"safedep.io/" labels`) +} + +func TestParseSelector(t *testing.T) { + tests := []struct { + in string + want string + wantErr string + }{ + {in: "custom/criticality=high", want: "custom/criticality=high"}, + {in: "custom/a==1, scm/forge=github", want: "custom/a=1, scm/forge=github"}, + {in: "custom/a!=1", want: "custom/a notin (1)"}, + {in: "custom/tier in (gold, silver)", want: "custom/tier in (gold,silver)"}, + {in: "custom/tier notin (bronze)", want: "custom/tier notin (bronze)"}, + {in: "custom/owner", want: "custom/owner"}, + {in: "!custom/legacy", want: "!custom/legacy"}, + {in: "", wantErr: "the selector is empty"}, + {in: "custom/tier in ()", wantErr: "needs at least one value"}, + {in: "custom/tier in (a", wantErr: "has a '(' with no ')'"}, + {in: "team=release", wantErr: "is not valid"}, + {in: "custom/a=1,custom/a=2", wantErr: "conflicts with"}, + } + for _, tt := range tests { + t.Run(tt.in, func(t *testing.T) { + got, err := ParseSelector(tt.in) + if tt.wantErr != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantErr) + return + } + require.NoError(t, err) + assert.Equal(t, tt.want, FormatSelector(got)) + }) + } +} + +func TestFormatSelector_EmptyMatchesEverySubject(t *testing.T) { + assert.Equal(t, "(every subject)", FormatSelector(nil)) + assert.Equal(t, "(every subject)", FormatSelector(&messagescontroltowerv1.LabelSelector{})) +} diff --git a/internal/cloudpolicy/labelwriter.go b/internal/cloudpolicy/labelwriter.go new file mode 100644 index 0000000..6f8aeaf --- /dev/null +++ b/internal/cloudpolicy/labelwriter.go @@ -0,0 +1,91 @@ +package cloudpolicy + +import ( + "context" + "fmt" + + policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" + messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/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" + "google.golang.org/grpc" +) + +// maxLabelSubjects is the limit of subjects in one label request. +const maxLabelSubjects = 100 + +// NewLabelClient returns the LabelService client of a control plane +// connection. +func NewLabelClient(conn grpc.ClientConnInterface) policyv1grpc.LabelServiceClient { + return policyv1grpc.NewLabelServiceClient(conn) +} + +// NewPolicyClient returns the PolicyService client of a control plane +// connection. +func NewPolicyClient(conn grpc.ClientConnInterface) policyv1grpc.PolicyServiceClient { + return policyv1grpc.NewPolicyServiceClient(conn) +} + +// SetLabels sets "custom/" labels on subjects of one kind. +func SetLabels( + ctx context.Context, + client policyv1grpc.LabelServiceClient, + kind specv1.SubjectKind, + ids []string, + labels []*messagescontroltowerv1.Label, +) error { + subjects, err := labelSubjects(kind, ids) + if err != nil { + return err + } + req := &policyv1.SetSubjectLabelsRequest{} + req.SetSubjects(subjects) + req.SetLabels(labels) + if _, err := client.SetSubjectLabels(ctx, req); err != nil { + return fmt.Errorf("set labels: %w", err) + } + return nil +} + +// DeleteLabels removes "custom/" labels from subjects of one kind. +func DeleteLabels( + ctx context.Context, + client policyv1grpc.LabelServiceClient, + kind specv1.SubjectKind, + ids []string, + keys []string, +) error { + if err := ValidateCustomKeys(keys); err != nil { + return err + } + subjects, err := labelSubjects(kind, ids) + if err != nil { + return err + } + req := &policyv1.DeleteSubjectLabelsRequest{} + req.SetSubjects(subjects) + req.SetKeys(keys) + if _, err := client.DeleteSubjectLabels(ctx, req); err != nil { + return fmt.Errorf("delete labels: %w", err) + } + return nil +} + +func labelSubjects(kind specv1.SubjectKind, ids []string) ([]*specv1.Subject, error) { + if len(ids) == 0 { + return nil, fmt.Errorf("give at least one %s", subjectKindName(kind)) + } + if len(ids) > maxLabelSubjects { + return nil, fmt.Errorf("give at most %d subjects in one command", maxLabelSubjects) + } + seen := make(map[string]struct{}, len(ids)) + subjects := make([]*specv1.Subject, 0, len(ids)) + for _, id := range ids { + if _, dup := seen[id]; dup { + continue + } + seen[id] = struct{}{} + subjects = append(subjects, NewSubject(kind, id)) + } + return subjects, nil +} diff --git a/internal/cloudpolicy/labelwriter_test.go b/internal/cloudpolicy/labelwriter_test.go new file mode 100644 index 0000000..222d6d0 --- /dev/null +++ b/internal/cloudpolicy/labelwriter_test.go @@ -0,0 +1,66 @@ +package cloudpolicy + +import ( + "context" + "errors" + "fmt" + "testing" + + 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" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + "github.com/safedep/cli/internal/cloudpolicy/mocks" +) + +func TestSetLabels(t *testing.T) { + client := mocks.NewLabelServiceClientMock(t) + labels, err := ParseCustomLabels([]string{"custom/criticality=high"}) + require.NoError(t, err) + + client.EXPECT().SetSubjectLabels(mock.Anything, mock.MatchedBy(func(req *policyv1.SetSubjectLabelsRequest) bool { + return len(req.GetSubjects()) == 2 && + req.GetSubjects()[0].GetKind() == specv1.SubjectKind_SUBJECT_KIND_PROJECT && + req.GetSubjects()[0].GetId() == "p_1" && + req.GetSubjects()[1].GetId() == "p_2" && + req.GetLabels()[0].GetKey() == "custom/criticality" + })).Return(&policyv1.SetSubjectLabelsResponse{}, nil) + + err = SetLabels(context.Background(), client, specv1.SubjectKind_SUBJECT_KIND_PROJECT, + []string{"p_1", "p_2", "p_1"}, labels) + require.NoError(t, err) +} + +func TestSetLabels_Errors(t *testing.T) { + client := mocks.NewLabelServiceClientMock(t) + labels, err := ParseCustomLabels([]string{"custom/a=1"}) + require.NoError(t, err) + + err = SetLabels(context.Background(), client, specv1.SubjectKind_SUBJECT_KIND_ENDPOINT, nil, labels) + assert.ErrorContains(t, err, "give at least one endpoint") + + many := make([]string, 101) + for i := range many { + many[i] = fmt.Sprintf("e_%d", i) + } + err = SetLabels(context.Background(), client, specv1.SubjectKind_SUBJECT_KIND_ENDPOINT, many, labels) + assert.ErrorContains(t, err, "at most 100 subjects") + + client.EXPECT().SetSubjectLabels(mock.Anything, mock.Anything).Return(nil, errors.New("denied")) + err = SetLabels(context.Background(), client, specv1.SubjectKind_SUBJECT_KIND_ENDPOINT, []string{"e_1"}, labels) + assert.ErrorContains(t, err, "set labels: denied") +} + +func TestDeleteLabels(t *testing.T) { + client := mocks.NewLabelServiceClientMock(t) + err := DeleteLabels(context.Background(), client, specv1.SubjectKind_SUBJECT_KIND_PROJECT, []string{"p_1"}, []string{"scm/forge"}) + assert.ErrorContains(t, err, `"scm/" labels`) + + client.EXPECT().DeleteSubjectLabels(mock.Anything, mock.MatchedBy(func(req *policyv1.DeleteSubjectLabelsRequest) bool { + return req.GetKeys()[0] == "custom/team" && req.GetSubjects()[0].GetId() == "p_1" + })).Return(&policyv1.DeleteSubjectLabelsResponse{}, nil) + require.NoError(t, DeleteLabels(context.Background(), client, specv1.SubjectKind_SUBJECT_KIND_PROJECT, + []string{"p_1"}, []string{"custom/team"})) +} diff --git a/internal/cloudpolicy/mocks/LabelServiceClient_mock.go b/internal/cloudpolicy/mocks/LabelServiceClient_mock.go new file mode 100644 index 0000000..2fb185f --- /dev/null +++ b/internal/cloudpolicy/mocks/LabelServiceClient_mock.go @@ -0,0 +1,289 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mocks + +import ( + "context" + + "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + mock "github.com/stretchr/testify/mock" + "google.golang.org/grpc" +) + +// NewLabelServiceClientMock creates a new instance of LabelServiceClientMock. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewLabelServiceClientMock(t interface { + mock.TestingT + Cleanup(func()) +}) *LabelServiceClientMock { + mock := &LabelServiceClientMock{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// LabelServiceClientMock is an autogenerated mock type for the LabelServiceClient type +type LabelServiceClientMock struct { + mock.Mock +} + +type LabelServiceClientMock_Expecter struct { + mock *mock.Mock +} + +func (_m *LabelServiceClientMock) EXPECT() *LabelServiceClientMock_Expecter { + return &LabelServiceClientMock_Expecter{mock: &_m.Mock} +} + +// DeleteSubjectLabels provides a mock function for the type LabelServiceClientMock +func (_mock *LabelServiceClientMock) DeleteSubjectLabels(ctx context.Context, in *policyv1.DeleteSubjectLabelsRequest, opts ...grpc.CallOption) (*policyv1.DeleteSubjectLabelsResponse, error) { + var tmpRet mock.Arguments + if len(opts) > 0 { + tmpRet = _mock.Called(ctx, in, opts) + } else { + tmpRet = _mock.Called(ctx, in) + } + ret := tmpRet + + if len(ret) == 0 { + panic("no return value specified for DeleteSubjectLabels") + } + + var r0 *policyv1.DeleteSubjectLabelsResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.DeleteSubjectLabelsRequest, ...grpc.CallOption) (*policyv1.DeleteSubjectLabelsResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.DeleteSubjectLabelsRequest, ...grpc.CallOption) *policyv1.DeleteSubjectLabelsResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*policyv1.DeleteSubjectLabelsResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *policyv1.DeleteSubjectLabelsRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// LabelServiceClientMock_DeleteSubjectLabels_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeleteSubjectLabels' +type LabelServiceClientMock_DeleteSubjectLabels_Call struct { + *mock.Call +} + +// DeleteSubjectLabels is a helper method to define mock.On call +// - ctx context.Context +// - in *policyv1.DeleteSubjectLabelsRequest +// - opts ...grpc.CallOption +func (_e *LabelServiceClientMock_Expecter) DeleteSubjectLabels(ctx interface{}, in interface{}, opts ...interface{}) *LabelServiceClientMock_DeleteSubjectLabels_Call { + return &LabelServiceClientMock_DeleteSubjectLabels_Call{Call: _e.mock.On("DeleteSubjectLabels", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *LabelServiceClientMock_DeleteSubjectLabels_Call) Run(run func(ctx context.Context, in *policyv1.DeleteSubjectLabelsRequest, opts ...grpc.CallOption)) *LabelServiceClientMock_DeleteSubjectLabels_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *policyv1.DeleteSubjectLabelsRequest + if args[1] != nil { + arg1 = args[1].(*policyv1.DeleteSubjectLabelsRequest) + } + var arg2 []grpc.CallOption + var variadicArgs []grpc.CallOption + if len(args) > 2 { + variadicArgs = args[2].([]grpc.CallOption) + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *LabelServiceClientMock_DeleteSubjectLabels_Call) Return(deleteSubjectLabelsResponse *policyv1.DeleteSubjectLabelsResponse, err error) *LabelServiceClientMock_DeleteSubjectLabels_Call { + _c.Call.Return(deleteSubjectLabelsResponse, err) + return _c +} + +func (_c *LabelServiceClientMock_DeleteSubjectLabels_Call) RunAndReturn(run func(ctx context.Context, in *policyv1.DeleteSubjectLabelsRequest, opts ...grpc.CallOption) (*policyv1.DeleteSubjectLabelsResponse, error)) *LabelServiceClientMock_DeleteSubjectLabels_Call { + _c.Call.Return(run) + return _c +} + +// ListSubjectLabels provides a mock function for the type LabelServiceClientMock +func (_mock *LabelServiceClientMock) ListSubjectLabels(ctx context.Context, in *policyv1.ListSubjectLabelsRequest, opts ...grpc.CallOption) (*policyv1.ListSubjectLabelsResponse, error) { + var tmpRet mock.Arguments + if len(opts) > 0 { + tmpRet = _mock.Called(ctx, in, opts) + } else { + tmpRet = _mock.Called(ctx, in) + } + ret := tmpRet + + if len(ret) == 0 { + panic("no return value specified for ListSubjectLabels") + } + + var r0 *policyv1.ListSubjectLabelsResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.ListSubjectLabelsRequest, ...grpc.CallOption) (*policyv1.ListSubjectLabelsResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.ListSubjectLabelsRequest, ...grpc.CallOption) *policyv1.ListSubjectLabelsResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*policyv1.ListSubjectLabelsResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *policyv1.ListSubjectLabelsRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// LabelServiceClientMock_ListSubjectLabels_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListSubjectLabels' +type LabelServiceClientMock_ListSubjectLabels_Call struct { + *mock.Call +} + +// ListSubjectLabels is a helper method to define mock.On call +// - ctx context.Context +// - in *policyv1.ListSubjectLabelsRequest +// - opts ...grpc.CallOption +func (_e *LabelServiceClientMock_Expecter) ListSubjectLabels(ctx interface{}, in interface{}, opts ...interface{}) *LabelServiceClientMock_ListSubjectLabels_Call { + return &LabelServiceClientMock_ListSubjectLabels_Call{Call: _e.mock.On("ListSubjectLabels", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *LabelServiceClientMock_ListSubjectLabels_Call) Run(run func(ctx context.Context, in *policyv1.ListSubjectLabelsRequest, opts ...grpc.CallOption)) *LabelServiceClientMock_ListSubjectLabels_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *policyv1.ListSubjectLabelsRequest + if args[1] != nil { + arg1 = args[1].(*policyv1.ListSubjectLabelsRequest) + } + var arg2 []grpc.CallOption + var variadicArgs []grpc.CallOption + if len(args) > 2 { + variadicArgs = args[2].([]grpc.CallOption) + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *LabelServiceClientMock_ListSubjectLabels_Call) Return(listSubjectLabelsResponse *policyv1.ListSubjectLabelsResponse, err error) *LabelServiceClientMock_ListSubjectLabels_Call { + _c.Call.Return(listSubjectLabelsResponse, err) + return _c +} + +func (_c *LabelServiceClientMock_ListSubjectLabels_Call) RunAndReturn(run func(ctx context.Context, in *policyv1.ListSubjectLabelsRequest, opts ...grpc.CallOption) (*policyv1.ListSubjectLabelsResponse, error)) *LabelServiceClientMock_ListSubjectLabels_Call { + _c.Call.Return(run) + return _c +} + +// SetSubjectLabels provides a mock function for the type LabelServiceClientMock +func (_mock *LabelServiceClientMock) SetSubjectLabels(ctx context.Context, in *policyv1.SetSubjectLabelsRequest, opts ...grpc.CallOption) (*policyv1.SetSubjectLabelsResponse, error) { + var tmpRet mock.Arguments + if len(opts) > 0 { + tmpRet = _mock.Called(ctx, in, opts) + } else { + tmpRet = _mock.Called(ctx, in) + } + ret := tmpRet + + if len(ret) == 0 { + panic("no return value specified for SetSubjectLabels") + } + + var r0 *policyv1.SetSubjectLabelsResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.SetSubjectLabelsRequest, ...grpc.CallOption) (*policyv1.SetSubjectLabelsResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.SetSubjectLabelsRequest, ...grpc.CallOption) *policyv1.SetSubjectLabelsResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*policyv1.SetSubjectLabelsResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *policyv1.SetSubjectLabelsRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// LabelServiceClientMock_SetSubjectLabels_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetSubjectLabels' +type LabelServiceClientMock_SetSubjectLabels_Call struct { + *mock.Call +} + +// SetSubjectLabels is a helper method to define mock.On call +// - ctx context.Context +// - in *policyv1.SetSubjectLabelsRequest +// - opts ...grpc.CallOption +func (_e *LabelServiceClientMock_Expecter) SetSubjectLabels(ctx interface{}, in interface{}, opts ...interface{}) *LabelServiceClientMock_SetSubjectLabels_Call { + return &LabelServiceClientMock_SetSubjectLabels_Call{Call: _e.mock.On("SetSubjectLabels", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *LabelServiceClientMock_SetSubjectLabels_Call) Run(run func(ctx context.Context, in *policyv1.SetSubjectLabelsRequest, opts ...grpc.CallOption)) *LabelServiceClientMock_SetSubjectLabels_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *policyv1.SetSubjectLabelsRequest + if args[1] != nil { + arg1 = args[1].(*policyv1.SetSubjectLabelsRequest) + } + var arg2 []grpc.CallOption + var variadicArgs []grpc.CallOption + if len(args) > 2 { + variadicArgs = args[2].([]grpc.CallOption) + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *LabelServiceClientMock_SetSubjectLabels_Call) Return(setSubjectLabelsResponse *policyv1.SetSubjectLabelsResponse, err error) *LabelServiceClientMock_SetSubjectLabels_Call { + _c.Call.Return(setSubjectLabelsResponse, err) + return _c +} + +func (_c *LabelServiceClientMock_SetSubjectLabels_Call) RunAndReturn(run func(ctx context.Context, in *policyv1.SetSubjectLabelsRequest, opts ...grpc.CallOption) (*policyv1.SetSubjectLabelsResponse, error)) *LabelServiceClientMock_SetSubjectLabels_Call { + _c.Call.Return(run) + return _c +} diff --git a/internal/cloudpolicy/mocks/PolicyServiceClient_mock.go b/internal/cloudpolicy/mocks/PolicyServiceClient_mock.go new file mode 100644 index 0000000..4979e96 --- /dev/null +++ b/internal/cloudpolicy/mocks/PolicyServiceClient_mock.go @@ -0,0 +1,1534 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mocks + +import ( + "context" + + "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + mock "github.com/stretchr/testify/mock" + "google.golang.org/grpc" +) + +// NewPolicyServiceClientMock creates a new instance of PolicyServiceClientMock. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewPolicyServiceClientMock(t interface { + mock.TestingT + Cleanup(func()) +}) *PolicyServiceClientMock { + mock := &PolicyServiceClientMock{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// PolicyServiceClientMock is an autogenerated mock type for the PolicyServiceClient type +type PolicyServiceClientMock struct { + mock.Mock +} + +type PolicyServiceClientMock_Expecter struct { + mock *mock.Mock +} + +func (_m *PolicyServiceClientMock) EXPECT() *PolicyServiceClientMock_Expecter { + return &PolicyServiceClientMock_Expecter{mock: &_m.Mock} +} + +// CreatePackageRules provides a mock function for the type PolicyServiceClientMock +func (_mock *PolicyServiceClientMock) CreatePackageRules(ctx context.Context, in *policyv1.CreatePackageRulesRequest, opts ...grpc.CallOption) (*policyv1.CreatePackageRulesResponse, error) { + var tmpRet mock.Arguments + if len(opts) > 0 { + tmpRet = _mock.Called(ctx, in, opts) + } else { + tmpRet = _mock.Called(ctx, in) + } + ret := tmpRet + + if len(ret) == 0 { + panic("no return value specified for CreatePackageRules") + } + + var r0 *policyv1.CreatePackageRulesResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.CreatePackageRulesRequest, ...grpc.CallOption) (*policyv1.CreatePackageRulesResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.CreatePackageRulesRequest, ...grpc.CallOption) *policyv1.CreatePackageRulesResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*policyv1.CreatePackageRulesResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *policyv1.CreatePackageRulesRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// PolicyServiceClientMock_CreatePackageRules_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreatePackageRules' +type PolicyServiceClientMock_CreatePackageRules_Call struct { + *mock.Call +} + +// CreatePackageRules is a helper method to define mock.On call +// - ctx context.Context +// - in *policyv1.CreatePackageRulesRequest +// - opts ...grpc.CallOption +func (_e *PolicyServiceClientMock_Expecter) CreatePackageRules(ctx interface{}, in interface{}, opts ...interface{}) *PolicyServiceClientMock_CreatePackageRules_Call { + return &PolicyServiceClientMock_CreatePackageRules_Call{Call: _e.mock.On("CreatePackageRules", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *PolicyServiceClientMock_CreatePackageRules_Call) Run(run func(ctx context.Context, in *policyv1.CreatePackageRulesRequest, opts ...grpc.CallOption)) *PolicyServiceClientMock_CreatePackageRules_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *policyv1.CreatePackageRulesRequest + if args[1] != nil { + arg1 = args[1].(*policyv1.CreatePackageRulesRequest) + } + var arg2 []grpc.CallOption + var variadicArgs []grpc.CallOption + if len(args) > 2 { + variadicArgs = args[2].([]grpc.CallOption) + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *PolicyServiceClientMock_CreatePackageRules_Call) Return(createPackageRulesResponse *policyv1.CreatePackageRulesResponse, err error) *PolicyServiceClientMock_CreatePackageRules_Call { + _c.Call.Return(createPackageRulesResponse, err) + return _c +} + +func (_c *PolicyServiceClientMock_CreatePackageRules_Call) RunAndReturn(run func(ctx context.Context, in *policyv1.CreatePackageRulesRequest, opts ...grpc.CallOption) (*policyv1.CreatePackageRulesResponse, error)) *PolicyServiceClientMock_CreatePackageRules_Call { + _c.Call.Return(run) + return _c +} + +// CreatePolicyChange provides a mock function for the type PolicyServiceClientMock +func (_mock *PolicyServiceClientMock) CreatePolicyChange(ctx context.Context, in *policyv1.CreatePolicyChangeRequest, opts ...grpc.CallOption) (*policyv1.CreatePolicyChangeResponse, error) { + var tmpRet mock.Arguments + if len(opts) > 0 { + tmpRet = _mock.Called(ctx, in, opts) + } else { + tmpRet = _mock.Called(ctx, in) + } + ret := tmpRet + + if len(ret) == 0 { + panic("no return value specified for CreatePolicyChange") + } + + var r0 *policyv1.CreatePolicyChangeResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.CreatePolicyChangeRequest, ...grpc.CallOption) (*policyv1.CreatePolicyChangeResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.CreatePolicyChangeRequest, ...grpc.CallOption) *policyv1.CreatePolicyChangeResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*policyv1.CreatePolicyChangeResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *policyv1.CreatePolicyChangeRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// PolicyServiceClientMock_CreatePolicyChange_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreatePolicyChange' +type PolicyServiceClientMock_CreatePolicyChange_Call struct { + *mock.Call +} + +// CreatePolicyChange is a helper method to define mock.On call +// - ctx context.Context +// - in *policyv1.CreatePolicyChangeRequest +// - opts ...grpc.CallOption +func (_e *PolicyServiceClientMock_Expecter) CreatePolicyChange(ctx interface{}, in interface{}, opts ...interface{}) *PolicyServiceClientMock_CreatePolicyChange_Call { + return &PolicyServiceClientMock_CreatePolicyChange_Call{Call: _e.mock.On("CreatePolicyChange", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *PolicyServiceClientMock_CreatePolicyChange_Call) Run(run func(ctx context.Context, in *policyv1.CreatePolicyChangeRequest, opts ...grpc.CallOption)) *PolicyServiceClientMock_CreatePolicyChange_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *policyv1.CreatePolicyChangeRequest + if args[1] != nil { + arg1 = args[1].(*policyv1.CreatePolicyChangeRequest) + } + var arg2 []grpc.CallOption + var variadicArgs []grpc.CallOption + if len(args) > 2 { + variadicArgs = args[2].([]grpc.CallOption) + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *PolicyServiceClientMock_CreatePolicyChange_Call) Return(createPolicyChangeResponse *policyv1.CreatePolicyChangeResponse, err error) *PolicyServiceClientMock_CreatePolicyChange_Call { + _c.Call.Return(createPolicyChangeResponse, err) + return _c +} + +func (_c *PolicyServiceClientMock_CreatePolicyChange_Call) RunAndReturn(run func(ctx context.Context, in *policyv1.CreatePolicyChangeRequest, opts ...grpc.CallOption) (*policyv1.CreatePolicyChangeResponse, error)) *PolicyServiceClientMock_CreatePolicyChange_Call { + _c.Call.Return(run) + return _c +} + +// DeletePackageRule provides a mock function for the type PolicyServiceClientMock +func (_mock *PolicyServiceClientMock) DeletePackageRule(ctx context.Context, in *policyv1.DeletePackageRuleRequest, opts ...grpc.CallOption) (*policyv1.DeletePackageRuleResponse, error) { + var tmpRet mock.Arguments + if len(opts) > 0 { + tmpRet = _mock.Called(ctx, in, opts) + } else { + tmpRet = _mock.Called(ctx, in) + } + ret := tmpRet + + if len(ret) == 0 { + panic("no return value specified for DeletePackageRule") + } + + var r0 *policyv1.DeletePackageRuleResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.DeletePackageRuleRequest, ...grpc.CallOption) (*policyv1.DeletePackageRuleResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.DeletePackageRuleRequest, ...grpc.CallOption) *policyv1.DeletePackageRuleResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*policyv1.DeletePackageRuleResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *policyv1.DeletePackageRuleRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// PolicyServiceClientMock_DeletePackageRule_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeletePackageRule' +type PolicyServiceClientMock_DeletePackageRule_Call struct { + *mock.Call +} + +// DeletePackageRule is a helper method to define mock.On call +// - ctx context.Context +// - in *policyv1.DeletePackageRuleRequest +// - opts ...grpc.CallOption +func (_e *PolicyServiceClientMock_Expecter) DeletePackageRule(ctx interface{}, in interface{}, opts ...interface{}) *PolicyServiceClientMock_DeletePackageRule_Call { + return &PolicyServiceClientMock_DeletePackageRule_Call{Call: _e.mock.On("DeletePackageRule", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *PolicyServiceClientMock_DeletePackageRule_Call) Run(run func(ctx context.Context, in *policyv1.DeletePackageRuleRequest, opts ...grpc.CallOption)) *PolicyServiceClientMock_DeletePackageRule_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *policyv1.DeletePackageRuleRequest + if args[1] != nil { + arg1 = args[1].(*policyv1.DeletePackageRuleRequest) + } + var arg2 []grpc.CallOption + var variadicArgs []grpc.CallOption + if len(args) > 2 { + variadicArgs = args[2].([]grpc.CallOption) + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *PolicyServiceClientMock_DeletePackageRule_Call) Return(deletePackageRuleResponse *policyv1.DeletePackageRuleResponse, err error) *PolicyServiceClientMock_DeletePackageRule_Call { + _c.Call.Return(deletePackageRuleResponse, err) + return _c +} + +func (_c *PolicyServiceClientMock_DeletePackageRule_Call) RunAndReturn(run func(ctx context.Context, in *policyv1.DeletePackageRuleRequest, opts ...grpc.CallOption) (*policyv1.DeletePackageRuleResponse, error)) *PolicyServiceClientMock_DeletePackageRule_Call { + _c.Call.Return(run) + return _c +} + +// DeletePolicyChange provides a mock function for the type PolicyServiceClientMock +func (_mock *PolicyServiceClientMock) DeletePolicyChange(ctx context.Context, in *policyv1.DeletePolicyChangeRequest, opts ...grpc.CallOption) (*policyv1.DeletePolicyChangeResponse, error) { + var tmpRet mock.Arguments + if len(opts) > 0 { + tmpRet = _mock.Called(ctx, in, opts) + } else { + tmpRet = _mock.Called(ctx, in) + } + ret := tmpRet + + if len(ret) == 0 { + panic("no return value specified for DeletePolicyChange") + } + + var r0 *policyv1.DeletePolicyChangeResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.DeletePolicyChangeRequest, ...grpc.CallOption) (*policyv1.DeletePolicyChangeResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.DeletePolicyChangeRequest, ...grpc.CallOption) *policyv1.DeletePolicyChangeResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*policyv1.DeletePolicyChangeResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *policyv1.DeletePolicyChangeRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// PolicyServiceClientMock_DeletePolicyChange_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeletePolicyChange' +type PolicyServiceClientMock_DeletePolicyChange_Call struct { + *mock.Call +} + +// DeletePolicyChange is a helper method to define mock.On call +// - ctx context.Context +// - in *policyv1.DeletePolicyChangeRequest +// - opts ...grpc.CallOption +func (_e *PolicyServiceClientMock_Expecter) DeletePolicyChange(ctx interface{}, in interface{}, opts ...interface{}) *PolicyServiceClientMock_DeletePolicyChange_Call { + return &PolicyServiceClientMock_DeletePolicyChange_Call{Call: _e.mock.On("DeletePolicyChange", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *PolicyServiceClientMock_DeletePolicyChange_Call) Run(run func(ctx context.Context, in *policyv1.DeletePolicyChangeRequest, opts ...grpc.CallOption)) *PolicyServiceClientMock_DeletePolicyChange_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *policyv1.DeletePolicyChangeRequest + if args[1] != nil { + arg1 = args[1].(*policyv1.DeletePolicyChangeRequest) + } + var arg2 []grpc.CallOption + var variadicArgs []grpc.CallOption + if len(args) > 2 { + variadicArgs = args[2].([]grpc.CallOption) + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *PolicyServiceClientMock_DeletePolicyChange_Call) Return(deletePolicyChangeResponse *policyv1.DeletePolicyChangeResponse, err error) *PolicyServiceClientMock_DeletePolicyChange_Call { + _c.Call.Return(deletePolicyChangeResponse, err) + return _c +} + +func (_c *PolicyServiceClientMock_DeletePolicyChange_Call) RunAndReturn(run func(ctx context.Context, in *policyv1.DeletePolicyChangeRequest, opts ...grpc.CallOption) (*policyv1.DeletePolicyChangeResponse, error)) *PolicyServiceClientMock_DeletePolicyChange_Call { + _c.Call.Return(run) + return _c +} + +// GetPackageRule provides a mock function for the type PolicyServiceClientMock +func (_mock *PolicyServiceClientMock) GetPackageRule(ctx context.Context, in *policyv1.GetPackageRuleRequest, opts ...grpc.CallOption) (*policyv1.GetPackageRuleResponse, error) { + var tmpRet mock.Arguments + if len(opts) > 0 { + tmpRet = _mock.Called(ctx, in, opts) + } else { + tmpRet = _mock.Called(ctx, in) + } + ret := tmpRet + + if len(ret) == 0 { + panic("no return value specified for GetPackageRule") + } + + var r0 *policyv1.GetPackageRuleResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.GetPackageRuleRequest, ...grpc.CallOption) (*policyv1.GetPackageRuleResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.GetPackageRuleRequest, ...grpc.CallOption) *policyv1.GetPackageRuleResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*policyv1.GetPackageRuleResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *policyv1.GetPackageRuleRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// PolicyServiceClientMock_GetPackageRule_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPackageRule' +type PolicyServiceClientMock_GetPackageRule_Call struct { + *mock.Call +} + +// GetPackageRule is a helper method to define mock.On call +// - ctx context.Context +// - in *policyv1.GetPackageRuleRequest +// - opts ...grpc.CallOption +func (_e *PolicyServiceClientMock_Expecter) GetPackageRule(ctx interface{}, in interface{}, opts ...interface{}) *PolicyServiceClientMock_GetPackageRule_Call { + return &PolicyServiceClientMock_GetPackageRule_Call{Call: _e.mock.On("GetPackageRule", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *PolicyServiceClientMock_GetPackageRule_Call) Run(run func(ctx context.Context, in *policyv1.GetPackageRuleRequest, opts ...grpc.CallOption)) *PolicyServiceClientMock_GetPackageRule_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *policyv1.GetPackageRuleRequest + if args[1] != nil { + arg1 = args[1].(*policyv1.GetPackageRuleRequest) + } + var arg2 []grpc.CallOption + var variadicArgs []grpc.CallOption + if len(args) > 2 { + variadicArgs = args[2].([]grpc.CallOption) + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *PolicyServiceClientMock_GetPackageRule_Call) Return(getPackageRuleResponse *policyv1.GetPackageRuleResponse, err error) *PolicyServiceClientMock_GetPackageRule_Call { + _c.Call.Return(getPackageRuleResponse, err) + return _c +} + +func (_c *PolicyServiceClientMock_GetPackageRule_Call) RunAndReturn(run func(ctx context.Context, in *policyv1.GetPackageRuleRequest, opts ...grpc.CallOption) (*policyv1.GetPackageRuleResponse, error)) *PolicyServiceClientMock_GetPackageRule_Call { + _c.Call.Return(run) + return _c +} + +// GetPolicy provides a mock function for the type PolicyServiceClientMock +func (_mock *PolicyServiceClientMock) GetPolicy(ctx context.Context, in *policyv1.GetPolicyRequest, opts ...grpc.CallOption) (*policyv1.GetPolicyResponse, error) { + var tmpRet mock.Arguments + if len(opts) > 0 { + tmpRet = _mock.Called(ctx, in, opts) + } else { + tmpRet = _mock.Called(ctx, in) + } + ret := tmpRet + + if len(ret) == 0 { + panic("no return value specified for GetPolicy") + } + + var r0 *policyv1.GetPolicyResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.GetPolicyRequest, ...grpc.CallOption) (*policyv1.GetPolicyResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.GetPolicyRequest, ...grpc.CallOption) *policyv1.GetPolicyResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*policyv1.GetPolicyResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *policyv1.GetPolicyRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// PolicyServiceClientMock_GetPolicy_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPolicy' +type PolicyServiceClientMock_GetPolicy_Call struct { + *mock.Call +} + +// GetPolicy is a helper method to define mock.On call +// - ctx context.Context +// - in *policyv1.GetPolicyRequest +// - opts ...grpc.CallOption +func (_e *PolicyServiceClientMock_Expecter) GetPolicy(ctx interface{}, in interface{}, opts ...interface{}) *PolicyServiceClientMock_GetPolicy_Call { + return &PolicyServiceClientMock_GetPolicy_Call{Call: _e.mock.On("GetPolicy", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *PolicyServiceClientMock_GetPolicy_Call) Run(run func(ctx context.Context, in *policyv1.GetPolicyRequest, opts ...grpc.CallOption)) *PolicyServiceClientMock_GetPolicy_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *policyv1.GetPolicyRequest + if args[1] != nil { + arg1 = args[1].(*policyv1.GetPolicyRequest) + } + var arg2 []grpc.CallOption + var variadicArgs []grpc.CallOption + if len(args) > 2 { + variadicArgs = args[2].([]grpc.CallOption) + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *PolicyServiceClientMock_GetPolicy_Call) Return(getPolicyResponse *policyv1.GetPolicyResponse, err error) *PolicyServiceClientMock_GetPolicy_Call { + _c.Call.Return(getPolicyResponse, err) + return _c +} + +func (_c *PolicyServiceClientMock_GetPolicy_Call) RunAndReturn(run func(ctx context.Context, in *policyv1.GetPolicyRequest, opts ...grpc.CallOption) (*policyv1.GetPolicyResponse, error)) *PolicyServiceClientMock_GetPolicy_Call { + _c.Call.Return(run) + return _c +} + +// GetPolicyCatalog provides a mock function for the type PolicyServiceClientMock +func (_mock *PolicyServiceClientMock) GetPolicyCatalog(ctx context.Context, in *policyv1.GetPolicyCatalogRequest, opts ...grpc.CallOption) (*policyv1.GetPolicyCatalogResponse, error) { + var tmpRet mock.Arguments + if len(opts) > 0 { + tmpRet = _mock.Called(ctx, in, opts) + } else { + tmpRet = _mock.Called(ctx, in) + } + ret := tmpRet + + if len(ret) == 0 { + panic("no return value specified for GetPolicyCatalog") + } + + var r0 *policyv1.GetPolicyCatalogResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.GetPolicyCatalogRequest, ...grpc.CallOption) (*policyv1.GetPolicyCatalogResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.GetPolicyCatalogRequest, ...grpc.CallOption) *policyv1.GetPolicyCatalogResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*policyv1.GetPolicyCatalogResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *policyv1.GetPolicyCatalogRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// PolicyServiceClientMock_GetPolicyCatalog_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPolicyCatalog' +type PolicyServiceClientMock_GetPolicyCatalog_Call struct { + *mock.Call +} + +// GetPolicyCatalog is a helper method to define mock.On call +// - ctx context.Context +// - in *policyv1.GetPolicyCatalogRequest +// - opts ...grpc.CallOption +func (_e *PolicyServiceClientMock_Expecter) GetPolicyCatalog(ctx interface{}, in interface{}, opts ...interface{}) *PolicyServiceClientMock_GetPolicyCatalog_Call { + return &PolicyServiceClientMock_GetPolicyCatalog_Call{Call: _e.mock.On("GetPolicyCatalog", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *PolicyServiceClientMock_GetPolicyCatalog_Call) Run(run func(ctx context.Context, in *policyv1.GetPolicyCatalogRequest, opts ...grpc.CallOption)) *PolicyServiceClientMock_GetPolicyCatalog_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *policyv1.GetPolicyCatalogRequest + if args[1] != nil { + arg1 = args[1].(*policyv1.GetPolicyCatalogRequest) + } + var arg2 []grpc.CallOption + var variadicArgs []grpc.CallOption + if len(args) > 2 { + variadicArgs = args[2].([]grpc.CallOption) + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *PolicyServiceClientMock_GetPolicyCatalog_Call) Return(getPolicyCatalogResponse *policyv1.GetPolicyCatalogResponse, err error) *PolicyServiceClientMock_GetPolicyCatalog_Call { + _c.Call.Return(getPolicyCatalogResponse, err) + return _c +} + +func (_c *PolicyServiceClientMock_GetPolicyCatalog_Call) RunAndReturn(run func(ctx context.Context, in *policyv1.GetPolicyCatalogRequest, opts ...grpc.CallOption) (*policyv1.GetPolicyCatalogResponse, error)) *PolicyServiceClientMock_GetPolicyCatalog_Call { + _c.Call.Return(run) + return _c +} + +// GetPolicyChange provides a mock function for the type PolicyServiceClientMock +func (_mock *PolicyServiceClientMock) GetPolicyChange(ctx context.Context, in *policyv1.GetPolicyChangeRequest, opts ...grpc.CallOption) (*policyv1.GetPolicyChangeResponse, error) { + var tmpRet mock.Arguments + if len(opts) > 0 { + tmpRet = _mock.Called(ctx, in, opts) + } else { + tmpRet = _mock.Called(ctx, in) + } + ret := tmpRet + + if len(ret) == 0 { + panic("no return value specified for GetPolicyChange") + } + + var r0 *policyv1.GetPolicyChangeResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.GetPolicyChangeRequest, ...grpc.CallOption) (*policyv1.GetPolicyChangeResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.GetPolicyChangeRequest, ...grpc.CallOption) *policyv1.GetPolicyChangeResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*policyv1.GetPolicyChangeResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *policyv1.GetPolicyChangeRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// PolicyServiceClientMock_GetPolicyChange_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPolicyChange' +type PolicyServiceClientMock_GetPolicyChange_Call struct { + *mock.Call +} + +// GetPolicyChange is a helper method to define mock.On call +// - ctx context.Context +// - in *policyv1.GetPolicyChangeRequest +// - opts ...grpc.CallOption +func (_e *PolicyServiceClientMock_Expecter) GetPolicyChange(ctx interface{}, in interface{}, opts ...interface{}) *PolicyServiceClientMock_GetPolicyChange_Call { + return &PolicyServiceClientMock_GetPolicyChange_Call{Call: _e.mock.On("GetPolicyChange", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *PolicyServiceClientMock_GetPolicyChange_Call) Run(run func(ctx context.Context, in *policyv1.GetPolicyChangeRequest, opts ...grpc.CallOption)) *PolicyServiceClientMock_GetPolicyChange_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *policyv1.GetPolicyChangeRequest + if args[1] != nil { + arg1 = args[1].(*policyv1.GetPolicyChangeRequest) + } + var arg2 []grpc.CallOption + var variadicArgs []grpc.CallOption + if len(args) > 2 { + variadicArgs = args[2].([]grpc.CallOption) + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *PolicyServiceClientMock_GetPolicyChange_Call) Return(getPolicyChangeResponse *policyv1.GetPolicyChangeResponse, err error) *PolicyServiceClientMock_GetPolicyChange_Call { + _c.Call.Return(getPolicyChangeResponse, err) + return _c +} + +func (_c *PolicyServiceClientMock_GetPolicyChange_Call) RunAndReturn(run func(ctx context.Context, in *policyv1.GetPolicyChangeRequest, opts ...grpc.CallOption) (*policyv1.GetPolicyChangeResponse, error)) *PolicyServiceClientMock_GetPolicyChange_Call { + _c.Call.Return(run) + return _c +} + +// GetPolicyRevision provides a mock function for the type PolicyServiceClientMock +func (_mock *PolicyServiceClientMock) GetPolicyRevision(ctx context.Context, in *policyv1.GetPolicyRevisionRequest, opts ...grpc.CallOption) (*policyv1.GetPolicyRevisionResponse, error) { + var tmpRet mock.Arguments + if len(opts) > 0 { + tmpRet = _mock.Called(ctx, in, opts) + } else { + tmpRet = _mock.Called(ctx, in) + } + ret := tmpRet + + if len(ret) == 0 { + panic("no return value specified for GetPolicyRevision") + } + + var r0 *policyv1.GetPolicyRevisionResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.GetPolicyRevisionRequest, ...grpc.CallOption) (*policyv1.GetPolicyRevisionResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.GetPolicyRevisionRequest, ...grpc.CallOption) *policyv1.GetPolicyRevisionResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*policyv1.GetPolicyRevisionResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *policyv1.GetPolicyRevisionRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// PolicyServiceClientMock_GetPolicyRevision_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPolicyRevision' +type PolicyServiceClientMock_GetPolicyRevision_Call struct { + *mock.Call +} + +// GetPolicyRevision is a helper method to define mock.On call +// - ctx context.Context +// - in *policyv1.GetPolicyRevisionRequest +// - opts ...grpc.CallOption +func (_e *PolicyServiceClientMock_Expecter) GetPolicyRevision(ctx interface{}, in interface{}, opts ...interface{}) *PolicyServiceClientMock_GetPolicyRevision_Call { + return &PolicyServiceClientMock_GetPolicyRevision_Call{Call: _e.mock.On("GetPolicyRevision", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *PolicyServiceClientMock_GetPolicyRevision_Call) Run(run func(ctx context.Context, in *policyv1.GetPolicyRevisionRequest, opts ...grpc.CallOption)) *PolicyServiceClientMock_GetPolicyRevision_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *policyv1.GetPolicyRevisionRequest + if args[1] != nil { + arg1 = args[1].(*policyv1.GetPolicyRevisionRequest) + } + var arg2 []grpc.CallOption + var variadicArgs []grpc.CallOption + if len(args) > 2 { + variadicArgs = args[2].([]grpc.CallOption) + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *PolicyServiceClientMock_GetPolicyRevision_Call) Return(getPolicyRevisionResponse *policyv1.GetPolicyRevisionResponse, err error) *PolicyServiceClientMock_GetPolicyRevision_Call { + _c.Call.Return(getPolicyRevisionResponse, err) + return _c +} + +func (_c *PolicyServiceClientMock_GetPolicyRevision_Call) RunAndReturn(run func(ctx context.Context, in *policyv1.GetPolicyRevisionRequest, opts ...grpc.CallOption) (*policyv1.GetPolicyRevisionResponse, error)) *PolicyServiceClientMock_GetPolicyRevision_Call { + _c.Call.Return(run) + return _c +} + +// GetSubjectPolicy provides a mock function for the type PolicyServiceClientMock +func (_mock *PolicyServiceClientMock) GetSubjectPolicy(ctx context.Context, in *policyv1.GetSubjectPolicyRequest, opts ...grpc.CallOption) (*policyv1.GetSubjectPolicyResponse, error) { + var tmpRet mock.Arguments + if len(opts) > 0 { + tmpRet = _mock.Called(ctx, in, opts) + } else { + tmpRet = _mock.Called(ctx, in) + } + ret := tmpRet + + if len(ret) == 0 { + panic("no return value specified for GetSubjectPolicy") + } + + var r0 *policyv1.GetSubjectPolicyResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.GetSubjectPolicyRequest, ...grpc.CallOption) (*policyv1.GetSubjectPolicyResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.GetSubjectPolicyRequest, ...grpc.CallOption) *policyv1.GetSubjectPolicyResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*policyv1.GetSubjectPolicyResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *policyv1.GetSubjectPolicyRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// PolicyServiceClientMock_GetSubjectPolicy_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetSubjectPolicy' +type PolicyServiceClientMock_GetSubjectPolicy_Call struct { + *mock.Call +} + +// GetSubjectPolicy is a helper method to define mock.On call +// - ctx context.Context +// - in *policyv1.GetSubjectPolicyRequest +// - opts ...grpc.CallOption +func (_e *PolicyServiceClientMock_Expecter) GetSubjectPolicy(ctx interface{}, in interface{}, opts ...interface{}) *PolicyServiceClientMock_GetSubjectPolicy_Call { + return &PolicyServiceClientMock_GetSubjectPolicy_Call{Call: _e.mock.On("GetSubjectPolicy", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *PolicyServiceClientMock_GetSubjectPolicy_Call) Run(run func(ctx context.Context, in *policyv1.GetSubjectPolicyRequest, opts ...grpc.CallOption)) *PolicyServiceClientMock_GetSubjectPolicy_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *policyv1.GetSubjectPolicyRequest + if args[1] != nil { + arg1 = args[1].(*policyv1.GetSubjectPolicyRequest) + } + var arg2 []grpc.CallOption + var variadicArgs []grpc.CallOption + if len(args) > 2 { + variadicArgs = args[2].([]grpc.CallOption) + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *PolicyServiceClientMock_GetSubjectPolicy_Call) Return(getSubjectPolicyResponse *policyv1.GetSubjectPolicyResponse, err error) *PolicyServiceClientMock_GetSubjectPolicy_Call { + _c.Call.Return(getSubjectPolicyResponse, err) + return _c +} + +func (_c *PolicyServiceClientMock_GetSubjectPolicy_Call) RunAndReturn(run func(ctx context.Context, in *policyv1.GetSubjectPolicyRequest, opts ...grpc.CallOption) (*policyv1.GetSubjectPolicyResponse, error)) *PolicyServiceClientMock_GetSubjectPolicy_Call { + _c.Call.Return(run) + return _c +} + +// ListPackageRules provides a mock function for the type PolicyServiceClientMock +func (_mock *PolicyServiceClientMock) ListPackageRules(ctx context.Context, in *policyv1.ListPackageRulesRequest, opts ...grpc.CallOption) (*policyv1.ListPackageRulesResponse, error) { + var tmpRet mock.Arguments + if len(opts) > 0 { + tmpRet = _mock.Called(ctx, in, opts) + } else { + tmpRet = _mock.Called(ctx, in) + } + ret := tmpRet + + if len(ret) == 0 { + panic("no return value specified for ListPackageRules") + } + + var r0 *policyv1.ListPackageRulesResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.ListPackageRulesRequest, ...grpc.CallOption) (*policyv1.ListPackageRulesResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.ListPackageRulesRequest, ...grpc.CallOption) *policyv1.ListPackageRulesResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*policyv1.ListPackageRulesResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *policyv1.ListPackageRulesRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// PolicyServiceClientMock_ListPackageRules_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListPackageRules' +type PolicyServiceClientMock_ListPackageRules_Call struct { + *mock.Call +} + +// ListPackageRules is a helper method to define mock.On call +// - ctx context.Context +// - in *policyv1.ListPackageRulesRequest +// - opts ...grpc.CallOption +func (_e *PolicyServiceClientMock_Expecter) ListPackageRules(ctx interface{}, in interface{}, opts ...interface{}) *PolicyServiceClientMock_ListPackageRules_Call { + return &PolicyServiceClientMock_ListPackageRules_Call{Call: _e.mock.On("ListPackageRules", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *PolicyServiceClientMock_ListPackageRules_Call) Run(run func(ctx context.Context, in *policyv1.ListPackageRulesRequest, opts ...grpc.CallOption)) *PolicyServiceClientMock_ListPackageRules_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *policyv1.ListPackageRulesRequest + if args[1] != nil { + arg1 = args[1].(*policyv1.ListPackageRulesRequest) + } + var arg2 []grpc.CallOption + var variadicArgs []grpc.CallOption + if len(args) > 2 { + variadicArgs = args[2].([]grpc.CallOption) + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *PolicyServiceClientMock_ListPackageRules_Call) Return(listPackageRulesResponse *policyv1.ListPackageRulesResponse, err error) *PolicyServiceClientMock_ListPackageRules_Call { + _c.Call.Return(listPackageRulesResponse, err) + return _c +} + +func (_c *PolicyServiceClientMock_ListPackageRules_Call) RunAndReturn(run func(ctx context.Context, in *policyv1.ListPackageRulesRequest, opts ...grpc.CallOption) (*policyv1.ListPackageRulesResponse, error)) *PolicyServiceClientMock_ListPackageRules_Call { + _c.Call.Return(run) + return _c +} + +// ListPolicyChanges provides a mock function for the type PolicyServiceClientMock +func (_mock *PolicyServiceClientMock) ListPolicyChanges(ctx context.Context, in *policyv1.ListPolicyChangesRequest, opts ...grpc.CallOption) (*policyv1.ListPolicyChangesResponse, error) { + var tmpRet mock.Arguments + if len(opts) > 0 { + tmpRet = _mock.Called(ctx, in, opts) + } else { + tmpRet = _mock.Called(ctx, in) + } + ret := tmpRet + + if len(ret) == 0 { + panic("no return value specified for ListPolicyChanges") + } + + var r0 *policyv1.ListPolicyChangesResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.ListPolicyChangesRequest, ...grpc.CallOption) (*policyv1.ListPolicyChangesResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.ListPolicyChangesRequest, ...grpc.CallOption) *policyv1.ListPolicyChangesResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*policyv1.ListPolicyChangesResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *policyv1.ListPolicyChangesRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// PolicyServiceClientMock_ListPolicyChanges_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListPolicyChanges' +type PolicyServiceClientMock_ListPolicyChanges_Call struct { + *mock.Call +} + +// ListPolicyChanges is a helper method to define mock.On call +// - ctx context.Context +// - in *policyv1.ListPolicyChangesRequest +// - opts ...grpc.CallOption +func (_e *PolicyServiceClientMock_Expecter) ListPolicyChanges(ctx interface{}, in interface{}, opts ...interface{}) *PolicyServiceClientMock_ListPolicyChanges_Call { + return &PolicyServiceClientMock_ListPolicyChanges_Call{Call: _e.mock.On("ListPolicyChanges", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *PolicyServiceClientMock_ListPolicyChanges_Call) Run(run func(ctx context.Context, in *policyv1.ListPolicyChangesRequest, opts ...grpc.CallOption)) *PolicyServiceClientMock_ListPolicyChanges_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *policyv1.ListPolicyChangesRequest + if args[1] != nil { + arg1 = args[1].(*policyv1.ListPolicyChangesRequest) + } + var arg2 []grpc.CallOption + var variadicArgs []grpc.CallOption + if len(args) > 2 { + variadicArgs = args[2].([]grpc.CallOption) + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *PolicyServiceClientMock_ListPolicyChanges_Call) Return(listPolicyChangesResponse *policyv1.ListPolicyChangesResponse, err error) *PolicyServiceClientMock_ListPolicyChanges_Call { + _c.Call.Return(listPolicyChangesResponse, err) + return _c +} + +func (_c *PolicyServiceClientMock_ListPolicyChanges_Call) RunAndReturn(run func(ctx context.Context, in *policyv1.ListPolicyChangesRequest, opts ...grpc.CallOption) (*policyv1.ListPolicyChangesResponse, error)) *PolicyServiceClientMock_ListPolicyChanges_Call { + _c.Call.Return(run) + return _c +} + +// ListPolicyRevisions provides a mock function for the type PolicyServiceClientMock +func (_mock *PolicyServiceClientMock) ListPolicyRevisions(ctx context.Context, in *policyv1.ListPolicyRevisionsRequest, opts ...grpc.CallOption) (*policyv1.ListPolicyRevisionsResponse, error) { + var tmpRet mock.Arguments + if len(opts) > 0 { + tmpRet = _mock.Called(ctx, in, opts) + } else { + tmpRet = _mock.Called(ctx, in) + } + ret := tmpRet + + if len(ret) == 0 { + panic("no return value specified for ListPolicyRevisions") + } + + var r0 *policyv1.ListPolicyRevisionsResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.ListPolicyRevisionsRequest, ...grpc.CallOption) (*policyv1.ListPolicyRevisionsResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.ListPolicyRevisionsRequest, ...grpc.CallOption) *policyv1.ListPolicyRevisionsResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*policyv1.ListPolicyRevisionsResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *policyv1.ListPolicyRevisionsRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// PolicyServiceClientMock_ListPolicyRevisions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListPolicyRevisions' +type PolicyServiceClientMock_ListPolicyRevisions_Call struct { + *mock.Call +} + +// ListPolicyRevisions is a helper method to define mock.On call +// - ctx context.Context +// - in *policyv1.ListPolicyRevisionsRequest +// - opts ...grpc.CallOption +func (_e *PolicyServiceClientMock_Expecter) ListPolicyRevisions(ctx interface{}, in interface{}, opts ...interface{}) *PolicyServiceClientMock_ListPolicyRevisions_Call { + return &PolicyServiceClientMock_ListPolicyRevisions_Call{Call: _e.mock.On("ListPolicyRevisions", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *PolicyServiceClientMock_ListPolicyRevisions_Call) Run(run func(ctx context.Context, in *policyv1.ListPolicyRevisionsRequest, opts ...grpc.CallOption)) *PolicyServiceClientMock_ListPolicyRevisions_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *policyv1.ListPolicyRevisionsRequest + if args[1] != nil { + arg1 = args[1].(*policyv1.ListPolicyRevisionsRequest) + } + var arg2 []grpc.CallOption + var variadicArgs []grpc.CallOption + if len(args) > 2 { + variadicArgs = args[2].([]grpc.CallOption) + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *PolicyServiceClientMock_ListPolicyRevisions_Call) Return(listPolicyRevisionsResponse *policyv1.ListPolicyRevisionsResponse, err error) *PolicyServiceClientMock_ListPolicyRevisions_Call { + _c.Call.Return(listPolicyRevisionsResponse, err) + return _c +} + +func (_c *PolicyServiceClientMock_ListPolicyRevisions_Call) RunAndReturn(run func(ctx context.Context, in *policyv1.ListPolicyRevisionsRequest, opts ...grpc.CallOption) (*policyv1.ListPolicyRevisionsResponse, error)) *PolicyServiceClientMock_ListPolicyRevisions_Call { + _c.Call.Return(run) + return _c +} + +// PreviewPolicyChange provides a mock function for the type PolicyServiceClientMock +func (_mock *PolicyServiceClientMock) PreviewPolicyChange(ctx context.Context, in *policyv1.PreviewPolicyChangeRequest, opts ...grpc.CallOption) (*policyv1.PreviewPolicyChangeResponse, error) { + var tmpRet mock.Arguments + if len(opts) > 0 { + tmpRet = _mock.Called(ctx, in, opts) + } else { + tmpRet = _mock.Called(ctx, in) + } + ret := tmpRet + + if len(ret) == 0 { + panic("no return value specified for PreviewPolicyChange") + } + + var r0 *policyv1.PreviewPolicyChangeResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.PreviewPolicyChangeRequest, ...grpc.CallOption) (*policyv1.PreviewPolicyChangeResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.PreviewPolicyChangeRequest, ...grpc.CallOption) *policyv1.PreviewPolicyChangeResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*policyv1.PreviewPolicyChangeResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *policyv1.PreviewPolicyChangeRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// PolicyServiceClientMock_PreviewPolicyChange_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PreviewPolicyChange' +type PolicyServiceClientMock_PreviewPolicyChange_Call struct { + *mock.Call +} + +// PreviewPolicyChange is a helper method to define mock.On call +// - ctx context.Context +// - in *policyv1.PreviewPolicyChangeRequest +// - opts ...grpc.CallOption +func (_e *PolicyServiceClientMock_Expecter) PreviewPolicyChange(ctx interface{}, in interface{}, opts ...interface{}) *PolicyServiceClientMock_PreviewPolicyChange_Call { + return &PolicyServiceClientMock_PreviewPolicyChange_Call{Call: _e.mock.On("PreviewPolicyChange", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *PolicyServiceClientMock_PreviewPolicyChange_Call) Run(run func(ctx context.Context, in *policyv1.PreviewPolicyChangeRequest, opts ...grpc.CallOption)) *PolicyServiceClientMock_PreviewPolicyChange_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *policyv1.PreviewPolicyChangeRequest + if args[1] != nil { + arg1 = args[1].(*policyv1.PreviewPolicyChangeRequest) + } + var arg2 []grpc.CallOption + var variadicArgs []grpc.CallOption + if len(args) > 2 { + variadicArgs = args[2].([]grpc.CallOption) + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *PolicyServiceClientMock_PreviewPolicyChange_Call) Return(previewPolicyChangeResponse *policyv1.PreviewPolicyChangeResponse, err error) *PolicyServiceClientMock_PreviewPolicyChange_Call { + _c.Call.Return(previewPolicyChangeResponse, err) + return _c +} + +func (_c *PolicyServiceClientMock_PreviewPolicyChange_Call) RunAndReturn(run func(ctx context.Context, in *policyv1.PreviewPolicyChangeRequest, opts ...grpc.CallOption) (*policyv1.PreviewPolicyChangeResponse, error)) *PolicyServiceClientMock_PreviewPolicyChange_Call { + _c.Call.Return(run) + return _c +} + +// PublishPolicyChange provides a mock function for the type PolicyServiceClientMock +func (_mock *PolicyServiceClientMock) PublishPolicyChange(ctx context.Context, in *policyv1.PublishPolicyChangeRequest, opts ...grpc.CallOption) (*policyv1.PublishPolicyChangeResponse, error) { + var tmpRet mock.Arguments + if len(opts) > 0 { + tmpRet = _mock.Called(ctx, in, opts) + } else { + tmpRet = _mock.Called(ctx, in) + } + ret := tmpRet + + if len(ret) == 0 { + panic("no return value specified for PublishPolicyChange") + } + + var r0 *policyv1.PublishPolicyChangeResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.PublishPolicyChangeRequest, ...grpc.CallOption) (*policyv1.PublishPolicyChangeResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.PublishPolicyChangeRequest, ...grpc.CallOption) *policyv1.PublishPolicyChangeResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*policyv1.PublishPolicyChangeResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *policyv1.PublishPolicyChangeRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// PolicyServiceClientMock_PublishPolicyChange_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PublishPolicyChange' +type PolicyServiceClientMock_PublishPolicyChange_Call struct { + *mock.Call +} + +// PublishPolicyChange is a helper method to define mock.On call +// - ctx context.Context +// - in *policyv1.PublishPolicyChangeRequest +// - opts ...grpc.CallOption +func (_e *PolicyServiceClientMock_Expecter) PublishPolicyChange(ctx interface{}, in interface{}, opts ...interface{}) *PolicyServiceClientMock_PublishPolicyChange_Call { + return &PolicyServiceClientMock_PublishPolicyChange_Call{Call: _e.mock.On("PublishPolicyChange", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *PolicyServiceClientMock_PublishPolicyChange_Call) Run(run func(ctx context.Context, in *policyv1.PublishPolicyChangeRequest, opts ...grpc.CallOption)) *PolicyServiceClientMock_PublishPolicyChange_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *policyv1.PublishPolicyChangeRequest + if args[1] != nil { + arg1 = args[1].(*policyv1.PublishPolicyChangeRequest) + } + var arg2 []grpc.CallOption + var variadicArgs []grpc.CallOption + if len(args) > 2 { + variadicArgs = args[2].([]grpc.CallOption) + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *PolicyServiceClientMock_PublishPolicyChange_Call) Return(publishPolicyChangeResponse *policyv1.PublishPolicyChangeResponse, err error) *PolicyServiceClientMock_PublishPolicyChange_Call { + _c.Call.Return(publishPolicyChangeResponse, err) + return _c +} + +func (_c *PolicyServiceClientMock_PublishPolicyChange_Call) RunAndReturn(run func(ctx context.Context, in *policyv1.PublishPolicyChangeRequest, opts ...grpc.CallOption) (*policyv1.PublishPolicyChangeResponse, error)) *PolicyServiceClientMock_PublishPolicyChange_Call { + _c.Call.Return(run) + return _c +} + +// SyncPolicyChange provides a mock function for the type PolicyServiceClientMock +func (_mock *PolicyServiceClientMock) SyncPolicyChange(ctx context.Context, in *policyv1.SyncPolicyChangeRequest, opts ...grpc.CallOption) (*policyv1.SyncPolicyChangeResponse, error) { + var tmpRet mock.Arguments + if len(opts) > 0 { + tmpRet = _mock.Called(ctx, in, opts) + } else { + tmpRet = _mock.Called(ctx, in) + } + ret := tmpRet + + if len(ret) == 0 { + panic("no return value specified for SyncPolicyChange") + } + + var r0 *policyv1.SyncPolicyChangeResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.SyncPolicyChangeRequest, ...grpc.CallOption) (*policyv1.SyncPolicyChangeResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.SyncPolicyChangeRequest, ...grpc.CallOption) *policyv1.SyncPolicyChangeResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*policyv1.SyncPolicyChangeResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *policyv1.SyncPolicyChangeRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// PolicyServiceClientMock_SyncPolicyChange_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SyncPolicyChange' +type PolicyServiceClientMock_SyncPolicyChange_Call struct { + *mock.Call +} + +// SyncPolicyChange is a helper method to define mock.On call +// - ctx context.Context +// - in *policyv1.SyncPolicyChangeRequest +// - opts ...grpc.CallOption +func (_e *PolicyServiceClientMock_Expecter) SyncPolicyChange(ctx interface{}, in interface{}, opts ...interface{}) *PolicyServiceClientMock_SyncPolicyChange_Call { + return &PolicyServiceClientMock_SyncPolicyChange_Call{Call: _e.mock.On("SyncPolicyChange", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *PolicyServiceClientMock_SyncPolicyChange_Call) Run(run func(ctx context.Context, in *policyv1.SyncPolicyChangeRequest, opts ...grpc.CallOption)) *PolicyServiceClientMock_SyncPolicyChange_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *policyv1.SyncPolicyChangeRequest + if args[1] != nil { + arg1 = args[1].(*policyv1.SyncPolicyChangeRequest) + } + var arg2 []grpc.CallOption + var variadicArgs []grpc.CallOption + if len(args) > 2 { + variadicArgs = args[2].([]grpc.CallOption) + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *PolicyServiceClientMock_SyncPolicyChange_Call) Return(syncPolicyChangeResponse *policyv1.SyncPolicyChangeResponse, err error) *PolicyServiceClientMock_SyncPolicyChange_Call { + _c.Call.Return(syncPolicyChangeResponse, err) + return _c +} + +func (_c *PolicyServiceClientMock_SyncPolicyChange_Call) RunAndReturn(run func(ctx context.Context, in *policyv1.SyncPolicyChangeRequest, opts ...grpc.CallOption) (*policyv1.SyncPolicyChangeResponse, error)) *PolicyServiceClientMock_SyncPolicyChange_Call { + _c.Call.Return(run) + return _c +} + +// UpdatePackageRule provides a mock function for the type PolicyServiceClientMock +func (_mock *PolicyServiceClientMock) UpdatePackageRule(ctx context.Context, in *policyv1.UpdatePackageRuleRequest, opts ...grpc.CallOption) (*policyv1.UpdatePackageRuleResponse, error) { + var tmpRet mock.Arguments + if len(opts) > 0 { + tmpRet = _mock.Called(ctx, in, opts) + } else { + tmpRet = _mock.Called(ctx, in) + } + ret := tmpRet + + if len(ret) == 0 { + panic("no return value specified for UpdatePackageRule") + } + + var r0 *policyv1.UpdatePackageRuleResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.UpdatePackageRuleRequest, ...grpc.CallOption) (*policyv1.UpdatePackageRuleResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.UpdatePackageRuleRequest, ...grpc.CallOption) *policyv1.UpdatePackageRuleResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*policyv1.UpdatePackageRuleResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *policyv1.UpdatePackageRuleRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// PolicyServiceClientMock_UpdatePackageRule_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdatePackageRule' +type PolicyServiceClientMock_UpdatePackageRule_Call struct { + *mock.Call +} + +// UpdatePackageRule is a helper method to define mock.On call +// - ctx context.Context +// - in *policyv1.UpdatePackageRuleRequest +// - opts ...grpc.CallOption +func (_e *PolicyServiceClientMock_Expecter) UpdatePackageRule(ctx interface{}, in interface{}, opts ...interface{}) *PolicyServiceClientMock_UpdatePackageRule_Call { + return &PolicyServiceClientMock_UpdatePackageRule_Call{Call: _e.mock.On("UpdatePackageRule", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *PolicyServiceClientMock_UpdatePackageRule_Call) Run(run func(ctx context.Context, in *policyv1.UpdatePackageRuleRequest, opts ...grpc.CallOption)) *PolicyServiceClientMock_UpdatePackageRule_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *policyv1.UpdatePackageRuleRequest + if args[1] != nil { + arg1 = args[1].(*policyv1.UpdatePackageRuleRequest) + } + var arg2 []grpc.CallOption + var variadicArgs []grpc.CallOption + if len(args) > 2 { + variadicArgs = args[2].([]grpc.CallOption) + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *PolicyServiceClientMock_UpdatePackageRule_Call) Return(updatePackageRuleResponse *policyv1.UpdatePackageRuleResponse, err error) *PolicyServiceClientMock_UpdatePackageRule_Call { + _c.Call.Return(updatePackageRuleResponse, err) + return _c +} + +func (_c *PolicyServiceClientMock_UpdatePackageRule_Call) RunAndReturn(run func(ctx context.Context, in *policyv1.UpdatePackageRuleRequest, opts ...grpc.CallOption) (*policyv1.UpdatePackageRuleResponse, error)) *PolicyServiceClientMock_UpdatePackageRule_Call { + _c.Call.Return(run) + return _c +} + +// UpdatePolicyChange provides a mock function for the type PolicyServiceClientMock +func (_mock *PolicyServiceClientMock) UpdatePolicyChange(ctx context.Context, in *policyv1.UpdatePolicyChangeRequest, opts ...grpc.CallOption) (*policyv1.UpdatePolicyChangeResponse, error) { + var tmpRet mock.Arguments + if len(opts) > 0 { + tmpRet = _mock.Called(ctx, in, opts) + } else { + tmpRet = _mock.Called(ctx, in) + } + ret := tmpRet + + if len(ret) == 0 { + panic("no return value specified for UpdatePolicyChange") + } + + var r0 *policyv1.UpdatePolicyChangeResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.UpdatePolicyChangeRequest, ...grpc.CallOption) (*policyv1.UpdatePolicyChangeResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.UpdatePolicyChangeRequest, ...grpc.CallOption) *policyv1.UpdatePolicyChangeResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*policyv1.UpdatePolicyChangeResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *policyv1.UpdatePolicyChangeRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// PolicyServiceClientMock_UpdatePolicyChange_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdatePolicyChange' +type PolicyServiceClientMock_UpdatePolicyChange_Call struct { + *mock.Call +} + +// UpdatePolicyChange is a helper method to define mock.On call +// - ctx context.Context +// - in *policyv1.UpdatePolicyChangeRequest +// - opts ...grpc.CallOption +func (_e *PolicyServiceClientMock_Expecter) UpdatePolicyChange(ctx interface{}, in interface{}, opts ...interface{}) *PolicyServiceClientMock_UpdatePolicyChange_Call { + return &PolicyServiceClientMock_UpdatePolicyChange_Call{Call: _e.mock.On("UpdatePolicyChange", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *PolicyServiceClientMock_UpdatePolicyChange_Call) Run(run func(ctx context.Context, in *policyv1.UpdatePolicyChangeRequest, opts ...grpc.CallOption)) *PolicyServiceClientMock_UpdatePolicyChange_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *policyv1.UpdatePolicyChangeRequest + if args[1] != nil { + arg1 = args[1].(*policyv1.UpdatePolicyChangeRequest) + } + var arg2 []grpc.CallOption + var variadicArgs []grpc.CallOption + if len(args) > 2 { + variadicArgs = args[2].([]grpc.CallOption) + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *PolicyServiceClientMock_UpdatePolicyChange_Call) Return(updatePolicyChangeResponse *policyv1.UpdatePolicyChangeResponse, err error) *PolicyServiceClientMock_UpdatePolicyChange_Call { + _c.Call.Return(updatePolicyChangeResponse, err) + return _c +} + +func (_c *PolicyServiceClientMock_UpdatePolicyChange_Call) RunAndReturn(run func(ctx context.Context, in *policyv1.UpdatePolicyChangeRequest, opts ...grpc.CallOption) (*policyv1.UpdatePolicyChangeResponse, error)) *PolicyServiceClientMock_UpdatePolicyChange_Call { + _c.Call.Return(run) + return _c +} diff --git a/internal/cloudpolicy/protoyaml.go b/internal/cloudpolicy/protoyaml.go new file mode 100644 index 0000000..6643f99 --- /dev/null +++ b/internal/cloudpolicy/protoyaml.go @@ -0,0 +1,564 @@ +package cloudpolicy + +import ( + "encoding/base64" + "fmt" + "sort" + "strconv" + "strings" + "time" + + yaml "go.yaml.in/yaml/v3" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/types/known/durationpb" + "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/safedep/cli/internal/duration" + "github.com/safedep/cli/internal/tui" +) + +// The YAML form walks the proto descriptor, so a new contract field works +// after an SDK bump with no code change here. Three message types get a +// form for people: a duration ("168h"), a timestamp (RFC 3339) and a label +// selector (the Kubernetes form, with matchLabels and matchExpressions). + +const ( + durationFullName = "google.protobuf.Duration" + timestampFullName = "google.protobuf.Timestamp" + labelSelectorFullName = "safedep.messages.controltower.v1.LabelSelector" +) + +// selectorOperators maps the LabelSelectorOperator numbers to the Kubernetes +// operator names. +var selectorOperators = map[protoreflect.EnumNumber]string{ + 1: "In", + 2: "NotIn", + 3: "Exists", + 4: "DoesNotExist", +} + +// yamlCodec encodes and decodes proto messages as YAML nodes. skip names the +// fields that the document leaves out, by full name. +type yamlCodec struct { + skip map[protoreflect.FullName]string +} + +func (c *yamlCodec) encodeMessage(m protoreflect.Message) *yaml.Node { + switch m.Descriptor().FullName() { + case durationFullName, timestampFullName: + return scalarNode(c.formatWellKnown(m)) + case labelSelectorFullName: + return encodeSelector(m) + } + + out := &yaml.Node{Kind: yaml.MappingNode} + fields := m.Descriptor().Fields() + for i := 0; i < fields.Len(); i++ { + fd := fields.Get(i) + if _, skipped := c.skip[fd.FullName()]; skipped || !m.Has(fd) { + continue + } + out.Content = append(out.Content, scalarNode(string(fd.Name())), c.encodeField(fd, m.Get(fd))) + } + return out +} + +func (c *yamlCodec) encodeField(fd protoreflect.FieldDescriptor, v protoreflect.Value) *yaml.Node { + switch { + case fd.IsList(): + list := v.List() + out := &yaml.Node{Kind: yaml.SequenceNode} + for i := 0; i < list.Len(); i++ { + out.Content = append(out.Content, c.encodeSingular(fd, list.Get(i))) + } + return out + case fd.IsMap(): + entries := v.Map() + keys := make([]protoreflect.MapKey, 0, entries.Len()) + entries.Range(func(k protoreflect.MapKey, _ protoreflect.Value) bool { + keys = append(keys, k) + return true + }) + sort.Slice(keys, func(i, j int) bool { return keys[i].String() < keys[j].String() }) + out := &yaml.Node{Kind: yaml.MappingNode} + for _, k := range keys { + out.Content = append(out.Content, scalarNode(k.String()), c.encodeSingular(fd.MapValue(), entries.Get(k))) + } + return out + default: + return c.encodeSingular(fd, v) + } +} + +func (c *yamlCodec) encodeSingular(fd protoreflect.FieldDescriptor, v protoreflect.Value) *yaml.Node { + switch fd.Kind() { + case protoreflect.MessageKind, protoreflect.GroupKind: + return c.encodeMessage(v.Message()) + case protoreflect.EnumKind: + return scalarNode(enumValueToken(fd.Enum(), v.Enum())) + case protoreflect.BytesKind: + return scalarNode(base64.StdEncoding.EncodeToString(v.Bytes())) + case protoreflect.StringKind: + return stringNode(v.String()) + default: + return scalarNode(v.String()) + } +} + +func (c *yamlCodec) formatWellKnown(m protoreflect.Message) string { + switch msg := m.Interface().(type) { + case *durationpb.Duration: + return duration.Format(msg.AsDuration()) + case *timestamppb.Timestamp: + return msg.AsTime().UTC().Format(time.RFC3339) + default: + return "" + } +} + +func encodeSelector(m protoreflect.Message) *yaml.Node { + fields := m.Descriptor().Fields() + out := &yaml.Node{Kind: yaml.MappingNode} + + if labels := m.Get(fields.ByName("match_labels")).Map(); labels.Len() > 0 { + keys := make([]string, 0, labels.Len()) + labels.Range(func(k protoreflect.MapKey, _ protoreflect.Value) bool { + keys = append(keys, k.String()) + return true + }) + sort.Strings(keys) + node := &yaml.Node{Kind: yaml.MappingNode, Style: yaml.FlowStyle} + for _, k := range keys { + v := labels.Get(protoreflect.ValueOfString(k).MapKey()) + node.Content = append(node.Content, scalarNode(k), stringNode(v.String())) + } + out.Content = append(out.Content, scalarNode("matchLabels"), node) + } + + if exprs := m.Get(fields.ByName("match_expressions")).List(); exprs.Len() > 0 { + seq := &yaml.Node{Kind: yaml.SequenceNode} + for i := 0; i < exprs.Len(); i++ { + expr := exprs.Get(i).Message() + efs := expr.Descriptor().Fields() + item := &yaml.Node{Kind: yaml.MappingNode, Style: yaml.FlowStyle} + item.Content = append(item.Content, + scalarNode("key"), stringNode(expr.Get(efs.ByName("key")).String()), + scalarNode("operator"), scalarNode(selectorOperators[expr.Get(efs.ByName("operator")).Enum()]), + ) + if values := expr.Get(efs.ByName("values")).List(); values.Len() > 0 { + valueSeq := &yaml.Node{Kind: yaml.SequenceNode, Style: yaml.FlowStyle} + for j := 0; j < values.Len(); j++ { + valueSeq.Content = append(valueSeq.Content, stringNode(values.Get(j).String())) + } + item.Content = append(item.Content, scalarNode("values"), valueSeq) + } + seq.Content = append(seq.Content, item) + } + out.Content = append(out.Content, scalarNode("matchExpressions"), seq) + } + if len(out.Content) == 0 { + out.Style = yaml.FlowStyle + } + return out +} + +func scalarNode(value string) *yaml.Node { + return &yaml.Node{Kind: yaml.ScalarNode, Value: value} +} + +// stringNode tags the value as a string, so a value such as "true" or "300" +// keeps its type through a round trip. +func stringNode(value string) *yaml.Node { + return &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: value} +} + +// enumPrefix is the prefix that every value of a SafeDep enum shares, taken +// from its zero value, as "SEVERITY_" from "SEVERITY_UNSPECIFIED". +func enumPrefix(ed protoreflect.EnumDescriptor) string { + zero := ed.Values().ByNumber(0) + if zero == nil { + return "" + } + return strings.TrimSuffix(string(zero.Name()), "UNSPECIFIED") +} + +// enumValueToken writes an enum value as a short token, as "medium" for +// SEVERITY_MEDIUM. A number that the SDK does not know stays a number. +func enumValueToken(ed protoreflect.EnumDescriptor, n protoreflect.EnumNumber) string { + value := ed.Values().ByNumber(n) + if value == nil { + return strconv.Itoa(int(n)) + } + return tui.EnumToken(string(value.Name()), enumPrefix(ed)) +} + +// enumTokens lists the tokens of an enum, without the zero value. +func enumTokens(ed protoreflect.EnumDescriptor) []string { + names := make(map[int32]string, ed.Values().Len()) + for i := 0; i < ed.Values().Len(); i++ { + v := ed.Values().Get(i) + names[int32(v.Number())] = string(v.Name()) + } + return tui.EnumTokens(names, enumPrefix(ed)) +} + +// parseEnumToken reads a token, a full value name or a number. +func parseEnumToken(ed protoreflect.EnumDescriptor, token string) (protoreflect.EnumNumber, bool) { + text := strings.TrimSpace(token) + prefix := enumPrefix(ed) + for i := 0; i < ed.Values().Len(); i++ { + v := ed.Values().Get(i) + if v.Number() == 0 { + continue + } + name := string(v.Name()) + if text == name || strings.EqualFold(text, tui.EnumToken(name, prefix)) || + strings.EqualFold(strings.ReplaceAll(text, "_", "-"), tui.EnumToken(name, prefix)) { + return v.Number(), true + } + } + return 0, false +} + +// decodeError carries the line and the document path of a decode failure. +type decodeError struct { + line int + path string + msg string +} + +func (e *decodeError) Error() string { + if e.line > 0 { + return fmt.Sprintf("line %d: %s: %s", e.line, e.path, e.msg) + } + return fmt.Sprintf("%s: %s", e.path, e.msg) +} + +func errAt(n *yaml.Node, path, format string, args ...any) error { + return &decodeError{line: n.Line, path: path, msg: fmt.Sprintf(format, args...)} +} + +func isNull(n *yaml.Node) bool { + return n.Kind == yaml.ScalarNode && n.Tag == "!!null" +} + +func joinPath(path, name string) string { + if path == "" { + return name + } + return path + "." + name +} + +func (c *yamlCodec) decodeMessage(n *yaml.Node, m protoreflect.Message, path string) error { + if isNull(n) { + return nil + } + switch m.Descriptor().FullName() { + case durationFullName: + return decodeDuration(n, m, path) + case timestampFullName: + return decodeTimestamp(n, m, path) + case labelSelectorFullName: + return decodeSelector(n, m, path) + } + if n.Kind != yaml.MappingNode { + return errAt(n, path, "expected a mapping of fields") + } + + fields := m.Descriptor().Fields() + seen := make(map[protoreflect.Name]struct{}, len(n.Content)/2) + for i := 0; i+1 < len(n.Content); i += 2 { + key, value := n.Content[i], n.Content[i+1] + fieldPath := joinPath(path, key.Value) + fd := fields.ByName(protoreflect.Name(key.Value)) + if fd == nil { + fd = fields.ByJSONName(key.Value) + } + if fd == nil { + return errAt(key, fieldPath, "unknown field. Known fields: %s", strings.Join(c.knownFields(m.Descriptor()), ", ")) + } + if reason, skipped := c.skip[fd.FullName()]; skipped && reason != "" { + return errAt(key, fieldPath, "%s", reason) + } + if _, dup := seen[fd.Name()]; dup { + return errAt(key, fieldPath, "the field is set twice") + } + seen[fd.Name()] = struct{}{} + if isNull(value) { + continue + } + if err := c.decodeField(value, m, fd, fieldPath); err != nil { + return err + } + } + return nil +} + +func (c *yamlCodec) knownFields(md protoreflect.MessageDescriptor) []string { + names := make([]string, 0, md.Fields().Len()) + for i := 0; i < md.Fields().Len(); i++ { + fd := md.Fields().Get(i) + if _, skipped := c.skip[fd.FullName()]; skipped { + continue + } + names = append(names, string(fd.Name())) + } + return names +} + +func (c *yamlCodec) decodeField(n *yaml.Node, m protoreflect.Message, fd protoreflect.FieldDescriptor, path string) error { + switch { + case fd.IsList(): + if n.Kind != yaml.SequenceNode { + return errAt(n, path, "expected a list") + } + list := m.Mutable(fd).List() + for i, item := range n.Content { + v, err := c.decodeSingular(item, fd, list.NewElement, fmt.Sprintf("%s[%d]", path, i)) + if err != nil { + return err + } + list.Append(v) + } + return nil + case fd.IsMap(): + if n.Kind != yaml.MappingNode { + return errAt(n, path, "expected a mapping") + } + if fd.MapKey().Kind() != protoreflect.StringKind { + return errAt(n, path, "this map field is not supported in the YAML form") + } + entries := m.Mutable(fd).Map() + for i := 0; i+1 < len(n.Content); i += 2 { + key, value := n.Content[i], n.Content[i+1] + v, err := c.decodeSingular(value, fd.MapValue(), entries.NewValue, joinPath(path, key.Value)) + if err != nil { + return err + } + entries.Set(protoreflect.ValueOfString(key.Value).MapKey(), v) + } + return nil + default: + v, err := c.decodeSingular(n, fd, func() protoreflect.Value { return m.NewField(fd) }, path) + if err != nil { + return err + } + m.Set(fd, v) + return nil + } +} + +func (c *yamlCodec) decodeSingular( + n *yaml.Node, + fd protoreflect.FieldDescriptor, + newMessage func() protoreflect.Value, + path string, +) (protoreflect.Value, error) { + if fd.Kind() == protoreflect.MessageKind || fd.Kind() == protoreflect.GroupKind { + v := newMessage() + if err := c.decodeMessage(n, v.Message(), path); err != nil { + return protoreflect.Value{}, err + } + return v, nil + } + if n.Kind != yaml.ScalarNode { + return protoreflect.Value{}, errAt(n, path, "expected a single value") + } + return decodeScalar(n, fd, path) +} + +func decodeScalar(n *yaml.Node, fd protoreflect.FieldDescriptor, path string) (protoreflect.Value, error) { + text := n.Value + switch fd.Kind() { + case protoreflect.StringKind: + return protoreflect.ValueOfString(text), nil + case protoreflect.BoolKind: + b, err := strconv.ParseBool(text) + if err != nil { + return protoreflect.Value{}, errAt(n, path, "expected true or false, not %q", text) + } + return protoreflect.ValueOfBool(b), nil + case protoreflect.EnumKind: + number, ok := parseEnumToken(fd.Enum(), text) + if !ok { + return protoreflect.Value{}, errAt(n, path, "unknown value %q. Use one of: %s", + text, strings.Join(enumTokens(fd.Enum()), ", ")) + } + return protoreflect.ValueOfEnum(number), nil + case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind: + i, err := strconv.ParseInt(text, 10, 32) + if err != nil { + return protoreflect.Value{}, errAt(n, path, "expected a whole number, not %q", text) + } + return protoreflect.ValueOfInt32(int32(i)), nil + case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: + i, err := strconv.ParseInt(text, 10, 64) + if err != nil { + return protoreflect.Value{}, errAt(n, path, "expected a whole number, not %q", text) + } + return protoreflect.ValueOfInt64(i), nil + case protoreflect.Uint32Kind, protoreflect.Fixed32Kind: + u, err := strconv.ParseUint(text, 10, 32) + if err != nil { + return protoreflect.Value{}, errAt(n, path, "expected a positive whole number, not %q", text) + } + return protoreflect.ValueOfUint32(uint32(u)), nil + case protoreflect.Uint64Kind, protoreflect.Fixed64Kind: + u, err := strconv.ParseUint(text, 10, 64) + if err != nil { + return protoreflect.Value{}, errAt(n, path, "expected a positive whole number, not %q", text) + } + return protoreflect.ValueOfUint64(u), nil + case protoreflect.FloatKind: + f, err := strconv.ParseFloat(text, 32) + if err != nil { + return protoreflect.Value{}, errAt(n, path, "expected a number, not %q", text) + } + return protoreflect.ValueOfFloat32(float32(f)), nil + case protoreflect.DoubleKind: + f, err := strconv.ParseFloat(text, 64) + if err != nil { + return protoreflect.Value{}, errAt(n, path, "expected a number, not %q", text) + } + return protoreflect.ValueOfFloat64(f), nil + case protoreflect.BytesKind: + b, err := base64.StdEncoding.DecodeString(text) + if err != nil { + return protoreflect.Value{}, errAt(n, path, "expected base64 data") + } + return protoreflect.ValueOfBytes(b), nil + default: + return protoreflect.Value{}, errAt(n, path, "this field kind is not supported in the YAML form") + } +} + +func decodeDuration(n *yaml.Node, m protoreflect.Message, path string) error { + if n.Kind != yaml.ScalarNode { + return errAt(n, path, "expected a duration, as in 168h or 7d") + } + d, err := duration.Parse(n.Value) + if err != nil { + return errAt(n, path, "%v", err) + } + pb := durationpb.New(d) + fields := m.Descriptor().Fields() + m.Set(fields.ByName("seconds"), protoreflect.ValueOfInt64(pb.GetSeconds())) + m.Set(fields.ByName("nanos"), protoreflect.ValueOfInt32(pb.GetNanos())) + return nil +} + +func decodeTimestamp(n *yaml.Node, m protoreflect.Message, path string) error { + if n.Kind != yaml.ScalarNode { + return errAt(n, path, "expected a time, as in 2026-12-31T00:00:00Z") + } + t, err := ParseTime(n.Value) + if err != nil { + return errAt(n, path, "%v", err) + } + pb := timestamppb.New(t) + fields := m.Descriptor().Fields() + m.Set(fields.ByName("seconds"), protoreflect.ValueOfInt64(pb.GetSeconds())) + m.Set(fields.ByName("nanos"), protoreflect.ValueOfInt32(pb.GetNanos())) + return nil +} + +// ParseTime reads an RFC 3339 time or a date, as in "2027-01-26". A date is +// midnight UTC. +func ParseTime(s string) (time.Time, error) { + text := strings.TrimSpace(s) + if t, err := time.Parse(time.RFC3339, text); err == nil { + return t, nil + } + if t, err := time.Parse(time.DateOnly, text); err == nil { + return t, nil + } + return time.Time{}, fmt.Errorf("invalid time %q: use RFC 3339, as in 2027-01-26T00:00:00Z, or a date, as in 2027-01-26", s) +} + +func decodeSelector(n *yaml.Node, m protoreflect.Message, path string) error { + if n.Kind != yaml.MappingNode { + return errAt(n, path, "expected a mapping with matchLabels or matchExpressions") + } + fields := m.Descriptor().Fields() + for i := 0; i+1 < len(n.Content); i += 2 { + key, value := n.Content[i], n.Content[i+1] + fieldPath := joinPath(path, key.Value) + switch key.Value { + case "matchLabels", "match_labels": + if isNull(value) { + continue + } + if value.Kind != yaml.MappingNode { + return errAt(value, fieldPath, "expected a mapping of label keys and values") + } + labels := m.Mutable(fields.ByName("match_labels")).Map() + for j := 0; j+1 < len(value.Content); j += 2 { + k, v := value.Content[j], value.Content[j+1] + if v.Kind != yaml.ScalarNode { + return errAt(v, joinPath(fieldPath, k.Value), "expected a label value") + } + labels.Set(protoreflect.ValueOfString(k.Value).MapKey(), protoreflect.ValueOfString(v.Value)) + } + case "matchExpressions", "match_expressions": + if isNull(value) { + continue + } + if err := decodeSelectorExpressions(value, m, fieldPath); err != nil { + return err + } + default: + return errAt(key, fieldPath, "unknown field. Known fields: matchLabels, matchExpressions") + } + } + return nil +} + +func decodeSelectorExpressions(n *yaml.Node, m protoreflect.Message, path string) error { + if n.Kind != yaml.SequenceNode { + return errAt(n, path, "expected a list of expressions") + } + list := m.Mutable(m.Descriptor().Fields().ByName("match_expressions")).List() + for i, item := range n.Content { + itemPath := fmt.Sprintf("%s[%d]", path, i) + if item.Kind != yaml.MappingNode { + return errAt(item, itemPath, "expected a mapping with key, operator and values") + } + expr := list.NewElement() + efs := expr.Message().Descriptor().Fields() + for j := 0; j+1 < len(item.Content); j += 2 { + k, v := item.Content[j], item.Content[j+1] + fieldPath := joinPath(itemPath, k.Value) + switch k.Value { + case "key": + expr.Message().Set(efs.ByName("key"), protoreflect.ValueOfString(v.Value)) + case "operator": + op, ok := parseSelectorOperator(v.Value) + if !ok { + return errAt(v, fieldPath, "unknown operator %q. Use one of: In, NotIn, Exists, DoesNotExist", v.Value) + } + expr.Message().Set(efs.ByName("operator"), protoreflect.ValueOfEnum(op)) + case "values": + if v.Kind != yaml.SequenceNode { + return errAt(v, fieldPath, "expected a list of values") + } + values := expr.Message().Mutable(efs.ByName("values")).List() + for _, value := range v.Content { + values.Append(protoreflect.ValueOfString(value.Value)) + } + default: + return errAt(k, fieldPath, "unknown field. Known fields: key, operator, values") + } + } + list.Append(expr) + } + return nil +} + +func parseSelectorOperator(text string) (protoreflect.EnumNumber, bool) { + for number, name := range selectorOperators { + if strings.EqualFold(text, name) { + return number, true + } + } + return 0, false +} diff --git a/internal/cloudpolicy/render.go b/internal/cloudpolicy/render.go new file mode 100644 index 0000000..68b2428 --- /dev/null +++ b/internal/cloudpolicy/render.go @@ -0,0 +1,34 @@ +package cloudpolicy + +import ( + "strings" +) + +// Separator joins the parts of a summary line, as in "revision 47", +// separator, "published 6m ago by alice". It is a middle dot with spaces. +const Separator = " · " + +// KeyValues writes label and value rows with the values in one column. A +// value with line breaks keeps the column on each line. +func KeyValues(rows [][2]string) string { + width := 0 + for _, r := range rows { + width = max(width, len(r[0])) + } + var b strings.Builder + for i, r := range rows { + if i > 0 { + b.WriteByte('\n') + } + lines := strings.Split(r[1], "\n") + b.WriteString(r[0]) + b.WriteString(strings.Repeat(" ", width-len(r[0])+2)) + b.WriteString(lines[0]) + for _, line := range lines[1:] { + b.WriteByte('\n') + b.WriteString(strings.Repeat(" ", width+2)) + b.WriteString(line) + } + } + return b.String() +} diff --git a/internal/cloudpolicy/subject.go b/internal/cloudpolicy/subject.go new file mode 100644 index 0000000..3df8c6c --- /dev/null +++ b/internal/cloudpolicy/subject.go @@ -0,0 +1,415 @@ +package cloudpolicy + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "time" + + corev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/core/v1" + recordv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/record/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" + "github.com/safedep/dry/tui/humanize" + "github.com/safedep/dry/tui/table" + "google.golang.org/grpc" + "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/safedep/cli/internal/tui" +) + +// SubjectPolicyClient reads the policy of one subject. +type SubjectPolicyClient interface { + GetSubjectPolicy( + context.Context, + *policyv1.GetSubjectPolicyRequest, + ...grpc.CallOption, + ) (*policyv1.GetSubjectPolicyResponse, error) +} + +// NewSubject builds a subject of the policy. +func NewSubject(kind specv1.SubjectKind, id string) *specv1.Subject { + s := &specv1.Subject{} + s.SetKind(kind) + s.SetId(id) + return s +} + +// SubjectPolicy is the intended policy of one subject, the source of each +// value, and the policy that each tool or check applied. +type SubjectPolicy struct { + Kind string + Name string + ID string + Revision uint64 + DefaultRevision uint64 + Matched []MatchedOverride + Labels []string + TrustRules int + BlockRules int + Fields []SubjectField + Applied []AppliedPolicy + Filtered bool +} + +// MatchedOverride is a policy override that matches the subject. +type MatchedOverride struct { + ID string `json:"override_id"` + Name string `json:"name"` + Priority uint32 `json:"priority"` +} + +// SubjectField is one field of the intended policy. +type SubjectField struct { + Path string + Value string + Human string + Source string + Exceptions []string +} + +// AppliedPolicy is the last policy that one tool or check reported. +type AppliedPolicy struct { + Implementer string + Version string + Revision uint64 + DefaultRevision uint64 + State string + RejectedReason string + FetchedAt *time.Time + AppliedAt *time.Time + ReportedAt *time.Time + Exceptions []FieldException +} + +// FieldException is one field that a tool did not apply as the policy says. +type FieldException struct { + Path string `json:"path"` + Reason string `json:"reason"` + Detail string `json:"detail,omitempty"` +} + +const ( + layerPrefix = "LAYER_" + applyStatePrefix = "APPLY_STATE_" + exceptionReasonPrefix = "FIELD_EXCEPTION_REASON_" +) + +// GetSubjectPolicy reads the policy of a subject. name labels the subject in +// the output. fields limits the output to these contract paths and the paths +// below them. +func GetSubjectPolicy( + ctx context.Context, + client SubjectPolicyClient, + subject *specv1.Subject, + name string, + fields []string, +) (*SubjectPolicy, error) { + if err := ValidateFieldPaths(fields); err != nil { + return nil, err + } + req := &policyv1.GetSubjectPolicyRequest{} + req.SetSubject(subject) + res, err := client.GetSubjectPolicy(ctx, req) + if err != nil { + return nil, fmt.Errorf("get subject policy: %w", err) + } + return translateSubjectPolicy(res, subject, name, fields), nil +} + +func translateSubjectPolicy( + res *policyv1.GetSubjectPolicyResponse, + subject *specv1.Subject, + name string, + fields []string, +) *SubjectPolicy { + intended := res.GetIntended() + header := intended.GetHeader() + out := &SubjectPolicy{ + Kind: subjectKindName(subject.GetKind()), + Name: name, + ID: subject.GetId(), + Revision: header.GetRevision(), + DefaultRevision: header.GetDefaultPolicyRevision(), + Labels: FormatLabels(res.GetLabels()), + Filtered: len(fields) > 0, + } + + overrides := make(map[string]MatchedOverride, len(header.GetMatchedOverrides())) + for _, o := range header.GetMatchedOverrides() { + m := MatchedOverride{ID: o.GetOverrideId(), Name: o.GetName(), Priority: o.GetPriority()} + out.Matched = append(out.Matched, m) + overrides[m.ID] = m + } + + for _, rule := range intended.GetSpec().GetCore().GetPackageRules() { + switch rule.GetEffect() { + case corev1.Effect_EFFECT_TRUST: + out.TrustRules++ + case corev1.Effect_EFFECT_BLOCK: + out.BlockRules++ + } + } + + sources := make(map[string][]string) + for _, s := range intended.GetFieldSources() { + sources[s.GetPath()] = appendUnique(sources[s.GetPath()], sourceLabel(s, overrides)) + } + + for _, a := range res.GetApplied() { + out.Applied = append(out.Applied, translateApplied(a)) + } + + for _, f := range Fields(intended.GetSpec()) { + if !MatchesFieldFilter([]string{f.Path}, fields) { + continue + } + field := SubjectField{Path: f.Path, Value: f.Value, Human: f.Human, Source: "-"} + if s := sources[f.Path]; len(s) > 0 { + field.Source = strings.Join(s, ", ") + } + for _, a := range out.Applied { + for _, e := range a.Exceptions { + if e.Path == f.Path { + field.Exceptions = append(field.Exceptions, a.Implementer+": "+exceptionText(e)) + } + } + } + out.Fields = append(out.Fields, field) + } + return out +} + +func translateApplied(a *policyv1.AppliedPolicy) AppliedPolicy { + report := a.GetReport() + out := AppliedPolicy{ + Implementer: a.GetImplementer(), + Version: a.GetImplementerVersion(), + Revision: report.GetRevision(), + DefaultRevision: report.GetDefaultPolicyRevision(), + State: tui.EnumToken(report.GetState().String(), applyStatePrefix), + RejectedReason: report.GetRejectedReason(), + FetchedAt: timePtr(report.GetFetchedAt()), + AppliedAt: timePtr(report.GetAppliedAt()), + ReportedAt: timePtr(a.GetReportedAt()), + } + for _, e := range report.GetExceptions() { + out.Exceptions = append(out.Exceptions, FieldException{ + Path: e.GetPath(), + Reason: tui.EnumToken(e.GetReason().String(), exceptionReasonPrefix), + Detail: e.GetDetail(), + }) + } + return out +} + +func exceptionText(e FieldException) string { + if e.Detail == "" { + return e.Reason + } + return e.Reason + " (" + e.Detail + ")" +} + +func sourceLabel(s *specv1.FieldSource, overrides map[string]MatchedOverride) string { + switch s.GetLayer() { + case recordv1.Layer_LAYER_DEFAULT_POLICY: + return "default policy" + case recordv1.Layer_LAYER_BASE: + return "base" + case recordv1.Layer_LAYER_OVERRIDE: + if o, ok := overrides[s.GetOverrideId()]; ok { + return fmt.Sprintf("override %q (%d)", o.Name, o.Priority) + } + return "override " + s.GetOverrideId() + default: + return tui.EnumToken(s.GetLayer().String(), layerPrefix) + } +} + +func subjectKindName(kind specv1.SubjectKind) string { + return tui.EnumToken(kind.String(), "SUBJECT_KIND_") +} + +func appendUnique(values []string, v string) []string { + for _, existing := range values { + if existing == v { + return values + } + } + return append(values, v) +} + +func timePtr(ts *timestamppb.Timestamp) *time.Time { + if ts == nil { + return nil + } + t := ts.AsTime().UTC() + return &t +} + +// PolicyLine summarises the intended policy in one line: the revision and +// the matched policy overrides, or "no override matches" and "base only". +func (p *SubjectPolicy) PolicyLine() string { + parts := []string{fmt.Sprintf("revision %d", p.Revision)} + if len(p.Matched) == 0 { + parts = append(parts, "no override matches", "base only") + } else { + names := make([]string, 0, len(p.Matched)) + for _, o := range p.Matched { + names = append(names, fmt.Sprintf("%s (%d)", o.Name, o.Priority)) + } + parts = append(parts, "overrides "+strings.Join(names, ", ")) + } + return strings.Join(parts, Separator) +} + +type subjectFieldJSON struct { + Path string `json:"path"` + Value string `json:"value"` + Source string `json:"source"` + Exceptions []string `json:"exceptions,omitempty"` +} + +type appliedPolicyJSON struct { + Implementer string `json:"implementer"` + Version string `json:"implementer_version,omitempty"` + Revision uint64 `json:"revision"` + DefaultRevision uint64 `json:"default_policy_revision"` + State string `json:"state"` + RejectedReason string `json:"rejected_reason,omitempty"` + FetchedAt string `json:"fetched_at,omitempty"` + AppliedAt string `json:"applied_at,omitempty"` + ReportedAt string `json:"reported_at,omitempty"` + Exceptions []FieldException `json:"exceptions,omitempty"` +} + +type subjectPolicyJSON struct { + Kind string `json:"kind"` + Name string `json:"name,omitempty"` + ID string `json:"id"` + Revision uint64 `json:"revision"` + DefaultRevision uint64 `json:"default_policy_revision"` + Matched []MatchedOverride `json:"matched_overrides"` + Labels []string `json:"labels"` + TrustRules int `json:"trust_rules"` + BlockRules int `json:"block_rules"` + Fields []subjectFieldJSON `json:"fields"` + Applied []appliedPolicyJSON `json:"applied"` +} + +func (p *SubjectPolicy) RenderJSON() ([]byte, error) { + out := subjectPolicyJSON{ + Kind: p.Kind, Name: p.Name, ID: p.ID, + Revision: p.Revision, DefaultRevision: p.DefaultRevision, + Matched: p.Matched, Labels: p.Labels, + TrustRules: p.TrustRules, BlockRules: p.BlockRules, + Fields: make([]subjectFieldJSON, 0, len(p.Fields)), + Applied: make([]appliedPolicyJSON, 0, len(p.Applied)), + } + if out.Matched == nil { + out.Matched = []MatchedOverride{} + } + if out.Labels == nil { + out.Labels = []string{} + } + for _, f := range p.Fields { + out.Fields = append(out.Fields, subjectFieldJSON{ + Path: f.Path, Value: f.Value, Source: f.Source, Exceptions: f.Exceptions, + }) + } + for _, a := range p.Applied { + out.Applied = append(out.Applied, appliedPolicyJSON{ + Implementer: a.Implementer, Version: a.Version, + Revision: a.Revision, DefaultRevision: a.DefaultRevision, + State: a.State, RejectedReason: a.RejectedReason, + FetchedAt: RFC3339(a.FetchedAt), AppliedAt: RFC3339(a.AppliedAt), ReportedAt: RFC3339(a.ReportedAt), + Exceptions: a.Exceptions, + }) + } + return json.MarshalIndent(out, "", " ") +} + +func (p *SubjectPolicy) RenderTable() string { + now := time.Now() + title := strings.ToUpper(p.Kind[:1]) + p.Kind[1:] + subject := p.Name + if subject == "" { + subject = p.ID + } else if p.ID != "" && p.ID != p.Name { + subject += " (" + p.ID + ")" + } + rows := [][2]string{ + {title, subject}, + {"Policy", p.PolicyLine()}, + {"Default policy", fmt.Sprintf("revision %d", p.DefaultRevision)}, + {"Package rules", fmt.Sprintf("%d (%d trust, %d block)", p.TrustRules+p.BlockRules, p.TrustRules, p.BlockRules)}, + } + if !p.Filtered { + rows = append(rows, [2]string{"Labels", emptyDash(strings.Join(p.Labels, " "))}) + } + + fieldRows := make([][]string, 0, len(p.Fields)) + for _, f := range p.Fields { + fieldRows = append(fieldRows, []string{f.Path, f.Human, f.Source, emptyDash(strings.Join(f.Exceptions, "; "))}) + } + empty := "The policy sets no fields for this " + p.Kind + "." + if p.Filtered { + empty = "The policy sets none of the requested fields for this " + p.Kind + "." + } + fieldTable := table.New(). + Headers("FIELD", "VALUE", "SOURCE", "EXCEPTIONS"). + Rows(fieldRows...). + EmptyMessage(empty). + Render() + + appliedRows := make([][]string, 0, len(p.Applied)) + for _, a := range p.Applied { + appliedRows = append(appliedRows, []string{ + a.Implementer, emptyDash(a.Version), fmt.Sprintf("%d", a.Revision), a.State, + humanTime(a.FetchedAt, now), humanTime(a.ReportedAt, now), + }) + } + appliedTable := table.New(). + Title("Applied policy, as each tool reported it"). + Headers("TOOL", "VERSION", "REVISION", "STATE", "FETCHED", "REPORTED"). + Rows(appliedRows...). + EmptyMessage("No tool or check reported the policy that it applies for this " + p.Kind + " yet."). + Render() + + return KeyValues(rows) + "\n\n" + fieldTable + "\n\n" + appliedTable +} + +func (p *SubjectPolicy) RenderPlain() string { + var b strings.Builder + b.WriteString("path\tvalue\tsource\texceptions") + for _, f := range p.Fields { + fmt.Fprintf(&b, "\n%s\t%s\t%s\t%s", f.Path, f.Value, f.Source, strings.Join(f.Exceptions, "; ")) + } + for _, a := range p.Applied { + fmt.Fprintf(&b, "\napplied:%s\t%d\t%s\t%s", a.Implementer, a.Revision, a.State, RFC3339(a.ReportedAt)) + } + return b.String() +} + +func humanTime(t *time.Time, now time.Time) string { + if t == nil { + return "-" + } + return humanize.Time(*t, now) +} + +// RFC3339 writes an optional time in UTC, or "" when it is absent. +func RFC3339(t *time.Time) string { + if t == nil { + return "" + } + return t.UTC().Format(time.RFC3339) +} + +func emptyDash(s string) string { + if s == "" { + return "-" + } + return s +} diff --git a/internal/cloudpolicy/subject_test.go b/internal/cloudpolicy/subject_test.go new file mode 100644 index 0000000..81ee5d3 --- /dev/null +++ b/internal/cloudpolicy/subject_test.go @@ -0,0 +1,163 @@ +package cloudpolicy + +import ( + "context" + "encoding/json" + "errors" + "testing" + "time" + + messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" + corev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/core/v1" + recordv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/record/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" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/protobuf/types/known/timestamppb" +) + +// fakeSubjectPolicyClient is a hand fake for the one RPC of +// SubjectPolicyClient. +type fakeSubjectPolicyClient struct { + req *policyv1.GetSubjectPolicyRequest + res *policyv1.GetSubjectPolicyResponse + err error +} + +func (f *fakeSubjectPolicyClient) GetSubjectPolicy( + _ context.Context, + req *policyv1.GetSubjectPolicyRequest, + _ ...grpc.CallOption, +) (*policyv1.GetSubjectPolicyResponse, error) { + f.req = req + return f.res, f.err +} + +func fieldSource(path string, layer recordv1.Layer, overrideID string) *specv1.FieldSource { + s := &specv1.FieldSource{} + s.SetPath(path) + s.SetLayer(layer) + s.SetOverrideId(overrideID) + return s +} + +func subjectPolicyResponse() *policyv1.GetSubjectPolicyResponse { + spec := specWith(scangatev1.Severity_SEVERITY_MEDIUM, 168*time.Hour) + block := &corev1.PackageRule{} + block.SetEffect(corev1.Effect_EFFECT_BLOCK) + trust := &corev1.PackageRule{} + trust.SetEffect(corev1.Effect_EFFECT_TRUST) + core := &corev1.Core{} + core.SetPackageRules([]*corev1.PackageRule{block, block, trust}) + spec.SetCore(core) + + matched := &specv1.MatchedOverride{} + matched.SetOverrideId("ov_1") + matched.SetName("payments") + matched.SetPriority(200) + header := &specv1.ResolvedPolicyHeader{} + header.SetRevision(47) + header.SetDefaultPolicyRevision(12) + header.SetMatchedOverrides([]*specv1.MatchedOverride{matched}) + + intended := &specv1.ResolvedPolicy{} + intended.SetHeader(header) + intended.SetSpec(spec) + intended.SetFieldSources([]*specv1.FieldSource{ + fieldSource("scan_gate.fail_on", recordv1.Layer_LAYER_OVERRIDE, "ov_1"), + fieldSource("package_admission.cooldown.min_age", recordv1.Layer_LAYER_BASE, ""), + }) + + exception := &recordv1.FieldException{} + exception.SetPath("package_admission.cooldown.min_age") + exception.SetReason(recordv1.FieldExceptionReason_FIELD_EXCEPTION_REASON_LOCKED) + exception.SetDetail("floor in /etc/safedep/cloud.yml") + report := &recordv1.ApplyReport{} + report.SetRevision(46) + report.SetState(recordv1.ApplyState_APPLY_STATE_APPLIED) + report.SetExceptions([]*recordv1.FieldException{exception}) + applied := &policyv1.AppliedPolicy{} + applied.SetImplementer("pmg") + applied.SetImplementerVersion("2.3.1") + applied.SetReport(report) + applied.SetReportedAt(timestamppb.New(time.Date(2026, 10, 30, 0, 0, 0, 0, time.UTC))) + + label := &messagescontroltowerv1.Label{} + label.SetKey("custom/criticality") + label.SetValue("high") + + res := &policyv1.GetSubjectPolicyResponse{} + res.SetIntended(intended) + res.SetApplied([]*policyv1.AppliedPolicy{applied}) + res.SetLabels([]*messagescontroltowerv1.Label{label}) + return res +} + +func TestGetSubjectPolicy(t *testing.T) { + client := &fakeSubjectPolicyClient{res: subjectPolicyResponse()} + subject := NewSubject(specv1.SubjectKind_SUBJECT_KIND_PROJECT, "p_1") + + got, err := GetSubjectPolicy(context.Background(), client, subject, "acme/payments-api", nil) + require.NoError(t, err) + + assert.Equal(t, specv1.SubjectKind_SUBJECT_KIND_PROJECT, client.req.GetSubject().GetKind()) + assert.Equal(t, "p_1", client.req.GetSubject().GetId()) + assert.Equal(t, "project", got.Kind) + assert.Equal(t, uint64(47), got.Revision) + assert.Equal(t, 1, got.TrustRules) + assert.Equal(t, 2, got.BlockRules) + assert.Equal(t, []string{"custom/criticality=high"}, got.Labels) + assert.Equal(t, "revision 47 · overrides payments (200)", got.PolicyLine()) + require.Len(t, got.Fields, 2) + assert.Equal(t, SubjectField{ + Path: "package_admission.cooldown.min_age", Value: "168h", Human: "7d", Source: "base", + Exceptions: []string{"pmg: locked (floor in /etc/safedep/cloud.yml)"}, + }, got.Fields[0]) + assert.Equal(t, `override "payments" (200)`, got.Fields[1].Source) + require.Len(t, got.Applied, 1) + assert.Equal(t, "applied", got.Applied[0].State) + + table := got.RenderTable() + assert.Contains(t, table, "scan_gate.fail_on") + assert.Contains(t, table, "pmg") + + var decoded map[string]any + b, err := got.RenderJSON() + require.NoError(t, err) + require.NoError(t, json.Unmarshal(b, &decoded)) + assert.Equal(t, "p_1", decoded["id"]) + assert.Contains(t, got.RenderPlain(), "scan_gate.fail_on\tmedium\toverride \"payments\" (200)") +} + +func TestGetSubjectPolicy_FieldFilter(t *testing.T) { + client := &fakeSubjectPolicyClient{res: subjectPolicyResponse()} + subject := NewSubject(specv1.SubjectKind_SUBJECT_KIND_ENDPOINT, "ep_1") + + got, err := GetSubjectPolicy(context.Background(), client, subject, "", []string{"scan_gate"}) + require.NoError(t, err) + require.Len(t, got.Fields, 1) + assert.Equal(t, "scan_gate.fail_on", got.Fields[0].Path) + assert.True(t, got.Filtered) +} + +func TestGetSubjectPolicy_NoOverrideMatches(t *testing.T) { + res := subjectPolicyResponse() + res.GetIntended().GetHeader().SetMatchedOverrides(nil) + got, err := GetSubjectPolicy(context.Background(), &fakeSubjectPolicyClient{res: res}, + NewSubject(specv1.SubjectKind_SUBJECT_KIND_PROJECT, "p_1"), "", nil) + require.NoError(t, err) + assert.Equal(t, "revision 47 · no override matches · base only", got.PolicyLine()) + assert.Equal(t, "override ov_1", got.Fields[1].Source, "an unknown override shows its id") +} + +func TestGetSubjectPolicy_Errors(t *testing.T) { + subject := NewSubject(specv1.SubjectKind_SUBJECT_KIND_PROJECT, "p_1") + _, err := GetSubjectPolicy(context.Background(), &fakeSubjectPolicyClient{}, subject, "", []string{"nope"}) + assert.ErrorContains(t, err, "unknown policy field") + + _, err = GetSubjectPolicy(context.Background(), &fakeSubjectPolicyClient{err: errors.New("boom")}, subject, "", nil) + assert.ErrorContains(t, err, "get subject policy: boom") +} diff --git a/internal/cmd/policy/change_create.go b/internal/cmd/policy/change_create.go new file mode 100644 index 0000000..c88db9e --- /dev/null +++ b/internal/cmd/policy/change_create.go @@ -0,0 +1,141 @@ +package policy + +import ( + "context" + "errors" + "fmt" + "slices" + "strings" + + policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/safedep/dry/tui" + "github.com/spf13/cobra" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" +) + +const ( + packageRulesKeepHead = "head" + packageRulesFromRevision = "revision" +) + +type changeCreateInput struct { + FromRevision uint64 + Capabilities []string + PackageRules string + Title string +} + +func changeCreateCmd(a *app.App) *cobra.Command { + var in changeCreateInput + cmd := &cobra.Command{ + Use: "create --from-revision REVISION", + Short: "Create a policy change that restores an old revision", + Long: "Create a policy change that restores capabilities from an old policy revision, for a " + + "rollback. For each restored capability, the policy base and every policy override take " + + "their values from that revision. Package rules stay at head unless you pass " + + "--package-rules revision. The change is a draft: review it, then publish it. Revision " + + "numbers only go up, so the publish makes a new revision.", + Args: func(cmd *cobra.Command, args []string) error { + if err := cobra.NoArgs(cmd, args); err != nil { + return err + } + return validateChangeCreate(in) + }, + RunE: func(cmd *cobra.Command, _ []string) error { + client, err := a.ControlPlane() + if err != nil { + return err + } + policyClient := cloudpolicy.NewPolicyClient(client.Connection()) + change, err := runChangeCreate(cmd.Context(), policyClient, in) + if err != nil { + return err + } + tui.Success("change %s %s", change.GetChangeId(), restoreSummary(change.GetRestore())) + reportRestoreDirection(cmd.Context(), policyClient, change.GetChangeId()) + tui.Info(" Review it: safedep policy change show %s", change.GetChangeId()) + tui.Info(" Publish it: safedep policy change publish %s", change.GetChangeId()) + return nil + }, + } + f := cmd.Flags() + f.Uint64Var(&in.FromRevision, "from-revision", 0, "the policy revision to restore from (required)") + f.StringSliceVar(&in.Capabilities, "capability", nil, + "a capability to restore ("+strings.Join(cloudpolicy.Capabilities(), ", ")+"); repeatable; every capability when absent") + f.StringVar(&in.PackageRules, "package-rules", packageRulesKeepHead, + "the package rules after the restore: head keeps them, revision restores the set of --from-revision") + f.StringVarP(&in.Title, "message", "m", "", "the title of the policy change") + return cmd +} + +func validateChangeCreate(in changeCreateInput) error { + if in.FromRevision == 0 { + return invalidInputError(errors.New("--from-revision is required"), + "Find the revision in: safedep policy revision list") + } + known := cloudpolicy.Capabilities() + for _, c := range in.Capabilities { + if !slices.Contains(known, c) { + return invalidInputError( + fmt.Errorf("unknown --capability %q: known capabilities are %s", c, strings.Join(known, ", ")), + "Retry with one of: "+strings.Join(known, ", ")) + } + } + switch in.PackageRules { + case packageRulesKeepHead, packageRulesFromRevision: + return nil + default: + return invalidInputError( + fmt.Errorf("unknown --package-rules %q: use head or revision", in.PackageRules), + "Retry with --package-rules head or --package-rules revision") + } +} + +func runChangeCreate( + ctx context.Context, + client policyv1grpc.PolicyServiceClient, + in changeCreateInput, +) (*policyv1.PolicyChange, error) { + if err := validateChangeCreate(in); err != nil { + return nil, err + } + restore := &policyv1.RestoreSource{} + restore.SetFromRevision(in.FromRevision) + if len(in.Capabilities) > 0 { + restore.SetCapabilities(in.Capabilities) + } + rules := policyv1.PackageRuleRestore_PACKAGE_RULE_RESTORE_KEEP_HEAD + if in.PackageRules == packageRulesFromRevision { + rules = policyv1.PackageRuleRestore_PACKAGE_RULE_RESTORE_FROM_REVISION + } + restore.SetPackageRules(rules) + + req := &policyv1.CreatePolicyChangeRequest{} + req.SetTitle(in.Title) + req.SetRestore(restore) + res, err := client.CreatePolicyChange(ctx, req) + if err != nil { + return nil, mapChangeError("create", fmt.Sprintf("from revision %d", in.FromRevision), err) + } + return res.GetChange(), nil +} + +// reportRestoreDirection names each field that the restore loosens, so the +// admin sees it before the publish. The change exists already, so a failed +// preview is a warning, not an error. +func reportRestoreDirection(ctx context.Context, client policyv1grpc.PolicyServiceClient, id string) { + preview, err := previewChange(ctx, client, id) + if err != nil { + tui.Warning("Could not preview change %s: %v", id, err) + return + } + for _, item := range preview.Items { + if item.Direction != "LOOSENS" { + continue + } + tui.Warning("It loosens %s (%s -> %s) in %s", item.What, item.oldHuman, item.newHuman, item.Where) + } +} diff --git a/internal/cmd/policy/change_list.go b/internal/cmd/policy/change_list.go new file mode 100644 index 0000000..7103ecf --- /dev/null +++ b/internal/cmd/policy/change_list.go @@ -0,0 +1,213 @@ +package policy + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "time" + + policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/safedep/dry/tui/table" + "github.com/spf13/cobra" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" + "github.com/safedep/cli/internal/paging" + "github.com/safedep/cli/internal/tui" +) + +type changeListInput struct { + State string + PageSize uint32 + PageToken string +} + +type changeView struct { + ID string `json:"change_id"` + Title string `json:"title"` + State string `json:"state"` + BaseRevision uint64 `json:"base_revision"` + PublishedRevision uint64 `json:"published_revision,omitempty"` + Author string `json:"author"` + EditsSettings bool `json:"edits_settings"` + RuleOperations int `json:"package_rule_operations"` + RestoreFrom uint64 `json:"restore_from_revision,omitempty"` + Created string `json:"created_at,omitempty"` + Updated string `json:"updated_at,omitempty"` + updatedAt *time.Time +} + +func newChangeView(c *policyv1.PolicyChange) changeView { + updated := timeOf(c.GetUpdatedAt()) + v := changeView{ + ID: c.GetChangeId(), + Title: c.GetTitle(), + State: tui.EnumToken(c.GetState().String(), changeStatePrefix), + BaseRevision: c.GetBaseRevision(), + PublishedRevision: c.GetPublishedRevision(), + Author: actorName(c.GetAuthor()), + EditsSettings: c.HasSettings(), + RuleOperations: len(c.GetPackageRuleOperations()), + Created: cloudpolicy.RFC3339(timeOf(c.GetCreatedAt())), + Updated: cloudpolicy.RFC3339(updated), + updatedAt: updated, + } + if c.HasRestore() { + v.RestoreFrom = c.GetRestore().GetFromRevision() + } + return v +} + +func (v changeView) titleOrUntitled() string { + if v.Title == "" { + return "(untitled)" + } + return v.Title +} + +// contents says what the change edits, as in "settings, 2 rule operations". +func (v changeView) contents() string { + var parts []string + if v.RestoreFrom > 0 { + parts = append(parts, fmt.Sprintf("restore from revision %d", v.RestoreFrom)) + } + if v.EditsSettings { + parts = append(parts, "settings") + } + if v.RuleOperations > 0 { + parts = append(parts, fmt.Sprintf("%d rule %s", v.RuleOperations, plural(v.RuleOperations, "operation", "operations"))) + } + if len(parts) == 0 { + return "nothing" + } + return strings.Join(parts, ", ") +} + +type changeListResult struct { + Changes []changeView `json:"changes"` + NextPageToken string `json:"next_page_token,omitempty"` +} + +func changeListCmd(a *app.App) *cobra.Command { + var in changeListInput + cmd := &cobra.Command{ + Use: "list", + Short: "List policy changes, newest first", + Long: "List the policy changes of the tenant, newest first. Filter by state. One page is returned " + + "per invocation, so follow --page-token to read the next page.", + Args: func(cmd *cobra.Command, args []string) error { + if err := cobra.NoArgs(cmd, args); err != nil { + return err + } + _, err := parseChangeState(in.State) + return err + }, + RunE: func(cmd *cobra.Command, _ []string) error { + client, err := a.ControlPlane() + if err != nil { + return err + } + res, err := runChangeList(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), in) + if err != nil { + return err + } + return a.Output.Print(res) + }, + } + f := cmd.Flags() + f.StringVar(&in.State, "state", "", "filter: change state ("+strings.Join(changeStateTokens(), ", ")+")") + f.Uint32Var(&in.PageSize, "limit", 0, "page size; server default when 0") + f.StringVar(&in.PageToken, "page-token", "", "continuation token from a prior response") + return cmd +} + +func changeStateTokens() []string { + return tui.EnumTokens(policyv1.PolicyChangeState_name, changeStatePrefix) +} + +func parseChangeState(token string) (policyv1.PolicyChangeState, error) { + if token == "" { + return policyv1.PolicyChangeState_POLICY_CHANGE_STATE_UNSPECIFIED, nil + } + n, ok := tui.ParseEnumToken(policyv1.PolicyChangeState_name, changeStatePrefix, token) + if !ok { + return 0, invalidInputError( + fmt.Errorf("unknown --state value %q: allowed values are %s", token, strings.Join(changeStateTokens(), ", ")), + "Retry with one of: "+strings.Join(changeStateTokens(), ", ")) + } + return policyv1.PolicyChangeState(n), nil +} + +func runChangeList( + ctx context.Context, + client policyv1grpc.PolicyServiceClient, + in changeListInput, +) (*changeListResult, error) { + state, err := parseChangeState(in.State) + if err != nil { + return nil, err + } + req := &policyv1.ListPolicyChangesRequest{} + req.SetPagination(paging.NewPaginationRequest(in.PageSize, in.PageToken)) + if state != policyv1.PolicyChangeState_POLICY_CHANGE_STATE_UNSPECIFIED { + filters := &policyv1.ListPolicyChangesRequest_Filters{} + filters.SetState(state) + req.SetFilters(filters) + } + res, err := client.ListPolicyChanges(ctx, req) + if err != nil { + return nil, fmt.Errorf("policy change list: %w", err) + } + out := &changeListResult{ + Changes: make([]changeView, 0, len(res.GetChanges())), + NextPageToken: res.GetPagination().GetNextPageToken(), + } + for _, c := range res.GetChanges() { + out.Changes = append(out.Changes, newChangeView(c)) + } + return out, nil +} + +func (r *changeListResult) RenderJSON() ([]byte, error) { + return json.MarshalIndent(r, "", " ") +} + +func (r *changeListResult) RenderTable() string { + now := time.Now() + rows := make([][]string, 0, len(r.Changes)) + for _, c := range r.Changes { + state := c.State + if c.PublishedRevision > 0 { + state = fmt.Sprintf("%s as rev %d", state, c.PublishedRevision) + } + rows = append(rows, []string{ + c.ID, c.titleOrUntitled(), state, fmt.Sprintf("%d", c.BaseRevision), + c.contents(), emptyDash(c.Author), humanTimeCell(c.updatedAt, now), + }) + } + t := table.New(). + Title("Policy changes"). + Headers("CHANGE", "TITLE", "STATE", "BASE REV", "EDITS", "AUTHOR", "UPDATED"). + Rows(rows...). + EmptyMessage("No policy changes. Create one with: safedep policy edit") + if len(rows) > 0 { + footer := fmt.Sprintf("%d %s", len(rows), plural(len(rows), "change", "changes")) + if r.NextPageToken != "" { + footer += ". More available: --page-token " + r.NextPageToken + } + t = t.Footer(footer) + } + return t.Render() +} + +func (r *changeListResult) RenderPlain() string { + var b strings.Builder + b.WriteString("change_id\ttitle\tstate\tbase_revision\tpublished_revision\tauthor\tupdated_at") + for _, c := range r.Changes { + fmt.Fprintf(&b, "\n%s\t%s\t%s\t%d\t%d\t%s\t%s", + c.ID, c.Title, c.State, c.BaseRevision, c.PublishedRevision, c.Author, c.Updated) + } + return b.String() +} diff --git a/internal/cmd/policy/change_ops.go b/internal/cmd/policy/change_ops.go new file mode 100644 index 0000000..5051879 --- /dev/null +++ b/internal/cmd/policy/change_ops.go @@ -0,0 +1,245 @@ +package policy + +import ( + "context" + "errors" + "fmt" + + policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/safedep/dry/tui" + "github.com/spf13/cobra" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" +) + +func changeEditCmd(a *app.App) *cobra.Command { + var in editInput + cmd := &cobra.Command{ + Use: "edit CHANGE", + Short: "Edit the policy settings of an open policy change", + Long: "Open the policy settings of an open policy change in $VISUAL or $EDITOR. Saving updates the " + + "change on the server. A change that does not edit the settings yet starts from the head " + + "settings. Use -m to change the title, and --override NAME to edit one policy override.", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + if err := requireTerminal(); err != nil { + return err + } + client, err := a.ControlPlane() + if err != nil { + return err + } + change, err := runChangeEdit(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), + openEditor, a.Tenant(), args[0], in) + if errors.Is(err, errNoChange) { + tui.Info("No change. Nothing is saved") + return nil + } + if err != nil { + return err + } + tui.Success("change %s updated", change.GetChangeId()) + tui.Info(" Review it: safedep policy change show %s", change.GetChangeId()) + return nil + }, + } + cmd.Flags().StringVarP(&in.Title, "message", "m", "", "a new title for the policy change") + cmd.Flags().StringVar(&in.Override, "override", "", "edit only the policy override with this name") + return cmd +} + +func runChangeEdit( + ctx context.Context, + client policyv1grpc.PolicyServiceClient, + open openEditorFunc, + tenant, id string, + in editInput, +) (*policyv1.PolicyChange, error) { + change, err := getChange(ctx, client, id) + if err != nil { + return nil, err + } + if err := requireOpen(change); err != nil { + return nil, err + } + head, err := getPolicy(ctx, client) + if err != nil { + return nil, err + } + + start := head.GetPolicy() + if change.HasSettings() { + start = change.GetSettings() + } + if change.HasRestore() { + tui.Warning("Change %s restores from revision %d. Saving replaces the settings that the restore made", + id, change.GetRestore().GetFromRevision()) + } + intro := []string{ + fmt.Sprintf("Change %s of %s%sbase revision %d%shead revision %d", + id, tenantName(tenant), sep, change.GetBaseRevision(), sep, head.GetHeadRevision()), + "Saving updates the draft change. Nothing applies until you publish it.", + } + + var updated *policyv1.PolicyChange + err = editSettings(ctx, open, start, editHeader(intro, head), in.Override, func(p *policyv1.Policy) error { + req := &policyv1.UpdatePolicyChangeRequest{} + req.SetChangeId(id) + req.SetEtag(change.GetEtag()) + req.SetSettings(p) + if in.Title != "" { + req.SetTitle(in.Title) + } + res, err := client.UpdatePolicyChange(ctx, req) + if err != nil { + return mapChangeError("update", id, err) + } + updated = res.GetChange() + return nil + }) + if err != nil { + return nil, err + } + return updated, nil +} + +func requireOpen(change *policyv1.PolicyChange) error { + if change.GetState() == policyv1.PolicyChangeState_POLICY_CHANGE_STATE_OPEN { + return nil + } + view := newChangeView(change) + return invalidInputError( + fmt.Errorf("change %s is %s: only an open change can change", view.ID, view.State), + "List the open changes: safedep policy change list --state open") +} + +func changeSyncCmd(a *app.App) *cobra.Command { + return &cobra.Command{ + Use: "sync CHANGE", + Short: "Move the base of a policy change to the head revision", + Long: "Move the base of an open policy change to the head revision. The change keeps its settings " + + "as you wrote them. The server never merges, so review the change again before you publish: " + + "the preview shows every difference against head.", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + client, err := a.ControlPlane() + if err != nil { + return err + } + change, err := runChangeSync(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), args[0]) + if err != nil { + return err + } + tui.Success("change %s rebased on revision %d%sreview it: safedep policy change show %s", + change.GetChangeId(), change.GetBaseRevision(), sep, change.GetChangeId()) + return nil + }, + } +} + +func runChangeSync(ctx context.Context, client policyv1grpc.PolicyServiceClient, id string) (*policyv1.PolicyChange, error) { + change, err := getChange(ctx, client, id) + if err != nil { + return nil, err + } + if err := requireOpen(change); err != nil { + return nil, err + } + req := &policyv1.SyncPolicyChangeRequest{} + req.SetChangeId(id) + req.SetEtag(change.GetEtag()) + res, err := client.SyncPolicyChange(ctx, req) + if err != nil { + return nil, mapChangeError("sync", id, err) + } + return res.GetChange(), nil +} + +func changeDeleteCmd(a *app.App) *cobra.Command { + return &cobra.Command{ + Use: "delete CHANGE", + Short: "Delete an open policy change", + Long: "Delete an open policy change. The policy does not change. A published change stays in the history.", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + client, err := a.ControlPlane() + if err != nil { + return err + } + if err := runChangeDelete(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), args[0]); err != nil { + return err + } + tui.Success("change %s deleted", args[0]) + return nil + }, + } +} + +func runChangeDelete(ctx context.Context, client policyv1grpc.PolicyServiceClient, id string) error { + req := &policyv1.DeletePolicyChangeRequest{} + req.SetChangeId(id) + if _, err := client.DeletePolicyChange(ctx, req); err != nil { + return mapChangeError("delete", id, err) + } + return nil +} + +func changePublishCmd(a *app.App) *cobra.Command { + var message string + cmd := &cobra.Command{ + Use: "publish CHANGE", + Short: "Publish an open policy change as a new policy revision", + Long: "Publish an open policy change. The publish makes a new policy revision for the whole " + + "tenant. Projects resolve it at their next check, and endpoints apply it after their next " + + "policy fetch. If a part that the change edits moved since its base revision, the publish " + + "stops. Then sync the change and review it again.", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + client, err := a.ControlPlane() + if err != nil { + return err + } + rev, err := runChangePublish(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), args[0], message) + if err != nil { + return err + } + reportPublish(rev.GetRevision()) + return nil + }, + } + cmd.Flags().StringVarP(&message, "message", "m", "", "the publish message; the change title becomes the title when it is empty") + return cmd +} + +func runChangePublish( + ctx context.Context, + client policyv1grpc.PolicyServiceClient, + id, message string, +) (*policyv1.PolicyRevision, error) { + change, err := getChange(ctx, client, id) + if err != nil { + return nil, err + } + if err := requireOpen(change); err != nil { + return nil, err + } + req := &policyv1.PublishPolicyChangeRequest{} + req.SetChangeId(id) + req.SetEtag(change.GetEtag()) + req.SetMessage(message) + res, err := client.PublishPolicyChange(ctx, req) + if err != nil { + return nil, mapChangeError("publish", id, err) + } + return res.GetRevision(), nil +} + +// reportPublish tells the admin when the new revision applies and how to +// find the endpoints that lag. +func reportPublish(revision uint64) { + tui.Success("revision %d published", revision) + tui.Info(" Projects resolve it at their next check. Endpoints apply it after their next policy fetch") + tui.Info(" Endpoints that have not applied it yet: safedep endpoint list --applied-revision '<%d'", revision) +} diff --git a/internal/cmd/policy/change_show.go b/internal/cmd/policy/change_show.go new file mode 100644 index 0000000..8076f11 --- /dev/null +++ b/internal/cmd/policy/change_show.go @@ -0,0 +1,353 @@ +package policy + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "time" + + policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" + recordv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/record/v1" + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/safedep/dry/tui/table" + "github.com/spf13/cobra" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" + "github.com/safedep/cli/internal/tui" +) + +const ( + overrideKindPrefix = "OVERRIDE_CHANGE_KIND_" + warningCodePrefix = "PREVIEW_WARNING_CODE_" +) + +// changeItem is one row of "What changes": a field, a policy override or a +// package rule operation. +type changeItem struct { + Where string `json:"where"` + What string `json:"what"` + Old string `json:"old,omitempty"` + New string `json:"new,omitempty"` + Direction string `json:"direction"` + oldHuman string + newHuman string +} + +type coverageView struct { + Path string `json:"path"` + Value string `json:"value,omitempty"` + Enforce uint32 `json:"enforce"` + Partial uint32 `json:"partial"` + Detect uint32 `json:"detect"` + Unsupported uint32 `json:"unsupported"` +} + +type warningView struct { + Code string `json:"code"` + Subject string `json:"subject,omitempty"` + Message string `json:"message"` +} + +type previewView struct { + HeadRevision uint64 `json:"head_revision"` + Stale bool `json:"stale"` + Direction string `json:"direction"` + Items []changeItem `json:"changes"` + MatchedProjects uint32 `json:"matched_project_count"` + MatchedEndpoints uint32 `json:"matched_endpoint_count"` + Coverage []coverageView `json:"coverage"` + Warnings []warningView `json:"warnings"` +} + +type changeShowResult struct { + Change changeView `json:"change"` + Restore string `json:"restore,omitempty"` + Preview *previewView `json:"preview,omitempty"` + ruleOnly []changeItem +} + +func changeShowCmd(a *app.App) *cobra.Command { + return &cobra.Command{ + Use: "show CHANGE", + Short: "Show what a policy change does", + Long: "Show a policy change. For an open change, the server previews it against head: the changed " + + "fields and their change direction, the changes to policy overrides, the package rule " + + "operations, the subjects that the change reaches, how well they enforce it, and warnings.", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + client, err := a.ControlPlane() + if err != nil { + return err + } + res, err := runChangeShow(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), args[0]) + if err != nil { + return err + } + return a.Output.Print(res) + }, + } +} + +func getChange(ctx context.Context, client policyv1grpc.PolicyServiceClient, id string) (*policyv1.PolicyChange, error) { + req := &policyv1.GetPolicyChangeRequest{} + req.SetChangeId(id) + res, err := client.GetPolicyChange(ctx, req) + if err != nil { + return nil, mapChangeError("get", id, err) + } + return res.GetChange(), nil +} + +func previewChange(ctx context.Context, client policyv1grpc.PolicyServiceClient, id string) (*previewView, error) { + req := &policyv1.PreviewPolicyChangeRequest{} + req.SetChangeId(id) + res, err := client.PreviewPolicyChange(ctx, req) + if err != nil { + return nil, mapChangeError("preview", id, err) + } + return newPreviewView(res), nil +} + +func runChangeShow(ctx context.Context, client policyv1grpc.PolicyServiceClient, id string) (*changeShowResult, error) { + change, err := getChange(ctx, client, id) + if err != nil { + return nil, err + } + out := &changeShowResult{Change: newChangeView(change)} + if change.HasRestore() { + out.Restore = restoreSummary(change.GetRestore()) + } + if change.GetState() != policyv1.PolicyChangeState_POLICY_CHANGE_STATE_OPEN { + out.ruleOnly = ruleOperationItems(change.GetPackageRuleOperations()) + return out, nil + } + preview, err := previewChange(ctx, client, id) + if err != nil { + return nil, err + } + out.Preview = preview + return out, nil +} + +func restoreSummary(r *policyv1.RestoreSource) string { + capabilities := "every capability" + if len(r.GetCapabilities()) > 0 { + capabilities = strings.Join(r.GetCapabilities(), ", ") + } + rules := "package rules stay at head" + if r.GetPackageRules() == policyv1.PackageRuleRestore_PACKAGE_RULE_RESTORE_FROM_REVISION { + rules = fmt.Sprintf("package rules from revision %d", r.GetFromRevision()) + } + return fmt.Sprintf("restores %s from revision %d%s%s", capabilities, r.GetFromRevision(), sep, rules) +} + +func newPreviewView(res *policyv1.PreviewPolicyChangeResponse) *previewView { + v := &previewView{ + HeadRevision: res.GetHeadRevision(), + Stale: res.GetStale(), + Direction: directionToken(res.GetDirection()), + MatchedProjects: res.GetMatchedProjectCount(), + MatchedEndpoints: res.GetMatchedEndpointCount(), + Items: []changeItem{}, + Coverage: []coverageView{}, + Warnings: []warningView{}, + } + for _, c := range res.GetChanges() { + where := "base" + if c.GetLayer() == recordv1.Layer_LAYER_OVERRIDE { + where = fmt.Sprintf("override %q", c.GetOverrideName()) + } + oldValue, oldHuman := cloudpolicy.FormatJSONValue(c.GetPath(), c.GetOldValue()) + newValue, newHuman := cloudpolicy.FormatJSONValue(c.GetPath(), c.GetNewValue()) + v.Items = append(v.Items, changeItem{ + Where: where, What: c.GetPath(), Old: oldValue, New: newValue, + Direction: directionToken(c.GetDirection()), oldHuman: oldHuman, newHuman: newHuman, + }) + } + for _, c := range res.GetOverrideChanges() { + v.Items = append(v.Items, changeItem{ + Where: fmt.Sprintf("override %q", c.GetOverrideName()), + What: tui.EnumToken(c.GetKind().String(), overrideKindPrefix), + Old: c.GetOldValue(), + New: c.GetNewValue(), + Direction: directionToken(c.GetDirection()), + oldHuman: emptyDash(c.GetOldValue()), + newHuman: emptyDash(c.GetNewValue()), + }) + } + for _, op := range res.GetPackageRuleOperations() { + item := ruleOperationItem(op.GetOperation()) + item.Direction = directionToken(op.GetDirection()) + if op.GetOperation().HasCreate() { + item.New = fmt.Sprintf("matches %d packages, seen on %d endpoints in 30d", + op.GetMatchedPackageCount(), op.GetMatchedEndpointCount()) + item.newHuman = item.New + } + v.Items = append(v.Items, item) + } + for _, c := range res.GetCoverage() { + value, _ := cloudpolicy.FormatJSONValue(c.GetPath(), c.GetValue()) + if c.GetValue() == "" { + value = "" + } + v.Coverage = append(v.Coverage, coverageView{ + Path: c.GetPath(), Value: value, Enforce: c.GetEnforceCount(), Partial: c.GetPartialCount(), + Detect: c.GetDetectCount(), Unsupported: c.GetUnsupportedCount(), + }) + } + for _, w := range res.GetWarnings() { + v.Warnings = append(v.Warnings, warningView{ + Code: strings.TrimPrefix(w.GetCode().String(), warningCodePrefix), + Subject: w.GetSubject(), + Message: w.GetMessage(), + }) + } + return v +} + +func ruleOperationItems(ops []*policyv1.PackageRuleOperation) []changeItem { + out := make([]changeItem, 0, len(ops)) + for _, op := range ops { + out = append(out, ruleOperationItem(op)) + } + return out +} + +func ruleOperationItem(op *policyv1.PackageRuleOperation) changeItem { + item := changeItem{Where: "package rules", oldHuman: "-", newHuman: "-"} + switch { + case op.HasCreate(): + rule := op.GetCreate().GetRule() + item.What = fmt.Sprintf("create %s %s", + tui.EnumToken(rule.GetEffect().String(), effectPrefix), selectorText(rule.GetSelector())) + if id := op.GetCreate().GetOverrideId(); id != "" { + item.Where = "package rules of override " + id + } + case op.HasUpdate(): + item.What = "update " + op.GetUpdate().GetRuleId() + case op.HasDelete(): + item.What = "delete " + op.GetDelete().GetRuleId() + } + return item +} + +func (r *changeShowResult) RenderJSON() ([]byte, error) { + type out struct { + *changeShowResult + Operations []changeItem `json:"package_rule_operations,omitempty"` + } + return json.MarshalIndent(out{changeShowResult: r, Operations: r.ruleOnly}, "", " ") +} + +func (r *changeShowResult) headline() string { + c := r.Change + parts := []string{fmt.Sprintf("Change %s %q", c.ID, c.titleOrUntitled()), c.State, fmt.Sprintf("base rev %d", c.BaseRevision)} + if c.PublishedRevision > 0 { + parts = append(parts, fmt.Sprintf("published as rev %d", c.PublishedRevision)) + } + if r.Preview != nil { + parts = append(parts, fmt.Sprintf("head rev %d", r.Preview.HeadRevision)) + if r.Preview.Stale { + parts = append(parts, "STALE: sync it before you publish") + } else { + parts = append(parts, "no conflict") + } + } + return strings.Join(parts, sep) +} + +func (r *changeShowResult) RenderTable() string { + now := time.Now() + sections := []string{r.headline()} + details := [][2]string{{"Author", emptyDash(r.Change.Author)}, {"Updated", humanTimeCell(r.Change.updatedAt, now)}} + if r.Restore != "" { + details = append(details, [2]string{"Restore", r.Restore}) + } + sections = append(sections, cloudpolicy.KeyValues(details)) + + items := r.ruleOnly + if r.Preview != nil { + items = r.Preview.Items + } + rows := make([][]string, 0, len(items)) + for _, it := range items { + rows = append(rows, []string{it.Where, it.What, it.oldHuman + " -> " + it.newHuman, emptyDash(it.Direction)}) + } + sections = append(sections, table.New(). + Title("What changes"). + Headers("WHERE", "WHAT", "OLD -> NEW", "DIRECTION"). + Rows(rows...). + EmptyMessage("The change edits nothing."). + Render()) + + if p := r.Preview; p != nil { + sections = append(sections, r.impactTable(p), r.warningTable(p), + cloudpolicy.KeyValues([][2]string{{"Direction", directionLine(p.Direction)}})) + } + return strings.Join(sections, "\n\n") +} + +func (r *changeShowResult) impactTable(p *previewView) string { + rows := make([][]string, 0, len(p.Coverage)) + for _, c := range p.Coverage { + what := c.Path + if c.Value != "" { + what += " = " + c.Value + } + rows = append(rows, []string{what, fmt.Sprint(c.Enforce), fmt.Sprint(c.Partial), fmt.Sprint(c.Detect), fmt.Sprint(c.Unsupported)}) + } + return table.New(). + Title(fmt.Sprintf("Impact%ssubjects matched: %d %s, %d %s", sep, + p.MatchedProjects, plural(int(p.MatchedProjects), "project", "projects"), + p.MatchedEndpoints, plural(int(p.MatchedEndpoints), "endpoint", "endpoints"))). + Headers("FIELD", "ENFORCED", "PARTIAL", "DETECT ONLY", "NOT SUPPORTED"). + Rows(rows...). + EmptyMessage("No coverage data for the changed fields."). + Render() +} + +func (r *changeShowResult) warningTable(p *previewView) string { + rows := make([][]string, 0, len(p.Warnings)) + for _, w := range p.Warnings { + rows = append(rows, []string{w.Code, emptyDash(w.Subject), w.Message}) + } + return table.New(). + Title("Warnings"). + Headers("CODE", "SUBJECT", "MESSAGE"). + Rows(rows...). + EmptyMessage("No warnings."). + Render() +} + +func directionLine(direction string) string { + switch direction { + case "LOOSENS": + return "LOOSENS. Only an Admin can publish it, and Admins and Owners get a notice" + case "TIGHTENS": + return "TIGHTENS. An Admin can publish it" + default: + return direction + } +} + +func (r *changeShowResult) RenderPlain() string { + var b strings.Builder + c := r.Change + fmt.Fprintf(&b, "change_id\t%s\ntitle\t%s\nstate\t%s\nbase_revision\t%d", c.ID, c.Title, c.State, c.BaseRevision) + items := r.ruleOnly + if p := r.Preview; p != nil { + fmt.Fprintf(&b, "\nhead_revision\t%d\nstale\t%t\ndirection\t%s", p.HeadRevision, p.Stale, p.Direction) + items = p.Items + } + for _, it := range items { + fmt.Fprintf(&b, "\nchange\t%s\t%s\t%s\t%s\t%s", it.Where, it.What, it.Old, it.New, it.Direction) + } + if p := r.Preview; p != nil { + for _, w := range p.Warnings { + fmt.Fprintf(&b, "\nwarning\t%s\t%s\t%s", w.Code, w.Subject, w.Message) + } + } + return b.String() +} diff --git a/internal/cmd/policy/change_test.go b/internal/cmd/policy/change_test.go new file mode 100644 index 0000000..3e63f3b --- /dev/null +++ b/internal/cmd/policy/change_test.go @@ -0,0 +1,302 @@ +package policy + +import ( + "context" + "testing" + + errorv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/error/v1" + recordv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/record/v1" + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/safedep/dry/usefulerror" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/safedep/cli/internal/cloudpolicy/mocks" +) + +func changeResponse(c *policyv1.PolicyChange) *policyv1.GetPolicyChangeResponse { + res := &policyv1.GetPolicyChangeResponse{} + res.SetChange(c) + return res +} + +func TestRunChangeList(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + published := openChange("17") + published.SetState(policyv1.PolicyChangeState_POLICY_CHANGE_STATE_PUBLISHED) + published.SetPublishedRevision(46) + published.SetTitle("") + res := &policyv1.ListPolicyChangesResponse{} + res.SetChanges([]*policyv1.PolicyChange{openChange("18"), published}) + + client.EXPECT().ListPolicyChanges(mock.Anything, mock.MatchedBy(func(r *policyv1.ListPolicyChangesRequest) bool { + return r.GetFilters().GetState() == policyv1.PolicyChangeState_POLICY_CHANGE_STATE_OPEN && + r.GetPagination().GetPageSize() == 5 + })).Return(res, nil) + + got, err := runChangeList(context.Background(), client, changeListInput{State: "open", PageSize: 5}) + require.NoError(t, err) + require.Len(t, got.Changes, 2) + table := got.RenderTable() + assert.Contains(t, table, "payments: medium + cooldown") + assert.Contains(t, table, "(untitled)") + assert.Contains(t, table, "published as rev 46") + + _, err = runChangeList(context.Background(), client, changeListInput{State: "draft"}) + assert.ErrorContains(t, err, `unknown --state value "draft": allowed values are open, published, deleted`) +} + +func previewResponse() *policyv1.PreviewPolicyChangeResponse { + field := &policyv1.PathChange{} + field.SetPath("scan_gate.fail_on") + field.SetLayer(recordv1.Layer_LAYER_OVERRIDE) + field.SetOverrideName("payments") + field.SetOldValue(`"SEVERITY_HIGH"`) + field.SetNewValue(`"SEVERITY_MEDIUM"`) + field.SetDirection(policyv1.ChangeDirection_CHANGE_DIRECTION_TIGHTENS) + + cooldown := &policyv1.PathChange{} + cooldown.SetPath("package_admission.cooldown.min_age") + cooldown.SetLayer(recordv1.Layer_LAYER_OVERRIDE) + cooldown.SetOverrideName("payments") + cooldown.SetNewValue(`"604800s"`) + cooldown.SetDirection(policyv1.ChangeDirection_CHANGE_DIRECTION_TIGHTENS) + + selector := &policyv1.OverrideChange{} + selector.SetOverrideName("payments") + selector.SetKind(policyv1.OverrideChangeKind_OVERRIDE_CHANGE_KIND_SELECTOR) + selector.SetOldValue("scm-property/criticality=high") + selector.SetNewValue("custom/criticality=high") + selector.SetDirection(policyv1.ChangeDirection_CHANGE_DIRECTION_LOOSENS) + + coverage := &policyv1.CoverageSummary{} + coverage.SetPath("scan_gate.fail_on") + coverage.SetValue(`"SEVERITY_MEDIUM"`) + coverage.SetEnforceCount(2) + coverage.SetPartialCount(1) + + warning := &policyv1.PreviewWarning{} + warning.SetCode(policyv1.PreviewWarningCode_PREVIEW_WARNING_CODE_LOW_ENFORCED_COVERAGE) + warning.SetSubject("scan_gate.fail_on") + warning.SetMessage(`1 of 3 projects cannot enforce "medium" yet`) + + res := &policyv1.PreviewPolicyChangeResponse{} + res.SetHeadRevision(46) + res.SetChanges([]*policyv1.PathChange{field, cooldown}) + res.SetOverrideChanges([]*policyv1.OverrideChange{selector}) + res.SetDirection(policyv1.ChangeDirection_CHANGE_DIRECTION_LOOSENS) + res.SetMatchedProjectCount(3) + res.SetCoverage([]*policyv1.CoverageSummary{coverage}) + res.SetWarnings([]*policyv1.PreviewWarning{warning}) + return res +} + +func TestRunChangeShow_PreviewsAnOpenChange(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicyChange(mock.Anything, mock.Anything).Return(changeResponse(openChange("18")), nil) + client.EXPECT().PreviewPolicyChange(mock.Anything, mock.MatchedBy(func(r *policyv1.PreviewPolicyChangeRequest) bool { + return r.GetChangeId() == "18" + })).Return(previewResponse(), nil) + + got, err := runChangeShow(context.Background(), client, "18") + require.NoError(t, err) + table := got.RenderTable() + for _, want := range []string{ + `Change 18 "payments: medium + cooldown" · open · base rev 46 · head rev 46 · no conflict`, + `override "payments"`, + "high -> medium", + "- -> 7d", + "scm-property/criticality=high -> custom/criticality=high", + "LOW_ENFORCED_COVERAGE", + "subjects matched: 3 projects, 0 endpoints", + "scan_gate.fail_on = medium", + "LOOSENS. Only an Admin can publish it", + } { + assert.Contains(t, table, want) + } + b, err := got.RenderJSON() + require.NoError(t, err) + assert.Contains(t, string(b), `"direction": "LOOSENS"`) + assert.Contains(t, got.RenderPlain(), "change\toverride \"payments\"\tscan_gate.fail_on\thigh\tmedium\tTIGHTENS") +} + +func TestRunChangeShow_StaleChange(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicyChange(mock.Anything, mock.Anything).Return(changeResponse(openChange("19")), nil) + preview := previewResponse() + preview.SetStale(true) + preview.SetHeadRevision(51) + client.EXPECT().PreviewPolicyChange(mock.Anything, mock.Anything).Return(preview, nil) + + got, err := runChangeShow(context.Background(), client, "19") + require.NoError(t, err) + assert.Contains(t, got.RenderTable(), "head rev 51 · STALE: sync it before you publish") +} + +func TestRunChangeShow_PublishedChangeHasNoPreview(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + c := openChange("17") + c.SetState(policyv1.PolicyChangeState_POLICY_CHANGE_STATE_PUBLISHED) + c.SetPublishedRevision(47) + del := &policyv1.PackageRuleDelete{} + del.SetRuleId("r_80b") + op := &policyv1.PackageRuleOperation{} + op.SetDelete(del) + c.SetPackageRuleOperations([]*policyv1.PackageRuleOperation{op}) + client.EXPECT().GetPolicyChange(mock.Anything, mock.Anything).Return(changeResponse(c), nil) + + got, err := runChangeShow(context.Background(), client, "17") + require.NoError(t, err) + assert.Nil(t, got.Preview) + assert.Contains(t, got.RenderTable(), "delete r_80b") + assert.Contains(t, got.RenderTable(), "published as rev 47") +} + +func TestRunChangePublish(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicyChange(mock.Anything, mock.Anything).Return(changeResponse(openChange("18")), nil) + res := &policyv1.PublishPolicyChangeResponse{} + res.SetRevision(revision(47, "payments")) + client.EXPECT().PublishPolicyChange(mock.Anything, mock.MatchedBy(func(r *policyv1.PublishPolicyChangeRequest) bool { + return r.GetChangeId() == "18" && r.GetEtag() == "etag-1" && r.GetMessage() == "payments: fail on medium" + })).Return(res, nil) + + rev, err := runChangePublish(context.Background(), client, "18", "payments: fail on medium") + require.NoError(t, err) + assert.Equal(t, uint64(47), rev.GetRevision()) +} + +func TestRunChangePublish_Errors(t *testing.T) { + tests := []struct { + name string + err error + wantText string + wantHelp string + }{ + { + name: "stale", + err: reasonError(codes.Aborted, errorv1.ErrorReason_ERROR_REASON_POLICY_CHANGE_STALE), + wantText: "The policy moved", + wantHelp: "safedep policy change sync 19", + }, + { + name: "etag", + err: reasonError(codes.Aborted, errorv1.ErrorReason_ERROR_REASON_POLICY_CHANGE_ETAG_MISMATCH), + wantText: "Another request updated change 19", + wantHelp: "safedep policy change show 19", + }, + { + name: "role", + err: status.Error(codes.PermissionDenied, "no"), + wantText: "Your role cannot change the policy", + wantHelp: "Ask an Admin", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicyChange(mock.Anything, mock.Anything).Return(changeResponse(openChange("19")), nil) + client.EXPECT().PublishPolicyChange(mock.Anything, mock.Anything).Return(nil, tt.err) + + _, err := runChangePublish(context.Background(), client, "19", "") + require.Error(t, err) + ue, ok := usefulerror.AsUsefulError(err) + require.True(t, ok) + assert.Contains(t, ue.HumanError(), tt.wantText) + assert.Contains(t, ue.Help(), tt.wantHelp) + }) + } +} + +func TestRunChangePublish_OnlyAnOpenChange(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + c := openChange("17") + c.SetState(policyv1.PolicyChangeState_POLICY_CHANGE_STATE_DELETED) + client.EXPECT().GetPolicyChange(mock.Anything, mock.Anything).Return(changeResponse(c), nil) + + _, err := runChangePublish(context.Background(), client, "17", "") + assert.ErrorContains(t, err, "change 17 is deleted: only an open change can change") +} + +func TestRunChangeGet_NotFound(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicyChange(mock.Anything, mock.Anything).Return(nil, status.Error(codes.NotFound, "x")) + _, err := runChangeSync(context.Background(), client, "99") + ue, ok := usefulerror.AsUsefulError(err) + require.True(t, ok) + assert.Equal(t, "Policy change 99 does not exist", ue.HumanError()) +} + +func TestRunChangeSync(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicyChange(mock.Anything, mock.Anything).Return(changeResponse(openChange("19")), nil) + synced := openChange("19") + synced.SetBaseRevision(51) + res := &policyv1.SyncPolicyChangeResponse{} + res.SetChange(synced) + client.EXPECT().SyncPolicyChange(mock.Anything, mock.MatchedBy(func(r *policyv1.SyncPolicyChangeRequest) bool { + return r.GetEtag() == "etag-1" + })).Return(res, nil) + + got, err := runChangeSync(context.Background(), client, "19") + require.NoError(t, err) + assert.Equal(t, uint64(51), got.GetBaseRevision()) +} + +func TestRunChangeDelete(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().DeletePolicyChange(mock.Anything, mock.MatchedBy(func(r *policyv1.DeletePolicyChangeRequest) bool { + return r.GetChangeId() == "19" + })).Return(&policyv1.DeletePolicyChangeResponse{}, nil) + require.NoError(t, runChangeDelete(context.Background(), client, "19")) +} + +func TestRunChangeEdit_UpdatesWithTheEtag(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + c := openChange("18") + c.SetSettings(headPolicy()) + client.EXPECT().GetPolicyChange(mock.Anything, mock.Anything).Return(changeResponse(c), nil) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(headResponse(), nil) + res := &policyv1.UpdatePolicyChangeResponse{} + res.SetChange(c) + client.EXPECT().UpdatePolicyChange(mock.Anything, mock.MatchedBy(func(r *policyv1.UpdatePolicyChangeRequest) bool { + return r.GetEtag() == "etag-1" && r.GetTitle() == "new title" && r.HasSettings() && + r.GetSettings().GetOverrides()[0].GetDescription() == "why" + })).Return(res, nil) + + ed := &scriptedEditor{edits: []func(string) string{replace(" - name: payments\n", " - name: payments\n description: why\n")}} + _, err := runChangeEdit(context.Background(), client, ed.open, "", "18", editInput{Title: "new title"}) + require.NoError(t, err) + assert.Contains(t, ed.seen[0], "# Change 18 of this tenant · base revision 46 · head revision 46") +} + +func TestChangeCreate(t *testing.T) { + assert.ErrorContains(t, validateChangeCreate(changeCreateInput{PackageRules: "head"}), "--from-revision is required") + assert.ErrorContains(t, validateChangeCreate(changeCreateInput{FromRevision: 46, PackageRules: "head", Capabilities: []string{"core"}}), + `unknown --capability "core"`) + assert.ErrorContains(t, validateChangeCreate(changeCreateInput{FromRevision: 46, PackageRules: "all"}), "unknown --package-rules") + + client := mocks.NewPolicyServiceClientMock(t) + created := openChange("20") + restore := &policyv1.RestoreSource{} + restore.SetFromRevision(46) + restore.SetCapabilities([]string{"scan_gate"}) + created.SetRestore(restore) + res := &policyv1.CreatePolicyChangeResponse{} + res.SetChange(created) + client.EXPECT().CreatePolicyChange(mock.Anything, mock.MatchedBy(func(r *policyv1.CreatePolicyChangeRequest) bool { + return !r.HasSettings() && r.GetRestore().GetFromRevision() == 46 && + r.GetRestore().GetCapabilities()[0] == "scan_gate" && + r.GetRestore().GetPackageRules() == policyv1.PackageRuleRestore_PACKAGE_RULE_RESTORE_KEEP_HEAD && + r.GetTitle() == "revert fail_on to high" + })).Return(res, nil) + + got, err := runChangeCreate(context.Background(), client, changeCreateInput{ + FromRevision: 46, Capabilities: []string{"scan_gate"}, PackageRules: "head", Title: "revert fail_on to high", + }) + require.NoError(t, err) + assert.Equal(t, "restores scan_gate from revision 46 · package rules stay at head", restoreSummary(got.GetRestore())) +} diff --git a/internal/cmd/policy/cmd.go b/internal/cmd/policy/cmd.go new file mode 100644 index 0000000..9331ffb --- /dev/null +++ b/internal/cmd/policy/cmd.go @@ -0,0 +1,59 @@ +// Package policy registers the `safedep policy` command tree, the CLI for +// policy management in SafeDep Cloud: the policy settings document, policy +// changes, policy revisions and package rules. Every verb needs control +// plane credentials. +package policy + +import ( + "github.com/spf13/cobra" + + "github.com/safedep/cli/internal/app" +) + +func Register(root *cobra.Command, a *app.App) { + parent := &cobra.Command{ + Use: "policy", + Short: "Manage the policy of your SafeDep Cloud tenant", + Long: "Manage the one policy of your SafeDep Cloud tenant. The policy settings document holds the " + + "policy base and the policy overrides. Package rules trust or block packages. An edit of the " + + "settings makes a policy change, which applies only after you publish it. Each publish makes " + + "a policy revision.", + } + parent.AddCommand(showCmd(a), getCmd(a), editCmd(a)) + + change := &cobra.Command{ + Use: "change", + Short: "Review, sync and publish policy changes", + Long: "Review, edit, sync, publish and delete policy changes. A policy change is a draft on the " + + "server. Nothing applies until you publish it. Create one with `safedep policy edit`, or with " + + "`safedep policy change create --from-revision` for a rollback.", + } + change.AddCommand( + changeListCmd(a), + changeShowCmd(a), + changeEditCmd(a), + changeSyncCmd(a), + changeDeleteCmd(a), + changePublishCmd(a), + changeCreateCmd(a), + ) + + revision := &cobra.Command{ + Use: "revision", + Short: "Inspect policy revisions", + Long: "Inspect policy revisions. Each publish makes one immutable revision. Revision numbers only go up.", + } + revision.AddCommand(revisionListCmd(a), revisionShowCmd(a)) + + rule := &cobra.Command{ + Use: "rule", + Short: "Manage package rules: trust and block entries", + Long: "Manage package rules. A block entry stops the install of the packages that it selects. A trust " + + "entry waives verdicts of its trust scopes for one package, but never a verdict of verified " + + "malware. Each create, update or delete publishes a new policy revision at once.", + } + rule.AddCommand(ruleCreateCmd(a), ruleListCmd(a), ruleShowCmd(a), ruleUpdateCmd(a), ruleDeleteCmd(a)) + + parent.AddCommand(change, revision, rule) + root.AddCommand(parent) +} diff --git a/internal/cmd/policy/edit.go b/internal/cmd/policy/edit.go new file mode 100644 index 0000000..4fd9113 --- /dev/null +++ b/internal/cmd/policy/edit.go @@ -0,0 +1,251 @@ +package policy + +import ( + "context" + "errors" + "fmt" + "strings" + + policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/safedep/dry/tui" + "github.com/safedep/dry/usefulerror" + "github.com/spf13/cobra" + "google.golang.org/protobuf/proto" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" + "github.com/safedep/cli/internal/config" + clitui "github.com/safedep/cli/internal/tui" +) + +type editInput struct { + Title string + Override string +} + +func editCmd(a *app.App) *cobra.Command { + var in editInput + cmd := &cobra.Command{ + Use: "edit", + Short: "Edit the policy settings document in your editor", + Long: "Open the policy settings document of the tenant in $VISUAL or $EDITOR: the policy base and " + + "every policy override. Saving creates a policy change on the server. Nothing applies until " + + "you publish the change. Use --override NAME to edit one policy override. Package rules are " + + "not in the document. Change them with `safedep policy rule`.", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + if err := requireTerminal(); err != nil { + return err + } + client, err := a.ControlPlane() + if err != nil { + return err + } + change, err := runEdit(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), + openEditor, a.Tenant(), in) + if errors.Is(err, errNoChange) { + tui.Info("No change. Nothing is saved") + return nil + } + if err != nil { + return err + } + tui.Success("change %s saved from revision %d", change.GetChangeId(), change.GetBaseRevision()) + tui.Info(" Review it: safedep policy change show %s", change.GetChangeId()) + return nil + }, + } + cmd.Flags().StringVarP(&in.Title, "message", "m", "", "the title of the policy change") + cmd.Flags().StringVar(&in.Override, "override", "", "edit only the policy override with this name") + return cmd +} + +func openEditor(ctx context.Context, path string) error { + return clitui.RunEditor(ctx, config.Editor(), path) +} + +func requireTerminal() error { + if clitui.IsInteractive() { + return nil + } + cause := errors.New("this command opens an editor and needs a terminal") + return newPolicyError(usefulerror.ErrBadRequest, cause.Error(), + "Run it in a terminal. To read the policy in a script, run: safedep policy get", cause) +} + +func runEdit( + ctx context.Context, + client policyv1grpc.PolicyServiceClient, + open openEditorFunc, + tenant string, + in editInput, +) (*policyv1.PolicyChange, error) { + head, err := getPolicy(ctx, client) + if err != nil { + return nil, err + } + intro := []string{ + fmt.Sprintf("Policy of %s%shead revision %d", tenantName(tenant), sep, head.GetHeadRevision()), + "Saving creates a draft change. Nothing applies until you publish it.", + } + header := editHeader(intro, head) + + var change *policyv1.PolicyChange + err = editSettings(ctx, open, head.GetPolicy(), header, in.Override, func(p *policyv1.Policy) error { + req := &policyv1.CreatePolicyChangeRequest{} + req.SetTitle(in.Title) + req.SetSettings(p) + req.SetBaseRevision(head.GetHeadRevision()) + res, err := client.CreatePolicyChange(ctx, req) + if err != nil { + return fmt.Errorf("policy change create: %w", err) + } + change = res.GetChange() + return nil + }) + if err != nil { + return nil, err + } + return change, nil +} + +func tenantName(tenant string) string { + if tenant == "" { + return "this tenant" + } + return tenant +} + +// editHeader is the comment block at the top of the document. It shows the +// layers, because the SafeDep default policy is below the policy base and +// the tenant cannot change it. +func editHeader(intro []string, head *policyv1.GetPolicyResponse) string { + defaults := make([]string, 0) + for _, f := range cloudpolicy.Fields(head.GetDefaultPolicy().GetSpec()) { + defaults = append(defaults, f.Path+": "+f.Value) + } + if len(defaults) == 0 { + defaults = append(defaults, "(no values)") + } + counts := head.GetPackageRuleCounts() + rules := counts.GetTrustCount() + counts.GetBlockCount() + + lines := append([]string{}, intro...) + lines = append(lines, + "", + "Layers, from low to high, for each subject:", + fmt.Sprintf(" 1. SafeDep default policy (read-only, revision %d):", head.GetDefaultPolicy().GetRevision()), + " "+strings.Join(defaults, sep), + " 2. base - applies to every endpoint and project of this tenant", + " 3. overrides - apply to the subjects that their selector matches.", + " For each field, the highest priority that sets it wins.", + "", + fmt.Sprintf("Package rules are not in this file: %d %s (safedep policy rule list)", rules, plural(int(rules), "rule", "rules")), + "The policy keeps no comments. Write the reason for a value in a description field.", + ) + return cloudpolicy.CommentBlock(lines) +} + +// editSettings opens the settings, or one policy override of them, in the +// editor and gives the whole edited document to commit. +func editSettings( + ctx context.Context, + open openEditorFunc, + start *policyv1.Policy, + header string, + overrideName string, + commit func(*policyv1.Policy) error, +) error { + if start == nil { + start = &policyv1.Policy{} + } + if overrideName == "" { + text, err := cloudpolicy.MarshalPolicy(start, header) + if err != nil { + return err + } + return editLoop(ctx, open, text, func(saved []byte) error { + edited, err := cloudpolicy.UnmarshalPolicy(saved) + if err != nil { + return retryable(err) + } + cloudpolicy.RestoreOverrideIDs(edited, start) + if err := validateSettings(edited); err != nil { + return retryable(err) + } + warnComments(saved, header) + return commit(edited) + }) + } + + current, err := findOverride(start, overrideName) + if err != nil { + return err + } + text, err := cloudpolicy.MarshalOverride(current, header) + if err != nil { + return err + } + return editLoop(ctx, open, text, func(saved []byte) error { + edited, err := cloudpolicy.UnmarshalOverride(saved) + if err != nil { + return retryable(err) + } + if edited.GetOverrideId() == "" { + edited.SetOverrideId(current.GetOverrideId()) + } + full, ok := proto.Clone(start).(*policyv1.Policy) + if !ok { + return errors.New("policy edit: clone the policy") + } + overrides := full.GetOverrides() + for i, o := range overrides { + if o.GetOverrideId() == current.GetOverrideId() { + overrides[i] = edited + } + } + full.SetOverrides(overrides) + if err := validateSettings(full); err != nil { + return retryable(err) + } + warnComments(saved, header) + return commit(full) + }) +} + +// validateSettings checks the rules that a person breaks most often in an +// edit, so the editor shows them before the RPC. The server checks every +// rule. +func validateSettings(p *policyv1.Policy) error { + names := map[string]struct{}{} + priorities := map[uint32]string{} + for i, o := range p.GetOverrides() { + if o.GetName() == "" { + return fmt.Errorf("overrides[%d]: give the override a name", i) + } + if _, dup := names[o.GetName()]; dup { + return fmt.Errorf("overrides[%d]: two overrides are named %q. Each name must be unique", i, o.GetName()) + } + names[o.GetName()] = struct{}{} + if o.GetPriority() == 0 { + return fmt.Errorf("override %q: give it a priority from 1 to 1000000", o.GetName()) + } + if other, dup := priorities[o.GetPriority()]; dup { + return fmt.Errorf("override %q: priority %d is also the priority of %q. Each priority must be unique", + o.GetName(), o.GetPriority(), other) + } + priorities[o.GetPriority()] = o.GetName() + if !o.HasSelector() { + return fmt.Errorf("override %q: give it a selector. Write selector: {} to select every subject", o.GetName()) + } + } + return nil +} + +func warnComments(saved []byte, header string) { + if cloudpolicy.HasUserComments(saved, header) { + tui.Warning("The file holds comments. The policy keeps no comments, so they are lost. " + + "Write the reason in a description field") + } +} diff --git a/internal/cmd/policy/edit_test.go b/internal/cmd/policy/edit_test.go new file mode 100644 index 0000000..0566c7c --- /dev/null +++ b/internal/cmd/policy/edit_test.go @@ -0,0 +1,207 @@ +package policy + +import ( + "context" + "errors" + "os" + "strings" + "testing" + + scangatev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/scangate/v1" + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/safedep/cli/internal/cloudpolicy/mocks" +) + +// scriptedEditor plays one edit for each open. An edit gets the file text +// and returns the text to save. +type scriptedEditor struct { + edits []func(string) string + seen []string +} + +func (e *scriptedEditor) open(_ context.Context, path string) error { + b, err := os.ReadFile(path) + if err != nil { + return err + } + e.seen = append(e.seen, string(b)) + if len(e.edits) == 0 { + return errors.New("unexpected editor open") + } + edit := e.edits[0] + e.edits = e.edits[1:] + return os.WriteFile(path, []byte(edit(string(b))), 0o600) +} + +func replace(old, new string) func(string) string { + return func(s string) string { return strings.Replace(s, old, new, 1) } +} + +func keep(s string) string { return s } + +func TestEditLoop_NoChange(t *testing.T) { + ed := &scriptedEditor{edits: []func(string) string{keep}} + err := editLoop(context.Background(), ed.open, []byte("a: 1\n"), func([]byte) error { + t.Fatal("save must not run") + return nil + }) + assert.ErrorIs(t, err, errNoChange) +} + +func TestEditLoop_ReopensWithTheErrorAndSaves(t *testing.T) { + ed := &scriptedEditor{edits: []func(string) string{ + replace("a: 1", "a: bad"), + replace("a: bad", "a: 2"), + }} + var saved []string + err := editLoop(context.Background(), ed.open, []byte("a: 1\n"), func(text []byte) error { + saved = append(saved, string(text)) + if strings.Contains(string(text), "bad") { + return retryable(errors.New("line 1: a: expected a number")) + } + return nil + }) + require.NoError(t, err) + assert.Equal(t, []string{"a: bad\n", "a: 2\n"}, saved, "the error lines never reach save") + require.Len(t, ed.seen, 2) + assert.Contains(t, ed.seen[1], "# ! The last save failed:") + assert.Contains(t, ed.seen[1], "line 1: a: expected a number") +} + +func TestEditLoop_ServerRejectionIsRetryable(t *testing.T) { + ed := &scriptedEditor{edits: []func(string) string{replace("1", "2"), replace("2", "3")}} + calls := 0 + err := editLoop(context.Background(), ed.open, []byte("a: 1\n"), func([]byte) error { + calls++ + if calls == 1 { + return status.Error(codes.InvalidArgument, "override priorities must be unique") + } + return nil + }) + require.NoError(t, err) + assert.Equal(t, 2, calls) +} + +func TestEditLoop_StopsWhenTheUserGivesUp(t *testing.T) { + ed := &scriptedEditor{edits: []func(string) string{replace("1", "x"), keep}} + err := editLoop(context.Background(), ed.open, []byte("a: 1\n"), func([]byte) error { + return retryable(errors.New("bad")) + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "the file still has errors") +} + +func TestEditLoop_KeepsTheFileOnAnRPCFailure(t *testing.T) { + ed := &scriptedEditor{edits: []func(string) string{replace("1", "2")}} + err := editLoop(context.Background(), ed.open, []byte("a: 1\n"), func([]byte) error { + return status.Error(codes.Unavailable, "down") + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "down") +} + +func TestRunEdit_CreatesAChangeFromTheHead(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(headResponse(), nil) + + var req *policyv1.CreatePolicyChangeRequest + client.EXPECT().CreatePolicyChange(mock.Anything, mock.Anything). + RunAndReturn(func(_ context.Context, r *policyv1.CreatePolicyChangeRequest, _ ...grpc.CallOption) (*policyv1.CreatePolicyChangeResponse, error) { + req = r + c := openChange("18") + res := &policyv1.CreatePolicyChangeResponse{} + res.SetChange(c) + return res, nil + }) + + ed := &scriptedEditor{edits: []func(string) string{ + replace("custom/criticality: high}\n spec:\n scan_gate:\n fail_on: high", + "custom/criticality: high}\n spec:\n scan_gate:\n fail_on: medium"), + }} + change, err := runEdit(context.Background(), client, ed.open, "platform-eng.acme.safedep.io", + editInput{Title: "payments: medium"}) + require.NoError(t, err) + assert.Equal(t, "18", change.GetChangeId()) + + header := ed.seen[0] + assert.Contains(t, header, "# Policy of platform-eng.acme.safedep.io · head revision 46") + assert.Contains(t, header, "# 1. SafeDep default policy (read-only, revision 12):") + assert.Contains(t, header, "scan_gate.fail_on: high") + assert.Contains(t, header, "# Package rules are not in this file: 211 rules") + + require.NotNil(t, req) + assert.Equal(t, "payments: medium", req.GetTitle()) + assert.Equal(t, uint64(46), req.GetBaseRevision()) + overrides := req.GetSettings().GetOverrides() + require.Len(t, overrides, 2) + assert.Equal(t, "ov_pay", overrides[0].GetOverrideId(), "the edit keeps the ids of the overrides") + assert.Equal(t, scangatev1.Severity_SEVERITY_MEDIUM, overrides[0].GetSpec().GetScanGate().GetFailOn()) + assert.Equal(t, "ov_ci", overrides[1].GetOverrideId()) +} + +func TestRunEdit_OneOverride(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(headResponse(), nil) + var req *policyv1.CreatePolicyChangeRequest + client.EXPECT().CreatePolicyChange(mock.Anything, mock.Anything). + RunAndReturn(func(_ context.Context, r *policyv1.CreatePolicyChangeRequest, _ ...grpc.CallOption) (*policyv1.CreatePolicyChangeResponse, error) { + req = r + res := &policyv1.CreatePolicyChangeResponse{} + res.SetChange(openChange("19")) + return res, nil + }) + + ed := &scriptedEditor{edits: []func(string) string{replace("fail_on: critical", "fail_on: high")}} + _, err := runEdit(context.Background(), client, ed.open, "", editInput{Override: "ci"}) + require.NoError(t, err) + assert.NotContains(t, ed.seen[0], "payments", "only the named override opens") + assert.Contains(t, ed.seen[0], "# Policy of this tenant") + + overrides := req.GetSettings().GetOverrides() + require.Len(t, overrides, 2) + assert.Equal(t, scangatev1.Severity_SEVERITY_HIGH, overrides[0].GetSpec().GetScanGate().GetFailOn(), "payments stays") + assert.Equal(t, "ov_ci", overrides[1].GetOverrideId()) + assert.Equal(t, scangatev1.Severity_SEVERITY_HIGH, overrides[1].GetSpec().GetScanGate().GetFailOn()) +} + +func TestRunEdit_UnknownOverride(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(headResponse(), nil) + _, err := runEdit(context.Background(), client, (&scriptedEditor{}).open, "", editInput{Override: "laptops"}) + require.Error(t, err) + assert.Contains(t, err.Error(), `no policy override is named "laptops": known overrides: ci, payments`) +} + +func TestValidateSettings(t *testing.T) { + tests := []struct { + name string + mutate func(*policyv1.Policy) + want string + }{ + {"valid", func(*policyv1.Policy) {}, ""}, + {"duplicate name", func(p *policyv1.Policy) { p.GetOverrides()[1].SetName("payments") }, `two overrides are named "payments"`}, + {"duplicate priority", func(p *policyv1.Policy) { p.GetOverrides()[1].SetPriority(200) }, "priority 200 is also the priority"}, + {"no priority", func(p *policyv1.Policy) { p.GetOverrides()[0].SetPriority(0) }, "give it a priority"}, + {"no selector", func(p *policyv1.Policy) { p.GetOverrides()[0].ClearSelector() }, "give it a selector"}, + {"no name", func(p *policyv1.Policy) { p.GetOverrides()[0].SetName("") }, "give the override a name"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + p := headPolicy() + tt.mutate(p) + err := validateSettings(p) + if tt.want == "" { + require.NoError(t, err) + return + } + assert.ErrorContains(t, err, tt.want) + }) + } +} diff --git a/internal/cmd/policy/editor.go b/internal/cmd/policy/editor.go new file mode 100644 index 0000000..01893f6 --- /dev/null +++ b/internal/cmd/policy/editor.go @@ -0,0 +1,127 @@ +package policy + +import ( + "bytes" + "context" + "errors" + "fmt" + "os" + "strings" + + "github.com/safedep/dry/tui" + "github.com/safedep/dry/usefulerror" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +const ( + maxEditAttempts = 5 + errorLinePrefix = "# ! " +) + +// openEditorFunc opens a file in the editor of the user and returns when +// the user closes it. +type openEditorFunc func(ctx context.Context, path string) error + +// errNoChange stops an edit that the user saved with no change. +var errNoChange = errors.New("no change") + +// retryableError marks a save error that the user can fix in the editor: a +// document that does not parse, or a change that the server rejects as +// invalid. +type retryableError struct{ err error } + +func (e *retryableError) Error() string { return e.err.Error() } +func (e *retryableError) Unwrap() error { return e.err } + +func retryable(err error) error { return &retryableError{err: err} } + +func isRetryable(err error) bool { + var r *retryableError + if errors.As(err, &r) { + return true + } + st, ok := status.FromError(err) + return ok && st.Code() == codes.InvalidArgument +} + +// editLoop writes text to a temporary file, opens the editor on it, and +// gives the saved text to save. When save fails with an error that the user +// can fix, the loop opens the file again with the error at the top. The file +// stays on disk when the edit fails for another reason, so no work is lost. +func editLoop(ctx context.Context, open openEditorFunc, text []byte, save func([]byte) error) error { + f, err := os.CreateTemp("", "safedep-policy-*.yaml") + if err != nil { + return fmt.Errorf("policy edit: temporary file: %w", err) + } + path := f.Name() + if _, err := f.Write(text); err != nil { + return errors.Join(fmt.Errorf("policy edit: write %s: %w", path, err), f.Close()) + } + if err := f.Close(); err != nil { + return fmt.Errorf("policy edit: write %s: %w", path, err) + } + + last := text + for attempt := 0; attempt < maxEditAttempts; attempt++ { + if err := open(ctx, path); err != nil { + return keptEditError(path, err) + } + saved, err := os.ReadFile(path) + if err != nil { + return fmt.Errorf("policy edit: read %s: %w", path, err) + } + saved = stripErrorLines(saved) + if bytes.Equal(saved, stripErrorLines(last)) { + if attempt == 0 { + return errors.Join(errNoChange, os.Remove(path)) + } + return keptEditError(path, errors.New("the file still has errors")) + } + + err = save(saved) + if err == nil { + if rmErr := os.Remove(path); rmErr != nil { + tui.Warning("could not remove the temporary file %s: %v", path, rmErr) + } + return nil + } + if !isRetryable(err) { + return keptEditError(path, err) + } + last = append(errorLines(err), saved...) + if err := os.WriteFile(path, last, 0o600); err != nil { //nolint:gosec // G703: the CLI made the path with os.CreateTemp. + return fmt.Errorf("policy edit: write %s: %w", path, err) + } + } + return keptEditError(path, fmt.Errorf("the file still has errors after %d saves", maxEditAttempts)) +} + +func errorLines(err error) []byte { + var b strings.Builder + b.WriteString(errorLinePrefix + "The last save failed:\n") + for _, line := range strings.Split(err.Error(), "\n") { + b.WriteString(errorLinePrefix + " " + line + "\n") + } + b.WriteString(errorLinePrefix + "Fix the file and save it again. Close it with no change to stop.\n") + return []byte(b.String()) +} + +func stripErrorLines(text []byte) []byte { + for bytes.HasPrefix(text, []byte(errorLinePrefix)) { + i := bytes.IndexByte(text, '\n') + if i < 0 { + return nil + } + text = text[i+1:] + } + return text +} + +func keptEditError(path string, cause error) error { + return usefulerror.NewUsefulError(). + WithCode(usefulerror.ErrBadRequest). + WithHumanError("The policy edit was not saved: " + cause.Error()). + WithHelp("Your edit is in " + path + ". Copy what you need from it, then run the command again"). + Wrap(cause) +} diff --git a/internal/cmd/policy/errors.go b/internal/cmd/policy/errors.go new file mode 100644 index 0000000..76428a6 --- /dev/null +++ b/internal/cmd/policy/errors.go @@ -0,0 +1,77 @@ +package policy + +import ( + "fmt" + + errorv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/error/v1" + "github.com/safedep/dry/usefulerror" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/safedep/cli/internal/rpcerror" +) + +func newPolicyError(code, humanError, help string, cause error) error { + return usefulerror.NewUsefulError(). + WithCode(code). + WithHumanError(humanError). + WithHelp(help). + Wrap(cause) +} + +func invalidInputError(cause error, help string) error { + return newPolicyError(usefulerror.ErrBadRequest, cause.Error(), help, cause) +} + +// mapChangeError gives the recovery for the errors of a policy change RPC: +// a stale base, an old etag, or a change that does not exist. +func mapChangeError(op, changeID string, err error) error { + cause := fmt.Errorf("policy change %s: %w", op, err) + switch rpcerror.Reason(err) { + case errorv1.ErrorReason_ERROR_REASON_POLICY_CHANGE_STALE: + return newPolicyError(usefulerror.ErrConflict, + fmt.Sprintf("The policy moved: a part that change %s edits changed after its base revision", changeID), + fmt.Sprintf("Sync it and review it again: safedep policy change sync %s", changeID), + cause) + case errorv1.ErrorReason_ERROR_REASON_POLICY_CHANGE_ETAG_MISMATCH: + return newPolicyError(usefulerror.ErrConflict, + fmt.Sprintf("Another request updated change %s after this command read it", changeID), + fmt.Sprintf("Review it again: safedep policy change show %s", changeID), + cause) + } + if st, ok := status.FromError(err); ok { + switch st.Code() { + case codes.NotFound: + return newPolicyError(usefulerror.ErrNotFound, + fmt.Sprintf("Policy change %s does not exist", changeID), + "List the changes: safedep policy change list", + cause) + case codes.PermissionDenied: + return newPolicyError(usefulerror.ErrAuthorizationFailed, + "Your role cannot change the policy", + "Ask an Admin of the tenant to do it", + cause) + } + } + return cause +} + +// mapRuleError gives the recovery for the errors of a package rule RPC. +func mapRuleError(op, ruleID string, err error) error { + cause := fmt.Errorf("package rule %s: %w", op, err) + if st, ok := status.FromError(err); ok { + switch st.Code() { + case codes.NotFound: + return newPolicyError(usefulerror.ErrNotFound, + fmt.Sprintf("Package rule %s does not exist", ruleID), + "List the rules: safedep policy rule list", + cause) + case codes.PermissionDenied: + return newPolicyError(usefulerror.ErrAuthorizationFailed, + "Your role cannot change package rules", + "Ask an Admin of the tenant to do it", + cause) + } + } + return cause +} diff --git a/internal/cmd/policy/fixtures_test.go b/internal/cmd/policy/fixtures_test.go new file mode 100644 index 0000000..e84131c --- /dev/null +++ b/internal/cmd/policy/fixtures_test.go @@ -0,0 +1,105 @@ +package policy + +import ( + "time" + + messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" + errorv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/error/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" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/timestamppb" +) + +var fixedNow = time.Date(2026, 10, 31, 12, 0, 0, 0, time.UTC) + +func failOnSpec(severity scangatev1.Severity) *specv1.PolicySpec { + gate := &scangatev1.ScanGate{} + gate.SetFailOn(severity) + spec := &specv1.PolicySpec{} + spec.SetScanGate(gate) + return spec +} + +func override(id, name string, priority uint32, labelKey, labelValue string, severity scangatev1.Severity) *policyv1.Override { + sel := &messagescontroltowerv1.LabelSelector{} + sel.SetMatchLabels(map[string]string{labelKey: labelValue}) + o := &policyv1.Override{} + o.SetOverrideId(id) + o.SetName(name) + o.SetPriority(priority) + o.SetSelector(sel) + o.SetSpec(failOnSpec(severity)) + return o +} + +func headPolicy() *policyv1.Policy { + p := &policyv1.Policy{} + p.SetBase(failOnSpec(scangatev1.Severity_SEVERITY_HIGH)) + p.SetOverrides([]*policyv1.Override{ + override("ov_pay", "payments", 200, "custom/criticality", "high", scangatev1.Severity_SEVERITY_HIGH), + override("ov_ci", "ci", 300, "managed/deployment-kind", "ci", scangatev1.Severity_SEVERITY_CRITICAL), + }) + return p +} + +func actor(name string) *messagescontroltowerv1.Actor { + a := &messagescontroltowerv1.Actor{} + a.SetKind(messagescontroltowerv1.ActorKind_ACTOR_KIND_USER) + a.SetId("u_" + name) + a.SetDisplayName(name) + return a +} + +func revision(n uint64, message string) *policyv1.PolicyRevision { + r := &policyv1.PolicyRevision{} + r.SetRevision(n) + r.SetAuthor(actor("alice")) + r.SetMessage(message) + r.SetSource(policyv1.ChangeSource_CHANGE_SOURCE_CLI) + r.SetDirection(policyv1.ChangeDirection_CHANGE_DIRECTION_TIGHTENS) + r.SetPublishedAt(timestamppb.New(time.Now().Add(-49 * time.Hour))) + return r +} + +func headResponse() *policyv1.GetPolicyResponse { + def := &policyv1.DefaultPolicy{} + def.SetRevision(12) + def.SetSpec(failOnSpec(scangatev1.Severity_SEVERITY_HIGH)) + counts := &policyv1.PackageRuleCounts{} + counts.SetTrustCount(184) + counts.SetBlockCount(27) + counts.SetTrustExpiringSoonCount(23) + + res := &policyv1.GetPolicyResponse{} + res.SetPolicy(headPolicy()) + res.SetHeadRevision(46) + res.SetHead(revision(46, "cooldown 5d for laptops")) + res.SetDefaultPolicy(def) + res.SetPackageRuleCounts(counts) + return res +} + +func openChange(id string) *policyv1.PolicyChange { + c := &policyv1.PolicyChange{} + c.SetChangeId(id) + c.SetState(policyv1.PolicyChangeState_POLICY_CHANGE_STATE_OPEN) + c.SetTitle("payments: medium + cooldown") + c.SetBaseRevision(46) + c.SetEtag("etag-1") + c.SetAuthor(actor("alice")) + c.SetUpdatedAt(timestamppb.New(fixedNow.Add(-2 * time.Minute))) + return c +} + +func reasonError(code codes.Code, reason errorv1.ErrorReason) error { + detail := &errorv1.ErrorDetail{} + detail.SetReason(reason) + st, err := status.New(code, "rpc failed").WithDetails(detail) + if err != nil { + panic(err) + } + return st.Err() +} diff --git a/internal/cmd/policy/get.go b/internal/cmd/policy/get.go new file mode 100644 index 0000000..6d2f340 --- /dev/null +++ b/internal/cmd/policy/get.go @@ -0,0 +1,124 @@ +package policy + +import ( + "context" + "encoding/json" + "fmt" + + policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/spf13/cobra" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" +) + +type getInput struct { + Revision uint64 +} + +// getResult is the policy settings document. The table and plain forms are +// the YAML that `safedep policy edit` opens, so `safedep policy get > +// policy.yaml` writes a file that a person or a script can read. +type getResult struct { + Revision uint64 + Document any + YAML string +} + +func getCmd(a *app.App) *cobra.Command { + var in getInput + cmd := &cobra.Command{ + Use: "get", + Short: "Write the policy settings document as YAML", + Long: "Write the policy settings document of the tenant as YAML: the policy base and every policy " + + "override. Package rules are not in it. By default the command writes the head revision. " + + "Use --revision for an older one. With --output json, the command writes the same document " + + "as JSON.", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + client, err := a.ControlPlane() + if err != nil { + return err + } + res, err := runGet(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), in, a.Tenant()) + if err != nil { + return err + } + return a.Output.Print(res) + }, + } + cmd.Flags().Uint64Var(&in.Revision, "revision", 0, "the policy revision to write; the head revision when 0") + return cmd +} + +func runGet( + ctx context.Context, + client policyv1grpc.PolicyServiceClient, + in getInput, + tenant string, +) (*getResult, error) { + revision, policy, err := readPolicyAt(ctx, client, in.Revision) + if err != nil { + return nil, err + } + doc, err := cloudpolicy.PolicyMap(policy) + if err != nil { + return nil, err + } + text, err := cloudpolicy.MarshalPolicy(policy, getHeader(tenant, revision)) + if err != nil { + return nil, err + } + return &getResult{Revision: revision, Document: doc, YAML: string(trimNewline(text))}, nil +} + +// readPolicyAt reads the policy settings at a revision, or at head for 0. +func readPolicyAt( + ctx context.Context, + client policyv1grpc.PolicyServiceClient, + revision uint64, +) (uint64, *policyv1.Policy, error) { + if revision == 0 { + res, err := getPolicy(ctx, client) + if err != nil { + return 0, nil, err + } + return res.GetHeadRevision(), res.GetPolicy(), nil + } + req := &policyv1.GetPolicyRevisionRequest{} + req.SetRevision(revision) + res, err := client.GetPolicyRevision(ctx, req) + if err != nil { + return 0, nil, fmt.Errorf("policy: get revision %d: %w", revision, err) + } + return revision, res.GetPolicy(), nil +} + +func getHeader(tenant string, revision uint64) string { + if tenant == "" { + tenant = "this tenant" + } + return cloudpolicy.CommentBlock([]string{ + fmt.Sprintf("Policy settings of %s%srevision %d", tenant, sep, revision), + "Package rules are not in this file: safedep policy rule list", + }) +} + +func (r *getResult) RenderJSON() ([]byte, error) { + return json.MarshalIndent(struct { + Revision uint64 `json:"revision"` + Policy any `json:"policy"` + }{Revision: r.Revision, Policy: r.Document}, "", " ") +} + +func (r *getResult) RenderTable() string { return r.YAML } + +func (r *getResult) RenderPlain() string { return r.YAML } + +func trimNewline(b []byte) []byte { + for len(b) > 0 && b[len(b)-1] == '\n' { + b = b[:len(b)-1] + } + return b +} diff --git a/internal/cmd/policy/revision.go b/internal/cmd/policy/revision.go new file mode 100644 index 0000000..6be7713 --- /dev/null +++ b/internal/cmd/policy/revision.go @@ -0,0 +1,200 @@ +package policy + +import ( + "context" + "encoding/json" + "fmt" + "strconv" + "strings" + "time" + + policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/safedep/dry/tui/table" + "github.com/spf13/cobra" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" + "github.com/safedep/cli/internal/paging" +) + +type revisionListInput struct { + PageSize uint32 + PageToken string +} + +type revisionListResult struct { + Revisions []*revisionView `json:"revisions"` + NextPageToken string `json:"next_page_token,omitempty"` +} + +func revisionListCmd(a *app.App) *cobra.Command { + var in revisionListInput + cmd := &cobra.Command{ + Use: "list", + Short: "List policy revisions, newest first", + Long: "List the policy revisions of the tenant, newest first, with the author, the source, the change " + + "direction and the publish message. One page is returned per invocation, so follow " + + "--page-token to read the next page.", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + client, err := a.ControlPlane() + if err != nil { + return err + } + res, err := runRevisionList(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), in) + if err != nil { + return err + } + return a.Output.Print(res) + }, + } + cmd.Flags().Uint32Var(&in.PageSize, "limit", 0, "page size; server default when 0") + cmd.Flags().StringVar(&in.PageToken, "page-token", "", "continuation token from a prior response") + return cmd +} + +func runRevisionList( + ctx context.Context, + client policyv1grpc.PolicyServiceClient, + in revisionListInput, +) (*revisionListResult, error) { + req := &policyv1.ListPolicyRevisionsRequest{} + req.SetPagination(paging.NewPaginationRequest(in.PageSize, in.PageToken)) + res, err := client.ListPolicyRevisions(ctx, req) + if err != nil { + return nil, fmt.Errorf("policy revision list: %w", err) + } + out := &revisionListResult{ + Revisions: make([]*revisionView, 0, len(res.GetRevisions())), + NextPageToken: res.GetPagination().GetNextPageToken(), + } + for _, r := range res.GetRevisions() { + out.Revisions = append(out.Revisions, newRevisionView(r)) + } + return out, nil +} + +func (r *revisionListResult) RenderJSON() ([]byte, error) { + return json.MarshalIndent(r, "", " ") +} + +func (r *revisionListResult) RenderTable() string { + now := time.Now() + rows := make([][]string, 0, len(r.Revisions)) + for _, rev := range r.Revisions { + rows = append(rows, []string{ + fmt.Sprintf("%d", rev.Revision), humanTimeCell(rev.PublishedAt, now), emptyDash(rev.Author), + rev.Source, rev.Direction, emptyDash(rev.Message), + }) + } + t := table.New(). + Title("Policy revisions"). + Headers("REV", "PUBLISHED", "BY", "SOURCE", "DIRECTION", "MESSAGE"). + Rows(rows...). + EmptyMessage("No policy revisions. The tenant has not published a policy yet.") + if r.NextPageToken != "" { + t = t.Footer("More available: --page-token " + r.NextPageToken) + } + return t.Render() +} + +func (r *revisionListResult) RenderPlain() string { + var b strings.Builder + b.WriteString("revision\tpublished_at\tauthor\tsource\tdirection\tchange_id\tmessage") + for _, rev := range r.Revisions { + fmt.Fprintf(&b, "\n%d\t%s\t%s\t%s\t%s\t%s\t%s", + rev.Revision, rev.Published, rev.Author, rev.Source, rev.Direction, rev.ChangeID, rev.Message) + } + return b.String() +} + +type revisionShowResult struct { + Revision *revisionView + Document any + YAML string +} + +func revisionShowCmd(a *app.App) *cobra.Command { + return &cobra.Command{ + Use: "show REVISION", + Short: "Show one policy revision with its policy settings", + Long: "Show one policy revision: who published it, when, from which change, its change direction, " + + "and the policy settings document at that revision.", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + revision, err := parseRevision(args[0]) + if err != nil { + return err + } + client, err := a.ControlPlane() + if err != nil { + return err + } + res, err := runRevisionShow(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), revision) + if err != nil { + return err + } + return a.Output.Print(res) + }, + } +} + +func parseRevision(text string) (uint64, error) { + n, err := strconv.ParseUint(strings.TrimPrefix(text, "rev"), 10, 64) + if err != nil || n == 0 { + return 0, invalidInputError(fmt.Errorf("revision %q is not a revision number", text), + "Give a number from: safedep policy revision list") + } + return n, nil +} + +func runRevisionShow(ctx context.Context, client policyv1grpc.PolicyServiceClient, revision uint64) (*revisionShowResult, error) { + req := &policyv1.GetPolicyRevisionRequest{} + req.SetRevision(revision) + res, err := client.GetPolicyRevision(ctx, req) + if err != nil { + return nil, fmt.Errorf("policy revision show: %w", err) + } + doc, err := cloudpolicy.PolicyMap(res.GetPolicy()) + if err != nil { + return nil, err + } + text, err := cloudpolicy.MarshalPolicy(res.GetPolicy(), "") + if err != nil { + return nil, err + } + view := newRevisionView(res.GetRevision()) + if view == nil { + return nil, fmt.Errorf("policy revision show: invalid response: revision %d is missing", revision) + } + return &revisionShowResult{Revision: view, Document: doc, YAML: string(trimNewline(text))}, nil +} + +func (r *revisionShowResult) RenderJSON() ([]byte, error) { + return json.MarshalIndent(struct { + Revision *revisionView `json:"revision"` + Policy any `json:"policy"` + }{Revision: r.Revision, Policy: r.Document}, "", " ") +} + +func (r *revisionShowResult) RenderTable() string { + rev := r.Revision + change := "-" + if rev.ChangeID != "" { + change = rev.ChangeID + sep + "safedep policy change show " + rev.ChangeID + } + rows := [][2]string{ + {"Revision", rev.summary(time.Now())}, + {"Source", rev.Source}, + {"Direction", rev.Direction}, + {"Change", change}, + } + return cloudpolicy.KeyValues(rows) + "\n\nPolicy settings\n" + r.YAML +} + +func (r *revisionShowResult) RenderPlain() string { + rev := r.Revision + return fmt.Sprintf("revision\t%d\npublished_at\t%s\nauthor\t%s\nsource\t%s\ndirection\t%s\nchange_id\t%s\nmessage\t%s\n%s", + rev.Revision, rev.Published, rev.Author, rev.Source, rev.Direction, rev.ChangeID, rev.Message, r.YAML) +} diff --git a/internal/cmd/policy/revision_test.go b/internal/cmd/policy/revision_test.go new file mode 100644 index 0000000..6510739 --- /dev/null +++ b/internal/cmd/policy/revision_test.go @@ -0,0 +1,59 @@ +package policy + +import ( + "context" + "testing" + + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + "github.com/safedep/cli/internal/cloudpolicy/mocks" +) + +func TestRunRevisionList(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + res := &policyv1.ListPolicyRevisionsResponse{} + res.SetRevisions([]*policyv1.PolicyRevision{revision(51, "delete r_80b"), revision(50, "extend r_77e")}) + client.EXPECT().ListPolicyRevisions(mock.Anything, mock.MatchedBy(func(r *policyv1.ListPolicyRevisionsRequest) bool { + return r.GetPagination().GetPageSize() == 5 + })).Return(res, nil) + + got, err := runRevisionList(context.Background(), client, revisionListInput{PageSize: 5}) + require.NoError(t, err) + table := got.RenderTable() + assert.Contains(t, table, "delete r_80b") + assert.Contains(t, table, "CLI") + assert.Contains(t, table, "TIGHTENS") + assert.Contains(t, got.RenderPlain(), "51\t") +} + +func TestRunRevisionShow(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + res := &policyv1.GetPolicyRevisionResponse{} + rev := revision(47, "payments: fail on medium") + rev.SetChangeId("18") + res.SetRevision(rev) + res.SetPolicy(headPolicy()) + client.EXPECT().GetPolicyRevision(mock.Anything, mock.Anything).Return(res, nil) + + got, err := runRevisionShow(context.Background(), client, 47) + require.NoError(t, err) + table := got.RenderTable() + assert.Contains(t, table, "18 · safedep policy change show 18") + assert.Contains(t, table, "Policy settings\nbase:") + b, err := got.RenderJSON() + require.NoError(t, err) + assert.Contains(t, string(b), `"change_id": "18"`) +} + +func TestParseRevision(t *testing.T) { + n, err := parseRevision("47") + require.NoError(t, err) + assert.Equal(t, uint64(47), n) + _, err = parseRevision("0") + assert.Error(t, err) + _, err = parseRevision("head") + assert.Error(t, err) +} diff --git a/internal/cmd/policy/rule_create.go b/internal/cmd/policy/rule_create.go new file mode 100644 index 0000000..f842a6f --- /dev/null +++ b/internal/cmd/policy/rule_create.go @@ -0,0 +1,345 @@ +package policy + +import ( + "bufio" + "bytes" + "context" + "errors" + "fmt" + "io" + "os" + "slices" + "strings" + "time" + + policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" + corev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/core/v1" + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/safedep/dry/tui" + "github.com/safedep/dry/tui/humanize" + "github.com/spf13/cobra" + "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" +) + +const ( + // maxBulkRules is the limit of rule operations in one change. + maxBulkRules = 1000 + scopeAll = "all" +) + +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 +} + +type ruleCreateResult struct { + Rules []*policyv1.PackageRuleWithAttributes + Revision uint64 +} + +func ruleCreateCmd(a *app.App) *cobra.Command { + var in ruleCreateInput + cmd := &cobra.Command{ + Use: "create (--block | --trust) [PURL]", + Short: "Create a trust entry or block entries, and publish at once", + Long: "Create a package rule and publish it at once as a new policy revision. A block entry " + + "stops new installs of the packages that it selects. It can select a prefix that ends with " + + "/* or .*, as in pkg:npm/@acme/*. Use --block -f FILE to block up to 1,000 selectors in one " + + "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. " + + "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 { + return err + } + if len(args) == 1 { + in.Selector = args[0] + } + return validateRuleCreate(in) + }, + RunE: func(cmd *cobra.Command, _ []string) error { + rules, err := buildRuleCreates(in, cmd.InOrStdin(), time.Now()) + if err != nil { + return err + } + client, err := a.ControlPlane() + if err != nil { + return err + } + announceRuleCreate(in, rules) + res, err := runRuleCreate(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), in, rules) + if err != nil { + return err + } + reportRuleCreate(in, res, time.Now()) + return nil + }, + } + f := cmd.Flags() + f.BoolVar(&in.Block, "block", false, "create block entries") + f.BoolVar(&in.Trust, "trust", false, "create a trust entry") + f.StringVarP(&in.File, "file", "f", "", "with --block: a file of selectors, one on each line; - reads 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: the verdicts to waive ("+strings.Join(trustScopeTokens(), ", ")+", or all); repeatable") + f.StringVar(&in.Reason, "reason", "", "why the rule exists (required); tools show it in a block message") + 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") + f.StringVar(&in.Expires, "expires", "", "when the rule stops: a duration, as in 30d, or a date (required with --trust)") + f.StringVar(&in.Override, "override", "", "attach the rule to the policy override with this name; the policy base when empty") + f.StringVarP(&in.Message, "message", "m", "", "the publish message; the server writes one when it is empty") + return cmd +} + +func validateRuleCreate(in ruleCreateInput) error { + switch { + case in.Block == in.Trust: + return invalidInputError(errors.New("give one of --block or --trust"), + "Block: safedep policy rule create --block pkg:npm/name --reason TEXT") + case in.File != "" && in.Selector != "": + return invalidInputError(errors.New("give a PURL or --file, not both"), "Use --file for a list of selectors") + case in.File == "" && in.Selector == "": + return invalidInputError(errors.New("give the PURL of the package"), + "As in: safedep policy rule create --block pkg:npm/evil --reason TEXT") + case in.File != "" && in.Trust: + return invalidInputError(errors.New("only block entries can come from a file"), + "Create each trust entry with its own command") + case in.File != "" && in.Vers != "": + return invalidInputError(errors.New("--vers applies to one PURL: in a file, write the range after the PURL"), + "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: + return invalidInputError(errors.New("a trust entry needs --scope"), + "Name each verdict that it waives: --scope "+strings.Join(trustScopeTokens(), ", --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") + } + _, err := expandScopes(in.Scopes) + return err +} + +// 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. +func expandScopes(values []string) ([]corev1.TrustScope, error) { + var out []corev1.TrustScope + for _, v := range values { + if strings.EqualFold(strings.TrimSpace(v), scopeAll) { + out = out[:0] + for _, token := range trustScopeTokens() { + scope, err := parseTrustScope(token) + if err != nil { + return nil, err + } + out = append(out, scope) + } + return out, nil + } + scope, err := parseTrustScope(v) + if err != nil { + return nil, err + } + if !slices.Contains(out, scope) { + out = append(out, scope) + } + } + return out, nil +} + +// buildRuleCreates checks every selector and builds the rules, before any +// RPC, so one bad line in a file stops the whole create. +func buildRuleCreates(in ruleCreateInput, stdin io.Reader, now time.Time) ([]*policyv1.PackageRuleCreate, error) { + if err := validateRuleCreate(in); err != nil { + return nil, err + } + effect := corev1.Effect_EFFECT_BLOCK + if in.Trust { + effect = corev1.Effect_EFFECT_TRUST + } + scopes, err := expandScopes(in.Scopes) + if err != nil { + return nil, err + } + var expires *timestamppb.Timestamp + if in.Expires != "" { + t, err := parseExpiry(in.Expires, now) + if err != nil { + return nil, invalidInputError(err, "Use a duration, as in 30d, or a date, as in 2027-01-26") + } + expires = timestamppb.New(t) + } + + entries := []selectorEntry{{purl: in.Selector, vers: in.Vers}} + if in.File != "" { + entries, err = readSelectorFile(in.File, stdin) + if err != nil { + return nil, err + } + } + + creates := make([]*policyv1.PackageRuleCreate, 0, len(entries)) + for _, e := range entries { + selector, err := buildSelector(e.purl, e.vers, effect) + if err != nil { + if e.line > 0 { + err = fmt.Errorf("%s line %d: %w", in.File, e.line, err) + } + return nil, invalidInputError(err, "Fix the selector and run the command again") + } + rule := &corev1.PackageRule{} + rule.SetSelector(selector) + rule.SetEffect(effect) + rule.SetScopes(scopes) + rule.SetReason(in.Reason) + if expires != nil { + rule.SetExpiresAt(expires) + } + create := &policyv1.PackageRuleCreate{} + create.SetRule(rule) + create.SetTicket(in.Ticket) + create.SetRequestedBy(in.RequestedBy) + creates = append(creates, create) + } + return creates, nil +} + +type selectorEntry struct { + purl string + vers string + line int +} + +// readSelectorFile reads one selector on each line: a PURL and an optional +// range after a space. A line that starts with # and an empty line are +// skipped. +func readSelectorFile(path string, stdin io.Reader) ([]selectorEntry, error) { + r := stdin + if path != "-" { + data, err := os.ReadFile(path) + if err != nil { + return nil, invalidInputError(fmt.Errorf("read %s: %w", path, err), "Check the path of --file") + } + r = bytes.NewReader(data) + } + var entries []selectorEntry + scanner := bufio.NewScanner(r) + for n := 1; scanner.Scan(); n++ { + line := strings.TrimSpace(scanner.Text()) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + fields := strings.Fields(line) + if len(fields) > 2 { + return nil, invalidInputError(fmt.Errorf("%s line %d: write a PURL and an optional range, not %d values", path, n, len(fields)), + "Write each line as: PURL [RANGE]") + } + entry := selectorEntry{purl: fields[0], line: n} + if len(fields) == 2 { + entry.vers = fields[1] + } + entries = append(entries, entry) + if len(entries) > maxBulkRules { + return nil, invalidInputError(fmt.Errorf("%s has more than %d selectors", path, maxBulkRules), + fmt.Sprintf("Split the file into parts of %d lines or fewer", maxBulkRules)) + } + } + if err := scanner.Err(); err != nil { + return nil, fmt.Errorf("read %s: %w", path, err) + } + if len(entries) == 0 { + return nil, invalidInputError(fmt.Errorf("%s has no selectors", path), "Write one PURL on each line") + } + return entries, nil +} + +func runRuleCreate( + ctx context.Context, + client policyv1grpc.PolicyServiceClient, + in ruleCreateInput, + creates []*policyv1.PackageRuleCreate, +) (*ruleCreateResult, error) { + if in.Override != "" { + head, err := getPolicy(ctx, client) + if err != nil { + return nil, err + } + o, err := findOverride(head.GetPolicy(), in.Override) + if err != nil { + return nil, err + } + for _, c := range creates { + c.SetOverrideId(o.GetOverrideId()) + } + } + req := &policyv1.CreatePackageRulesRequest{} + req.SetRules(creates) + req.SetMessage(in.Message) + res, err := client.CreatePackageRules(ctx, req) + if err != nil { + return nil, mapRuleError("create", "", err) + } + return &ruleCreateResult{Rules: res.GetRules(), Revision: res.GetRevision().GetRevision()}, nil +} + +// announceRuleCreate says what the rule does before the publish. +func announceRuleCreate(in ruleCreateInput, creates []*policyv1.PackageRuleCreate) { + if in.Override == "" { + tui.Info("Applies to every endpoint and project of the tenant (base). Use --override NAME to narrow it.") + } else { + tui.Info("Applies to the subjects that policy override %q selects.", in.Override) + } + if in.Block { + 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), purl) + } + tui.Warning("Verified malware stays blocked") +} + +func scopeEffect(scope corev1.TrustScope) string { + switch scope { + case corev1.TrustScope_TRUST_SCOPE_MALWARE: + return "a malware verdict that is not verified" + case corev1.TrustScope_TRUST_SCOPE_COOLDOWN: + return "the dependency cooldown" + case corev1.TrustScope_TRUST_SCOPE_VULNERABILITY: + return "the vulnerability findings of a scan gate" + default: + return "the verdicts of scope " + scope.String() + } +} + +func reportRuleCreate(in ruleCreateInput, res *ruleCreateResult, now time.Time) { + if len(res.Rules) == 1 { + tui.Success("rule %s created%srevision %d published", res.Rules[0].GetRule().GetRuleId(), sep, res.Revision) + } else { + tui.Success("%d rules created%srevision %d published", len(res.Rules), sep, res.Revision) + } + if in.Trust && len(res.Rules) == 1 { + if expires := timeOf(res.Rules[0].GetRule().GetExpiresAt()); expires != nil { + tui.Info(" The rule expires %s (%s)", humanize.Time(*expires, now), expires.Format(time.DateOnly)) + } + } + tui.Info(" Each endpoint applies it after its next policy fetch. Pull request checks apply it at once.") + tui.Info(" Endpoints that have not applied it yet: safedep endpoint list --applied-revision '<%d'", res.Revision) +} diff --git a/internal/cmd/policy/rule_list.go b/internal/cmd/policy/rule_list.go new file mode 100644 index 0000000..d84fad6 --- /dev/null +++ b/internal/cmd/policy/rule_list.go @@ -0,0 +1,319 @@ +package policy + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "time" + + policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" + corev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/core/v1" + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/safedep/dry/tui/humanize" + "github.com/safedep/dry/tui/table" + "github.com/spf13/cobra" + "google.golang.org/protobuf/types/known/durationpb" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" + "github.com/safedep/cli/internal/duration" + "github.com/safedep/cli/internal/paging" + "github.com/safedep/cli/internal/tui" +) + +const baseAttachment = "base" + +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"` + 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 +} + +// newRuleView translates a rule. names maps override ids to names. A rule +// whose override is not in names shows the override id. +func newRuleView(r *policyv1.PackageRuleWithAttributes, names map[string]string) ruleView { + rule := r.GetRule() + expires := timeOf(rule.GetExpiresAt()) + v := ruleView{ + ID: rule.GetRuleId(), + Purl: rule.GetSelector().GetPurl(), + Vers: rule.GetSelector().GetVers(), + Effect: tui.EnumToken(rule.GetEffect().String(), effectPrefix), + Scopes: scopeTokens(rule.GetScopes()), + Reason: rule.GetReason(), + Ticket: r.GetTicket(), + RequestedBy: r.GetRequestedBy(), + OverrideID: r.GetOverrideId(), + AttachesTo: baseAttachment, + CreatedBy: actorName(r.GetCreatedBy()), + AddedRevision: r.GetAddedRevision(), + RemovedRevision: r.GetRemovedRevision(), + ExpiresAt: cloudpolicy.RFC3339(expires), + CreatedAt: cloudpolicy.RFC3339(timeOf(r.GetCreatedAt())), + UpdatedAt: cloudpolicy.RFC3339(timeOf(r.GetUpdatedAt())), + expires: expires, + } + if id := r.GetOverrideId(); id != "" { + v.AttachesTo = "override " + id + if name, ok := names[id]; ok { + v.AttachesTo = fmt.Sprintf("override %q", name) + } + } + return v +} + +func (v ruleView) selector() string { + if v.Vers == "" { + return v.Purl + } + return v.Purl + " " + v.Vers +} + +func (v ruleView) expiresCell(now time.Time) string { + if v.expires == nil { + return "never" + } + return humanize.Time(*v.expires, now) +} + +type ruleListInput struct { + Effect string + Scope string + SelectorPrefix string + Expiring time.Duration + Override string + Base bool + AtRevision uint64 + PageSize uint32 + PageToken string +} + +type ruleListResult struct { + Rules []ruleView `json:"rules"` + NextPageToken string `json:"next_page_token,omitempty"` +} + +func ruleListCmd(a *app.App) *cobra.Command { + var in ruleListInput + cmd := &cobra.Command{ + Use: "list", + Short: "List package rules", + Long: "List the active package rules at head, or at an older policy revision with --at-revision. " + + "Filter by effect, trust scope, selector prefix, expiry, or the policy override that a rule " + + "attaches to. One page is returned per invocation, so follow --page-token to read the next page.", + Args: func(cmd *cobra.Command, args []string) error { + if err := cobra.NoArgs(cmd, args); err != nil { + return err + } + _, err := ruleListFilters(&in, "") + return err + }, + RunE: func(cmd *cobra.Command, _ []string) error { + client, err := a.ControlPlane() + if err != nil { + return err + } + res, err := runRuleList(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), &in) + if err != nil { + return err + } + return a.Output.Print(res) + }, + } + f := cmd.Flags() + f.StringVar(&in.Effect, "effect", "", "filter: trust or block") + f.StringVar(&in.Scope, "scope", "", "filter: trust scope ("+strings.Join(trustScopeTokens(), ", ")+")") + f.StringVar(&in.SelectorPrefix, "selector-prefix", "", "filter: rules whose selector starts with this text, as in pkg:npm/") + f.Var(duration.NewValue(&in.Expiring, 0), "expiring", "filter: rules that expire within this time from now, as in 7d") + f.StringVar(&in.Override, "override", "", "filter: rules that attach to the policy override with this name") + f.BoolVar(&in.Base, "base", false, "filter: rules that attach to the policy base") + f.Uint64Var(&in.AtRevision, "at-revision", 0, "list the rules that were active at this policy revision") + f.Uint32Var(&in.PageSize, "limit", 0, "page size; server default when 0") + f.StringVar(&in.PageToken, "page-token", "", "continuation token from a prior response") + return cmd +} + +func trustScopeTokens() []string { + return tui.EnumTokens(corev1.TrustScope_name, trustScopePrefix) +} + +func parseEffect(token string) (corev1.Effect, error) { + n, ok := tui.ParseEnumToken(corev1.Effect_name, effectPrefix, token) + if !ok { + return 0, invalidInputError(fmt.Errorf("unknown --effect value %q: use trust or block", token), + "Retry with --effect trust or --effect block") + } + 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 { + return 0, invalidInputError( + fmt.Errorf("unknown trust scope %q: allowed values are %s", token, strings.Join(trustScopeTokens(), ", ")), + "Retry with one of: "+strings.Join(trustScopeTokens(), ", ")) + } + return corev1.TrustScope(n), nil +} + +// ruleListFilters builds the filters. overrideID is the id of in.Override, +// which the caller resolves. +func ruleListFilters(in *ruleListInput, overrideID string) (*policyv1.ListPackageRulesRequest_Filters, error) { + if in.Override != "" && in.Base { + return nil, invalidInputError(fmt.Errorf("--override and --base select different rules"), "Use one of them") + } + filters := &policyv1.ListPackageRulesRequest_Filters{} + set := false + if in.Effect != "" { + effect, err := parseEffect(in.Effect) + if err != nil { + return nil, err + } + filters.SetEffect(effect) + set = true + } + if in.Scope != "" { + scope, err := parseTrustScope(in.Scope) + if err != nil { + return nil, err + } + filters.SetScope(scope) + set = true + } + if in.SelectorPrefix != "" { + filters.SetSelectorPrefix(in.SelectorPrefix) + set = true + } + if in.Expiring < 0 { + return nil, invalidInputError(fmt.Errorf("--expiring must not be negative"), "Use a duration such as 7d") + } + if in.Expiring > 0 { + filters.SetExpiringWithin(durationpb.New(in.Expiring)) + set = true + } + if in.Base { + filters.SetOverrideId("") + set = true + } + if overrideID != "" { + filters.SetOverrideId(overrideID) + set = true + } + if in.AtRevision > 0 { + filters.SetAtRevision(in.AtRevision) + set = true + } + if !set { + return nil, nil + } + return filters, nil +} + +func runRuleList(ctx context.Context, client policyv1grpc.PolicyServiceClient, in *ruleListInput) (*ruleListResult, error) { + var names map[string]string + overrideID := "" + if in.Override != "" { + head, err := getPolicy(ctx, client) + if err != nil { + return nil, err + } + o, err := findOverride(head.GetPolicy(), in.Override) + if err != nil { + return nil, err + } + overrideID = o.GetOverrideId() + names = overrideNames(head.GetPolicy()) + } + filters, err := ruleListFilters(in, overrideID) + if err != nil { + return nil, err + } + req := &policyv1.ListPackageRulesRequest{} + req.SetPagination(paging.NewPaginationRequest(in.PageSize, in.PageToken)) + if filters != nil { + req.SetFilters(filters) + } + res, err := client.ListPackageRules(ctx, req) + if err != nil { + return nil, fmt.Errorf("policy rule list: %w", err) + } + + if names == nil && attachesToOverride(res.GetRules()) { + head, err := getPolicy(ctx, client) + if err != nil { + return nil, err + } + names = overrideNames(head.GetPolicy()) + } + out := &ruleListResult{ + Rules: make([]ruleView, 0, len(res.GetRules())), + NextPageToken: res.GetPagination().GetNextPageToken(), + } + for _, r := range res.GetRules() { + out.Rules = append(out.Rules, newRuleView(r, names)) + } + return out, nil +} + +func attachesToOverride(rules []*policyv1.PackageRuleWithAttributes) bool { + for _, r := range rules { + if r.GetOverrideId() != "" { + return true + } + } + return false +} + +func (r *ruleListResult) RenderJSON() ([]byte, error) { + return json.MarshalIndent(r, "", " ") +} + +func (r *ruleListResult) RenderTable() string { + now := time.Now() + rows := make([][]string, 0, len(r.Rules)) + for _, rule := range r.Rules { + rows = append(rows, []string{ + rule.ID, rule.selector(), rule.Effect, emptyDash(strings.Join(rule.Scopes, ",")), + rule.Reason, emptyDash(rule.RequestedBy), rule.AttachesTo, rule.expiresCell(now), + }) + } + t := table.New(). + Title("Package rules"). + Headers("RULE", "SELECTOR", "EFFECT", "SCOPE", "REASON", "REQUESTED BY", "ATTACHES TO", "EXPIRES"). + Rows(rows...). + EmptyMessage("No package rules match. Block a package with: safedep policy rule create --block pkg:npm/name --reason TEXT") + if len(rows) > 0 { + footer := fmt.Sprintf("%d %s", len(rows), plural(len(rows), "rule", "rules")) + if r.NextPageToken != "" { + footer += ". More available: --page-token " + r.NextPageToken + } + t = t.Footer(footer) + } + return t.Render() +} + +func (r *ruleListResult) RenderPlain() string { + var b strings.Builder + b.WriteString("rule_id\tpurl\tvers\teffect\tscopes\treason\trequested_by\toverride_id\texpires_at") + for _, rule := range r.Rules { + fmt.Fprintf(&b, "\n%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s", + rule.ID, rule.Purl, rule.Vers, rule.Effect, strings.Join(rule.Scopes, ","), + rule.Reason, rule.RequestedBy, rule.OverrideID, rule.ExpiresAt) + } + return b.String() +} diff --git a/internal/cmd/policy/rule_ops.go b/internal/cmd/policy/rule_ops.go new file mode 100644 index 0000000..e05d1d3 --- /dev/null +++ b/internal/cmd/policy/rule_ops.go @@ -0,0 +1,263 @@ +package policy + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + "time" + + policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/safedep/dry/tui" + "github.com/spf13/cobra" + "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" +) + +type ruleShowResult struct { + Rule ruleView `json:"rule"` +} + +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 " + + "policy override that it attaches to, its expiry, and the revisions that added and removed it. " + + "A block message of a tool cites the rule id.", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + client, err := a.ControlPlane() + if err != nil { + return err + } + res, err := runRuleShow(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), args[0]) + if err != nil { + return err + } + return a.Output.Print(res) + }, + } +} + +func runRuleShow(ctx context.Context, client policyv1grpc.PolicyServiceClient, id string) (*ruleShowResult, error) { + req := &policyv1.GetPackageRuleRequest{} + req.SetRuleId(id) + res, err := client.GetPackageRule(ctx, req) + if err != nil { + return nil, mapRuleError("show", id, err) + } + var names map[string]string + if res.GetRule().GetOverrideId() != "" { + head, err := getPolicy(ctx, client) + if err != nil { + return nil, err + } + names = overrideNames(head.GetPolicy()) + } + return &ruleShowResult{Rule: newRuleView(res.GetRule(), names)}, nil +} + +func (r *ruleShowResult) RenderJSON() ([]byte, error) { + return json.MarshalIndent(r, "", " ") +} + +func (r *ruleShowResult) RenderTable() string { + v := r.Rule + now := time.Now() + removed := "active" + if v.RemovedRevision > 0 { + removed = fmt.Sprintf("removed in revision %d", v.RemovedRevision) + } + expires := v.expiresCell(now) + if v.expires != nil { + expires += " (" + v.expires.Format(time.DateOnly) + ")" + } + return cloudpolicy.KeyValues([][2]string{ + {"Rule", v.ID}, + {"Selector", v.selector()}, + {"Effect", v.Effect}, + {"Scope", emptyDash(strings.Join(v.Scopes, ", "))}, + {"Reason", v.Reason}, + {"Ticket", emptyDash(v.Ticket)}, + {"Requested by", emptyDash(v.RequestedBy)}, + {"Attaches to", v.AttachesTo}, + {"Expires", expires}, + {"Created by", emptyDash(v.CreatedBy)}, + {"Revisions", fmt.Sprintf("added in revision %d%s%s", v.AddedRevision, sep, removed)}, + }) +} + +func (r *ruleShowResult) RenderPlain() string { + v := r.Rule + return strings.Join([]string{ + "rule_id\t" + v.ID, + "purl\t" + v.Purl, + "vers\t" + v.Vers, + "effect\t" + v.Effect, + "scopes\t" + strings.Join(v.Scopes, ","), + "reason\t" + v.Reason, + "ticket\t" + v.Ticket, + "requested_by\t" + v.RequestedBy, + "override_id\t" + v.OverrideID, + "expires_at\t" + v.ExpiresAt, + "created_by\t" + v.CreatedBy, + fmt.Sprintf("added_revision\t%d", v.AddedRevision), + fmt.Sprintf("removed_revision\t%d", v.RemovedRevision), + }, "\n") +} + +type ruleUpdateInput struct { + Reason string + Expires string + Ticket string + RequestedBy string + Message string + changed func(name string) bool +} + +func ruleUpdateCmd(a *app.App) *cobra.Command { + var in ruleUpdateInput + cmd := &cobra.Command{ + Use: "update RULE", + Short: "Change the reason, expiry, ticket or requester of a package rule", + Long: "Change a package rule and publish the change at once as a new policy revision. A rule never " + + "changes its selector, effect or trust scopes: delete it and create another. A later expiry " + + "of a trust entry loosens the policy.", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + in.changed = cmd.Flags().Changed + update, err := buildRuleUpdate(args[0], in, time.Now()) + if err != nil { + return err + } + client, err := a.ControlPlane() + if err != nil { + return err + } + res, err := runRuleUpdate(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), update, in.Message) + if err != nil { + return err + } + msg := fmt.Sprintf("rule %s updated", args[0]) + if update.HasExpiresAt() { + msg = fmt.Sprintf("rule %s now expires on %s", args[0], update.GetExpiresAt().AsTime().Format(time.DateOnly)) + } + tui.Success("%s%srevision %d published", msg, sep, res.GetRevision().GetRevision()) + return nil + }, + } + f := cmd.Flags() + f.StringVar(&in.Reason, "reason", "", "the new reason") + f.StringVar(&in.Expires, "expires", "", "the new expiry: a duration from now, as in 90d, or a date") + f.StringVar(&in.Ticket, "ticket", "", "the new ticket or incident reference") + f.StringVar(&in.RequestedBy, "requested-by", "", "the new team or person that asked for the rule") + f.StringVarP(&in.Message, "message", "m", "", "the publish message; the server writes one when it is empty") + return cmd +} + +func buildRuleUpdate(id string, in ruleUpdateInput, now time.Time) (*policyv1.PackageRuleUpdate, error) { + changed := in.changed + if changed == nil { + changed = func(string) bool { return false } + } + update := &policyv1.PackageRuleUpdate{} + update.SetRuleId(id) + set := false + if changed("reason") { + if strings.TrimSpace(in.Reason) == "" { + return nil, invalidInputError(errors.New("--reason must not be empty"), "Say why the rule exists") + } + update.SetReason(in.Reason) + set = true + } + if changed("expires") { + t, err := parseExpiry(in.Expires, now) + if err != nil { + return nil, invalidInputError(err, "Use a duration, as in 90d, or a date, as in 2027-01-26") + } + update.SetExpiresAt(timestamppb.New(t)) + set = true + } + if changed("ticket") { + update.SetTicket(in.Ticket) + set = true + } + if changed("requested-by") { + update.SetRequestedBy(in.RequestedBy) + set = true + } + if !set { + return nil, invalidInputError(errors.New("give at least one of --reason, --expires, --ticket or --requested-by"), + "As in: safedep policy rule update "+id+" --expires 90d") + } + return update, nil +} + +func runRuleUpdate( + ctx context.Context, + client policyv1grpc.PolicyServiceClient, + update *policyv1.PackageRuleUpdate, + message string, +) (*policyv1.UpdatePackageRuleResponse, error) { + req := &policyv1.UpdatePackageRuleRequest{} + req.SetUpdate(update) + req.SetMessage(message) + res, err := client.UpdatePackageRule(ctx, req) + if err != nil { + return nil, mapRuleError("update", update.GetRuleId(), err) + } + return res, nil +} + +func ruleDeleteCmd(a *app.App) *cobra.Command { + var reason, message string + cmd := &cobra.Command{ + Use: "delete RULE --reason TEXT", + Short: "Delete a package rule and publish at once", + Long: "Delete a package rule and publish the change at once as a new policy revision. The rule " + + "stays in the history of the revisions. The delete of a block entry loosens the policy.", + Args: func(cmd *cobra.Command, args []string) error { + if err := cobra.ExactArgs(1)(cmd, args); err != nil { + return err + } + if strings.TrimSpace(reason) == "" { + return invalidInputError(errors.New("--reason is required"), "Say why the rule goes, as in --reason \"no longer needed\"") + } + return nil + }, + RunE: func(cmd *cobra.Command, args []string) error { + client, err := a.ControlPlane() + if err != nil { + return err + } + rev, err := runRuleDelete(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), args[0], reason, message) + if err != nil { + return err + } + tui.Success("rule %s deleted%srevision %d published", args[0], sep, rev) + return nil + }, + } + cmd.Flags().StringVar(&reason, "reason", "", "why the rule goes (required)") + cmd.Flags().StringVarP(&message, "message", "m", "", "the publish message; the server writes one when it is empty") + return cmd +} + +func runRuleDelete(ctx context.Context, client policyv1grpc.PolicyServiceClient, id, reason, message string) (uint64, error) { + del := &policyv1.PackageRuleDelete{} + del.SetRuleId(id) + del.SetReason(reason) + req := &policyv1.DeletePackageRuleRequest{} + req.SetDelete(del) + req.SetMessage(message) + res, err := client.DeletePackageRule(ctx, req) + if err != nil { + return 0, mapRuleError("delete", id, err) + } + return res.GetRevision().GetRevision(), nil +} diff --git a/internal/cmd/policy/rule_test.go b/internal/cmd/policy/rule_test.go new file mode 100644 index 0000000..5933984 --- /dev/null +++ b/internal/cmd/policy/rule_test.go @@ -0,0 +1,373 @@ +package policy + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" + + corev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/core/v1" + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/safedep/dry/usefulerror" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/safedep/cli/internal/cloudpolicy/mocks" +) + +func TestValidateRuleCreate(t *testing.T) { + block := ruleCreateInput{Block: true, Selector: "pkg:npm/evil", Reason: "IR-2291"} + trust := ruleCreateInput{Trust: true, Selector: "pkg:pypi/foo@1.0.3", Reason: "FP", Scopes: []string{"malware"}, Expires: "30d"} + tests := []struct { + name string + mutate func(*ruleCreateInput) + base ruleCreateInput + want string + }{ + {"block", func(*ruleCreateInput) {}, block, ""}, + {"trust", func(*ruleCreateInput) {}, trust, ""}, + {"neither", func(in *ruleCreateInput) { in.Block = false }, block, "give one of --block or --trust"}, + {"both", func(in *ruleCreateInput) { in.Trust = true }, block, "give one of --block or --trust"}, + {"no selector", func(in *ruleCreateInput) { in.Selector = "" }, block, "give the PURL"}, + {"selector and file", func(in *ruleCreateInput) { in.File = "x" }, block, "not both"}, + {"trust from file", func(in *ruleCreateInput) { in.Selector, in.File = "", "x" }, trust, "only block entries can come from a file"}, + {"vers with file", func(in *ruleCreateInput) { in.Selector, in.File, in.Vers = "", "x", ">=1" }, block, "--vers applies to one PURL"}, + {"no reason", func(in *ruleCreateInput) { in.Reason = " " }, block, "--reason is required"}, + {"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"`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + in := tt.base + tt.mutate(&in) + err := validateRuleCreate(in) + if tt.want == "" { + require.NoError(t, err) + return + } + assert.ErrorContains(t, err, tt.want) + }) + } +} + +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) + for _, s := range all { + assert.NotEqual(t, corev1.TrustScope_TRUST_SCOPE_UNSPECIFIED, s) + } + + some, err := expandScopes([]string{"malware", "COOLDOWN", "malware"}) + require.NoError(t, err) + assert.Equal(t, []corev1.TrustScope{corev1.TrustScope_TRUST_SCOPE_MALWARE, corev1.TrustScope_TRUST_SCOPE_COOLDOWN}, some) +} + +func TestBuildSelector(t *testing.T) { + block, trust := corev1.Effect_EFFECT_BLOCK, corev1.Effect_EFFECT_TRUST + tests := []struct { + purl, vers string + effect corev1.Effect + wantVers string + wantErr string + }{ + {purl: "pkg:npm/evil", vers: ">=1.2.0", effect: block, wantVers: "vers:npm/>=1.2.0"}, + {purl: "pkg:npm/evil", vers: "vers:npm/>=1.2.0|<2.0.0", effect: block, wantVers: "vers:npm/>=1.2.0|<2.0.0"}, + {purl: "pkg:npm/@acme/*", effect: block}, + {purl: "pkg:maven/org.apache.*", effect: block}, + {purl: "pkg:nuget/Microsoft.*", effect: block}, + {purl: "pkg:npm/*", effect: block}, + {purl: "pkg:pypi/foo@1.0.3", effect: trust}, + {purl: "pkg:npm/@acme/foo", vers: ">=1", effect: trust, wantVers: "vers:npm/>=1"}, + {purl: "pkg:npm/@acme/*", effect: trust, wantErr: "a trust entry selects one package"}, + {purl: "pkg:npm/ac*", effect: block, wantErr: "a prefix has one '*'"}, + {purl: "pkg:npm/*/x", effect: block, wantErr: "a prefix has one '*'"}, + {purl: "pkg:npm/x@1.*", effect: block, wantErr: "a prefix has no version"}, + {purl: "pkg:npm/x?a=1/*", effect: block, wantErr: "a prefix has one '*'"}, + {purl: "pkg:npm/%2A", effect: block, wantErr: "do not encode '*'"}, + {purl: "npm/evil", effect: block, wantErr: "write a PURL"}, + {purl: "pkg:npm", effect: block, wantErr: "a PURL has a type and a name"}, + {purl: "pkg:", effect: block, wantErr: "write a PURL"}, + {purl: "pkg:npm//x", effect: block, wantErr: "a PURL has a type and a name"}, + {purl: "pkg:pypi/foo@1.0.3", vers: ">=1", effect: trust, wantErr: "not both"}, + } + for _, tt := range tests { + t.Run(tt.purl+" "+tt.vers, func(t *testing.T) { + got, err := buildSelector(tt.purl, tt.vers, tt.effect) + if tt.wantErr != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantErr) + return + } + require.NoError(t, err) + assert.Equal(t, tt.purl, got.GetPurl()) + assert.Equal(t, tt.wantVers, got.GetVers()) + }) + } +} + +func TestParseExpiry(t *testing.T) { + got, err := parseExpiry("30d", fixedNow) + require.NoError(t, err) + assert.Equal(t, fixedNow.Add(30*24*time.Hour), got) + + got, err = parseExpiry("2027-01-26", fixedNow) + require.NoError(t, err) + assert.Equal(t, time.Date(2027, 1, 26, 0, 0, 0, 0, time.UTC), got) + + _, err = parseExpiry("2026-01-01", fixedNow) + assert.ErrorContains(t, err, "in the past") + _, err = parseExpiry("0s", fixedNow) + assert.ErrorContains(t, err, "after now") + _, err = parseExpiry("soon", fixedNow) + assert.ErrorContains(t, err, "give a duration") +} + +func TestBuildRuleCreates_Trust(t *testing.T) { + in := ruleCreateInput{ + Trust: true, Selector: "pkg:pypi/foo@1.0.3", Scopes: []string{"malware"}, + Reason: "False positive, S-88", Expires: "30d", RequestedBy: "data-eng", Ticket: "S-88", + } + creates, err := buildRuleCreates(in, nil, fixedNow) + require.NoError(t, err) + require.Len(t, creates, 1) + rule := creates[0].GetRule() + assert.Equal(t, corev1.Effect_EFFECT_TRUST, rule.GetEffect()) + assert.Equal(t, []corev1.TrustScope{corev1.TrustScope_TRUST_SCOPE_MALWARE}, rule.GetScopes()) + assert.Equal(t, fixedNow.Add(30*24*time.Hour), rule.GetExpiresAt().AsTime()) + assert.Empty(t, rule.GetRuleId(), "the server sets the rule id") + assert.Equal(t, "data-eng", creates[0].GetRequestedBy()) + assert.Equal(t, "S-88", creates[0].GetTicket()) +} + +func TestBuildRuleCreates_BulkBlockFromFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "list.txt") + require.NoError(t, os.WriteFile(path, []byte("# incident IR-2291\npkg:npm/evil >=1.2.0\n\npkg:npm/@evil/*\n"), 0o600)) + + creates, err := buildRuleCreates(ruleCreateInput{Block: true, File: path, Reason: "IR-2291"}, nil, fixedNow) + require.NoError(t, err) + require.Len(t, creates, 2) + assert.Equal(t, "vers:npm/>=1.2.0", creates[0].GetRule().GetSelector().GetVers()) + assert.Equal(t, "pkg:npm/@evil/*", creates[1].GetRule().GetSelector().GetPurl()) + assert.False(t, creates[0].GetRule().HasExpiresAt()) + + creates, err = buildRuleCreates(ruleCreateInput{Block: true, File: "-", Reason: "x"}, strings.NewReader("pkg:npm/a\n"), fixedNow) + require.NoError(t, err) + assert.Len(t, creates, 1, "- reads stdin") +} + +func TestBuildRuleCreates_FileErrors(t *testing.T) { + dir := t.TempDir() + write := func(name, text string) string { + p := filepath.Join(dir, name) + require.NoError(t, os.WriteFile(p, []byte(text), 0o600)) + return p + } + var many strings.Builder + for i := 0; i <= maxBulkRules; i++ { + fmt.Fprintf(&many, "pkg:npm/p%d\n", i) + } + tests := []struct { + name, path, want string + }{ + {"bad line", write("bad.txt", "pkg:npm/ok\npkg:npm/ac*\n"), "bad.txt line 2: selector"}, + {"too many values", write("vals.txt", "pkg:npm/a >=1 extra\n"), "write a PURL and an optional range"}, + {"empty", write("empty.txt", "# nothing\n"), "has no selectors"}, + {"too many", write("many.txt", many.String()), "more than 1000 selectors"}, + {"missing", filepath.Join(dir, "missing.txt"), "Check the path"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := buildRuleCreates(ruleCreateInput{Block: true, File: tt.path, Reason: "x"}, nil, fixedNow) + require.Error(t, err) + msg := err.Error() + if ue, ok := usefulerror.AsUsefulError(err); ok { + msg += " " + ue.HumanError() + " " + ue.Help() + } + assert.Contains(t, msg, tt.want) + }) + } +} + +func ruleWithAttributes(id string, effect corev1.Effect, overrideID string) *policyv1.PackageRuleWithAttributes { + sel := &corev1.PackageSelector{} + sel.SetPurl("pkg:npm/leftpad") + rule := &corev1.PackageRule{} + rule.SetRuleId(id) + rule.SetSelector(sel) + rule.SetEffect(effect) + rule.SetReason("FP, S-71") + if effect == corev1.Effect_EFFECT_TRUST { + rule.SetScopes([]corev1.TrustScope{corev1.TrustScope_TRUST_SCOPE_MALWARE}) + rule.SetExpiresAt(timestamppb.New(time.Now().Add(49 * time.Hour))) + } + r := &policyv1.PackageRuleWithAttributes{} + r.SetRule(rule) + r.SetOverrideId(overrideID) + r.SetRequestedBy("web") + r.SetAddedRevision(40) + return r +} + +func TestRunRuleCreate_AttachesToAnOverride(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(headResponse(), nil) + res := &policyv1.CreatePackageRulesResponse{} + res.SetRules([]*policyv1.PackageRuleWithAttributes{ruleWithAttributes("r_9c1", corev1.Effect_EFFECT_BLOCK, "ov_pay")}) + res.SetRevision(revision(48, "block")) + client.EXPECT().CreatePackageRules(mock.Anything, mock.MatchedBy(func(r *policyv1.CreatePackageRulesRequest) bool { + return len(r.GetRules()) == 1 && r.GetRules()[0].GetOverrideId() == "ov_pay" && r.GetMessage() == "IR-2291" + })).Return(res, nil) + + in := ruleCreateInput{Block: true, Selector: "pkg:npm/evil", Reason: "x", Override: "payments", Message: "IR-2291"} + creates, err := buildRuleCreates(in, nil, fixedNow) + require.NoError(t, err) + got, err := runRuleCreate(context.Background(), client, in, creates) + require.NoError(t, err) + assert.Equal(t, uint64(48), got.Revision) +} + +func TestRunRuleCreate_PermissionDenied(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().CreatePackageRules(mock.Anything, mock.Anything).Return(nil, status.Error(codes.PermissionDenied, "member")) + in := ruleCreateInput{Block: true, Selector: "pkg:npm/evil", Reason: "x"} + creates, err := buildRuleCreates(in, nil, fixedNow) + require.NoError(t, err) + _, err = runRuleCreate(context.Background(), client, in, creates) + ue, ok := usefulerror.AsUsefulError(err) + require.True(t, ok) + assert.Equal(t, "Your role cannot change package rules", ue.HumanError()) +} + +func TestRuleListFilters(t *testing.T) { + in := &ruleListInput{Effect: "trust", Scope: "malware", SelectorPrefix: "pkg:npm/", Expiring: 7 * 24 * time.Hour, AtRevision: 40} + f, err := ruleListFilters(in, "") + require.NoError(t, err) + assert.Equal(t, corev1.Effect_EFFECT_TRUST, f.GetEffect()) + assert.Equal(t, corev1.TrustScope_TRUST_SCOPE_MALWARE, f.GetScope()) + assert.Equal(t, "pkg:npm/", f.GetSelectorPrefix()) + assert.Equal(t, 7*24*time.Hour, f.GetExpiringWithin().AsDuration()) + assert.Equal(t, uint64(40), f.GetAtRevision()) + assert.False(t, f.HasOverrideId()) + + f, err = ruleListFilters(&ruleListInput{Base: true}, "") + require.NoError(t, err) + assert.True(t, f.HasOverrideId(), "--base sends an empty override id") + assert.Empty(t, f.GetOverrideId()) + + f, err = ruleListFilters(&ruleListInput{}, "") + require.NoError(t, err) + assert.Nil(t, f) + + _, err = ruleListFilters(&ruleListInput{Base: true, Override: "x"}, "") + assert.ErrorContains(t, err, "--override and --base") + _, err = ruleListFilters(&ruleListInput{Effect: "allow"}, "") + assert.ErrorContains(t, err, `unknown --effect value "allow"`) +} + +func TestRunRuleList_NamesTheOverride(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + res := &policyv1.ListPackageRulesResponse{} + res.SetRules([]*policyv1.PackageRuleWithAttributes{ + ruleWithAttributes("r_77e", corev1.Effect_EFFECT_TRUST, "ov_pay"), + ruleWithAttributes("r_80b", corev1.Effect_EFFECT_BLOCK, ""), + }) + client.EXPECT().ListPackageRules(mock.Anything, mock.Anything).Return(res, nil) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(headResponse(), nil) + + got, err := runRuleList(context.Background(), client, &ruleListInput{}) + require.NoError(t, err) + require.Len(t, got.Rules, 2) + assert.Equal(t, `override "payments"`, got.Rules[0].AttachesTo) + assert.Equal(t, "base", got.Rules[1].AttachesTo) + assert.Equal(t, []string{"malware"}, got.Rules[0].Scopes) + + table := got.RenderTable() + assert.Contains(t, table, "r_77e") + assert.Contains(t, table, "in 2d") + assert.Contains(t, table, "never") + assert.Contains(t, got.RenderPlain(), "r_80b\tpkg:npm/leftpad\t\tblock\t\tFP, S-71\tweb\t\t") +} + +func TestRunRuleShow(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + res := &policyv1.GetPackageRuleResponse{} + res.SetRule(ruleWithAttributes("r_9c1", corev1.Effect_EFFECT_BLOCK, "")) + client.EXPECT().GetPackageRule(mock.Anything, mock.Anything).Return(res, nil) + + 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, "added in revision 40 · active") + + missing := mocks.NewPolicyServiceClientMock(t) + missing.EXPECT().GetPackageRule(mock.Anything, mock.Anything).Return(nil, status.Error(codes.NotFound, "x")) + _, err = runRuleShow(context.Background(), missing, "r_x") + ue, ok := usefulerror.AsUsefulError(err) + require.True(t, ok) + assert.Equal(t, "Package rule r_x does not exist", ue.HumanError()) +} + +func TestBuildRuleUpdate(t *testing.T) { + changed := func(names ...string) func(string) bool { + return func(n string) bool { + for _, c := range names { + if c == n { + return true + } + } + return false + } + } + update, err := buildRuleUpdate("r_77e", ruleUpdateInput{Expires: "90d", Reason: "renewed", changed: changed("expires", "reason")}, fixedNow) + require.NoError(t, err) + assert.Equal(t, fixedNow.Add(90*24*time.Hour), update.GetExpiresAt().AsTime()) + assert.Equal(t, "renewed", update.GetReason()) + assert.False(t, update.HasTicket()) + + update, err = buildRuleUpdate("r_77e", ruleUpdateInput{changed: changed("ticket")}, fixedNow) + require.NoError(t, err) + assert.True(t, update.HasTicket(), "an empty --ticket clears the ticket") + + _, err = buildRuleUpdate("r_77e", ruleUpdateInput{}, fixedNow) + assert.ErrorContains(t, err, "give at least one of") + _, err = buildRuleUpdate("r_77e", ruleUpdateInput{changed: changed("reason")}, fixedNow) + assert.ErrorContains(t, err, "--reason must not be empty") +} + +func TestRunRuleUpdateAndDelete(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + upd := &policyv1.UpdatePackageRuleResponse{} + upd.SetRevision(revision(50, "")) + client.EXPECT().UpdatePackageRule(mock.Anything, mock.MatchedBy(func(r *policyv1.UpdatePackageRuleRequest) bool { + return r.GetUpdate().GetRuleId() == "r_77e" && r.GetMessage() == "m" + })).Return(upd, nil) + update := &policyv1.PackageRuleUpdate{} + update.SetRuleId("r_77e") + res, err := runRuleUpdate(context.Background(), client, update, "m") + require.NoError(t, err) + assert.Equal(t, uint64(50), res.GetRevision().GetRevision()) + + del := &policyv1.DeletePackageRuleResponse{} + del.SetRevision(revision(51, "")) + client.EXPECT().DeletePackageRule(mock.Anything, mock.MatchedBy(func(r *policyv1.DeletePackageRuleRequest) bool { + return r.GetDelete().GetRuleId() == "r_80b" && r.GetDelete().GetReason() == "no longer needed" + })).Return(del, nil) + rev, err := runRuleDelete(context.Background(), client, "r_80b", "no longer needed", "") + require.NoError(t, err) + assert.Equal(t, uint64(51), rev) +} diff --git a/internal/cmd/policy/selector.go b/internal/cmd/policy/selector.go new file mode 100644 index 0000000..4a4891d --- /dev/null +++ b/internal/cmd/policy/selector.go @@ -0,0 +1,117 @@ +package policy + +import ( + "fmt" + "regexp" + "strings" + "time" + + corev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/core/v1" + + "github.com/safedep/cli/internal/cloudpolicy" + "github.com/safedep/cli/internal/duration" +) + +// These patterns mirror the checks of PackageSelector in the contract. The +// server checks them too. The CLI checks them first, so a typo fails with a +// clear message and no publish. +var ( + purlTypePattern = regexp.MustCompile(`^pkg:[A-Za-z0-9.+-]+/[^/].*$`) + prefixPattern = regexp.MustCompile(`^[^*?#]*(/|[^/*?#][.])[*]$`) + prefixVersionPattern = regexp.MustCompile(`[^/]@`) + encodedStarPattern = regexp.MustCompile(`(?i)%2a`) + purlVersionPattern = regexp.MustCompile(`^[^?#]*@[^/?#]+([?#].*)?$`) +) + +const ( + minSelectorLength = 6 + maxSelectorLength = 512 +) + +// buildSelector checks a PURL or a prefix and an optional vers range, and +// builds the package selector. A trust entry selects one package: only a +// block entry can use a prefix. +func buildSelector(purl, vers string, effect corev1.Effect) (*corev1.PackageSelector, error) { + purl = strings.TrimSpace(purl) + if err := validatePURL(purl, effect); err != nil { + return nil, err + } + selector := &corev1.PackageSelector{} + selector.SetPurl(purl) + if vers = strings.TrimSpace(vers); vers != "" { + if purlVersionPattern.MatchString(purl) { + return nil, fmt.Errorf("selector %s: set a version in the PURL or a --vers range, not both", purl) + } + selector.SetVers(normalizeVers(purl, vers)) + if len(selector.GetVers()) > maxSelectorLength { + return nil, fmt.Errorf("vers range of %s: the limit is %d characters", purl, maxSelectorLength) + } + } + return selector, nil +} + +func validatePURL(purl string, effect corev1.Effect) error { + if !strings.HasPrefix(purl, "pkg:") || len(purl) < minSelectorLength || len(purl) > maxSelectorLength { + return fmt.Errorf("selector %q: write a PURL of %d to %d characters, as in pkg:npm/name", + purl, minSelectorLength, maxSelectorLength) + } + if !purlTypePattern.MatchString(purl) { + return fmt.Errorf("selector %q: a PURL has a type and a name, as in pkg:npm/name", purl) + } + if encodedStarPattern.MatchString(purl) { + return fmt.Errorf("selector %q: do not encode '*' as %%2A", purl) + } + if !strings.Contains(purl, "*") { + return nil + } + if effect == corev1.Effect_EFFECT_TRUST { + return fmt.Errorf("selector %q: a trust entry selects one package, so it cannot use a prefix. "+ + "Only a block entry can use a prefix that ends with /* or .*", purl) + } + if strings.Count(purl, "*") > 1 || !prefixPattern.MatchString(purl) { + return fmt.Errorf("selector %q: a prefix has one '*', at the end, after '/' or '.', "+ + "as in pkg:npm/@acme/* or pkg:maven/org.apache.*. It has no qualifiers or subpath", purl) + } + if prefixVersionPattern.MatchString(purl) { + return fmt.Errorf("selector %q: a prefix has no version. Use --vers for a range", purl) + } + return nil +} + +// normalizeVers turns a bare range such as ">=1.2.0" into the vers form of +// the contract, "vers:npm/>=1.2.0", with the type of the PURL. +func normalizeVers(purl, vers string) string { + if strings.HasPrefix(vers, "vers:") { + return vers + } + purlType, _, _ := strings.Cut(strings.TrimPrefix(purl, "pkg:"), "/") + return "vers:" + strings.ToLower(purlType) + "/" + vers +} + +// selectorText writes a selector as one value, as in +// "pkg:npm/evil vers:npm/>=1.2.0". +func selectorText(s *corev1.PackageSelector) string { + if s.GetVers() == "" { + return s.GetPurl() + } + return s.GetPurl() + " " + s.GetVers() +} + +// parseExpiry reads a duration from now, as "30d", or a time, as +// "2027-01-26". The expiry must be in the future. +func parseExpiry(text string, now time.Time) (time.Time, error) { + if d, err := duration.Parse(text); err == nil { + if d <= 0 { + return time.Time{}, fmt.Errorf("--expires %q: give a duration after now, as in 30d", text) + } + return now.Add(d).UTC(), nil + } + t, err := cloudpolicy.ParseTime(text) + if err != nil { + return time.Time{}, fmt.Errorf("--expires %q: give a duration, as in 30d, or a date, as in 2027-01-26", text) + } + if !t.After(now) { + return time.Time{}, fmt.Errorf("--expires %q: the time is in the past", text) + } + return t.UTC(), nil +} diff --git a/internal/cmd/policy/show.go b/internal/cmd/policy/show.go new file mode 100644 index 0000000..841f483 --- /dev/null +++ b/internal/cmd/policy/show.go @@ -0,0 +1,199 @@ +package policy + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "time" + + policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" + "github.com/safedep/dry/tui/table" + "github.com/spf13/cobra" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" +) + +type showResult struct { + Tenant string + HeadRevision uint64 + Head *revisionView + DefaultRevision uint64 + DefaultFields []cloudpolicy.FieldValue + OpenChanges uint32 + TrustRules uint32 + BlockRules uint32 + ExpiringSoon uint32 + BaseDescription string + Overrides []overrideView + Document any +} + +type showResultJSON struct { + Tenant string `json:"tenant,omitempty"` + HeadRevision uint64 `json:"head_revision"` + Head *revisionView `json:"head,omitempty"` + DefaultRevision uint64 `json:"default_policy_revision"` + DefaultPolicy map[string]string `json:"default_policy"` + OpenChanges uint32 `json:"open_change_count"` + PackageRules map[string]uint32 `json:"package_rule_counts"` + Overrides []overrideView `json:"overrides"` + Policy any `json:"policy"` +} + +func showCmd(a *app.App) *cobra.Command { + return &cobra.Command{ + Use: "show", + Short: "Show a summary of the tenant policy", + Long: "Show the head policy revision, the open policy changes, the package rule counts, the " + + "SafeDep default policy and the policy overrides in priority order. With --output json, the " + + "output also holds the policy settings document.", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + client, err := a.ControlPlane() + if err != nil { + return err + } + res, err := runShow(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), a.Tenant()) + if err != nil { + return err + } + return a.Output.Print(res) + }, + } +} + +func runShow(ctx context.Context, client policyv1grpc.PolicyServiceClient, tenant string) (*showResult, error) { + res, err := getPolicy(ctx, client) + if err != nil { + return nil, err + } + doc, err := cloudpolicy.PolicyMap(res.GetPolicy()) + if err != nil { + return nil, err + } + counts := res.GetPackageRuleCounts() + return &showResult{ + Tenant: tenant, + HeadRevision: res.GetHeadRevision(), + Head: newRevisionView(res.GetHead()), + DefaultRevision: res.GetDefaultPolicy().GetRevision(), + DefaultFields: cloudpolicy.Fields(res.GetDefaultPolicy().GetSpec()), + OpenChanges: res.GetOpenChangeCount(), + TrustRules: counts.GetTrustCount(), + BlockRules: counts.GetBlockCount(), + ExpiringSoon: counts.GetTrustExpiringSoonCount(), + BaseDescription: res.GetPolicy().GetBaseDescription(), + Overrides: overrideViews(res.GetPolicy()), + Document: doc, + }, nil +} + +func (r *showResult) RenderJSON() ([]byte, error) { + defaults := make(map[string]string, len(r.DefaultFields)) + for _, f := range r.DefaultFields { + defaults[f.Path] = f.Value + } + overrides := r.Overrides + if overrides == nil { + overrides = []overrideView{} + } + return json.MarshalIndent(showResultJSON{ + Tenant: r.Tenant, + HeadRevision: r.HeadRevision, + Head: r.Head, + DefaultRevision: r.DefaultRevision, + DefaultPolicy: defaults, + OpenChanges: r.OpenChanges, + PackageRules: map[string]uint32{ + "trust": r.TrustRules, + "block": r.BlockRules, + "trust_expiring_in_7d": r.ExpiringSoon, + "total": r.TrustRules + r.BlockRules, + }, + Overrides: overrides, + Policy: r.Document, + }, "", " ") +} + +func (r *showResult) headLine(now time.Time) string { + if r.Head == nil { + return "none: the tenant has not published a policy yet" + } + return r.Head.summary(now) +} + +func (r *showResult) openLine() string { + if r.OpenChanges == 0 { + return "none" + } + return fmt.Sprintf("%d%ssafedep policy change list --state open", r.OpenChanges, sep) +} + +func (r *showResult) rulesLine() string { + line := fmt.Sprintf("%d (%d trust, %d block)", r.TrustRules+r.BlockRules, r.TrustRules, r.BlockRules) + if r.ExpiringSoon > 0 { + line += fmt.Sprintf("%s%d expire in 7d", sep, r.ExpiringSoon) + } + return line +} + +func (r *showResult) defaultLine() string { + parts := []string{fmt.Sprintf("revision %d", r.DefaultRevision)} + for _, f := range r.DefaultFields { + parts = append(parts, f.Path+": "+f.Human) + } + return strings.Join(parts, sep) +} + +func (r *showResult) RenderTable() string { + now := time.Now() + tenant := r.Tenant + if tenant == "" { + tenant = "(this tenant)" + } + rows := [][2]string{ + {"Policy", tenant}, + {"Head revision", r.headLine(now)}, + {"Open changes", r.openLine()}, + {"Package rules", r.rulesLine()}, + {"Default policy", r.defaultLine()}, + } + if r.BaseDescription != "" { + rows = append(rows, [2]string{"Base", r.BaseDescription}) + } + + overrideRows := make([][]string, 0, len(r.Overrides)) + for _, o := range r.Overrides { + expires := "-" + if o.expires != nil { + expires = humanTimeCell(o.expires, now) + } + overrideRows = append(overrideRows, []string{ + fmt.Sprintf("%d", o.Priority), o.Name, o.Selector, expires, emptyDash(o.Description), + }) + } + overrides := table.New(). + Title("Overrides (priority, highest first)"). + Headers("PRIORITY", "NAME", "SELECTOR", "EXPIRES", "DESCRIPTION"). + Rows(overrideRows...). + EmptyMessage("No policy overrides. The policy base applies to every subject. Add one with: safedep policy edit"). + Render() + return cloudpolicy.KeyValues(rows) + "\n\n" + overrides +} + +func (r *showResult) RenderPlain() string { + var b strings.Builder + fmt.Fprintf(&b, "tenant\t%s\n", r.Tenant) + fmt.Fprintf(&b, "head_revision\t%d\n", r.HeadRevision) + fmt.Fprintf(&b, "default_policy_revision\t%d\n", r.DefaultRevision) + fmt.Fprintf(&b, "open_change_count\t%d\n", r.OpenChanges) + fmt.Fprintf(&b, "trust_rules\t%d\n", r.TrustRules) + fmt.Fprintf(&b, "block_rules\t%d\n", r.BlockRules) + fmt.Fprintf(&b, "trust_expiring_in_7d\t%d", r.ExpiringSoon) + for _, o := range r.Overrides { + fmt.Fprintf(&b, "\noverride\t%d\t%s\t%s\t%s", o.Priority, o.Name, o.Selector, o.ExpiresAt) + } + return b.String() +} diff --git a/internal/cmd/policy/show_test.go b/internal/cmd/policy/show_test.go new file mode 100644 index 0000000..f1b5709 --- /dev/null +++ b/internal/cmd/policy/show_test.go @@ -0,0 +1,93 @@ +package policy + +import ( + "context" + "encoding/json" + "testing" + + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + "github.com/safedep/cli/internal/cloudpolicy/mocks" +) + +func TestRunShow(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(headResponse(), nil) + + res, err := runShow(context.Background(), client, "platform-eng.acme.safedep.io") + require.NoError(t, err) + + require.Len(t, res.Overrides, 2) + assert.Equal(t, "ci", res.Overrides[0].Name, "the highest priority comes first") + assert.Equal(t, "managed/deployment-kind=ci", res.Overrides[0].Selector) + + table := res.RenderTable() + for _, want := range []string{ + "Policy platform-eng.acme.safedep.io", + `46 · published 2d ago by alice · "cooldown 5d for laptops"`, + "Open changes none", + "211 (184 trust, 27 block) · 23 expire in 7d", + "revision 12 · scan_gate.fail_on: high", + "Overrides (priority, highest first)", + "payments", + } { + assert.Contains(t, table, want) + } + + b, err := res.RenderJSON() + require.NoError(t, err) + var out map[string]any + require.NoError(t, json.Unmarshal(b, &out)) + assert.InDelta(t, 46, out["head_revision"], 0) + assert.Equal(t, map[string]any{"scan_gate.fail_on": "high"}, out["default_policy"]) + policy, ok := out["policy"].(map[string]any) + require.True(t, ok) + assert.Contains(t, policy, "overrides") + + assert.Contains(t, res.RenderPlain(), "override\t300\tci\tmanaged/deployment-kind=ci") +} + +func TestRunShow_NeverPublished(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + res := &policyv1.GetPolicyResponse{} + res.SetOpenChangeCount(2) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(res, nil) + + got, err := runShow(context.Background(), client, "") + require.NoError(t, err) + table := got.RenderTable() + assert.Contains(t, table, "none: the tenant has not published a policy yet") + assert.Contains(t, table, "2 · safedep policy change list --state open") + assert.Contains(t, table, "No policy overrides") +} + +func TestRunGet(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(headResponse(), nil) + + res, err := runGet(context.Background(), client, getInput{}, "acme") + require.NoError(t, err) + assert.Equal(t, uint64(46), res.Revision) + assert.Contains(t, res.RenderPlain(), "# Policy settings of acme · revision 46\n") + assert.Contains(t, res.RenderTable(), "overrides:\n - name: payments") + b, err := res.RenderJSON() + require.NoError(t, err) + assert.Contains(t, string(b), `"revision": 46`) +} + +func TestRunGet_AtRevision(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + rev := &policyv1.GetPolicyRevisionResponse{} + rev.SetRevision(revision(40, "old")) + rev.SetPolicy(headPolicy()) + client.EXPECT().GetPolicyRevision(mock.Anything, mock.MatchedBy(func(r *policyv1.GetPolicyRevisionRequest) bool { + return r.GetRevision() == 40 + })).Return(rev, nil) + + res, err := runGet(context.Background(), client, getInput{Revision: 40}, "") + require.NoError(t, err) + assert.Contains(t, res.YAML, "# Policy settings of this tenant · revision 40") +} diff --git a/internal/cmd/policy/view.go b/internal/cmd/policy/view.go new file mode 100644 index 0000000..fef1e0a --- /dev/null +++ b/internal/cmd/policy/view.go @@ -0,0 +1,199 @@ +package policy + +import ( + "context" + "fmt" + "slices" + "sort" + "strings" + "time" + + policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" + messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" + corev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/core/v1" + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/safedep/dry/tui/humanize" + "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/safedep/cli/internal/cloudpolicy" + "github.com/safedep/cli/internal/tui" +) + +// The views below translate the proto messages that more than one verb +// prints. Renderers read the views, never the proto messages. + +const ( + sep = cloudpolicy.Separator + + directionPrefix = "CHANGE_DIRECTION_" + sourcePrefix = "CHANGE_SOURCE_" + changeStatePrefix = "POLICY_CHANGE_STATE_" + effectPrefix = "EFFECT_" + trustScopePrefix = "TRUST_SCOPE_" +) + +type revisionView struct { + Revision uint64 `json:"revision"` + ChangeID string `json:"change_id,omitempty"` + Author string `json:"author"` + Message string `json:"message"` + Source string `json:"source"` + Direction string `json:"direction"` + PublishedAt *time.Time `json:"-"` + Published string `json:"published_at,omitempty"` +} + +func newRevisionView(r *policyv1.PolicyRevision) *revisionView { + if r == nil { + return nil + } + published := timeOf(r.GetPublishedAt()) + return &revisionView{ + Revision: r.GetRevision(), + ChangeID: r.GetChangeId(), + Author: actorName(r.GetAuthor()), + Message: r.GetMessage(), + Source: strings.ToUpper(tui.EnumToken(r.GetSource().String(), sourcePrefix)), + Direction: directionToken(r.GetDirection()), + PublishedAt: published, + Published: cloudpolicy.RFC3339(published), + } +} + +// summary is the one-line form: the revision, when and by whom it was +// published, and the publish message. +func (r *revisionView) summary(now time.Time) string { + parts := []string{fmt.Sprintf("%d", r.Revision)} + published := "published" + if r.PublishedAt != nil { + published += " " + humanize.Time(*r.PublishedAt, now) + } + if r.Author != "" { + published += " by " + r.Author + } + parts = append(parts, published) + if r.Message != "" { + parts = append(parts, fmt.Sprintf("%q", r.Message)) + } + return strings.Join(parts, sep) +} + +func actorName(a *messagescontroltowerv1.Actor) string { + if a == nil { + return "" + } + if a.GetDisplayName() != "" { + return a.GetDisplayName() + } + return a.GetId() +} + +func directionToken(d policyv1.ChangeDirection) string { + return strings.ToUpper(tui.EnumToken(d.String(), directionPrefix)) +} + +func timeOf(ts *timestamppb.Timestamp) *time.Time { + if ts == nil { + return nil + } + t := ts.AsTime().UTC() + return &t +} + +func humanTimeCell(t *time.Time, now time.Time) string { + if t == nil { + return "-" + } + return humanize.Time(*t, now) +} + +func emptyDash(s string) string { + if s == "" { + return "-" + } + return s +} + +func plural(n int, singular, pluralForm string) string { + if n == 1 { + return singular + } + return pluralForm +} + +// overrideView is a policy override without its values. +type overrideView struct { + ID string `json:"override_id"` + Name string `json:"name"` + Priority uint32 `json:"priority"` + Selector string `json:"selector"` + Description string `json:"description,omitempty"` + ExpiresAt string `json:"expires_at,omitempty"` + expires *time.Time +} + +// overrideViews lists the policy overrides from the highest priority to the +// lowest, the order in which they win. +func overrideViews(p *policyv1.Policy) []overrideView { + out := make([]overrideView, 0, len(p.GetOverrides())) + for _, o := range p.GetOverrides() { + expires := timeOf(o.GetExpiresAt()) + out = append(out, overrideView{ + ID: o.GetOverrideId(), + Name: o.GetName(), + Priority: o.GetPriority(), + Selector: cloudpolicy.FormatSelector(o.GetSelector()), + Description: o.GetDescription(), + ExpiresAt: cloudpolicy.RFC3339(expires), + expires: expires, + }) + } + sort.SliceStable(out, func(i, j int) bool { return out[i].Priority > out[j].Priority }) + return out +} + +// getPolicy reads the head policy of the tenant. +func getPolicy(ctx context.Context, client policyv1grpc.PolicyServiceClient) (*policyv1.GetPolicyResponse, error) { + res, err := client.GetPolicy(ctx, &policyv1.GetPolicyRequest{}) + if err != nil { + return nil, fmt.Errorf("policy: get policy: %w", err) + } + return res, nil +} + +// findOverride returns the policy override with the name. +func findOverride(p *policyv1.Policy, name string) (*policyv1.Override, error) { + names := make([]string, 0, len(p.GetOverrides())) + for _, o := range p.GetOverrides() { + if o.GetName() == name { + return o, nil + } + names = append(names, o.GetName()) + } + known := "the policy has no overrides" + if len(names) > 0 { + slices.Sort(names) + known = "known overrides: " + strings.Join(names, ", ") + } + return nil, invalidInputError( + fmt.Errorf("no policy override is named %q: %s", name, known), + "See the policy overrides: safedep policy show", + ) +} + +// overrideNames maps override ids to names, for output that cites an id. +func overrideNames(p *policyv1.Policy) map[string]string { + out := make(map[string]string, len(p.GetOverrides())) + for _, o := range p.GetOverrides() { + out[o.GetOverrideId()] = o.GetName() + } + return out +} + +func scopeTokens(scopes []corev1.TrustScope) []string { + out := make([]string, 0, len(scopes)) + for _, s := range scopes { + out = append(out, tui.EnumToken(s.String(), trustScopePrefix)) + } + return out +} diff --git a/internal/cmd/safedep.go b/internal/cmd/safedep.go index cc9c94d..b06244e 100644 --- a/internal/cmd/safedep.go +++ b/internal/cmd/safedep.go @@ -6,6 +6,7 @@ import ( "github.com/safedep/cli/internal/cmd/endpoint" "github.com/safedep/cli/internal/cmd/integration" "github.com/safedep/cli/internal/cmd/packages" + "github.com/safedep/cli/internal/cmd/policy" "github.com/safedep/cli/internal/cmd/project" "github.com/safedep/cli/internal/cmd/protect" "github.com/safedep/cli/internal/cmd/query" @@ -22,6 +23,7 @@ func NewSafedep(a *app.App) *cobra.Command { auth.Register(root, a) endpoint.Register(root, a) packages.Register(root, a) + policy.Register(root, a) project.Register(root, a) query.Register(root, a) integration.Register(root, a) diff --git a/internal/cmd/subscription/service.go b/internal/cmd/subscription/service.go index 379cbe6..f32b82b 100644 --- a/internal/cmd/subscription/service.go +++ b/internal/cmd/subscription/service.go @@ -11,6 +11,7 @@ import ( msgv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" errorv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/error/v1" ctv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" + "github.com/safedep/cli/internal/rpcerror" "github.com/safedep/cli/internal/tui" "google.golang.org/grpc" "google.golang.org/grpc/codes" @@ -498,7 +499,7 @@ func catalogFromProto(pb *msgv1.BillingCatalog) *Catalog { // an actionable message naming the next command, matching the on-demand enable // path. func mapAddOnAttachError(err error) error { - switch errorReason(err) { + switch rpcerror.Reason(err) { case errorv1.ErrorReason_ERROR_REASON_ENTITLEMENT_NOT_AVAILABLE: return errors.New("add-ons need an active paid plan: subscribe first with `safedep subscription create`") case errorv1.ErrorReason_ERROR_REASON_SUBSCRIPTION_PAST_DUE: @@ -526,7 +527,7 @@ func mapCheckoutError(err error) error { // mapOnDemandEnableError routes the typed ErrorReason to an actionable // message so the user knows the next command to run. func mapOnDemandEnableError(err error) error { - switch errorReason(err) { + switch rpcerror.Reason(err) { case errorv1.ErrorReason_ERROR_REASON_ENTITLEMENT_NOT_AVAILABLE: return errors.New("on-demand billing needs a paid plan: subscribe first with `safedep subscription create`") case errorv1.ErrorReason_ERROR_REASON_PAYMENT_METHOD_REQUIRED: @@ -536,21 +537,6 @@ func mapOnDemandEnableError(err error) error { } } -// errorReason extracts the typed business ErrorReason from a gRPC status -// error's details, or UNSPECIFIED when none is present. -func errorReason(err error) errorv1.ErrorReason { - st, ok := status.FromError(err) - if !ok { - return errorv1.ErrorReason_ERROR_REASON_UNSPECIFIED - } - for _, d := range st.Details() { - if detail, ok := d.(*errorv1.ErrorDetail); ok { - return detail.GetReason() - } - } - return errorv1.ErrorReason_ERROR_REASON_UNSPECIFIED -} - func customerFromProto(c *msgv1.BillingCustomer) *Customer { return &Customer{ ID: c.GetId(), diff --git a/internal/cmd/verbs.go b/internal/cmd/verbs.go index f136605..df0d8b2 100644 --- a/internal/cmd/verbs.go +++ b/internal/cmd/verbs.go @@ -9,21 +9,24 @@ var AllowedVerbs = map[string]struct{}{ // add/remove attach or detach a fixed catalog item (a subscription add-on) // to an existing resource. They read as attach/detach, distinct from // create/delete which mint or destroy a resource the user defines. - "add": {}, - "create": {}, - "delete": {}, - "disable": {}, - "edit": {}, - "enable": {}, - "exec": {}, - "get": {}, - "init": {}, - "install": {}, - "list": {}, - "login": {}, - "logout": {}, - "open": {}, - "pricing": {}, + "add": {}, + "create": {}, + "delete": {}, + "disable": {}, + "edit": {}, + "enable": {}, + "exec": {}, + "get": {}, + "init": {}, + "install": {}, + "list": {}, + "login": {}, + "logout": {}, + "open": {}, + "pricing": {}, + // publish makes a policy change live for the fleet as a new policy + // revision. It is not an update of the change, which stays a draft. + "publish": {}, "remove": {}, "run": {}, "set": {}, diff --git a/internal/config/config.go b/internal/config/config.go index 8ccf37e..36f2378 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -19,6 +19,8 @@ import ( "fmt" "os" "path/filepath" + "runtime" + "strings" "github.com/spf13/viper" ) @@ -56,6 +58,20 @@ func EnvVar(key string) string { return os.Getenv(key) } +// Editor returns the editor command of the user: VISUAL, then EDITOR, then +// vi, or notepad on Windows. +func Editor() string { + for _, key := range []string{"VISUAL", "EDITOR"} { + if v := strings.TrimSpace(os.Getenv(key)); v != "" { + return v + } + } + if runtime.GOOS == "windows" { + return "notepad" + } + return "vi" +} + // Load reads the config file into a Config. A missing file is not an // error: it returns a zero Config so first-run commands behave like a // fresh install. Any other read error (permission, malformed) is fatal. diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 5f24f1c..fa50871 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -83,3 +83,11 @@ func TestDir(t *testing.T) { "override is the safedep namespace; we must not double-prefix") }) } + +func TestEditor(t *testing.T) { + t.Setenv("VISUAL", "") + t.Setenv("EDITOR", "nano") + assert.Equal(t, "nano", Editor()) + t.Setenv("VISUAL", "code --wait") + assert.Equal(t, "code --wait", Editor()) +} diff --git a/internal/duration/duration.go b/internal/duration/duration.go new file mode 100644 index 0000000..3fe71bf --- /dev/null +++ b/internal/duration/duration.go @@ -0,0 +1,99 @@ +// Package duration reads and writes the durations of the CLI. A flag that +// takes a duration accepts a day unit, as in "30d", because policy durations +// such as a trust expiry are in days. The time package has no day unit. +package duration + +import ( + "fmt" + "regexp" + "strconv" + "strings" + "time" +) + +const ( + day = 24 * time.Hour + + // maxDays keeps the result inside time.Duration, which holds about + // 106,751 days. + maxDays = 100000 +) + +var dayPattern = regexp.MustCompile(`^([0-9]+)d(.*)$`) + +// Parse reads a duration as time.ParseDuration does, and also accepts a +// leading day unit: "30d", "1d12h". A day is 24 hours. +func Parse(s string) (time.Duration, error) { + text := strings.TrimSpace(s) + match := dayPattern.FindStringSubmatch(text) + if match == nil { + d, err := time.ParseDuration(text) + if err != nil { + return 0, fmt.Errorf("invalid duration %q: use a number and a unit, as in 30d, 12h or 90m", s) + } + return d, nil + } + + days, err := strconv.Atoi(match[1]) + if err != nil || days > maxDays { + return 0, fmt.Errorf("invalid duration %q: use at most %d days", s, maxDays) + } + total := time.Duration(days) * day + if match[2] == "" { + return total, nil + } + rest, err := time.ParseDuration(match[2]) + if err != nil || rest < 0 { + return 0, fmt.Errorf("invalid duration %q: use a number and a unit, as in 30d, 12h or 90m", s) + } + return total + rest, nil +} + +// Format writes a duration that Parse reads back to the same value. It drops +// zero minutes and seconds, so 48 hours is "48h", not "48h0m0s". Tables use +// dry/tui/humanize instead. +func Format(d time.Duration) string { + if d == 0 { + return "0s" + } + s := d.String() + if strings.HasSuffix(s, "m0s") { + s = strings.TrimSuffix(s, "0s") + } + if strings.HasSuffix(s, "h0m") { + s = strings.TrimSuffix(s, "0m") + } + return s +} + +// Value is a pflag value for a duration that accepts the day unit. +type Value struct { + target *time.Duration +} + +// NewValue sets *target to def and returns a flag value that writes to it. +func NewValue(target *time.Duration, def time.Duration) *Value { + *target = def + return &Value{target: target} +} + +func (v *Value) String() string { + if v == nil || v.target == nil { + return "" + } + if *v.target == 0 { + return "" + } + return Format(*v.target) +} + +func (v *Value) Set(s string) error { + d, err := Parse(s) + if err != nil { + return err + } + *v.target = d + return nil +} + +func (v *Value) Type() string { return "duration" } diff --git a/internal/duration/duration_test.go b/internal/duration/duration_test.go new file mode 100644 index 0000000..6e85136 --- /dev/null +++ b/internal/duration/duration_test.go @@ -0,0 +1,73 @@ +package duration + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestParse(t *testing.T) { + tests := []struct { + in string + want time.Duration + wantErr bool + }{ + {in: "30d", want: 30 * 24 * time.Hour}, + {in: "1d12h", want: 36 * time.Hour}, + {in: "7d", want: 168 * time.Hour}, + {in: "48h", want: 48 * time.Hour}, + {in: "90m", want: 90 * time.Minute}, + {in: " 2d ", want: 48 * time.Hour}, + {in: "0s", want: 0}, + {in: "d", wantErr: true}, + {in: "30days", wantErr: true}, + {in: "1d-1h", wantErr: true}, + {in: "200000d", wantErr: true}, + {in: "", wantErr: true}, + } + for _, tt := range tests { + t.Run(tt.in, func(t *testing.T) { + got, err := Parse(tt.in) + if tt.wantErr { + require.Error(t, err) + return + } + require.NoError(t, err) + assert.Equal(t, tt.want, got) + }) + } +} + +func TestFormat(t *testing.T) { + tests := []struct { + in time.Duration + want string + }{ + {0, "0s"}, + {48 * time.Hour, "48h"}, + {168 * time.Hour, "168h"}, + {90 * time.Minute, "1h30m"}, + {30 * time.Second, "30s"}, + {time.Hour + 30*time.Second, "1h0m30s"}, + {1500 * time.Millisecond, "1.5s"}, + } + for _, tt := range tests { + got := Format(tt.in) + assert.Equal(t, tt.want, got) + back, err := Parse(got) + require.NoError(t, err) + assert.Equal(t, tt.in, back, "Format must round trip through Parse") + } +} + +func TestValue(t *testing.T) { + var d time.Duration + v := NewValue(&d, 7*24*time.Hour) + assert.Equal(t, "168h", v.String()) + require.NoError(t, v.Set("30d")) + assert.Equal(t, 30*24*time.Hour, d) + require.Error(t, v.Set("soon")) + assert.Equal(t, "duration", v.Type()) +} diff --git a/internal/rpcerror/rpcerror.go b/internal/rpcerror/rpcerror.go new file mode 100644 index 0000000..2881e89 --- /dev/null +++ b/internal/rpcerror/rpcerror.go @@ -0,0 +1,24 @@ +// Package rpcerror reads the SafeDep business reason of a gRPC error. Every +// command package that maps a reason to a recovery reads it here. +package rpcerror + +import ( + errorv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/error/v1" + "google.golang.org/grpc/status" +) + +// Reason returns the ErrorReason of the ErrorDetail in a gRPC status error. +// It returns ERROR_REASON_UNSPECIFIED when the error has no such detail, so a +// caller falls back to the status code. +func Reason(err error) errorv1.ErrorReason { + st, ok := status.FromError(err) + if !ok { + return errorv1.ErrorReason_ERROR_REASON_UNSPECIFIED + } + for _, d := range st.Details() { + if detail, ok := d.(*errorv1.ErrorDetail); ok { + return detail.GetReason() + } + } + return errorv1.ErrorReason_ERROR_REASON_UNSPECIFIED +} diff --git a/internal/rpcerror/rpcerror_test.go b/internal/rpcerror/rpcerror_test.go new file mode 100644 index 0000000..0a84bc4 --- /dev/null +++ b/internal/rpcerror/rpcerror_test.go @@ -0,0 +1,32 @@ +package rpcerror + +import ( + "errors" + "testing" + + errorv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/error/v1" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func TestReason(t *testing.T) { + detail := &errorv1.ErrorDetail{} + detail.SetReason(errorv1.ErrorReason_ERROR_REASON_POLICY_CHANGE_STALE) + st, err := status.New(codes.Aborted, "stale").WithDetails(detail) + require.NoError(t, err) + + tests := []struct { + name string + err error + want errorv1.ErrorReason + }{ + {"detail", st.Err(), errorv1.ErrorReason_ERROR_REASON_POLICY_CHANGE_STALE}, + {"status without detail", status.Error(codes.Aborted, "x"), errorv1.ErrorReason_ERROR_REASON_UNSPECIFIED}, + {"not a status", errors.New("x"), errorv1.ErrorReason_ERROR_REASON_UNSPECIFIED}, + } + for _, tt := range tests { + assert.Equal(t, tt.want, Reason(tt.err), tt.name) + } +} diff --git a/internal/tui/editor.go b/internal/tui/editor.go new file mode 100644 index 0000000..298fa1c --- /dev/null +++ b/internal/tui/editor.go @@ -0,0 +1,30 @@ +package tui + +import ( + "context" + "errors" + "fmt" + "os" + "os/exec" + "strings" +) + +// RunEditor opens path in the editor command and waits for it to exit. The +// command can carry arguments, as in "code --wait". The editor gets the +// terminal of the CLI, so it lives here with the other terminal code. +func RunEditor(ctx context.Context, command, path string) error { + parts := strings.Fields(command) + if len(parts) == 0 { + return errors.New("no editor is set: set VISUAL or EDITOR, as in EDITOR=vi") + } + args := append(append([]string{}, parts[1:]...), path) + //nolint:gosec // G204: the user picks the editor through VISUAL or EDITOR. + cmd := exec.CommandContext(ctx, parts[0], args...) + cmd.Stdin = os.Stdin + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + if err := cmd.Run(); err != nil { + return fmt.Errorf("editor %q: %w", parts[0], err) + } + return nil +} diff --git a/internal/tui/editor_test.go b/internal/tui/editor_test.go new file mode 100644 index 0000000..602bf40 --- /dev/null +++ b/internal/tui/editor_test.go @@ -0,0 +1,18 @@ +package tui + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestRunEditor_NeedsACommand(t *testing.T) { + err := RunEditor(context.Background(), " ", "/tmp/x.yaml") + assert.ErrorContains(t, err, "no editor is set") +} + +func TestRunEditor_ReportsAFailedEditor(t *testing.T) { + err := RunEditor(context.Background(), "false --flag", "/tmp/x.yaml") + assert.ErrorContains(t, err, `editor "false"`) +} From c846b5f3ef4e9c1940a2f1663a4dca81a0b6a990 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 31 Oct 2026 08:30:51 +0000 Subject: [PATCH 02/17] feat(project,endpoint,audit): add label, policy and audit commands The policy selects projects and endpoints by label, but the CLI could not list subjects by label, write custom labels, or show which policy applies to a subject. This change adds them for safedep/control-tower#1591: - project list --selector, project show, project label set and delete, and project policy show. - endpoint list --applied-revision '<N' and --selector, endpoint label set and delete, and endpoint policy show. The endpoint list shows the applied policy revision of each tool. - audit event list, with --since, --until, --action, --resource and --actor. The label commands write only custom/ labels. The CLI rejects every other prefix before the request, because the server rejects it too. Policy show names the source of each value: the default policy, the policy base or a policy override. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MhRi597EX9odoSDXbVBsxz --- README.md | 16 ++ docs/cmd/audit-event-list.md | 60 ++++++ docs/cmd/endpoint-label-delete.md | 33 +++ docs/cmd/endpoint-label-set.md | 45 ++++ docs/cmd/endpoint-list.md | 15 +- docs/cmd/endpoint-policy-show.md | 51 +++++ docs/cmd/project-label-delete.md | 38 ++++ docs/cmd/project-label-set.md | 43 ++++ docs/cmd/project-list.md | 64 ++++++ docs/cmd/project-policy-show.md | 59 ++++++ docs/cmd/project-show.md | 45 ++++ internal/cmd/audit/cmd.go | 28 +++ internal/cmd/audit/list.go | 300 +++++++++++++++++++++++++++ internal/cmd/audit/list_test.go | 142 +++++++++++++ internal/cmd/endpoint/cmd.go | 4 +- internal/cmd/endpoint/list.go | 102 +++++++-- internal/cmd/endpoint/policy.go | 216 +++++++++++++++++++ internal/cmd/endpoint/policy_test.go | 174 ++++++++++++++++ internal/cmd/endpoint/service.go | 48 ++++- internal/cmd/project/cmd.go | 6 +- internal/cmd/project/inventory.go | 227 ++++++++++++++++++++ internal/cmd/project/label.go | 169 +++++++++++++++ internal/cmd/project/policy.go | 86 ++++++++ internal/cmd/project/policy_test.go | 228 ++++++++++++++++++++ internal/cmd/project/resolver.go | 38 ++-- internal/cmd/project/show.go | 174 ++++++++++++++++ internal/cmd/safedep.go | 2 + 27 files changed, 2376 insertions(+), 37 deletions(-) create mode 100644 docs/cmd/audit-event-list.md create mode 100644 docs/cmd/endpoint-label-delete.md create mode 100644 docs/cmd/endpoint-label-set.md create mode 100644 docs/cmd/endpoint-policy-show.md create mode 100644 docs/cmd/project-label-delete.md create mode 100644 docs/cmd/project-label-set.md create mode 100644 docs/cmd/project-list.md create mode 100644 docs/cmd/project-policy-show.md create mode 100644 docs/cmd/project-show.md create mode 100644 internal/cmd/audit/cmd.go create mode 100644 internal/cmd/audit/list.go create mode 100644 internal/cmd/audit/list_test.go create mode 100644 internal/cmd/endpoint/policy.go create mode 100644 internal/cmd/endpoint/policy_test.go create mode 100644 internal/cmd/project/inventory.go create mode 100644 internal/cmd/project/label.go create mode 100644 internal/cmd/project/policy.go create mode 100644 internal/cmd/project/policy_test.go create mode 100644 internal/cmd/project/show.go diff --git a/README.md b/README.md index edeef74..e82c0bc 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,13 @@ Edit the one policy of your tenant: the policy base, policy overrides that selec endpoints and projects by label, and package rules that trust or block packages. Review each policy change before you publish it, and roll back from any policy revision. +**Projects and labels**: `safedep project` +List projects by label selector, set `custom/` labels, and see which policy applies +to a project and why. + +**Audit log**: `safedep audit` +See who changed the policy, what, and when. + **Security telemetry queries**: `safedep query` Run SQL against SafeDep Cloud's query service. Inspect packages, events, and findings across your entire fleet. @@ -123,6 +130,9 @@ Push SafeDep malware findings to external security tools. JFrog XRay is supporte | [`safedep endpoint show`](./docs/cmd/endpoint-show.md) | Show endpoint detail | | [`safedep endpoint activity list`](./docs/cmd/endpoint-activity-list.md) | List recent endpoint activity | | [`safedep endpoint inventory list`](./docs/cmd/endpoint-inventory-list.md) | List current endpoint inventory | +| [`safedep endpoint label set`](./docs/cmd/endpoint-label-set.md) | Set custom labels on endpoints | +| [`safedep endpoint label delete`](./docs/cmd/endpoint-label-delete.md) | Delete custom labels from endpoints | +| [`safedep endpoint policy show`](./docs/cmd/endpoint-policy-show.md) | Show the policy of an endpoint and the source of each value | | [`safedep policy show`](./docs/cmd/policy-show.md) | Show a summary of the tenant policy | | [`safedep policy get`](./docs/cmd/policy-get.md) | Write the policy settings document as YAML | | [`safedep policy edit`](./docs/cmd/policy-edit.md) | Edit the policy settings document in your editor | @@ -140,11 +150,17 @@ Push SafeDep malware findings to external security tools. JFrog XRay is supporte | [`safedep policy rule show`](./docs/cmd/policy-rule-show.md) | Show one package rule | | [`safedep policy rule update`](./docs/cmd/policy-rule-update.md) | Change the reason, expiry, ticket or requester of a package rule | | [`safedep policy rule delete`](./docs/cmd/policy-rule-delete.md) | Delete a package rule | +| [`safedep audit event list`](./docs/cmd/audit-event-list.md) | List audit events of the tenant | | [`safedep query exec`](./docs/cmd/query-exec.md) | Execute a SQL query against SafeDep Cloud | | [`safedep query schema list`](./docs/cmd/query-schema-list.md) | List tables in the query schema | | [`safedep query schema show`](./docs/cmd/query-schema-show.md) | Show one table from the query schema | | [`safedep query schema get`](./docs/cmd/query-schema-get.md) | Get the full schema in one call (for AI agents and scripts) | | [`safedep project sync`](./docs/cmd/project-sync.md) | Sync GitHub or Bitbucket repositories into SafeDep projects | +| [`safedep project list`](./docs/cmd/project-list.md) | List projects with their labels | +| [`safedep project show`](./docs/cmd/project-show.md) | Show one project with its labels and policy | +| [`safedep project label set`](./docs/cmd/project-label-set.md) | Set custom labels on projects | +| [`safedep project label delete`](./docs/cmd/project-label-delete.md) | Delete custom labels from projects | +| [`safedep project policy show`](./docs/cmd/project-policy-show.md) | Show the policy of a project and the source of each value | | [`safedep project scan create`](./docs/cmd/project-scan-create.md) | Submit project scans by name to SafeDep Cloud-hosted scanners | | [`safedep project scan list`](./docs/cmd/project-scan-list.md) | List project scans with filters | | [`safedep package scan run`](./docs/cmd/package-scan-run.md) | Submit a package for on-demand scanning | diff --git a/docs/cmd/audit-event-list.md b/docs/cmd/audit-event-list.md new file mode 100644 index 0000000..3b78ef6 --- /dev/null +++ b/docs/cmd/audit-event-list.md @@ -0,0 +1,60 @@ +# safedep audit event list + +List the audit events of the tenant, newest first. Each admin action, such as a +policy publish or a label change, writes one audit event. + +## Synopsis + +``` +safedep audit event list [--since DURATION] [--until DURATION] [--action PREFIX] + [--resource KIND[/ID]] [--actor ACTOR] + [--limit N] [--page-token TOKEN] [--output table|plain|json] +``` + +## Flags + +| Flag | Description | +|------|-------------| +| `--since <duration>` | Only events in this time before now, as `7d` or `12h`. | +| `--until <duration>` | Only events older than this time before now, as `1d`. It must be shorter than `--since`. | +| `--action <prefix>` | Only events whose action starts with this text, as `policy.` or `policy.rule.`. | +| `--resource <kind[/id]>` | Only events about a resource kind, or one resource, as `package_rule` or `policy_change/18`. | +| `--actor <actor>` | Only events of this actor. The server matches the actor id or the display name exactly. | +| `--limit <n>` | Page size. The server default applies when 0. | +| `--page-token <token>` | Continuation token from a prior response. | + +## Examples + +```bash +safedep audit event list --since 7d --action policy. +``` + +``` +Audit events +WHEN ACTOR ACTION RESOURCE RESULT DETAIL +10m ago alice policy.rule.delete package_rule r_80b success revision=51 +12m ago alice policy.rule.update package_rule r_77e success revision=50 +2d ago alice policy.change.publish policy_change 18 success revision=47 +3 events +``` + +## Output + +`json` holds `events` (event id, actor, actor kind, action, resource kind and id, +result, details, request id, time) and `next_page_token`. `plain` writes a +tab-separated header and one row for each event. + +## Permissions + +Reading the audit log needs the Admin role. + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The page was read. | +| non-zero | Validation, authentication or the request failed. | diff --git a/docs/cmd/endpoint-label-delete.md b/docs/cmd/endpoint-label-delete.md new file mode 100644 index 0000000..851ab63 --- /dev/null +++ b/docs/cmd/endpoint-label-delete.md @@ -0,0 +1,33 @@ +# safedep endpoint label delete + +Delete `custom/` labels from endpoints. The change takes effect at the next +policy fetch of each endpoint. + +## Synopsis + +``` +safedep endpoint label delete ENDPOINT... --key custom/KEY... +``` + +## Flags + +| Flag | Description | +|------|-------------| +| `--key <custom/key>` | A label key. Repeatable, up to 32. | + +## Examples + +```bash +safedep endpoint label delete arjuns-mbp --key custom/team +``` + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The labels were deleted. | +| non-zero | Validation, endpoint resolution or the request failed. | diff --git a/docs/cmd/endpoint-label-set.md b/docs/cmd/endpoint-label-set.md new file mode 100644 index 0000000..69e31a5 --- /dev/null +++ b/docs/cmd/endpoint-label-set.md @@ -0,0 +1,45 @@ +# safedep endpoint label set + +Set `custom/` labels on endpoints. A policy override selects endpoints by their +labels. The label takes effect at the next policy fetch of each endpoint. + +## Synopsis + +``` +safedep endpoint label set ENDPOINT... --label custom/KEY=VALUE... +``` + +## Flags + +| Flag | Description | +|------|-------------| +| `--label <custom/key=value>` | A label. Repeatable, up to 32. | + +An endpoint is a ULID, a unique ULID prefix, or a hostname that +`safedep endpoint list` cached. Give up to 100 endpoints. An admin writes only +`custom/` labels: the shared managed file sets `managed/` labels, and the tools +report `reported/` labels. + +Until endpoint enrollment ships, an endpoint label is not an access boundary. +Select on `custom/` labels for a policy override that loosens the policy. + +## Examples + +```bash +safedep endpoint label set arjuns-mbp --label custom/team=release +``` + +``` +✓ label set on 1 endpoint. It takes effect at the next policy fetch of each endpoint +``` + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The labels were set. | +| non-zero | Validation, endpoint resolution or the request failed. | diff --git a/docs/cmd/endpoint-list.md b/docs/cmd/endpoint-list.md index 4a6976c..2cd2529 100644 --- a/docs/cmd/endpoint-list.md +++ b/docs/cmd/endpoint-list.md @@ -1,6 +1,6 @@ # safedep endpoint list -List endpoints reporting to SafeDep Cloud, with optional filters for capability, blocked installs, silent duration, and identity search. +List endpoints reporting to SafeDep Cloud, with optional filters for capability, blocked installs, silent duration, identity search, labels, and the applied policy revision. ## Synopsis @@ -17,6 +17,8 @@ safedep endpoint list [flags] [--output table|plain|json] [--profile <name>] | `--blocked` | Only endpoints with at least one blocked package-guard install in the window. | | `--silent-for <duration>` | Only endpoints whose last sync is older than this duration (client-side filter; best-effort within `--limit`). | | `--search <substring>` | Case-insensitive substring match on hostname or name (client-side filter; best-effort within `--limit`). | +| `--selector <selector>` | Only endpoints whose labels match this label selector, as `managed/deployment-kind=laptop,custom/team=release`. The syntax is the one of [`safedep project list`](./project-list.md). | +| `--applied-revision '<N'` | Only endpoints where a tool applies a policy revision lower than `N`, as `'<48'`. Quote the value, because the shell reads `<`. | | `--limit <n>` | Page size. Server default applies when `0` (the default). | | `--page-token <token>` | Continuation token from a prior response, to fetch the following page. | @@ -24,6 +26,17 @@ Inherits root flags `--output` and `--profile`. ## Examples +Find the endpoints that have not applied policy revision 48 yet: + +```bash +safedep endpoint list --applied-revision '<48' +``` + +The `Policy` column shows the applied policy revision that each tool reported: +`rev 48` when every tool applies the same revision, or `pmg 48, vet 47`. JSON +output carries `tool_policies` for each endpoint: the tool, its version, its +applied policy revision and the state of the policy in the tool. + List all endpoints active in the last 24 hours (default window): ```bash diff --git a/docs/cmd/endpoint-policy-show.md b/docs/cmd/endpoint-policy-show.md new file mode 100644 index 0000000..3e252fa --- /dev/null +++ b/docs/cmd/endpoint-policy-show.md @@ -0,0 +1,51 @@ +# safedep endpoint policy show + +Show the intended policy of one endpoint: each field, its value, and its source. +The output also shows the applied policy revision and the exceptions that each +tool reported, such as a field that a managed file locks. + +## Synopsis + +``` +safedep endpoint policy show ENDPOINT [--field PATH]... [--output table|plain|json] +``` + +## Flags + +| Flag | Description | +|------|-------------| +| `--field <path>` | Show only this contract path, or the paths below it. Repeatable. | + +## Examples + +```bash +safedep endpoint policy show arjuns-mbp --field package_admission.cooldown.min_age +``` + +``` +Endpoint arjuns-mbp (01KR0EKN6PMW0ZRFRN992H1PKX) +Policy revision 52 · overrides laptops (100) +Default policy revision 12 +Package rules 211 (184 trust, 27 block) + +FIELD VALUE SOURCE EXCEPTIONS +package_admission.cooldown.min_age 5d override "laptops" (100) pmg: locked (floor in /etc/safedep/cloud.yml) + +Applied policy, as each tool reported it +TOOL VERSION REVISION STATE FETCHED REPORTED +pmg 2.3.1 52 applied 3m ago 3m ago +``` + +The output format is the same as for +[`safedep project policy show`](./project-policy-show.md). + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The policy was read. | +| non-zero | Validation, endpoint resolution or the request failed. | diff --git a/docs/cmd/project-label-delete.md b/docs/cmd/project-label-delete.md new file mode 100644 index 0000000..fcfa584 --- /dev/null +++ b/docs/cmd/project-label-delete.md @@ -0,0 +1,38 @@ +# safedep project label delete + +Delete `custom/` labels from projects. The change takes effect at the next check +of each project. + +## Synopsis + +``` +safedep project label delete [PROJECT_NAME...] [--project-id ID]... --key custom/KEY... +``` + +## Flags + +| Flag | Description | +|------|-------------| +| `--key <custom/key>` | A label key. Repeatable, up to 32. | +| `--project-id <id>` | A project ID instead of a name. Repeatable. | + +## Examples + +```bash +safedep project label delete acme/ledger --key custom/criticality +``` + +``` +✓ label deleted from 1 project. It takes effect at the next check of each project +``` + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The labels were deleted. | +| non-zero | Validation, name resolution or the request failed. | diff --git a/docs/cmd/project-label-set.md b/docs/cmd/project-label-set.md new file mode 100644 index 0000000..2242c3c --- /dev/null +++ b/docs/cmd/project-label-set.md @@ -0,0 +1,43 @@ +# safedep project label set + +Set `custom/` labels on projects. A policy override selects projects by their +labels. The label takes effect at the next check of each project. + +## Synopsis + +``` +safedep project label set [PROJECT_NAME...] [--project-id ID]... --label custom/KEY=VALUE... +``` + +## Flags + +| Flag | Description | +|------|-------------| +| `--label <custom/key=value>` | A label. Repeatable, up to 32. | +| `--project-id <id>` | A project ID instead of a name. Repeatable. | + +Give up to 100 projects by exact name or ID. An admin writes only `custom/` +labels. The CLI rejects any other prefix before the request: the forge sync +writes `scm/` and `scm-property/` labels, and the server writes `safedep.io/` +labels. A value has at most 63 characters. + +## Examples + +```bash +safedep project label set acme/payments-api acme/ledger PAY/settlement --label custom/criticality=high +``` + +``` +✓ label set on 3 projects. It takes effect at the next check of each project +``` + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The labels were set. | +| non-zero | Validation, name resolution or the request failed. | diff --git a/docs/cmd/project-list.md b/docs/cmd/project-list.md new file mode 100644 index 0000000..d340a1d --- /dev/null +++ b/docs/cmd/project-list.md @@ -0,0 +1,64 @@ +# safedep project list + +List the projects of the tenant with their labels. A repository is a project. + +## Synopsis + +``` +safedep project list [--selector SELECTOR] [--source SOURCE]... [--name NAME]... + [--limit N] [--page-token TOKEN] [--output table|plain|json] +``` + +## Flags + +| Flag | Description | +|------|-------------| +| `--selector <selector>` | A label selector, as a policy override uses. See below. | +| `--source <source>` | `github`, `gitlab`, `bitbucket`, `other`, `developer-machine` or `container-image`. Repeatable. | +| `--name <name>` | An exact project name. Repeat for up to 10 names. | +| `--limit <n>` | Page size. The server default applies when 0. | +| `--page-token <token>` | Continuation token from a prior response. | + +A selector has terms separated by commas. The terms AND together: + +| Term | Matches | +|------|---------| +| `key=value` | The label has the value. | +| `key!=value` | The label does not have the value. | +| `key in (a,b)` | The label has one of the values. | +| `key notin (a,b)` | The label has none of the values. | +| `key` | The label exists. | +| `!key` | The label does not exist. | + +## Examples + +Find the projects that a policy override will select: + +```bash +safedep project list --selector scm-property/criticality=high +``` + +``` +Projects +PROJECT SOURCE LABELS VULNS VIOLATIONS CREATED +acme/payments-api github custom/team=pay, scm-property/criticality=high 3 - 3d ago +acme/ledger github scm-property/criticality=high 0 - 1mo ago +2 projects +``` + +## Output + +`json` holds `projects` (project id, name, source, origin URL, labels, counts, +creation time) and `next_page_token`. `plain` writes a tab-separated header and +one row for each project. + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The page was read. | +| non-zero | Validation, authentication or the request failed. | diff --git a/docs/cmd/project-policy-show.md b/docs/cmd/project-policy-show.md new file mode 100644 index 0000000..1b07da1 --- /dev/null +++ b/docs/cmd/project-policy-show.md @@ -0,0 +1,59 @@ +# safedep project policy show + +Show the intended policy of one project: each field, its value, and its source. +The source is the SafeDep default policy, the policy base, or a policy override. +The output also shows the applied policy revision and the exceptions that each +tool or check reported. + +## Synopsis + +``` +safedep project policy show [PROJECT_NAME | --project-id ID] [--field PATH]... + [--output table|plain|json] +``` + +## Flags + +| Flag | Description | +|------|-------------| +| `--project-id <id>` | The project ID instead of a name. | +| `--field <path>` | Show only this contract path, or the paths below it, as `scan_gate.fail_on` or `scan_gate`. Repeatable. | + +## Examples + +```bash +safedep project policy show acme/payments-api --field scan_gate.fail_on,package_admission.cooldown.min_age +``` + +``` +Project acme/payments-api +Policy revision 47 · overrides payments (200) +Default policy revision 12 +Package rules 211 (184 trust, 27 block) + +FIELD VALUE SOURCE EXCEPTIONS +package_admission.cooldown.min_age 7d override "payments" (200) - +scan_gate.fail_on medium override "payments" (200) - + +Applied policy, as each tool reported it +TOOL VERSION REVISION STATE FETCHED REPORTED +scm-check - 47 applied 3h ago 3h ago +``` + +## Output + +`json` holds the subject, the revision, the matched overrides, the labels, the +rule counts, `fields` (path, value, source, exceptions) and `applied` (one entry +for each tool or check). `plain` writes one `path<TAB>value<TAB>source<TAB>exceptions` +line for each field and one `applied:<tool>` line for each report. + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The policy was read. | +| non-zero | Validation, name resolution or the request failed. | diff --git a/docs/cmd/project-show.md b/docs/cmd/project-show.md new file mode 100644 index 0000000..5bb4356 --- /dev/null +++ b/docs/cmd/project-show.md @@ -0,0 +1,45 @@ +# safedep project show + +Show one project by its exact name: its source, its labels from every source, and +the policy revision and policy overrides that apply to it. + +## Synopsis + +``` +safedep project show PROJECT_NAME [--output table|plain|json] +``` + +## Examples + +```bash +safedep project show PAY/settlement +``` + +``` +Project PAY/settlement +ID 3f1c... +Source bitbucket · https://bitbucket.org/acme/settlement +Labels safedep.io/project-source=bitbucket + scm/forge=bitbucket + scm/owner=acme +Policy revision 46 · no override matches · base only +Vulnerabilities 0 +Violations - +Created 3d ago + +Policy of each field: safedep project policy show PAY/settlement +``` + +When the policy service does not answer, the command warns and shows the rest. +When two projects have the name, the command lists their ids. + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The project was read. | +| non-zero | The project does not exist, the name is ambiguous, or the request failed. | diff --git a/internal/cmd/audit/cmd.go b/internal/cmd/audit/cmd.go new file mode 100644 index 0000000..b63c86b --- /dev/null +++ b/internal/cmd/audit/cmd.go @@ -0,0 +1,28 @@ +// Package audit registers the `safedep audit` command tree. It reads the +// audit events of the tenant from SafeDep Cloud: who did an admin action, +// what, to which resource, when, and with which result. Every verb needs +// control plane credentials and the Admin role. +package audit + +import ( + "github.com/spf13/cobra" + + "github.com/safedep/cli/internal/app" +) + +func Register(root *cobra.Command, a *app.App) { + parent := &cobra.Command{ + Use: "audit", + Short: "Read the audit log of your SafeDep Cloud tenant", + Long: "Read the audit log of your SafeDep Cloud tenant. Each admin action, such as a policy " + + "publish or a label change, writes one audit event. Reading the audit log needs the Admin role.", + } + event := &cobra.Command{ + Use: "event", + Short: "List audit events", + Long: "List the audit events of the tenant, newest first, with filters for time, action, resource and actor.", + } + event.AddCommand(eventListCmd(a)) + parent.AddCommand(event) + root.AddCommand(parent) +} diff --git a/internal/cmd/audit/list.go b/internal/cmd/audit/list.go new file mode 100644 index 0000000..854839a --- /dev/null +++ b/internal/cmd/audit/list.go @@ -0,0 +1,300 @@ +package audit + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "sort" + "strings" + "time" + + auditv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/audit/v1/auditv1grpc" + messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" + auditv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/audit/v1" + "github.com/safedep/dry/tui/humanize" + "github.com/safedep/dry/tui/table" + "github.com/safedep/dry/usefulerror" + "github.com/spf13/cobra" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/duration" + "github.com/safedep/cli/internal/paging" + "github.com/safedep/cli/internal/tui" +) + +const resultPrefix = "AUDIT_RESULT_" + +// eventLister is the one RPC that the command calls. +type eventLister interface { + ListAuditEvents( + context.Context, + *auditv1.ListAuditEventsRequest, + ...grpc.CallOption, + ) (*auditv1.ListAuditEventsResponse, error) +} + +type listInput struct { + Since time.Duration + Until time.Duration + Action string + Resource string + Actor string + PageSize uint32 + PageToken string +} + +type eventView struct { + ID string `json:"event_id"` + Actor string `json:"actor"` + ActorKind string `json:"actor_kind"` + Action string `json:"action"` + Kind string `json:"resource_kind"` + ResourceID string `json:"resource_id"` + Result string `json:"result"` + Details map[string]any `json:"details,omitempty"` + RequestID string `json:"request_id,omitempty"` + OccurredAt string `json:"occurred_at"` + occurred *time.Time +} + +type listResult struct { + Events []eventView `json:"events"` + NextPageToken string `json:"next_page_token,omitempty"` +} + +func eventListCmd(a *app.App) *cobra.Command { + var in listInput + cmd := &cobra.Command{ + Use: "list", + Short: "List audit events, newest first", + Long: "List the audit events of the tenant, newest first. --since and --until take a duration " + + "before now, as in 7d or 12h. --action takes a prefix of the action, as in policy. or " + + "policy.rule. --resource takes a resource kind, or a kind and an id, as in policy_change/18. " + + "--actor matches the actor id or the display name exactly. One page is returned per " + + "invocation, so follow --page-token to read the next page.", + Args: func(cmd *cobra.Command, args []string) error { + if err := cobra.NoArgs(cmd, args); err != nil { + return err + } + _, err := newListRequest(in, time.Now()) + return err + }, + RunE: func(cmd *cobra.Command, _ []string) error { + client, err := a.ControlPlane() + if err != nil { + return err + } + res, err := runList(cmd.Context(), auditv1grpc.NewAuditServiceClient(client.Connection()), in, time.Now()) + if err != nil { + return err + } + return a.Output.Print(res) + }, + } + f := cmd.Flags() + f.Var(duration.NewValue(&in.Since, 0), "since", "only events in this time before now, as in 7d or 12h") + f.Var(duration.NewValue(&in.Until, 0), "until", "only events older than this time before now, as in 1d") + f.StringVar(&in.Action, "action", "", "only events whose action starts with this text, as in policy.") + f.StringVar(&in.Resource, "resource", "", "only events about a resource: KIND or KIND/ID, as in policy_change/18") + f.StringVar(&in.Actor, "actor", "", "only events of this actor id or display name, as in alice@acme.io") + f.Uint32Var(&in.PageSize, "limit", 0, "page size; server default when 0") + f.StringVar(&in.PageToken, "page-token", "", "continuation token from a prior response") + return cmd +} + +func invalidFilter(cause error, help string) error { + return usefulerror.NewUsefulError(). + WithCode(usefulerror.ErrBadRequest). + WithHumanError(cause.Error()). + WithHelp(help). + Wrap(cause) +} + +func newListRequest(in listInput, now time.Time) (*auditv1.ListAuditEventsRequest, error) { + filters := &auditv1.ListAuditEventsRequest_Filters{} + set := false + if in.Since < 0 || in.Until < 0 { + return nil, invalidFilter(errors.New("--since and --until must not be negative"), "Use a duration such as 7d") + } + if in.Since > 0 { + filters.SetOccurredAfter(timestamppb.New(now.Add(-in.Since))) + set = true + } + if in.Until > 0 { + if in.Since > 0 && in.Until >= in.Since { + return nil, invalidFilter(errors.New("--until must be shorter than --since"), + "As in --since 7d --until 1d for the events from 7 days ago to 1 day ago") + } + filters.SetOccurredBefore(timestamppb.New(now.Add(-in.Until))) + set = true + } + if in.Action != "" { + filters.SetActionPrefix(in.Action) + set = true + } + if in.Resource != "" { + kind, id, hasID := strings.Cut(in.Resource, "/") + if kind == "" || (hasID && id == "") { + return nil, invalidFilter(fmt.Errorf("--resource %q: write KIND or KIND/ID", in.Resource), + "As in --resource package_rule or --resource policy_change/18") + } + filters.SetResourceKind(kind) + if hasID { + filters.SetResourceId(id) + } + set = true + } + if in.Actor != "" { + filters.SetActor(in.Actor) + set = true + } + + req := &auditv1.ListAuditEventsRequest{} + req.SetPagination(paging.NewPaginationRequest(in.PageSize, in.PageToken)) + if set { + req.SetFilters(filters) + } + return req, nil +} + +func runList(ctx context.Context, client eventLister, in listInput, now time.Time) (*listResult, error) { + req, err := newListRequest(in, now) + if err != nil { + return nil, err + } + res, err := client.ListAuditEvents(ctx, req) + if err != nil { + return nil, mapListError(err) + } + out := &listResult{ + Events: make([]eventView, 0, len(res.GetEvents())), + NextPageToken: res.GetPagination().GetNextPageToken(), + } + for _, e := range res.GetEvents() { + out.Events = append(out.Events, newEventView(e)) + } + return out, nil +} + +func mapListError(err error) error { + cause := fmt.Errorf("audit event list: %w", err) + if st, ok := status.FromError(err); ok && st.Code() == codes.PermissionDenied { + return usefulerror.NewUsefulError(). + WithCode(usefulerror.ErrAuthorizationFailed). + WithHumanError("Only an Admin can read the audit log"). + WithHelp("Ask an Admin of the tenant to run the command"). + Wrap(cause) + } + return cause +} + +func newEventView(e *auditv1.AuditEvent) eventView { + v := eventView{ + ID: e.GetEventId(), + Actor: actorName(e.GetActor()), + ActorKind: tui.EnumToken(e.GetActor().GetKind().String(), "ACTOR_KIND_"), + Action: e.GetAction(), + Kind: e.GetResource().GetKind(), + ResourceID: e.GetResource().GetId(), + Result: tui.EnumToken(e.GetResult().String(), resultPrefix), + RequestID: e.GetRequestId(), + } + if e.HasDetails() { + v.Details = e.GetDetails().AsMap() + } + if ts := e.GetOccurredAt(); ts != nil { + t := ts.AsTime().UTC() + v.occurred = &t + v.OccurredAt = t.Format(time.RFC3339) + } + return v +} + +func actorName(a *messagescontroltowerv1.Actor) string { + if a.GetDisplayName() != "" { + return a.GetDisplayName() + } + return a.GetId() +} + +func (v eventView) resource() string { + if v.ResourceID == "" { + return v.Kind + } + return v.Kind + " " + v.ResourceID +} + +// detail writes the details as sorted "key=value" items. +func (v eventView) detail() string { + keys := make([]string, 0, len(v.Details)) + for k := range v.Details { + keys = append(keys, k) + } + sort.Strings(keys) + parts := make([]string, 0, len(keys)) + for _, k := range keys { + value := v.Details[k] + text := fmt.Sprint(value) + if _, scalar := value.(string); !scalar { + if b, err := json.Marshal(value); err == nil { + text = string(b) + } + } + parts = append(parts, k+"="+text) + } + return strings.Join(parts, ", ") +} + +func (r *listResult) RenderJSON() ([]byte, error) { + return json.MarshalIndent(r, "", " ") +} + +func (r *listResult) RenderTable() string { + now := time.Now() + rows := make([][]string, 0, len(r.Events)) + for _, e := range r.Events { + when := "-" + if e.occurred != nil { + when = humanize.Time(*e.occurred, now) + } + detail := e.detail() + if detail == "" { + detail = "-" + } + rows = append(rows, []string{when, e.Actor, e.Action, e.resource(), e.Result, detail}) + } + t := table.New(). + Title("Audit events"). + Headers("WHEN", "ACTOR", "ACTION", "RESOURCE", "RESULT", "DETAIL"). + Rows(rows...). + EmptyMessage("No audit events match. Try a wider --since window.") + if len(rows) > 0 { + footer := fmt.Sprintf("%d %s", len(rows), plural(len(rows))) + if r.NextPageToken != "" { + footer += ". More available: --page-token " + r.NextPageToken + } + t = t.Footer(footer) + } + return t.Render() +} + +func (r *listResult) RenderPlain() string { + var b strings.Builder + b.WriteString("occurred_at\tactor\taction\tresource_kind\tresource_id\tresult\tdetails") + for _, e := range r.Events { + fmt.Fprintf(&b, "\n%s\t%s\t%s\t%s\t%s\t%s\t%s", e.OccurredAt, e.Actor, e.Action, e.Kind, e.ResourceID, e.Result, e.detail()) + } + return b.String() +} + +func plural(n int) string { + if n == 1 { + return "event" + } + return "events" +} diff --git a/internal/cmd/audit/list_test.go b/internal/cmd/audit/list_test.go new file mode 100644 index 0000000..8b39105 --- /dev/null +++ b/internal/cmd/audit/list_test.go @@ -0,0 +1,142 @@ +package audit + +import ( + "context" + "testing" + "time" + + messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" + auditv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/audit/v1" + "github.com/safedep/dry/usefulerror" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/structpb" + "google.golang.org/protobuf/types/known/timestamppb" +) + +var now = time.Date(2026, 10, 31, 12, 0, 0, 0, time.UTC) + +// fakeLister is a hand fake for the one RPC of eventLister. +type fakeLister struct { + req *auditv1.ListAuditEventsRequest + res *auditv1.ListAuditEventsResponse + err error +} + +func (f *fakeLister) ListAuditEvents(_ context.Context, req *auditv1.ListAuditEventsRequest, _ ...grpc.CallOption) (*auditv1.ListAuditEventsResponse, error) { + f.req = req + return f.res, f.err +} + +func TestNewListRequest(t *testing.T) { + tests := []struct { + name string + in listInput + check func(*testing.T, *auditv1.ListAuditEventsRequest_Filters) + wantErr string + }{ + { + name: "no filters", + in: listInput{}, + check: func(t *testing.T, f *auditv1.ListAuditEventsRequest_Filters) { + assert.Nil(t, f) + }, + }, + { + name: "every filter", + in: listInput{ + Since: 7 * 24 * time.Hour, Until: 24 * time.Hour, + Action: "policy.", Resource: "policy_change/18", Actor: "alice@acme.io", + }, + check: func(t *testing.T, f *auditv1.ListAuditEventsRequest_Filters) { + assert.Equal(t, now.Add(-7*24*time.Hour), f.GetOccurredAfter().AsTime()) + assert.Equal(t, now.Add(-24*time.Hour), f.GetOccurredBefore().AsTime()) + assert.Equal(t, "policy.", f.GetActionPrefix()) + assert.Equal(t, "policy_change", f.GetResourceKind()) + assert.Equal(t, "18", f.GetResourceId()) + assert.Equal(t, "alice@acme.io", f.GetActor()) + }, + }, + { + name: "resource kind only", + in: listInput{Resource: "package_rule"}, + check: func(t *testing.T, f *auditv1.ListAuditEventsRequest_Filters) { + assert.Equal(t, "package_rule", f.GetResourceKind()) + assert.False(t, f.HasResourceId()) + }, + }, + {name: "empty resource id", in: listInput{Resource: "policy_change/"}, wantErr: "write KIND or KIND/ID"}, + {name: "empty resource kind", in: listInput{Resource: "/18"}, wantErr: "write KIND or KIND/ID"}, + {name: "until after since", in: listInput{Since: time.Hour, Until: 2 * time.Hour}, wantErr: "--until must be shorter than --since"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + req, err := newListRequest(tt.in, now) + if tt.wantErr != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantErr) + return + } + require.NoError(t, err) + if req.HasFilters() { + tt.check(t, req.GetFilters()) + } else { + tt.check(t, nil) + } + }) + } +} + +func auditEvent() *auditv1.AuditEvent { + actor := &messagescontroltowerv1.Actor{} + actor.SetKind(messagescontroltowerv1.ActorKind_ACTOR_KIND_USER) + actor.SetId("u_1") + actor.SetDisplayName("alice") + resource := &auditv1.AuditResource{} + resource.SetKind("package_rule") + resource.SetId("r_80b") + details, err := structpb.NewStruct(map[string]any{"revision": 51, "reason": "no longer needed"}) + if err != nil { + panic(err) + } + e := &auditv1.AuditEvent{} + e.SetEventId("ev_1") + e.SetActor(actor) + e.SetAction("policy.rule.delete") + e.SetResource(resource) + e.SetResult(auditv1.AuditResult_AUDIT_RESULT_SUCCESS) + e.SetDetails(details) + e.SetOccurredAt(timestamppb.New(time.Now().Add(-10 * time.Minute))) + return e +} + +func TestRunList(t *testing.T) { + res := &auditv1.ListAuditEventsResponse{} + res.SetEvents([]*auditv1.AuditEvent{auditEvent()}) + client := &fakeLister{res: res} + + got, err := runList(context.Background(), client, listInput{Action: "policy.", PageSize: 20}, now) + require.NoError(t, err) + assert.Equal(t, uint32(20), client.req.GetPagination().GetPageSize()) + require.Len(t, got.Events, 1) + + table := got.RenderTable() + for _, want := range []string{"10m ago", "alice", "policy.rule.delete", "package_rule r_80b", "success", "reason=no longer needed, revision=51"} { + assert.Contains(t, table, want) + } + assert.Contains(t, got.RenderPlain(), "\talice\tpolicy.rule.delete\tpackage_rule\tr_80b\tsuccess\t") + b, err := got.RenderJSON() + require.NoError(t, err) + assert.Contains(t, string(b), `"actor_kind": "user"`) +} + +func TestRunList_MemberIsDenied(t *testing.T) { + client := &fakeLister{err: status.Error(codes.PermissionDenied, "member")} + _, err := runList(context.Background(), client, listInput{}, now) + ue, ok := usefulerror.AsUsefulError(err) + require.True(t, ok) + assert.Equal(t, "Only an Admin can read the audit log", ue.HumanError()) +} diff --git a/internal/cmd/endpoint/cmd.go b/internal/cmd/endpoint/cmd.go index 4dbd98a..572da96 100644 --- a/internal/cmd/endpoint/cmd.go +++ b/internal/cmd/endpoint/cmd.go @@ -12,7 +12,7 @@ func Register(root *cobra.Command, a *app.App) { parent := &cobra.Command{ Use: "endpoint", Short: "Inspect endpoints reporting to SafeDep Cloud", - Long: "View fleet health, inspect individual endpoints, audit recent activity, and inspect inventory across endpoints reporting to SafeDep Cloud (Endpoint Hub).", + Long: "View fleet health, inspect individual endpoints, audit recent activity, inspect inventory, and manage the labels and policy of endpoints reporting to SafeDep Cloud (Endpoint Hub).", } parent.AddCommand( statusCmd(a), @@ -20,6 +20,8 @@ func Register(root *cobra.Command, a *app.App) { showCmd(a), activityCmd(a), inventoryCmd(a), + labelCmd(a), + policyCmd(a), ) root.AddCommand(parent) } diff --git a/internal/cmd/endpoint/list.go b/internal/cmd/endpoint/list.go index 0d0a1b6..8a274e6 100644 --- a/internal/cmd/endpoint/list.go +++ b/internal/cmd/endpoint/list.go @@ -4,25 +4,30 @@ import ( "context" "encoding/json" "fmt" + "strconv" "strings" "time" + messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" "github.com/safedep/dry/tui/humanize" "github.com/safedep/dry/tui/table" "github.com/spf13/cobra" ) type listInput struct { - Window TimeWindow - Capabilities []controltowerv1.EndpointCapability - OnlyBlocked bool - SilentFor time.Duration - Search string - PageSize uint32 - PageToken string - _now func() time.Time // injectable for tests + Window TimeWindow + Capabilities []controltowerv1.EndpointCapability + OnlyBlocked bool + SilentFor time.Duration + Search string + LabelSelector *messagescontroltowerv1.LabelSelector + AppliedRevisionBelow uint64 + PageSize uint32 + PageToken string + _now func() time.Time // injectable for tests } type capabilityToken string @@ -37,6 +42,7 @@ const ( func listCmd(a *app.App) *cobra.Command { var ( searchFlag, pageTokenFlag string + selectorFlag, appliedFlag string since time.Duration capabilitiesRaw []string onlyBlocked bool @@ -46,8 +52,15 @@ func listCmd(a *app.App) *cobra.Command { cmd := &cobra.Command{ Use: "list", Short: "List endpoints with filters", - Long: "List endpoints reporting to SafeDep Cloud, with filters for capability, blocked installs, silent duration, and identity search.", + Long: "List endpoints reporting to SafeDep Cloud, with filters for capability, blocked installs, silent duration, identity search, " + + "labels, and the applied policy revision. --applied-revision '<48' keeps the endpoints where a tool applies a policy " + + "revision lower than 48, so you can see which endpoints have not applied a publish yet. The POLICY column shows the " + + "applied policy revision that each tool reported.", RunE: func(cmd *cobra.Command, _ []string) error { + selector, applied, err := parsePolicyFilters(selectorFlag, appliedFlag) + if err != nil { + return err + } client, err := a.ControlPlane() if err != nil { return err @@ -64,6 +77,7 @@ func listCmd(a *app.App) *cobra.Command { in := listInput{ Window: window, Capabilities: caps, OnlyBlocked: onlyBlocked, SilentFor: silentFor, Search: searchFlag, + LabelSelector: selector, AppliedRevisionBelow: applied, PageSize: pageSize, PageToken: pageTokenFlag, } res, err := runList(cmd.Context(), NewService(client.Connection()), dir, in) @@ -79,6 +93,8 @@ func listCmd(a *app.App) *cobra.Command { f.BoolVar(&onlyBlocked, "blocked", false, "only endpoints with at least one blocked install in the window") f.DurationVar(&silentFor, "silent-for", 0, "only endpoints not seen for at least this duration (client-side; best-effort within --limit)") f.StringVar(&searchFlag, "search", "", "case-insensitive substring match on hostname/name (client-side; best-effort within --limit)") + f.StringVar(&selectorFlag, "selector", "", "filter: a label selector, as in managed/deployment-kind=laptop,custom/team=release") + f.StringVar(&appliedFlag, "applied-revision", "", "filter: '<N' keeps endpoints where a tool applies a policy revision lower than N, as in '<48'") f.Uint32Var(&pageSize, "limit", 0, "page size; server default when 0") f.StringVar(&pageTokenFlag, "page-token", "", "continuation token from a prior response") return cmd @@ -91,6 +107,7 @@ func runList(ctx context.Context, lister EndpointLister, dir *Directory, in list } res, err := lister.List(ctx, ListInput{ Window: in.Window, Capabilities: in.Capabilities, MinPMGBlocked: minBlocked, + LabelSelector: in.LabelSelector, AppliedRevisionBelow: in.AppliedRevisionBelow, PageSize: in.PageSize, PageToken: in.PageToken, }) if err != nil { @@ -178,22 +195,33 @@ type listResult struct { } func (r *listResult) RenderJSON() ([]byte, error) { + type toolPolicy struct { + Tool string `json:"tool"` + Version string `json:"tool_version,omitempty"` + Revision uint64 `json:"applied_policy_revision"` + State string `json:"state"` + } type row struct { ID, Identifier, Hostname, OS, Arch string LastSync time.Time Capabilities []string Blocked uint64 Inventory uint64 + ToolPolicies []toolPolicy `json:"tool_policies"` } out := struct { Endpoints []row `json:"endpoints"` NextPage string `json:"next_page_token,omitempty"` }{NextPage: r.nextPage} for _, e := range r.endpoints { + policies := make([]toolPolicy, 0, len(e.ToolPolicies)) + for _, p := range e.ToolPolicies { + policies = append(policies, toolPolicy{Tool: p.Tool, Version: p.Version, Revision: p.Revision, State: p.State}) + } out.Endpoints = append(out.Endpoints, row{ ID: e.ID, Identifier: e.Identifier, Hostname: e.Hostname, OS: e.OS, Arch: e.Arch, LastSync: e.LastSync, Capabilities: capabilityNames(e.Capabilities), - Blocked: e.PMGBlockedEvents, Inventory: e.InventoryEvents, + Blocked: e.PMGBlockedEvents, Inventory: e.InventoryEvents, ToolPolicies: policies, }) } return json.MarshalIndent(out, "", " ") @@ -204,11 +232,11 @@ func (r *listResult) RenderPlain() string { return "no endpoints" } var b strings.Builder - b.WriteString("ID\tHOSTNAME\tOS\tCAPS\tLAST SYNC\tBLOCKED\tINVENTORY\n") + b.WriteString("ID\tHOSTNAME\tOS\tCAPS\tLAST SYNC\tBLOCKED\tINVENTORY\tPOLICY\n") for _, e := range r.endpoints { - fmt.Fprintf(&b, "%s\t%s\t%s/%s\t%s\t%s\t%d\t%d\n", + fmt.Fprintf(&b, "%s\t%s\t%s/%s\t%s\t%s\t%d\t%d\t%s\n", e.ID, e.Hostname, e.OS, e.Arch, strings.Join(capabilityNames(e.Capabilities), ","), - formatTime(e.LastSync), e.PMGBlockedEvents, e.InventoryEvents, + formatTime(e.LastSync), e.PMGBlockedEvents, e.InventoryEvents, policyCell(e.ToolPolicies), ) } return strings.TrimRight(b.String(), "\n") @@ -224,11 +252,12 @@ func (r *listResult) RenderTable() string { humanize.Time(e.LastSync, now), fmt.Sprint(e.PMGBlockedEvents), fmt.Sprint(e.InventoryEvents), + policyCell(e.ToolPolicies), }) } t := table.New(). Title("Endpoints"). - Headers("ID", "Hostname", "OS/Arch", "Capabilities", "Last Sync", "Blocked", "Inventory"). + Headers("ID", "Hostname", "OS/Arch", "Capabilities", "Last Sync", "Blocked", "Inventory", "Policy"). Rows(rows...). EmptyMessage("No endpoints found. Endpoints appear after a SafeDep tool syncs. Try a wider --since window.") if len(rows) > 0 { @@ -366,3 +395,48 @@ func capabilityNames(caps []controltowerv1.EndpointCapability) []string { } return out } + +// parsePolicyFilters reads --selector and --applied-revision. The contract +// filters on a revision below a bound only, so '<N' is the one form. +func parsePolicyFilters(selector, applied string) (*messagescontroltowerv1.LabelSelector, uint64, error) { + var sel *messagescontroltowerv1.LabelSelector + if selector != "" { + parsed, err := cloudpolicy.ParseSelector(selector) + if err != nil { + return nil, 0, err + } + sel = parsed + } + if applied == "" { + return sel, 0, nil + } + text, ok := strings.CutPrefix(strings.TrimSpace(applied), "<") + n, err := strconv.ParseUint(strings.TrimSpace(text), 10, 64) + if !ok || err != nil || n < 2 { + return nil, 0, fmt.Errorf("--applied-revision %q: write '<N' with N of 2 or more, as in '<48', "+ + "for the endpoints where a tool applies a policy revision lower than N", applied) + } + return sel, n, nil +} + +// policyCell shows the applied policy revision of each tool, as "rev 47" when +// every tool applies the same revision, or "pmg 47, vet 46". +func policyCell(policies []ToolPolicy) string { + if len(policies) == 0 { + return "-" + } + same := true + for _, p := range policies[1:] { + if p.Revision != policies[0].Revision { + same = false + } + } + if same { + return fmt.Sprintf("rev %d", policies[0].Revision) + } + parts := make([]string, 0, len(policies)) + for _, p := range policies { + parts = append(parts, fmt.Sprintf("%s %d", p.Tool, p.Revision)) + } + return strings.Join(parts, ", ") +} diff --git a/internal/cmd/endpoint/policy.go b/internal/cmd/endpoint/policy.go new file mode 100644 index 0000000..9845198 --- /dev/null +++ b/internal/cmd/endpoint/policy.go @@ -0,0 +1,216 @@ +package endpoint + +import ( + "context" + "fmt" + + policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" + messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" + specv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/spec/v1" + "github.com/safedep/dry/tui" + "github.com/spf13/cobra" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" +) + +// This file holds the policy verbs of the endpoint tree: `label set|delete` +// and `policy show`. An endpoint argument is a ULID, a unique ULID prefix, +// or a hostname that `safedep endpoint list` cached. + +func labelCmd(a *app.App) *cobra.Command { + parent := &cobra.Command{ + Use: "label", + Short: "Set or delete the custom labels of endpoints", + Long: "Set or delete the custom/ labels of endpoints. A policy override selects endpoints by their " + + "labels. An admin writes only custom/ labels. The shared managed file sets managed/ labels, and " + + "the tools report reported/ labels. A label change takes effect at the next policy fetch of " + + "each endpoint.", + } + parent.AddCommand(labelSetCmd(a), labelDeleteCmd(a)) + return parent +} + +func labelSetCmd(a *app.App) *cobra.Command { + var labels []string + cmd := &cobra.Command{ + Use: "set ENDPOINT... --label custom/KEY=VALUE", + Short: "Set custom labels on endpoints", + Long: "Set custom/ labels on up to 100 endpoints. A label with an existing key gets the new value. " + + "The label takes effect at the next policy fetch of each endpoint.", + Args: func(cmd *cobra.Command, args []string) error { + if err := cobra.MinimumNArgs(1)(cmd, args); err != nil { + return err + } + _, err := cloudpolicy.ParseCustomLabels(labels) + return err + }, + RunE: func(cmd *cobra.Command, args []string) error { + parsed, err := cloudpolicy.ParseCustomLabels(labels) + if err != nil { + return err + } + client, err := a.ControlPlane() + if err != nil { + return err + } + dir, err := NewDirectoryFromApp(a) + if err != nil { + return err + } + n, err := runLabelSet(cmd.Context(), cloudpolicy.NewLabelClient(client.Connection()), dir, args, parsed) + if err != nil { + return err + } + tui.Success("label set on %d %s. It takes effect at the next policy fetch of each endpoint", + n, plural(n, "endpoint", "endpoints")) + return nil + }, + } + cmd.Flags().StringArrayVar(&labels, "label", nil, "a label as custom/KEY=VALUE; repeatable") + return cmd +} + +func labelDeleteCmd(a *app.App) *cobra.Command { + var keys []string + cmd := &cobra.Command{ + Use: "delete ENDPOINT... --key custom/KEY", + Short: "Delete custom labels from endpoints", + Long: "Delete custom/ labels from up to 100 endpoints. The change takes effect at the next policy fetch of each endpoint.", + Args: func(cmd *cobra.Command, args []string) error { + if err := cobra.MinimumNArgs(1)(cmd, args); err != nil { + return err + } + return cloudpolicy.ValidateCustomKeys(keys) + }, + RunE: func(cmd *cobra.Command, args []string) error { + client, err := a.ControlPlane() + if err != nil { + return err + } + dir, err := NewDirectoryFromApp(a) + if err != nil { + return err + } + n, err := runLabelDelete(cmd.Context(), cloudpolicy.NewLabelClient(client.Connection()), dir, args, keys) + if err != nil { + return err + } + tui.Success("label deleted from %d %s. It takes effect at the next policy fetch of each endpoint", + n, plural(n, "endpoint", "endpoints")) + return nil + }, + } + cmd.Flags().StringArrayVar(&keys, "key", nil, "a label key as custom/KEY; repeatable") + return cmd +} + +func resolveEndpoints(ctx context.Context, dir *Directory, refs []string) ([]string, error) { + ids := make([]string, 0, len(refs)) + for _, ref := range refs { + id, err := dir.Resolve(ctx, ref) + if err != nil { + return nil, fmt.Errorf("endpoint %q: %w", ref, err) + } + ids = append(ids, id) + } + return ids, nil +} + +func runLabelSet( + ctx context.Context, + client policyv1grpc.LabelServiceClient, + dir *Directory, + refs []string, + labels []*messagescontroltowerv1.Label, +) (int, error) { + ids, err := resolveEndpoints(ctx, dir, refs) + if err != nil { + return 0, err + } + if err := cloudpolicy.SetLabels(ctx, client, specv1.SubjectKind_SUBJECT_KIND_ENDPOINT, ids, labels); err != nil { + return 0, err + } + return len(ids), nil +} + +func runLabelDelete( + ctx context.Context, + client policyv1grpc.LabelServiceClient, + dir *Directory, + refs []string, + keys []string, +) (int, error) { + ids, err := resolveEndpoints(ctx, dir, refs) + if err != nil { + return 0, err + } + if err := cloudpolicy.DeleteLabels(ctx, client, specv1.SubjectKind_SUBJECT_KIND_ENDPOINT, ids, keys); err != nil { + return 0, err + } + return len(ids), nil +} + +func policyCmd(a *app.App) *cobra.Command { + parent := &cobra.Command{ + Use: "policy", + Short: "Inspect the policy of an endpoint", + Long: "Inspect the policy that applies to an endpoint, with the source of each value and what each tool applied.", + } + parent.AddCommand(policyShowCmd(a)) + return parent +} + +func policyShowCmd(a *app.App) *cobra.Command { + var fields []string + cmd := &cobra.Command{ + Use: "show ENDPOINT", + Short: "Show the policy of an endpoint and the source of each value", + Long: "Show the intended policy of one endpoint: each field, its value, and its source, which is " + + "the SafeDep default policy, the policy base, or a policy override. The output also shows the " + + "applied policy revision and the exceptions that each tool reported, such as a field that a " + + "managed file locks. Use --field to show some fields only.", + Args: func(cmd *cobra.Command, args []string) error { + if err := cobra.ExactArgs(1)(cmd, args); err != nil { + return err + } + return cloudpolicy.ValidateFieldPaths(fields) + }, + RunE: func(cmd *cobra.Command, args []string) error { + client, err := a.ControlPlane() + if err != nil { + return err + } + dir, err := NewDirectoryFromApp(a) + if err != nil { + return err + } + res, err := runPolicyShow(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), dir, args[0], fields) + if err != nil { + return err + } + return a.Output.Print(res) + }, + } + cmd.Flags().StringSliceVar(&fields, "field", nil, "show only these contract paths, as in package_admission.cooldown.min_age; repeatable") + return cmd +} + +func runPolicyShow( + ctx context.Context, + client cloudpolicy.SubjectPolicyClient, + dir *Directory, + ref string, + fields []string, +) (*cloudpolicy.SubjectPolicy, error) { + id, err := dir.Resolve(ctx, ref) + if err != nil { + return nil, err + } + name := ref + if entry, ok := dir.Lookup(ctx, id); ok && entry.Hostname != "" { + name = entry.Hostname + } + subject := cloudpolicy.NewSubject(specv1.SubjectKind_SUBJECT_KIND_ENDPOINT, id) + return cloudpolicy.GetSubjectPolicy(ctx, client, subject, name, fields) +} diff --git a/internal/cmd/endpoint/policy_test.go b/internal/cmd/endpoint/policy_test.go new file mode 100644 index 0000000..1432831 --- /dev/null +++ b/internal/cmd/endpoint/policy_test.go @@ -0,0 +1,174 @@ +package endpoint + +import ( + "context" + "testing" + "time" + + controltowerv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/v1/controltowerv1grpc" + recordv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/record/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" + controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/safedep/cli/internal/cloudpolicy" + "github.com/safedep/cli/internal/cloudpolicy/mocks" +) + +const testEndpointID = "01KR0EKN6PMW0ZRFRN992H1PKX" + +// listEndpointsClient fakes the one RPC that Service.List calls. The +// embedded interface is nil, so any other RPC panics the test. +type listEndpointsClient struct { + controltowerv1grpc.EndpointManagementServiceClient + req *controltowerv1.ListEndpointsRequest + res *controltowerv1.ListEndpointsResponse +} + +func (c *listEndpointsClient) ListEndpoints( + _ context.Context, + req *controltowerv1.ListEndpointsRequest, + _ ...grpc.CallOption, +) (*controltowerv1.ListEndpointsResponse, error) { + c.req = req + return c.res, nil +} + +func toolPolicy(tool string, revision uint64) *controltowerv1.EndpointToolPolicy { + report := &recordv1.ApplyReport{} + report.SetRevision(revision) + report.SetState(recordv1.ApplyState_APPLY_STATE_STALE) + p := &controltowerv1.EndpointToolPolicy{} + p.SetToolName(tool) + p.SetToolVersion("2.3.1") + p.SetPolicy(report) + p.SetReportedAt(timestamppb.New(time.Now())) + return p +} + +func TestServiceList_SendsThePolicyFilters(t *testing.T) { + ep := &controltowerv1.ListEndpointsResponse_EndpointWithAttributes{} + ep.SetEndpointId(testEndpointID) + ep.SetToolPolicies([]*controltowerv1.EndpointToolPolicy{toolPolicy("pmg", 47), toolPolicy("vet", 46)}) + res := &controltowerv1.ListEndpointsResponse{} + res.SetEndpoints([]*controltowerv1.ListEndpointsResponse_EndpointWithAttributes{ep}) + fake := &listEndpointsClient{res: res} + + selector, applied, err := parsePolicyFilters("managed/deployment-kind=laptop", "<48") + require.NoError(t, err) + out, err := (&Service{client: fake}).List(context.Background(), ListInput{LabelSelector: selector, AppliedRevisionBelow: applied}) + require.NoError(t, err) + + f := fake.req.GetFilter() + assert.Equal(t, uint64(48), f.GetAppliedPolicyRevisionBelow()) + assert.Equal(t, map[string]string{"managed/deployment-kind": "laptop"}, f.GetLabelSelector().GetMatchLabels()) + require.Len(t, out.Endpoints, 1) + assert.Equal(t, []ToolPolicy{ + {Tool: "pmg", Version: "2.3.1", Revision: 47, State: "stale", ReportedAt: out.Endpoints[0].ToolPolicies[0].ReportedAt}, + {Tool: "vet", Version: "2.3.1", Revision: 46, State: "stale", ReportedAt: out.Endpoints[0].ToolPolicies[1].ReportedAt}, + }, out.Endpoints[0].ToolPolicies) + assert.Equal(t, "pmg 47, vet 46", policyCell(out.Endpoints[0].ToolPolicies)) +} + +func TestParsePolicyFilters(t *testing.T) { + tests := []struct { + applied string + want uint64 + wantErr bool + }{ + {applied: "", want: 0}, + {applied: "<48", want: 48}, + {applied: " < 48 ", want: 48}, + {applied: "48", wantErr: true}, + {applied: ">48", wantErr: true}, + {applied: "<1", wantErr: true}, + {applied: "<x", wantErr: true}, + } + for _, tt := range tests { + t.Run(tt.applied, func(t *testing.T) { + _, got, err := parsePolicyFilters("", tt.applied) + if tt.wantErr { + require.Error(t, err) + assert.Contains(t, err.Error(), "write '<N'") + return + } + require.NoError(t, err) + assert.Equal(t, tt.want, got) + }) + } + _, _, err := parsePolicyFilters("deployment-kind=ci", "") + assert.ErrorContains(t, err, "is not valid") +} + +func TestPolicyCell(t *testing.T) { + assert.Equal(t, "-", policyCell(nil)) + assert.Equal(t, "rev 47", policyCell([]ToolPolicy{{Tool: "pmg", Revision: 47}, {Tool: "vet", Revision: 47}})) +} + +func TestRunList_ShowsTheAppliedRevision(t *testing.T) { + f := &fakeLister{out: &ListResult{Endpoints: []ListEndpoint{{ + ID: testEndpointID, Hostname: "arjuns-mbp", ToolPolicies: []ToolPolicy{{Tool: "pmg", Revision: 47, State: "applied"}}, + }}}} + res, err := runList(context.Background(), f, newNopDirectory(t), listInput{AppliedRevisionBelow: 48}) + require.NoError(t, err) + assert.Equal(t, uint64(48), f.in.AppliedRevisionBelow) + assert.Contains(t, res.RenderTable(), "rev 47") + b, err := res.RenderJSON() + require.NoError(t, err) + assert.Contains(t, string(b), `"applied_policy_revision": 47`) +} + +func TestRunLabelSet_ResolvesCachedHostnames(t *testing.T) { + dir := newTestDirectory(t) + require.NoError(t, dir.Upsert(context.Background(), []DirectoryEntry{{ID: testEndpointID, Hostname: "arjuns-mbp"}})) + labels, err := cloudpolicy.ParseCustomLabels([]string{"custom/team=release"}) + require.NoError(t, err) + + client := mocks.NewLabelServiceClientMock(t) + client.EXPECT().SetSubjectLabels(mock.Anything, mock.MatchedBy(func(r *policyv1.SetSubjectLabelsRequest) bool { + s := r.GetSubjects()[0] + return s.GetKind() == specv1.SubjectKind_SUBJECT_KIND_ENDPOINT && s.GetId() == testEndpointID + })).Return(&policyv1.SetSubjectLabelsResponse{}, nil) + + n, err := runLabelSet(context.Background(), client, dir, []string{"arjuns-mbp"}, labels) + require.NoError(t, err) + assert.Equal(t, 1, n) + + _, err = runLabelSet(context.Background(), client, dir, []string{"unknown-host"}, labels) + assert.ErrorContains(t, err, `endpoint "unknown-host"`) +} + +func TestRunLabelDelete(t *testing.T) { + client := mocks.NewLabelServiceClientMock(t) + client.EXPECT().DeleteSubjectLabels(mock.Anything, mock.Anything).Return(&policyv1.DeleteSubjectLabelsResponse{}, nil) + n, err := runLabelDelete(context.Background(), client, newTestDirectory(t), []string{testEndpointID}, []string{"custom/team"}) + require.NoError(t, err) + assert.Equal(t, 1, n) +} + +func TestRunPolicyShow(t *testing.T) { + dir := newTestDirectory(t) + require.NoError(t, dir.Upsert(context.Background(), []DirectoryEntry{{ID: testEndpointID, Hostname: "arjuns-mbp"}})) + + client := mocks.NewPolicyServiceClientMock(t) + header := &specv1.ResolvedPolicyHeader{} + header.SetRevision(52) + intended := &specv1.ResolvedPolicy{} + intended.SetHeader(header) + res := &policyv1.GetSubjectPolicyResponse{} + res.SetIntended(intended) + client.EXPECT().GetSubjectPolicy(mock.Anything, mock.MatchedBy(func(r *policyv1.GetSubjectPolicyRequest) bool { + return r.GetSubject().GetKind() == specv1.SubjectKind_SUBJECT_KIND_ENDPOINT && r.GetSubject().GetId() == testEndpointID + })).Return(res, nil) + + got, err := runPolicyShow(context.Background(), client, dir, "arjuns-mbp", nil) + require.NoError(t, err) + assert.Equal(t, "arjuns-mbp", got.Name) + assert.Contains(t, got.RenderTable(), "Endpoint") + assert.Contains(t, got.RenderTable(), "revision 52") +} diff --git a/internal/cmd/endpoint/service.go b/internal/cmd/endpoint/service.go index 04cf1b2..65110cc 100644 --- a/internal/cmd/endpoint/service.go +++ b/internal/cmd/endpoint/service.go @@ -12,6 +12,8 @@ import ( controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" "google.golang.org/grpc" "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/safedep/cli/internal/tui" ) // Five small interfaces, one per RPC, so unit tests can pass focused @@ -101,8 +103,23 @@ type ListInput struct { Window TimeWindow Capabilities []controltowerv1.EndpointCapability MinPMGBlocked uint64 // 0 = no filter - PageSize uint32 - PageToken string + // LabelSelector keeps the endpoints whose labels match. Nil = no filter. + LabelSelector *messagescontroltowerv1.LabelSelector + // AppliedRevisionBelow keeps the endpoints where a tool applies a policy + // revision lower than this one. 0 = no filter. + AppliedRevisionBelow uint64 + PageSize uint32 + PageToken string +} + +// ToolPolicy is the cloud policy that one tool on an endpoint reported last: +// its applied policy revision and the state of the policy in the tool. +type ToolPolicy struct { + Tool string + Version string + Revision uint64 + State string + ReportedAt time.Time } type ListEndpoint struct { ID string @@ -115,6 +132,7 @@ type ListEndpoint struct { PMGBlockedEvents uint64 PMGTotalEvents uint64 InventoryEvents uint64 + ToolPolicies []ToolPolicy } type ListResult struct { Endpoints []ListEndpoint @@ -270,7 +288,7 @@ func (s *Service) List(ctx context.Context, in ListInput) (*ListResult, error) { if in.PageSize > 0 { req.SetPagination(newPagination(in.PageSize, in.PageToken)) } - if len(in.Capabilities) > 0 || in.MinPMGBlocked > 0 { + if len(in.Capabilities) > 0 || in.MinPMGBlocked > 0 || in.LabelSelector != nil || in.AppliedRevisionBelow > 0 { f := &controltowerv1.ListEndpointsRequest_Filter{} if len(in.Capabilities) > 0 { f.SetCapabilities(in.Capabilities) @@ -278,6 +296,12 @@ func (s *Service) List(ctx context.Context, in ListInput) (*ListResult, error) { if in.MinPMGBlocked > 0 { f.SetMinPackageGuardBlockedEventsCount(in.MinPMGBlocked) } + if in.LabelSelector != nil { + f.SetLabelSelector(in.LabelSelector) + } + if in.AppliedRevisionBelow > 0 { + f.SetAppliedPolicyRevisionBelow(in.AppliedRevisionBelow) + } req.SetFilter(f) } res, err := s.client.ListEndpoints(ctx, req) @@ -299,11 +323,29 @@ func (s *Service) List(ctx context.Context, in ListInput) (*ListResult, error) { PMGBlockedEvents: ep.GetPackageGuardBlockedEventsCount(), PMGTotalEvents: ep.GetPackageGuardEventsCount(), InventoryEvents: ep.GetVetInventoryEventsCount(), + ToolPolicies: toolPolicies(ep.GetToolPolicies()), }) } return out, nil } +func toolPolicies(in []*controltowerv1.EndpointToolPolicy) []ToolPolicy { + out := make([]ToolPolicy, 0, len(in)) + for _, p := range in { + tp := ToolPolicy{ + Tool: p.GetToolName(), + Version: p.GetToolVersion(), + Revision: p.GetPolicy().GetRevision(), + State: tui.EnumToken(p.GetPolicy().GetState().String(), "APPLY_STATE_"), + } + if ts := p.GetReportedAt(); ts != nil { + tp.ReportedAt = ts.AsTime().UTC() + } + out = append(out, tp) + } + return out +} + func (s *Service) Get(ctx context.Context, in GetInput) (*GetResult, error) { req := &controltowerv1.GetEndpointRequest{} req.SetEndpointId(in.EndpointID) diff --git a/internal/cmd/project/cmd.go b/internal/cmd/project/cmd.go index a558388..9e521c4 100644 --- a/internal/cmd/project/cmd.go +++ b/internal/cmd/project/cmd.go @@ -10,8 +10,8 @@ func Register(root *cobra.Command, a *app.App) { parent := &cobra.Command{ Use: "project", Short: "Work with SafeDep projects", - Long: "Work with SafeDep projects, including syncing them from linked source code hosts " + - "and scans performed by SafeDep Cloud-hosted scanners.", + Long: "Work with SafeDep projects, including syncing them from linked source code hosts, " + + "their labels and policy, and scans performed by SafeDep Cloud-hosted scanners.", } scan := &cobra.Command{ Use: "scan", @@ -21,6 +21,6 @@ func Register(root *cobra.Command, a *app.App) { scan.AddCommand(createCmd(a)) scan.AddCommand(listCmd(a)) parent.AddCommand(scan) - parent.AddCommand(syncCmd(a)) + parent.AddCommand(syncCmd(a), projectListCmd(a), showCmd(a), labelCmd(a), policyCmd(a)) root.AddCommand(parent) } diff --git a/internal/cmd/project/inventory.go b/internal/cmd/project/inventory.go new file mode 100644 index 0000000..71743bc --- /dev/null +++ b/internal/cmd/project/inventory.go @@ -0,0 +1,227 @@ +package project + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "time" + + messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" + controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" + "github.com/safedep/dry/tui/humanize" + "github.com/safedep/dry/tui/table" + "github.com/spf13/cobra" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" + "github.com/safedep/cli/internal/paging" + "github.com/safedep/cli/internal/tui" +) + +// This file holds `project list`, the list of the projects themselves. +// `project scan list` lists scans and lives in list.go. + +const projectSourcePrefix = "SOURCE_" + +type projectListInput struct { + Selector string + Sources []string + Names []string + PageSize uint32 + PageToken string +} + +type projectView struct { + ID string `json:"project_id"` + Name string `json:"name"` + Source string `json:"source"` + OriginURL string `json:"origin_url,omitempty"` + Labels []string `json:"labels"` + Vulnerabilities *uint32 `json:"vulnerabilities,omitempty"` + PolicyViolations *uint32 `json:"policy_violations,omitempty"` + CreatedAt string `json:"created_at,omitempty"` + created *time.Time +} + +type projectListResult struct { + Projects []projectView `json:"projects"` + NextPageToken string `json:"next_page_token,omitempty"` +} + +func projectListCmd(a *app.App) *cobra.Command { + var in projectListInput + cmd := &cobra.Command{ + Use: "list", + Short: "List SafeDep projects with their labels", + Long: "List the projects of the tenant with their labels. --selector takes a label selector, as a " + + "policy override does, so you can see which projects an override selects: " + + "key=value, key!=value, key in (a,b), key notin (a,b), key or !key, separated by commas. " + + "The terms AND together. One page is returned per invocation, so follow --page-token to read " + + "the next page.", + Args: func(cmd *cobra.Command, args []string) error { + if err := cobra.NoArgs(cmd, args); err != nil { + return err + } + _, err := newProjectListRequest(in) + return err + }, + RunE: func(cmd *cobra.Command, _ []string) error { + client, err := a.ControlPlane() + if err != nil { + return err + } + res, err := runProjectList(cmd.Context(), newListProjectsClient(client.Connection()), in) + if err != nil { + return err + } + return a.Output.Print(res) + }, + } + f := cmd.Flags() + f.StringVar(&in.Selector, "selector", "", "filter: a label selector, as in custom/criticality=high,scm/forge=github") + f.StringArrayVar(&in.Sources, "source", nil, + "filter: project source ("+strings.Join(projectSourceTokens(), ", ")+"); repeatable") + f.StringArrayVar(&in.Names, "name", nil, + fmt.Sprintf("filter: exact project name; repeat for up to %d names", maxScanFilterValues)) + f.Uint32Var(&in.PageSize, "limit", 0, "page size; server default when 0") + f.StringVar(&in.PageToken, "page-token", "", "continuation token from a prior response") + return cmd +} + +func projectSourceTokens() []string { + return tui.EnumTokens(messagescontroltowerv1.Project_Source_name, projectSourcePrefix) +} + +func newProjectListRequest(in projectListInput) (*controltowerv1.ListProjectsRequest, error) { + filter := &controltowerv1.ListProjectsRequest_Filter{} + set := false + if in.Selector != "" { + selector, err := cloudpolicy.ParseSelector(in.Selector) + if err != nil { + return nil, invalidProjectSelectionError(err, "Write the selector as key=value, as in custom/team=release") + } + filter.SetLabelSelector(selector) + set = true + } + if len(in.Sources) > 0 { + sources := make([]messagescontroltowerv1.Project_Source, 0, len(in.Sources)) + for _, token := range in.Sources { + n, ok := tui.ParseEnumToken(messagescontroltowerv1.Project_Source_name, projectSourcePrefix, token) + if !ok { + return nil, unknownFilterValueError("source", token, projectSourceTokens()) + } + sources = append(sources, messagescontroltowerv1.Project_Source(n)) + } + filter.SetSources(sources) + set = true + } + if len(in.Names) > 0 { + if err := validateScanFilterValues(in.Names, "project name"); err != nil { + return nil, err + } + filter.SetProjectNames(in.Names) + set = true + } + req := &controltowerv1.ListProjectsRequest{} + req.SetPagination(paging.NewPaginationRequest(in.PageSize, in.PageToken)) + if set { + req.SetFilterV2(filter) + } + return req, nil +} + +func runProjectList(ctx context.Context, client listProjectsClient, in projectListInput) (*projectListResult, error) { + req, err := newProjectListRequest(in) + if err != nil { + return nil, err + } + res, err := client.ListProjects(ctx, req) + if err != nil { + return nil, fmt.Errorf("project list: %w", err) + } + out := &projectListResult{ + Projects: make([]projectView, 0, len(res.GetProjects())), + NextPageToken: res.GetPagination().GetNextPageToken(), + } + for _, p := range res.GetProjects() { + out.Projects = append(out.Projects, newProjectView(p)) + } + return out, nil +} + +func newProjectView(p *controltowerv1.ProjectWithAttributes) projectView { + project := p.GetProject() + attrs := p.GetAttributes() + v := projectView{ + ID: project.GetProjectId(), + Name: project.GetName(), + Source: tui.EnumToken(project.GetSource().String(), projectSourcePrefix), + OriginURL: project.GetOriginUrl(), + Labels: cloudpolicy.FormatLabels(attrs.GetLabels()), + } + if attrs.HasVulnerabilities() { + v.Vulnerabilities = new(attrs.GetVulnerabilities()) + } + if attrs.HasPolicyViolations() { + v.PolicyViolations = new(attrs.GetPolicyViolations()) + } + if ts := project.GetCreatedAt(); ts != nil { + t := ts.AsTime().UTC() + v.created = &t + v.CreatedAt = t.Format(time.RFC3339) + } + return v +} + +func (r *projectListResult) RenderJSON() ([]byte, error) { + return json.MarshalIndent(r, "", " ") +} + +func (r *projectListResult) RenderTable() string { + now := time.Now() + rows := make([][]string, 0, len(r.Projects)) + for _, p := range r.Projects { + created := "-" + if p.created != nil { + created = humanize.Time(*p.created, now) + } + labels := strings.Join(p.Labels, ", ") + if labels == "" { + labels = "-" + } + rows = append(rows, []string{ + p.Name, p.Source, labels, countCell(p.Vulnerabilities), countCell(p.PolicyViolations), created, + }) + } + t := table.New(). + Title("Projects"). + Headers("PROJECT", "SOURCE", "LABELS", "VULNS", "VIOLATIONS", "CREATED"). + Rows(rows...). + EmptyMessage("No projects match. Sync repositories with: safedep project sync") + if len(rows) > 0 { + footer := fmt.Sprintf("%d %s", len(rows), pluralProjects(len(rows))) + if r.NextPageToken != "" { + footer += ". More available: --page-token " + r.NextPageToken + } + t = t.Footer(footer) + } + return t.Render() +} + +func (r *projectListResult) RenderPlain() string { + var b strings.Builder + b.WriteString("project_id\tname\tsource\tlabels\tvulnerabilities\tpolicy_violations\tcreated_at") + for _, p := range r.Projects { + fmt.Fprintf(&b, "\n%s\t%s\t%s\t%s\t%s\t%s\t%s", p.ID, p.Name, p.Source, strings.Join(p.Labels, ","), + countCell(p.Vulnerabilities), countCell(p.PolicyViolations), p.CreatedAt) + } + return b.String() +} + +func pluralProjects(n int) string { + if n == 1 { + return "project" + } + return "projects" +} diff --git a/internal/cmd/project/label.go b/internal/cmd/project/label.go new file mode 100644 index 0000000..91900e3 --- /dev/null +++ b/internal/cmd/project/label.go @@ -0,0 +1,169 @@ +package project + +import ( + "context" + "errors" + + policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" + specv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/spec/v1" + "github.com/safedep/dry/tui" + "github.com/safedep/dry/usefulerror" + "github.com/spf13/cobra" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" +) + +type labelInput struct { + Names []string + ProjectIDs []string + Labels []string + Keys []string +} + +func labelCmd(a *app.App) *cobra.Command { + parent := &cobra.Command{ + Use: "label", + Short: "Set or delete the custom labels of projects", + Long: "Set or delete the custom/ labels of projects. A policy override selects projects by their " + + "labels. An admin writes only custom/ labels. The forge sync writes scm/ labels, and the server " + + "writes safedep.io/ labels. A label change takes effect at the next check of each project.", + } + parent.AddCommand(labelSetCmd(a), labelDeleteCmd(a)) + return parent +} + +func labelSetCmd(a *app.App) *cobra.Command { + var in labelInput + cmd := &cobra.Command{ + Use: "set [PROJECT_NAME...] --label custom/KEY=VALUE", + Short: "Set custom labels on projects", + Long: "Set custom/ labels on up to 100 projects, by exact name or with --project-id. A label with " + + "an existing key gets the new value. The label takes effect at the next check of each project.", + Args: func(_ *cobra.Command, args []string) error { + in.Names = args + if err := requireProjects(in); err != nil { + return err + } + _, err := cloudpolicy.ParseCustomLabels(in.Labels) + return labelError(err) + }, + RunE: func(cmd *cobra.Command, args []string) error { + in.Names = args + client, err := a.ControlPlane() + if err != nil { + return err + } + conn := client.Connection() + n, err := runLabelSet(cmd.Context(), newListProjectsClient(conn), cloudpolicy.NewLabelClient(conn), in) + if err != nil { + return err + } + tui.Success("label set on %d %s. It takes effect at the next check of each project", n, pluralProjects(n)) + return nil + }, + } + cmd.Flags().StringArrayVar(&in.Labels, "label", nil, "a label as custom/KEY=VALUE; repeatable") + cmd.Flags().StringArrayVar(&in.ProjectIDs, "project-id", nil, "a project ID instead of a name; repeatable") + return cmd +} + +func labelDeleteCmd(a *app.App) *cobra.Command { + var in labelInput + cmd := &cobra.Command{ + Use: "delete [PROJECT_NAME...] --key custom/KEY", + Short: "Delete custom labels from projects", + Long: "Delete custom/ labels from up to 100 projects, by exact name or with --project-id. The " + + "change takes effect at the next check of each project.", + Args: func(_ *cobra.Command, args []string) error { + in.Names = args + if err := requireProjects(in); err != nil { + return err + } + return labelError(cloudpolicy.ValidateCustomKeys(in.Keys)) + }, + RunE: func(cmd *cobra.Command, args []string) error { + in.Names = args + client, err := a.ControlPlane() + if err != nil { + return err + } + conn := client.Connection() + n, err := runLabelDelete(cmd.Context(), newListProjectsClient(conn), cloudpolicy.NewLabelClient(conn), in) + if err != nil { + return err + } + tui.Success("label deleted from %d %s. It takes effect at the next check of each project", n, pluralProjects(n)) + return nil + }, + } + cmd.Flags().StringArrayVar(&in.Keys, "key", nil, "a label key as custom/KEY; repeatable") + cmd.Flags().StringArrayVar(&in.ProjectIDs, "project-id", nil, "a project ID instead of a name; repeatable") + return cmd +} + +func requireProjects(in labelInput) error { + if len(in.Names)+len(in.ProjectIDs) == 0 { + return invalidProjectSelectionError(errors.New("give at least one project"), + "Give project names, or --project-id. Find them with: safedep project list") + } + if err := validateUniqueValues(in.ProjectIDs, "project ID"); err != nil { + return err + } + return validateUniqueValues(in.Names, "project name") +} + +func labelError(err error) error { + if err == nil { + return nil + } + return newProjectError(usefulerror.ErrBadRequest, err.Error(), "Write a label as custom/KEY=VALUE, as in custom/team=release", err) +} + +// labelProjectIDs resolves the names and adds the given project IDs. +func labelProjectIDs(ctx context.Context, projects listProjectsClient, op string, in labelInput) ([]string, error) { + resolved, err := resolveProjectNamesFor(ctx, projects, op, in.Names) + if err != nil { + return nil, err + } + return append(append([]string{}, in.ProjectIDs...), resolved...), nil +} + +func runLabelSet( + ctx context.Context, + projects listProjectsClient, + labels policyv1grpc.LabelServiceClient, + in labelInput, +) (int, error) { + parsed, err := cloudpolicy.ParseCustomLabels(in.Labels) + if err != nil { + return 0, labelError(err) + } + ids, err := labelProjectIDs(ctx, projects, "project label set", in) + if err != nil { + return 0, err + } + if err := cloudpolicy.SetLabels(ctx, labels, specv1.SubjectKind_SUBJECT_KIND_PROJECT, ids, parsed); err != nil { + return 0, err + } + return len(ids), nil +} + +func runLabelDelete( + ctx context.Context, + projects listProjectsClient, + labels policyv1grpc.LabelServiceClient, + in labelInput, +) (int, error) { + if err := cloudpolicy.ValidateCustomKeys(in.Keys); err != nil { + return 0, labelError(err) + } + ids, err := labelProjectIDs(ctx, projects, "project label delete", in) + if err != nil { + return 0, err + } + if err := cloudpolicy.DeleteLabels(ctx, labels, specv1.SubjectKind_SUBJECT_KIND_PROJECT, ids, in.Keys); err != nil { + return 0, err + } + return len(ids), nil +} diff --git a/internal/cmd/project/policy.go b/internal/cmd/project/policy.go new file mode 100644 index 0000000..a7d3cad --- /dev/null +++ b/internal/cmd/project/policy.go @@ -0,0 +1,86 @@ +package project + +import ( + "context" + "errors" + + specv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/spec/v1" + "github.com/spf13/cobra" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" +) + +type policyShowInput struct { + Name string + ProjectID string + Fields []string +} + +func policyCmd(a *app.App) *cobra.Command { + parent := &cobra.Command{ + Use: "policy", + Short: "Inspect the policy of a project", + Long: "Inspect the policy that applies to a project, with the source of each value.", + } + parent.AddCommand(policyShowCmd(a)) + return parent +} + +func policyShowCmd(a *app.App) *cobra.Command { + var in policyShowInput + cmd := &cobra.Command{ + Use: "show [PROJECT_NAME]", + Short: "Show the policy of a project and the source of each value", + Long: "Show the intended policy of one project: each field, its value, and its source, which is " + + "the SafeDep default policy, the policy base, or a policy override. The output also shows the " + + "exceptions and the applied policy revision that each tool or check reported. Use --field to " + + "show some fields only.", + Args: func(cmd *cobra.Command, args []string) error { + if err := cobra.MaximumNArgs(1)(cmd, args); err != nil { + return err + } + if (len(args) == 1) == (in.ProjectID != "") { + return invalidProjectSelectionError(errors.New("give a project name or --project-id"), + "As in: safedep project policy show acme/payments-api") + } + return cloudpolicy.ValidateFieldPaths(in.Fields) + }, + RunE: func(cmd *cobra.Command, args []string) error { + if len(args) == 1 { + in.Name = args[0] + } + client, err := a.ControlPlane() + if err != nil { + return err + } + conn := client.Connection() + res, err := runPolicyShow(cmd.Context(), newListProjectsClient(conn), cloudpolicy.NewPolicyClient(conn), in) + if err != nil { + return err + } + return a.Output.Print(res) + }, + } + cmd.Flags().StringVar(&in.ProjectID, "project-id", "", "the project ID instead of a name") + cmd.Flags().StringSliceVar(&in.Fields, "field", nil, "show only these contract paths, as in scan_gate.fail_on; repeatable") + return cmd +} + +func runPolicyShow( + ctx context.Context, + projects listProjectsClient, + policies cloudpolicy.SubjectPolicyClient, + in policyShowInput, +) (*cloudpolicy.SubjectPolicy, error) { + id := in.ProjectID + if id == "" { + project, err := findProject(ctx, projects, "project policy show", in.Name) + if err != nil { + return nil, err + } + id = project.GetProject().GetProjectId() + } + subject := cloudpolicy.NewSubject(specv1.SubjectKind_SUBJECT_KIND_PROJECT, id) + return cloudpolicy.GetSubjectPolicy(ctx, policies, subject, in.Name, in.Fields) +} diff --git a/internal/cmd/project/policy_test.go b/internal/cmd/project/policy_test.go new file mode 100644 index 0000000..abffb7a --- /dev/null +++ b/internal/cmd/project/policy_test.go @@ -0,0 +1,228 @@ +package project + +import ( + "context" + "errors" + "testing" + "time" + + messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/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" + controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/safedep/cli/internal/cloudpolicy/mocks" +) + +// fakeSubjectPolicyClient is a hand fake for the one RPC of +// cloudpolicy.SubjectPolicyClient. +type fakeSubjectPolicyClient struct { + req *policyv1.GetSubjectPolicyRequest + err error +} + +func (f *fakeSubjectPolicyClient) GetSubjectPolicy( + _ context.Context, + req *policyv1.GetSubjectPolicyRequest, + _ ...grpc.CallOption, +) (*policyv1.GetSubjectPolicyResponse, error) { + f.req = req + if f.err != nil { + return nil, f.err + } + header := &specv1.ResolvedPolicyHeader{} + header.SetRevision(46) + intended := &specv1.ResolvedPolicy{} + intended.SetHeader(header) + res := &policyv1.GetSubjectPolicyResponse{} + res.SetIntended(intended) + return res, nil +} + +func labeledProject(id, name string, source messagescontroltowerv1.Project_Source, labels map[string]string) *controltowerv1.ProjectWithAttributes { + p := &messagescontroltowerv1.Project{} + p.SetProjectId(id) + p.SetName(name) + p.SetSource(source) + p.SetOriginUrl("https://example.com/" + name) + p.SetCreatedAt(timestamppb.New(time.Now().Add(-72 * time.Hour))) + attrs := &controltowerv1.ProjectAttributes{} + var list []*messagescontroltowerv1.Label + for k, v := range labels { + l := &messagescontroltowerv1.Label{} + l.SetKey(k) + l.SetValue(v) + list = append(list, l) + } + attrs.SetLabels(list) + attrs.SetVulnerabilities(3) + out := &controltowerv1.ProjectWithAttributes{} + out.SetProject(p) + out.SetAttributes(attrs) + return out +} + +func projectsResponse(projects ...*controltowerv1.ProjectWithAttributes) *controltowerv1.ListProjectsResponse { + res := &controltowerv1.ListProjectsResponse{} + res.SetProjects(projects) + return res +} + +func TestNewProjectListRequest(t *testing.T) { + req, err := newProjectListRequest(projectListInput{ + Selector: "scm-property/criticality=high", Sources: []string{"github", "bitbucket"}, PageSize: 10, + }) + require.NoError(t, err) + f := req.GetFilterV2() + assert.Equal(t, map[string]string{"scm-property/criticality": "high"}, f.GetLabelSelector().GetMatchLabels()) + assert.Equal(t, []messagescontroltowerv1.Project_Source{ + messagescontroltowerv1.Project_SOURCE_GITHUB, messagescontroltowerv1.Project_SOURCE_BITBUCKET, + }, f.GetSources()) + assert.Equal(t, uint32(10), req.GetPagination().GetPageSize()) + + req, err = newProjectListRequest(projectListInput{}) + require.NoError(t, err) + assert.False(t, req.HasFilterV2()) + + _, err = newProjectListRequest(projectListInput{Sources: []string{"svn"}}) + assert.ErrorContains(t, err, `unknown --source value "svn"`) + _, err = newProjectListRequest(projectListInput{Selector: "criticality=high"}) + assert.ErrorContains(t, err, "is not valid") +} + +func TestRunProjectList(t *testing.T) { + client := &fakeListProjectsClient{listFn: func(*controltowerv1.ListProjectsRequest) (*controltowerv1.ListProjectsResponse, error) { + return projectsResponse(labeledProject("p_1", "acme/payments-api", messagescontroltowerv1.Project_SOURCE_GITHUB, + map[string]string{"scm-property/criticality": "high", "custom/team": "pay"})), nil + }} + got, err := runProjectList(context.Background(), client, projectListInput{Selector: "scm-property/criticality=high"}) + require.NoError(t, err) + require.Len(t, got.Projects, 1) + assert.Equal(t, []string{"custom/team=pay", "scm-property/criticality=high"}, got.Projects[0].Labels) + + table := got.RenderTable() + assert.Contains(t, table, "acme/payments-api") + assert.Contains(t, table, "custom/team=pay, scm-property/criticality=high") + assert.Contains(t, got.RenderPlain(), "p_1\tacme/payments-api\tgithub\tcustom/team=pay,scm-property/criticality=high\t3\t-\t") +} + +func TestRunShow_ProjectWithPolicy(t *testing.T) { + client := &fakeListProjectsClient{listFn: func(req *controltowerv1.ListProjectsRequest) (*controltowerv1.ListProjectsResponse, error) { + assert.Equal(t, []string{"PAY/settlement"}, req.GetFilterV2().GetProjectNames()) + return projectsResponse( + labeledProject("p_9", "PAY/settlement", messagescontroltowerv1.Project_SOURCE_BITBUCKET, + map[string]string{"scm/forge": "bitbucket"}), + labeledProject("p_x", "PAY/settlement-old", messagescontroltowerv1.Project_SOURCE_BITBUCKET, nil), + ), nil + }} + policies := &fakeSubjectPolicyClient{} + got, err := runShow(context.Background(), client, policies, "PAY/settlement") + require.NoError(t, err) + assert.Equal(t, "p_9", policies.req.GetSubject().GetId()) + assert.Equal(t, specv1.SubjectKind_SUBJECT_KIND_PROJECT, policies.req.GetSubject().GetKind()) + + table := got.RenderTable() + assert.Contains(t, table, "Project PAY/settlement") + assert.Contains(t, table, "bitbucket · https://example.com/PAY/settlement") + assert.Contains(t, table, "revision 46 · no override matches · base only") + b, err := got.RenderJSON() + require.NoError(t, err) + assert.Contains(t, string(b), `"revision": 46`) +} + +func TestRunShow_PolicyUnavailableStillShowsTheProject(t *testing.T) { + client := &fakeListProjectsClient{listFn: func(*controltowerv1.ListProjectsRequest) (*controltowerv1.ListProjectsResponse, error) { + return projectsResponse(labeledProject("p_9", "x", messagescontroltowerv1.Project_SOURCE_GITHUB, nil)), nil + }} + got, err := runShow(context.Background(), client, &fakeSubjectPolicyClient{err: errors.New("unimplemented")}, "x") + require.NoError(t, err) + assert.Contains(t, got.RenderTable(), "unknown: the policy service did not answer") +} + +func TestFindProject(t *testing.T) { + empty := &fakeListProjectsClient{listFn: func(*controltowerv1.ListProjectsRequest) (*controltowerv1.ListProjectsResponse, error) { + return projectsResponse(), nil + }} + _, err := findProject(context.Background(), empty, "project show", "missing") + requireUsefulError(t, err, "not_found", "Project not found", `Check the name with: safedep project list --name "missing"`) + + two := &fakeListProjectsClient{listFn: func(*controltowerv1.ListProjectsRequest) (*controltowerv1.ListProjectsResponse, error) { + return projectsResponse( + labeledProject("p_1", "shared", messagescontroltowerv1.Project_SOURCE_GITHUB, nil), + labeledProject("p_2", "shared", messagescontroltowerv1.Project_SOURCE_BITBUCKET, nil), + ), nil + }} + _, err = findProject(context.Background(), two, "project show", "shared") + require.Error(t, err) + assert.Contains(t, err.Error(), `project show: project name "shared" is ambiguous`) +} + +func TestRunPolicyShow(t *testing.T) { + policies := &fakeSubjectPolicyClient{} + got, err := runPolicyShow(context.Background(), nil, policies, policyShowInput{ProjectID: "p_7", Fields: []string{"scan_gate"}}) + require.NoError(t, err) + assert.Equal(t, "p_7", policies.req.GetSubject().GetId()) + assert.True(t, got.Filtered) + + client := &fakeListProjectsClient{listFn: func(*controltowerv1.ListProjectsRequest) (*controltowerv1.ListProjectsResponse, error) { + return projectsResponse(labeledProject("p_1", "acme/payments-api", messagescontroltowerv1.Project_SOURCE_GITHUB, nil)), nil + }} + _, err = runPolicyShow(context.Background(), client, policies, policyShowInput{Name: "acme/payments-api"}) + require.NoError(t, err) + assert.Equal(t, "p_1", policies.req.GetSubject().GetId()) +} + +func TestRunLabelSet(t *testing.T) { + projects := &fakeListProjectsClient{listFn: func(*controltowerv1.ListProjectsRequest) (*controltowerv1.ListProjectsResponse, error) { + return projectsResponse( + labeledProject("p_1", "acme/payments-api", messagescontroltowerv1.Project_SOURCE_GITHUB, nil), + labeledProject("p_2", "acme/ledger", messagescontroltowerv1.Project_SOURCE_GITHUB, nil), + ), nil + }} + labels := mocks.NewLabelServiceClientMock(t) + labels.EXPECT().SetSubjectLabels(mock.Anything, mock.MatchedBy(func(r *policyv1.SetSubjectLabelsRequest) bool { + ids := []string{} + for _, s := range r.GetSubjects() { + ids = append(ids, s.GetId()) + } + return assert.ObjectsAreEqual([]string{"p_9", "p_1", "p_2"}, ids) && + r.GetLabels()[0].GetKey() == "custom/criticality" && r.GetLabels()[0].GetValue() == "high" + })).Return(&policyv1.SetSubjectLabelsResponse{}, nil) + + n, err := runLabelSet(context.Background(), projects, labels, labelInput{ + Names: []string{"acme/payments-api", "acme/ledger"}, ProjectIDs: []string{"p_9"}, + Labels: []string{"custom/criticality=high"}, + }) + require.NoError(t, err) + assert.Equal(t, 3, n) +} + +func TestRunLabelSet_RejectsOtherPrefixesBeforeAnyRPC(t *testing.T) { + _, err := runLabelSet(context.Background(), nil, mocks.NewLabelServiceClientMock(t), labelInput{ + ProjectIDs: []string{"p_1"}, Labels: []string{"scm-property/criticality=high"}, + }) + require.Error(t, err) + assert.Contains(t, err.Error(), `an admin writes only "custom/" labels`) +} + +func TestRunLabelDelete(t *testing.T) { + labels := mocks.NewLabelServiceClientMock(t) + labels.EXPECT().DeleteSubjectLabels(mock.Anything, mock.MatchedBy(func(r *policyv1.DeleteSubjectLabelsRequest) bool { + return r.GetKeys()[0] == "custom/criticality" && r.GetSubjects()[0].GetId() == "p_1" + })).Return(&policyv1.DeleteSubjectLabelsResponse{}, nil) + n, err := runLabelDelete(context.Background(), &fakeListProjectsClient{}, labels, labelInput{ + ProjectIDs: []string{"p_1"}, Keys: []string{"custom/criticality"}, + }) + require.NoError(t, err) + assert.Equal(t, 1, n) +} + +func TestRequireProjects(t *testing.T) { + assert.ErrorContains(t, requireProjects(labelInput{}), "give at least one project") + assert.ErrorContains(t, requireProjects(labelInput{Names: []string{"a", "a"}}), `duplicate project name "a"`) +} diff --git a/internal/cmd/project/resolver.go b/internal/cmd/project/resolver.go index 6975b69..6ccf4f1 100644 --- a/internal/cmd/project/resolver.go +++ b/internal/cmd/project/resolver.go @@ -77,6 +77,17 @@ func resolveProjectNames( ctx context.Context, client listProjectsClient, projectNames []string, +) ([]string, error) { + return resolveProjectNamesFor(ctx, client, "project scan create", projectNames) +} + +// resolveProjectNamesFor resolves exact project names to project IDs. op +// names the command in errors, as in "project label set". +func resolveProjectNamesFor( + ctx context.Context, + client listProjectsClient, + op string, + projectNames []string, ) ([]string, error) { if len(projectNames) == 0 { return nil, nil @@ -85,7 +96,7 @@ func resolveProjectNames( matches := make(map[string]map[string]projectMatch, len(projectNames)) for start := 0; start < len(projectNames); start += projectLookupChunkSize { end := min(start+projectLookupChunkSize, len(projectNames)) - if err := resolveProjectNameChunk(ctx, client, projectNames[start:end], matches); err != nil { + if err := resolveProjectNameChunk(ctx, client, op, projectNames[start:end], matches); err != nil { return nil, err } } @@ -95,7 +106,7 @@ func resolveProjectNames( byID := matches[name] switch len(byID) { case 0: - cause := fmt.Errorf("project scan create: project %q not found", name) + cause := fmt.Errorf("%s: project %q not found", op, name) return nil, newProjectError( usefulerror.ErrNotFound, "Project not found", @@ -107,7 +118,7 @@ func resolveProjectNames( resolved = append(resolved, id) } default: - return nil, ambiguousProjectNameError(name, byID) + return nil, ambiguousProjectNameError(op, name, byID) } } return resolved, nil @@ -116,6 +127,7 @@ func resolveProjectNames( func resolveProjectNameChunk( ctx context.Context, client listProjectsClient, + op string, names []string, matches map[string]map[string]projectMatch, ) error { @@ -124,13 +136,13 @@ func resolveProjectNameChunk( requested[name] = struct{}{} } - const label = "project scan create: resolve projects" + label := op + ": resolve projects" return paging.Paginate(ctx, label, func(ctx context.Context, pageToken string) (string, error) { res, err := client.ListProjects(ctx, newListProjectsRequest(names, pageToken)) if err != nil { return "", fmt.Errorf("%s: %w", label, err) } - if err := collectProjectMatches(res, requested, matches); err != nil { + if err := collectProjectMatches(label, res, requested, matches); err != nil { return "", err } return res.GetPagination().GetNextPageToken(), nil @@ -147,6 +159,7 @@ func newListProjectsRequest(names []string, pageToken string) *controltowerv1.Li } func collectProjectMatches( + label string, res *controltowerv1.ListProjectsResponse, requested map[string]struct{}, matches map[string]map[string]projectMatch, @@ -154,17 +167,11 @@ func collectProjectMatches( for i, item := range res.GetProjects() { project := item.GetProject() if project == nil || project.GetProjectId() == "" || project.GetName() == "" { - return fmt.Errorf( - "project scan create: resolve projects: invalid response: project %d is missing identity", - i+1, - ) + return fmt.Errorf("%s: invalid response: project %d is missing identity", label, i+1) } name := project.GetName() if _, ok := requested[name]; !ok { - return fmt.Errorf( - "project scan create: resolve projects: invalid response: unexpected project name %q", - name, - ) + return fmt.Errorf("%s: invalid response: unexpected project name %q", label, name) } if matches[name] == nil { matches[name] = make(map[string]projectMatch) @@ -178,7 +185,7 @@ func collectProjectMatches( return nil } -func ambiguousProjectNameError(name string, byID map[string]projectMatch) error { +func ambiguousProjectNameError(op, name string, byID map[string]projectMatch) error { items := make([]projectMatch, 0, len(byID)) for _, match := range byID { items = append(items, match) @@ -196,7 +203,8 @@ func ambiguousProjectNameError(name string, byID map[string]projectMatch) error labels = append(labels, fmt.Sprintf("%s (%s)", item.id, details)) } cause := fmt.Errorf( - "project scan create: project name %q is ambiguous: %s; use a project ID", + "%s: project name %q is ambiguous: %s; use a project ID", + op, name, strings.Join(labels, ", "), ) diff --git a/internal/cmd/project/show.go b/internal/cmd/project/show.go new file mode 100644 index 0000000..67e4868 --- /dev/null +++ b/internal/cmd/project/show.go @@ -0,0 +1,174 @@ +package project + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "time" + + specv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/spec/v1" + controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" + "github.com/safedep/dry/tui" + "github.com/safedep/dry/tui/humanize" + "github.com/safedep/dry/usefulerror" + "github.com/spf13/cobra" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" +) + +type projectShowResult struct { + Project projectView `json:"project"` + Policy *cloudpolicy.SubjectPolicy `json:"-"` +} + +func showCmd(a *app.App) *cobra.Command { + return &cobra.Command{ + Use: "show PROJECT_NAME", + Short: "Show one project with its labels and policy", + Long: "Show one project by its exact name: its source, its labels from every source, and the " + + "policy revision and policy overrides that apply to it. A repository is a project.", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + client, err := a.ControlPlane() + if err != nil { + return err + } + conn := client.Connection() + res, err := runShow(cmd.Context(), newListProjectsClient(conn), cloudpolicy.NewPolicyClient(conn), args[0]) + if err != nil { + return err + } + return a.Output.Print(res) + }, + } +} + +// findProject reads one project by its exact name. +func findProject(ctx context.Context, client listProjectsClient, op, name string) (*controltowerv1.ProjectWithAttributes, error) { + filter := &controltowerv1.ListProjectsRequest_Filter{} + filter.SetProjectNames([]string{name}) + req := &controltowerv1.ListProjectsRequest{} + req.SetFilterV2(filter) + res, err := client.ListProjects(ctx, req) + if err != nil { + return nil, fmt.Errorf("%s: %w", op, err) + } + var found []*controltowerv1.ProjectWithAttributes + byID := map[string]projectMatch{} + for _, p := range res.GetProjects() { + if p.GetProject().GetName() != name { + continue + } + found = append(found, p) + byID[p.GetProject().GetProjectId()] = projectMatch{ + id: p.GetProject().GetProjectId(), + source: newProjectView(p).Source, + originURL: p.GetProject().GetOriginUrl(), + } + } + switch len(found) { + case 0: + return nil, newProjectError(usefulerror.ErrNotFound, "Project not found", + fmt.Sprintf("Check the name with: safedep project list --name %q", name), + fmt.Errorf("%s: project %q not found", op, name)) + case 1: + return found[0], nil + default: + return nil, ambiguousProjectNameError(op, name, byID) + } +} + +func runShow( + ctx context.Context, + projects listProjectsClient, + policies cloudpolicy.SubjectPolicyClient, + name string, +) (*projectShowResult, error) { + project, err := findProject(ctx, projects, "project show", name) + if err != nil { + return nil, err + } + out := &projectShowResult{Project: newProjectView(project)} + subject := cloudpolicy.NewSubject(specv1.SubjectKind_SUBJECT_KIND_PROJECT, out.Project.ID) + policy, err := cloudpolicy.GetSubjectPolicy(ctx, policies, subject, name, nil) + if err != nil { + // The project data is still useful when the policy service does not + // answer, so the command warns and shows the rest. + tui.Warning("Could not read the policy of project %s: %v", name, err) + return out, nil + } + out.Policy = policy + return out, nil +} + +func (r *projectShowResult) RenderJSON() ([]byte, error) { + type policyJSON struct { + Revision uint64 `json:"revision"` + DefaultRevision uint64 `json:"default_policy_revision"` + Matched []cloudpolicy.MatchedOverride `json:"matched_overrides"` + } + out := struct { + projectView + Policy *policyJSON `json:"policy,omitempty"` + }{projectView: r.Project} + if p := r.Policy; p != nil { + matched := p.Matched + if matched == nil { + matched = []cloudpolicy.MatchedOverride{} + } + out.Policy = &policyJSON{Revision: p.Revision, DefaultRevision: p.DefaultRevision, Matched: matched} + } + return json.MarshalIndent(out, "", " ") +} + +func (r *projectShowResult) policyLine() string { + if r.Policy == nil { + return "unknown: the policy service did not answer" + } + return r.Policy.PolicyLine() +} + +func (r *projectShowResult) RenderTable() string { + p := r.Project + source := p.Source + if p.OriginURL != "" { + source += cloudpolicy.Separator + p.OriginURL + } + created := "-" + if p.created != nil { + created = humanize.Time(*p.created, time.Now()) + } + labels := strings.Join(p.Labels, "\n") + if labels == "" { + labels = "-" + } + return cloudpolicy.KeyValues([][2]string{ + {"Project", p.Name}, + {"ID", p.ID}, + {"Source", source}, + {"Labels", labels}, + {"Policy", r.policyLine()}, + {"Vulnerabilities", countCell(p.Vulnerabilities)}, + {"Violations", countCell(p.PolicyViolations)}, + {"Created", created}, + }) + "\n\nPolicy of each field: safedep project policy show " + p.Name +} + +func (r *projectShowResult) RenderPlain() string { + p := r.Project + policy := "" + if r.Policy != nil { + policy = fmt.Sprintf("%d", r.Policy.Revision) + } + return strings.Join([]string{ + "project_id\t" + p.ID, + "name\t" + p.Name, + "source\t" + p.Source, + "origin_url\t" + p.OriginURL, + "labels\t" + strings.Join(p.Labels, ","), + "policy_revision\t" + policy, + "created_at\t" + p.CreatedAt, + }, "\n") +} diff --git a/internal/cmd/safedep.go b/internal/cmd/safedep.go index b06244e..f96ac81 100644 --- a/internal/cmd/safedep.go +++ b/internal/cmd/safedep.go @@ -2,6 +2,7 @@ package cmd import ( "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cmd/audit" "github.com/safedep/cli/internal/cmd/auth" "github.com/safedep/cli/internal/cmd/endpoint" "github.com/safedep/cli/internal/cmd/integration" @@ -20,6 +21,7 @@ import ( // convention tests both consume this so they walk an identical tree. func NewSafedep(a *app.App) *cobra.Command { root := NewRootCommand(a) + audit.Register(root, a) auth.Register(root, a) endpoint.Register(root, a) packages.Register(root, a) From 4e649b16c3514e0f6cf534349e61ed18862a48f1 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 31 Oct 2026 08:51:06 +0000 Subject: [PATCH 03/17] fix(policy): keep override ids, guard edits, confirm loosening publishes A review found these problems in the policy commands: - The YAML left out the override id, so a rename reached the server as a new override. The document now writes the id as "id". The decoder keeps the id that the user leaves. The CLI refuses an id that is not in the policy and warns before the save for each removed override. - An edit dropped contract fields that this SDK does not know. The CLI now stops before the editor opens and tells the user to update. - Change publish acted with no preview. It now previews the change, shows the change direction and every warning, stops on a stale change with the sync hint, and asks before it publishes a change that loosens the policy. With no terminal it needs --yes. The success line names the direction. - Server text reached the terminal unescaped. A new helper in internal/tui escapes control and bidirectional characters, and every table and plain renderer and every warning with server text uses it. JSON output stays raw. - internal/rpcerror repeated usefulerror.ReasonOf of dry. It is gone. - Rule create warns about a selector that blocks a whole ecosystem, and rule create and update refuse a trust expiry over 90 days. - Policy edit maps PermissionDenied, so a Member sees who can act. A restore from a missing revision names the revision. - The audit help names the resource kinds and the action prefix. The change also moves the shared display helpers to cloudpolicy, pads key and value rows by display width, compares decoded documents with proto.Equal in the edit loop, writes the paging help in active voice, and splits the leaf files that were over the line cap. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MhRi597EX9odoSDXbVBsxz --- docs/cmd/audit-event-list.md | 8 +- docs/cmd/policy-change-publish.md | 12 +- docs/cmd/policy-edit.md | 8 + docs/cmd/policy-get.md | 6 +- docs/cmd/policy-rule-create.md | 4 +- docs/cmd/policy-rule-update.md | 2 +- internal/cloudpolicy/document.go | 91 ++++++--- internal/cloudpolicy/document_test.go | 61 ++++-- internal/cloudpolicy/protoyaml.go | 42 +++- internal/cloudpolicy/render.go | 58 ++++-- internal/cloudpolicy/subject.go | 40 ++-- internal/cloudpolicy/subject_test.go | 20 ++ internal/cmd/audit/list.go | 145 +------------- internal/cmd/audit/list_test.go | 20 ++ internal/cmd/audit/view.go | 127 +++++++++++++ internal/cmd/endpoint/label.go | 148 +++++++++++++++ internal/cmd/endpoint/list.go | 9 +- internal/cmd/endpoint/policy.go | 143 +------------- internal/cmd/policy/change_create.go | 19 +- internal/cmd/policy/change_edit.go | 108 +++++++++++ internal/cmd/policy/change_list.go | 75 +------- internal/cmd/policy/change_ops.go | 156 +-------------- internal/cmd/policy/change_preview.go | 143 ++++++++++++++ internal/cmd/policy/change_publish.go | 163 ++++++++++++++++ internal/cmd/policy/change_render.go | 79 ++++++++ internal/cmd/policy/change_show.go | 203 +------------------- internal/cmd/policy/change_test.go | 27 +-- internal/cmd/policy/change_view.go | 73 +++++++ internal/cmd/policy/edit.go | 115 +---------- internal/cmd/policy/edit_test.go | 136 ++++++++++++- internal/cmd/policy/editor.go | 36 +++- internal/cmd/policy/errors.go | 20 +- internal/cmd/policy/get.go | 7 +- internal/cmd/policy/publish_test.go | 148 +++++++++++++++ internal/cmd/policy/revision.go | 106 +---------- internal/cmd/policy/revision_show.go | 116 ++++++++++++ internal/cmd/policy/rule_create.go | 187 ++---------------- internal/cmd/policy/rule_delete.go | 64 +++++++ internal/cmd/policy/rule_filters.go | 88 +++++++++ internal/cmd/policy/rule_input.go | 215 +++++++++++++++++++++ internal/cmd/policy/rule_list.go | 161 +--------------- internal/cmd/policy/rule_ops.go | 263 -------------------------- internal/cmd/policy/rule_show.go | 110 +++++++++++ internal/cmd/policy/rule_test.go | 85 ++++++++- internal/cmd/policy/rule_update.go | 150 +++++++++++++++ internal/cmd/policy/rule_view.go | 82 ++++++++ internal/cmd/policy/settings.go | 192 +++++++++++++++++++ internal/cmd/policy/show.go | 9 +- internal/cmd/policy/show_test.go | 2 +- internal/cmd/policy/view.go | 42 +--- internal/cmd/project/inventory.go | 44 +---- internal/cmd/project/policy_test.go | 16 ++ internal/cmd/project/show.go | 40 ++-- internal/cmd/project/view.go | 46 +++++ internal/cmd/subscription/service.go | 6 +- internal/rpcerror/rpcerror.go | 24 --- internal/rpcerror/rpcerror_test.go | 32 ---- internal/tui/escape.go | 112 +++++++++++ internal/tui/escape_test.go | 33 ++++ 59 files changed, 2876 insertions(+), 1801 deletions(-) create mode 100644 internal/cmd/audit/view.go create mode 100644 internal/cmd/endpoint/label.go create mode 100644 internal/cmd/policy/change_edit.go create mode 100644 internal/cmd/policy/change_preview.go create mode 100644 internal/cmd/policy/change_publish.go create mode 100644 internal/cmd/policy/change_render.go create mode 100644 internal/cmd/policy/change_view.go create mode 100644 internal/cmd/policy/publish_test.go create mode 100644 internal/cmd/policy/revision_show.go create mode 100644 internal/cmd/policy/rule_delete.go create mode 100644 internal/cmd/policy/rule_filters.go create mode 100644 internal/cmd/policy/rule_input.go delete mode 100644 internal/cmd/policy/rule_ops.go create mode 100644 internal/cmd/policy/rule_show.go create mode 100644 internal/cmd/policy/rule_update.go create mode 100644 internal/cmd/policy/rule_view.go create mode 100644 internal/cmd/policy/settings.go create mode 100644 internal/cmd/project/view.go delete mode 100644 internal/rpcerror/rpcerror.go delete mode 100644 internal/rpcerror/rpcerror_test.go create mode 100644 internal/tui/escape.go create mode 100644 internal/tui/escape_test.go diff --git a/docs/cmd/audit-event-list.md b/docs/cmd/audit-event-list.md index 3b78ef6..993f747 100644 --- a/docs/cmd/audit-event-list.md +++ b/docs/cmd/audit-event-list.md @@ -17,12 +17,16 @@ safedep audit event list [--since DURATION] [--until DURATION] [--action PREFIX] |------|-------------| | `--since <duration>` | Only events in this time before now, as `7d` or `12h`. | | `--until <duration>` | Only events older than this time before now, as `1d`. It must be shorter than `--since`. | -| `--action <prefix>` | Only events whose action starts with this text, as `policy.` or `policy.rule.`. | -| `--resource <kind[/id]>` | Only events about a resource kind, or one resource, as `package_rule` or `policy_change/18`. | +| `--action <prefix>` | Only events whose action starts with this text. `policy.` lists every policy action, and `policy.rule.` lists the package rule actions. | +| `--resource <kind[/id]>` | Only events about a resource kind, or one resource. The kinds are `policy_change`, `package_rule`, `endpoint` and `project`, as in `--resource package_rule` or `--resource policy_change/18`. | | `--actor <actor>` | Only events of this actor. The server matches the actor id or the display name exactly. | | `--limit <n>` | Page size. The server default applies when 0. | | `--page-token <token>` | Continuation token from a prior response. | +Actions have the form `<domain>.<resource>.<verb>`, as `policy.change.publish`. +To list the policy events, use `--action policy.`. `--resource` takes a resource +kind, not a domain. + ## Examples ```bash diff --git a/docs/cmd/policy-change-publish.md b/docs/cmd/policy-change-publish.md index 75ab3ec..ae112c2 100644 --- a/docs/cmd/policy-change-publish.md +++ b/docs/cmd/policy-change-publish.md @@ -5,7 +5,7 @@ Publish an open policy change as a new policy revision for the whole tenant. ## Synopsis ``` -safedep policy change publish CHANGE [-m MESSAGE] +safedep policy change publish CHANGE [-m MESSAGE] [--yes] ``` ## Flags @@ -13,6 +13,12 @@ safedep policy change publish CHANGE [-m MESSAGE] | Flag | Description | |------|-------------| | `-m`, `--message <text>` | The publish message. | +| `-y`, `--yes` | Publish a change that loosens the policy with no prompt. Required when no terminal is present. | + +The command previews the change first. It shows the change direction, each part +that loosens the policy, and every warning. A change that loosens the policy +needs a confirmation: the command asks in a terminal, and needs `--yes` in a +script. ## Examples @@ -21,7 +27,9 @@ safedep policy change publish 18 -m "payments: fail on medium, 7d cooldown (CUST ``` ``` -✓ revision 47 published +Change 18 · TIGHTENS. An Admin can publish it +! LOW_ENFORCED_COVERAGE scan_gate.fail_on: 1 of 3 projects cannot enforce "medium" yet +✓ revision 47 published · TIGHTENS Projects resolve it at their next check. Endpoints apply it after their next policy fetch Endpoints that have not applied it yet: safedep endpoint list --applied-revision '<47' ``` diff --git a/docs/cmd/policy-edit.md b/docs/cmd/policy-edit.md index 8bcff7e..f8bb515 100644 --- a/docs/cmd/policy-edit.md +++ b/docs/cmd/policy-edit.md @@ -38,6 +38,7 @@ The file starts with a header that shows the layers: # 3. overrides - apply to the subjects that their selector matches. # For each field, the highest priority that sets it wins. # +# Keep the id of each override. A new override has no id. # Package rules are not in this file: 211 rules (safedep policy rule list) # The policy keeps no comments. Write the reason for a value in a description field. ``` @@ -55,6 +56,13 @@ safedep policy edit --override payments ## Behavior +- Each policy override has its `id`. Keep it when you rename an override. Remove + an override, or add one with no `id`. The command refuses an `id` that is not in + the policy, and warns before the save for each override that the edit removes. + The server refuses to remove an override while package rules attach to it. +- When the policy holds fields that this CLI does not know, the command stops + before the editor opens, because a save would drop them. Update the CLI. +- An editor that only rewrites line endings or spacing makes no change. - When you close the editor with no change, the command saves nothing. - When the file does not parse, or the server rejects it as invalid, the editor opens again with the error at the top. Close it with no change to stop. diff --git a/docs/cmd/policy-get.md b/docs/cmd/policy-get.md index e5120c1..7e85038 100644 --- a/docs/cmd/policy-get.md +++ b/docs/cmd/policy-get.md @@ -33,7 +33,8 @@ base: scan_gate: fail_on: high overrides: - - name: payments + - id: ov_7c2 + name: payments description: Stricter gate for payment services (CUST-412) priority: 200 selector: @@ -60,7 +61,8 @@ The document form: - An enum value is a short token, as in `medium` for `SEVERITY_MEDIUM`. - A duration is a Go duration, as in `168h`. An edit also accepts days, as in `7d`. - A selector has the Kubernetes form: `matchLabels` and `matchExpressions`. -- The server owns the id of a policy override, so the document leaves it out. +- Each policy override has its `id`, which the server sets and keeps. A rename + keeps the id. A policy override with no id is a new one. ## Authentication diff --git a/docs/cmd/policy-rule-create.md b/docs/cmd/policy-rule-create.md index f759e0c..1b71f19 100644 --- a/docs/cmd/policy-rule-create.md +++ b/docs/cmd/policy-rule-create.md @@ -22,7 +22,7 @@ safedep policy rule create --trust PURL --scope SCOPE --expires DURATION --reaso | `-f`, `--file <path>` | 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 <range>` | 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 <scope>` | With `--trust`: `malware`, `cooldown`, `vulnerability` or `all`. Repeatable. Required. | -| `--expires <when>` | A duration from now, as `30d`, or a date, as `2027-01-26`. Required with `--trust`. | +| `--expires <when>` | 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 <text>` | Why the rule exists. Required. Tools show it in a block message. | | `--ticket <ref>` | A ticket or incident reference, as `IR-2291`. | | `--requested-by <who>` | The team or person that asked for the rule. | @@ -37,6 +37,8 @@ Selector rules, which the CLI checks before the request: has no version, qualifiers or subpath. Use `--vers` for a range. - A trust entry selects one package. - Set a version in the PURL or a `--vers` range, not both. +- 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. `--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. diff --git a/docs/cmd/policy-rule-update.md b/docs/cmd/policy-rule-update.md index 8a7fdbc..0c32d6d 100644 --- a/docs/cmd/policy-rule-update.md +++ b/docs/cmd/policy-rule-update.md @@ -21,7 +21,7 @@ safedep policy rule update RULE [--reason TEXT] [--expires WHEN] [--ticket REF] | `--requested-by <who>` | The new requester. An empty value clears it. | | `-m`, `--message <text>` | The publish message. | -Give at least one of the fields. A later expiry of a trust entry loosens the policy. +Give at least one of the fields. A later expiry of a trust entry loosens the policy. A trust entry expires at most 90 days from now. The command reads the rule to check it before the request. ## Examples diff --git a/internal/cloudpolicy/document.go b/internal/cloudpolicy/document.go index 5af0941..5a7d5df 100644 --- a/internal/cloudpolicy/document.go +++ b/internal/cloudpolicy/document.go @@ -14,18 +14,24 @@ import ( policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" yaml "go.yaml.in/yaml/v3" + "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" ) // documentCodec writes the policy settings document. It leaves out the -// package rules, because admins change them through rule operations, and the -// override ids, which the server owns. RestoreOverrideIDs puts the ids back -// by name before a save. -var documentCodec = &yamlCodec{skip: map[protoreflect.FullName]string{ - "safedep.policy.spec.v1.PolicySpec.core": "package rules are not in this file. " + - "Change them with: safedep policy rule", - "safedep.services.controltower.policy.v1.Override.override_id": "", -}} +// package rules, because admins change them through rule operations. It +// writes the id of each policy override as "id", so a rename keeps the +// override: the server sets the id, keeps it, and refuses an id that is not +// at head. An override with no id is a new one. +var documentCodec = &yamlCodec{ + skip: map[protoreflect.FullName]string{ + "safedep.policy.spec.v1.PolicySpec.core": "package rules are not in this file. " + + "Change them with: safedep policy rule", + }, + names: map[protoreflect.FullName]string{ + "safedep.services.controltower.policy.v1.Override.override_id": "id", + }, +} // ErrEmptyDocument is the error for a saved file with no content. var ErrEmptyDocument = errors.New("the file is empty") @@ -102,24 +108,6 @@ func PolicyMap(p *policyv1.Policy) (any, error) { return out, nil } -// RestoreOverrideIDs gives each edited policy override with no id the id of -// the head policy override with the same name. The document leaves the ids -// out, so the server can tell an edit of a policy override from a new one. -func RestoreOverrideIDs(edited, head *policyv1.Policy) { - ids := make(map[string]string, len(head.GetOverrides())) - for _, o := range head.GetOverrides() { - ids[o.GetName()] = o.GetOverrideId() - } - for _, o := range edited.GetOverrides() { - if o.GetOverrideId() != "" { - continue - } - if id, ok := ids[o.GetName()]; ok { - o.SetOverrideId(id) - } - } -} - // HasUserComments reports whether the saved file holds a comment other than // the header that the CLI wrote. The policy keeps no comments, so a person // loses them on save. @@ -172,3 +160,54 @@ func parseDocument(data []byte) (*yaml.Node, error) { } return node, nil } + +// ErrUnknownFields is the error for a policy with fields that the SDK of +// this CLI does not know. +var ErrUnknownFields = errors.New("the policy holds fields that this safedep CLI does not know") + +// CheckKnownFields walks every level of a message and fails when one holds +// fields that the SDK of this CLI does not know. An edit cannot show such a +// field, and a save would drop it from the policy, so the edit must stop. +func CheckKnownFields(m proto.Message) error { + if m == nil { + return nil + } + var paths []string + collectUnknown(m.ProtoReflect(), "", &paths) + if len(paths) == 0 { + return nil + } + return fmt.Errorf("%w: at %s", ErrUnknownFields, strings.Join(paths, ", ")) +} + +func collectUnknown(m protoreflect.Message, path string, out *[]string) { + if len(m.GetUnknown()) > 0 { + at := path + if at == "" { + at = "the document root" + } + *out = append(*out, at) + } + m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { + fieldPath := joinPath(path, string(fd.Name())) + switch { + case fd.IsList() && isMessageKind(fd): + list := v.List() + for i := 0; i < list.Len(); i++ { + collectUnknown(list.Get(i).Message(), fmt.Sprintf("%s[%d]", fieldPath, i), out) + } + case fd.IsMap() && isMessageKind(fd.MapValue()): + v.Map().Range(func(k protoreflect.MapKey, mv protoreflect.Value) bool { + collectUnknown(mv.Message(), joinPath(fieldPath, k.String()), out) + return true + }) + case !fd.IsList() && !fd.IsMap() && isMessageKind(fd): + collectUnknown(v.Message(), fieldPath, out) + } + return true + }) +} + +func isMessageKind(fd protoreflect.FieldDescriptor) bool { + return fd.Kind() == protoreflect.MessageKind || fd.Kind() == protoreflect.GroupKind +} diff --git a/internal/cloudpolicy/document_test.go b/internal/cloudpolicy/document_test.go index db9e386..878e123 100644 --- a/internal/cloudpolicy/document_test.go +++ b/internal/cloudpolicy/document_test.go @@ -10,6 +10,7 @@ import ( policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/timestamppb" ) @@ -26,7 +27,8 @@ func TestMarshalPolicy_WritesTheWalkthroughForm(t *testing.T) { scan_gate: fail_on: high overrides: - - name: ci + - id: ov_2 + name: ci priority: 300 selector: matchLabels: {managed/deployment-kind: ci} @@ -34,7 +36,8 @@ overrides: package_admission: cooldown: min_age: 168h - - name: payments + - id: ov_1 + name: payments description: Stricter gate for payment services (CUST-412) priority: 200 selector: @@ -47,7 +50,6 @@ overrides: fail_on: medium ` assert.Equal(t, want, string(b)) - assert.NotContains(t, string(b), "override_id", "the server owns override ids") } func TestUnmarshalPolicy_RoundTrips(t *testing.T) { @@ -57,7 +59,6 @@ func TestUnmarshalPolicy_RoundTrips(t *testing.T) { got, err := UnmarshalPolicy(b) require.NoError(t, err) - RestoreOverrideIDs(got, original) assert.True(t, proto.Equal(original, got), "got %v", got) } @@ -170,20 +171,44 @@ func TestEmptySelectorKeepsItsPresence(t *testing.T) { assert.True(t, got.HasSelector(), "selector: {} selects every subject and must stay set") } -func TestRestoreOverrideIDs(t *testing.T) { - head := samplePolicy() - edited := samplePolicy() - for _, o := range edited.GetOverrides() { - o.SetOverrideId("") - } - added := &policyv1.Override{} - added.SetName("new") - edited.SetOverrides(append(edited.GetOverrides(), added)) - - RestoreOverrideIDs(edited, head) - assert.Equal(t, "ov_2", edited.GetOverrides()[0].GetOverrideId()) - assert.Equal(t, "ov_1", edited.GetOverrides()[1].GetOverrideId()) - assert.Empty(t, edited.GetOverrides()[2].GetOverrideId(), "a new override gets its id from the server") +func TestUnmarshalPolicy_KeepsTheIDThatTheUserLeaves(t *testing.T) { + got, err := UnmarshalPolicy([]byte(` +overrides: + - id: ov_1 + name: renamed + priority: 1 + selector: {} + - override_id: ov_2 + name: proto-name-also-works + priority: 2 + selector: {} + - name: new + priority: 3 + selector: {} +`)) + require.NoError(t, err) + require.Len(t, got.GetOverrides(), 3) + assert.Equal(t, "ov_1", got.GetOverrides()[0].GetOverrideId(), "a rename keeps the id") + assert.Equal(t, "ov_2", got.GetOverrides()[1].GetOverrideId()) + assert.Empty(t, got.GetOverrides()[2].GetOverrideId(), "a new override gets its id from the server") +} + +func TestCheckKnownFields(t *testing.T) { + require.NoError(t, CheckKnownFields(samplePolicy())) + require.NoError(t, CheckKnownFields(nil)) + + p := samplePolicy() + // Field 99 of ScanGate is a field that a later contract can add. + unknown := protowire.AppendTag(nil, 99, protowire.VarintType) + unknown = protowire.AppendVarint(unknown, 1) + p.GetOverrides()[1].GetSpec().GetScanGate().ProtoReflect().SetUnknown(unknown) + p.ProtoReflect().SetUnknown(unknown) + + err := CheckKnownFields(p) + require.Error(t, err) + assert.ErrorIs(t, err, ErrUnknownFields) + assert.Contains(t, err.Error(), "the document root") + assert.Contains(t, err.Error(), "overrides[1].spec.scan_gate") } func TestHasUserComments(t *testing.T) { diff --git a/internal/cloudpolicy/protoyaml.go b/internal/cloudpolicy/protoyaml.go index 6643f99..d7c48a3 100644 --- a/internal/cloudpolicy/protoyaml.go +++ b/internal/cloudpolicy/protoyaml.go @@ -38,9 +38,35 @@ var selectorOperators = map[protoreflect.EnumNumber]string{ } // yamlCodec encodes and decodes proto messages as YAML nodes. skip names the -// fields that the document leaves out, by full name. +// fields that the document leaves out, by full name, with the reason that a +// decode gives when a document sets one. names gives a field another key in +// the document, by full name. type yamlCodec struct { - skip map[protoreflect.FullName]string + skip map[protoreflect.FullName]string + names map[protoreflect.FullName]string +} + +// key is the document key of a field. +func (c *yamlCodec) key(fd protoreflect.FieldDescriptor) string { + if name, ok := c.names[fd.FullName()]; ok { + return name + } + return string(fd.Name()) +} + +// fieldByKey finds the field of a document key. It also accepts the proto +// name and the JSON name of a field. +func (c *yamlCodec) fieldByKey(md protoreflect.MessageDescriptor, key string) protoreflect.FieldDescriptor { + fields := md.Fields() + for i := 0; i < fields.Len(); i++ { + if c.key(fields.Get(i)) == key { + return fields.Get(i) + } + } + if fd := fields.ByName(protoreflect.Name(key)); fd != nil { + return fd + } + return fields.ByJSONName(key) } func (c *yamlCodec) encodeMessage(m protoreflect.Message) *yaml.Node { @@ -58,7 +84,7 @@ func (c *yamlCodec) encodeMessage(m protoreflect.Message) *yaml.Node { if _, skipped := c.skip[fd.FullName()]; skipped || !m.Has(fd) { continue } - out.Content = append(out.Content, scalarNode(string(fd.Name())), c.encodeField(fd, m.Get(fd))) + out.Content = append(out.Content, scalarNode(c.key(fd)), c.encodeField(fd, m.Get(fd))) } return out } @@ -265,19 +291,15 @@ func (c *yamlCodec) decodeMessage(n *yaml.Node, m protoreflect.Message, path str return errAt(n, path, "expected a mapping of fields") } - fields := m.Descriptor().Fields() seen := make(map[protoreflect.Name]struct{}, len(n.Content)/2) for i := 0; i+1 < len(n.Content); i += 2 { key, value := n.Content[i], n.Content[i+1] fieldPath := joinPath(path, key.Value) - fd := fields.ByName(protoreflect.Name(key.Value)) - if fd == nil { - fd = fields.ByJSONName(key.Value) - } + fd := c.fieldByKey(m.Descriptor(), key.Value) if fd == nil { return errAt(key, fieldPath, "unknown field. Known fields: %s", strings.Join(c.knownFields(m.Descriptor()), ", ")) } - if reason, skipped := c.skip[fd.FullName()]; skipped && reason != "" { + if reason, skipped := c.skip[fd.FullName()]; skipped { return errAt(key, fieldPath, "%s", reason) } if _, dup := seen[fd.Name()]; dup { @@ -301,7 +323,7 @@ func (c *yamlCodec) knownFields(md protoreflect.MessageDescriptor) []string { if _, skipped := c.skip[fd.FullName()]; skipped { continue } - names = append(names, string(fd.Name())) + names = append(names, c.key(fd)) } return names } diff --git a/internal/cloudpolicy/render.go b/internal/cloudpolicy/render.go index 68b2428..891d0d3 100644 --- a/internal/cloudpolicy/render.go +++ b/internal/cloudpolicy/render.go @@ -2,33 +2,69 @@ package cloudpolicy import ( "strings" + "time" + + messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" + "github.com/charmbracelet/lipgloss" + "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/safedep/cli/internal/tui" ) // Separator joins the parts of a summary line, as in "revision 47", // separator, "published 6m ago by alice". It is a middle dot with spaces. const Separator = " · " -// KeyValues writes label and value rows with the values in one column. A -// value with line breaks keeps the column on each line. +// KeyValues writes label and value rows with the values in one column. The +// column uses the display width of the labels. Each value is escaped as one +// line, because a value can come from the server. A value that needs more +// lines takes more rows: a row with an empty label continues the row above. func KeyValues(rows [][2]string) string { width := 0 for _, r := range rows { - width = max(width, len(r[0])) + width = max(width, lipgloss.Width(r[0])) } var b strings.Builder for i, r := range rows { if i > 0 { b.WriteByte('\n') } - lines := strings.Split(r[1], "\n") b.WriteString(r[0]) - b.WriteString(strings.Repeat(" ", width-len(r[0])+2)) - b.WriteString(lines[0]) - for _, line := range lines[1:] { - b.WriteByte('\n') - b.WriteString(strings.Repeat(" ", width+2)) - b.WriteString(line) - } + b.WriteString(strings.Repeat(" ", width-lipgloss.Width(r[0])+2)) + b.WriteString(tui.EscapeLine(r[1])) } return b.String() } + +// EmptyDash keeps a table cell readable when a value is absent. +func EmptyDash(s string) string { + if s == "" { + return "-" + } + return s +} + +// Plural picks the singular or the plural form for n. +func Plural(n int, singular, plural string) string { + if n == 1 { + return singular + } + return plural +} + +// ActorName names an actor for people: the display name, or the id. +func ActorName(a *messagescontroltowerv1.Actor) string { + if a.GetDisplayName() != "" { + return a.GetDisplayName() + } + return a.GetId() +} + +// TimeOf returns a timestamp in UTC, or nil when it is absent. +func TimeOf(ts *timestamppb.Timestamp) *time.Time { + if ts == nil { + return nil + } + t := ts.AsTime().UTC() + return &t +} diff --git a/internal/cloudpolicy/subject.go b/internal/cloudpolicy/subject.go index 3df8c6c..56e9fc0 100644 --- a/internal/cloudpolicy/subject.go +++ b/internal/cloudpolicy/subject.go @@ -14,7 +14,6 @@ import ( "github.com/safedep/dry/tui/humanize" "github.com/safedep/dry/tui/table" "google.golang.org/grpc" - "google.golang.org/protobuf/types/known/timestamppb" "github.com/safedep/cli/internal/tui" ) @@ -190,9 +189,9 @@ func translateApplied(a *policyv1.AppliedPolicy) AppliedPolicy { DefaultRevision: report.GetDefaultPolicyRevision(), State: tui.EnumToken(report.GetState().String(), applyStatePrefix), RejectedReason: report.GetRejectedReason(), - FetchedAt: timePtr(report.GetFetchedAt()), - AppliedAt: timePtr(report.GetAppliedAt()), - ReportedAt: timePtr(a.GetReportedAt()), + FetchedAt: TimeOf(report.GetFetchedAt()), + AppliedAt: TimeOf(report.GetAppliedAt()), + ReportedAt: TimeOf(a.GetReportedAt()), } for _, e := range report.GetExceptions() { out.Exceptions = append(out.Exceptions, FieldException{ @@ -240,14 +239,6 @@ func appendUnique(values []string, v string) []string { return append(values, v) } -func timePtr(ts *timestamppb.Timestamp) *time.Time { - if ts == nil { - return nil - } - t := ts.AsTime().UTC() - return &t -} - // PolicyLine summarises the intended policy in one line: the revision and // the matched policy overrides, or "no override matches" and "base only". func (p *SubjectPolicy) PolicyLine() string { @@ -346,12 +337,16 @@ func (p *SubjectPolicy) RenderTable() string { {"Package rules", fmt.Sprintf("%d (%d trust, %d block)", p.TrustRules+p.BlockRules, p.TrustRules, p.BlockRules)}, } if !p.Filtered { - rows = append(rows, [2]string{"Labels", emptyDash(strings.Join(p.Labels, " "))}) + labels := make([]string, 0, len(p.Labels)) + for _, l := range p.Labels { + labels = append(labels, tui.EscapeLine(l)) + } + rows = append(rows, [2]string{"Labels", EmptyDash(strings.Join(labels, " "))}) } fieldRows := make([][]string, 0, len(p.Fields)) for _, f := range p.Fields { - fieldRows = append(fieldRows, []string{f.Path, f.Human, f.Source, emptyDash(strings.Join(f.Exceptions, "; "))}) + fieldRows = append(fieldRows, []string{f.Path, f.Human, f.Source, EmptyDash(strings.Join(f.Exceptions, "; "))}) } empty := "The policy sets no fields for this " + p.Kind + "." if p.Filtered { @@ -359,21 +354,21 @@ func (p *SubjectPolicy) RenderTable() string { } fieldTable := table.New(). Headers("FIELD", "VALUE", "SOURCE", "EXCEPTIONS"). - Rows(fieldRows...). + Rows(tui.EscapeCells(fieldRows)...). EmptyMessage(empty). Render() appliedRows := make([][]string, 0, len(p.Applied)) for _, a := range p.Applied { appliedRows = append(appliedRows, []string{ - a.Implementer, emptyDash(a.Version), fmt.Sprintf("%d", a.Revision), a.State, + a.Implementer, EmptyDash(a.Version), fmt.Sprintf("%d", a.Revision), a.State, humanTime(a.FetchedAt, now), humanTime(a.ReportedAt, now), }) } appliedTable := table.New(). Title("Applied policy, as each tool reported it"). Headers("TOOL", "VERSION", "REVISION", "STATE", "FETCHED", "REPORTED"). - Rows(appliedRows...). + Rows(tui.EscapeCells(appliedRows)...). EmptyMessage("No tool or check reported the policy that it applies for this " + p.Kind + " yet."). Render() @@ -384,10 +379,10 @@ func (p *SubjectPolicy) RenderPlain() string { var b strings.Builder b.WriteString("path\tvalue\tsource\texceptions") for _, f := range p.Fields { - fmt.Fprintf(&b, "\n%s\t%s\t%s\t%s", f.Path, f.Value, f.Source, strings.Join(f.Exceptions, "; ")) + b.WriteString("\n" + tui.PlainRow(f.Path, f.Value, f.Source, strings.Join(f.Exceptions, "; "))) } for _, a := range p.Applied { - fmt.Fprintf(&b, "\napplied:%s\t%d\t%s\t%s", a.Implementer, a.Revision, a.State, RFC3339(a.ReportedAt)) + b.WriteString("\n" + tui.PlainRow("applied:"+a.Implementer, fmt.Sprint(a.Revision), a.State, RFC3339(a.ReportedAt))) } return b.String() } @@ -406,10 +401,3 @@ func RFC3339(t *time.Time) string { } return t.UTC().Format(time.RFC3339) } - -func emptyDash(s string) string { - if s == "" { - return "-" - } - return s -} diff --git a/internal/cloudpolicy/subject_test.go b/internal/cloudpolicy/subject_test.go index 81ee5d3..6b8041a 100644 --- a/internal/cloudpolicy/subject_test.go +++ b/internal/cloudpolicy/subject_test.go @@ -132,6 +132,26 @@ func TestGetSubjectPolicy(t *testing.T) { assert.Contains(t, got.RenderPlain(), "scan_gate.fail_on\tmedium\toverride \"payments\" (200)") } +func TestSubjectPolicy_EscapesServerText(t *testing.T) { + res := subjectPolicyResponse() + label := res.GetLabels()[0] + label.SetValue("high\x1b[2J\x1b]0;pwned\x07") + got, err := GetSubjectPolicy(context.Background(), &fakeSubjectPolicyClient{res: res}, + NewSubject(specv1.SubjectKind_SUBJECT_KIND_ENDPOINT, "ep_1"), "host\nname", nil) + require.NoError(t, err) + + for _, out := range []string{got.RenderTable(), got.RenderPlain()} { + assert.NotContains(t, out, "\x1b") + assert.NotContains(t, out, "\x07") + } + assert.Contains(t, got.RenderTable(), `custom/criticality=high\x1b[2J\x1b]0;pwned\x07`) + assert.Contains(t, got.RenderTable(), `host\nname`) + + b, err := got.RenderJSON() + require.NoError(t, err) + assert.Contains(t, string(b), `\u001b[2J`, "JSON keeps the raw value, escaped by the JSON encoder") +} + func TestGetSubjectPolicy_FieldFilter(t *testing.T) { client := &fakeSubjectPolicyClient{res: subjectPolicyResponse()} subject := NewSubject(specv1.SubjectKind_SUBJECT_KIND_ENDPOINT, "ep_1") diff --git a/internal/cmd/audit/list.go b/internal/cmd/audit/list.go index 854839a..5078aff 100644 --- a/internal/cmd/audit/list.go +++ b/internal/cmd/audit/list.go @@ -2,18 +2,13 @@ package audit import ( "context" - "encoding/json" "errors" "fmt" - "sort" "strings" "time" auditv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/audit/v1/auditv1grpc" - messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" auditv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/audit/v1" - "github.com/safedep/dry/tui/humanize" - "github.com/safedep/dry/tui/table" "github.com/safedep/dry/usefulerror" "github.com/spf13/cobra" "google.golang.org/grpc" @@ -24,7 +19,6 @@ import ( "github.com/safedep/cli/internal/app" "github.com/safedep/cli/internal/duration" "github.com/safedep/cli/internal/paging" - "github.com/safedep/cli/internal/tui" ) const resultPrefix = "AUDIT_RESULT_" @@ -48,35 +42,17 @@ type listInput struct { PageToken string } -type eventView struct { - ID string `json:"event_id"` - Actor string `json:"actor"` - ActorKind string `json:"actor_kind"` - Action string `json:"action"` - Kind string `json:"resource_kind"` - ResourceID string `json:"resource_id"` - Result string `json:"result"` - Details map[string]any `json:"details,omitempty"` - RequestID string `json:"request_id,omitempty"` - OccurredAt string `json:"occurred_at"` - occurred *time.Time -} - -type listResult struct { - Events []eventView `json:"events"` - NextPageToken string `json:"next_page_token,omitempty"` -} - func eventListCmd(a *app.App) *cobra.Command { var in listInput cmd := &cobra.Command{ Use: "list", Short: "List audit events, newest first", Long: "List the audit events of the tenant, newest first. --since and --until take a duration " + - "before now, as in 7d or 12h. --action takes a prefix of the action, as in policy. or " + - "policy.rule. --resource takes a resource kind, or a kind and an id, as in policy_change/18. " + - "--actor matches the actor id or the display name exactly. One page is returned per " + - "invocation, so follow --page-token to read the next page.", + "before now, as in 7d or 12h. --action takes a prefix of the action: --action policy. lists " + + "every policy action, and --action policy.rule. lists the package rule actions. --resource " + + "takes a resource kind, as in policy_change, package_rule, endpoint or project, or a kind and " + + "an id, as in policy_change/18. --actor matches the actor id or the display name exactly. " + + "The command reads one page. Pass --page-token to read the next page.", Args: func(cmd *cobra.Command, args []string) error { if err := cobra.NoArgs(cmd, args); err != nil { return err @@ -99,8 +75,9 @@ func eventListCmd(a *app.App) *cobra.Command { f := cmd.Flags() f.Var(duration.NewValue(&in.Since, 0), "since", "only events in this time before now, as in 7d or 12h") f.Var(duration.NewValue(&in.Until, 0), "until", "only events older than this time before now, as in 1d") - f.StringVar(&in.Action, "action", "", "only events whose action starts with this text, as in policy.") - f.StringVar(&in.Resource, "resource", "", "only events about a resource: KIND or KIND/ID, as in policy_change/18") + f.StringVar(&in.Action, "action", "", "only events whose action starts with this text; policy. lists the policy actions") + f.StringVar(&in.Resource, "resource", "", + "only events about a resource: KIND (policy_change, package_rule, endpoint, project) or KIND/ID, as in policy_change/18") f.StringVar(&in.Actor, "actor", "", "only events of this actor id or display name, as in alice@acme.io") f.Uint32Var(&in.PageSize, "limit", 0, "page size; server default when 0") f.StringVar(&in.PageToken, "page-token", "", "continuation token from a prior response") @@ -192,109 +169,3 @@ func mapListError(err error) error { } return cause } - -func newEventView(e *auditv1.AuditEvent) eventView { - v := eventView{ - ID: e.GetEventId(), - Actor: actorName(e.GetActor()), - ActorKind: tui.EnumToken(e.GetActor().GetKind().String(), "ACTOR_KIND_"), - Action: e.GetAction(), - Kind: e.GetResource().GetKind(), - ResourceID: e.GetResource().GetId(), - Result: tui.EnumToken(e.GetResult().String(), resultPrefix), - RequestID: e.GetRequestId(), - } - if e.HasDetails() { - v.Details = e.GetDetails().AsMap() - } - if ts := e.GetOccurredAt(); ts != nil { - t := ts.AsTime().UTC() - v.occurred = &t - v.OccurredAt = t.Format(time.RFC3339) - } - return v -} - -func actorName(a *messagescontroltowerv1.Actor) string { - if a.GetDisplayName() != "" { - return a.GetDisplayName() - } - return a.GetId() -} - -func (v eventView) resource() string { - if v.ResourceID == "" { - return v.Kind - } - return v.Kind + " " + v.ResourceID -} - -// detail writes the details as sorted "key=value" items. -func (v eventView) detail() string { - keys := make([]string, 0, len(v.Details)) - for k := range v.Details { - keys = append(keys, k) - } - sort.Strings(keys) - parts := make([]string, 0, len(keys)) - for _, k := range keys { - value := v.Details[k] - text := fmt.Sprint(value) - if _, scalar := value.(string); !scalar { - if b, err := json.Marshal(value); err == nil { - text = string(b) - } - } - parts = append(parts, k+"="+text) - } - return strings.Join(parts, ", ") -} - -func (r *listResult) RenderJSON() ([]byte, error) { - return json.MarshalIndent(r, "", " ") -} - -func (r *listResult) RenderTable() string { - now := time.Now() - rows := make([][]string, 0, len(r.Events)) - for _, e := range r.Events { - when := "-" - if e.occurred != nil { - when = humanize.Time(*e.occurred, now) - } - detail := e.detail() - if detail == "" { - detail = "-" - } - rows = append(rows, []string{when, e.Actor, e.Action, e.resource(), e.Result, detail}) - } - t := table.New(). - Title("Audit events"). - Headers("WHEN", "ACTOR", "ACTION", "RESOURCE", "RESULT", "DETAIL"). - Rows(rows...). - EmptyMessage("No audit events match. Try a wider --since window.") - if len(rows) > 0 { - footer := fmt.Sprintf("%d %s", len(rows), plural(len(rows))) - if r.NextPageToken != "" { - footer += ". More available: --page-token " + r.NextPageToken - } - t = t.Footer(footer) - } - return t.Render() -} - -func (r *listResult) RenderPlain() string { - var b strings.Builder - b.WriteString("occurred_at\tactor\taction\tresource_kind\tresource_id\tresult\tdetails") - for _, e := range r.Events { - fmt.Fprintf(&b, "\n%s\t%s\t%s\t%s\t%s\t%s\t%s", e.OccurredAt, e.Actor, e.Action, e.Kind, e.ResourceID, e.Result, e.detail()) - } - return b.String() -} - -func plural(n int) string { - if n == 1 { - return "event" - } - return "events" -} diff --git a/internal/cmd/audit/list_test.go b/internal/cmd/audit/list_test.go index 8b39105..1f6bf47 100644 --- a/internal/cmd/audit/list_test.go +++ b/internal/cmd/audit/list_test.go @@ -2,6 +2,7 @@ package audit import ( "context" + "strings" "testing" "time" @@ -140,3 +141,22 @@ func TestRunList_MemberIsDenied(t *testing.T) { require.True(t, ok) assert.Equal(t, "Only an Admin can read the audit log", ue.HumanError()) } + +func TestRender_EscapesServerText(t *testing.T) { + e := auditEvent() + e.GetActor().SetDisplayName("mallory\x1b]0;owned\x07") + details, err := structpb.NewStruct(map[string]any{"reason": "a\nb"}) + require.NoError(t, err) + e.SetDetails(details) + res := &auditv1.ListAuditEventsResponse{} + res.SetEvents([]*auditv1.AuditEvent{e}) + + got, err := runList(context.Background(), &fakeLister{res: res}, listInput{}, now) + require.NoError(t, err) + for _, out := range []string{got.RenderTable(), got.RenderPlain()} { + assert.NotContains(t, out, "\x1b") + assert.Contains(t, out, `mallory\x1b]0;owned\x07`) + assert.Contains(t, out, `reason=a\nb`) + } + assert.Len(t, strings.Split(got.RenderPlain(), "\n"), 2, "a line break in a value adds no row") +} diff --git a/internal/cmd/audit/view.go b/internal/cmd/audit/view.go new file mode 100644 index 0000000..5e7bcdb --- /dev/null +++ b/internal/cmd/audit/view.go @@ -0,0 +1,127 @@ +package audit + +import ( + "encoding/json" + "fmt" + "sort" + "strings" + "time" + + auditv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/audit/v1" + "github.com/safedep/dry/tui/humanize" + "github.com/safedep/dry/tui/table" + + "github.com/safedep/cli/internal/cloudpolicy" + "github.com/safedep/cli/internal/tui" +) + +type eventView struct { + ID string `json:"event_id"` + Actor string `json:"actor"` + ActorKind string `json:"actor_kind"` + Action string `json:"action"` + Kind string `json:"resource_kind"` + ResourceID string `json:"resource_id"` + Result string `json:"result"` + Details map[string]any `json:"details,omitempty"` + RequestID string `json:"request_id,omitempty"` + OccurredAt string `json:"occurred_at"` + occurred *time.Time +} + +type listResult struct { + Events []eventView `json:"events"` + NextPageToken string `json:"next_page_token,omitempty"` +} + +func newEventView(e *auditv1.AuditEvent) eventView { + v := eventView{ + ID: e.GetEventId(), + Actor: cloudpolicy.ActorName(e.GetActor()), + ActorKind: tui.EnumToken(e.GetActor().GetKind().String(), "ACTOR_KIND_"), + Action: e.GetAction(), + Kind: e.GetResource().GetKind(), + ResourceID: e.GetResource().GetId(), + Result: tui.EnumToken(e.GetResult().String(), resultPrefix), + RequestID: e.GetRequestId(), + } + if e.HasDetails() { + v.Details = e.GetDetails().AsMap() + } + if ts := e.GetOccurredAt(); ts != nil { + t := ts.AsTime().UTC() + v.occurred = &t + v.OccurredAt = t.Format(time.RFC3339) + } + return v +} + +func (v eventView) resource() string { + if v.ResourceID == "" { + return v.Kind + } + return v.Kind + " " + v.ResourceID +} + +// detail writes the details as sorted "key=value" items. +func (v eventView) detail() string { + keys := make([]string, 0, len(v.Details)) + for k := range v.Details { + keys = append(keys, k) + } + sort.Strings(keys) + parts := make([]string, 0, len(keys)) + for _, k := range keys { + value := v.Details[k] + text := fmt.Sprint(value) + if _, scalar := value.(string); !scalar { + if b, err := json.Marshal(value); err == nil { + text = string(b) + } + } + parts = append(parts, k+"="+text) + } + return strings.Join(parts, ", ") +} + +func (r *listResult) RenderJSON() ([]byte, error) { + return json.MarshalIndent(r, "", " ") +} + +func (r *listResult) RenderTable() string { + now := time.Now() + rows := make([][]string, 0, len(r.Events)) + for _, e := range r.Events { + when := "-" + if e.occurred != nil { + when = humanize.Time(*e.occurred, now) + } + detail := e.detail() + if detail == "" { + detail = "-" + } + rows = append(rows, []string{when, e.Actor, e.Action, e.resource(), e.Result, detail}) + } + t := table.New(). + Title("Audit events"). + Headers("WHEN", "ACTOR", "ACTION", "RESOURCE", "RESULT", "DETAIL"). + Rows(tui.EscapeCells(rows)...). + EmptyMessage("No audit events match. Try a wider --since window.") + if len(rows) > 0 { + footer := fmt.Sprintf("%d %s", len(rows), cloudpolicy.Plural(len(rows), "event", "events")) + if r.NextPageToken != "" { + footer += ". More available: --page-token " + r.NextPageToken + } + t = t.Footer(footer) + } + return t.Render() +} + +func (r *listResult) RenderPlain() string { + var b strings.Builder + b.WriteString("occurred_at\tactor\taction\tresource_kind\tresource_id\tresult\tdetails") + for _, e := range r.Events { + b.WriteString("\n" + tui.PlainRow(e.OccurredAt, e.Actor, e.Action, e.Kind, e.ResourceID, e.Result, e.detail())) + } + return b.String() +} diff --git a/internal/cmd/endpoint/label.go b/internal/cmd/endpoint/label.go new file mode 100644 index 0000000..83211c8 --- /dev/null +++ b/internal/cmd/endpoint/label.go @@ -0,0 +1,148 @@ +package endpoint + +import ( + "context" + "fmt" + + policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" + messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" + specv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/spec/v1" + "github.com/safedep/dry/tui" + "github.com/spf13/cobra" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" +) + +func labelCmd(a *app.App) *cobra.Command { + parent := &cobra.Command{ + Use: "label", + Short: "Set or delete the custom labels of endpoints", + Long: "Set or delete the custom/ labels of endpoints. A policy override selects endpoints by their " + + "labels. An admin writes only custom/ labels. The shared managed file sets managed/ labels, and " + + "the tools report reported/ labels. A label change takes effect at the next policy fetch of " + + "each endpoint.", + } + parent.AddCommand(labelSetCmd(a), labelDeleteCmd(a)) + return parent +} + +func labelSetCmd(a *app.App) *cobra.Command { + var labels []string + cmd := &cobra.Command{ + Use: "set ENDPOINT... --label custom/KEY=VALUE", + Short: "Set custom labels on endpoints", + Long: "Set custom/ labels on up to 100 endpoints. A label with an existing key gets the new value. " + + "The label takes effect at the next policy fetch of each endpoint.", + Args: func(cmd *cobra.Command, args []string) error { + if err := cobra.MinimumNArgs(1)(cmd, args); err != nil { + return err + } + _, err := cloudpolicy.ParseCustomLabels(labels) + return err + }, + RunE: func(cmd *cobra.Command, args []string) error { + parsed, err := cloudpolicy.ParseCustomLabels(labels) + if err != nil { + return err + } + client, err := a.ControlPlane() + if err != nil { + return err + } + dir, err := NewDirectoryFromApp(a) + if err != nil { + return err + } + n, err := runLabelSet(cmd.Context(), cloudpolicy.NewLabelClient(client.Connection()), dir, args, parsed) + if err != nil { + return err + } + tui.Success("label set on %d %s. It takes effect at the next policy fetch of each endpoint", + n, plural(n, "endpoint", "endpoints")) + return nil + }, + } + cmd.Flags().StringArrayVar(&labels, "label", nil, "a label as custom/KEY=VALUE; repeatable") + return cmd +} + +func labelDeleteCmd(a *app.App) *cobra.Command { + var keys []string + cmd := &cobra.Command{ + Use: "delete ENDPOINT... --key custom/KEY", + Short: "Delete custom labels from endpoints", + Long: "Delete custom/ labels from up to 100 endpoints. The change takes effect at the next policy fetch of each endpoint.", + Args: func(cmd *cobra.Command, args []string) error { + if err := cobra.MinimumNArgs(1)(cmd, args); err != nil { + return err + } + return cloudpolicy.ValidateCustomKeys(keys) + }, + RunE: func(cmd *cobra.Command, args []string) error { + client, err := a.ControlPlane() + if err != nil { + return err + } + dir, err := NewDirectoryFromApp(a) + if err != nil { + return err + } + n, err := runLabelDelete(cmd.Context(), cloudpolicy.NewLabelClient(client.Connection()), dir, args, keys) + if err != nil { + return err + } + tui.Success("label deleted from %d %s. It takes effect at the next policy fetch of each endpoint", + n, plural(n, "endpoint", "endpoints")) + return nil + }, + } + cmd.Flags().StringArrayVar(&keys, "key", nil, "a label key as custom/KEY; repeatable") + return cmd +} + +func resolveEndpoints(ctx context.Context, dir *Directory, refs []string) ([]string, error) { + ids := make([]string, 0, len(refs)) + for _, ref := range refs { + id, err := dir.Resolve(ctx, ref) + if err != nil { + return nil, fmt.Errorf("endpoint %q: %w", ref, err) + } + ids = append(ids, id) + } + return ids, nil +} + +func runLabelSet( + ctx context.Context, + client policyv1grpc.LabelServiceClient, + dir *Directory, + refs []string, + labels []*messagescontroltowerv1.Label, +) (int, error) { + ids, err := resolveEndpoints(ctx, dir, refs) + if err != nil { + return 0, err + } + if err := cloudpolicy.SetLabels(ctx, client, specv1.SubjectKind_SUBJECT_KIND_ENDPOINT, ids, labels); err != nil { + return 0, err + } + return len(ids), nil +} + +func runLabelDelete( + ctx context.Context, + client policyv1grpc.LabelServiceClient, + dir *Directory, + refs []string, + keys []string, +) (int, error) { + ids, err := resolveEndpoints(ctx, dir, refs) + if err != nil { + return 0, err + } + if err := cloudpolicy.DeleteLabels(ctx, client, specv1.SubjectKind_SUBJECT_KIND_ENDPOINT, ids, keys); err != nil { + return 0, err + } + return len(ids), nil +} diff --git a/internal/cmd/endpoint/list.go b/internal/cmd/endpoint/list.go index 8a274e6..b60cfeb 100644 --- a/internal/cmd/endpoint/list.go +++ b/internal/cmd/endpoint/list.go @@ -12,6 +12,7 @@ import ( controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" "github.com/safedep/cli/internal/app" "github.com/safedep/cli/internal/cloudpolicy" + "github.com/safedep/cli/internal/tui" "github.com/safedep/dry/tui/humanize" "github.com/safedep/dry/tui/table" "github.com/spf13/cobra" @@ -234,10 +235,8 @@ func (r *listResult) RenderPlain() string { var b strings.Builder b.WriteString("ID\tHOSTNAME\tOS\tCAPS\tLAST SYNC\tBLOCKED\tINVENTORY\tPOLICY\n") for _, e := range r.endpoints { - fmt.Fprintf(&b, "%s\t%s\t%s/%s\t%s\t%s\t%d\t%d\t%s\n", - e.ID, e.Hostname, e.OS, e.Arch, strings.Join(capabilityNames(e.Capabilities), ","), - formatTime(e.LastSync), e.PMGBlockedEvents, e.InventoryEvents, policyCell(e.ToolPolicies), - ) + b.WriteString(tui.PlainRow(e.ID, e.Hostname, e.OS+"/"+e.Arch, strings.Join(capabilityNames(e.Capabilities), ","), + formatTime(e.LastSync), fmt.Sprint(e.PMGBlockedEvents), fmt.Sprint(e.InventoryEvents), policyCell(e.ToolPolicies)) + "\n") } return strings.TrimRight(b.String(), "\n") } @@ -258,7 +257,7 @@ func (r *listResult) RenderTable() string { t := table.New(). Title("Endpoints"). Headers("ID", "Hostname", "OS/Arch", "Capabilities", "Last Sync", "Blocked", "Inventory", "Policy"). - Rows(rows...). + Rows(tui.EscapeCells(rows)...). EmptyMessage("No endpoints found. Endpoints appear after a SafeDep tool syncs. Try a wider --since window.") if len(rows) > 0 { footer := fmt.Sprintf("%d %s", len(rows), plural(len(rows), "endpoint", "endpoints")) diff --git a/internal/cmd/endpoint/policy.go b/internal/cmd/endpoint/policy.go index 9845198..08e229b 100644 --- a/internal/cmd/endpoint/policy.go +++ b/internal/cmd/endpoint/policy.go @@ -2,154 +2,17 @@ package endpoint import ( "context" - "fmt" - policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" - messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" specv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/spec/v1" - "github.com/safedep/dry/tui" "github.com/spf13/cobra" "github.com/safedep/cli/internal/app" "github.com/safedep/cli/internal/cloudpolicy" ) -// This file holds the policy verbs of the endpoint tree: `label set|delete` -// and `policy show`. An endpoint argument is a ULID, a unique ULID prefix, -// or a hostname that `safedep endpoint list` cached. - -func labelCmd(a *app.App) *cobra.Command { - parent := &cobra.Command{ - Use: "label", - Short: "Set or delete the custom labels of endpoints", - Long: "Set or delete the custom/ labels of endpoints. A policy override selects endpoints by their " + - "labels. An admin writes only custom/ labels. The shared managed file sets managed/ labels, and " + - "the tools report reported/ labels. A label change takes effect at the next policy fetch of " + - "each endpoint.", - } - parent.AddCommand(labelSetCmd(a), labelDeleteCmd(a)) - return parent -} - -func labelSetCmd(a *app.App) *cobra.Command { - var labels []string - cmd := &cobra.Command{ - Use: "set ENDPOINT... --label custom/KEY=VALUE", - Short: "Set custom labels on endpoints", - Long: "Set custom/ labels on up to 100 endpoints. A label with an existing key gets the new value. " + - "The label takes effect at the next policy fetch of each endpoint.", - Args: func(cmd *cobra.Command, args []string) error { - if err := cobra.MinimumNArgs(1)(cmd, args); err != nil { - return err - } - _, err := cloudpolicy.ParseCustomLabels(labels) - return err - }, - RunE: func(cmd *cobra.Command, args []string) error { - parsed, err := cloudpolicy.ParseCustomLabels(labels) - if err != nil { - return err - } - client, err := a.ControlPlane() - if err != nil { - return err - } - dir, err := NewDirectoryFromApp(a) - if err != nil { - return err - } - n, err := runLabelSet(cmd.Context(), cloudpolicy.NewLabelClient(client.Connection()), dir, args, parsed) - if err != nil { - return err - } - tui.Success("label set on %d %s. It takes effect at the next policy fetch of each endpoint", - n, plural(n, "endpoint", "endpoints")) - return nil - }, - } - cmd.Flags().StringArrayVar(&labels, "label", nil, "a label as custom/KEY=VALUE; repeatable") - return cmd -} - -func labelDeleteCmd(a *app.App) *cobra.Command { - var keys []string - cmd := &cobra.Command{ - Use: "delete ENDPOINT... --key custom/KEY", - Short: "Delete custom labels from endpoints", - Long: "Delete custom/ labels from up to 100 endpoints. The change takes effect at the next policy fetch of each endpoint.", - Args: func(cmd *cobra.Command, args []string) error { - if err := cobra.MinimumNArgs(1)(cmd, args); err != nil { - return err - } - return cloudpolicy.ValidateCustomKeys(keys) - }, - RunE: func(cmd *cobra.Command, args []string) error { - client, err := a.ControlPlane() - if err != nil { - return err - } - dir, err := NewDirectoryFromApp(a) - if err != nil { - return err - } - n, err := runLabelDelete(cmd.Context(), cloudpolicy.NewLabelClient(client.Connection()), dir, args, keys) - if err != nil { - return err - } - tui.Success("label deleted from %d %s. It takes effect at the next policy fetch of each endpoint", - n, plural(n, "endpoint", "endpoints")) - return nil - }, - } - cmd.Flags().StringArrayVar(&keys, "key", nil, "a label key as custom/KEY; repeatable") - return cmd -} - -func resolveEndpoints(ctx context.Context, dir *Directory, refs []string) ([]string, error) { - ids := make([]string, 0, len(refs)) - for _, ref := range refs { - id, err := dir.Resolve(ctx, ref) - if err != nil { - return nil, fmt.Errorf("endpoint %q: %w", ref, err) - } - ids = append(ids, id) - } - return ids, nil -} - -func runLabelSet( - ctx context.Context, - client policyv1grpc.LabelServiceClient, - dir *Directory, - refs []string, - labels []*messagescontroltowerv1.Label, -) (int, error) { - ids, err := resolveEndpoints(ctx, dir, refs) - if err != nil { - return 0, err - } - if err := cloudpolicy.SetLabels(ctx, client, specv1.SubjectKind_SUBJECT_KIND_ENDPOINT, ids, labels); err != nil { - return 0, err - } - return len(ids), nil -} - -func runLabelDelete( - ctx context.Context, - client policyv1grpc.LabelServiceClient, - dir *Directory, - refs []string, - keys []string, -) (int, error) { - ids, err := resolveEndpoints(ctx, dir, refs) - if err != nil { - return 0, err - } - if err := cloudpolicy.DeleteLabels(ctx, client, specv1.SubjectKind_SUBJECT_KIND_ENDPOINT, ids, keys); err != nil { - return 0, err - } - return len(ids), nil -} +// This file holds `endpoint policy show`. label.go holds `label set|delete`. +// An endpoint argument is a ULID, a unique ULID prefix, or a hostname that +// `safedep endpoint list` cached. func policyCmd(a *app.App) *cobra.Command { parent := &cobra.Command{ diff --git a/internal/cmd/policy/change_create.go b/internal/cmd/policy/change_create.go index c88db9e..3fbf440 100644 --- a/internal/cmd/policy/change_create.go +++ b/internal/cmd/policy/change_create.go @@ -14,6 +14,7 @@ import ( "github.com/safedep/cli/internal/app" "github.com/safedep/cli/internal/cloudpolicy" + clitui "github.com/safedep/cli/internal/tui" ) const ( @@ -54,10 +55,11 @@ func changeCreateCmd(a *app.App) *cobra.Command { if err != nil { return err } - tui.Success("change %s %s", change.GetChangeId(), restoreSummary(change.GetRestore())) + id := clitui.EscapeLine(change.GetChangeId()) + tui.Success("change %s %s", id, clitui.EscapeLine(restoreSummary(change.GetRestore()))) reportRestoreDirection(cmd.Context(), policyClient, change.GetChangeId()) - tui.Info(" Review it: safedep policy change show %s", change.GetChangeId()) - tui.Info(" Publish it: safedep policy change publish %s", change.GetChangeId()) + tui.Info(" Review it: safedep policy change show %s", id) + tui.Info(" Publish it: safedep policy change publish %s", id) return nil }, } @@ -118,7 +120,7 @@ func runChangeCreate( req.SetRestore(restore) res, err := client.CreatePolicyChange(ctx, req) if err != nil { - return nil, mapChangeError("create", fmt.Sprintf("from revision %d", in.FromRevision), err) + return nil, mapRestoreError(in.FromRevision, err) } return res.GetChange(), nil } @@ -129,13 +131,8 @@ func runChangeCreate( func reportRestoreDirection(ctx context.Context, client policyv1grpc.PolicyServiceClient, id string) { preview, err := previewChange(ctx, client, id) if err != nil { - tui.Warning("Could not preview change %s: %v", id, err) + tui.Warning("Could not preview change %s: %s", clitui.EscapeLine(id), clitui.EscapeLine(err.Error())) return } - for _, item := range preview.Items { - if item.Direction != "LOOSENS" { - continue - } - tui.Warning("It loosens %s (%s -> %s) in %s", item.What, item.oldHuman, item.newHuman, item.Where) - } + reportLoosening(preview) } diff --git a/internal/cmd/policy/change_edit.go b/internal/cmd/policy/change_edit.go new file mode 100644 index 0000000..db1fd7b --- /dev/null +++ b/internal/cmd/policy/change_edit.go @@ -0,0 +1,108 @@ +package policy + +import ( + "context" + "errors" + "fmt" + + policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/safedep/dry/tui" + "github.com/spf13/cobra" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" + clitui "github.com/safedep/cli/internal/tui" +) + +func changeEditCmd(a *app.App) *cobra.Command { + var in editInput + cmd := &cobra.Command{ + Use: "edit CHANGE", + Short: "Edit the policy settings of an open policy change", + Long: "Open the policy settings of an open policy change in $VISUAL or $EDITOR. Saving updates the " + + "change on the server. A change that does not edit the settings yet starts from the head " + + "settings. Use -m to change the title, and --override NAME to edit one policy override.", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + if err := requireTerminal(); err != nil { + return err + } + client, err := a.ControlPlane() + if err != nil { + return err + } + change, err := runChangeEdit(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), + openEditor, a.Tenant(), args[0], in) + if errors.Is(err, errNoChange) { + tui.Info("No change. Nothing is saved") + return nil + } + if err != nil { + return err + } + id := clitui.EscapeLine(change.GetChangeId()) + tui.Success("change %s updated", id) + tui.Info(" Review it: safedep policy change show %s", id) + return nil + }, + } + cmd.Flags().StringVarP(&in.Title, "message", "m", "", "a new title for the policy change") + cmd.Flags().StringVar(&in.Override, "override", "", "edit only the policy override with this name") + return cmd +} + +func runChangeEdit( + ctx context.Context, + client policyv1grpc.PolicyServiceClient, + open openEditorFunc, + tenant, id string, + in editInput, +) (*policyv1.PolicyChange, error) { + change, err := getChange(ctx, client, id) + if err != nil { + return nil, err + } + if err := requireOpen(change); err != nil { + return nil, err + } + head, err := getPolicy(ctx, client) + if err != nil { + return nil, err + } + + start := head.GetPolicy() + if change.HasSettings() { + start = change.GetSettings() + } + if change.HasRestore() { + tui.Warning("Change %s restores from revision %d. Saving replaces the settings that the restore made", + clitui.EscapeLine(id), change.GetRestore().GetFromRevision()) + } + intro := []string{ + fmt.Sprintf("Change %s of %s%sbase revision %d%shead revision %d", + id, tenantName(tenant), sep, change.GetBaseRevision(), sep, head.GetHeadRevision()), + "Saving updates the draft change. Nothing applies until you publish it.", + } + + var updated *policyv1.PolicyChange + err = editSettings(ctx, open, start, editHeader(intro, head), in.Override, func(p *policyv1.Policy) error { + req := &policyv1.UpdatePolicyChangeRequest{} + req.SetChangeId(id) + req.SetEtag(change.GetEtag()) + req.SetSettings(p) + if in.Title != "" { + req.SetTitle(in.Title) + } + res, err := client.UpdatePolicyChange(ctx, req) + if err != nil { + return mapChangeError("update", id, err) + } + updated = res.GetChange() + return nil + }) + if err != nil { + return nil, err + } + return updated, nil +} diff --git a/internal/cmd/policy/change_list.go b/internal/cmd/policy/change_list.go index 7103ecf..c999f81 100644 --- a/internal/cmd/policy/change_list.go +++ b/internal/cmd/policy/change_list.go @@ -24,67 +24,6 @@ type changeListInput struct { PageToken string } -type changeView struct { - ID string `json:"change_id"` - Title string `json:"title"` - State string `json:"state"` - BaseRevision uint64 `json:"base_revision"` - PublishedRevision uint64 `json:"published_revision,omitempty"` - Author string `json:"author"` - EditsSettings bool `json:"edits_settings"` - RuleOperations int `json:"package_rule_operations"` - RestoreFrom uint64 `json:"restore_from_revision,omitempty"` - Created string `json:"created_at,omitempty"` - Updated string `json:"updated_at,omitempty"` - updatedAt *time.Time -} - -func newChangeView(c *policyv1.PolicyChange) changeView { - updated := timeOf(c.GetUpdatedAt()) - v := changeView{ - ID: c.GetChangeId(), - Title: c.GetTitle(), - State: tui.EnumToken(c.GetState().String(), changeStatePrefix), - BaseRevision: c.GetBaseRevision(), - PublishedRevision: c.GetPublishedRevision(), - Author: actorName(c.GetAuthor()), - EditsSettings: c.HasSettings(), - RuleOperations: len(c.GetPackageRuleOperations()), - Created: cloudpolicy.RFC3339(timeOf(c.GetCreatedAt())), - Updated: cloudpolicy.RFC3339(updated), - updatedAt: updated, - } - if c.HasRestore() { - v.RestoreFrom = c.GetRestore().GetFromRevision() - } - return v -} - -func (v changeView) titleOrUntitled() string { - if v.Title == "" { - return "(untitled)" - } - return v.Title -} - -// contents says what the change edits, as in "settings, 2 rule operations". -func (v changeView) contents() string { - var parts []string - if v.RestoreFrom > 0 { - parts = append(parts, fmt.Sprintf("restore from revision %d", v.RestoreFrom)) - } - if v.EditsSettings { - parts = append(parts, "settings") - } - if v.RuleOperations > 0 { - parts = append(parts, fmt.Sprintf("%d rule %s", v.RuleOperations, plural(v.RuleOperations, "operation", "operations"))) - } - if len(parts) == 0 { - return "nothing" - } - return strings.Join(parts, ", ") -} - type changeListResult struct { Changes []changeView `json:"changes"` NextPageToken string `json:"next_page_token,omitempty"` @@ -95,8 +34,8 @@ func changeListCmd(a *app.App) *cobra.Command { cmd := &cobra.Command{ Use: "list", Short: "List policy changes, newest first", - Long: "List the policy changes of the tenant, newest first. Filter by state. One page is returned " + - "per invocation, so follow --page-token to read the next page.", + Long: "List the policy changes of the tenant, newest first. Filter by state. The command reads one page. " + + "Pass --page-token to read the next page.", Args: func(cmd *cobra.Command, args []string) error { if err := cobra.NoArgs(cmd, args); err != nil { return err @@ -184,16 +123,16 @@ func (r *changeListResult) RenderTable() string { } rows = append(rows, []string{ c.ID, c.titleOrUntitled(), state, fmt.Sprintf("%d", c.BaseRevision), - c.contents(), emptyDash(c.Author), humanTimeCell(c.updatedAt, now), + c.contents(), cloudpolicy.EmptyDash(c.Author), humanTimeCell(c.updatedAt, now), }) } t := table.New(). Title("Policy changes"). Headers("CHANGE", "TITLE", "STATE", "BASE REV", "EDITS", "AUTHOR", "UPDATED"). - Rows(rows...). + Rows(tui.EscapeCells(rows)...). EmptyMessage("No policy changes. Create one with: safedep policy edit") if len(rows) > 0 { - footer := fmt.Sprintf("%d %s", len(rows), plural(len(rows), "change", "changes")) + footer := fmt.Sprintf("%d %s", len(rows), cloudpolicy.Plural(len(rows), "change", "changes")) if r.NextPageToken != "" { footer += ". More available: --page-token " + r.NextPageToken } @@ -206,8 +145,8 @@ func (r *changeListResult) RenderPlain() string { var b strings.Builder b.WriteString("change_id\ttitle\tstate\tbase_revision\tpublished_revision\tauthor\tupdated_at") for _, c := range r.Changes { - fmt.Fprintf(&b, "\n%s\t%s\t%s\t%d\t%d\t%s\t%s", - c.ID, c.Title, c.State, c.BaseRevision, c.PublishedRevision, c.Author, c.Updated) + b.WriteString("\n" + tui.PlainRow(c.ID, c.Title, c.State, fmt.Sprint(c.BaseRevision), + fmt.Sprint(c.PublishedRevision), c.Author, c.Updated)) } return b.String() } diff --git a/internal/cmd/policy/change_ops.go b/internal/cmd/policy/change_ops.go index 5051879..c5965e7 100644 --- a/internal/cmd/policy/change_ops.go +++ b/internal/cmd/policy/change_ops.go @@ -2,7 +2,6 @@ package policy import ( "context" - "errors" "fmt" policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" @@ -12,99 +11,9 @@ import ( "github.com/safedep/cli/internal/app" "github.com/safedep/cli/internal/cloudpolicy" + clitui "github.com/safedep/cli/internal/tui" ) -func changeEditCmd(a *app.App) *cobra.Command { - var in editInput - cmd := &cobra.Command{ - Use: "edit CHANGE", - Short: "Edit the policy settings of an open policy change", - Long: "Open the policy settings of an open policy change in $VISUAL or $EDITOR. Saving updates the " + - "change on the server. A change that does not edit the settings yet starts from the head " + - "settings. Use -m to change the title, and --override NAME to edit one policy override.", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - if err := requireTerminal(); err != nil { - return err - } - client, err := a.ControlPlane() - if err != nil { - return err - } - change, err := runChangeEdit(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), - openEditor, a.Tenant(), args[0], in) - if errors.Is(err, errNoChange) { - tui.Info("No change. Nothing is saved") - return nil - } - if err != nil { - return err - } - tui.Success("change %s updated", change.GetChangeId()) - tui.Info(" Review it: safedep policy change show %s", change.GetChangeId()) - return nil - }, - } - cmd.Flags().StringVarP(&in.Title, "message", "m", "", "a new title for the policy change") - cmd.Flags().StringVar(&in.Override, "override", "", "edit only the policy override with this name") - return cmd -} - -func runChangeEdit( - ctx context.Context, - client policyv1grpc.PolicyServiceClient, - open openEditorFunc, - tenant, id string, - in editInput, -) (*policyv1.PolicyChange, error) { - change, err := getChange(ctx, client, id) - if err != nil { - return nil, err - } - if err := requireOpen(change); err != nil { - return nil, err - } - head, err := getPolicy(ctx, client) - if err != nil { - return nil, err - } - - start := head.GetPolicy() - if change.HasSettings() { - start = change.GetSettings() - } - if change.HasRestore() { - tui.Warning("Change %s restores from revision %d. Saving replaces the settings that the restore made", - id, change.GetRestore().GetFromRevision()) - } - intro := []string{ - fmt.Sprintf("Change %s of %s%sbase revision %d%shead revision %d", - id, tenantName(tenant), sep, change.GetBaseRevision(), sep, head.GetHeadRevision()), - "Saving updates the draft change. Nothing applies until you publish it.", - } - - var updated *policyv1.PolicyChange - err = editSettings(ctx, open, start, editHeader(intro, head), in.Override, func(p *policyv1.Policy) error { - req := &policyv1.UpdatePolicyChangeRequest{} - req.SetChangeId(id) - req.SetEtag(change.GetEtag()) - req.SetSettings(p) - if in.Title != "" { - req.SetTitle(in.Title) - } - res, err := client.UpdatePolicyChange(ctx, req) - if err != nil { - return mapChangeError("update", id, err) - } - updated = res.GetChange() - return nil - }) - if err != nil { - return nil, err - } - return updated, nil -} - func requireOpen(change *policyv1.PolicyChange) error { if change.GetState() == policyv1.PolicyChangeState_POLICY_CHANGE_STATE_OPEN { return nil @@ -132,8 +41,9 @@ func changeSyncCmd(a *app.App) *cobra.Command { if err != nil { return err } + id := clitui.EscapeLine(change.GetChangeId()) tui.Success("change %s rebased on revision %d%sreview it: safedep policy change show %s", - change.GetChangeId(), change.GetBaseRevision(), sep, change.GetChangeId()) + id, change.GetBaseRevision(), sep, id) return nil }, } @@ -171,7 +81,7 @@ func changeDeleteCmd(a *app.App) *cobra.Command { if err := runChangeDelete(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), args[0]); err != nil { return err } - tui.Success("change %s deleted", args[0]) + tui.Success("change %s deleted", clitui.EscapeLine(args[0])) return nil }, } @@ -185,61 +95,3 @@ func runChangeDelete(ctx context.Context, client policyv1grpc.PolicyServiceClien } return nil } - -func changePublishCmd(a *app.App) *cobra.Command { - var message string - cmd := &cobra.Command{ - Use: "publish CHANGE", - Short: "Publish an open policy change as a new policy revision", - Long: "Publish an open policy change. The publish makes a new policy revision for the whole " + - "tenant. Projects resolve it at their next check, and endpoints apply it after their next " + - "policy fetch. If a part that the change edits moved since its base revision, the publish " + - "stops. Then sync the change and review it again.", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - client, err := a.ControlPlane() - if err != nil { - return err - } - rev, err := runChangePublish(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), args[0], message) - if err != nil { - return err - } - reportPublish(rev.GetRevision()) - return nil - }, - } - cmd.Flags().StringVarP(&message, "message", "m", "", "the publish message; the change title becomes the title when it is empty") - return cmd -} - -func runChangePublish( - ctx context.Context, - client policyv1grpc.PolicyServiceClient, - id, message string, -) (*policyv1.PolicyRevision, error) { - change, err := getChange(ctx, client, id) - if err != nil { - return nil, err - } - if err := requireOpen(change); err != nil { - return nil, err - } - req := &policyv1.PublishPolicyChangeRequest{} - req.SetChangeId(id) - req.SetEtag(change.GetEtag()) - req.SetMessage(message) - res, err := client.PublishPolicyChange(ctx, req) - if err != nil { - return nil, mapChangeError("publish", id, err) - } - return res.GetRevision(), nil -} - -// reportPublish tells the admin when the new revision applies and how to -// find the endpoints that lag. -func reportPublish(revision uint64) { - tui.Success("revision %d published", revision) - tui.Info(" Projects resolve it at their next check. Endpoints apply it after their next policy fetch") - tui.Info(" Endpoints that have not applied it yet: safedep endpoint list --applied-revision '<%d'", revision) -} diff --git a/internal/cmd/policy/change_preview.go b/internal/cmd/policy/change_preview.go new file mode 100644 index 0000000..40de860 --- /dev/null +++ b/internal/cmd/policy/change_preview.go @@ -0,0 +1,143 @@ +package policy + +import ( + "fmt" + "strings" + + recordv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/record/v1" + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + + "github.com/safedep/cli/internal/cloudpolicy" + "github.com/safedep/cli/internal/tui" +) + +// This file turns a PreviewPolicyChangeResponse into the view that +// `change show` and `change publish` print. + +// changeItem is one row of "What changes": a field, a policy override or a +// package rule operation. +type changeItem struct { + Where string `json:"where"` + What string `json:"what"` + Old string `json:"old,omitempty"` + New string `json:"new,omitempty"` + Direction string `json:"direction"` + oldHuman string + newHuman string +} + +type coverageView struct { + Path string `json:"path"` + Value string `json:"value,omitempty"` + Enforce uint32 `json:"enforce"` + Partial uint32 `json:"partial"` + Detect uint32 `json:"detect"` + Unsupported uint32 `json:"unsupported"` +} + +type warningView struct { + Code string `json:"code"` + Subject string `json:"subject,omitempty"` + Message string `json:"message"` +} + +type previewView struct { + HeadRevision uint64 `json:"head_revision"` + Stale bool `json:"stale"` + Direction string `json:"direction"` + Items []changeItem `json:"changes"` + MatchedProjects uint32 `json:"matched_project_count"` + MatchedEndpoints uint32 `json:"matched_endpoint_count"` + Coverage []coverageView `json:"coverage"` + Warnings []warningView `json:"warnings"` +} + +func newPreviewView(res *policyv1.PreviewPolicyChangeResponse) *previewView { + v := &previewView{ + HeadRevision: res.GetHeadRevision(), + Stale: res.GetStale(), + Direction: directionToken(res.GetDirection()), + MatchedProjects: res.GetMatchedProjectCount(), + MatchedEndpoints: res.GetMatchedEndpointCount(), + Items: []changeItem{}, + Coverage: []coverageView{}, + Warnings: []warningView{}, + } + for _, c := range res.GetChanges() { + where := "base" + if c.GetLayer() == recordv1.Layer_LAYER_OVERRIDE { + where = fmt.Sprintf("override %q", c.GetOverrideName()) + } + oldValue, oldHuman := cloudpolicy.FormatJSONValue(c.GetPath(), c.GetOldValue()) + newValue, newHuman := cloudpolicy.FormatJSONValue(c.GetPath(), c.GetNewValue()) + v.Items = append(v.Items, changeItem{ + Where: where, What: c.GetPath(), Old: oldValue, New: newValue, + Direction: directionToken(c.GetDirection()), oldHuman: oldHuman, newHuman: newHuman, + }) + } + for _, c := range res.GetOverrideChanges() { + v.Items = append(v.Items, changeItem{ + Where: fmt.Sprintf("override %q", c.GetOverrideName()), + What: tui.EnumToken(c.GetKind().String(), overrideKindPrefix), + Old: c.GetOldValue(), + New: c.GetNewValue(), + Direction: directionToken(c.GetDirection()), + oldHuman: cloudpolicy.EmptyDash(c.GetOldValue()), + newHuman: cloudpolicy.EmptyDash(c.GetNewValue()), + }) + } + for _, op := range res.GetPackageRuleOperations() { + item := ruleOperationItem(op.GetOperation()) + item.Direction = directionToken(op.GetDirection()) + if op.GetOperation().HasCreate() { + item.New = fmt.Sprintf("matches %d packages, seen on %d endpoints in 30d", + op.GetMatchedPackageCount(), op.GetMatchedEndpointCount()) + item.newHuman = item.New + } + v.Items = append(v.Items, item) + } + for _, c := range res.GetCoverage() { + value, _ := cloudpolicy.FormatJSONValue(c.GetPath(), c.GetValue()) + if c.GetValue() == "" { + value = "" + } + v.Coverage = append(v.Coverage, coverageView{ + Path: c.GetPath(), Value: value, Enforce: c.GetEnforceCount(), Partial: c.GetPartialCount(), + Detect: c.GetDetectCount(), Unsupported: c.GetUnsupportedCount(), + }) + } + for _, w := range res.GetWarnings() { + v.Warnings = append(v.Warnings, warningView{ + Code: strings.TrimPrefix(w.GetCode().String(), warningCodePrefix), + Subject: w.GetSubject(), + Message: w.GetMessage(), + }) + } + return v +} + +func ruleOperationItems(ops []*policyv1.PackageRuleOperation) []changeItem { + out := make([]changeItem, 0, len(ops)) + for _, op := range ops { + out = append(out, ruleOperationItem(op)) + } + return out +} + +func ruleOperationItem(op *policyv1.PackageRuleOperation) changeItem { + item := changeItem{Where: "package rules", oldHuman: "-", newHuman: "-"} + switch { + case op.HasCreate(): + rule := op.GetCreate().GetRule() + item.What = fmt.Sprintf("create %s %s", + tui.EnumToken(rule.GetEffect().String(), effectPrefix), selectorText(rule.GetSelector())) + if id := op.GetCreate().GetOverrideId(); id != "" { + item.Where = "package rules of override " + id + } + case op.HasUpdate(): + item.What = "update " + op.GetUpdate().GetRuleId() + case op.HasDelete(): + item.What = "delete " + op.GetDelete().GetRuleId() + } + return item +} diff --git a/internal/cmd/policy/change_publish.go b/internal/cmd/policy/change_publish.go new file mode 100644 index 0000000..0d29c63 --- /dev/null +++ b/internal/cmd/policy/change_publish.go @@ -0,0 +1,163 @@ +package policy + +import ( + "context" + "errors" + "fmt" + + policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/safedep/dry/tui" + "github.com/safedep/dry/tui/prompt" + "github.com/safedep/dry/usefulerror" + "github.com/spf13/cobra" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" + clitui "github.com/safedep/cli/internal/tui" +) + +const directionLoosens = "LOOSENS" + +// confirmFunc asks the user to confirm an action and returns the answer. +type confirmFunc func(question string) (bool, error) + +// errPublishCancelled stops a publish that the user did not confirm. +var errPublishCancelled = errors.New("publish cancelled") + +func changePublishCmd(a *app.App) *cobra.Command { + var ( + message string + yes bool + ) + cmd := &cobra.Command{ + Use: "publish CHANGE", + Short: "Publish an open policy change as a new policy revision", + Long: "Publish an open policy change. The command previews the change first and shows its change " + + "direction and every warning. A change that loosens the policy needs a confirmation: the " + + "command asks in a terminal, and needs --yes when no terminal is present. The publish makes a " + + "new policy revision for the whole tenant. Projects resolve it at their next check, and " + + "endpoints apply it after their next policy fetch. If a part that the change edits moved " + + "since its base revision, the publish stops. Then sync the change and review it again.", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + client, err := a.ControlPlane() + if err != nil { + return err + } + rev, err := runChangePublish(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), + args[0], message, publishConfirm(yes, clitui.IsInteractive())) + if errors.Is(err, errPublishCancelled) { + tui.Info("Nothing is published") + return nil + } + if err != nil { + return err + } + reportPublish(rev.GetRevision(), directionToken(rev.GetDirection())) + return nil + }, + } + cmd.Flags().StringVarP(&message, "message", "m", "", "the publish message; the change title becomes the title when it is empty") + cmd.Flags().BoolVarP(&yes, "yes", "y", false, "publish a change that loosens the policy with no prompt") + return cmd +} + +// publishConfirm asks in a terminal. With no terminal it needs --yes, so a +// script never loosens the policy by accident. +func publishConfirm(yes, interactive bool) confirmFunc { + return func(question string) (bool, error) { + if yes { + return true, nil + } + if !interactive { + cause := errors.New("the change loosens the policy, and no terminal is present to confirm it") + return false, newPolicyError(usefulerror.ErrBadRequest, cause.Error(), + "Review it with safedep policy change show, then pass --yes to publish it", cause) + } + return prompt.Confirm(question, false) + } +} + +func runChangePublish( + ctx context.Context, + client policyv1grpc.PolicyServiceClient, + id, message string, + confirm confirmFunc, +) (*policyv1.PolicyRevision, error) { + change, err := getChange(ctx, client, id) + if err != nil { + return nil, err + } + if err := requireOpen(change); err != nil { + return nil, err + } + preview, err := previewChange(ctx, client, id) + if err != nil { + return nil, err + } + reportPreview(id, preview) + if preview.Stale { + cause := fmt.Errorf("policy change publish: change %s is stale at head revision %d", id, preview.HeadRevision) + return nil, newPolicyError(usefulerror.ErrConflict, + fmt.Sprintf("The policy moved: a part that change %s edits changed after its base revision", id), + fmt.Sprintf("Sync it and review it again: safedep policy change sync %s", id), + cause) + } + if preview.Direction == directionLoosens { + ok, err := confirm(fmt.Sprintf("Change %s loosens the policy. Publish it?", clitui.EscapeLine(id))) + if err != nil { + return nil, err + } + if !ok { + return nil, errPublishCancelled + } + } + + req := &policyv1.PublishPolicyChangeRequest{} + req.SetChangeId(id) + req.SetEtag(change.GetEtag()) + req.SetMessage(message) + res, err := client.PublishPolicyChange(ctx, req) + if err != nil { + return nil, mapChangeError("publish", id, err) + } + return res.GetRevision(), nil +} + +// reportPreview shows the change direction, each part that loosens the +// policy, and every warning of the preview, before the admin decides. +func reportPreview(id string, p *previewView) { + tui.Info("Change %s%s%s", clitui.EscapeLine(id), sep, directionLine(p.Direction)) + reportLoosening(p) + for _, w := range p.Warnings { + subject := "" + if w.Subject != "" { + subject = " " + clitui.EscapeLine(w.Subject) + } + tui.Warning("%s%s: %s", clitui.EscapeLine(w.Code), subject, clitui.EscapeLine(w.Message)) + } + if p.Stale { + tui.Warning("Change %s is stale: the policy moved after its base revision. Sync it: safedep policy change sync %s", + clitui.EscapeLine(id), clitui.EscapeLine(id)) + } +} + +// reportLoosening names each part of a change that loosens the policy. +func reportLoosening(p *previewView) { + for _, item := range p.Items { + if item.Direction != directionLoosens { + continue + } + tui.Warning("It loosens %s (%s -> %s) in %s", clitui.EscapeLine(item.What), + clitui.EscapeLine(item.oldHuman), clitui.EscapeLine(item.newHuman), clitui.EscapeLine(item.Where)) + } +} + +// reportPublish tells the admin the new revision, its change direction, when +// it applies, and how to find the endpoints that lag. +func reportPublish(revision uint64, direction string) { + tui.Success("revision %d published%s%s", revision, sep, direction) + tui.Info(" Projects resolve it at their next check. Endpoints apply it after their next policy fetch") + tui.Info(" Endpoints that have not applied it yet: safedep endpoint list --applied-revision '<%d'", revision) +} diff --git a/internal/cmd/policy/change_render.go b/internal/cmd/policy/change_render.go new file mode 100644 index 0000000..c05131b --- /dev/null +++ b/internal/cmd/policy/change_render.go @@ -0,0 +1,79 @@ +package policy + +import ( + "fmt" + "strings" + + "github.com/safedep/dry/tui/table" + + "github.com/safedep/cli/internal/cloudpolicy" + "github.com/safedep/cli/internal/tui" +) + +func (r *changeShowResult) impactTable(p *previewView) string { + rows := make([][]string, 0, len(p.Coverage)) + for _, c := range p.Coverage { + what := c.Path + if c.Value != "" { + what += " = " + c.Value + } + rows = append(rows, []string{what, fmt.Sprint(c.Enforce), fmt.Sprint(c.Partial), fmt.Sprint(c.Detect), fmt.Sprint(c.Unsupported)}) + } + return table.New(). + Title(fmt.Sprintf("Impact%ssubjects matched: %d %s, %d %s", sep, + p.MatchedProjects, cloudpolicy.Plural(int(p.MatchedProjects), "project", "projects"), + p.MatchedEndpoints, cloudpolicy.Plural(int(p.MatchedEndpoints), "endpoint", "endpoints"))). + Headers("FIELD", "ENFORCED", "PARTIAL", "DETECT ONLY", "NOT SUPPORTED"). + Rows(tui.EscapeCells(rows)...). + EmptyMessage("No coverage data for the changed fields."). + Render() +} + +func (r *changeShowResult) warningTable(p *previewView) string { + rows := make([][]string, 0, len(p.Warnings)) + for _, w := range p.Warnings { + rows = append(rows, []string{w.Code, cloudpolicy.EmptyDash(w.Subject), w.Message}) + } + return table.New(). + Title("Warnings"). + Headers("CODE", "SUBJECT", "MESSAGE"). + Rows(tui.EscapeCells(rows)...). + EmptyMessage("No warnings."). + Render() +} + +func directionLine(direction string) string { + switch direction { + case "LOOSENS": + return "LOOSENS. Only an Admin can publish it, and Admins and Owners get a notice" + case "TIGHTENS": + return "TIGHTENS. An Admin can publish it" + default: + return direction + } +} + +func (r *changeShowResult) RenderPlain() string { + var b strings.Builder + c := r.Change + b.WriteString(strings.Join([]string{ + tui.PlainRow("change_id", c.ID), + tui.PlainRow("title", c.Title), + tui.PlainRow("state", c.State), + tui.PlainRow("base_revision", fmt.Sprint(c.BaseRevision)), + }, "\n")) + items := r.ruleOnly + if p := r.Preview; p != nil { + fmt.Fprintf(&b, "\nhead_revision\t%d\nstale\t%t\ndirection\t%s", p.HeadRevision, p.Stale, p.Direction) + items = p.Items + } + for _, it := range items { + b.WriteString("\n" + tui.PlainRow("change", it.Where, it.What, it.Old, it.New, it.Direction)) + } + if p := r.Preview; p != nil { + for _, w := range p.Warnings { + b.WriteString("\n" + tui.PlainRow("warning", w.Code, w.Subject, w.Message)) + } + } + return b.String() +} diff --git a/internal/cmd/policy/change_show.go b/internal/cmd/policy/change_show.go index 8076f11..59714d8 100644 --- a/internal/cmd/policy/change_show.go +++ b/internal/cmd/policy/change_show.go @@ -8,7 +8,6 @@ import ( "time" policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" - recordv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/record/v1" policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" "github.com/safedep/dry/tui/table" "github.com/spf13/cobra" @@ -23,44 +22,6 @@ const ( warningCodePrefix = "PREVIEW_WARNING_CODE_" ) -// changeItem is one row of "What changes": a field, a policy override or a -// package rule operation. -type changeItem struct { - Where string `json:"where"` - What string `json:"what"` - Old string `json:"old,omitempty"` - New string `json:"new,omitempty"` - Direction string `json:"direction"` - oldHuman string - newHuman string -} - -type coverageView struct { - Path string `json:"path"` - Value string `json:"value,omitempty"` - Enforce uint32 `json:"enforce"` - Partial uint32 `json:"partial"` - Detect uint32 `json:"detect"` - Unsupported uint32 `json:"unsupported"` -} - -type warningView struct { - Code string `json:"code"` - Subject string `json:"subject,omitempty"` - Message string `json:"message"` -} - -type previewView struct { - HeadRevision uint64 `json:"head_revision"` - Stale bool `json:"stale"` - Direction string `json:"direction"` - Items []changeItem `json:"changes"` - MatchedProjects uint32 `json:"matched_project_count"` - MatchedEndpoints uint32 `json:"matched_endpoint_count"` - Coverage []coverageView `json:"coverage"` - Warnings []warningView `json:"warnings"` -} - type changeShowResult struct { Change changeView `json:"change"` Restore string `json:"restore,omitempty"` @@ -143,96 +104,6 @@ func restoreSummary(r *policyv1.RestoreSource) string { return fmt.Sprintf("restores %s from revision %d%s%s", capabilities, r.GetFromRevision(), sep, rules) } -func newPreviewView(res *policyv1.PreviewPolicyChangeResponse) *previewView { - v := &previewView{ - HeadRevision: res.GetHeadRevision(), - Stale: res.GetStale(), - Direction: directionToken(res.GetDirection()), - MatchedProjects: res.GetMatchedProjectCount(), - MatchedEndpoints: res.GetMatchedEndpointCount(), - Items: []changeItem{}, - Coverage: []coverageView{}, - Warnings: []warningView{}, - } - for _, c := range res.GetChanges() { - where := "base" - if c.GetLayer() == recordv1.Layer_LAYER_OVERRIDE { - where = fmt.Sprintf("override %q", c.GetOverrideName()) - } - oldValue, oldHuman := cloudpolicy.FormatJSONValue(c.GetPath(), c.GetOldValue()) - newValue, newHuman := cloudpolicy.FormatJSONValue(c.GetPath(), c.GetNewValue()) - v.Items = append(v.Items, changeItem{ - Where: where, What: c.GetPath(), Old: oldValue, New: newValue, - Direction: directionToken(c.GetDirection()), oldHuman: oldHuman, newHuman: newHuman, - }) - } - for _, c := range res.GetOverrideChanges() { - v.Items = append(v.Items, changeItem{ - Where: fmt.Sprintf("override %q", c.GetOverrideName()), - What: tui.EnumToken(c.GetKind().String(), overrideKindPrefix), - Old: c.GetOldValue(), - New: c.GetNewValue(), - Direction: directionToken(c.GetDirection()), - oldHuman: emptyDash(c.GetOldValue()), - newHuman: emptyDash(c.GetNewValue()), - }) - } - for _, op := range res.GetPackageRuleOperations() { - item := ruleOperationItem(op.GetOperation()) - item.Direction = directionToken(op.GetDirection()) - if op.GetOperation().HasCreate() { - item.New = fmt.Sprintf("matches %d packages, seen on %d endpoints in 30d", - op.GetMatchedPackageCount(), op.GetMatchedEndpointCount()) - item.newHuman = item.New - } - v.Items = append(v.Items, item) - } - for _, c := range res.GetCoverage() { - value, _ := cloudpolicy.FormatJSONValue(c.GetPath(), c.GetValue()) - if c.GetValue() == "" { - value = "" - } - v.Coverage = append(v.Coverage, coverageView{ - Path: c.GetPath(), Value: value, Enforce: c.GetEnforceCount(), Partial: c.GetPartialCount(), - Detect: c.GetDetectCount(), Unsupported: c.GetUnsupportedCount(), - }) - } - for _, w := range res.GetWarnings() { - v.Warnings = append(v.Warnings, warningView{ - Code: strings.TrimPrefix(w.GetCode().String(), warningCodePrefix), - Subject: w.GetSubject(), - Message: w.GetMessage(), - }) - } - return v -} - -func ruleOperationItems(ops []*policyv1.PackageRuleOperation) []changeItem { - out := make([]changeItem, 0, len(ops)) - for _, op := range ops { - out = append(out, ruleOperationItem(op)) - } - return out -} - -func ruleOperationItem(op *policyv1.PackageRuleOperation) changeItem { - item := changeItem{Where: "package rules", oldHuman: "-", newHuman: "-"} - switch { - case op.HasCreate(): - rule := op.GetCreate().GetRule() - item.What = fmt.Sprintf("create %s %s", - tui.EnumToken(rule.GetEffect().String(), effectPrefix), selectorText(rule.GetSelector())) - if id := op.GetCreate().GetOverrideId(); id != "" { - item.Where = "package rules of override " + id - } - case op.HasUpdate(): - item.What = "update " + op.GetUpdate().GetRuleId() - case op.HasDelete(): - item.What = "delete " + op.GetDelete().GetRuleId() - } - return item -} - func (r *changeShowResult) RenderJSON() ([]byte, error) { type out struct { *changeShowResult @@ -243,7 +114,10 @@ func (r *changeShowResult) RenderJSON() ([]byte, error) { func (r *changeShowResult) headline() string { c := r.Change - parts := []string{fmt.Sprintf("Change %s %q", c.ID, c.titleOrUntitled()), c.State, fmt.Sprintf("base rev %d", c.BaseRevision)} + parts := []string{ + fmt.Sprintf("Change %s \"%s\"", tui.EscapeLine(c.ID), tui.EscapeLine(c.titleOrUntitled())), + c.State, fmt.Sprintf("base rev %d", c.BaseRevision), + } if c.PublishedRevision > 0 { parts = append(parts, fmt.Sprintf("published as rev %d", c.PublishedRevision)) } @@ -261,7 +135,7 @@ func (r *changeShowResult) headline() string { func (r *changeShowResult) RenderTable() string { now := time.Now() sections := []string{r.headline()} - details := [][2]string{{"Author", emptyDash(r.Change.Author)}, {"Updated", humanTimeCell(r.Change.updatedAt, now)}} + details := [][2]string{{"Author", cloudpolicy.EmptyDash(r.Change.Author)}, {"Updated", humanTimeCell(r.Change.updatedAt, now)}} if r.Restore != "" { details = append(details, [2]string{"Restore", r.Restore}) } @@ -273,12 +147,12 @@ func (r *changeShowResult) RenderTable() string { } rows := make([][]string, 0, len(items)) for _, it := range items { - rows = append(rows, []string{it.Where, it.What, it.oldHuman + " -> " + it.newHuman, emptyDash(it.Direction)}) + rows = append(rows, []string{it.Where, it.What, it.oldHuman + " -> " + it.newHuman, cloudpolicy.EmptyDash(it.Direction)}) } sections = append(sections, table.New(). Title("What changes"). Headers("WHERE", "WHAT", "OLD -> NEW", "DIRECTION"). - Rows(rows...). + Rows(tui.EscapeCells(rows)...). EmptyMessage("The change edits nothing."). Render()) @@ -288,66 +162,3 @@ func (r *changeShowResult) RenderTable() string { } return strings.Join(sections, "\n\n") } - -func (r *changeShowResult) impactTable(p *previewView) string { - rows := make([][]string, 0, len(p.Coverage)) - for _, c := range p.Coverage { - what := c.Path - if c.Value != "" { - what += " = " + c.Value - } - rows = append(rows, []string{what, fmt.Sprint(c.Enforce), fmt.Sprint(c.Partial), fmt.Sprint(c.Detect), fmt.Sprint(c.Unsupported)}) - } - return table.New(). - Title(fmt.Sprintf("Impact%ssubjects matched: %d %s, %d %s", sep, - p.MatchedProjects, plural(int(p.MatchedProjects), "project", "projects"), - p.MatchedEndpoints, plural(int(p.MatchedEndpoints), "endpoint", "endpoints"))). - Headers("FIELD", "ENFORCED", "PARTIAL", "DETECT ONLY", "NOT SUPPORTED"). - Rows(rows...). - EmptyMessage("No coverage data for the changed fields."). - Render() -} - -func (r *changeShowResult) warningTable(p *previewView) string { - rows := make([][]string, 0, len(p.Warnings)) - for _, w := range p.Warnings { - rows = append(rows, []string{w.Code, emptyDash(w.Subject), w.Message}) - } - return table.New(). - Title("Warnings"). - Headers("CODE", "SUBJECT", "MESSAGE"). - Rows(rows...). - EmptyMessage("No warnings."). - Render() -} - -func directionLine(direction string) string { - switch direction { - case "LOOSENS": - return "LOOSENS. Only an Admin can publish it, and Admins and Owners get a notice" - case "TIGHTENS": - return "TIGHTENS. An Admin can publish it" - default: - return direction - } -} - -func (r *changeShowResult) RenderPlain() string { - var b strings.Builder - c := r.Change - fmt.Fprintf(&b, "change_id\t%s\ntitle\t%s\nstate\t%s\nbase_revision\t%d", c.ID, c.Title, c.State, c.BaseRevision) - items := r.ruleOnly - if p := r.Preview; p != nil { - fmt.Fprintf(&b, "\nhead_revision\t%d\nstale\t%t\ndirection\t%s", p.HeadRevision, p.Stale, p.Direction) - items = p.Items - } - for _, it := range items { - fmt.Fprintf(&b, "\nchange\t%s\t%s\t%s\t%s\t%s", it.Where, it.What, it.Old, it.New, it.Direction) - } - if p := r.Preview; p != nil { - for _, w := range p.Warnings { - fmt.Fprintf(&b, "\nwarning\t%s\t%s\t%s", w.Code, w.Subject, w.Message) - } - } - return b.String() -} diff --git a/internal/cmd/policy/change_test.go b/internal/cmd/policy/change_test.go index 3e63f3b..839fe3c 100644 --- a/internal/cmd/policy/change_test.go +++ b/internal/cmd/policy/change_test.go @@ -120,7 +120,10 @@ func TestRunChangeShow_PreviewsAnOpenChange(t *testing.T) { b, err := got.RenderJSON() require.NoError(t, err) assert.Contains(t, string(b), `"direction": "LOOSENS"`) - assert.Contains(t, got.RenderPlain(), "change\toverride \"payments\"\tscan_gate.fail_on\thigh\tmedium\tTIGHTENS") + plain := got.RenderPlain() + assert.Contains(t, plain, "change_id\t18\ntitle\tpayments: medium + cooldown\nstate\topen\nbase_revision\t46") + assert.Contains(t, plain, "change\toverride \"payments\"\tscan_gate.fail_on\thigh\tmedium\tTIGHTENS") + assert.Contains(t, plain, "warning\tLOW_ENFORCED_COVERAGE\tscan_gate.fail_on\t1 of 3 projects cannot enforce \"medium\" yet") } func TestRunChangeShow_StaleChange(t *testing.T) { @@ -155,20 +158,6 @@ func TestRunChangeShow_PublishedChangeHasNoPreview(t *testing.T) { assert.Contains(t, got.RenderTable(), "published as rev 47") } -func TestRunChangePublish(t *testing.T) { - client := mocks.NewPolicyServiceClientMock(t) - client.EXPECT().GetPolicyChange(mock.Anything, mock.Anything).Return(changeResponse(openChange("18")), nil) - res := &policyv1.PublishPolicyChangeResponse{} - res.SetRevision(revision(47, "payments")) - client.EXPECT().PublishPolicyChange(mock.Anything, mock.MatchedBy(func(r *policyv1.PublishPolicyChangeRequest) bool { - return r.GetChangeId() == "18" && r.GetEtag() == "etag-1" && r.GetMessage() == "payments: fail on medium" - })).Return(res, nil) - - rev, err := runChangePublish(context.Background(), client, "18", "payments: fail on medium") - require.NoError(t, err) - assert.Equal(t, uint64(47), rev.GetRevision()) -} - func TestRunChangePublish_Errors(t *testing.T) { tests := []struct { name string @@ -197,11 +186,13 @@ func TestRunChangePublish_Errors(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + captureStderr(t) client := mocks.NewPolicyServiceClientMock(t) client.EXPECT().GetPolicyChange(mock.Anything, mock.Anything).Return(changeResponse(openChange("19")), nil) + client.EXPECT().PreviewPolicyChange(mock.Anything, mock.Anything).Return(tighteningPreview(), nil) client.EXPECT().PublishPolicyChange(mock.Anything, mock.Anything).Return(nil, tt.err) - _, err := runChangePublish(context.Background(), client, "19", "") + _, err := runChangePublish(context.Background(), client, "19", "", refuseConfirm(t)) require.Error(t, err) ue, ok := usefulerror.AsUsefulError(err) require.True(t, ok) @@ -217,7 +208,7 @@ func TestRunChangePublish_OnlyAnOpenChange(t *testing.T) { c.SetState(policyv1.PolicyChangeState_POLICY_CHANGE_STATE_DELETED) client.EXPECT().GetPolicyChange(mock.Anything, mock.Anything).Return(changeResponse(c), nil) - _, err := runChangePublish(context.Background(), client, "17", "") + _, err := runChangePublish(context.Background(), client, "17", "", refuseConfirm(t)) assert.ErrorContains(t, err, "change 17 is deleted: only an open change can change") } @@ -267,7 +258,7 @@ func TestRunChangeEdit_UpdatesWithTheEtag(t *testing.T) { r.GetSettings().GetOverrides()[0].GetDescription() == "why" })).Return(res, nil) - ed := &scriptedEditor{edits: []func(string) string{replace(" - name: payments\n", " - name: payments\n description: why\n")}} + ed := &scriptedEditor{edits: []func(string) string{replace(" name: payments\n", " name: payments\n description: why\n")}} _, err := runChangeEdit(context.Background(), client, ed.open, "", "18", editInput{Title: "new title"}) require.NoError(t, err) assert.Contains(t, ed.seen[0], "# Change 18 of this tenant · base revision 46 · head revision 46") diff --git a/internal/cmd/policy/change_view.go b/internal/cmd/policy/change_view.go new file mode 100644 index 0000000..4834d26 --- /dev/null +++ b/internal/cmd/policy/change_view.go @@ -0,0 +1,73 @@ +package policy + +import ( + "fmt" + "strings" + "time" + + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + + "github.com/safedep/cli/internal/cloudpolicy" + "github.com/safedep/cli/internal/tui" +) + +type changeView struct { + ID string `json:"change_id"` + Title string `json:"title"` + State string `json:"state"` + BaseRevision uint64 `json:"base_revision"` + PublishedRevision uint64 `json:"published_revision,omitempty"` + Author string `json:"author"` + EditsSettings bool `json:"edits_settings"` + RuleOperations int `json:"package_rule_operations"` + RestoreFrom uint64 `json:"restore_from_revision,omitempty"` + Created string `json:"created_at,omitempty"` + Updated string `json:"updated_at,omitempty"` + updatedAt *time.Time +} + +func newChangeView(c *policyv1.PolicyChange) changeView { + updated := cloudpolicy.TimeOf(c.GetUpdatedAt()) + v := changeView{ + ID: c.GetChangeId(), + Title: c.GetTitle(), + State: tui.EnumToken(c.GetState().String(), changeStatePrefix), + BaseRevision: c.GetBaseRevision(), + PublishedRevision: c.GetPublishedRevision(), + Author: cloudpolicy.ActorName(c.GetAuthor()), + EditsSettings: c.HasSettings(), + RuleOperations: len(c.GetPackageRuleOperations()), + Created: cloudpolicy.RFC3339(cloudpolicy.TimeOf(c.GetCreatedAt())), + Updated: cloudpolicy.RFC3339(updated), + updatedAt: updated, + } + if c.HasRestore() { + v.RestoreFrom = c.GetRestore().GetFromRevision() + } + return v +} + +func (v changeView) titleOrUntitled() string { + if v.Title == "" { + return "(untitled)" + } + return v.Title +} + +// contents says what the change edits, as in "settings, 2 rule operations". +func (v changeView) contents() string { + var parts []string + if v.RestoreFrom > 0 { + parts = append(parts, fmt.Sprintf("restore from revision %d", v.RestoreFrom)) + } + if v.EditsSettings { + parts = append(parts, "settings") + } + if v.RuleOperations > 0 { + parts = append(parts, fmt.Sprintf("%d rule %s", v.RuleOperations, cloudpolicy.Plural(v.RuleOperations, "operation", "operations"))) + } + if len(parts) == 0 { + return "nothing" + } + return strings.Join(parts, ", ") +} diff --git a/internal/cmd/policy/edit.go b/internal/cmd/policy/edit.go index 4fd9113..002fd6e 100644 --- a/internal/cmd/policy/edit.go +++ b/internal/cmd/policy/edit.go @@ -11,7 +11,6 @@ import ( "github.com/safedep/dry/tui" "github.com/safedep/dry/usefulerror" "github.com/spf13/cobra" - "google.golang.org/protobuf/proto" "github.com/safedep/cli/internal/app" "github.com/safedep/cli/internal/cloudpolicy" @@ -51,8 +50,9 @@ func editCmd(a *app.App) *cobra.Command { if err != nil { return err } - tui.Success("change %s saved from revision %d", change.GetChangeId(), change.GetBaseRevision()) - tui.Info(" Review it: safedep policy change show %s", change.GetChangeId()) + id := clitui.EscapeLine(change.GetChangeId()) + tui.Success("change %s saved from revision %d", id, change.GetBaseRevision()) + tui.Info(" Review it: safedep policy change show %s", id) return nil }, } @@ -99,7 +99,7 @@ func runEdit( req.SetBaseRevision(head.GetHeadRevision()) res, err := client.CreatePolicyChange(ctx, req) if err != nil { - return fmt.Errorf("policy change create: %w", err) + return mapChangeError("create", "", err) } change = res.GetChange() return nil @@ -141,111 +141,10 @@ func editHeader(intro []string, head *policyv1.GetPolicyResponse) string { " 3. overrides - apply to the subjects that their selector matches.", " For each field, the highest priority that sets it wins.", "", - fmt.Sprintf("Package rules are not in this file: %d %s (safedep policy rule list)", rules, plural(int(rules), "rule", "rules")), + "Keep the id of each override. A new override has no id.", + fmt.Sprintf("Package rules are not in this file: %d %s (safedep policy rule list)", + rules, cloudpolicy.Plural(int(rules), "rule", "rules")), "The policy keeps no comments. Write the reason for a value in a description field.", ) return cloudpolicy.CommentBlock(lines) } - -// editSettings opens the settings, or one policy override of them, in the -// editor and gives the whole edited document to commit. -func editSettings( - ctx context.Context, - open openEditorFunc, - start *policyv1.Policy, - header string, - overrideName string, - commit func(*policyv1.Policy) error, -) error { - if start == nil { - start = &policyv1.Policy{} - } - if overrideName == "" { - text, err := cloudpolicy.MarshalPolicy(start, header) - if err != nil { - return err - } - return editLoop(ctx, open, text, func(saved []byte) error { - edited, err := cloudpolicy.UnmarshalPolicy(saved) - if err != nil { - return retryable(err) - } - cloudpolicy.RestoreOverrideIDs(edited, start) - if err := validateSettings(edited); err != nil { - return retryable(err) - } - warnComments(saved, header) - return commit(edited) - }) - } - - current, err := findOverride(start, overrideName) - if err != nil { - return err - } - text, err := cloudpolicy.MarshalOverride(current, header) - if err != nil { - return err - } - return editLoop(ctx, open, text, func(saved []byte) error { - edited, err := cloudpolicy.UnmarshalOverride(saved) - if err != nil { - return retryable(err) - } - if edited.GetOverrideId() == "" { - edited.SetOverrideId(current.GetOverrideId()) - } - full, ok := proto.Clone(start).(*policyv1.Policy) - if !ok { - return errors.New("policy edit: clone the policy") - } - overrides := full.GetOverrides() - for i, o := range overrides { - if o.GetOverrideId() == current.GetOverrideId() { - overrides[i] = edited - } - } - full.SetOverrides(overrides) - if err := validateSettings(full); err != nil { - return retryable(err) - } - warnComments(saved, header) - return commit(full) - }) -} - -// validateSettings checks the rules that a person breaks most often in an -// edit, so the editor shows them before the RPC. The server checks every -// rule. -func validateSettings(p *policyv1.Policy) error { - names := map[string]struct{}{} - priorities := map[uint32]string{} - for i, o := range p.GetOverrides() { - if o.GetName() == "" { - return fmt.Errorf("overrides[%d]: give the override a name", i) - } - if _, dup := names[o.GetName()]; dup { - return fmt.Errorf("overrides[%d]: two overrides are named %q. Each name must be unique", i, o.GetName()) - } - names[o.GetName()] = struct{}{} - if o.GetPriority() == 0 { - return fmt.Errorf("override %q: give it a priority from 1 to 1000000", o.GetName()) - } - if other, dup := priorities[o.GetPriority()]; dup { - return fmt.Errorf("override %q: priority %d is also the priority of %q. Each priority must be unique", - o.GetName(), o.GetPriority(), other) - } - priorities[o.GetPriority()] = o.GetName() - if !o.HasSelector() { - return fmt.Errorf("override %q: give it a selector. Write selector: {} to select every subject", o.GetName()) - } - } - return nil -} - -func warnComments(saved []byte, header string) { - if cloudpolicy.HasUserComments(saved, header) { - tui.Warning("The file holds comments. The policy keeps no comments, so they are lost. " + - "Write the reason in a description field") - } -} diff --git a/internal/cmd/policy/edit_test.go b/internal/cmd/policy/edit_test.go index 0566c7c..1ddf8f2 100644 --- a/internal/cmd/policy/edit_test.go +++ b/internal/cmd/policy/edit_test.go @@ -9,12 +9,14 @@ import ( scangatev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/scangate/v1" policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/safedep/dry/usefulerror" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/encoding/protowire" "github.com/safedep/cli/internal/cloudpolicy/mocks" ) @@ -46,9 +48,13 @@ func replace(old, new string) func(string) string { func keep(s string) string { return s } +func sameAs(original string) func([]byte) bool { + return func(saved []byte) bool { return string(saved) == original } +} + func TestEditLoop_NoChange(t *testing.T) { ed := &scriptedEditor{edits: []func(string) string{keep}} - err := editLoop(context.Background(), ed.open, []byte("a: 1\n"), func([]byte) error { + err := editLoop(context.Background(), ed.open, []byte("a: 1\n"), sameAs("a: 1\n"), func([]byte) error { t.Fatal("save must not run") return nil }) @@ -61,7 +67,7 @@ func TestEditLoop_ReopensWithTheErrorAndSaves(t *testing.T) { replace("a: bad", "a: 2"), }} var saved []string - err := editLoop(context.Background(), ed.open, []byte("a: 1\n"), func(text []byte) error { + err := editLoop(context.Background(), ed.open, []byte("a: 1\n"), sameAs("a: 1\n"), func(text []byte) error { saved = append(saved, string(text)) if strings.Contains(string(text), "bad") { return retryable(errors.New("line 1: a: expected a number")) @@ -78,7 +84,7 @@ func TestEditLoop_ReopensWithTheErrorAndSaves(t *testing.T) { func TestEditLoop_ServerRejectionIsRetryable(t *testing.T) { ed := &scriptedEditor{edits: []func(string) string{replace("1", "2"), replace("2", "3")}} calls := 0 - err := editLoop(context.Background(), ed.open, []byte("a: 1\n"), func([]byte) error { + err := editLoop(context.Background(), ed.open, []byte("a: 1\n"), sameAs("a: 1\n"), func([]byte) error { calls++ if calls == 1 { return status.Error(codes.InvalidArgument, "override priorities must be unique") @@ -91,7 +97,7 @@ func TestEditLoop_ServerRejectionIsRetryable(t *testing.T) { func TestEditLoop_StopsWhenTheUserGivesUp(t *testing.T) { ed := &scriptedEditor{edits: []func(string) string{replace("1", "x"), keep}} - err := editLoop(context.Background(), ed.open, []byte("a: 1\n"), func([]byte) error { + err := editLoop(context.Background(), ed.open, []byte("a: 1\n"), sameAs("a: 1\n"), func([]byte) error { return retryable(errors.New("bad")) }) require.Error(t, err) @@ -100,7 +106,7 @@ func TestEditLoop_StopsWhenTheUserGivesUp(t *testing.T) { func TestEditLoop_KeepsTheFileOnAnRPCFailure(t *testing.T) { ed := &scriptedEditor{edits: []func(string) string{replace("1", "2")}} - err := editLoop(context.Background(), ed.open, []byte("a: 1\n"), func([]byte) error { + err := editLoop(context.Background(), ed.open, []byte("a: 1\n"), sameAs("a: 1\n"), func([]byte) error { return status.Error(codes.Unavailable, "down") }) require.Error(t, err) @@ -205,3 +211,123 @@ func TestValidateSettings(t *testing.T) { }) } } + +func TestRunEdit_RenameKeepsTheOverrideID(t *testing.T) { + stderr := captureStderr(t) + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(headResponse(), nil) + var req *policyv1.CreatePolicyChangeRequest + client.EXPECT().CreatePolicyChange(mock.Anything, mock.Anything). + RunAndReturn(func(_ context.Context, r *policyv1.CreatePolicyChangeRequest, _ ...grpc.CallOption) (*policyv1.CreatePolicyChangeResponse, error) { + req = r + res := &policyv1.CreatePolicyChangeResponse{} + res.SetChange(openChange("18")) + return res, nil + }) + + ed := &scriptedEditor{edits: []func(string) string{replace("name: payments", "name: payments-critical")}} + _, err := runEdit(context.Background(), client, ed.open, "", editInput{}) + require.NoError(t, err) + assert.Contains(t, ed.seen[0], " - id: ov_pay\n name: payments\n") + + o := req.GetSettings().GetOverrides()[0] + assert.Equal(t, "payments-critical", o.GetName()) + assert.Equal(t, "ov_pay", o.GetOverrideId(), "a rename keeps the id, so it is not a new override") + assert.NotContains(t, stderr.String(), "This removes") +} + +func TestRunEdit_WarnsAboutARemovedOverride(t *testing.T) { + stderr := captureStderr(t) + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(headResponse(), nil) + var req *policyv1.CreatePolicyChangeRequest + client.EXPECT().CreatePolicyChange(mock.Anything, mock.Anything). + RunAndReturn(func(_ context.Context, r *policyv1.CreatePolicyChangeRequest, _ ...grpc.CallOption) (*policyv1.CreatePolicyChangeResponse, error) { + req = r + res := &policyv1.CreatePolicyChangeResponse{} + res.SetChange(openChange("18")) + return res, nil + }) + + removeCI := func(s string) string { + i := strings.Index(s, " - id: ov_ci") + return s[:i] + } + ed := &scriptedEditor{edits: []func(string) string{removeCI}} + _, err := runEdit(context.Background(), client, ed.open, "", editInput{}) + require.NoError(t, err) + require.Len(t, req.GetSettings().GetOverrides(), 1) + assert.Contains(t, stderr.String(), `This removes policy override "ci" (id ov_ci)`) +} + +func TestRunEdit_RefusesAnIDThatIsNotInThePolicy(t *testing.T) { + captureStderr(t) + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(headResponse(), nil) + ed := &scriptedEditor{edits: []func(string) string{replace("id: ov_ci", "id: ov_other"), keep}} + _, err := runEdit(context.Background(), client, ed.open, "", editInput{}) + require.Error(t, err) + assert.Contains(t, ed.seen[1], `id "ov_other" is not in the policy`) +} + +func TestRunEdit_RefusesFieldsThatThisCLIDoesNotKnow(t *testing.T) { + head := headResponse() + unknown := protowire.AppendTag(nil, 99, protowire.VarintType) + unknown = protowire.AppendVarint(unknown, 1) + head.GetPolicy().GetBase().GetScanGate().ProtoReflect().SetUnknown(unknown) + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(head, nil) + + _, err := runEdit(context.Background(), client, (&scriptedEditor{}).open, "", editInput{}) + require.Error(t, err) + ue, ok := usefulerror.AsUsefulError(err) + require.True(t, ok) + assert.Contains(t, ue.HumanError(), "the policy holds fields that this safedep CLI does not know: at base.scan_gate") + assert.Contains(t, ue.Help(), "Update the safedep CLI") +} + +func TestRunEdit_PermissionDenied(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(headResponse(), nil) + client.EXPECT().CreatePolicyChange(mock.Anything, mock.Anything).Return(nil, status.Error(codes.PermissionDenied, "member")) + + ed := &scriptedEditor{edits: []func(string) string{replace("fail_on: critical", "fail_on: high")}} + _, err := runEdit(context.Background(), client, ed.open, "", editInput{}) + require.Error(t, err) + ue, ok := usefulerror.AsUsefulError(err) + require.True(t, ok) + assert.Equal(t, usefulerror.ErrAuthorizationFailed, ue.Code()) + assert.Contains(t, ue.HumanError(), "Your role cannot change the policy") + assert.Contains(t, ue.Help(), "Ask an Admin of the tenant to do it") + assert.Contains(t, ue.Help(), "Your edit is in") +} + +func TestRunEdit_RewrittenLineEndingsAreNoChange(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(headResponse(), nil) + crlf := func(s string) string { return strings.ReplaceAll(s, "\n", "\r\n") } + _, err := runEdit(context.Background(), client, (&scriptedEditor{edits: []func(string) string{crlf}}).open, "", editInput{}) + assert.ErrorIs(t, err, errNoChange) +} + +func TestRunChangeEdit_RestoreChange(t *testing.T) { + stderr := captureStderr(t) + client := mocks.NewPolicyServiceClientMock(t) + c := openChange("20") + restore := &policyv1.RestoreSource{} + restore.SetFromRevision(46) + c.SetRestore(restore) + client.EXPECT().GetPolicyChange(mock.Anything, mock.Anything).Return(changeResponse(c), nil) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(headResponse(), nil) + res := &policyv1.UpdatePolicyChangeResponse{} + res.SetChange(c) + client.EXPECT().UpdatePolicyChange(mock.Anything, mock.MatchedBy(func(r *policyv1.UpdatePolicyChangeRequest) bool { + return r.HasSettings() && r.GetSettings().GetBase().GetScanGate().GetFailOn() == scangatev1.Severity_SEVERITY_LOW + })).Return(res, nil) + + ed := &scriptedEditor{edits: []func(string) string{replace("base:\n scan_gate:\n fail_on: high", "base:\n scan_gate:\n fail_on: low")}} + _, err := runChangeEdit(context.Background(), client, ed.open, "", "20", editInput{}) + require.NoError(t, err) + assert.Contains(t, stderr.String(), "Change 20 restores from revision 46. Saving replaces the settings that the restore made") + assert.Contains(t, ed.seen[0], "fail_on: high", "a change with no settings starts from head") +} diff --git a/internal/cmd/policy/editor.go b/internal/cmd/policy/editor.go index 01893f6..17ce5f6 100644 --- a/internal/cmd/policy/editor.go +++ b/internal/cmd/policy/editor.go @@ -46,10 +46,18 @@ func isRetryable(err error) bool { } // editLoop writes text to a temporary file, opens the editor on it, and -// gives the saved text to save. When save fails with an error that the user +// gives the saved text to save. unchanged reports whether the saved text +// means the same as text. It compares decoded messages, so an editor that +// only rewrites line endings or spacing makes no change. When save fails with an error that the user // can fix, the loop opens the file again with the error at the top. The file // stays on disk when the edit fails for another reason, so no work is lost. -func editLoop(ctx context.Context, open openEditorFunc, text []byte, save func([]byte) error) error { +func editLoop( + ctx context.Context, + open openEditorFunc, + text []byte, + unchanged func(saved []byte) bool, + save func([]byte) error, +) error { f, err := os.CreateTemp("", "safedep-policy-*.yaml") if err != nil { return fmt.Errorf("policy edit: temporary file: %w", err) @@ -72,10 +80,10 @@ func editLoop(ctx context.Context, open openEditorFunc, text []byte, save func([ return fmt.Errorf("policy edit: read %s: %w", path, err) } saved = stripErrorLines(saved) - if bytes.Equal(saved, stripErrorLines(last)) { - if attempt == 0 { - return errors.Join(errNoChange, os.Remove(path)) - } + if attempt == 0 && unchanged(saved) { + return errors.Join(errNoChange, os.Remove(path)) + } + if attempt > 0 && bytes.Equal(saved, stripErrorLines(last)) { return keptEditError(path, errors.New("the file still has errors")) } @@ -118,10 +126,20 @@ func stripErrorLines(text []byte) []byte { return text } +// keptEditError keeps the code, the message and the help of a useful +// error, such as the one for a role that cannot change the policy, and adds +// the path of the kept file. func keptEditError(path string, cause error) error { + code, human, help := usefulerror.ErrBadRequest, "The policy edit was not saved: "+cause.Error(), "" + if ue, ok := usefulerror.AsUsefulError(cause); ok { + code, human = ue.Code(), "The policy edit was not saved: "+ue.HumanError() + if ue.Help() != "" { + help = ue.Help() + ". " + } + } return usefulerror.NewUsefulError(). - WithCode(usefulerror.ErrBadRequest). - WithHumanError("The policy edit was not saved: " + cause.Error()). - WithHelp("Your edit is in " + path + ". Copy what you need from it, then run the command again"). + WithCode(code). + WithHumanError(human). + WithHelp(help + "Your edit is in " + path + ". Copy what you need from it, then run the command again"). Wrap(cause) } diff --git a/internal/cmd/policy/errors.go b/internal/cmd/policy/errors.go index 76428a6..c1f8c6a 100644 --- a/internal/cmd/policy/errors.go +++ b/internal/cmd/policy/errors.go @@ -7,8 +7,6 @@ import ( "github.com/safedep/dry/usefulerror" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - - "github.com/safedep/cli/internal/rpcerror" ) func newPolicyError(code, humanError, help string, cause error) error { @@ -27,7 +25,7 @@ func invalidInputError(cause error, help string) error { // a stale base, an old etag, or a change that does not exist. func mapChangeError(op, changeID string, err error) error { cause := fmt.Errorf("policy change %s: %w", op, err) - switch rpcerror.Reason(err) { + switch reason, _ := usefulerror.ReasonOf(err); reason { case errorv1.ErrorReason_ERROR_REASON_POLICY_CHANGE_STALE: return newPolicyError(usefulerror.ErrConflict, fmt.Sprintf("The policy moved: a part that change %s edits changed after its base revision", changeID), @@ -42,6 +40,9 @@ func mapChangeError(op, changeID string, err error) error { if st, ok := status.FromError(err); ok { switch st.Code() { case codes.NotFound: + if changeID == "" { + return cause + } return newPolicyError(usefulerror.ErrNotFound, fmt.Sprintf("Policy change %s does not exist", changeID), "List the changes: safedep policy change list", @@ -56,6 +57,19 @@ func mapChangeError(op, changeID string, err error) error { return cause } +// mapRestoreError gives the recovery for the errors of a create that +// restores an old revision. A missing revision is the usual cause of +// NotFound. +func mapRestoreError(fromRevision uint64, err error) error { + if st, ok := status.FromError(err); ok && st.Code() == codes.NotFound { + return newPolicyError(usefulerror.ErrNotFound, + fmt.Sprintf("Policy revision %d does not exist", fromRevision), + "List the revisions: safedep policy revision list", + fmt.Errorf("policy change create: %w", err)) + } + return mapChangeError("create", "", err) +} + // mapRuleError gives the recovery for the errors of a package rule RPC. func mapRuleError(op, ruleID string, err error) error { cause := fmt.Errorf("package rule %s: %w", op, err) diff --git a/internal/cmd/policy/get.go b/internal/cmd/policy/get.go index 6d2f340..28dc77a 100644 --- a/internal/cmd/policy/get.go +++ b/internal/cmd/policy/get.go @@ -11,6 +11,7 @@ import ( "github.com/safedep/cli/internal/app" "github.com/safedep/cli/internal/cloudpolicy" + clitui "github.com/safedep/cli/internal/tui" ) type getInput struct { @@ -112,8 +113,12 @@ func (r *getResult) RenderJSON() ([]byte, error) { }{Revision: r.Revision, Policy: r.Document}, "", " ") } -func (r *getResult) RenderTable() string { return r.YAML } +// RenderTable escapes the document for a terminal. yaml.v3 escapes control +// characters in strings, but not bidirectional format characters. +func (r *getResult) RenderTable() string { return clitui.EscapeText(r.YAML) } +// RenderPlain writes the document as it is, because `policy get > file` +// must give back the exact values. func (r *getResult) RenderPlain() string { return r.YAML } func trimNewline(b []byte) []byte { diff --git a/internal/cmd/policy/publish_test.go b/internal/cmd/policy/publish_test.go new file mode 100644 index 0000000..e8633fb --- /dev/null +++ b/internal/cmd/policy/publish_test.go @@ -0,0 +1,148 @@ +package policy + +import ( + "bytes" + "context" + "errors" + "os" + "testing" + + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/safedep/dry/tui/output" + "github.com/safedep/dry/usefulerror" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + "github.com/safedep/cli/internal/cloudpolicy/mocks" +) + +// captureStderr sends the messages of dry/tui to a buffer for one test. +func captureStderr(t *testing.T) *bytes.Buffer { + t.Helper() + var buf bytes.Buffer + output.SetWriters(os.Stdout, &buf) + t.Cleanup(func() { output.SetWriters(os.Stdout, os.Stderr) }) + return &buf +} + +// refuseConfirm fails the test when the command asks for a confirmation. +func refuseConfirm(t *testing.T) confirmFunc { + return func(string) (bool, error) { + t.Fatal("the command must not ask for a confirmation") + return false, nil + } +} + +func tighteningPreview() *policyv1.PreviewPolicyChangeResponse { + res := &policyv1.PreviewPolicyChangeResponse{} + res.SetHeadRevision(46) + res.SetDirection(policyv1.ChangeDirection_CHANGE_DIRECTION_TIGHTENS) + return res +} + +func publishResponse(direction policyv1.ChangeDirection) *policyv1.PublishPolicyChangeResponse { + rev := revision(47, "payments") + rev.SetDirection(direction) + res := &policyv1.PublishPolicyChangeResponse{} + res.SetRevision(rev) + return res +} + +func TestRunChangePublish_TighteningNeedsNoConfirmation(t *testing.T) { + stderr := captureStderr(t) + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicyChange(mock.Anything, mock.Anything).Return(changeResponse(openChange("18")), nil) + client.EXPECT().PreviewPolicyChange(mock.Anything, mock.Anything).Return(tighteningPreview(), nil) + client.EXPECT().PublishPolicyChange(mock.Anything, mock.MatchedBy(func(r *policyv1.PublishPolicyChangeRequest) bool { + return r.GetChangeId() == "18" && r.GetEtag() == "etag-1" && r.GetMessage() == "payments: fail on medium" + })).Return(publishResponse(policyv1.ChangeDirection_CHANGE_DIRECTION_TIGHTENS), nil) + + rev, err := runChangePublish(context.Background(), client, "18", "payments: fail on medium", refuseConfirm(t)) + require.NoError(t, err) + assert.Equal(t, uint64(47), rev.GetRevision()) + assert.Contains(t, stderr.String(), "Change 18 · TIGHTENS. An Admin can publish it") + + reportPublish(rev.GetRevision(), directionToken(rev.GetDirection())) + assert.Contains(t, stderr.String(), "revision 47 published · TIGHTENS") + assert.Contains(t, stderr.String(), "safedep endpoint list --applied-revision '<47'") +} + +func TestRunChangePublish_ShowsTheDirectionAndEveryWarning(t *testing.T) { + stderr := captureStderr(t) + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicyChange(mock.Anything, mock.Anything).Return(changeResponse(openChange("18")), nil) + client.EXPECT().PreviewPolicyChange(mock.Anything, mock.Anything).Return(previewResponse(), nil) + client.EXPECT().PublishPolicyChange(mock.Anything, mock.Anything). + Return(publishResponse(policyv1.ChangeDirection_CHANGE_DIRECTION_LOOSENS), nil) + + var asked string + _, err := runChangePublish(context.Background(), client, "18", "", func(q string) (bool, error) { + asked = q + return true, nil + }) + require.NoError(t, err) + assert.Equal(t, "Change 18 loosens the policy. Publish it?", asked) + + out := stderr.String() + assert.Contains(t, out, "Change 18 · LOOSENS. Only an Admin can publish it") + assert.Contains(t, out, "It loosens selector (scm-property/criticality=high -> custom/criticality=high) in override \"payments\"") + assert.Contains(t, out, `LOW_ENFORCED_COVERAGE scan_gate.fail_on: 1 of 3 projects cannot enforce "medium" yet`) +} + +func TestRunChangePublish_LooseningThatTheUserRefuses(t *testing.T) { + captureStderr(t) + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicyChange(mock.Anything, mock.Anything).Return(changeResponse(openChange("18")), nil) + client.EXPECT().PreviewPolicyChange(mock.Anything, mock.Anything).Return(previewResponse(), nil) + + _, err := runChangePublish(context.Background(), client, "18", "", func(string) (bool, error) { return false, nil }) + assert.ErrorIs(t, err, errPublishCancelled) +} + +func TestPublishConfirm(t *testing.T) { + ok, err := publishConfirm(true, false)("q") + require.NoError(t, err) + assert.True(t, ok, "--yes confirms with no terminal") + + _, err = publishConfirm(false, false)("q") + require.Error(t, err) + ue, isUseful := usefulerror.AsUsefulError(err) + require.True(t, isUseful) + assert.Contains(t, ue.HumanError(), "no terminal is present to confirm it") + assert.Contains(t, ue.Help(), "pass --yes") +} + +func TestRunChangePublish_StaleStopsBeforeThePublish(t *testing.T) { + stderr := captureStderr(t) + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicyChange(mock.Anything, mock.Anything).Return(changeResponse(openChange("19")), nil) + preview := tighteningPreview() + preview.SetStale(true) + preview.SetHeadRevision(51) + client.EXPECT().PreviewPolicyChange(mock.Anything, mock.Anything).Return(preview, nil) + + _, err := runChangePublish(context.Background(), client, "19", "", refuseConfirm(t)) + require.Error(t, err) + ue, ok := usefulerror.AsUsefulError(err) + require.True(t, ok) + assert.Equal(t, "safedep policy change sync 19", ue.Help()[len(ue.Help())-len("safedep policy change sync 19"):]) + assert.Contains(t, stderr.String(), "Change 19 is stale") +} + +func TestRunChangePublish_PreviewFails(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicyChange(mock.Anything, mock.Anything).Return(changeResponse(openChange("18")), nil) + client.EXPECT().PreviewPolicyChange(mock.Anything, mock.Anything).Return(nil, errors.New("down")) + _, err := runChangePublish(context.Background(), client, "18", "", refuseConfirm(t)) + assert.ErrorContains(t, err, "policy change preview: down") +} + +func TestReportPreview_EscapesServerText(t *testing.T) { + stderr := captureStderr(t) + preview := newPreviewView(previewResponse()) + preview.Warnings[0].Message = "evil\x1b]0;title\x07" + reportPreview("18", preview) + assert.NotContains(t, stderr.String(), "\x1b") + assert.Contains(t, stderr.String(), `evil\x1b]0;title\x07`) +} diff --git a/internal/cmd/policy/revision.go b/internal/cmd/policy/revision.go index 6be7713..846b8a0 100644 --- a/internal/cmd/policy/revision.go +++ b/internal/cmd/policy/revision.go @@ -4,7 +4,6 @@ import ( "context" "encoding/json" "fmt" - "strconv" "strings" "time" @@ -16,6 +15,7 @@ import ( "github.com/safedep/cli/internal/app" "github.com/safedep/cli/internal/cloudpolicy" "github.com/safedep/cli/internal/paging" + clitui "github.com/safedep/cli/internal/tui" ) type revisionListInput struct { @@ -34,8 +34,8 @@ func revisionListCmd(a *app.App) *cobra.Command { Use: "list", Short: "List policy revisions, newest first", Long: "List the policy revisions of the tenant, newest first, with the author, the source, the change " + - "direction and the publish message. One page is returned per invocation, so follow " + - "--page-token to read the next page.", + "direction and the publish message. The command reads one page. Pass --page-token to " + + "read the next page.", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { client, err := a.ControlPlane() @@ -84,14 +84,14 @@ func (r *revisionListResult) RenderTable() string { rows := make([][]string, 0, len(r.Revisions)) for _, rev := range r.Revisions { rows = append(rows, []string{ - fmt.Sprintf("%d", rev.Revision), humanTimeCell(rev.PublishedAt, now), emptyDash(rev.Author), - rev.Source, rev.Direction, emptyDash(rev.Message), + fmt.Sprintf("%d", rev.Revision), humanTimeCell(rev.PublishedAt, now), cloudpolicy.EmptyDash(rev.Author), + rev.Source, rev.Direction, cloudpolicy.EmptyDash(rev.Message), }) } t := table.New(). Title("Policy revisions"). Headers("REV", "PUBLISHED", "BY", "SOURCE", "DIRECTION", "MESSAGE"). - Rows(rows...). + Rows(clitui.EscapeCells(rows)...). EmptyMessage("No policy revisions. The tenant has not published a policy yet.") if r.NextPageToken != "" { t = t.Footer("More available: --page-token " + r.NextPageToken) @@ -103,98 +103,8 @@ func (r *revisionListResult) RenderPlain() string { var b strings.Builder b.WriteString("revision\tpublished_at\tauthor\tsource\tdirection\tchange_id\tmessage") for _, rev := range r.Revisions { - fmt.Fprintf(&b, "\n%d\t%s\t%s\t%s\t%s\t%s\t%s", - rev.Revision, rev.Published, rev.Author, rev.Source, rev.Direction, rev.ChangeID, rev.Message) + b.WriteString("\n" + clitui.PlainRow(fmt.Sprint(rev.Revision), rev.Published, rev.Author, rev.Source, + rev.Direction, rev.ChangeID, rev.Message)) } return b.String() } - -type revisionShowResult struct { - Revision *revisionView - Document any - YAML string -} - -func revisionShowCmd(a *app.App) *cobra.Command { - return &cobra.Command{ - Use: "show REVISION", - Short: "Show one policy revision with its policy settings", - Long: "Show one policy revision: who published it, when, from which change, its change direction, " + - "and the policy settings document at that revision.", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - revision, err := parseRevision(args[0]) - if err != nil { - return err - } - client, err := a.ControlPlane() - if err != nil { - return err - } - res, err := runRevisionShow(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), revision) - if err != nil { - return err - } - return a.Output.Print(res) - }, - } -} - -func parseRevision(text string) (uint64, error) { - n, err := strconv.ParseUint(strings.TrimPrefix(text, "rev"), 10, 64) - if err != nil || n == 0 { - return 0, invalidInputError(fmt.Errorf("revision %q is not a revision number", text), - "Give a number from: safedep policy revision list") - } - return n, nil -} - -func runRevisionShow(ctx context.Context, client policyv1grpc.PolicyServiceClient, revision uint64) (*revisionShowResult, error) { - req := &policyv1.GetPolicyRevisionRequest{} - req.SetRevision(revision) - res, err := client.GetPolicyRevision(ctx, req) - if err != nil { - return nil, fmt.Errorf("policy revision show: %w", err) - } - doc, err := cloudpolicy.PolicyMap(res.GetPolicy()) - if err != nil { - return nil, err - } - text, err := cloudpolicy.MarshalPolicy(res.GetPolicy(), "") - if err != nil { - return nil, err - } - view := newRevisionView(res.GetRevision()) - if view == nil { - return nil, fmt.Errorf("policy revision show: invalid response: revision %d is missing", revision) - } - return &revisionShowResult{Revision: view, Document: doc, YAML: string(trimNewline(text))}, nil -} - -func (r *revisionShowResult) RenderJSON() ([]byte, error) { - return json.MarshalIndent(struct { - Revision *revisionView `json:"revision"` - Policy any `json:"policy"` - }{Revision: r.Revision, Policy: r.Document}, "", " ") -} - -func (r *revisionShowResult) RenderTable() string { - rev := r.Revision - change := "-" - if rev.ChangeID != "" { - change = rev.ChangeID + sep + "safedep policy change show " + rev.ChangeID - } - rows := [][2]string{ - {"Revision", rev.summary(time.Now())}, - {"Source", rev.Source}, - {"Direction", rev.Direction}, - {"Change", change}, - } - return cloudpolicy.KeyValues(rows) + "\n\nPolicy settings\n" + r.YAML -} - -func (r *revisionShowResult) RenderPlain() string { - rev := r.Revision - return fmt.Sprintf("revision\t%d\npublished_at\t%s\nauthor\t%s\nsource\t%s\ndirection\t%s\nchange_id\t%s\nmessage\t%s\n%s", - rev.Revision, rev.Published, rev.Author, rev.Source, rev.Direction, rev.ChangeID, rev.Message, r.YAML) -} diff --git a/internal/cmd/policy/revision_show.go b/internal/cmd/policy/revision_show.go new file mode 100644 index 0000000..3a24387 --- /dev/null +++ b/internal/cmd/policy/revision_show.go @@ -0,0 +1,116 @@ +package policy + +import ( + "context" + "encoding/json" + "fmt" + "strconv" + "strings" + "time" + + policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/spf13/cobra" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" + clitui "github.com/safedep/cli/internal/tui" +) + +type revisionShowResult struct { + Revision *revisionView + Document any + YAML string +} + +func revisionShowCmd(a *app.App) *cobra.Command { + return &cobra.Command{ + Use: "show REVISION", + Short: "Show one policy revision with its policy settings", + Long: "Show one policy revision: who published it, when, from which change, its change direction, " + + "and the policy settings document at that revision.", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + revision, err := parseRevision(args[0]) + if err != nil { + return err + } + client, err := a.ControlPlane() + if err != nil { + return err + } + res, err := runRevisionShow(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), revision) + if err != nil { + return err + } + return a.Output.Print(res) + }, + } +} + +func parseRevision(text string) (uint64, error) { + n, err := strconv.ParseUint(strings.TrimPrefix(text, "rev"), 10, 64) + if err != nil || n == 0 { + return 0, invalidInputError(fmt.Errorf("revision %q is not a revision number", text), + "Give a number from: safedep policy revision list") + } + return n, nil +} + +func runRevisionShow(ctx context.Context, client policyv1grpc.PolicyServiceClient, revision uint64) (*revisionShowResult, error) { + req := &policyv1.GetPolicyRevisionRequest{} + req.SetRevision(revision) + res, err := client.GetPolicyRevision(ctx, req) + if err != nil { + return nil, fmt.Errorf("policy revision show: %w", err) + } + doc, err := cloudpolicy.PolicyMap(res.GetPolicy()) + if err != nil { + return nil, err + } + text, err := cloudpolicy.MarshalPolicy(res.GetPolicy(), "") + if err != nil { + return nil, err + } + view := newRevisionView(res.GetRevision()) + if view == nil { + return nil, fmt.Errorf("policy revision show: invalid response: revision %d is missing", revision) + } + return &revisionShowResult{Revision: view, Document: doc, YAML: string(trimNewline(text))}, nil +} + +func (r *revisionShowResult) RenderJSON() ([]byte, error) { + return json.MarshalIndent(struct { + Revision *revisionView `json:"revision"` + Policy any `json:"policy"` + }{Revision: r.Revision, Policy: r.Document}, "", " ") +} + +func (r *revisionShowResult) RenderTable() string { + rev := r.Revision + change := "-" + if rev.ChangeID != "" { + change = rev.ChangeID + sep + "safedep policy change show " + rev.ChangeID + } + rows := [][2]string{ + {"Revision", rev.summary(time.Now())}, + {"Source", rev.Source}, + {"Direction", rev.Direction}, + {"Change", change}, + } + return cloudpolicy.KeyValues(rows) + "\n\nPolicy settings\n" + clitui.EscapeText(r.YAML) +} + +func (r *revisionShowResult) RenderPlain() string { + rev := r.Revision + return strings.Join([]string{ + clitui.PlainRow("revision", fmt.Sprint(rev.Revision)), + clitui.PlainRow("published_at", rev.Published), + clitui.PlainRow("author", rev.Author), + clitui.PlainRow("source", rev.Source), + clitui.PlainRow("direction", rev.Direction), + clitui.PlainRow("change_id", rev.ChangeID), + clitui.PlainRow("message", rev.Message), + clitui.EscapeText(r.YAML), + }, "\n") +} diff --git a/internal/cmd/policy/rule_create.go b/internal/cmd/policy/rule_create.go index f842a6f..8a8e871 100644 --- a/internal/cmd/policy/rule_create.go +++ b/internal/cmd/policy/rule_create.go @@ -1,14 +1,7 @@ package policy import ( - "bufio" - "bytes" "context" - "errors" - "fmt" - "io" - "os" - "slices" "strings" "time" @@ -18,10 +11,10 @@ import ( "github.com/safedep/dry/tui" "github.com/safedep/dry/tui/humanize" "github.com/spf13/cobra" - "google.golang.org/protobuf/types/known/timestamppb" "github.com/safedep/cli/internal/app" "github.com/safedep/cli/internal/cloudpolicy" + clitui "github.com/safedep/cli/internal/tui" ) const ( @@ -105,170 +98,6 @@ func ruleCreateCmd(a *app.App) *cobra.Command { return cmd } -func validateRuleCreate(in ruleCreateInput) error { - switch { - case in.Block == in.Trust: - return invalidInputError(errors.New("give one of --block or --trust"), - "Block: safedep policy rule create --block pkg:npm/name --reason TEXT") - case in.File != "" && in.Selector != "": - return invalidInputError(errors.New("give a PURL or --file, not both"), "Use --file for a list of selectors") - case in.File == "" && in.Selector == "": - return invalidInputError(errors.New("give the PURL of the package"), - "As in: safedep policy rule create --block pkg:npm/evil --reason TEXT") - case in.File != "" && in.Trust: - return invalidInputError(errors.New("only block entries can come from a file"), - "Create each trust entry with its own command") - case in.File != "" && in.Vers != "": - return invalidInputError(errors.New("--vers applies to one PURL: in a file, write the range after the PURL"), - "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: - return invalidInputError(errors.New("a trust entry needs --scope"), - "Name each verdict that it waives: --scope "+strings.Join(trustScopeTokens(), ", --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") - } - _, err := expandScopes(in.Scopes) - return err -} - -// 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. -func expandScopes(values []string) ([]corev1.TrustScope, error) { - var out []corev1.TrustScope - for _, v := range values { - if strings.EqualFold(strings.TrimSpace(v), scopeAll) { - out = out[:0] - for _, token := range trustScopeTokens() { - scope, err := parseTrustScope(token) - if err != nil { - return nil, err - } - out = append(out, scope) - } - return out, nil - } - scope, err := parseTrustScope(v) - if err != nil { - return nil, err - } - if !slices.Contains(out, scope) { - out = append(out, scope) - } - } - return out, nil -} - -// buildRuleCreates checks every selector and builds the rules, before any -// RPC, so one bad line in a file stops the whole create. -func buildRuleCreates(in ruleCreateInput, stdin io.Reader, now time.Time) ([]*policyv1.PackageRuleCreate, error) { - if err := validateRuleCreate(in); err != nil { - return nil, err - } - effect := corev1.Effect_EFFECT_BLOCK - if in.Trust { - effect = corev1.Effect_EFFECT_TRUST - } - scopes, err := expandScopes(in.Scopes) - if err != nil { - return nil, err - } - var expires *timestamppb.Timestamp - if in.Expires != "" { - t, err := parseExpiry(in.Expires, now) - if err != nil { - return nil, invalidInputError(err, "Use a duration, as in 30d, or a date, as in 2027-01-26") - } - expires = timestamppb.New(t) - } - - entries := []selectorEntry{{purl: in.Selector, vers: in.Vers}} - if in.File != "" { - entries, err = readSelectorFile(in.File, stdin) - if err != nil { - return nil, err - } - } - - creates := make([]*policyv1.PackageRuleCreate, 0, len(entries)) - for _, e := range entries { - selector, err := buildSelector(e.purl, e.vers, effect) - if err != nil { - if e.line > 0 { - err = fmt.Errorf("%s line %d: %w", in.File, e.line, err) - } - return nil, invalidInputError(err, "Fix the selector and run the command again") - } - rule := &corev1.PackageRule{} - rule.SetSelector(selector) - rule.SetEffect(effect) - rule.SetScopes(scopes) - rule.SetReason(in.Reason) - if expires != nil { - rule.SetExpiresAt(expires) - } - create := &policyv1.PackageRuleCreate{} - create.SetRule(rule) - create.SetTicket(in.Ticket) - create.SetRequestedBy(in.RequestedBy) - creates = append(creates, create) - } - return creates, nil -} - -type selectorEntry struct { - purl string - vers string - line int -} - -// readSelectorFile reads one selector on each line: a PURL and an optional -// range after a space. A line that starts with # and an empty line are -// skipped. -func readSelectorFile(path string, stdin io.Reader) ([]selectorEntry, error) { - r := stdin - if path != "-" { - data, err := os.ReadFile(path) - if err != nil { - return nil, invalidInputError(fmt.Errorf("read %s: %w", path, err), "Check the path of --file") - } - r = bytes.NewReader(data) - } - var entries []selectorEntry - scanner := bufio.NewScanner(r) - for n := 1; scanner.Scan(); n++ { - line := strings.TrimSpace(scanner.Text()) - if line == "" || strings.HasPrefix(line, "#") { - continue - } - fields := strings.Fields(line) - if len(fields) > 2 { - return nil, invalidInputError(fmt.Errorf("%s line %d: write a PURL and an optional range, not %d values", path, n, len(fields)), - "Write each line as: PURL [RANGE]") - } - entry := selectorEntry{purl: fields[0], line: n} - if len(fields) == 2 { - entry.vers = fields[1] - } - entries = append(entries, entry) - if len(entries) > maxBulkRules { - return nil, invalidInputError(fmt.Errorf("%s has more than %d selectors", path, maxBulkRules), - fmt.Sprintf("Split the file into parts of %d lines or fewer", maxBulkRules)) - } - } - if err := scanner.Err(); err != nil { - return nil, fmt.Errorf("read %s: %w", path, err) - } - if len(entries) == 0 { - return nil, invalidInputError(fmt.Errorf("%s has no selectors", path), "Write one PURL on each line") - } - return entries, nil -} - func runRuleCreate( ctx context.Context, client policyv1grpc.PolicyServiceClient, @@ -303,15 +132,21 @@ func announceRuleCreate(in ruleCreateInput, creates []*policyv1.PackageRuleCreat if in.Override == "" { tui.Info("Applies to every endpoint and project of the tenant (base). Use --override NAME to narrow it.") } else { - tui.Info("Applies to the subjects that policy override %q selects.", in.Override) + tui.Info("Applies to the subjects that policy override %q selects.", clitui.EscapeLine(in.Override)) } if in.Block { + for _, c := range creates { + if purl := c.GetRule().GetSelector().GetPurl(); isWideSelector(purl) { + tui.Warning("Selector %s blocks every package of its ecosystem. It stops every install of that ecosystem in the tenant", + clitui.EscapeLine(purl)) + } + } 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), purl) + tui.Warning("This rule loosens the policy: it waives %s for %s.", scopeEffect(scope), clitui.EscapeLine(purl)) } tui.Warning("Verified malware stays blocked") } @@ -331,12 +166,12 @@ func scopeEffect(scope corev1.TrustScope) string { func reportRuleCreate(in ruleCreateInput, res *ruleCreateResult, now time.Time) { if len(res.Rules) == 1 { - tui.Success("rule %s created%srevision %d published", res.Rules[0].GetRule().GetRuleId(), sep, res.Revision) + tui.Success("rule %s created%srevision %d published", clitui.EscapeLine(res.Rules[0].GetRule().GetRuleId()), sep, res.Revision) } else { tui.Success("%d rules created%srevision %d published", len(res.Rules), sep, res.Revision) } if in.Trust && len(res.Rules) == 1 { - if expires := timeOf(res.Rules[0].GetRule().GetExpiresAt()); expires != nil { + if expires := cloudpolicy.TimeOf(res.Rules[0].GetRule().GetExpiresAt()); expires != nil { tui.Info(" The rule expires %s (%s)", humanize.Time(*expires, now), expires.Format(time.DateOnly)) } } diff --git a/internal/cmd/policy/rule_delete.go b/internal/cmd/policy/rule_delete.go new file mode 100644 index 0000000..420effe --- /dev/null +++ b/internal/cmd/policy/rule_delete.go @@ -0,0 +1,64 @@ +package policy + +import ( + "context" + "errors" + "strings" + + policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/safedep/dry/tui" + "github.com/spf13/cobra" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" + clitui "github.com/safedep/cli/internal/tui" +) + +func ruleDeleteCmd(a *app.App) *cobra.Command { + var reason, message string + cmd := &cobra.Command{ + Use: "delete RULE --reason TEXT", + Short: "Delete a package rule and publish at once", + Long: "Delete a package rule and publish the change at once as a new policy revision. The rule " + + "stays in the history of the revisions. The delete of a block entry loosens the policy.", + Args: func(cmd *cobra.Command, args []string) error { + if err := cobra.ExactArgs(1)(cmd, args); err != nil { + return err + } + if strings.TrimSpace(reason) == "" { + return invalidInputError(errors.New("--reason is required"), "Say why the rule goes, as in --reason \"no longer needed\"") + } + return nil + }, + RunE: func(cmd *cobra.Command, args []string) error { + client, err := a.ControlPlane() + if err != nil { + return err + } + rev, err := runRuleDelete(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), args[0], reason, message) + if err != nil { + return err + } + tui.Success("rule %s deleted%srevision %d published", clitui.EscapeLine(args[0]), sep, rev) + return nil + }, + } + cmd.Flags().StringVar(&reason, "reason", "", "why the rule goes (required)") + cmd.Flags().StringVarP(&message, "message", "m", "", "the publish message; the server writes one when it is empty") + return cmd +} + +func runRuleDelete(ctx context.Context, client policyv1grpc.PolicyServiceClient, id, reason, message string) (uint64, error) { + del := &policyv1.PackageRuleDelete{} + del.SetRuleId(id) + del.SetReason(reason) + req := &policyv1.DeletePackageRuleRequest{} + req.SetDelete(del) + req.SetMessage(message) + res, err := client.DeletePackageRule(ctx, req) + if err != nil { + return 0, mapRuleError("delete", id, err) + } + return res.GetRevision().GetRevision(), nil +} diff --git a/internal/cmd/policy/rule_filters.go b/internal/cmd/policy/rule_filters.go new file mode 100644 index 0000000..d234446 --- /dev/null +++ b/internal/cmd/policy/rule_filters.go @@ -0,0 +1,88 @@ +package policy + +import ( + "fmt" + "strings" + + corev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/core/v1" + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "google.golang.org/protobuf/types/known/durationpb" + + "github.com/safedep/cli/internal/tui" +) + +func trustScopeTokens() []string { + return tui.EnumTokens(corev1.TrustScope_name, trustScopePrefix) +} + +func parseEffect(token string) (corev1.Effect, error) { + n, ok := tui.ParseEnumToken(corev1.Effect_name, effectPrefix, token) + if !ok { + return 0, invalidInputError(fmt.Errorf("unknown --effect value %q: use trust or block", token), + "Retry with --effect trust or --effect block") + } + 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 { + return 0, invalidInputError( + fmt.Errorf("unknown trust scope %q: allowed values are %s", token, strings.Join(trustScopeTokens(), ", ")), + "Retry with one of: "+strings.Join(trustScopeTokens(), ", ")) + } + return corev1.TrustScope(n), nil +} + +// ruleListFilters builds the filters. overrideID is the id of in.Override, +// which the caller resolves. +func ruleListFilters(in *ruleListInput, overrideID string) (*policyv1.ListPackageRulesRequest_Filters, error) { + if in.Override != "" && in.Base { + return nil, invalidInputError(fmt.Errorf("--override and --base select different rules"), "Use one of them") + } + filters := &policyv1.ListPackageRulesRequest_Filters{} + set := false + if in.Effect != "" { + effect, err := parseEffect(in.Effect) + if err != nil { + return nil, err + } + filters.SetEffect(effect) + set = true + } + if in.Scope != "" { + scope, err := parseTrustScope(in.Scope) + if err != nil { + return nil, err + } + filters.SetScope(scope) + set = true + } + if in.SelectorPrefix != "" { + filters.SetSelectorPrefix(in.SelectorPrefix) + set = true + } + if in.Expiring < 0 { + return nil, invalidInputError(fmt.Errorf("--expiring must not be negative"), "Use a duration such as 7d") + } + if in.Expiring > 0 { + filters.SetExpiringWithin(durationpb.New(in.Expiring)) + set = true + } + if in.Base { + filters.SetOverrideId("") + set = true + } + if overrideID != "" { + filters.SetOverrideId(overrideID) + set = true + } + if in.AtRevision > 0 { + filters.SetAtRevision(in.AtRevision) + set = true + } + if !set { + return nil, nil + } + return filters, nil +} diff --git a/internal/cmd/policy/rule_input.go b/internal/cmd/policy/rule_input.go new file mode 100644 index 0000000..2e1f9f5 --- /dev/null +++ b/internal/cmd/policy/rule_input.go @@ -0,0 +1,215 @@ +package policy + +import ( + "bufio" + "bytes" + "errors" + "fmt" + "io" + "os" + "regexp" + "slices" + "strings" + "time" + + corev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/core/v1" + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "google.golang.org/protobuf/types/known/timestamppb" +) + +// This file checks and builds the input of `policy rule create`, before any +// RPC, so one bad line in a file stops the whole create. + +const ( + // maxTrustExpiry is the longest life of a trust entry in the MVP. The + // server refuses a later expiry. A tenant preference changes it later. + maxTrustExpiry = 90 * 24 * time.Hour +) + +// widePattern matches a prefix that selects every package of an +// ecosystem, as "pkg:npm/*". +var widePattern = regexp.MustCompile(`^pkg:[A-Za-z0-9.+-]+/[*]$`) + +// checkTrustExpiry refuses a trust expiry that the server refuses too. +func checkTrustExpiry(expires, now time.Time) error { + if expires.Sub(now) <= maxTrustExpiry { + return nil + } + return invalidInputError( + fmt.Errorf("a trust entry expires at most 90 days from now, not on %s", expires.Format(time.DateOnly)), + "Use --expires 90d or less. Extend the entry later with: safedep policy rule update RULE --expires 90d") +} + +// isWideSelector reports a block that stops every install of an ecosystem. +func isWideSelector(purl string) bool { + return widePattern.MatchString(purl) +} + +func validateRuleCreate(in ruleCreateInput) error { + switch { + case in.Block == in.Trust: + return invalidInputError(errors.New("give one of --block or --trust"), + "Block: safedep policy rule create --block pkg:npm/name --reason TEXT") + case in.File != "" && in.Selector != "": + return invalidInputError(errors.New("give a PURL or --file, not both"), "Use --file for a list of selectors") + case in.File == "" && in.Selector == "": + return invalidInputError(errors.New("give the PURL of the package"), + "As in: safedep policy rule create --block pkg:npm/evil --reason TEXT") + case in.File != "" && in.Trust: + return invalidInputError(errors.New("only block entries can come from a file"), + "Create each trust entry with its own command") + case in.File != "" && in.Vers != "": + return invalidInputError(errors.New("--vers applies to one PURL: in a file, write the range after the PURL"), + "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: + return invalidInputError(errors.New("a trust entry needs --scope"), + "Name each verdict that it waives: --scope "+strings.Join(trustScopeTokens(), ", --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") + } + _, err := expandScopes(in.Scopes) + return err +} + +// 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. +func expandScopes(values []string) ([]corev1.TrustScope, error) { + var out []corev1.TrustScope + for _, v := range values { + if strings.EqualFold(strings.TrimSpace(v), scopeAll) { + out = out[:0] + for _, token := range trustScopeTokens() { + scope, err := parseTrustScope(token) + if err != nil { + return nil, err + } + out = append(out, scope) + } + return out, nil + } + scope, err := parseTrustScope(v) + if err != nil { + return nil, err + } + if !slices.Contains(out, scope) { + out = append(out, scope) + } + } + return out, nil +} + +// buildRuleCreates checks every selector and builds the rules, before any +// RPC, so one bad line in a file stops the whole create. +func buildRuleCreates(in ruleCreateInput, stdin io.Reader, now time.Time) ([]*policyv1.PackageRuleCreate, error) { + if err := validateRuleCreate(in); err != nil { + return nil, err + } + effect := corev1.Effect_EFFECT_BLOCK + if in.Trust { + effect = corev1.Effect_EFFECT_TRUST + } + scopes, err := expandScopes(in.Scopes) + if err != nil { + return nil, err + } + var expires *timestamppb.Timestamp + if in.Expires != "" { + t, err := parseExpiry(in.Expires, now) + if err != nil { + return nil, invalidInputError(err, "Use a duration, as in 30d, or a date, as in 2027-01-26") + } + if in.Trust { + if err := checkTrustExpiry(t, now); err != nil { + return nil, err + } + } + expires = timestamppb.New(t) + } + + entries := []selectorEntry{{purl: in.Selector, vers: in.Vers}} + if in.File != "" { + entries, err = readSelectorFile(in.File, stdin) + if err != nil { + return nil, err + } + } + + creates := make([]*policyv1.PackageRuleCreate, 0, len(entries)) + for _, e := range entries { + selector, err := buildSelector(e.purl, e.vers, effect) + if err != nil { + if e.line > 0 { + err = fmt.Errorf("%s line %d: %w", in.File, e.line, err) + } + return nil, invalidInputError(err, "Fix the selector and run the command again") + } + rule := &corev1.PackageRule{} + rule.SetSelector(selector) + rule.SetEffect(effect) + rule.SetScopes(scopes) + rule.SetReason(in.Reason) + if expires != nil { + rule.SetExpiresAt(expires) + } + create := &policyv1.PackageRuleCreate{} + create.SetRule(rule) + create.SetTicket(in.Ticket) + create.SetRequestedBy(in.RequestedBy) + creates = append(creates, create) + } + return creates, nil +} + +type selectorEntry struct { + purl string + vers string + line int +} + +// readSelectorFile reads one selector on each line: a PURL and an optional +// range after a space. A line that starts with # and an empty line are +// skipped. +func readSelectorFile(path string, stdin io.Reader) ([]selectorEntry, error) { + r := stdin + if path != "-" { + data, err := os.ReadFile(path) + if err != nil { + return nil, invalidInputError(fmt.Errorf("read %s: %w", path, err), "Check the path of --file") + } + r = bytes.NewReader(data) + } + var entries []selectorEntry + scanner := bufio.NewScanner(r) + for n := 1; scanner.Scan(); n++ { + line := strings.TrimSpace(scanner.Text()) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + fields := strings.Fields(line) + if len(fields) > 2 { + return nil, invalidInputError(fmt.Errorf("%s line %d: write a PURL and an optional range, not %d values", path, n, len(fields)), + "Write each line as: PURL [RANGE]") + } + entry := selectorEntry{purl: fields[0], line: n} + if len(fields) == 2 { + entry.vers = fields[1] + } + entries = append(entries, entry) + if len(entries) > maxBulkRules { + return nil, invalidInputError(fmt.Errorf("%s has more than %d selectors", path, maxBulkRules), + fmt.Sprintf("Split the file into parts of %d lines or fewer", maxBulkRules)) + } + } + if err := scanner.Err(); err != nil { + return nil, fmt.Errorf("read %s: %w", path, err) + } + if len(entries) == 0 { + return nil, invalidInputError(fmt.Errorf("%s has no selectors", path), "Write one PURL on each line") + } + return entries, nil +} diff --git a/internal/cmd/policy/rule_list.go b/internal/cmd/policy/rule_list.go index d84fad6..637622e 100644 --- a/internal/cmd/policy/rule_list.go +++ b/internal/cmd/policy/rule_list.go @@ -8,12 +8,9 @@ import ( "time" policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" - corev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/core/v1" policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" - "github.com/safedep/dry/tui/humanize" "github.com/safedep/dry/tui/table" "github.com/spf13/cobra" - "google.golang.org/protobuf/types/known/durationpb" "github.com/safedep/cli/internal/app" "github.com/safedep/cli/internal/cloudpolicy" @@ -24,73 +21,6 @@ import ( const baseAttachment = "base" -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"` - 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 -} - -// newRuleView translates a rule. names maps override ids to names. A rule -// whose override is not in names shows the override id. -func newRuleView(r *policyv1.PackageRuleWithAttributes, names map[string]string) ruleView { - rule := r.GetRule() - expires := timeOf(rule.GetExpiresAt()) - v := ruleView{ - ID: rule.GetRuleId(), - Purl: rule.GetSelector().GetPurl(), - Vers: rule.GetSelector().GetVers(), - Effect: tui.EnumToken(rule.GetEffect().String(), effectPrefix), - Scopes: scopeTokens(rule.GetScopes()), - Reason: rule.GetReason(), - Ticket: r.GetTicket(), - RequestedBy: r.GetRequestedBy(), - OverrideID: r.GetOverrideId(), - AttachesTo: baseAttachment, - CreatedBy: actorName(r.GetCreatedBy()), - AddedRevision: r.GetAddedRevision(), - RemovedRevision: r.GetRemovedRevision(), - ExpiresAt: cloudpolicy.RFC3339(expires), - CreatedAt: cloudpolicy.RFC3339(timeOf(r.GetCreatedAt())), - UpdatedAt: cloudpolicy.RFC3339(timeOf(r.GetUpdatedAt())), - expires: expires, - } - if id := r.GetOverrideId(); id != "" { - v.AttachesTo = "override " + id - if name, ok := names[id]; ok { - v.AttachesTo = fmt.Sprintf("override %q", name) - } - } - return v -} - -func (v ruleView) selector() string { - if v.Vers == "" { - return v.Purl - } - return v.Purl + " " + v.Vers -} - -func (v ruleView) expiresCell(now time.Time) string { - if v.expires == nil { - return "never" - } - return humanize.Time(*v.expires, now) -} - type ruleListInput struct { Effect string Scope string @@ -115,7 +45,7 @@ func ruleListCmd(a *app.App) *cobra.Command { Short: "List package rules", Long: "List the active package rules at head, or at an older policy revision with --at-revision. " + "Filter by effect, trust scope, selector prefix, expiry, or the policy override that a rule " + - "attaches to. One page is returned per invocation, so follow --page-token to read the next page.", + "attaches to. The command reads one page. Pass --page-token to read the next page.", Args: func(cmd *cobra.Command, args []string) error { if err := cobra.NoArgs(cmd, args); err != nil { return err @@ -148,82 +78,6 @@ func ruleListCmd(a *app.App) *cobra.Command { return cmd } -func trustScopeTokens() []string { - return tui.EnumTokens(corev1.TrustScope_name, trustScopePrefix) -} - -func parseEffect(token string) (corev1.Effect, error) { - n, ok := tui.ParseEnumToken(corev1.Effect_name, effectPrefix, token) - if !ok { - return 0, invalidInputError(fmt.Errorf("unknown --effect value %q: use trust or block", token), - "Retry with --effect trust or --effect block") - } - 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 { - return 0, invalidInputError( - fmt.Errorf("unknown trust scope %q: allowed values are %s", token, strings.Join(trustScopeTokens(), ", ")), - "Retry with one of: "+strings.Join(trustScopeTokens(), ", ")) - } - return corev1.TrustScope(n), nil -} - -// ruleListFilters builds the filters. overrideID is the id of in.Override, -// which the caller resolves. -func ruleListFilters(in *ruleListInput, overrideID string) (*policyv1.ListPackageRulesRequest_Filters, error) { - if in.Override != "" && in.Base { - return nil, invalidInputError(fmt.Errorf("--override and --base select different rules"), "Use one of them") - } - filters := &policyv1.ListPackageRulesRequest_Filters{} - set := false - if in.Effect != "" { - effect, err := parseEffect(in.Effect) - if err != nil { - return nil, err - } - filters.SetEffect(effect) - set = true - } - if in.Scope != "" { - scope, err := parseTrustScope(in.Scope) - if err != nil { - return nil, err - } - filters.SetScope(scope) - set = true - } - if in.SelectorPrefix != "" { - filters.SetSelectorPrefix(in.SelectorPrefix) - set = true - } - if in.Expiring < 0 { - return nil, invalidInputError(fmt.Errorf("--expiring must not be negative"), "Use a duration such as 7d") - } - if in.Expiring > 0 { - filters.SetExpiringWithin(durationpb.New(in.Expiring)) - set = true - } - if in.Base { - filters.SetOverrideId("") - set = true - } - if overrideID != "" { - filters.SetOverrideId(overrideID) - set = true - } - if in.AtRevision > 0 { - filters.SetAtRevision(in.AtRevision) - set = true - } - if !set { - return nil, nil - } - return filters, nil -} - func runRuleList(ctx context.Context, client policyv1grpc.PolicyServiceClient, in *ruleListInput) (*ruleListResult, error) { var names map[string]string overrideID := "" @@ -288,17 +142,17 @@ 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, emptyDash(strings.Join(rule.Scopes, ",")), - rule.Reason, emptyDash(rule.RequestedBy), rule.AttachesTo, rule.expiresCell(now), + rule.ID, rule.selector(), rule.Effect, cloudpolicy.EmptyDash(strings.Join(rule.Scopes, ",")), + rule.Reason, cloudpolicy.EmptyDash(rule.RequestedBy), rule.AttachesTo, rule.expiresCell(now), }) } t := table.New(). Title("Package rules"). Headers("RULE", "SELECTOR", "EFFECT", "SCOPE", "REASON", "REQUESTED BY", "ATTACHES TO", "EXPIRES"). - Rows(rows...). + Rows(tui.EscapeCells(rows)...). EmptyMessage("No package rules match. Block a package with: safedep policy rule create --block pkg:npm/name --reason TEXT") if len(rows) > 0 { - footer := fmt.Sprintf("%d %s", len(rows), plural(len(rows), "rule", "rules")) + footer := fmt.Sprintf("%d %s", len(rows), cloudpolicy.Plural(len(rows), "rule", "rules")) if r.NextPageToken != "" { footer += ". More available: --page-token " + r.NextPageToken } @@ -311,9 +165,8 @@ func (r *ruleListResult) RenderPlain() string { var b strings.Builder b.WriteString("rule_id\tpurl\tvers\teffect\tscopes\treason\trequested_by\toverride_id\texpires_at") for _, rule := range r.Rules { - fmt.Fprintf(&b, "\n%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s", - rule.ID, rule.Purl, rule.Vers, rule.Effect, strings.Join(rule.Scopes, ","), - rule.Reason, rule.RequestedBy, rule.OverrideID, rule.ExpiresAt) + 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)) } return b.String() } diff --git a/internal/cmd/policy/rule_ops.go b/internal/cmd/policy/rule_ops.go deleted file mode 100644 index e05d1d3..0000000 --- a/internal/cmd/policy/rule_ops.go +++ /dev/null @@ -1,263 +0,0 @@ -package policy - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "strings" - "time" - - policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" - policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" - "github.com/safedep/dry/tui" - "github.com/spf13/cobra" - "google.golang.org/protobuf/types/known/timestamppb" - - "github.com/safedep/cli/internal/app" - "github.com/safedep/cli/internal/cloudpolicy" -) - -type ruleShowResult struct { - Rule ruleView `json:"rule"` -} - -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 " + - "policy override that it attaches to, its expiry, and the revisions that added and removed it. " + - "A block message of a tool cites the rule id.", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - client, err := a.ControlPlane() - if err != nil { - return err - } - res, err := runRuleShow(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), args[0]) - if err != nil { - return err - } - return a.Output.Print(res) - }, - } -} - -func runRuleShow(ctx context.Context, client policyv1grpc.PolicyServiceClient, id string) (*ruleShowResult, error) { - req := &policyv1.GetPackageRuleRequest{} - req.SetRuleId(id) - res, err := client.GetPackageRule(ctx, req) - if err != nil { - return nil, mapRuleError("show", id, err) - } - var names map[string]string - if res.GetRule().GetOverrideId() != "" { - head, err := getPolicy(ctx, client) - if err != nil { - return nil, err - } - names = overrideNames(head.GetPolicy()) - } - return &ruleShowResult{Rule: newRuleView(res.GetRule(), names)}, nil -} - -func (r *ruleShowResult) RenderJSON() ([]byte, error) { - return json.MarshalIndent(r, "", " ") -} - -func (r *ruleShowResult) RenderTable() string { - v := r.Rule - now := time.Now() - removed := "active" - if v.RemovedRevision > 0 { - removed = fmt.Sprintf("removed in revision %d", v.RemovedRevision) - } - expires := v.expiresCell(now) - if v.expires != nil { - expires += " (" + v.expires.Format(time.DateOnly) + ")" - } - return cloudpolicy.KeyValues([][2]string{ - {"Rule", v.ID}, - {"Selector", v.selector()}, - {"Effect", v.Effect}, - {"Scope", emptyDash(strings.Join(v.Scopes, ", "))}, - {"Reason", v.Reason}, - {"Ticket", emptyDash(v.Ticket)}, - {"Requested by", emptyDash(v.RequestedBy)}, - {"Attaches to", v.AttachesTo}, - {"Expires", expires}, - {"Created by", emptyDash(v.CreatedBy)}, - {"Revisions", fmt.Sprintf("added in revision %d%s%s", v.AddedRevision, sep, removed)}, - }) -} - -func (r *ruleShowResult) RenderPlain() string { - v := r.Rule - return strings.Join([]string{ - "rule_id\t" + v.ID, - "purl\t" + v.Purl, - "vers\t" + v.Vers, - "effect\t" + v.Effect, - "scopes\t" + strings.Join(v.Scopes, ","), - "reason\t" + v.Reason, - "ticket\t" + v.Ticket, - "requested_by\t" + v.RequestedBy, - "override_id\t" + v.OverrideID, - "expires_at\t" + v.ExpiresAt, - "created_by\t" + v.CreatedBy, - fmt.Sprintf("added_revision\t%d", v.AddedRevision), - fmt.Sprintf("removed_revision\t%d", v.RemovedRevision), - }, "\n") -} - -type ruleUpdateInput struct { - Reason string - Expires string - Ticket string - RequestedBy string - Message string - changed func(name string) bool -} - -func ruleUpdateCmd(a *app.App) *cobra.Command { - var in ruleUpdateInput - cmd := &cobra.Command{ - Use: "update RULE", - Short: "Change the reason, expiry, ticket or requester of a package rule", - Long: "Change a package rule and publish the change at once as a new policy revision. A rule never " + - "changes its selector, effect or trust scopes: delete it and create another. A later expiry " + - "of a trust entry loosens the policy.", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - in.changed = cmd.Flags().Changed - update, err := buildRuleUpdate(args[0], in, time.Now()) - if err != nil { - return err - } - client, err := a.ControlPlane() - if err != nil { - return err - } - res, err := runRuleUpdate(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), update, in.Message) - if err != nil { - return err - } - msg := fmt.Sprintf("rule %s updated", args[0]) - if update.HasExpiresAt() { - msg = fmt.Sprintf("rule %s now expires on %s", args[0], update.GetExpiresAt().AsTime().Format(time.DateOnly)) - } - tui.Success("%s%srevision %d published", msg, sep, res.GetRevision().GetRevision()) - return nil - }, - } - f := cmd.Flags() - f.StringVar(&in.Reason, "reason", "", "the new reason") - f.StringVar(&in.Expires, "expires", "", "the new expiry: a duration from now, as in 90d, or a date") - f.StringVar(&in.Ticket, "ticket", "", "the new ticket or incident reference") - f.StringVar(&in.RequestedBy, "requested-by", "", "the new team or person that asked for the rule") - f.StringVarP(&in.Message, "message", "m", "", "the publish message; the server writes one when it is empty") - return cmd -} - -func buildRuleUpdate(id string, in ruleUpdateInput, now time.Time) (*policyv1.PackageRuleUpdate, error) { - changed := in.changed - if changed == nil { - changed = func(string) bool { return false } - } - update := &policyv1.PackageRuleUpdate{} - update.SetRuleId(id) - set := false - if changed("reason") { - if strings.TrimSpace(in.Reason) == "" { - return nil, invalidInputError(errors.New("--reason must not be empty"), "Say why the rule exists") - } - update.SetReason(in.Reason) - set = true - } - if changed("expires") { - t, err := parseExpiry(in.Expires, now) - if err != nil { - return nil, invalidInputError(err, "Use a duration, as in 90d, or a date, as in 2027-01-26") - } - update.SetExpiresAt(timestamppb.New(t)) - set = true - } - if changed("ticket") { - update.SetTicket(in.Ticket) - set = true - } - if changed("requested-by") { - update.SetRequestedBy(in.RequestedBy) - set = true - } - if !set { - return nil, invalidInputError(errors.New("give at least one of --reason, --expires, --ticket or --requested-by"), - "As in: safedep policy rule update "+id+" --expires 90d") - } - return update, nil -} - -func runRuleUpdate( - ctx context.Context, - client policyv1grpc.PolicyServiceClient, - update *policyv1.PackageRuleUpdate, - message string, -) (*policyv1.UpdatePackageRuleResponse, error) { - req := &policyv1.UpdatePackageRuleRequest{} - req.SetUpdate(update) - req.SetMessage(message) - res, err := client.UpdatePackageRule(ctx, req) - if err != nil { - return nil, mapRuleError("update", update.GetRuleId(), err) - } - return res, nil -} - -func ruleDeleteCmd(a *app.App) *cobra.Command { - var reason, message string - cmd := &cobra.Command{ - Use: "delete RULE --reason TEXT", - Short: "Delete a package rule and publish at once", - Long: "Delete a package rule and publish the change at once as a new policy revision. The rule " + - "stays in the history of the revisions. The delete of a block entry loosens the policy.", - Args: func(cmd *cobra.Command, args []string) error { - if err := cobra.ExactArgs(1)(cmd, args); err != nil { - return err - } - if strings.TrimSpace(reason) == "" { - return invalidInputError(errors.New("--reason is required"), "Say why the rule goes, as in --reason \"no longer needed\"") - } - return nil - }, - RunE: func(cmd *cobra.Command, args []string) error { - client, err := a.ControlPlane() - if err != nil { - return err - } - rev, err := runRuleDelete(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), args[0], reason, message) - if err != nil { - return err - } - tui.Success("rule %s deleted%srevision %d published", args[0], sep, rev) - return nil - }, - } - cmd.Flags().StringVar(&reason, "reason", "", "why the rule goes (required)") - cmd.Flags().StringVarP(&message, "message", "m", "", "the publish message; the server writes one when it is empty") - return cmd -} - -func runRuleDelete(ctx context.Context, client policyv1grpc.PolicyServiceClient, id, reason, message string) (uint64, error) { - del := &policyv1.PackageRuleDelete{} - del.SetRuleId(id) - del.SetReason(reason) - req := &policyv1.DeletePackageRuleRequest{} - req.SetDelete(del) - req.SetMessage(message) - res, err := client.DeletePackageRule(ctx, req) - if err != nil { - return 0, mapRuleError("delete", id, err) - } - return res.GetRevision().GetRevision(), nil -} diff --git a/internal/cmd/policy/rule_show.go b/internal/cmd/policy/rule_show.go new file mode 100644 index 0000000..d1dc6b5 --- /dev/null +++ b/internal/cmd/policy/rule_show.go @@ -0,0 +1,110 @@ +package policy + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "time" + + policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/spf13/cobra" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" + clitui "github.com/safedep/cli/internal/tui" +) + +type ruleShowResult struct { + Rule ruleView `json:"rule"` +} + +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 " + + "policy override that it attaches to, its expiry, and the revisions that added and removed it. " + + "A block message of a tool cites the rule id.", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + client, err := a.ControlPlane() + if err != nil { + return err + } + res, err := runRuleShow(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), args[0]) + if err != nil { + return err + } + return a.Output.Print(res) + }, + } +} + +func runRuleShow(ctx context.Context, client policyv1grpc.PolicyServiceClient, id string) (*ruleShowResult, error) { + req := &policyv1.GetPackageRuleRequest{} + req.SetRuleId(id) + res, err := client.GetPackageRule(ctx, req) + if err != nil { + return nil, mapRuleError("show", id, err) + } + var names map[string]string + if res.GetRule().GetOverrideId() != "" { + head, err := getPolicy(ctx, client) + if err != nil { + return nil, err + } + names = overrideNames(head.GetPolicy()) + } + return &ruleShowResult{Rule: newRuleView(res.GetRule(), names)}, nil +} + +func (r *ruleShowResult) RenderJSON() ([]byte, error) { + return json.MarshalIndent(r, "", " ") +} + +func (r *ruleShowResult) RenderTable() string { + v := r.Rule + now := time.Now() + removed := "active" + if v.RemovedRevision > 0 { + removed = fmt.Sprintf("removed in revision %d", v.RemovedRevision) + } + expires := v.expiresCell(now) + if v.expires != nil { + expires += " (" + v.expires.Format(time.DateOnly) + ")" + } + return cloudpolicy.KeyValues([][2]string{ + {"Rule", v.ID}, + {"Selector", v.selector()}, + {"Effect", v.Effect}, + {"Scope", cloudpolicy.EmptyDash(strings.Join(v.Scopes, ", "))}, + {"Reason", v.Reason}, + {"Ticket", cloudpolicy.EmptyDash(v.Ticket)}, + {"Requested by", cloudpolicy.EmptyDash(v.RequestedBy)}, + {"Attaches to", v.AttachesTo}, + {"Expires", expires}, + {"Created by", cloudpolicy.EmptyDash(v.CreatedBy)}, + {"Revisions", fmt.Sprintf("added in revision %d%s%s", v.AddedRevision, sep, removed)}, + }) +} + +func (r *ruleShowResult) RenderPlain() string { + v := r.Rule + return strings.Join([]string{ + clitui.PlainRow("rule_id", v.ID), + clitui.PlainRow("purl", v.Purl), + clitui.PlainRow("vers", v.Vers), + clitui.PlainRow("effect", v.Effect), + clitui.PlainRow("scopes", strings.Join(v.Scopes, ",")), + clitui.PlainRow("reason", v.Reason), + clitui.PlainRow("ticket", v.Ticket), + clitui.PlainRow("requested_by", v.RequestedBy), + clitui.PlainRow("override_id", v.OverrideID), + clitui.PlainRow("expires_at", v.ExpiresAt), + clitui.PlainRow("created_by", v.CreatedBy), + clitui.PlainRow("added_revision", fmt.Sprint(v.AddedRevision)), + clitui.PlainRow("removed_revision", fmt.Sprint(v.RemovedRevision)), + }, "\n") +} diff --git a/internal/cmd/policy/rule_test.go b/internal/cmd/policy/rule_test.go index 5933984..4037f98 100644 --- a/internal/cmd/policy/rule_test.go +++ b/internal/cmd/policy/rule_test.go @@ -358,7 +358,7 @@ func TestRunRuleUpdateAndDelete(t *testing.T) { })).Return(upd, nil) update := &policyv1.PackageRuleUpdate{} update.SetRuleId("r_77e") - res, err := runRuleUpdate(context.Background(), client, update, "m") + res, err := runRuleUpdate(context.Background(), client, update, "m", fixedNow) require.NoError(t, err) assert.Equal(t, uint64(50), res.GetRevision().GetRevision()) @@ -371,3 +371,86 @@ func TestRunRuleUpdateAndDelete(t *testing.T) { require.NoError(t, err) assert.Equal(t, uint64(51), rev) } + +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) + } +} + +func TestBuildRuleCreates_TrustExpiryLimit(t *testing.T) { + in := ruleCreateInput{Trust: true, Selector: "pkg:pypi/foo@1.0.3", Scopes: []string{"malware"}, Reason: "FP", Expires: "90d"} + _, err := buildRuleCreates(in, nil, fixedNow) + require.NoError(t, err) + + in.Expires = "91d" + _, err = buildRuleCreates(in, nil, fixedNow) + ue, ok := usefulerror.AsUsefulError(err) + require.True(t, ok) + assert.Contains(t, ue.HumanError(), "a trust entry expires at most 90 days from now") + + block := ruleCreateInput{Block: true, Selector: "pkg:npm/evil", Reason: "x", Expires: "365d"} + _, err = buildRuleCreates(block, nil, fixedNow) + require.NoError(t, err, "a block entry has no expiry limit") +} + +func TestAnnounceRuleCreate_WarnsAboutAWideSelector(t *testing.T) { + stderr := captureStderr(t) + in := ruleCreateInput{Block: true, Selector: "pkg:npm/*", Reason: "x"} + creates, err := buildRuleCreates(in, nil, fixedNow) + require.NoError(t, err) + announceRuleCreate(in, creates) + assert.Contains(t, stderr.String(), "Selector pkg:npm/* blocks every package of its ecosystem") + + stderr.Reset() + in.Selector = "pkg:npm/@acme/*" + creates, err = buildRuleCreates(in, nil, fixedNow) + require.NoError(t, err) + announceRuleCreate(in, creates) + assert.NotContains(t, stderr.String(), "every package of its ecosystem") +} + +func TestRunRuleUpdate_TrustExpiryLimit(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + res := &policyv1.GetPackageRuleResponse{} + res.SetRule(ruleWithAttributes("r_77e", corev1.Effect_EFFECT_TRUST, "")) + client.EXPECT().GetPackageRule(mock.Anything, mock.Anything).Return(res, nil) + + update := &policyv1.PackageRuleUpdate{} + update.SetRuleId("r_77e") + update.SetExpiresAt(timestamppb.New(fixedNow.Add(120 * 24 * time.Hour))) + _, err := runRuleUpdate(context.Background(), client, update, "", fixedNow) + ue, ok := usefulerror.AsUsefulError(err) + require.True(t, ok) + assert.Contains(t, ue.HumanError(), "a trust entry expires at most 90 days from now") +} + +func TestRuleList_RenderPlainEscapesServerText(t *testing.T) { + r := ruleWithAttributes("r_1", corev1.Effect_EFFECT_BLOCK, "") + r.GetRule().SetReason("IR-1\x1b[2J\tsecond column?") + res := &ruleListResult{Rules: []ruleView{newRuleView(r, nil)}} + + plain := res.RenderPlain() + assert.NotContains(t, plain, "\x1b") + 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.NotContains(t, res.RenderTable(), "\x1b") +} + +func TestMapRestoreError_MissingRevision(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().CreatePolicyChange(mock.Anything, mock.Anything).Return(nil, status.Error(codes.NotFound, "no revision")) + _, err := runChangeCreate(context.Background(), client, changeCreateInput{FromRevision: 99, PackageRules: "head"}) + ue, ok := usefulerror.AsUsefulError(err) + require.True(t, ok) + assert.Equal(t, "Policy revision 99 does not exist", ue.HumanError()) + assert.Equal(t, "List the revisions: safedep policy revision list", ue.Help()) +} diff --git a/internal/cmd/policy/rule_update.go b/internal/cmd/policy/rule_update.go new file mode 100644 index 0000000..d67ba6e --- /dev/null +++ b/internal/cmd/policy/rule_update.go @@ -0,0 +1,150 @@ +package policy + +import ( + "context" + "errors" + "fmt" + "strings" + "time" + + policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" + corev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/core/v1" + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/safedep/dry/tui" + "github.com/spf13/cobra" + "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" + clitui "github.com/safedep/cli/internal/tui" +) + +type ruleUpdateInput struct { + Reason string + Expires string + Ticket string + RequestedBy string + Message string + changed func(name string) bool +} + +func ruleUpdateCmd(a *app.App) *cobra.Command { + var in ruleUpdateInput + cmd := &cobra.Command{ + Use: "update RULE", + Short: "Change the reason, expiry, ticket or requester of a package rule", + Long: "Change a package rule and publish the change at once as a new policy revision. A rule never " + + "changes its selector, effect or trust scopes: delete it and create another. A later expiry " + + "of a trust entry loosens the policy.", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + in.changed = cmd.Flags().Changed + update, err := buildRuleUpdate(args[0], in, time.Now()) + if err != nil { + return err + } + client, err := a.ControlPlane() + if err != nil { + return err + } + res, err := runRuleUpdate(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), update, in.Message, time.Now()) + if err != nil { + return err + } + id := clitui.EscapeLine(args[0]) + msg := fmt.Sprintf("rule %s updated", id) + if update.HasExpiresAt() { + msg = fmt.Sprintf("rule %s now expires on %s", id, update.GetExpiresAt().AsTime().Format(time.DateOnly)) + } + tui.Success("%s%srevision %d published", msg, sep, res.GetRevision().GetRevision()) + return nil + }, + } + f := cmd.Flags() + f.StringVar(&in.Reason, "reason", "", "the new reason") + f.StringVar(&in.Expires, "expires", "", "the new expiry: a duration from now, as in 90d, or a date") + f.StringVar(&in.Ticket, "ticket", "", "the new ticket or incident reference") + f.StringVar(&in.RequestedBy, "requested-by", "", "the new team or person that asked for the rule") + f.StringVarP(&in.Message, "message", "m", "", "the publish message; the server writes one when it is empty") + return cmd +} + +func buildRuleUpdate(id string, in ruleUpdateInput, now time.Time) (*policyv1.PackageRuleUpdate, error) { + changed := in.changed + if changed == nil { + changed = func(string) bool { return false } + } + update := &policyv1.PackageRuleUpdate{} + update.SetRuleId(id) + set := false + if changed("reason") { + if strings.TrimSpace(in.Reason) == "" { + return nil, invalidInputError(errors.New("--reason must not be empty"), "Say why the rule exists") + } + update.SetReason(in.Reason) + set = true + } + if changed("expires") { + t, err := parseExpiry(in.Expires, now) + if err != nil { + return nil, invalidInputError(err, "Use a duration, as in 90d, or a date, as in 2027-01-26") + } + update.SetExpiresAt(timestamppb.New(t)) + set = true + } + if changed("ticket") { + update.SetTicket(in.Ticket) + set = true + } + if changed("requested-by") { + update.SetRequestedBy(in.RequestedBy) + set = true + } + if !set { + return nil, invalidInputError(errors.New("give at least one of --reason, --expires, --ticket or --requested-by"), + "As in: safedep policy rule update "+id+" --expires 90d") + } + return update, nil +} + +func runRuleUpdate( + ctx context.Context, + client policyv1grpc.PolicyServiceClient, + update *policyv1.PackageRuleUpdate, + message string, + now time.Time, +) (*policyv1.UpdatePackageRuleResponse, error) { + if update.HasExpiresAt() && update.GetExpiresAt().AsTime().Sub(now) > maxTrustExpiry { + if err := checkUpdatedTrustExpiry(ctx, client, update, now); err != nil { + return nil, err + } + } + req := &policyv1.UpdatePackageRuleRequest{} + req.SetUpdate(update) + req.SetMessage(message) + res, err := client.UpdatePackageRule(ctx, req) + if err != nil { + return nil, mapRuleError("update", update.GetRuleId(), err) + } + return res, nil +} + +// checkUpdatedTrustExpiry reads the rule, because only a trust entry has the +// 90-day limit. A block entry can expire later. +func checkUpdatedTrustExpiry( + ctx context.Context, + client policyv1grpc.PolicyServiceClient, + update *policyv1.PackageRuleUpdate, + now time.Time, +) error { + req := &policyv1.GetPackageRuleRequest{} + req.SetRuleId(update.GetRuleId()) + res, err := client.GetPackageRule(ctx, req) + if err != nil { + return mapRuleError("update", update.GetRuleId(), err) + } + if res.GetRule().GetRule().GetEffect() != corev1.Effect_EFFECT_TRUST { + return nil + } + return checkTrustExpiry(update.GetExpiresAt().AsTime(), now) +} diff --git a/internal/cmd/policy/rule_view.go b/internal/cmd/policy/rule_view.go new file mode 100644 index 0000000..e6c341b --- /dev/null +++ b/internal/cmd/policy/rule_view.go @@ -0,0 +1,82 @@ +package policy + +import ( + "fmt" + "time" + + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/safedep/dry/tui/humanize" + + "github.com/safedep/cli/internal/cloudpolicy" + "github.com/safedep/cli/internal/tui" +) + +// ruleView is the package rule that `rule list`, `rule show` and +// `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"` + 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 +} + +// newRuleView translates a rule. names maps override ids to names. A rule +// whose override is not in names shows the override id. +func newRuleView(r *policyv1.PackageRuleWithAttributes, names map[string]string) ruleView { + rule := r.GetRule() + expires := cloudpolicy.TimeOf(rule.GetExpiresAt()) + v := ruleView{ + ID: rule.GetRuleId(), + Purl: rule.GetSelector().GetPurl(), + Vers: rule.GetSelector().GetVers(), + Effect: tui.EnumToken(rule.GetEffect().String(), effectPrefix), + Scopes: scopeTokens(rule.GetScopes()), + Reason: rule.GetReason(), + Ticket: r.GetTicket(), + RequestedBy: r.GetRequestedBy(), + OverrideID: r.GetOverrideId(), + AttachesTo: baseAttachment, + CreatedBy: cloudpolicy.ActorName(r.GetCreatedBy()), + AddedRevision: r.GetAddedRevision(), + RemovedRevision: r.GetRemovedRevision(), + ExpiresAt: cloudpolicy.RFC3339(expires), + CreatedAt: cloudpolicy.RFC3339(cloudpolicy.TimeOf(r.GetCreatedAt())), + UpdatedAt: cloudpolicy.RFC3339(cloudpolicy.TimeOf(r.GetUpdatedAt())), + expires: expires, + } + if id := r.GetOverrideId(); id != "" { + v.AttachesTo = "override " + id + if name, ok := names[id]; ok { + v.AttachesTo = fmt.Sprintf("override %q", name) + } + } + return v +} + +func (v ruleView) selector() string { + if v.Vers == "" { + return v.Purl + } + return v.Purl + " " + v.Vers +} + +func (v ruleView) expiresCell(now time.Time) string { + if v.expires == nil { + return "never" + } + return humanize.Time(*v.expires, now) +} diff --git a/internal/cmd/policy/settings.go b/internal/cmd/policy/settings.go new file mode 100644 index 0000000..4687a5e --- /dev/null +++ b/internal/cmd/policy/settings.go @@ -0,0 +1,192 @@ +package policy + +import ( + "context" + "errors" + "fmt" + + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/safedep/dry/tui" + "github.com/safedep/dry/usefulerror" + "google.golang.org/protobuf/proto" + + "github.com/safedep/cli/internal/cloudpolicy" + clitui "github.com/safedep/cli/internal/tui" +) + +// editSettings opens the settings, or one policy override of them, in the +// editor and gives the whole edited document to commit. +func editSettings( + ctx context.Context, + open openEditorFunc, + start *policyv1.Policy, + header string, + overrideName string, + commit func(*policyv1.Policy) error, +) error { + if start == nil { + start = &policyv1.Policy{} + } + if err := requireKnownFields(start); err != nil { + return err + } + if overrideName == "" { + return editWholeDocument(ctx, open, start, header, commit) + } + return editOneOverride(ctx, open, start, header, overrideName, commit) +} + +func editWholeDocument( + ctx context.Context, + open openEditorFunc, + start *policyv1.Policy, + header string, + commit func(*policyv1.Policy) error, +) error { + text, err := cloudpolicy.MarshalPolicy(start, header) + if err != nil { + return err + } + unchanged := func(saved []byte) bool { + edited, err := cloudpolicy.UnmarshalPolicy(saved) + return err == nil && proto.Equal(edited, start) + } + return editLoop(ctx, open, text, unchanged, func(saved []byte) error { + edited, err := cloudpolicy.UnmarshalPolicy(saved) + if err != nil { + return retryable(err) + } + if err := checkEditedSettings(start, edited); err != nil { + return retryable(err) + } + warnComments(saved, header) + return commit(edited) + }) +} + +func editOneOverride( + ctx context.Context, + open openEditorFunc, + start *policyv1.Policy, + header string, + overrideName string, + commit func(*policyv1.Policy) error, +) error { + current, err := findOverride(start, overrideName) + if err != nil { + return err + } + text, err := cloudpolicy.MarshalOverride(current, header) + if err != nil { + return err + } + unchanged := func(saved []byte) bool { + edited, err := cloudpolicy.UnmarshalOverride(saved) + return err == nil && proto.Equal(edited, current) + } + return editLoop(ctx, open, text, unchanged, func(saved []byte) error { + edited, err := cloudpolicy.UnmarshalOverride(saved) + if err != nil { + return retryable(err) + } + full, ok := proto.Clone(start).(*policyv1.Policy) + if !ok { + return errors.New("policy edit: clone the policy") + } + overrides := full.GetOverrides() + for i, o := range overrides { + if o.GetOverrideId() == current.GetOverrideId() { + overrides[i] = edited + } + } + full.SetOverrides(overrides) + if err := checkEditedSettings(start, full); err != nil { + return retryable(err) + } + warnComments(saved, header) + return commit(full) + }) +} + +// requireKnownFields stops an edit of a policy with fields that this CLI +// does not know, because the save would drop them. +func requireKnownFields(p *policyv1.Policy) error { + err := cloudpolicy.CheckKnownFields(p) + if err == nil { + return nil + } + return usefulerror.NewUsefulError(). + WithCode(usefulerror.ErrBadRequest). + WithHumanError(err.Error() + ". An edit would drop them"). + WithHelp("Update the safedep CLI to the latest release, then run the command again"). + Wrap(err) +} + +// checkEditedSettings checks the rules that a person breaks most often in an +// edit, so the editor shows them before the RPC. The server checks every +// rule. It also warns about each policy override that the edit removes. +func checkEditedSettings(start, edited *policyv1.Policy) error { + if err := validateSettings(edited); err != nil { + return err + } + known := make(map[string]*policyv1.Override, len(start.GetOverrides())) + for _, o := range start.GetOverrides() { + known[o.GetOverrideId()] = o + } + kept := make(map[string]struct{}, len(edited.GetOverrides())) + for _, o := range edited.GetOverrides() { + id := o.GetOverrideId() + if id == "" { + continue + } + if _, ok := known[id]; !ok { + return fmt.Errorf("override %q: id %q is not in the policy. Remove the id line for a new override", + o.GetName(), id) + } + if _, dup := kept[id]; dup { + return fmt.Errorf("override %q: id %q is also the id of another override. Each id must be unique", + o.GetName(), id) + } + kept[id] = struct{}{} + } + for _, o := range start.GetOverrides() { + if _, ok := kept[o.GetOverrideId()]; !ok { + tui.Warning("This removes policy override %q (id %s). The server refuses the removal while package rules attach to it", + clitui.EscapeLine(o.GetName()), clitui.EscapeLine(o.GetOverrideId())) + } + } + return nil +} + +func validateSettings(p *policyv1.Policy) error { + names := map[string]struct{}{} + priorities := map[uint32]string{} + for i, o := range p.GetOverrides() { + if o.GetName() == "" { + return fmt.Errorf("overrides[%d]: give the override a name", i) + } + if _, dup := names[o.GetName()]; dup { + return fmt.Errorf("overrides[%d]: two overrides are named %q. Each name must be unique", i, o.GetName()) + } + names[o.GetName()] = struct{}{} + if o.GetPriority() == 0 { + return fmt.Errorf("override %q: give it a priority from 1 to 1000000", o.GetName()) + } + if other, dup := priorities[o.GetPriority()]; dup { + return fmt.Errorf("override %q: priority %d is also the priority of %q. Each priority must be unique", + o.GetName(), o.GetPriority(), other) + } + priorities[o.GetPriority()] = o.GetName() + if !o.HasSelector() { + return fmt.Errorf("override %q: give it a selector. Write selector: {} to select every subject", o.GetName()) + } + } + return nil +} + +func warnComments(saved []byte, header string) { + if cloudpolicy.HasUserComments(saved, header) { + tui.Warning("The file holds comments. The policy keeps no comments, so they are lost. " + + "Write the reason in a description field") + } +} diff --git a/internal/cmd/policy/show.go b/internal/cmd/policy/show.go index 841f483..3e53a58 100644 --- a/internal/cmd/policy/show.go +++ b/internal/cmd/policy/show.go @@ -13,6 +13,7 @@ import ( "github.com/safedep/cli/internal/app" "github.com/safedep/cli/internal/cloudpolicy" + clitui "github.com/safedep/cli/internal/tui" ) type showResult struct { @@ -171,13 +172,13 @@ func (r *showResult) RenderTable() string { expires = humanTimeCell(o.expires, now) } overrideRows = append(overrideRows, []string{ - fmt.Sprintf("%d", o.Priority), o.Name, o.Selector, expires, emptyDash(o.Description), + fmt.Sprintf("%d", o.Priority), o.Name, o.Selector, expires, cloudpolicy.EmptyDash(o.Description), }) } overrides := table.New(). Title("Overrides (priority, highest first)"). Headers("PRIORITY", "NAME", "SELECTOR", "EXPIRES", "DESCRIPTION"). - Rows(overrideRows...). + Rows(clitui.EscapeCells(overrideRows)...). EmptyMessage("No policy overrides. The policy base applies to every subject. Add one with: safedep policy edit"). Render() return cloudpolicy.KeyValues(rows) + "\n\n" + overrides @@ -185,7 +186,7 @@ func (r *showResult) RenderTable() string { func (r *showResult) RenderPlain() string { var b strings.Builder - fmt.Fprintf(&b, "tenant\t%s\n", r.Tenant) + fmt.Fprintf(&b, "tenant\t%s\n", clitui.EscapeLine(r.Tenant)) fmt.Fprintf(&b, "head_revision\t%d\n", r.HeadRevision) fmt.Fprintf(&b, "default_policy_revision\t%d\n", r.DefaultRevision) fmt.Fprintf(&b, "open_change_count\t%d\n", r.OpenChanges) @@ -193,7 +194,7 @@ func (r *showResult) RenderPlain() string { fmt.Fprintf(&b, "block_rules\t%d\n", r.BlockRules) fmt.Fprintf(&b, "trust_expiring_in_7d\t%d", r.ExpiringSoon) for _, o := range r.Overrides { - fmt.Fprintf(&b, "\noverride\t%d\t%s\t%s\t%s", o.Priority, o.Name, o.Selector, o.ExpiresAt) + b.WriteString("\n" + clitui.PlainRow("override", fmt.Sprint(o.Priority), o.Name, o.Selector, o.ExpiresAt)) } return b.String() } diff --git a/internal/cmd/policy/show_test.go b/internal/cmd/policy/show_test.go index f1b5709..5d64bbd 100644 --- a/internal/cmd/policy/show_test.go +++ b/internal/cmd/policy/show_test.go @@ -72,7 +72,7 @@ func TestRunGet(t *testing.T) { require.NoError(t, err) assert.Equal(t, uint64(46), res.Revision) assert.Contains(t, res.RenderPlain(), "# Policy settings of acme · revision 46\n") - assert.Contains(t, res.RenderTable(), "overrides:\n - name: payments") + assert.Contains(t, res.RenderTable(), "overrides:\n - id: ov_pay\n name: payments") b, err := res.RenderJSON() require.NoError(t, err) assert.Contains(t, string(b), `"revision": 46`) diff --git a/internal/cmd/policy/view.go b/internal/cmd/policy/view.go index fef1e0a..e72c795 100644 --- a/internal/cmd/policy/view.go +++ b/internal/cmd/policy/view.go @@ -9,11 +9,9 @@ import ( "time" policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" - messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" corev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/core/v1" policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" "github.com/safedep/dry/tui/humanize" - "google.golang.org/protobuf/types/known/timestamppb" "github.com/safedep/cli/internal/cloudpolicy" "github.com/safedep/cli/internal/tui" @@ -47,11 +45,11 @@ func newRevisionView(r *policyv1.PolicyRevision) *revisionView { if r == nil { return nil } - published := timeOf(r.GetPublishedAt()) + published := cloudpolicy.TimeOf(r.GetPublishedAt()) return &revisionView{ Revision: r.GetRevision(), ChangeID: r.GetChangeId(), - Author: actorName(r.GetAuthor()), + Author: cloudpolicy.ActorName(r.GetAuthor()), Message: r.GetMessage(), Source: strings.ToUpper(tui.EnumToken(r.GetSource().String(), sourcePrefix)), Direction: directionToken(r.GetDirection()), @@ -73,33 +71,15 @@ func (r *revisionView) summary(now time.Time) string { } parts = append(parts, published) if r.Message != "" { - parts = append(parts, fmt.Sprintf("%q", r.Message)) + parts = append(parts, "\""+tui.EscapeLine(r.Message)+"\"") } return strings.Join(parts, sep) } -func actorName(a *messagescontroltowerv1.Actor) string { - if a == nil { - return "" - } - if a.GetDisplayName() != "" { - return a.GetDisplayName() - } - return a.GetId() -} - func directionToken(d policyv1.ChangeDirection) string { return strings.ToUpper(tui.EnumToken(d.String(), directionPrefix)) } -func timeOf(ts *timestamppb.Timestamp) *time.Time { - if ts == nil { - return nil - } - t := ts.AsTime().UTC() - return &t -} - func humanTimeCell(t *time.Time, now time.Time) string { if t == nil { return "-" @@ -107,20 +87,6 @@ func humanTimeCell(t *time.Time, now time.Time) string { return humanize.Time(*t, now) } -func emptyDash(s string) string { - if s == "" { - return "-" - } - return s -} - -func plural(n int, singular, pluralForm string) string { - if n == 1 { - return singular - } - return pluralForm -} - // overrideView is a policy override without its values. type overrideView struct { ID string `json:"override_id"` @@ -137,7 +103,7 @@ type overrideView struct { func overrideViews(p *policyv1.Policy) []overrideView { out := make([]overrideView, 0, len(p.GetOverrides())) for _, o := range p.GetOverrides() { - expires := timeOf(o.GetExpiresAt()) + expires := cloudpolicy.TimeOf(o.GetExpiresAt()) out = append(out, overrideView{ ID: o.GetOverrideId(), Name: o.GetName(), diff --git a/internal/cmd/project/inventory.go b/internal/cmd/project/inventory.go index 71743bc..f049109 100644 --- a/internal/cmd/project/inventory.go +++ b/internal/cmd/project/inventory.go @@ -32,18 +32,6 @@ type projectListInput struct { PageToken string } -type projectView struct { - ID string `json:"project_id"` - Name string `json:"name"` - Source string `json:"source"` - OriginURL string `json:"origin_url,omitempty"` - Labels []string `json:"labels"` - Vulnerabilities *uint32 `json:"vulnerabilities,omitempty"` - PolicyViolations *uint32 `json:"policy_violations,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - created *time.Time -} - type projectListResult struct { Projects []projectView `json:"projects"` NextPageToken string `json:"next_page_token,omitempty"` @@ -57,7 +45,7 @@ func projectListCmd(a *app.App) *cobra.Command { Long: "List the projects of the tenant with their labels. --selector takes a label selector, as a " + "policy override does, so you can see which projects an override selects: " + "key=value, key!=value, key in (a,b), key notin (a,b), key or !key, separated by commas. " + - "The terms AND together. One page is returned per invocation, so follow --page-token to read " + + "The terms AND together. The command reads one page. Pass --page-token to read " + "the next page.", Args: func(cmd *cobra.Command, args []string) error { if err := cobra.NoArgs(cmd, args); err != nil { @@ -150,30 +138,6 @@ func runProjectList(ctx context.Context, client listProjectsClient, in projectLi return out, nil } -func newProjectView(p *controltowerv1.ProjectWithAttributes) projectView { - project := p.GetProject() - attrs := p.GetAttributes() - v := projectView{ - ID: project.GetProjectId(), - Name: project.GetName(), - Source: tui.EnumToken(project.GetSource().String(), projectSourcePrefix), - OriginURL: project.GetOriginUrl(), - Labels: cloudpolicy.FormatLabels(attrs.GetLabels()), - } - if attrs.HasVulnerabilities() { - v.Vulnerabilities = new(attrs.GetVulnerabilities()) - } - if attrs.HasPolicyViolations() { - v.PolicyViolations = new(attrs.GetPolicyViolations()) - } - if ts := project.GetCreatedAt(); ts != nil { - t := ts.AsTime().UTC() - v.created = &t - v.CreatedAt = t.Format(time.RFC3339) - } - return v -} - func (r *projectListResult) RenderJSON() ([]byte, error) { return json.MarshalIndent(r, "", " ") } @@ -197,7 +161,7 @@ func (r *projectListResult) RenderTable() string { t := table.New(). Title("Projects"). Headers("PROJECT", "SOURCE", "LABELS", "VULNS", "VIOLATIONS", "CREATED"). - Rows(rows...). + Rows(tui.EscapeCells(rows)...). EmptyMessage("No projects match. Sync repositories with: safedep project sync") if len(rows) > 0 { footer := fmt.Sprintf("%d %s", len(rows), pluralProjects(len(rows))) @@ -213,8 +177,8 @@ func (r *projectListResult) RenderPlain() string { var b strings.Builder b.WriteString("project_id\tname\tsource\tlabels\tvulnerabilities\tpolicy_violations\tcreated_at") for _, p := range r.Projects { - fmt.Fprintf(&b, "\n%s\t%s\t%s\t%s\t%s\t%s\t%s", p.ID, p.Name, p.Source, strings.Join(p.Labels, ","), - countCell(p.Vulnerabilities), countCell(p.PolicyViolations), p.CreatedAt) + b.WriteString("\n" + tui.PlainRow(p.ID, p.Name, p.Source, strings.Join(p.Labels, ","), + countCell(p.Vulnerabilities), countCell(p.PolicyViolations), p.CreatedAt)) } return b.String() } diff --git a/internal/cmd/project/policy_test.go b/internal/cmd/project/policy_test.go index abffb7a..81b48e6 100644 --- a/internal/cmd/project/policy_test.go +++ b/internal/cmd/project/policy_test.go @@ -226,3 +226,19 @@ func TestRequireProjects(t *testing.T) { assert.ErrorContains(t, requireProjects(labelInput{}), "give at least one project") assert.ErrorContains(t, requireProjects(labelInput{Names: []string{"a", "a"}}), `duplicate project name "a"`) } + +func TestRunProjectList_EscapesLabelValues(t *testing.T) { + client := &fakeListProjectsClient{listFn: func(*controltowerv1.ListProjectsRequest) (*controltowerv1.ListProjectsResponse, error) { + return projectsResponse(labeledProject("p_1", "acme/x", messagescontroltowerv1.Project_SOURCE_GITHUB, + map[string]string{"custom/team": "pay\x1b[31m\u202e"})), nil + }} + got, err := runProjectList(context.Background(), client, projectListInput{}) + require.NoError(t, err) + for _, out := range []string{got.RenderTable(), got.RenderPlain()} { + assert.NotContains(t, out, "\x1b") + assert.Contains(t, out, `custom/team=pay\x1b[31m\u202e`) + } + b, err := got.RenderJSON() + require.NoError(t, err) + assert.Contains(t, string(b), `\u001b[31m`, "JSON keeps the raw value") +} diff --git a/internal/cmd/project/show.go b/internal/cmd/project/show.go index 67e4868..f96a3bc 100644 --- a/internal/cmd/project/show.go +++ b/internal/cmd/project/show.go @@ -16,6 +16,7 @@ import ( "github.com/safedep/cli/internal/app" "github.com/safedep/cli/internal/cloudpolicy" + clitui "github.com/safedep/cli/internal/tui" ) type projectShowResult struct { @@ -96,7 +97,7 @@ func runShow( if err != nil { // The project data is still useful when the policy service does not // answer, so the command warns and shows the rest. - tui.Warning("Could not read the policy of project %s: %v", name, err) + tui.Warning("Could not read the policy of project %s: %s", clitui.EscapeLine(name), clitui.EscapeLine(err.Error())) return out, nil } out.Policy = policy @@ -140,20 +141,29 @@ func (r *projectShowResult) RenderTable() string { if p.created != nil { created = humanize.Time(*p.created, time.Now()) } - labels := strings.Join(p.Labels, "\n") - if labels == "" { - labels = "-" - } - return cloudpolicy.KeyValues([][2]string{ + rows := [][2]string{ {"Project", p.Name}, {"ID", p.ID}, {"Source", source}, - {"Labels", labels}, + } + labels := p.Labels + if len(labels) == 0 { + labels = []string{"-"} + } + for i, l := range labels { + key := "" + if i == 0 { + key = "Labels" + } + rows = append(rows, [2]string{key, l}) + } + rows = append(rows, [][2]string{ {"Policy", r.policyLine()}, {"Vulnerabilities", countCell(p.Vulnerabilities)}, {"Violations", countCell(p.PolicyViolations)}, {"Created", created}, - }) + "\n\nPolicy of each field: safedep project policy show " + p.Name + }...) + return cloudpolicy.KeyValues(rows) + "\n\nPolicy of each field: safedep project policy show " + clitui.EscapeLine(p.Name) } func (r *projectShowResult) RenderPlain() string { @@ -163,12 +173,12 @@ func (r *projectShowResult) RenderPlain() string { policy = fmt.Sprintf("%d", r.Policy.Revision) } return strings.Join([]string{ - "project_id\t" + p.ID, - "name\t" + p.Name, - "source\t" + p.Source, - "origin_url\t" + p.OriginURL, - "labels\t" + strings.Join(p.Labels, ","), - "policy_revision\t" + policy, - "created_at\t" + p.CreatedAt, + clitui.PlainRow("project_id", p.ID), + clitui.PlainRow("name", p.Name), + clitui.PlainRow("source", p.Source), + clitui.PlainRow("origin_url", p.OriginURL), + clitui.PlainRow("labels", strings.Join(p.Labels, ",")), + clitui.PlainRow("policy_revision", policy), + clitui.PlainRow("created_at", p.CreatedAt), }, "\n") } diff --git a/internal/cmd/project/view.go b/internal/cmd/project/view.go new file mode 100644 index 0000000..af89a45 --- /dev/null +++ b/internal/cmd/project/view.go @@ -0,0 +1,46 @@ +package project + +import ( + "time" + + controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" + + "github.com/safedep/cli/internal/cloudpolicy" + "github.com/safedep/cli/internal/tui" +) + +type projectView struct { + ID string `json:"project_id"` + Name string `json:"name"` + Source string `json:"source"` + OriginURL string `json:"origin_url,omitempty"` + Labels []string `json:"labels"` + Vulnerabilities *uint32 `json:"vulnerabilities,omitempty"` + PolicyViolations *uint32 `json:"policy_violations,omitempty"` + CreatedAt string `json:"created_at,omitempty"` + created *time.Time +} + +func newProjectView(p *controltowerv1.ProjectWithAttributes) projectView { + project := p.GetProject() + attrs := p.GetAttributes() + v := projectView{ + ID: project.GetProjectId(), + Name: project.GetName(), + Source: tui.EnumToken(project.GetSource().String(), projectSourcePrefix), + OriginURL: project.GetOriginUrl(), + Labels: cloudpolicy.FormatLabels(attrs.GetLabels()), + } + if attrs.HasVulnerabilities() { + v.Vulnerabilities = new(attrs.GetVulnerabilities()) + } + if attrs.HasPolicyViolations() { + v.PolicyViolations = new(attrs.GetPolicyViolations()) + } + if ts := project.GetCreatedAt(); ts != nil { + t := ts.AsTime().UTC() + v.created = &t + v.CreatedAt = t.Format(time.RFC3339) + } + return v +} diff --git a/internal/cmd/subscription/service.go b/internal/cmd/subscription/service.go index f32b82b..f0bdb54 100644 --- a/internal/cmd/subscription/service.go +++ b/internal/cmd/subscription/service.go @@ -11,8 +11,8 @@ import ( msgv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" errorv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/error/v1" ctv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" - "github.com/safedep/cli/internal/rpcerror" "github.com/safedep/cli/internal/tui" + "github.com/safedep/dry/usefulerror" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -499,7 +499,7 @@ func catalogFromProto(pb *msgv1.BillingCatalog) *Catalog { // an actionable message naming the next command, matching the on-demand enable // path. func mapAddOnAttachError(err error) error { - switch rpcerror.Reason(err) { + switch reason, _ := usefulerror.ReasonOf(err); reason { case errorv1.ErrorReason_ERROR_REASON_ENTITLEMENT_NOT_AVAILABLE: return errors.New("add-ons need an active paid plan: subscribe first with `safedep subscription create`") case errorv1.ErrorReason_ERROR_REASON_SUBSCRIPTION_PAST_DUE: @@ -527,7 +527,7 @@ func mapCheckoutError(err error) error { // mapOnDemandEnableError routes the typed ErrorReason to an actionable // message so the user knows the next command to run. func mapOnDemandEnableError(err error) error { - switch rpcerror.Reason(err) { + switch reason, _ := usefulerror.ReasonOf(err); reason { case errorv1.ErrorReason_ERROR_REASON_ENTITLEMENT_NOT_AVAILABLE: return errors.New("on-demand billing needs a paid plan: subscribe first with `safedep subscription create`") case errorv1.ErrorReason_ERROR_REASON_PAYMENT_METHOD_REQUIRED: diff --git a/internal/rpcerror/rpcerror.go b/internal/rpcerror/rpcerror.go deleted file mode 100644 index 2881e89..0000000 --- a/internal/rpcerror/rpcerror.go +++ /dev/null @@ -1,24 +0,0 @@ -// Package rpcerror reads the SafeDep business reason of a gRPC error. Every -// command package that maps a reason to a recovery reads it here. -package rpcerror - -import ( - errorv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/error/v1" - "google.golang.org/grpc/status" -) - -// Reason returns the ErrorReason of the ErrorDetail in a gRPC status error. -// It returns ERROR_REASON_UNSPECIFIED when the error has no such detail, so a -// caller falls back to the status code. -func Reason(err error) errorv1.ErrorReason { - st, ok := status.FromError(err) - if !ok { - return errorv1.ErrorReason_ERROR_REASON_UNSPECIFIED - } - for _, d := range st.Details() { - if detail, ok := d.(*errorv1.ErrorDetail); ok { - return detail.GetReason() - } - } - return errorv1.ErrorReason_ERROR_REASON_UNSPECIFIED -} diff --git a/internal/rpcerror/rpcerror_test.go b/internal/rpcerror/rpcerror_test.go deleted file mode 100644 index 0a84bc4..0000000 --- a/internal/rpcerror/rpcerror_test.go +++ /dev/null @@ -1,32 +0,0 @@ -package rpcerror - -import ( - "errors" - "testing" - - errorv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/error/v1" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" -) - -func TestReason(t *testing.T) { - detail := &errorv1.ErrorDetail{} - detail.SetReason(errorv1.ErrorReason_ERROR_REASON_POLICY_CHANGE_STALE) - st, err := status.New(codes.Aborted, "stale").WithDetails(detail) - require.NoError(t, err) - - tests := []struct { - name string - err error - want errorv1.ErrorReason - }{ - {"detail", st.Err(), errorv1.ErrorReason_ERROR_REASON_POLICY_CHANGE_STALE}, - {"status without detail", status.Error(codes.Aborted, "x"), errorv1.ErrorReason_ERROR_REASON_UNSPECIFIED}, - {"not a status", errors.New("x"), errorv1.ErrorReason_ERROR_REASON_UNSPECIFIED}, - } - for _, tt := range tests { - assert.Equal(t, tt.want, Reason(tt.err), tt.name) - } -} diff --git a/internal/tui/escape.go b/internal/tui/escape.go new file mode 100644 index 0000000..562269e --- /dev/null +++ b/internal/tui/escape.go @@ -0,0 +1,112 @@ +package tui + +import ( + "fmt" + "strings" + "unicode" + "unicode/utf8" +) + +// Text from SafeDep Cloud, such as a label that an endpoint sent or the +// reason of a package rule, can hold escape sequences that move the cursor, +// change the window title or hide text. Every table and plain renderer +// passes such text through these helpers. JSON output stays raw, because the +// JSON encoder escapes control characters itself. dry/tui has no escape +// helper yet, so the CLI keeps one here, with the API of vet's +// internal/tui/escape. + +// EscapeLine returns s as one line. It shows each control character, line +// breaks and tabs included, and each bidirectional format character as an +// escape, for example \n, \x1b or \u202e. Invalid UTF-8 becomes U+FFFD. +func EscapeLine(s string) string { + return escape(s, false) +} + +// EscapeText returns s with its line breaks kept. It escapes every other +// control character and each bidirectional format character. +func EscapeText(s string) string { + return escape(s, true) +} + +// EscapeCells escapes each cell of each table row as one line. +func EscapeCells(rows [][]string) [][]string { + out := make([][]string, len(rows)) + for i, row := range rows { + out[i] = make([]string, len(row)) + for j, cell := range row { + out[i][j] = EscapeLine(cell) + } + } + return out +} + +// PlainRow escapes each field as one line and joins the fields with tabs, so +// a tab or a line break in a value never adds a column or a row. +func PlainRow(fields ...string) string { + escaped := make([]string, len(fields)) + for i, f := range fields { + escaped[i] = EscapeLine(f) + } + return strings.Join(escaped, "\t") +} + +func escape(s string, keepNewlines bool) string { + if isSafe(s, keepNewlines) { + return s + } + var b strings.Builder + b.Grow(len(s) + 8) + for _, r := range s { + switch { + case r == '\n' && keepNewlines: + b.WriteRune(r) + case r == '\n': + b.WriteString(`\n`) + case r == '\r': + b.WriteString(`\r`) + case r == '\t': + b.WriteString(`\t`) + case r == unicode.ReplacementChar: + b.WriteRune(r) + case r < 0x20 || r == 0x7f: + fmt.Fprintf(&b, `\x%02x`, r) + case unsafeRune(r): + fmt.Fprintf(&b, `\u%04x`, r) + default: + b.WriteRune(r) + } + } + return b.String() +} + +func isSafe(s string, keepNewlines bool) bool { + if !utf8.ValidString(s) { + return false + } + for _, r := range s { + if r == '\n' && keepNewlines { + continue + } + if r < 0x20 || r == 0x7f || unsafeRune(r) { + return false + } + } + return true +} + +// unsafeRune reports a C1 control character or a bidirectional format +// character. A bidirectional override can show text in another order than +// the bytes, as in the "Trojan Source" attack. +func unsafeRune(r rune) bool { + switch { + case r >= 0x80 && r <= 0x9f: + return true + case r == 0x061c, r == 0x200e, r == 0x200f: + return true + case r >= 0x202a && r <= 0x202e: + return true + case r >= 0x2066 && r <= 0x2069: + return true + } + return false +} diff --git a/internal/tui/escape_test.go b/internal/tui/escape_test.go new file mode 100644 index 0000000..6467fc6 --- /dev/null +++ b/internal/tui/escape_test.go @@ -0,0 +1,33 @@ +package tui + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestEscape(t *testing.T) { + cases := []struct { + name, in, line, text string + }{ + {name: "plain text", in: "pkg:npm/left-pad@1.3.0", line: "pkg:npm/left-pad@1.3.0", text: "pkg:npm/left-pad@1.3.0"}, + {name: "unicode", in: "naïve · 日本", line: "naïve · 日本", text: "naïve · 日本"}, + {name: "line breaks", in: "a\nb\r\tc", line: `a\nb\r\tc`, text: "a\nb\\r\\tc"}, + {name: "ansi sequence", in: "evil\x1b[2J\x1b]0;title\x07", line: `evil\x1b[2J\x1b]0;title\x07`, text: `evil\x1b[2J\x1b]0;title\x07`}, + {name: "c1 control", in: "a\u009bb", line: `a\u009bb`, text: `a\u009bb`}, + {name: "bidi override", in: "admin\u202e\u2066txt", line: `admin\u202e\u2066txt`, text: `admin\u202e\u2066txt`}, + {name: "delete", in: "a\x7fb", line: `a\x7fb`, text: `a\x7fb`}, + {name: "invalid utf-8", in: "a\xffb", line: "a�b", text: "a�b"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.line, EscapeLine(tc.in)) + assert.Equal(t, tc.text, EscapeText(tc.in)) + }) + } +} + +func TestPlainRowAndEscapeCells(t *testing.T) { + assert.Equal(t, `a\tb`+"\t"+`c\nd`, PlainRow("a\tb", "c\nd")) + assert.Equal(t, [][]string{{`x\x1b[31m`, "y"}}, EscapeCells([][]string{{"x\x1b[31m", "y"}})) +} From 939daf586c832cdeaa492b11c29963817bf1e72b Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 31 Oct 2026 08:55:32 +0000 Subject: [PATCH 04/17] fix(policy): use one policy snapshot for rule list, keep fractional times Two problems from the review of #67: - rule list --at-revision N --override NAME resolved the name against head, not revision N. An override that a later revision renamed or removed failed, and a reused name filtered by the wrong id. The command now reads the policy at --at-revision once, and uses that one snapshot for the override lookup and for the names of the attached overrides. - The YAML wrote a timestamp with RFC 3339, which drops fractional seconds. An expires_at with a fraction then failed the no-change check, so policy edit made a draft with a truncated expiry. The YAML now writes RFC 3339 with nanoseconds, which omits a zero fraction. The decoder accepts both forms. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MhRi597EX9odoSDXbVBsxz --- internal/cloudpolicy/document_test.go | 16 +++++++++++++ internal/cloudpolicy/fields.go | 2 +- internal/cloudpolicy/protoyaml.go | 5 +++- internal/cmd/policy/rule_list.go | 33 +++++++++++++++++++++------ internal/cmd/policy/rule_test.go | 26 +++++++++++++++++++++ 5 files changed, 73 insertions(+), 9 deletions(-) diff --git a/internal/cloudpolicy/document_test.go b/internal/cloudpolicy/document_test.go index 878e123..2ba3a29 100644 --- a/internal/cloudpolicy/document_test.go +++ b/internal/cloudpolicy/document_test.go @@ -240,3 +240,19 @@ func TestPolicyMap(t *testing.T) { require.True(t, ok) assert.Equal(t, map[string]any{"fail_on": "high"}, base["scan_gate"]) } + +func TestOverrideExpiry_KeepsFractionalSeconds(t *testing.T) { + p := samplePolicy() + expires := time.Date(2027, 1, 26, 10, 30, 0, 123456789, time.UTC) + p.GetOverrides()[0].SetExpiresAt(timestamppb.New(expires)) + p.GetOverrides()[1].SetExpiresAt(timestamppb.New(time.Date(2027, 2, 1, 0, 0, 0, 0, time.UTC))) + + b, err := MarshalPolicy(p, "") + require.NoError(t, err) + assert.Contains(t, string(b), "expires_at: 2027-01-26T10:30:00.123456789Z") + assert.Contains(t, string(b), "expires_at: 2027-02-01T00:00:00Z", "a zero fraction stays out") + + got, err := UnmarshalPolicy(b) + require.NoError(t, err) + assert.True(t, proto.Equal(p, got), "an edit with no change must not change the expiry") +} diff --git a/internal/cloudpolicy/fields.go b/internal/cloudpolicy/fields.go index e4231ed..9529a78 100644 --- a/internal/cloudpolicy/fields.go +++ b/internal/cloudpolicy/fields.go @@ -180,7 +180,7 @@ func formatSingular(fd protoreflect.FieldDescriptor, v protoreflect.Value) (stri return duration.Format(d), humanDuration(d) case *timestamppb.Timestamp: t := msg.AsTime().UTC() - return t.Format(time.RFC3339), humanize.Time(t, time.Now()) + return t.Format(time.RFC3339Nano), humanize.Time(t, time.Now()) default: text := fmt.Sprint(v.Message().Interface()) return text, text diff --git a/internal/cloudpolicy/protoyaml.go b/internal/cloudpolicy/protoyaml.go index d7c48a3..ae6cd77 100644 --- a/internal/cloudpolicy/protoyaml.go +++ b/internal/cloudpolicy/protoyaml.go @@ -136,7 +136,10 @@ func (c *yamlCodec) formatWellKnown(m protoreflect.Message) string { case *durationpb.Duration: return duration.Format(msg.AsDuration()) case *timestamppb.Timestamp: - return msg.AsTime().UTC().Format(time.RFC3339) + // RFC3339Nano keeps fractional seconds and omits a zero fraction. + // RFC3339 drops them, and an edit with no change would then send a + // truncated time. + return msg.AsTime().UTC().Format(time.RFC3339Nano) default: return "" } diff --git a/internal/cmd/policy/rule_list.go b/internal/cmd/policy/rule_list.go index 637622e..b7d59ec 100644 --- a/internal/cmd/policy/rule_list.go +++ b/internal/cmd/policy/rule_list.go @@ -78,20 +78,38 @@ func ruleListCmd(a *app.App) *cobra.Command { return cmd } +// runRuleList reads the policy at --at-revision, or at head, once, and uses +// that one snapshot to resolve --override and to name the policy overrides +// of the rules. An override that a later revision renamed or removed then +// still resolves, and a reused name never selects the wrong override. func runRuleList(ctx context.Context, client policyv1grpc.PolicyServiceClient, in *ruleListInput) (*ruleListResult, error) { - var names map[string]string + var snapshot *policyv1.Policy + loadSnapshot := func() (*policyv1.Policy, error) { + if snapshot != nil { + return snapshot, nil + } + _, p, err := readPolicyAt(ctx, client, in.AtRevision) + if err != nil { + return nil, err + } + if p == nil { + p = &policyv1.Policy{} + } + snapshot = p + return p, nil + } + overrideID := "" if in.Override != "" { - head, err := getPolicy(ctx, client) + p, err := loadSnapshot() if err != nil { return nil, err } - o, err := findOverride(head.GetPolicy(), in.Override) + o, err := findOverride(p, in.Override) if err != nil { return nil, err } overrideID = o.GetOverrideId() - names = overrideNames(head.GetPolicy()) } filters, err := ruleListFilters(in, overrideID) if err != nil { @@ -107,12 +125,13 @@ func runRuleList(ctx context.Context, client policyv1grpc.PolicyServiceClient, i return nil, fmt.Errorf("policy rule list: %w", err) } - if names == nil && attachesToOverride(res.GetRules()) { - head, err := getPolicy(ctx, client) + var names map[string]string + if in.Override != "" || attachesToOverride(res.GetRules()) { + p, err := loadSnapshot() if err != nil { return nil, err } - names = overrideNames(head.GetPolicy()) + names = overrideNames(p) } out := &ruleListResult{ Rules: make([]ruleView, 0, len(res.GetRules())), diff --git a/internal/cmd/policy/rule_test.go b/internal/cmd/policy/rule_test.go index 4037f98..2049db7 100644 --- a/internal/cmd/policy/rule_test.go +++ b/internal/cmd/policy/rule_test.go @@ -454,3 +454,29 @@ func TestMapRestoreError_MissingRevision(t *testing.T) { assert.Equal(t, "Policy revision 99 does not exist", ue.HumanError()) assert.Equal(t, "List the revisions: safedep policy revision list", ue.Help()) } + +func TestRunRuleList_AtRevisionResolvesTheOverrideAtThatRevision(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + // At revision 40 the override ov_pay had the name "payments-old". Head + // renamed it, so a lookup at head would fail. The test sets no GetPolicy + // expectation, so a read of head fails the test. + old := headPolicy() + old.GetOverrides()[0].SetName("payments-old") + rev := &policyv1.GetPolicyRevisionResponse{} + rev.SetRevision(revision(40, "old")) + rev.SetPolicy(old) + client.EXPECT().GetPolicyRevision(mock.Anything, mock.MatchedBy(func(r *policyv1.GetPolicyRevisionRequest) bool { + return r.GetRevision() == 40 + })).Return(rev, nil).Once() + + res := &policyv1.ListPackageRulesResponse{} + res.SetRules([]*policyv1.PackageRuleWithAttributes{ruleWithAttributes("r_77e", corev1.Effect_EFFECT_TRUST, "ov_pay")}) + client.EXPECT().ListPackageRules(mock.Anything, mock.MatchedBy(func(r *policyv1.ListPackageRulesRequest) bool { + return r.GetFilters().GetOverrideId() == "ov_pay" && r.GetFilters().GetAtRevision() == 40 + })).Return(res, nil) + + got, err := runRuleList(context.Background(), client, &ruleListInput{AtRevision: 40, Override: "payments-old"}) + require.NoError(t, err) + require.Len(t, got.Rules, 1) + assert.Equal(t, `override "payments-old"`, got.Rules[0].AttachesTo) +} From 9429773821d3d59f2277f467d7501d8cf4cae5c1 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 31 Oct 2026 10:21:34 +0000 Subject: [PATCH 05/17] ci: skip the PMG cooldown for the SafeDep API SDK and dry The PMG cooldown of 2 days blocked the SafeDep API SDK that BSR built right after the API merge, so release-preflight failed. SafeDep publishes these modules, so the cooldown adds no protection for them. PMG still runs malware analysis on them. control-tower and malysis skip the same modules. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MhRi597EX9odoSDXbVBsxz --- .github/pmg/config.yml | 19 +++++++++++++++++++ .github/workflows/ci.yml | 2 ++ .github/workflows/goreleaser.yml | 2 ++ 3 files changed, 23 insertions(+) create mode 100644 .github/pmg/config.yml diff --git a/.github/pmg/config.yml b/.github/pmg/config.yml new file mode 100644 index 0000000..13b5622 --- /dev/null +++ b/.github/pmg/config.yml @@ -0,0 +1,19 @@ +# PMG settings for the CI jobs of this repository. ci.yml and goreleaser.yml +# pass this file to safedep/pmg as config-file. PMG reads the keys that this +# file does not set from its own template. +dependency_cooldown: + enabled: true + days: 2 + # SafeDep publishes these modules. The SDK bump takes the build that BSR + # makes right after an API merge, and the cooldown would block that build. + # PMG still runs malware analysis on them. control-tower and malysis skip + # the same modules. + skip: + - purl: pkg:golang/buf.build/gen/go/safedep/api/connectrpc/go + reason: "SafeDep API SDK, generated by BSR" + - purl: pkg:golang/buf.build/gen/go/safedep/api/grpc/go + reason: "SafeDep API SDK, generated by BSR" + - purl: pkg:golang/buf.build/gen/go/safedep/api/protocolbuffers/go + reason: "SafeDep API SDK, generated by BSR" + - purl: pkg:golang/github.com/safedep/dry + reason: "SafeDep shared library" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e090327..0d1823e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -67,6 +67,8 @@ jobs: api-key: ${{ secrets.SAFEDEP_CLOUD_API_KEY }} tenant-id: ${{ secrets.SAFEDEP_CLOUD_TENANT_DOMAIN }} endpoint-id: CICD_GHA_SAFEDEP_CLI + # The cooldown and its skip list. The path is relative to the checkout. + config-file: .github/pmg/config.yml - name: Install dependencies run: pnpm install --frozen-lockfile diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 28a75dd..95ddc09 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -48,6 +48,8 @@ jobs: api-key: ${{ secrets.SAFEDEP_CLOUD_API_KEY }} tenant-id: ${{ secrets.SAFEDEP_CLOUD_TENANT_DOMAIN }} endpoint-id: CICD_GHA_SAFEDEP_CLI + # The cooldown and its skip list. The path is relative to the checkout. + config-file: .github/pmg/config.yml - name: Install dependencies run: pnpm install --frozen-lockfile From 18da4bb243ae66349e1fb9fde949bd10fec82896 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Wed, 4 Nov 2026 18:41:32 +0000 Subject: [PATCH 06/17] chore(deps): bump the SafeDep API SDK for ListPolicyDecisions The policy decision log needs the RPC ListPolicyDecisions of PolicyService. The API build 20261104174030-9113dd6a8ea6 adds it. The regenerated PolicyServiceClient mock gets the new method. The same build moves GitRef to safedep.messages.scm.v1. The CLI does not use GitRef, so no other code changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MhRi597EX9odoSDXbVBsxz --- go.mod | 4 +- go.sum | 8 +- .../mocks/PolicyServiceClient_mock.go | 83 +++++++++++++++++++ 3 files changed, 89 insertions(+), 6 deletions(-) diff --git a/go.mod b/go.mod index a431329..a54d020 100644 --- a/go.mod +++ b/go.mod @@ -3,8 +3,8 @@ module github.com/safedep/cli go 1.26.2 require ( - buf.build/gen/go/safedep/api/grpc/go v1.6.2-20261031065119-dc85a10c2beb.1 - buf.build/gen/go/safedep/api/protocolbuffers/go v1.36.12-20261031065119-dc85a10c2beb.2 + buf.build/gen/go/safedep/api/grpc/go v1.6.2-20261104174030-9113dd6a8ea6.1 + buf.build/gen/go/safedep/api/protocolbuffers/go v1.36.12-20261104174030-9113dd6a8ea6.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 44bdf97..65baad8 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-20261031065119-dc85a10c2beb.1 h1:GFuHP+IKmox25L8V2EF4CR3rblReLuKjZCnuOuR7dc4= -buf.build/gen/go/safedep/api/grpc/go v1.6.2-20261031065119-dc85a10c2beb.1/go.mod h1:wVMcwuJdlWZbHcwPPepDJQR1zQDjh/ANlc7Zv0BDfiI= -buf.build/gen/go/safedep/api/protocolbuffers/go v1.36.12-20261031065119-dc85a10c2beb.2 h1:1p9CC/GyQ5POTKPtFvl+48Fk+37rQl/zbAOd1PDDabE= -buf.build/gen/go/safedep/api/protocolbuffers/go v1.36.12-20261031065119-dc85a10c2beb.2/go.mod h1:LfbopTmazyAppwhYT2vdRDLDH8ZTm4QNbp9yFjGRbHs= +buf.build/gen/go/safedep/api/grpc/go v1.6.2-20261104174030-9113dd6a8ea6.1 h1:oKI0awI3q9Ft7eISQzAknDpHx9gDUrFa9Qe4/5+1d+g= +buf.build/gen/go/safedep/api/grpc/go v1.6.2-20261104174030-9113dd6a8ea6.1/go.mod h1:hpgi3VWa8hReWhVtNpPAjWsU4TPf+lYozGgjrHggWhw= +buf.build/gen/go/safedep/api/protocolbuffers/go v1.36.12-20261104174030-9113dd6a8ea6.2 h1:zpGu3bDWbHdBkUgeSt45/O/38JbZMEvn55nEf30u5qg= +buf.build/gen/go/safedep/api/protocolbuffers/go v1.36.12-20261104174030-9113dd6a8ea6.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/mocks/PolicyServiceClient_mock.go b/internal/cloudpolicy/mocks/PolicyServiceClient_mock.go index 4979e96..34b844b 100644 --- a/internal/cloudpolicy/mocks/PolicyServiceClient_mock.go +++ b/internal/cloudpolicy/mocks/PolicyServiceClient_mock.go @@ -1035,6 +1035,89 @@ func (_c *PolicyServiceClientMock_ListPolicyChanges_Call) RunAndReturn(run func( return _c } +// ListPolicyDecisions provides a mock function for the type PolicyServiceClientMock +func (_mock *PolicyServiceClientMock) ListPolicyDecisions(ctx context.Context, in *policyv1.ListPolicyDecisionsRequest, opts ...grpc.CallOption) (*policyv1.ListPolicyDecisionsResponse, error) { + var tmpRet mock.Arguments + if len(opts) > 0 { + tmpRet = _mock.Called(ctx, in, opts) + } else { + tmpRet = _mock.Called(ctx, in) + } + ret := tmpRet + + if len(ret) == 0 { + panic("no return value specified for ListPolicyDecisions") + } + + var r0 *policyv1.ListPolicyDecisionsResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.ListPolicyDecisionsRequest, ...grpc.CallOption) (*policyv1.ListPolicyDecisionsResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *policyv1.ListPolicyDecisionsRequest, ...grpc.CallOption) *policyv1.ListPolicyDecisionsResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*policyv1.ListPolicyDecisionsResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *policyv1.ListPolicyDecisionsRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// PolicyServiceClientMock_ListPolicyDecisions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListPolicyDecisions' +type PolicyServiceClientMock_ListPolicyDecisions_Call struct { + *mock.Call +} + +// ListPolicyDecisions is a helper method to define mock.On call +// - ctx context.Context +// - in *policyv1.ListPolicyDecisionsRequest +// - opts ...grpc.CallOption +func (_e *PolicyServiceClientMock_Expecter) ListPolicyDecisions(ctx interface{}, in interface{}, opts ...interface{}) *PolicyServiceClientMock_ListPolicyDecisions_Call { + return &PolicyServiceClientMock_ListPolicyDecisions_Call{Call: _e.mock.On("ListPolicyDecisions", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *PolicyServiceClientMock_ListPolicyDecisions_Call) Run(run func(ctx context.Context, in *policyv1.ListPolicyDecisionsRequest, opts ...grpc.CallOption)) *PolicyServiceClientMock_ListPolicyDecisions_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *policyv1.ListPolicyDecisionsRequest + if args[1] != nil { + arg1 = args[1].(*policyv1.ListPolicyDecisionsRequest) + } + var arg2 []grpc.CallOption + var variadicArgs []grpc.CallOption + if len(args) > 2 { + variadicArgs = args[2].([]grpc.CallOption) + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *PolicyServiceClientMock_ListPolicyDecisions_Call) Return(listPolicyDecisionsResponse *policyv1.ListPolicyDecisionsResponse, err error) *PolicyServiceClientMock_ListPolicyDecisions_Call { + _c.Call.Return(listPolicyDecisionsResponse, err) + return _c +} + +func (_c *PolicyServiceClientMock_ListPolicyDecisions_Call) RunAndReturn(run func(ctx context.Context, in *policyv1.ListPolicyDecisionsRequest, opts ...grpc.CallOption) (*policyv1.ListPolicyDecisionsResponse, error)) *PolicyServiceClientMock_ListPolicyDecisions_Call { + _c.Call.Return(run) + return _c +} + // ListPolicyRevisions provides a mock function for the type PolicyServiceClientMock func (_mock *PolicyServiceClientMock) ListPolicyRevisions(ctx context.Context, in *policyv1.ListPolicyRevisionsRequest, opts ...grpc.CallOption) (*policyv1.ListPolicyRevisionsResponse, error) { var tmpRet mock.Arguments From 233f92bee59b8207170f2ac09d9328b55f937dc6 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Wed, 4 Nov 2026 18:49:34 +0000 Subject: [PATCH 07/17] refactor(duration): share the --since and --until time window audit event list turned --since and --until into a time range in its own code. policy decision list needs the same flags with the same checks. The logic now lives in duration.Window, so both commands refuse the same input with the same message. The audit behavior does not change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MhRi597EX9odoSDXbVBsxz --- internal/cmd/audit/list.go | 18 +++++-------- internal/duration/window.go | 40 +++++++++++++++++++++++++++ internal/duration/window_test.go | 46 ++++++++++++++++++++++++++++++++ 3 files changed, 93 insertions(+), 11 deletions(-) create mode 100644 internal/duration/window.go create mode 100644 internal/duration/window_test.go diff --git a/internal/cmd/audit/list.go b/internal/cmd/audit/list.go index 5078aff..53855d7 100644 --- a/internal/cmd/audit/list.go +++ b/internal/cmd/audit/list.go @@ -2,7 +2,6 @@ package audit import ( "context" - "errors" "fmt" "strings" "time" @@ -95,19 +94,16 @@ func invalidFilter(cause error, help string) error { func newListRequest(in listInput, now time.Time) (*auditv1.ListAuditEventsRequest, error) { filters := &auditv1.ListAuditEventsRequest_Filters{} set := false - if in.Since < 0 || in.Until < 0 { - return nil, invalidFilter(errors.New("--since and --until must not be negative"), "Use a duration such as 7d") + after, before, err := duration.Window(in.Since, in.Until, now) + if err != nil { + return nil, err } - if in.Since > 0 { - filters.SetOccurredAfter(timestamppb.New(now.Add(-in.Since))) + if after != nil { + filters.SetOccurredAfter(timestamppb.New(*after)) set = true } - if in.Until > 0 { - if in.Since > 0 && in.Until >= in.Since { - return nil, invalidFilter(errors.New("--until must be shorter than --since"), - "As in --since 7d --until 1d for the events from 7 days ago to 1 day ago") - } - filters.SetOccurredBefore(timestamppb.New(now.Add(-in.Until))) + if before != nil { + filters.SetOccurredBefore(timestamppb.New(*before)) set = true } if in.Action != "" { diff --git a/internal/duration/window.go b/internal/duration/window.go new file mode 100644 index 0000000..15d8579 --- /dev/null +++ b/internal/duration/window.go @@ -0,0 +1,40 @@ +package duration + +import ( + "errors" + "time" + + "github.com/safedep/dry/usefulerror" +) + +// Window turns the --since and --until flags of a list command into a time +// range. Both are durations before now, and zero means no bound. after is +// nil when since is zero, and before is nil when until is zero. More than +// one list command reads these flags, so they all refuse the same input with +// the same message. +func Window(since, until time.Duration, now time.Time) (after, before *time.Time, err error) { + if since < 0 || until < 0 { + return nil, nil, badWindow(errors.New("--since and --until must not be negative"), "Use a duration such as 7d") + } + if since > 0 && until >= since { + return nil, nil, badWindow(errors.New("--until must be shorter than --since"), + "As in --since 7d --until 1d for the time from 7 days ago to 1 day ago") + } + if since > 0 { + t := now.Add(-since) + after = &t + } + if until > 0 { + t := now.Add(-until) + before = &t + } + return after, before, nil +} + +func badWindow(cause error, help string) error { + return usefulerror.NewUsefulError(). + WithCode(usefulerror.ErrBadRequest). + WithHumanError(cause.Error()). + WithHelp(help). + Wrap(cause) +} diff --git a/internal/duration/window_test.go b/internal/duration/window_test.go new file mode 100644 index 0000000..0b4ecec --- /dev/null +++ b/internal/duration/window_test.go @@ -0,0 +1,46 @@ +package duration + +import ( + "testing" + "time" + + "github.com/safedep/dry/usefulerror" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestWindow(t *testing.T) { + now := time.Date(2026, 11, 4, 12, 0, 0, 0, time.UTC) + day := 24 * time.Hour + tests := []struct { + name string + since time.Duration + until time.Duration + wantAfter *time.Time + wantBefore *time.Time + wantErr string + }{ + {name: "no bounds"}, + {name: "since only", since: 7 * day, wantAfter: new(now.Add(-7 * day))}, + {name: "until only", until: day, wantBefore: new(now.Add(-day))}, + {name: "both", since: 7 * day, until: day, wantAfter: new(now.Add(-7 * day)), wantBefore: new(now.Add(-day))}, + {name: "until not shorter", since: time.Hour, until: time.Hour, wantErr: "--until must be shorter than --since"}, + {name: "negative", since: -time.Hour, wantErr: "must not be negative"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + after, before, err := Window(tt.since, tt.until, now) + if tt.wantErr != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantErr) + ue, ok := usefulerror.AsUsefulError(err) + require.True(t, ok) + assert.Equal(t, usefulerror.ErrBadRequest, ue.Code()) + return + } + require.NoError(t, err) + assert.Equal(t, tt.wantAfter, after) + assert.Equal(t, tt.wantBefore, before) + }) + } +} From 6c6959cf32a4a8681f2bba0c49f18b5c2636f473 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Wed, 4 Nov 2026 18:49:34 +0000 Subject: [PATCH 08/17] feat(policy): add safedep policy decision list An admin who changes a rule, or who sees a blocked install, could not ask which decisions a revision, an override or a rule made, and where. The new command reads ListPolicyDecisions and lists the decisions of pmg and the pull request check, newest first. Each filter of the RPC has a flag: --since, --until, --tool, --outcome, --revision, --rule, --override, --path, --package, --project and --endpoint. --override takes a name or an id and resolves it in the policy at --revision, or at head. --package takes a PURL with no version. Each row shows the time, the tool, the package version, the outcome, the rule or field with its layer or override, the revision, and the place. The revision cell adds the default policy revision when the default policy decided, so a cooldown block shows both. A pmg place is the hostname and the user, with one hint: the CI repository, else the Kubernetes workload, else the agent. A check shows the repository, the pull request number and the link. A scan shows the repository and the ref. The JSON output writes the messages of the server in protojson. The errors map to a missing entitlement, a role that cannot read the policy, a bad page token or filter, and a server without the RPC. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MhRi597EX9odoSDXbVBsxz --- README.md | 2 + docs/cmd/policy-decision-list.md | 111 ++++++ internal/cmd/policy/cmd.go | 15 +- internal/cmd/policy/decision_list.go | 284 ++++++++++++++ internal/cmd/policy/decision_test.go | 565 +++++++++++++++++++++++++++ internal/cmd/policy/decision_view.go | 253 ++++++++++++ internal/cmd/policy/errors.go | 49 +++ 7 files changed, 1276 insertions(+), 3 deletions(-) create mode 100644 docs/cmd/policy-decision-list.md create mode 100644 internal/cmd/policy/decision_list.go create mode 100644 internal/cmd/policy/decision_test.go create mode 100644 internal/cmd/policy/decision_view.go diff --git a/README.md b/README.md index e82c0bc..7c3faca 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,7 @@ and drill into package inventory and recent activity. Edit the one policy of your tenant: the policy base, policy overrides that select endpoints and projects by label, and package rules that trust or block packages. Review each policy change before you publish it, and roll back from any policy revision. +See which rule made each decision of pmg and the pull request check, and where. **Projects and labels**: `safedep project` List projects by label selector, set `custom/` labels, and see which policy applies @@ -150,6 +151,7 @@ Push SafeDep malware findings to external security tools. JFrog XRay is supporte | [`safedep policy rule show`](./docs/cmd/policy-rule-show.md) | Show one package rule | | [`safedep policy rule update`](./docs/cmd/policy-rule-update.md) | Change the reason, expiry, ticket or requester of a package rule | | [`safedep policy rule delete`](./docs/cmd/policy-rule-delete.md) | Delete a package rule | +| [`safedep policy decision list`](./docs/cmd/policy-decision-list.md) | List the decisions that the policy made, and where | | [`safedep audit event list`](./docs/cmd/audit-event-list.md) | List audit events of the tenant | | [`safedep query exec`](./docs/cmd/query-exec.md) | Execute a SQL query against SafeDep Cloud | | [`safedep query schema list`](./docs/cmd/query-schema-list.md) | List tables in the query schema | diff --git a/docs/cmd/policy-decision-list.md b/docs/cmd/policy-decision-list.md new file mode 100644 index 0000000..8cc3025 --- /dev/null +++ b/docs/cmd/policy-decision-list.md @@ -0,0 +1,111 @@ +# safedep policy decision list + +List the decisions that pmg and the pull request check made with the policy of +the tenant, newest first. Each row says which policy revision and which package +rule or field decided, and where the decision happened. A decision that did not +use the cloud policy is not in the list. + +## Synopsis + +``` +safedep policy decision list [--since DURATION] [--until DURATION] + [--tool pmg|pull-request-check|vet] + [--outcome blocked|failed|allowed] + [--revision N] [--rule RULE_ID] [--override NAME|ID] + [--path PATH] [--package PURL] + [--project PROJECT_ID] [--endpoint ENDPOINT_ID] + [--limit N] [--page-token TOKEN] [--output table|plain|json] +``` + +## Flags + +| Flag | Description | +|------|-------------| +| `--since <duration>` | Only decisions in this time before now, as `7d` or `12h`. | +| `--until <duration>` | Only decisions older than this time before now, as `1d`. It must be shorter than `--since`. | +| `--tool <tool>` | Only decisions of `pmg`, `pull-request-check` or `vet`. | +| `--outcome <outcome>` | Only decisions that `blocked` an install, `failed` a check, or `allowed` a package because a trust entry waived a verdict. | +| `--revision <n>` | Only decisions that applied this tenant policy revision. | +| `--rule <rule-id>` | Only decisions that this package rule made. | +| `--override <name\|id>` | Only decisions that this policy override made: a field that the override set, or a package rule that attaches to it. The command finds the name in the policy at `--revision`, or at head. | +| `--path <path>` | Only decisions that this field made, by its contract path, as `package_admission.cooldown.min_age`. | +| `--package <purl>` | Only decisions about this package, in all its versions. Give a PURL with no version, as `pkg:npm/lodash`. | +| `--project <id>` | Only decisions at a pull request or a scan of a repository that is bound to this project. | +| `--endpoint <id>` | Only decisions that pmg made on this endpoint. | +| `--limit <n>` | Page size. The server default applies when 0. | +| `--page-token <token>` | Continuation token from a prior response. | + +Inherits root flags `--output` and `--profile`. + +## Columns + +| Column | Content | +|--------|---------| +| `WHEN` | When the tool made the decision. | +| `TOOL` | `pmg`, `pull-request-check` or `vet`. | +| `PACKAGE` | The ecosystem, the name and the version. | +| `OUTCOME` | `blocked`, `failed` or `allowed`. | +| `DECIDED BY` | The package rule, or the field path, and the layer or the override that set it: `default policy`, `base` or `override NAME`. | +| `REV` | The tenant policy revision. When the default policy decided, also its revision, as `47 · default 12`. | +| `WHERE` | For pmg, the hostname and the user, and one hint: the CI repository, else the Kubernetes namespace and workload, else the agent. For a check, the repository and the pull request number. For a scan, the repository and the branch or the commit. | +| `LINK` | The check run, the pull request or the CI run. The table has this column only when a row has a link. | + +## Examples + +The decisions that one package rule made: + +```bash +safedep policy decision list --rule r_9c1x4kq7dm +``` + +``` +Policy decisions +WHEN TOOL PACKAGE OUTCOME DECIDED BY REV WHERE LINK +5m ago pmg npm/evil@1.0.0 blocked rule r_9c1x4kq7dm 47 dev-laptop (alice) - +5m ago pull-request-check npm/evil@1.0.1 failed rule r_9c1x4kq7dm 47 acme/payments-api#42 https://github.com/acme/payments-api/runs/7 +2 decisions +``` + +The installs that the cooldown blocked in the last day: + +```bash +safedep policy decision list --path package_admission.cooldown.min_age --since 1d +``` + +``` +Policy decisions +WHEN TOOL PACKAGE OUTCOME DECIDED BY REV WHERE +5m ago pmg npm/fresh@0.0.1 blocked package_admission.cooldown.min_age · default policy 47 · default 12 dev-laptop (alice) +1 decision +``` + +The decisions of a policy override at one revision: + +```bash +safedep policy decision list --override payments --revision 47 +``` + +## Output + +`json` holds `decisions`, the `PolicyDecision` messages as the server sends them +in protojson with the field names of the contract, and `next_page_token`. Each +message has the full citation (revisions, digest, path, rule id, override id, +layer) and the full decision point, such as the working directory, the CI branch +and commit, the Kubernetes Pod and the agent of a pmg run. `plain` writes a +tab-separated header and one row for each decision, with exact times and ids. + +## Permissions + +The roles that can read the policy can read the decision log. The tenant needs +policy management. + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The page was read, also when it is empty. | +| non-zero | Validation, authentication or the request failed. | diff --git a/internal/cmd/policy/cmd.go b/internal/cmd/policy/cmd.go index 9331ffb..b896e2a 100644 --- a/internal/cmd/policy/cmd.go +++ b/internal/cmd/policy/cmd.go @@ -1,7 +1,7 @@ // Package policy registers the `safedep policy` command tree, the CLI for // policy management in SafeDep Cloud: the policy settings document, policy -// changes, policy revisions and package rules. Every verb needs control -// plane credentials. +// changes, policy revisions, package rules and the decision log. Every +// verb needs control plane credentials. package policy import ( @@ -54,6 +54,15 @@ func Register(root *cobra.Command, a *app.App) { } rule.AddCommand(ruleCreateCmd(a), ruleListCmd(a), ruleShowCmd(a), ruleUpdateCmd(a), ruleDeleteCmd(a)) - parent.AddCommand(change, revision, rule) + decision := &cobra.Command{ + Use: "decision", + Short: "Read the decisions that the policy made", + Long: "Read the decision log: the decisions that pmg and the pull request check made with the policy " + + "of the tenant. Each decision cites the policy revision and the rule or field that decided, and " + + "says where it happened. The roles that can read the policy can read the decision log.", + } + decision.AddCommand(decisionListCmd(a)) + + parent.AddCommand(change, revision, rule, decision) root.AddCommand(parent) } diff --git a/internal/cmd/policy/decision_list.go b/internal/cmd/policy/decision_list.go new file mode 100644 index 0000000..f392725 --- /dev/null +++ b/internal/cmd/policy/decision_list.go @@ -0,0 +1,284 @@ +package policy + +import ( + "context" + "fmt" + "strings" + "time" + + policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" + packagev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/package/v1" + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + drypb "github.com/safedep/dry/api/pb" + "github.com/safedep/dry/log" + "github.com/spf13/cobra" + "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" + "github.com/safedep/cli/internal/duration" + "github.com/safedep/cli/internal/paging" + "github.com/safedep/cli/internal/tui" +) + +const ( + decisionToolPrefix = "DECISION_TOOL_" + decisionOutcomePrefix = "DECISION_OUTCOME_" +) + +type decisionListInput struct { + Since time.Duration + Until time.Duration + Tool string + Outcome string + Revision uint64 + Rule string + Override string + Path string + Package string + Project string + Endpoint string + PageSize uint32 + PageToken string +} + +func decisionListCmd(a *app.App) *cobra.Command { + var in decisionListInput + cmd := &cobra.Command{ + Use: "list", + Short: "List the decisions that the policy made, newest first", + Long: "List the decisions that pmg and the pull request check made with the policy of the tenant, " + + "newest first. Each row says which policy revision and which rule or field decided, and where: " + + "the endpoint and the user for pmg, the repository and the pull request for a check. " + + "--since and --until take a duration before now, as in 7d or 12h. --override takes the name " + + "or the id of a policy override. --package takes a PURL with no version, as in pkg:npm/lodash. " + + "The command reads one page. Pass --page-token to read the next page.", + Args: func(cmd *cobra.Command, args []string) error { + if err := cobra.NoArgs(cmd, args); err != nil { + return err + } + _, err := newDecisionFilters(in, "", time.Now()) + return err + }, + RunE: func(cmd *cobra.Command, _ []string) error { + client, err := a.ControlPlane() + if err != nil { + return err + } + res, err := runDecisionList(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), in, time.Now()) + if err != nil { + return err + } + return a.Output.Print(res) + }, + } + f := cmd.Flags() + f.Var(duration.NewValue(&in.Since, 0), "since", "only decisions in this time before now, as in 7d or 12h") + f.Var(duration.NewValue(&in.Until, 0), "until", "only decisions older than this time before now, as in 1d") + f.StringVar(&in.Tool, "tool", "", "filter: the tool that decided ("+strings.Join(decisionToolTokens(), ", ")+")") + f.StringVar(&in.Outcome, "outcome", "", "filter: what the decision did ("+strings.Join(decisionOutcomeTokens(), ", ")+")") + f.Uint64Var(&in.Revision, "revision", 0, "filter: decisions that applied this policy revision") + f.StringVar(&in.Rule, "rule", "", "filter: decisions that this package rule made, by rule id") + f.StringVar(&in.Override, "override", "", "filter: decisions that this policy override made, by name or id") + f.StringVar(&in.Path, "path", "", "filter: decisions that this field made, as in package_admission.cooldown.min_age") + f.StringVar(&in.Package, "package", "", "filter: decisions about this package in all its versions, as in pkg:npm/lodash") + f.StringVar(&in.Project, "project", "", "filter: decisions at a repository that is bound to this project id") + f.StringVar(&in.Endpoint, "endpoint", "", "filter: decisions that pmg made on this endpoint id") + f.Uint32Var(&in.PageSize, "limit", 0, "page size; server default when 0") + f.StringVar(&in.PageToken, "page-token", "", "continuation token from a prior response") + return cmd +} + +func decisionToolTokens() []string { + return tui.EnumTokens(policyv1.DecisionTool_name, decisionToolPrefix) +} + +func decisionOutcomeTokens() []string { + return tui.EnumTokens(policyv1.DecisionOutcome_name, decisionOutcomePrefix) +} + +func parseDecisionEnum(flag, token string, names map[int32]string, prefix string, tokens []string) (int32, error) { + n, ok := tui.ParseEnumToken(names, prefix, token) + if !ok { + return 0, invalidInputError( + fmt.Errorf("unknown --%s value %q: allowed values are %s", flag, token, strings.Join(tokens, ", ")), + "Retry with one of: "+strings.Join(tokens, ", ")) + } + return n, nil +} + +// parseDecisionPackage reads a PURL with no version. The filter matches every +// version of the package, so a version in the PURL would mislead. +func parseDecisionPackage(purl string) (*packagev1.Package, error) { + help := "Give a PURL with no version, as in --package pkg:npm/lodash" + if !strings.HasPrefix(purl, "pkg:") { + return nil, invalidInputError(fmt.Errorf("--package %q is not a PURL", purl), help) + } + parsed, err := drypb.NewPurlPackageVersion(purl) + if err != nil { + return nil, invalidInputError(fmt.Errorf("--package %q: %w", purl, err), help) + } + pv := parsed.PackageVersion() + switch { + case pv.GetPackage().GetEcosystem() == packagev1.Ecosystem_ECOSYSTEM_UNSPECIFIED: + return nil, invalidInputError(fmt.Errorf("--package %q: unknown ecosystem", purl), help) + case pv.GetVersion() != "": + return nil, invalidInputError( + fmt.Errorf("--package %q has a version: the filter matches every version of the package", purl), help) + case pv.GetPackage().GetName() == "": + return nil, invalidInputError(fmt.Errorf("--package %q has no name", purl), help) + } + return pv.GetPackage(), nil +} + +// newDecisionFilters builds the request filters from the flags. overrideID is +// the id that --override resolved to. It returns nil when no filter is set. +func newDecisionFilters( + in decisionListInput, + overrideID string, + now time.Time, +) (*policyv1.ListPolicyDecisionsRequest_Filters, error) { + filters := &policyv1.ListPolicyDecisionsRequest_Filters{} + set := false + after, before, err := duration.Window(in.Since, in.Until, now) + if err != nil { + return nil, err + } + if after != nil { + filters.SetDecidedAfter(timestamppb.New(*after)) + set = true + } + if before != nil { + filters.SetDecidedBefore(timestamppb.New(*before)) + set = true + } + if in.Tool != "" { + n, err := parseDecisionEnum("tool", in.Tool, policyv1.DecisionTool_name, decisionToolPrefix, decisionToolTokens()) + if err != nil { + return nil, err + } + filters.SetTool(policyv1.DecisionTool(n)) + set = true + } + if in.Outcome != "" { + n, err := parseDecisionEnum("outcome", in.Outcome, policyv1.DecisionOutcome_name, decisionOutcomePrefix, + decisionOutcomeTokens()) + if err != nil { + return nil, err + } + filters.SetOutcome(policyv1.DecisionOutcome(n)) + set = true + } + if in.Revision > 0 { + filters.SetRevision(in.Revision) + set = true + } + if in.Package != "" { + pkg, err := parseDecisionPackage(in.Package) + if err != nil { + return nil, err + } + filters.SetPackage(pkg) + set = true + } + for _, text := range []struct { + value string + apply func(string) + }{ + {in.Rule, filters.SetRuleId}, + {overrideID, filters.SetOverrideId}, + {in.Path, filters.SetPath}, + {in.Project, filters.SetProjectId}, + {in.Endpoint, filters.SetEndpointId}, + } { + if text.value != "" { + text.apply(text.value) + set = true + } + } + if !set { + return nil, nil + } + return filters, nil +} + +// runDecisionList reads one page of decisions. It reads the policy only to +// resolve --override and to name the overrides that the decisions cite. It +// reads the policy at --revision when it is set, because the decisions of +// that revision used its overrides. +func runDecisionList( + ctx context.Context, + client policyv1grpc.PolicyServiceClient, + in decisionListInput, + now time.Time, +) (*decisionListResult, error) { + if _, err := newDecisionFilters(in, "", now); err != nil { + return nil, err + } + var snapshot *policyv1.Policy + overrideID := "" + if in.Override != "" { + _, p, err := readPolicyAt(ctx, client, in.Revision) + if err != nil { + return nil, err + } + snapshot = p + o, err := findOverrideByNameOrID(p, in.Override) + if err != nil { + return nil, err + } + overrideID = o.GetOverrideId() + } + filters, err := newDecisionFilters(in, overrideID, now) + if err != nil { + return nil, err + } + req := &policyv1.ListPolicyDecisionsRequest{} + req.SetPagination(paging.NewPaginationRequest(in.PageSize, in.PageToken)) + if filters != nil { + req.SetFilters(filters) + } + res, err := client.ListPolicyDecisions(ctx, req) + if err != nil { + return nil, mapDecisionListError(err) + } + + names := map[string]string{} + if citesOverride(res.GetDecisions()) { + if snapshot == nil { + _, p, err := readPolicyAt(ctx, client, in.Revision) + if err != nil { + // The names only label the output. The ids stay, so the list is + // still correct without them. + log.Warnf("policy decision list: read the override names: %v", err) + } + snapshot = p + } + names = overrideNames(snapshot) + } + return newDecisionListResult(res, names), nil +} + +func citesOverride(decisions []*policyv1.PolicyDecision) bool { + for _, d := range decisions { + if d.GetCitation().GetOverrideId() != "" { + return true + } + } + return false +} + +// findOverrideByNameOrID accepts the id too, because the JSON output of a +// decision gives the id of its override. A name wins over an id. +func findOverrideByNameOrID(p *policyv1.Policy, ref string) (*policyv1.Override, error) { + o, err := findOverride(p, ref) + if err == nil { + return o, nil + } + for _, o := range p.GetOverrides() { + if o.GetOverrideId() == ref { + return o, nil + } + } + return nil, err +} diff --git a/internal/cmd/policy/decision_test.go b/internal/cmd/policy/decision_test.go new file mode 100644 index 0000000..9d2ff69 --- /dev/null +++ b/internal/cmd/policy/decision_test.go @@ -0,0 +1,565 @@ +package policy + +import ( + "context" + "encoding/json" + "strings" + "testing" + "time" + + messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" + errorv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/error/v1" + packagev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/package/v1" + recordv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/record/v1" + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/safedep/dry/usefulerror" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + "google.golang.org/genproto/googleapis/rpc/errdetails" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/safedep/cli/internal/cloudpolicy/mocks" +) + +const prSHA = "0123456789abcdef0123456789abcdef01234567" + +func citation(revision, defaultRevision uint64, path, ruleID, overrideID string, layer recordv1.Layer) *recordv1.DecisionCitation { + c := &recordv1.DecisionCitation{} + c.SetRevision(revision) + c.SetDefaultPolicyRevision(defaultRevision) + c.SetPath(path) + c.SetRuleId(ruleID) + c.SetOverrideId(overrideID) + c.SetLayer(layer) + return c +} + +func endpointPoint(hostname, username string) *messagescontroltowerv1.EndpointPoint { + e := &messagescontroltowerv1.EndpointPoint{} + e.SetEndpointId("01JEP0000000000000000000") + if hostname != "" { + e.SetHostname(hostname) + } + if username != "" { + e.SetUsername(username) + } + e.SetInvocationId("inv_1") + return e +} + +func atEndpoint(e *messagescontroltowerv1.EndpointPoint) *messagescontroltowerv1.DecisionPoint { + p := &messagescontroltowerv1.DecisionPoint{} + p.SetEndpoint(e) + return p +} + +func atPullRequest(repo string, number uint32, url string) *messagescontroltowerv1.DecisionPoint { + pr := &messagescontroltowerv1.PullRequestPoint{} + pr.SetPlatform(messagescontroltowerv1.IntegrationType_INTEGRATION_TYPE_GITHUB) + pr.SetRepositoryId("123") + pr.SetRepositoryName(repo) + pr.SetNumber(number) + pr.SetHeadCommitSha(prSHA) + if url != "" { + pr.SetUrl(url) + } + p := &messagescontroltowerv1.DecisionPoint{} + p.SetPullRequest(pr) + return p +} + +func atScan(repo, ref string) *messagescontroltowerv1.DecisionPoint { + s := &messagescontroltowerv1.ScanPoint{} + s.SetRepositoryName(repo) + if ref != "" { + s.SetRef(ref) + } + s.SetCommitSha(prSHA) + s.SetUrl("https://ci.example.com/run/9") + p := &messagescontroltowerv1.DecisionPoint{} + p.SetScan(s) + return p +} + +func decision( + id string, + tool policyv1.DecisionTool, + outcome policyv1.DecisionOutcome, + name, version string, + c *recordv1.DecisionCitation, + point *messagescontroltowerv1.DecisionPoint, +) *policyv1.PolicyDecision { + pkg := &packagev1.Package{} + pkg.SetEcosystem(packagev1.Ecosystem_ECOSYSTEM_NPM) + pkg.SetName(name) + pv := &packagev1.PackageVersion{} + pv.SetPackage(pkg) + pv.SetVersion(version) + d := &policyv1.PolicyDecision{} + d.SetDecisionId(id) + d.SetDecidedAt(timestamppb.New(time.Now().Add(-5 * time.Minute))) + d.SetTool(tool) + d.SetOutcome(outcome) + d.SetPackageVersion(pv) + d.SetCitation(c) + if point != nil { + d.SetDecisionPoint(point) + } + return d +} + +// ruleDecisions are a pmg block and a failed pull request check that one +// package rule made. +func ruleDecisions() []*policyv1.PolicyDecision { + return []*policyv1.PolicyDecision{ + decision("d_pmg", policyv1.DecisionTool_DECISION_TOOL_PMG, policyv1.DecisionOutcome_DECISION_OUTCOME_BLOCKED, + "evil", "1.0.0", citation(47, 12, "", "r_9c1x4kq7dm", "", recordv1.Layer_LAYER_UNSPECIFIED), + atEndpoint(endpointPoint("dev-laptop", "alice"))), + decision("d_pr", policyv1.DecisionTool_DECISION_TOOL_PULL_REQUEST_CHECK, + policyv1.DecisionOutcome_DECISION_OUTCOME_FAILED, "evil", "1.0.1", + citation(47, 12, "", "r_9c1x4kq7dm", "", recordv1.Layer_LAYER_UNSPECIFIED), + atPullRequest("acme/payments-api", 42, "https://github.com/acme/payments-api/runs/7")), + } +} + +func decisionsResponse(next string, decisions ...*policyv1.PolicyDecision) *policyv1.ListPolicyDecisionsResponse { + page := &messagescontroltowerv1.PaginationResponse{} + page.SetNextPageToken(next) + res := &policyv1.ListPolicyDecisionsResponse{} + res.SetDecisions(decisions) + res.SetPagination(page) + return res +} + +func TestNewDecisionFilters(t *testing.T) { + day := 24 * time.Hour + tests := []struct { + name string + in decisionListInput + overrideID string + check func(*testing.T, *policyv1.ListPolicyDecisionsRequest_Filters) + wantErr string + }{ + { + name: "no filters", + check: func(t *testing.T, f *policyv1.ListPolicyDecisionsRequest_Filters) { assert.Nil(t, f) }, + }, + { + name: "time range", + in: decisionListInput{Since: 7 * day, Until: day}, + check: func(t *testing.T, f *policyv1.ListPolicyDecisionsRequest_Filters) { + assert.Equal(t, fixedNow.Add(-7*day), f.GetDecidedAfter().AsTime()) + assert.Equal(t, fixedNow.Add(-day), f.GetDecidedBefore().AsTime()) + }, + }, + { + name: "tool pmg", + in: decisionListInput{Tool: "pmg"}, + check: func(t *testing.T, f *policyv1.ListPolicyDecisionsRequest_Filters) { + assert.Equal(t, policyv1.DecisionTool_DECISION_TOOL_PMG, f.GetTool()) + }, + }, + { + name: "tool pull request check", + in: decisionListInput{Tool: "pull-request-check"}, + check: func(t *testing.T, f *policyv1.ListPolicyDecisionsRequest_Filters) { + assert.Equal(t, policyv1.DecisionTool_DECISION_TOOL_PULL_REQUEST_CHECK, f.GetTool()) + }, + }, + { + name: "outcome", + in: decisionListInput{Outcome: "allowed"}, + check: func(t *testing.T, f *policyv1.ListPolicyDecisionsRequest_Filters) { + assert.Equal(t, policyv1.DecisionOutcome_DECISION_OUTCOME_ALLOWED, f.GetOutcome()) + }, + }, + { + name: "revision", + in: decisionListInput{Revision: 47}, + check: func(t *testing.T, f *policyv1.ListPolicyDecisionsRequest_Filters) { + assert.Equal(t, uint64(47), f.GetRevision()) + }, + }, + { + name: "rule", + in: decisionListInput{Rule: "r_9c1x4kq7dm"}, + check: func(t *testing.T, f *policyv1.ListPolicyDecisionsRequest_Filters) { + assert.Equal(t, "r_9c1x4kq7dm", f.GetRuleId()) + }, + }, + { + name: "override id from the resolved name", + in: decisionListInput{Override: "payments"}, + overrideID: "ov_pay", + check: func(t *testing.T, f *policyv1.ListPolicyDecisionsRequest_Filters) { + assert.Equal(t, "ov_pay", f.GetOverrideId()) + }, + }, + { + name: "path", + in: decisionListInput{Path: "package_admission.cooldown.min_age"}, + check: func(t *testing.T, f *policyv1.ListPolicyDecisionsRequest_Filters) { + assert.Equal(t, "package_admission.cooldown.min_age", f.GetPath()) + }, + }, + { + name: "package", + in: decisionListInput{Package: "pkg:npm/%40acme/ui"}, + check: func(t *testing.T, f *policyv1.ListPolicyDecisionsRequest_Filters) { + assert.Equal(t, packagev1.Ecosystem_ECOSYSTEM_NPM, f.GetPackage().GetEcosystem()) + assert.Equal(t, "@acme/ui", f.GetPackage().GetName()) + }, + }, + { + name: "project", + in: decisionListInput{Project: "prj_1"}, + check: func(t *testing.T, f *policyv1.ListPolicyDecisionsRequest_Filters) { + assert.Equal(t, "prj_1", f.GetProjectId()) + }, + }, + { + name: "endpoint", + in: decisionListInput{Endpoint: "01JEP0000000000000000000"}, + check: func(t *testing.T, f *policyv1.ListPolicyDecisionsRequest_Filters) { + assert.Equal(t, "01JEP0000000000000000000", f.GetEndpointId()) + }, + }, + {name: "unknown tool", in: decisionListInput{Tool: "npm"}, wantErr: "unknown --tool value"}, + {name: "unknown outcome", in: decisionListInput{Outcome: "denied"}, wantErr: "unknown --outcome value"}, + {name: "package with a version", in: decisionListInput{Package: "pkg:npm/lodash@4.17.21"}, wantErr: "has a version"}, + {name: "package not a PURL", in: decisionListInput{Package: "lodash"}, wantErr: "is not a PURL"}, + {name: "package of an unknown ecosystem", in: decisionListInput{Package: "pkg:nope/x"}, wantErr: "unknown ecosystem"}, + {name: "until after since", in: decisionListInput{Since: time.Hour, Until: 2 * time.Hour}, wantErr: "--until must be shorter"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f, err := newDecisionFilters(tt.in, tt.overrideID, fixedNow) + if tt.wantErr != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantErr) + ue, ok := usefulerror.AsUsefulError(err) + require.True(t, ok) + assert.Equal(t, usefulerror.ErrBadRequest, ue.Code()) + return + } + require.NoError(t, err) + tt.check(t, f) + }) + } +} + +func TestRunDecisionList_RuleListsBothToolsWithThePlace(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().ListPolicyDecisions(mock.Anything, mock.MatchedBy(func(r *policyv1.ListPolicyDecisionsRequest) bool { + return r.GetFilters().GetRuleId() == "r_9c1x4kq7dm" + })).Return(decisionsResponse("", ruleDecisions()...), nil) + + got, err := runDecisionList(context.Background(), client, decisionListInput{Rule: "r_9c1x4kq7dm"}, fixedNow) + require.NoError(t, err) + + table := got.RenderTable() + for _, want := range []string{ + "5m ago", "pmg", "npm/evil@1.0.0", "blocked", "rule r_9c1x4kq7dm", "dev-laptop (alice)", + "pull-request-check", "failed", "acme/payments-api#42", "https://github.com/acme/payments-api/runs/7", + "LINK", "2 decisions", + } { + assert.Contains(t, table, want) + } + plain := strings.Split(got.RenderPlain(), "\n") + require.Len(t, plain, 3) + assert.Contains(t, plain[1], "\td_pmg\tpmg\tblocked\tnpm\tevil\t1.0.0\t47\t12\t\t\tr_9c1x4kq7dm\t\tendpoint\tdev-laptop (alice)\t") + assert.Contains(t, plain[2], "\tpull-request\tacme/payments-api#42\thttps://github.com/acme/payments-api/runs/7") +} + +func TestRunDecisionList_CooldownShowsThePathAndTheDefaultRevision(t *testing.T) { + cooldown := decision("d_cool", policyv1.DecisionTool_DECISION_TOOL_PMG, policyv1.DecisionOutcome_DECISION_OUTCOME_BLOCKED, + "fresh", "0.0.1", citation(47, 12, "package_admission.cooldown.min_age", "", "", recordv1.Layer_LAYER_DEFAULT_POLICY), + atEndpoint(endpointPoint("dev-laptop", "alice"))) + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().ListPolicyDecisions(mock.Anything, mock.MatchedBy(func(r *policyv1.ListPolicyDecisionsRequest) bool { + return r.GetFilters().GetPath() == "package_admission.cooldown.min_age" + })).Return(decisionsResponse("", cooldown), nil) + + got, err := runDecisionList(context.Background(), client, + decisionListInput{Path: "package_admission.cooldown.min_age"}, fixedNow) + require.NoError(t, err) + table := got.RenderTable() + assert.Contains(t, table, "package_admission.cooldown.min_age · default policy") + assert.Contains(t, table, "47 · default 12") + assert.NotContains(t, table, "LINK", "no decision has a link") + assert.Contains(t, got.RenderPlain(), "\t47\t12\tdefault-policy\tpackage_admission.cooldown.min_age\t") +} + +func TestRunDecisionList_Override(t *testing.T) { + overrideDecision := decision("d_ov", policyv1.DecisionTool_DECISION_TOOL_PMG, policyv1.DecisionOutcome_DECISION_OUTCOME_BLOCKED, + "fresh", "0.0.1", citation(47, 12, "package_admission.cooldown.min_age", "", "ov_pay", recordv1.Layer_LAYER_OVERRIDE), + atEndpoint(endpointPoint("dev-laptop", "alice"))) + tests := []struct { + name string + in decisionListInput + expect func(*mocks.PolicyServiceClientMock) + wantID string + wantCell string + wantErr string + }{ + { + name: "by name at head", + in: decisionListInput{Override: "payments"}, + expect: func(c *mocks.PolicyServiceClientMock) { + c.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(headResponse(), nil).Once() + }, + wantID: "ov_pay", + wantCell: "package_admission.cooldown.min_age · override payments", + }, + { + name: "by id", + in: decisionListInput{Override: "ov_pay"}, + expect: func(c *mocks.PolicyServiceClientMock) { + c.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(headResponse(), nil).Once() + }, + wantID: "ov_pay", + wantCell: "override payments", + }, + { + name: "by name at the revision", + in: decisionListInput{Override: "payments", Revision: 47}, + expect: func(c *mocks.PolicyServiceClientMock) { + res := &policyv1.GetPolicyRevisionResponse{} + res.SetPolicy(headPolicy()) + c.EXPECT().GetPolicyRevision(mock.Anything, mock.MatchedBy(func(r *policyv1.GetPolicyRevisionRequest) bool { + return r.GetRevision() == 47 + })).Return(res, nil).Once() + }, + wantID: "ov_pay", + wantCell: "override payments", + }, + { + name: "unknown name", + in: decisionListInput{Override: "nope"}, + expect: func(c *mocks.PolicyServiceClientMock) { + c.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(headResponse(), nil).Once() + }, + wantErr: `no policy override is named "nope"`, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + tt.expect(client) + if tt.wantErr == "" { + client.EXPECT().ListPolicyDecisions(mock.Anything, mock.MatchedBy(func(r *policyv1.ListPolicyDecisionsRequest) bool { + return r.GetFilters().GetOverrideId() == tt.wantID && r.GetFilters().GetRevision() == tt.in.Revision + })).Return(decisionsResponse("", overrideDecision), nil) + } + got, err := runDecisionList(context.Background(), client, tt.in, fixedNow) + if tt.wantErr != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantErr) + return + } + require.NoError(t, err) + assert.Contains(t, got.RenderTable(), tt.wantCell) + assert.Contains(t, got.RenderPlain(), "\tov_pay\t", "plain keeps the id") + }) + } +} + +func TestRunDecisionList_OverrideNameReadFailureKeepsTheID(t *testing.T) { + d := decision("d_ov", policyv1.DecisionTool_DECISION_TOOL_PMG, policyv1.DecisionOutcome_DECISION_OUTCOME_BLOCKED, + "evil", "1.0.0", citation(47, 12, "", "r_1", "ov_gone", recordv1.Layer_LAYER_UNSPECIFIED), + atEndpoint(endpointPoint("dev-laptop", ""))) + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().ListPolicyDecisions(mock.Anything, mock.Anything).Return(decisionsResponse("", d), nil) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(nil, status.Error(codes.Unavailable, "down")) + + got, err := runDecisionList(context.Background(), client, decisionListInput{}, fixedNow) + require.NoError(t, err) + assert.Contains(t, got.RenderTable(), "rule r_1 · override ov_gone") +} + +func TestDescribePlace(t *testing.T) { + ci := endpointPoint("runner-7", "runner") + ciContext := &messagescontroltowerv1.EndpointCIContext{} + ciContext.SetRepository("acme/api") + ciContext.SetBranch("main") + ci.SetCi(ciContext) + + pod := endpointPoint("api-7d9f-x2", "") + k8s := &messagescontroltowerv1.EndpointKubernetesContext{} + k8s.SetNamespace("payments") + k8s.SetWorkloadName("api") + pod.SetKubernetes(k8s) + + laptop := endpointPoint("dev-laptop", "alice") + agent := &messagescontroltowerv1.EndpointAgentContext{} + agent.SetAgentName("claude-code") + laptop.SetAgent(agent) + + tests := []struct { + name string + point *messagescontroltowerv1.DecisionPoint + wantKind string + wantPlace string + wantURL string + }{ + {"endpoint", atEndpoint(endpointPoint("dev-laptop", "alice")), placeEndpoint, "dev-laptop (alice)", ""}, + {"endpoint with no hostname", atEndpoint(endpointPoint("", "")), placeEndpoint, "01JEP0000000000000000000", ""}, + {"endpoint in CI", atEndpoint(ci), placeEndpoint, "runner-7 (runner) · ci acme/api", ""}, + {"endpoint in Kubernetes", atEndpoint(pod), placeEndpoint, "api-7d9f-x2 · k8s payments/api", ""}, + {"endpoint with an agent", atEndpoint(laptop), placeEndpoint, "dev-laptop (alice) · agent claude-code", ""}, + { + "pull request", atPullRequest("acme/api", 42, "https://github.com/acme/api/pull/42"), + placePullRequest, "acme/api#42", "https://github.com/acme/api/pull/42", + }, + {"pull request with no link", atPullRequest("acme/api", 42, ""), placePullRequest, "acme/api#42", ""}, + {"scan of a branch", atScan("acme/api", "main"), placeScan, "acme/api@main", "https://ci.example.com/run/9"}, + {"scan of a commit", atScan("acme/api", ""), placeScan, "acme/api@0123456789ab", "https://ci.example.com/run/9"}, + {"no place", nil, "", "", ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + kind, place, url := describePlace(tt.point) + assert.Equal(t, tt.wantKind, kind) + assert.Equal(t, tt.wantPlace, place) + assert.Equal(t, tt.wantURL, url) + }) + } +} + +func TestRunDecisionList_EscapesServerText(t *testing.T) { + d := decision("d_x", policyv1.DecisionTool_DECISION_TOOL_PMG, policyv1.DecisionOutcome_DECISION_OUTCOME_BLOCKED, + "evil\x1b]0;owned\x07", "1.0.0", citation(47, 12, "a\nb", "", "", recordv1.Layer_LAYER_BASE), + atEndpoint(endpointPoint("host\u202e", "mallory\tx"))) + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().ListPolicyDecisions(mock.Anything, mock.Anything).Return(decisionsResponse("", d), nil) + + got, err := runDecisionList(context.Background(), client, decisionListInput{}, fixedNow) + require.NoError(t, err) + for _, out := range []string{got.RenderTable(), got.RenderPlain()} { + assert.NotContains(t, out, "\x1b") + assert.NotContains(t, out, "\u202e") + assert.Contains(t, out, `evil\x1b]0;owned\x07`) + assert.Contains(t, out, `a\nb`) + assert.Contains(t, out, `mallory\tx`) + } + assert.Len(t, strings.Split(got.RenderPlain(), "\n"), 2, "a line break in a value adds no row") +} + +func TestRunDecisionList_Empty(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().ListPolicyDecisions(mock.Anything, mock.Anything).Return(decisionsResponse(""), nil) + + got, err := runDecisionList(context.Background(), client, decisionListInput{}, fixedNow) + require.NoError(t, err) + assert.Contains(t, got.RenderTable(), "No policy decisions match") + assert.Len(t, strings.Split(got.RenderPlain(), "\n"), 1, "plain writes only the header") + b, err := got.RenderJSON() + require.NoError(t, err) + assert.JSONEq(t, `{"decisions": []}`, string(b)) +} + +func TestRunDecisionList_Paging(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().ListPolicyDecisions(mock.Anything, mock.MatchedBy(func(r *policyv1.ListPolicyDecisionsRequest) bool { + return r.GetPagination().GetPageSize() == 2 && r.GetPagination().GetPageToken() == "tok_1" && !r.HasFilters() + })).Return(decisionsResponse("tok_2", ruleDecisions()...), nil) + + got, err := runDecisionList(context.Background(), client, decisionListInput{PageSize: 2, PageToken: "tok_1"}, fixedNow) + require.NoError(t, err) + assert.Contains(t, got.RenderTable(), "2 decisions. More available: --page-token tok_2") + b, err := got.RenderJSON() + require.NoError(t, err) + assert.Contains(t, string(b), `"next_page_token": "tok_2"`) +} + +func TestRunDecisionList_JSONHasTheRawMessages(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().ListPolicyDecisions(mock.Anything, mock.Anything).Return(decisionsResponse("", ruleDecisions()...), nil) + + got, err := runDecisionList(context.Background(), client, decisionListInput{}, fixedNow) + require.NoError(t, err) + b, err := got.RenderJSON() + require.NoError(t, err) + + var out struct { + Decisions []map[string]any `json:"decisions"` + } + require.NoError(t, json.Unmarshal(b, &out)) + require.Len(t, out.Decisions, 2) + pmg := out.Decisions[0] + assert.Equal(t, "d_pmg", pmg["decision_id"]) + assert.Equal(t, "DECISION_TOOL_PMG", pmg["tool"]) + assert.Equal(t, "DECISION_OUTCOME_BLOCKED", pmg["outcome"]) + assert.Equal(t, "r_9c1x4kq7dm", pmg["citation"].(map[string]any)["rule_id"]) + assert.Equal(t, "inv_1", pmg["decision_point"].(map[string]any)["endpoint"].(map[string]any)["invocation_id"]) + pr := out.Decisions[1]["decision_point"].(map[string]any)["pull_request"].(map[string]any) + assert.Equal(t, prSHA, pr["head_commit_sha"]) + assert.Equal(t, "INTEGRATION_TYPE_GITHUB", pr["platform"]) +} + +func TestMapDecisionListError(t *testing.T) { + badToken := usefulerror.NewStatus(codes.InvalidArgument, "the page token is not valid"). + WithDetail(&errdetails.BadRequest{FieldViolations: []*errdetails.BadRequest_FieldViolation{ + {Field: "pagination.page_token", Description: "the page token is not valid"}, + }}).Err() + tests := []struct { + name string + err error + wantCode string + wantHuman string + }{ + { + name: "feature not enabled", + err: usefulerror.NewStatus(codes.PermissionDenied, "no entitlement"). + WithReason(errorv1.ErrorReason_ERROR_REASON_ENTITLEMENT_NOT_AVAILABLE).Err(), + wantCode: usefulerror.ErrMissingEntitlements, + wantHuman: "Policy management is not enabled for this tenant", + }, + { + name: "role cannot read", + err: status.Error(codes.PermissionDenied, "denied"), + wantCode: usefulerror.ErrAuthorizationFailed, + wantHuman: "Your role cannot read the policy decision log", + }, + { + name: "bad page token", + err: badToken, + wantCode: usefulerror.ErrBadRequest, + wantHuman: "The page token is not valid", + }, + { + name: "bad filter", + err: status.Error(codes.InvalidArgument, "decided_after must be before decided_before\x1b[2J"), + wantCode: usefulerror.ErrBadRequest, + wantHuman: `The server refused the filters: decided_after must be before decided_before\x1b[2J`, + }, + { + name: "server without the RPC", + err: status.Error(codes.Unimplemented, "unknown method"), + wantCode: usefulerror.ErrServiceUnavailable, + wantHuman: "SafeDep Cloud does not have the policy decision log yet", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().ListPolicyDecisions(mock.Anything, mock.Anything).Return(nil, tt.err) + _, err := runDecisionList(context.Background(), client, decisionListInput{}, fixedNow) + ue, ok := usefulerror.AsUsefulError(err) + require.True(t, ok) + assert.Equal(t, tt.wantCode, ue.Code()) + assert.Equal(t, tt.wantHuman, ue.HumanError()) + assert.ErrorIs(t, err, tt.err) + }) + } + + t.Run("other errors keep the cause", func(t *testing.T) { + cause := status.Error(codes.Internal, "boom") + err := mapDecisionListError(cause) + assert.ErrorIs(t, err, cause) + assert.Contains(t, err.Error(), "policy decision list") + }) +} diff --git a/internal/cmd/policy/decision_view.go b/internal/cmd/policy/decision_view.go new file mode 100644 index 0000000..b77d72e --- /dev/null +++ b/internal/cmd/policy/decision_view.go @@ -0,0 +1,253 @@ +package policy + +import ( + "encoding/json" + "fmt" + "strings" + "time" + + messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" + recordv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/record/v1" + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/safedep/dry/tui/table" + "google.golang.org/protobuf/encoding/protojson" + + "github.com/safedep/cli/internal/cloudpolicy" + "github.com/safedep/cli/internal/tui" +) + +const ( + placeEndpoint = "endpoint" + placePullRequest = "pull-request" + placeScan = "scan" + + // shortSHA is the length of a commit hash in a table cell. + shortSHA = 12 +) + +// decisionView is one decision as the table and the plain output show it. +// The JSON output does not use it: it writes the messages of the server. +type decisionView struct { + ID string + DecidedAt *time.Time + Tool string + Outcome string + Ecosystem string + Name string + Version string + Revision uint64 + DefaultRev uint64 + Layer recordv1.Layer + Path string + RuleID string + OverrideID string + // override is the name of the override, or its id when the policy + // that the command read does not have it. + override string + PlaceKind string + Place string + URL string +} + +type decisionListResult struct { + decisions []*policyv1.PolicyDecision + views []decisionView + NextPageToken string +} + +func newDecisionListResult(res *policyv1.ListPolicyDecisionsResponse, overrideNames map[string]string) *decisionListResult { + out := &decisionListResult{ + decisions: res.GetDecisions(), + views: make([]decisionView, 0, len(res.GetDecisions())), + NextPageToken: res.GetPagination().GetNextPageToken(), + } + for _, d := range res.GetDecisions() { + out.views = append(out.views, newDecisionView(d, overrideNames)) + } + return out +} + +func newDecisionView(d *policyv1.PolicyDecision, overrideNames map[string]string) decisionView { + c := d.GetCitation() + pv := d.GetPackageVersion() + v := decisionView{ + ID: d.GetDecisionId(), + DecidedAt: cloudpolicy.TimeOf(d.GetDecidedAt()), + Tool: tui.EnumToken(d.GetTool().String(), decisionToolPrefix), + Outcome: tui.EnumToken(d.GetOutcome().String(), decisionOutcomePrefix), + Ecosystem: tui.EnumToken(pv.GetPackage().GetEcosystem().String(), "ECOSYSTEM_"), + Name: pv.GetPackage().GetName(), + Version: pv.GetVersion(), + Revision: c.GetRevision(), + DefaultRev: c.GetDefaultPolicyRevision(), + Layer: c.GetLayer(), + Path: c.GetPath(), + RuleID: c.GetRuleId(), + OverrideID: c.GetOverrideId(), + override: c.GetOverrideId(), + } + if name := overrideNames[v.OverrideID]; name != "" { + v.override = name + } + v.PlaceKind, v.Place, v.URL = describePlace(d.GetDecisionPoint()) + return v +} + +// describePlace names the place of a decision in one short cell. For pmg it +// is the hostname and the user, and one hint of the context: the CI +// repository, else the Kubernetes namespace and workload, else the agent. In +// CI and in Kubernetes the hostname is the name of a runner or a Pod, so the +// repository or the workload is the useful name. One hint keeps the cell +// short. The JSON output has the full context. +func describePlace(p *messagescontroltowerv1.DecisionPoint) (kind, place, url string) { + switch { + case p.HasEndpoint(): + e := p.GetEndpoint() + host := e.GetHostname() + if host == "" { + host = e.GetEndpointId() + } + if e.GetUsername() != "" { + host += " (" + e.GetUsername() + ")" + } + parts := []string{host} + k := e.GetKubernetes() + switch { + case e.GetCi().GetRepository() != "": + parts = append(parts, "ci "+e.GetCi().GetRepository()) + case k.GetNamespace() != "" || k.GetWorkloadName() != "": + parts = append(parts, "k8s "+strings.Trim(k.GetNamespace()+"/"+k.GetWorkloadName(), "/")) + case e.GetAgent().GetAgentName() != "": + parts = append(parts, "agent "+e.GetAgent().GetAgentName()) + } + return placeEndpoint, strings.Join(parts, sep), "" + case p.HasPullRequest(): + pr := p.GetPullRequest() + return placePullRequest, fmt.Sprintf("%s#%d", pr.GetRepositoryName(), pr.GetNumber()), pr.GetUrl() + case p.HasScan(): + s := p.GetScan() + ref := s.GetRef() + if ref == "" { + ref = s.GetCommitSha() + if len(ref) > shortSHA { + ref = ref[:shortSHA] + } + } + return placeScan, s.GetRepositoryName() + "@" + ref, s.GetUrl() + } + return "", "", "" +} + +func (v decisionView) pkg() string { + text := v.Ecosystem + "/" + v.Name + if v.Version != "" { + text += "@" + v.Version + } + return text +} + +// decidedBy names the rule or the field that decided, and the layer or the +// override that set it. +func (v decisionView) decidedBy() string { + var parts []string + switch { + case v.RuleID != "": + parts = append(parts, "rule "+v.RuleID) + case v.Path != "": + parts = append(parts, v.Path) + } + switch { + case v.override != "": + parts = append(parts, "override "+v.override) + case v.Layer == recordv1.Layer_LAYER_DEFAULT_POLICY: + parts = append(parts, "default policy") + case v.Layer == recordv1.Layer_LAYER_BASE: + parts = append(parts, "base") + } + return cloudpolicy.EmptyDash(strings.Join(parts, sep)) +} + +// revisionCell gives the tenant revision, and the default policy revision +// when the default policy decided or the tenant has no revision. +func (v decisionView) revisionCell() string { + var parts []string + if v.Revision > 0 { + parts = append(parts, fmt.Sprint(v.Revision)) + } + if v.DefaultRev > 0 && (v.Layer == recordv1.Layer_LAYER_DEFAULT_POLICY || v.Revision == 0) { + parts = append(parts, fmt.Sprintf("default %d", v.DefaultRev)) + } + return cloudpolicy.EmptyDash(strings.Join(parts, sep)) +} + +func (v decisionView) layer() string { + if v.Layer == recordv1.Layer_LAYER_UNSPECIFIED { + return "" + } + return tui.EnumToken(v.Layer.String(), "LAYER_") +} + +// RenderJSON writes the decisions as the server sent them, in protojson with +// the field names of the contract. +func (r *decisionListResult) RenderJSON() ([]byte, error) { + decisions := make([]json.RawMessage, 0, len(r.decisions)) + for _, d := range r.decisions { + b, err := protojson.MarshalOptions{UseProtoNames: true}.Marshal(d) + if err != nil { + return nil, fmt.Errorf("policy decision list: encode decision %s: %w", d.GetDecisionId(), err) + } + decisions = append(decisions, b) + } + return json.MarshalIndent(struct { + Decisions []json.RawMessage `json:"decisions"` + NextPageToken string `json:"next_page_token,omitempty"` + }{decisions, r.NextPageToken}, "", " ") +} + +func (r *decisionListResult) RenderTable() string { + now := time.Now() + withLink := false + for _, v := range r.views { + withLink = withLink || v.URL != "" + } + headers := []string{"WHEN", "TOOL", "PACKAGE", "OUTCOME", "DECIDED BY", "REV", "WHERE"} + if withLink { + headers = append(headers, "LINK") + } + rows := make([][]string, 0, len(r.views)) + for _, v := range r.views { + row := []string{ + humanTimeCell(v.DecidedAt, now), v.Tool, v.pkg(), v.Outcome, v.decidedBy(), v.revisionCell(), + cloudpolicy.EmptyDash(v.Place), + } + if withLink { + row = append(row, cloudpolicy.EmptyDash(v.URL)) + } + rows = append(rows, row) + } + t := table.New(). + Title("Policy decisions"). + Headers(headers...). + Rows(tui.EscapeCells(rows)...). + EmptyMessage("No policy decisions match. Try a wider --since window or fewer filters.") + if len(rows) > 0 { + footer := fmt.Sprintf("%d %s", len(rows), cloudpolicy.Plural(len(rows), "decision", "decisions")) + if r.NextPageToken != "" { + footer += ". More available: --page-token " + r.NextPageToken + } + t = t.Footer(footer) + } + return t.Render() +} + +func (r *decisionListResult) RenderPlain() string { + var b strings.Builder + b.WriteString("decided_at\tdecision_id\ttool\toutcome\tecosystem\tpackage\tversion\trevision\t" + + "default_policy_revision\tlayer\tpath\trule_id\toverride_id\tplace_kind\tplace\turl") + for _, v := range r.views { + b.WriteString("\n" + tui.PlainRow(cloudpolicy.RFC3339(v.DecidedAt), v.ID, v.Tool, v.Outcome, v.Ecosystem, + v.Name, v.Version, fmt.Sprint(v.Revision), fmt.Sprint(v.DefaultRev), v.layer(), v.Path, v.RuleID, + v.OverrideID, v.PlaceKind, v.Place, v.URL)) + } + return b.String() +} diff --git a/internal/cmd/policy/errors.go b/internal/cmd/policy/errors.go index c1f8c6a..5b3e326 100644 --- a/internal/cmd/policy/errors.go +++ b/internal/cmd/policy/errors.go @@ -5,8 +5,11 @@ import ( errorv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/error/v1" "github.com/safedep/dry/usefulerror" + "google.golang.org/genproto/googleapis/rpc/errdetails" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/safedep/cli/internal/tui" ) func newPolicyError(code, humanError, help string, cause error) error { @@ -89,3 +92,49 @@ func mapRuleError(op, ruleID string, err error) error { } return cause } + +// mapDecisionListError gives the recovery for the errors of the decision +// log: a tenant without policy management, a role that cannot read the +// policy, a bad filter or page token, and a server that does not have the +// RPC yet. +func mapDecisionListError(err error) error { + cause := fmt.Errorf("policy decision list: %w", err) + if reason, _ := usefulerror.ReasonOf(err); reason == errorv1.ErrorReason_ERROR_REASON_ENTITLEMENT_NOT_AVAILABLE { + return newPolicyError(usefulerror.ErrMissingEntitlements, + "Policy management is not enabled for this tenant", + "See the plans at https://safedep.io/pricing, or ask SafeDep support to enable it", + cause) + } + st, ok := status.FromError(err) + if !ok { + return cause + } + switch st.Code() { + case codes.PermissionDenied: + return newPolicyError(usefulerror.ErrAuthorizationFailed, + "Your role cannot read the policy decision log", + "Ask an Admin of the tenant for a role that can read the policy", + cause) + case codes.InvalidArgument: + if bad, ok := usefulerror.DetailAs[*errdetails.BadRequest](err); ok { + for _, v := range bad.GetFieldViolations() { + if v.GetField() == "pagination.page_token" { + return newPolicyError(usefulerror.ErrBadRequest, + "The page token is not valid", + "Run the command again without --page-token", + cause) + } + } + } + return newPolicyError(usefulerror.ErrBadRequest, + "The server refused the filters: "+tui.EscapeLine(st.Message()), + "See the filters: safedep policy decision list --help", + cause) + case codes.Unimplemented: + return newPolicyError(usefulerror.ErrServiceUnavailable, + "SafeDep Cloud does not have the policy decision log yet", + "Try again after the next SafeDep Cloud release", + cause) + } + return cause +} From ddaa59ade7a23886d9da431b046fce69ff3b4567 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Wed, 4 Nov 2026 18:59:40 +0000 Subject: [PATCH 09/17] fix(policy): accept a deleted override id, keep package names, check lengths A review of policy decision list found these problems: - --override with the id of a deleted override failed with "no policy override is named". A stored decision keeps that id, and the server matches it. The command now sends a value with the shape of an override id ("ov_" and 8 to 64 Crockford base32 characters) as is when the policy does not have it. Other unknown values still fail. - --package let the PURL parser change the name. The parser lowercases a PyPI name and drops the vendor of a Composer package, but the server compares the stored name exactly. The command now takes only the ecosystem from the parser and builds the name from the PURL as written: npm @scope/name, Maven group:artifact, the Go module path, Composer vendor/name. It refuses qualifiers and a subpath. - The command did not check the length limits of the filters. It now refuses a --rule or --override over 64 characters, a --path over 256, a --project over 128, an --endpoint over 100 and a package name over 255, with the flag name in the message. - duration.Window changed the help of audit event list from "for the events" to "for the time". The caller now gives the noun, so the audit text is the same as before. - The command built the filters three times. It now checks the flags once in Args and passes the result to the run. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MhRi597EX9odoSDXbVBsxz --- docs/cmd/policy-decision-list.md | 21 ++- internal/cmd/audit/list.go | 2 +- internal/cmd/policy/decision_list.go | 183 ++++++++++++++---------- internal/cmd/policy/decision_package.go | 96 +++++++++++++ internal/cmd/policy/decision_test.go | 183 ++++++++++++++++++++---- internal/duration/window.go | 6 +- internal/duration/window_test.go | 5 +- 7 files changed, 385 insertions(+), 111 deletions(-) create mode 100644 internal/cmd/policy/decision_package.go diff --git a/docs/cmd/policy-decision-list.md b/docs/cmd/policy-decision-list.md index 8cc3025..2699184 100644 --- a/docs/cmd/policy-decision-list.md +++ b/docs/cmd/policy-decision-list.md @@ -27,9 +27,9 @@ safedep policy decision list [--since DURATION] [--until DURATION] | `--outcome <outcome>` | Only decisions that `blocked` an install, `failed` a check, or `allowed` a package because a trust entry waived a verdict. | | `--revision <n>` | Only decisions that applied this tenant policy revision. | | `--rule <rule-id>` | Only decisions that this package rule made. | -| `--override <name\|id>` | Only decisions that this policy override made: a field that the override set, or a package rule that attaches to it. The command finds the name in the policy at `--revision`, or at head. | +| `--override <name\|id>` | Only decisions that this policy override made: a field that the override set, or a package rule that attaches to it. The command finds the name or the id in the policy at `--revision`, or at head. An override id that the policy does not have, such as the id of a deleted override, goes to the server as is. | | `--path <path>` | Only decisions that this field made, by its contract path, as `package_admission.cooldown.min_age`. | -| `--package <purl>` | Only decisions about this package, in all its versions. Give a PURL with no version, as `pkg:npm/lodash`. | +| `--package <purl>` | Only decisions about this package, in all its versions. Give a PURL with no version, no qualifiers and no subpath, as `pkg:npm/lodash`. The name must match the stored name exactly, with the same case. See [Package names](#package-names). | | `--project <id>` | Only decisions at a pull request or a scan of a repository that is bound to this project. | | `--endpoint <id>` | Only decisions that pmg made on this endpoint. | | `--limit <n>` | Page size. The server default applies when 0. | @@ -37,6 +37,23 @@ safedep policy decision list [--since DURATION] [--until DURATION] Inherits root flags `--output` and `--profile`. +The command refuses a value that the server refuses for its length: `--rule` +and `--override` take at most 64 characters, `--path` 256, `--project` 128, +`--endpoint` 100 and the package name 255. + +## Package names + +The command keeps the name of the PURL as you write it, and writes it in the +form that pmg and vet store: + +| Ecosystem | PURL | Name | +|-----------|------|------| +| npm | `pkg:npm/%40acme/ui` | `@acme/ui` | +| Maven | `pkg:maven/org.apache.commons/commons-lang3` | `org.apache.commons:commons-lang3` | +| Go | `pkg:golang/github.com/BurntSushi/toml` | `github.com/BurntSushi/toml` | +| Composer | `pkg:composer/laravel/framework` | `laravel/framework` | +| PyPI | `pkg:pypi/Requests` | `Requests` | + ## Columns | Column | Content | diff --git a/internal/cmd/audit/list.go b/internal/cmd/audit/list.go index 53855d7..69d9c17 100644 --- a/internal/cmd/audit/list.go +++ b/internal/cmd/audit/list.go @@ -94,7 +94,7 @@ func invalidFilter(cause error, help string) error { func newListRequest(in listInput, now time.Time) (*auditv1.ListAuditEventsRequest, error) { filters := &auditv1.ListAuditEventsRequest_Filters{} set := false - after, before, err := duration.Window(in.Since, in.Until, now) + after, before, err := duration.Window(in.Since, in.Until, now, "events") if err != nil { return nil, err } diff --git a/internal/cmd/policy/decision_list.go b/internal/cmd/policy/decision_list.go index f392725..e7d9206 100644 --- a/internal/cmd/policy/decision_list.go +++ b/internal/cmd/policy/decision_list.go @@ -5,13 +5,13 @@ import ( "fmt" "strings" "time" + "unicode/utf8" policyv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/policy/v1/policyv1grpc" - packagev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/package/v1" policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" - drypb "github.com/safedep/dry/api/pb" "github.com/safedep/dry/log" "github.com/spf13/cobra" + "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/timestamppb" "github.com/safedep/cli/internal/app" @@ -24,6 +24,14 @@ import ( const ( decisionToolPrefix = "DECISION_TOOL_" decisionOutcomePrefix = "DECISION_OUTCOME_" + + // The longest values that the server accepts in the filters of + // ListPolicyDecisionsRequest, in characters. + maxRuleIDLen = 64 + maxOverrideIDLen = 64 + maxPathLen = 256 + maxProjectIDLen = 128 + maxEndpointIDLen = 100 ) type decisionListInput struct { @@ -42,8 +50,21 @@ type decisionListInput struct { PageToken string } +// decisionQuery is the checked input of one list. The filters hold every +// flag except --override, which needs the policy to resolve a name. +type decisionQuery struct { + filters *policyv1.ListPolicyDecisionsRequest_Filters + override string + revision uint64 + pageSize uint32 + pageToken string +} + func decisionListCmd(a *app.App) *cobra.Command { - var in decisionListInput + var ( + in decisionListInput + query *decisionQuery + ) cmd := &cobra.Command{ Use: "list", Short: "List the decisions that the policy made, newest first", @@ -57,7 +78,8 @@ func decisionListCmd(a *app.App) *cobra.Command { if err := cobra.NoArgs(cmd, args); err != nil { return err } - _, err := newDecisionFilters(in, "", time.Now()) + var err error + query, err = newDecisionQuery(in, time.Now()) return err }, RunE: func(cmd *cobra.Command, _ []string) error { @@ -65,7 +87,7 @@ func decisionListCmd(a *app.App) *cobra.Command { if err != nil { return err } - res, err := runDecisionList(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), in, time.Now()) + res, err := runDecisionList(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), query) if err != nil { return err } @@ -107,50 +129,28 @@ func parseDecisionEnum(flag, token string, names map[int32]string, prefix string return n, nil } -// parseDecisionPackage reads a PURL with no version. The filter matches every -// version of the package, so a version in the PURL would mislead. -func parseDecisionPackage(purl string) (*packagev1.Package, error) { - help := "Give a PURL with no version, as in --package pkg:npm/lodash" - if !strings.HasPrefix(purl, "pkg:") { - return nil, invalidInputError(fmt.Errorf("--package %q is not a PURL", purl), help) +// checkLength refuses locally a value that the server refuses for its length. +func checkLength(flag, value string, limit int) error { + if n := utf8.RuneCountInString(value); n > limit { + return invalidInputError(fmt.Errorf("--%s is %d characters long: the limit is %d", flag, n, limit), + fmt.Sprintf("Give a --%s value of at most %d characters", flag, limit)) } - parsed, err := drypb.NewPurlPackageVersion(purl) - if err != nil { - return nil, invalidInputError(fmt.Errorf("--package %q: %w", purl, err), help) - } - pv := parsed.PackageVersion() - switch { - case pv.GetPackage().GetEcosystem() == packagev1.Ecosystem_ECOSYSTEM_UNSPECIFIED: - return nil, invalidInputError(fmt.Errorf("--package %q: unknown ecosystem", purl), help) - case pv.GetVersion() != "": - return nil, invalidInputError( - fmt.Errorf("--package %q has a version: the filter matches every version of the package", purl), help) - case pv.GetPackage().GetName() == "": - return nil, invalidInputError(fmt.Errorf("--package %q has no name", purl), help) - } - return pv.GetPackage(), nil + return nil } -// newDecisionFilters builds the request filters from the flags. overrideID is -// the id that --override resolved to. It returns nil when no filter is set. -func newDecisionFilters( - in decisionListInput, - overrideID string, - now time.Time, -) (*policyv1.ListPolicyDecisionsRequest_Filters, error) { +// newDecisionQuery checks the flags and builds the filters. It makes no +// RPC, so the command refuses a bad flag before it reads credentials. +func newDecisionQuery(in decisionListInput, now time.Time) (*decisionQuery, error) { filters := &policyv1.ListPolicyDecisionsRequest_Filters{} - set := false - after, before, err := duration.Window(in.Since, in.Until, now) + after, before, err := duration.Window(in.Since, in.Until, now, "decisions") if err != nil { return nil, err } if after != nil { filters.SetDecidedAfter(timestamppb.New(*after)) - set = true } if before != nil { filters.SetDecidedBefore(timestamppb.New(*before)) - set = true } if in.Tool != "" { n, err := parseDecisionEnum("tool", in.Tool, policyv1.DecisionTool_name, decisionToolPrefix, decisionToolTokens()) @@ -158,7 +158,6 @@ func newDecisionFilters( return nil, err } filters.SetTool(policyv1.DecisionTool(n)) - set = true } if in.Outcome != "" { n, err := parseDecisionEnum("outcome", in.Outcome, policyv1.DecisionOutcome_name, decisionOutcomePrefix, @@ -167,11 +166,9 @@ func newDecisionFilters( return nil, err } filters.SetOutcome(policyv1.DecisionOutcome(n)) - set = true } if in.Revision > 0 { filters.SetRevision(in.Revision) - set = true } if in.Package != "" { pkg, err := parseDecisionPackage(in.Package) @@ -179,27 +176,38 @@ func newDecisionFilters( return nil, err } filters.SetPackage(pkg) - set = true + } + // An override name has at most 63 characters, so the limit of the id + // also holds for a name. + if err := checkLength("override", in.Override, maxOverrideIDLen); err != nil { + return nil, err } for _, text := range []struct { + flag string value string + limit int apply func(string) }{ - {in.Rule, filters.SetRuleId}, - {overrideID, filters.SetOverrideId}, - {in.Path, filters.SetPath}, - {in.Project, filters.SetProjectId}, - {in.Endpoint, filters.SetEndpointId}, + {"rule", in.Rule, maxRuleIDLen, filters.SetRuleId}, + {"path", in.Path, maxPathLen, filters.SetPath}, + {"project", in.Project, maxProjectIDLen, filters.SetProjectId}, + {"endpoint", in.Endpoint, maxEndpointIDLen, filters.SetEndpointId}, } { - if text.value != "" { - text.apply(text.value) - set = true + if text.value == "" { + continue } + if err := checkLength(text.flag, text.value, text.limit); err != nil { + return nil, err + } + text.apply(text.value) } - if !set { - return nil, nil - } - return filters, nil + return &decisionQuery{ + filters: filters, + override: in.Override, + revision: in.Revision, + pageSize: in.PageSize, + pageToken: in.PageToken, + }, nil } // runDecisionList reads one page of decisions. It reads the policy only to @@ -209,34 +217,26 @@ func newDecisionFilters( func runDecisionList( ctx context.Context, client policyv1grpc.PolicyServiceClient, - in decisionListInput, - now time.Time, + q *decisionQuery, ) (*decisionListResult, error) { - if _, err := newDecisionFilters(in, "", now); err != nil { - return nil, err - } var snapshot *policyv1.Policy - overrideID := "" - if in.Override != "" { - _, p, err := readPolicyAt(ctx, client, in.Revision) + if q.override != "" { + _, p, err := readPolicyAt(ctx, client, q.revision) if err != nil { return nil, err } snapshot = p - o, err := findOverrideByNameOrID(p, in.Override) + id, err := resolveOverrideID(p, q.override) if err != nil { return nil, err } - overrideID = o.GetOverrideId() - } - filters, err := newDecisionFilters(in, overrideID, now) - if err != nil { - return nil, err + q.filters.SetOverrideId(id) } req := &policyv1.ListPolicyDecisionsRequest{} - req.SetPagination(paging.NewPaginationRequest(in.PageSize, in.PageToken)) - if filters != nil { - req.SetFilters(filters) + req.SetPagination(paging.NewPaginationRequest(q.pageSize, q.pageToken)) + // Every filter is optional, so a set filter always adds bytes. + if proto.Size(q.filters) > 0 { + req.SetFilters(q.filters) } res, err := client.ListPolicyDecisions(ctx, req) if err != nil { @@ -246,7 +246,7 @@ func runDecisionList( names := map[string]string{} if citesOverride(res.GetDecisions()) { if snapshot == nil { - _, p, err := readPolicyAt(ctx, client, in.Revision) + _, p, err := readPolicyAt(ctx, client, q.revision) if err != nil { // The names only label the output. The ids stay, so the list is // still correct without them. @@ -268,17 +268,46 @@ func citesOverride(decisions []*policyv1.PolicyDecision) bool { return false } -// findOverrideByNameOrID accepts the id too, because the JSON output of a -// decision gives the id of its override. A name wins over an id. -func findOverrideByNameOrID(p *policyv1.Policy, ref string) (*policyv1.Override, error) { +// resolveOverrideID finds the override by name, then by id, in the policy +// that the command read. A stored decision keeps the id of an override that +// a later revision deleted, so a value with the shape of an override id goes +// to the server as is when the policy does not have it. +func resolveOverrideID(p *policyv1.Policy, ref string) (string, error) { o, err := findOverride(p, ref) if err == nil { - return o, nil + return o.GetOverrideId(), nil } for _, o := range p.GetOverrides() { if o.GetOverrideId() == ref { - return o, nil + return ref, nil + } + } + if isOverrideID(ref) { + return ref, nil + } + return "", err +} + +const ( + overrideIDPrefix = "ov_" + // overrideIDAlphabet is lowercase Crockford base32, the alphabet of the + // ids that the server makes. + overrideIDAlphabet = "0123456789abcdefghjkmnpqrstvwxyz" + minOverrideIDBody = 8 +) + +// isOverrideID reports the shape of an id that the server gives an override: +// "ov_" and 8 to 64 characters of overrideIDAlphabet. It repeats id.Valid of +// dry, which the dry version of this CLI does not have yet. +func isOverrideID(s string) bool { + body, ok := strings.CutPrefix(s, overrideIDPrefix) + if !ok || len(body) < minOverrideIDBody || len(s) > maxOverrideIDLen { + return false + } + for i := 0; i < len(body); i++ { + if strings.IndexByte(overrideIDAlphabet, body[i]) < 0 { + return false } } - return nil, err + return true } diff --git a/internal/cmd/policy/decision_package.go b/internal/cmd/policy/decision_package.go new file mode 100644 index 0000000..af1a7e1 --- /dev/null +++ b/internal/cmd/policy/decision_package.go @@ -0,0 +1,96 @@ +package policy + +import ( + "errors" + "fmt" + "net/url" + "strings" + + packagev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/package/v1" + drypb "github.com/safedep/dry/api/pb" +) + +// maxPackageNameLen is the longest package name that the server accepts. +const maxPackageNameLen = 255 + +const packageHelp = "Give a PURL with no version, as in --package pkg:npm/lodash or pkg:maven/org.example/lib" + +// parseDecisionPackage reads the --package PURL. The server compares the +// stored package name exactly, so the command keeps the name as the user +// wrote it. A PURL parser changes some names: it lowercases a PyPI name and +// drops the vendor of a Composer package. Only the ecosystem comes from the +// parser. The name has the form that pmg and vet store: +// +// npm @scope/name +// Maven group:artifact +// Go the module path +// Composer vendor/name +// others the namespace and the name, joined with "/" +// +// The filter matches every version, so the command refuses a version. It +// also refuses qualifiers and a subpath, because the filter has no field for +// them. +func parseDecisionPackage(purl string) (*packagev1.Package, error) { + fail := func(cause error) (*packagev1.Package, error) { + return nil, invalidInputError(fmt.Errorf("--package %q: %w", purl, cause), packageHelp) + } + if !strings.HasPrefix(strings.ToLower(purl), "pkg:") { + return fail(errors.New("not a PURL")) + } + rest := strings.TrimLeft(purl[len("pkg:"):], "/") + switch { + case strings.Contains(rest, "?"): + return fail(errors.New("has qualifiers: the filter does not use them")) + case strings.Contains(rest, "#"): + return fail(errors.New("has a subpath: the filter does not use it")) + } + purlType, path, ok := strings.Cut(rest, "/") + if !ok || path == "" { + return fail(errors.New("has no name")) + } + // An "@" at the start of a segment begins an npm scope. Any other "@" + // begins a version. + if at := strings.LastIndexByte(path, '@'); at > 0 && path[at-1] != '/' { + return fail(errors.New("has a version: the filter matches every version of the package")) + } + + parsed, err := drypb.NewPurlPackageVersion(purl) + if err != nil { + return fail(err) + } + ecosystem := parsed.Ecosystem() + if ecosystem == packagev1.Ecosystem_ECOSYSTEM_UNSPECIFIED { + return fail(fmt.Errorf("unknown ecosystem %q", purlType)) + } + + var segments []string + for _, raw := range strings.Split(path, "/") { + if raw == "" { + continue + } + segment, err := url.PathUnescape(raw) + if err != nil { + return fail(err) + } + segments = append(segments, segment) + } + if len(segments) == 0 { + return fail(errors.New("has no name")) + } + + name := strings.Join(segments, "/") + if ecosystem == packagev1.Ecosystem_ECOSYSTEM_MAVEN { + if len(segments) != 2 { + return fail(errors.New("a Maven PURL needs the group and the artifact, as in pkg:maven/org.example/lib")) + } + name = segments[0] + ":" + segments[1] + } + if err := checkLength("package", name, maxPackageNameLen); err != nil { + return nil, err + } + + pkg := &packagev1.Package{} + pkg.SetEcosystem(ecosystem) + pkg.SetName(name) + return pkg, nil +} diff --git a/internal/cmd/policy/decision_test.go b/internal/cmd/policy/decision_test.go index 9d2ff69..b0a67c4 100644 --- a/internal/cmd/policy/decision_test.go +++ b/internal/cmd/policy/decision_test.go @@ -134,19 +134,14 @@ func decisionsResponse(next string, decisions ...*policyv1.PolicyDecision) *poli return res } -func TestNewDecisionFilters(t *testing.T) { +func TestNewDecisionQuery(t *testing.T) { day := 24 * time.Hour tests := []struct { - name string - in decisionListInput - overrideID string - check func(*testing.T, *policyv1.ListPolicyDecisionsRequest_Filters) - wantErr string + name string + in decisionListInput + check func(*testing.T, *policyv1.ListPolicyDecisionsRequest_Filters) + wantErr string }{ - { - name: "no filters", - check: func(t *testing.T, f *policyv1.ListPolicyDecisionsRequest_Filters) { assert.Nil(t, f) }, - }, { name: "time range", in: decisionListInput{Since: 7 * day, Until: day}, @@ -191,11 +186,10 @@ func TestNewDecisionFilters(t *testing.T) { }, }, { - name: "override id from the resolved name", - in: decisionListInput{Override: "payments"}, - overrideID: "ov_pay", + name: "override waits for the policy read", + in: decisionListInput{Override: "payments"}, check: func(t *testing.T, f *policyv1.ListPolicyDecisionsRequest_Filters) { - assert.Equal(t, "ov_pay", f.GetOverrideId()) + assert.False(t, f.HasOverrideId()) }, }, { @@ -230,13 +224,95 @@ func TestNewDecisionFilters(t *testing.T) { {name: "unknown tool", in: decisionListInput{Tool: "npm"}, wantErr: "unknown --tool value"}, {name: "unknown outcome", in: decisionListInput{Outcome: "denied"}, wantErr: "unknown --outcome value"}, {name: "package with a version", in: decisionListInput{Package: "pkg:npm/lodash@4.17.21"}, wantErr: "has a version"}, - {name: "package not a PURL", in: decisionListInput{Package: "lodash"}, wantErr: "is not a PURL"}, + {name: "package not a PURL", in: decisionListInput{Package: "lodash"}, wantErr: "not a PURL"}, {name: "package of an unknown ecosystem", in: decisionListInput{Package: "pkg:nope/x"}, wantErr: "unknown ecosystem"}, + {name: "rule too long", in: decisionListInput{Rule: strings.Repeat("r", 65)}, wantErr: "--rule is 65 characters long: the limit is 64"}, + {name: "override too long", in: decisionListInput{Override: strings.Repeat("o", 65)}, wantErr: "--override is 65 characters long"}, + {name: "path too long", in: decisionListInput{Path: strings.Repeat("p", 257)}, wantErr: "--path is 257 characters long: the limit is 256"}, + {name: "project too long", in: decisionListInput{Project: strings.Repeat("j", 129)}, wantErr: "--project is 129 characters long: the limit is 128"}, + {name: "endpoint too long", in: decisionListInput{Endpoint: strings.Repeat("e", 101)}, wantErr: "--endpoint is 101 characters long: the limit is 100"}, + {name: "limits count characters, not bytes", in: decisionListInput{Rule: strings.Repeat("\u00e9", 64)}, + check: func(t *testing.T, f *policyv1.ListPolicyDecisionsRequest_Filters) { assert.True(t, f.HasRuleId()) }}, {name: "until after since", in: decisionListInput{Since: time.Hour, Until: 2 * time.Hour}, wantErr: "--until must be shorter"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - f, err := newDecisionFilters(tt.in, tt.overrideID, fixedNow) + q, err := newDecisionQuery(tt.in, fixedNow) + if tt.wantErr != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantErr) + ue, ok := usefulerror.AsUsefulError(err) + require.True(t, ok) + assert.Equal(t, usefulerror.ErrBadRequest, ue.Code()) + return + } + require.NoError(t, err) + tt.check(t, q.filters) + }) + } +} + +func TestNewDecisionQuery_UnsetFlagsSetNoFilter(t *testing.T) { + q, err := newDecisionQuery(decisionListInput{}, fixedNow) + require.NoError(t, err) + f := q.filters + for name, has := range map[string]bool{ + "decided_after": f.HasDecidedAfter(), + "decided_before": f.HasDecidedBefore(), + "tool": f.HasTool(), + "outcome": f.HasOutcome(), + "revision": f.HasRevision(), + "rule_id": f.HasRuleId(), + "override_id": f.HasOverrideId(), + "path": f.HasPath(), + "package": f.HasPackage(), + "project_id": f.HasProjectId(), + "endpoint_id": f.HasEndpointId(), + } { + assert.False(t, has, name) + } + + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().ListPolicyDecisions(mock.Anything, mock.MatchedBy(func(r *policyv1.ListPolicyDecisionsRequest) bool { + return !r.HasFilters() + })).Return(decisionsResponse(""), nil) + _, err = runDecisionList(context.Background(), client, q) + require.NoError(t, err) +} + +func TestParseDecisionPackage(t *testing.T) { + tests := []struct { + purl string + ecosystem packagev1.Ecosystem + name string + wantErr string + }{ + {purl: "pkg:npm/lodash", ecosystem: packagev1.Ecosystem_ECOSYSTEM_NPM, name: "lodash"}, + {purl: "pkg:npm/%40acme/ui", ecosystem: packagev1.Ecosystem_ECOSYSTEM_NPM, name: "@acme/ui"}, + {purl: "pkg:npm/@acme/ui", ecosystem: packagev1.Ecosystem_ECOSYSTEM_NPM, name: "@acme/ui"}, + {purl: "pkg:pypi/Requests", ecosystem: packagev1.Ecosystem_ECOSYSTEM_PYPI, name: "Requests"}, + {purl: "pkg:pypi/typing_extensions", ecosystem: packagev1.Ecosystem_ECOSYSTEM_PYPI, name: "typing_extensions"}, + {purl: "pkg:maven/org.apache.commons/commons-lang3", ecosystem: packagev1.Ecosystem_ECOSYSTEM_MAVEN, name: "org.apache.commons:commons-lang3"}, + {purl: "pkg:golang/github.com/BurntSushi/toml", ecosystem: packagev1.Ecosystem_ECOSYSTEM_GO, name: "github.com/BurntSushi/toml"}, + {purl: "pkg:composer/laravel/framework", ecosystem: packagev1.Ecosystem_ECOSYSTEM_PACKAGIST, name: "laravel/framework"}, + {purl: "pkg:gem/Rails", ecosystem: packagev1.Ecosystem_ECOSYSTEM_RUBYGEMS, name: "Rails"}, + {purl: "pkg:cargo/serde", ecosystem: packagev1.Ecosystem_ECOSYSTEM_CARGO, name: "serde"}, + {purl: "pkg:nuget/Newtonsoft.Json", ecosystem: packagev1.Ecosystem_ECOSYSTEM_NUGET, name: "Newtonsoft.Json"}, + {purl: "pkg:github/actions/checkout", ecosystem: packagev1.Ecosystem_ECOSYSTEM_GITHUB_ACTIONS, name: "actions/checkout"}, + {purl: "pkg:npm/lodash@4.17.21", wantErr: "has a version"}, + {purl: "pkg:npm/%40acme/ui@1.0.0", wantErr: "has a version"}, + {purl: "pkg:npm/@acme/ui@1.0.0", wantErr: "has a version"}, + {purl: "pkg:npm/lodash?repository_url=https://r.example.com", wantErr: "has qualifiers"}, + {purl: "pkg:golang/github.com/acme/mod#sub/dir", wantErr: "has a subpath"}, + {purl: "pkg:maven/commons-lang3", wantErr: "needs the group and the artifact"}, + {purl: "pkg:npm/", wantErr: "has no name"}, + {purl: "lodash", wantErr: "not a PURL"}, + {purl: "pkg:nope/x", wantErr: "unknown ecosystem"}, + {purl: "pkg:npm/" + strings.Repeat("a", 256), wantErr: "--package is 256 characters long: the limit is 255"}, + } + for _, tt := range tests { + t.Run(tt.purl, func(t *testing.T) { + pkg, err := parseDecisionPackage(tt.purl) if tt.wantErr != "" { require.Error(t, err) assert.Contains(t, err.Error(), tt.wantErr) @@ -246,18 +322,27 @@ func TestNewDecisionFilters(t *testing.T) { return } require.NoError(t, err) - tt.check(t, f) + assert.Equal(t, tt.ecosystem, pkg.GetEcosystem()) + assert.Equal(t, tt.name, pkg.GetName()) }) } } +// listQuery is the checked query of valid flags. +func listQuery(t *testing.T, in decisionListInput) *decisionQuery { + t.Helper() + q, err := newDecisionQuery(in, fixedNow) + require.NoError(t, err) + return q +} + func TestRunDecisionList_RuleListsBothToolsWithThePlace(t *testing.T) { client := mocks.NewPolicyServiceClientMock(t) client.EXPECT().ListPolicyDecisions(mock.Anything, mock.MatchedBy(func(r *policyv1.ListPolicyDecisionsRequest) bool { return r.GetFilters().GetRuleId() == "r_9c1x4kq7dm" })).Return(decisionsResponse("", ruleDecisions()...), nil) - got, err := runDecisionList(context.Background(), client, decisionListInput{Rule: "r_9c1x4kq7dm"}, fixedNow) + got, err := runDecisionList(context.Background(), client, listQuery(t, decisionListInput{Rule: "r_9c1x4kq7dm"})) require.NoError(t, err) table := got.RenderTable() @@ -283,8 +368,7 @@ func TestRunDecisionList_CooldownShowsThePathAndTheDefaultRevision(t *testing.T) return r.GetFilters().GetPath() == "package_admission.cooldown.min_age" })).Return(decisionsResponse("", cooldown), nil) - got, err := runDecisionList(context.Background(), client, - decisionListInput{Path: "package_admission.cooldown.min_age"}, fixedNow) + got, err := runDecisionList(context.Background(), client, listQuery(t, decisionListInput{Path: "package_admission.cooldown.min_age"})) require.NoError(t, err) table := got.RenderTable() assert.Contains(t, table, "package_admission.cooldown.min_age · default policy") @@ -354,7 +438,7 @@ func TestRunDecisionList_Override(t *testing.T) { return r.GetFilters().GetOverrideId() == tt.wantID && r.GetFilters().GetRevision() == tt.in.Revision })).Return(decisionsResponse("", overrideDecision), nil) } - got, err := runDecisionList(context.Background(), client, tt.in, fixedNow) + got, err := runDecisionList(context.Background(), client, listQuery(t, tt.in)) if tt.wantErr != "" { require.Error(t, err) assert.Contains(t, err.Error(), tt.wantErr) @@ -367,6 +451,51 @@ func TestRunDecisionList_Override(t *testing.T) { } } +func TestRunDecisionList_TheIDOfADeletedOverrideIsSentAsIs(t *testing.T) { + const deleted = "ov_9c1x4kq7dm" + d := decision("d_old", policyv1.DecisionTool_DECISION_TOOL_PMG, policyv1.DecisionOutcome_DECISION_OUTCOME_BLOCKED, + "fresh", "0.0.1", citation(49, 12, "package_admission.cooldown.min_age", "", deleted, recordv1.Layer_LAYER_OVERRIDE), + atEndpoint(endpointPoint("dev-laptop", "alice"))) + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(headResponse(), nil).Once() + client.EXPECT().ListPolicyDecisions(mock.Anything, mock.MatchedBy(func(r *policyv1.ListPolicyDecisionsRequest) bool { + return r.GetFilters().GetOverrideId() == deleted + })).Return(decisionsResponse("", d), nil) + + got, err := runDecisionList(context.Background(), client, listQuery(t, decisionListInput{Override: deleted})) + require.NoError(t, err) + assert.Contains(t, got.RenderTable(), "override "+deleted, "the table names the deleted override by its id") +} + +func TestResolveOverrideID(t *testing.T) { + p := headPolicy() + tests := []struct { + ref string + want string + wantErr string + }{ + {ref: "payments", want: "ov_pay"}, + {ref: "ov_ci", want: "ov_ci"}, + {ref: "ov_9c1x4kq7dm", want: "ov_9c1x4kq7dm"}, + {ref: "ov_short", wantErr: `no policy override is named "ov_short"`}, + // "l" is not in the alphabet of the ids. + {ref: "ov_9c1x4kq7dl", wantErr: "no policy override is named"}, + {ref: "nope", wantErr: `no policy override is named "nope"`}, + } + for _, tt := range tests { + t.Run(tt.ref, func(t *testing.T) { + got, err := resolveOverrideID(p, tt.ref) + if tt.wantErr != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantErr) + return + } + require.NoError(t, err) + assert.Equal(t, tt.want, got) + }) + } +} + func TestRunDecisionList_OverrideNameReadFailureKeepsTheID(t *testing.T) { d := decision("d_ov", policyv1.DecisionTool_DECISION_TOOL_PMG, policyv1.DecisionOutcome_DECISION_OUTCOME_BLOCKED, "evil", "1.0.0", citation(47, 12, "", "r_1", "ov_gone", recordv1.Layer_LAYER_UNSPECIFIED), @@ -375,7 +504,7 @@ func TestRunDecisionList_OverrideNameReadFailureKeepsTheID(t *testing.T) { client.EXPECT().ListPolicyDecisions(mock.Anything, mock.Anything).Return(decisionsResponse("", d), nil) client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(nil, status.Error(codes.Unavailable, "down")) - got, err := runDecisionList(context.Background(), client, decisionListInput{}, fixedNow) + got, err := runDecisionList(context.Background(), client, listQuery(t, decisionListInput{})) require.NoError(t, err) assert.Contains(t, got.RenderTable(), "rule r_1 · override ov_gone") } @@ -436,7 +565,7 @@ func TestRunDecisionList_EscapesServerText(t *testing.T) { client := mocks.NewPolicyServiceClientMock(t) client.EXPECT().ListPolicyDecisions(mock.Anything, mock.Anything).Return(decisionsResponse("", d), nil) - got, err := runDecisionList(context.Background(), client, decisionListInput{}, fixedNow) + got, err := runDecisionList(context.Background(), client, listQuery(t, decisionListInput{})) require.NoError(t, err) for _, out := range []string{got.RenderTable(), got.RenderPlain()} { assert.NotContains(t, out, "\x1b") @@ -452,7 +581,7 @@ func TestRunDecisionList_Empty(t *testing.T) { client := mocks.NewPolicyServiceClientMock(t) client.EXPECT().ListPolicyDecisions(mock.Anything, mock.Anything).Return(decisionsResponse(""), nil) - got, err := runDecisionList(context.Background(), client, decisionListInput{}, fixedNow) + got, err := runDecisionList(context.Background(), client, listQuery(t, decisionListInput{})) require.NoError(t, err) assert.Contains(t, got.RenderTable(), "No policy decisions match") assert.Len(t, strings.Split(got.RenderPlain(), "\n"), 1, "plain writes only the header") @@ -467,7 +596,7 @@ func TestRunDecisionList_Paging(t *testing.T) { return r.GetPagination().GetPageSize() == 2 && r.GetPagination().GetPageToken() == "tok_1" && !r.HasFilters() })).Return(decisionsResponse("tok_2", ruleDecisions()...), nil) - got, err := runDecisionList(context.Background(), client, decisionListInput{PageSize: 2, PageToken: "tok_1"}, fixedNow) + got, err := runDecisionList(context.Background(), client, listQuery(t, decisionListInput{PageSize: 2, PageToken: "tok_1"})) require.NoError(t, err) assert.Contains(t, got.RenderTable(), "2 decisions. More available: --page-token tok_2") b, err := got.RenderJSON() @@ -479,7 +608,7 @@ func TestRunDecisionList_JSONHasTheRawMessages(t *testing.T) { client := mocks.NewPolicyServiceClientMock(t) client.EXPECT().ListPolicyDecisions(mock.Anything, mock.Anything).Return(decisionsResponse("", ruleDecisions()...), nil) - got, err := runDecisionList(context.Background(), client, decisionListInput{}, fixedNow) + got, err := runDecisionList(context.Background(), client, listQuery(t, decisionListInput{})) require.NoError(t, err) b, err := got.RenderJSON() require.NoError(t, err) @@ -547,7 +676,7 @@ func TestMapDecisionListError(t *testing.T) { t.Run(tt.name, func(t *testing.T) { client := mocks.NewPolicyServiceClientMock(t) client.EXPECT().ListPolicyDecisions(mock.Anything, mock.Anything).Return(nil, tt.err) - _, err := runDecisionList(context.Background(), client, decisionListInput{}, fixedNow) + _, err := runDecisionList(context.Background(), client, listQuery(t, decisionListInput{})) ue, ok := usefulerror.AsUsefulError(err) require.True(t, ok) assert.Equal(t, tt.wantCode, ue.Code()) diff --git a/internal/duration/window.go b/internal/duration/window.go index 15d8579..76d9ddc 100644 --- a/internal/duration/window.go +++ b/internal/duration/window.go @@ -11,14 +11,14 @@ import ( // range. Both are durations before now, and zero means no bound. after is // nil when since is zero, and before is nil when until is zero. More than // one list command reads these flags, so they all refuse the same input with -// the same message. -func Window(since, until time.Duration, now time.Time) (after, before *time.Time, err error) { +// the same message. noun names the listed items in the help, as "events". +func Window(since, until time.Duration, now time.Time, noun string) (after, before *time.Time, err error) { if since < 0 || until < 0 { return nil, nil, badWindow(errors.New("--since and --until must not be negative"), "Use a duration such as 7d") } if since > 0 && until >= since { return nil, nil, badWindow(errors.New("--until must be shorter than --since"), - "As in --since 7d --until 1d for the time from 7 days ago to 1 day ago") + "As in --since 7d --until 1d for the "+noun+" from 7 days ago to 1 day ago") } if since > 0 { t := now.Add(-since) diff --git a/internal/duration/window_test.go b/internal/duration/window_test.go index 0b4ecec..1b1a015 100644 --- a/internal/duration/window_test.go +++ b/internal/duration/window_test.go @@ -29,13 +29,16 @@ func TestWindow(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - after, before, err := Window(tt.since, tt.until, now) + after, before, err := Window(tt.since, tt.until, now, "events") if tt.wantErr != "" { require.Error(t, err) assert.Contains(t, err.Error(), tt.wantErr) ue, ok := usefulerror.AsUsefulError(err) require.True(t, ok) assert.Equal(t, usefulerror.ErrBadRequest, ue.Code()) + if tt.since > 0 && tt.until >= tt.since { + assert.Equal(t, "As in --since 7d --until 1d for the events from 7 days ago to 1 day ago", ue.Help()) + } return } require.NoError(t, err) From ff6bc1841a5e3b08bc6feae10b7d76809b39f91f Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Thu, 5 Nov 2026 07:03:20 +0000 Subject: [PATCH 10/17] docs(cmd): show only labels, warnings and default policy values that exist A review checked the command docs against control-tower main and pmg. Some examples showed output that this release cannot give: - The SafeDep default policy is at revision 1, not 12. It sets only scan_gate.fail_on: high and scan_gate.fail_on_attacks: fail, and no cooldown. policy show, policy edit, endpoint policy show, project policy show and policy decision list now show revision 1. The decision list example of the default policy is now a failed pull request check on scan_gate.fail_on. Its cooldown example cites a policy override. - control-tower never sends the warning LOW_ENFORCED_COVERAGE. The examples of policy change show and policy change publish no longer show it. The tests use ENDPOINT_LABEL_LOOSENS, a warning that the server sends. - No writer sets scm-property/ labels, and the server does not set scm/forge-project or scm/visibility. The server sets safedep.io/project-id, safedep.io/project-source, and scm/forge, scm/owner and scm/repo from the repository binding. The project docs, the help of project label and the examples now say so, and use custom/ labels for a selector. - No tool sends managed/ labels. pmg sends reported/os and reported/arch. endpoint list, endpoint label set and policy show now use reported/ and custom/ labels. The server writes a selector change of a preview as protojson. The table of policy change show and the warning of policy change publish now write it in the selector syntax, as in custom/criticality=high, as the docs show. plain and json keep the value of the server. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MhRi597EX9odoSDXbVBsxz --- docs/cmd/endpoint-label-set.md | 4 +- docs/cmd/endpoint-list.md | 2 +- docs/cmd/endpoint-policy-show.md | 2 +- docs/cmd/policy-change-publish.md | 1 - docs/cmd/policy-change-show.md | 14 +++--- docs/cmd/policy-decision-list.md | 24 +++++++++-- docs/cmd/policy-edit.md | 4 +- docs/cmd/policy-show.md | 8 ++-- docs/cmd/project-label-set.md | 7 +-- docs/cmd/project-list.md | 12 ++++-- docs/cmd/project-policy-show.md | 2 +- docs/cmd/project-show.md | 6 ++- internal/cloudpolicy/document_test.go | 2 +- internal/cloudpolicy/fixtures_test.go | 2 +- internal/cmd/endpoint/label.go | 6 +-- internal/cmd/endpoint/list.go | 2 +- internal/cmd/endpoint/policy_test.go | 4 +- internal/cmd/policy/change_preview.go | 22 +++++++++- internal/cmd/policy/change_test.go | 62 ++++++++++++++++++++++----- internal/cmd/policy/decision_test.go | 51 +++++++++++++++------- internal/cmd/policy/edit_test.go | 2 +- internal/cmd/policy/fixtures_test.go | 9 ++-- internal/cmd/policy/publish_test.go | 8 ++-- internal/cmd/policy/show_test.go | 8 ++-- internal/cmd/project/label.go | 5 ++- internal/cmd/project/policy_test.go | 16 +++---- 26 files changed, 195 insertions(+), 90 deletions(-) diff --git a/docs/cmd/endpoint-label-set.md b/docs/cmd/endpoint-label-set.md index 69e31a5..2226e20 100644 --- a/docs/cmd/endpoint-label-set.md +++ b/docs/cmd/endpoint-label-set.md @@ -17,8 +17,8 @@ safedep endpoint label set ENDPOINT... --label custom/KEY=VALUE... An endpoint is a ULID, a unique ULID prefix, or a hostname that `safedep endpoint list` cached. Give up to 100 endpoints. An admin writes only -`custom/` labels: the shared managed file sets `managed/` labels, and the tools -report `reported/` labels. +`custom/` labels. pmg reports the `reported/os` and `reported/arch` labels, as +`reported/os=darwin`. No tool sends `managed/` labels in this release. Until endpoint enrollment ships, an endpoint label is not an access boundary. Select on `custom/` labels for a policy override that loosens the policy. diff --git a/docs/cmd/endpoint-list.md b/docs/cmd/endpoint-list.md index 2cd2529..b8142f8 100644 --- a/docs/cmd/endpoint-list.md +++ b/docs/cmd/endpoint-list.md @@ -17,7 +17,7 @@ safedep endpoint list [flags] [--output table|plain|json] [--profile <name>] | `--blocked` | Only endpoints with at least one blocked package-guard install in the window. | | `--silent-for <duration>` | Only endpoints whose last sync is older than this duration (client-side filter; best-effort within `--limit`). | | `--search <substring>` | Case-insensitive substring match on hostname or name (client-side filter; best-effort within `--limit`). | -| `--selector <selector>` | Only endpoints whose labels match this label selector, as `managed/deployment-kind=laptop,custom/team=release`. The syntax is the one of [`safedep project list`](./project-list.md). | +| `--selector <selector>` | Only endpoints whose labels match this label selector, as `reported/os=darwin,custom/team=release`. The syntax is the one of [`safedep project list`](./project-list.md). | | `--applied-revision '<N'` | Only endpoints where a tool applies a policy revision lower than `N`, as `'<48'`. Quote the value, because the shell reads `<`. | | `--limit <n>` | Page size. Server default applies when `0` (the default). | | `--page-token <token>` | Continuation token from a prior response, to fetch the following page. | diff --git a/docs/cmd/endpoint-policy-show.md b/docs/cmd/endpoint-policy-show.md index 3e252fa..4dd05bf 100644 --- a/docs/cmd/endpoint-policy-show.md +++ b/docs/cmd/endpoint-policy-show.md @@ -25,7 +25,7 @@ safedep endpoint policy show arjuns-mbp --field package_admission.cooldown.min_a ``` Endpoint arjuns-mbp (01KR0EKN6PMW0ZRFRN992H1PKX) Policy revision 52 · overrides laptops (100) -Default policy revision 12 +Default policy revision 1 Package rules 211 (184 trust, 27 block) FIELD VALUE SOURCE EXCEPTIONS diff --git a/docs/cmd/policy-change-publish.md b/docs/cmd/policy-change-publish.md index ae112c2..d3e23f0 100644 --- a/docs/cmd/policy-change-publish.md +++ b/docs/cmd/policy-change-publish.md @@ -28,7 +28,6 @@ safedep policy change publish 18 -m "payments: fail on medium, 7d cooldown (CUST ``` Change 18 · TIGHTENS. An Admin can publish it -! LOW_ENFORCED_COVERAGE scan_gate.fail_on: 1 of 3 projects cannot enforce "medium" yet ✓ revision 47 published · TIGHTENS Projects resolve it at their next check. Endpoints apply it after their next policy fetch Endpoints that have not applied it yet: safedep endpoint list --applied-revision '<47' diff --git a/docs/cmd/policy-change-show.md b/docs/cmd/policy-change-show.md index 7b8ccd1..e4f6427 100644 --- a/docs/cmd/policy-change-show.md +++ b/docs/cmd/policy-change-show.md @@ -24,18 +24,17 @@ Author alice Updated 2m ago What changes -WHERE WHAT OLD -> NEW DIRECTION -override "payments" scan_gate.fail_on high -> medium TIGHTENS -override "payments" package_admission.cooldown.min_age - -> 7d TIGHTENS -override "payments" selector scm-property/criticality=high -> custom/criticality=high LOOSENS +WHERE WHAT OLD -> NEW DIRECTION +override "payments" scan_gate.fail_on high -> medium TIGHTENS +override "payments" package_admission.cooldown.min_age - -> 7d TIGHTENS +override "payments" selector custom/team=pay -> custom/criticality=high LOOSENS Impact · subjects matched: 3 projects, 0 endpoints FIELD ENFORCED PARTIAL DETECT ONLY NOT SUPPORTED scan_gate.fail_on = medium 2 1 0 0 Warnings -CODE SUBJECT MESSAGE -LOW_ENFORCED_COVERAGE scan_gate.fail_on 1 of 3 projects cannot enforce "medium" yet +No warnings. Direction LOOSENS. Only an Admin can publish it, and Admins and Owners get a notice ``` @@ -48,7 +47,8 @@ published or deleted change shows no preview. `json` holds `change` and `preview` (head revision, stale, direction, changes, matched counts, coverage, warnings). `plain` writes `key<TAB>value` lines and one `change<TAB>where<TAB>what<TAB>old<TAB>new<TAB>direction` line for each change. -Values in `plain` and `json` are exact, as `168h`. The table humanizes them, as `7d`. +Values in `plain` and `json` are exact, as `168h`, and a selector is the protojson +that the server sends. The table humanizes them, as `7d` and `custom/criticality=high`. ## Authentication diff --git a/docs/cmd/policy-decision-list.md b/docs/cmd/policy-decision-list.md index 2699184..63b7124 100644 --- a/docs/cmd/policy-decision-list.md +++ b/docs/cmd/policy-decision-list.md @@ -63,7 +63,7 @@ form that pmg and vet store: | `PACKAGE` | The ecosystem, the name and the version. | | `OUTCOME` | `blocked`, `failed` or `allowed`. | | `DECIDED BY` | The package rule, or the field path, and the layer or the override that set it: `default policy`, `base` or `override NAME`. | -| `REV` | The tenant policy revision. When the default policy decided, also its revision, as `47 · default 12`. | +| `REV` | The tenant policy revision. When the default policy decided, also its revision, as `47 · default 1`. | | `WHERE` | For pmg, the hostname and the user, and one hint: the CI repository, else the Kubernetes namespace and workload, else the agent. For a check, the repository and the pull request number. For a scan, the repository and the branch or the commit. | | `LINK` | The check run, the pull request or the CI run. The table has this column only when a row has a link. | @@ -83,7 +83,8 @@ WHEN TOOL PACKAGE OUTCOME DECIDED BY REV WHE 2 decisions ``` -The installs that the cooldown blocked in the last day: +The installs that a cooldown blocked in the last day. The SafeDep default policy +sets no cooldown, so the policy base or a policy override decided each one: ```bash safedep policy decision list --path package_admission.cooldown.min_age --since 1d @@ -91,8 +92,23 @@ safedep policy decision list --path package_admission.cooldown.min_age --since 1 ``` Policy decisions -WHEN TOOL PACKAGE OUTCOME DECIDED BY REV WHERE -5m ago pmg npm/fresh@0.0.1 blocked package_admission.cooldown.min_age · default policy 47 · default 12 dev-laptop (alice) +WHEN TOOL PACKAGE OUTCOME DECIDED BY REV WHERE +5m ago pmg npm/fresh@0.0.1 blocked package_admission.cooldown.min_age · override laptops 47 dev-laptop (alice) +1 decision +``` + +The pull request checks that the SafeDep default policy failed. The default +policy at revision 1 sets `scan_gate.fail_on: high` and +`scan_gate.fail_on_attacks: fail`: + +```bash +safedep policy decision list --path scan_gate.fail_on --tool pull-request-check +``` + +``` +Policy decisions +WHEN TOOL PACKAGE OUTCOME DECIDED BY REV WHERE LINK +2h ago pull-request-check npm/lodash@4.17.20 failed scan_gate.fail_on · default policy 47 · default 1 acme/payments-api#42 https://github.com/acme/payments-api/runs/7 1 decision ``` diff --git a/docs/cmd/policy-edit.md b/docs/cmd/policy-edit.md index f8bb515..9cd6d42 100644 --- a/docs/cmd/policy-edit.md +++ b/docs/cmd/policy-edit.md @@ -32,8 +32,8 @@ The file starts with a header that shows the layers: # Saving creates a draft change. Nothing applies until you publish it. # # Layers, from low to high, for each subject: -# 1. SafeDep default policy (read-only, revision 12): -# scan_gate.fail_on: high +# 1. SafeDep default policy (read-only, revision 1): +# scan_gate.fail_on: high · scan_gate.fail_on_attacks: fail # 2. base - applies to every endpoint and project of this tenant # 3. overrides - apply to the subjects that their selector matches. # For each field, the highest priority that sets it wins. diff --git a/docs/cmd/policy-show.md b/docs/cmd/policy-show.md index 4420b53..a2e74db 100644 --- a/docs/cmd/policy-show.md +++ b/docs/cmd/policy-show.md @@ -26,12 +26,12 @@ Policy platform-eng.acme.safedep.io Head revision 46 · published 2d ago by alice · "cooldown 5d for laptops" Open changes none Package rules 211 (184 trust, 27 block) · 23 expire in 7d -Default policy revision 12 · scan_gate.fail_on: high +Default policy revision 1 · scan_gate.fail_on: high · scan_gate.fail_on_attacks: fail Overrides (priority, highest first) -PRIORITY NAME SELECTOR EXPIRES DESCRIPTION -300 ci managed/deployment-kind=ci - - -200 payments custom/criticality=high - - +PRIORITY NAME SELECTOR EXPIRES DESCRIPTION +300 ci custom/environment=ci - - +200 payments custom/criticality=high - - ``` Read the policy settings document as JSON: diff --git a/docs/cmd/project-label-set.md b/docs/cmd/project-label-set.md index 2242c3c..fa734c1 100644 --- a/docs/cmd/project-label-set.md +++ b/docs/cmd/project-label-set.md @@ -17,9 +17,10 @@ safedep project label set [PROJECT_NAME...] [--project-id ID]... --label custom/ | `--project-id <id>` | A project ID instead of a name. Repeatable. | Give up to 100 projects by exact name or ID. An admin writes only `custom/` -labels. The CLI rejects any other prefix before the request: the forge sync -writes `scm/` and `scm-property/` labels, and the server writes `safedep.io/` -labels. A value has at most 63 characters. +labels. The CLI rejects any other prefix before the request. The server sets the +`safedep.io/` labels (`safedep.io/project-id`, `safedep.io/project-source`), and +the `scm/` labels (`scm/forge`, `scm/owner`, `scm/repo`) from the repository of a +project. A value has at most 63 characters. ## Examples diff --git a/docs/cmd/project-list.md b/docs/cmd/project-list.md index d340a1d..40cab51 100644 --- a/docs/cmd/project-list.md +++ b/docs/cmd/project-list.md @@ -35,17 +35,21 @@ A selector has terms separated by commas. The terms AND together: Find the projects that a policy override will select: ```bash -safedep project list --selector scm-property/criticality=high +safedep project list --selector custom/criticality=high ``` ``` Projects -PROJECT SOURCE LABELS VULNS VIOLATIONS CREATED -acme/payments-api github custom/team=pay, scm-property/criticality=high 3 - 3d ago -acme/ledger github scm-property/criticality=high 0 - 1mo ago +PROJECT SOURCE LABELS VULNS VIOLATIONS CREATED +acme/payments-api github custom/criticality=high, custom/team=pay, safedep.io/project-id=01K88WX3G9RGAK8T3N5YJMFQN1, safedep.io/project-source=github, scm/forge=github, scm/owner=acme, scm/repo=payments-api 3 - 3d ago +acme/ledger github custom/criticality=high, safedep.io/project-id=01K88WX7ZQ4T2M6B9C1D3E5F7G, safedep.io/project-source=github, scm/forge=github, scm/owner=acme, scm/repo=ledger 0 - 1mo ago 2 projects ``` +The labels are every label of a project: the `custom/` labels that an admin +sets, the `safedep.io/` labels of the server, and the `scm/` labels of a project +that has a repository binding. + ## Output `json` holds `projects` (project id, name, source, origin URL, labels, counts, diff --git a/docs/cmd/project-policy-show.md b/docs/cmd/project-policy-show.md index 1b07da1..673c2a4 100644 --- a/docs/cmd/project-policy-show.md +++ b/docs/cmd/project-policy-show.md @@ -28,7 +28,7 @@ safedep project policy show acme/payments-api --field scan_gate.fail_on,package_ ``` Project acme/payments-api Policy revision 47 · overrides payments (200) -Default policy revision 12 +Default policy revision 1 Package rules 211 (184 trust, 27 block) FIELD VALUE SOURCE EXCEPTIONS diff --git a/docs/cmd/project-show.md b/docs/cmd/project-show.md index 5bb4356..e1ead42 100644 --- a/docs/cmd/project-show.md +++ b/docs/cmd/project-show.md @@ -17,11 +17,13 @@ safedep project show PAY/settlement ``` Project PAY/settlement -ID 3f1c... +ID 01K88WX3G9RGAK8T3N5YJMFQN1 Source bitbucket · https://bitbucket.org/acme/settlement -Labels safedep.io/project-source=bitbucket +Labels safedep.io/project-id=01K88WX3G9RGAK8T3N5YJMFQN1 + safedep.io/project-source=bitbucket scm/forge=bitbucket scm/owner=acme + scm/repo=settlement Policy revision 46 · no override matches · base only Vulnerabilities 0 Violations - diff --git a/internal/cloudpolicy/document_test.go b/internal/cloudpolicy/document_test.go index 2ba3a29..4cec783 100644 --- a/internal/cloudpolicy/document_test.go +++ b/internal/cloudpolicy/document_test.go @@ -31,7 +31,7 @@ overrides: name: ci priority: 300 selector: - matchLabels: {managed/deployment-kind: ci} + matchLabels: {custom/environment: ci} spec: package_admission: cooldown: diff --git a/internal/cloudpolicy/fixtures_test.go b/internal/cloudpolicy/fixtures_test.go index 7981a24..4a8a80a 100644 --- a/internal/cloudpolicy/fixtures_test.go +++ b/internal/cloudpolicy/fixtures_test.go @@ -43,7 +43,7 @@ func samplePolicy() *policyv1.Policy { o.SetSpec(specWith(scangatev1.Severity_SEVERITY_MEDIUM, 168*time.Hour)) ci := &messagescontroltowerv1.LabelSelector{} - ci.SetMatchLabels(map[string]string{"managed/deployment-kind": "ci"}) + ci.SetMatchLabels(map[string]string{"custom/environment": "ci"}) o2 := &policyv1.Override{} o2.SetOverrideId("ov_2") o2.SetName("ci") diff --git a/internal/cmd/endpoint/label.go b/internal/cmd/endpoint/label.go index 83211c8..f8d7e3f 100644 --- a/internal/cmd/endpoint/label.go +++ b/internal/cmd/endpoint/label.go @@ -19,9 +19,9 @@ func labelCmd(a *app.App) *cobra.Command { Use: "label", Short: "Set or delete the custom labels of endpoints", Long: "Set or delete the custom/ labels of endpoints. A policy override selects endpoints by their " + - "labels. An admin writes only custom/ labels. The shared managed file sets managed/ labels, and " + - "the tools report reported/ labels. A label change takes effect at the next policy fetch of " + - "each endpoint.", + "labels. An admin writes only custom/ labels. pmg reports the reported/os and reported/arch " + + "labels. No tool sends managed/ labels in this release. A label change takes effect at the next " + + "policy fetch of each endpoint.", } parent.AddCommand(labelSetCmd(a), labelDeleteCmd(a)) return parent diff --git a/internal/cmd/endpoint/list.go b/internal/cmd/endpoint/list.go index b60cfeb..134d90e 100644 --- a/internal/cmd/endpoint/list.go +++ b/internal/cmd/endpoint/list.go @@ -94,7 +94,7 @@ func listCmd(a *app.App) *cobra.Command { f.BoolVar(&onlyBlocked, "blocked", false, "only endpoints with at least one blocked install in the window") f.DurationVar(&silentFor, "silent-for", 0, "only endpoints not seen for at least this duration (client-side; best-effort within --limit)") f.StringVar(&searchFlag, "search", "", "case-insensitive substring match on hostname/name (client-side; best-effort within --limit)") - f.StringVar(&selectorFlag, "selector", "", "filter: a label selector, as in managed/deployment-kind=laptop,custom/team=release") + f.StringVar(&selectorFlag, "selector", "", "filter: a label selector, as in reported/os=darwin,custom/team=release") f.StringVar(&appliedFlag, "applied-revision", "", "filter: '<N' keeps endpoints where a tool applies a policy revision lower than N, as in '<48'") f.Uint32Var(&pageSize, "limit", 0, "page size; server default when 0") f.StringVar(&pageTokenFlag, "page-token", "", "continuation token from a prior response") diff --git a/internal/cmd/endpoint/policy_test.go b/internal/cmd/endpoint/policy_test.go index 1432831..763b3b6 100644 --- a/internal/cmd/endpoint/policy_test.go +++ b/internal/cmd/endpoint/policy_test.go @@ -59,14 +59,14 @@ func TestServiceList_SendsThePolicyFilters(t *testing.T) { res.SetEndpoints([]*controltowerv1.ListEndpointsResponse_EndpointWithAttributes{ep}) fake := &listEndpointsClient{res: res} - selector, applied, err := parsePolicyFilters("managed/deployment-kind=laptop", "<48") + selector, applied, err := parsePolicyFilters("reported/os=darwin", "<48") require.NoError(t, err) out, err := (&Service{client: fake}).List(context.Background(), ListInput{LabelSelector: selector, AppliedRevisionBelow: applied}) require.NoError(t, err) f := fake.req.GetFilter() assert.Equal(t, uint64(48), f.GetAppliedPolicyRevisionBelow()) - assert.Equal(t, map[string]string{"managed/deployment-kind": "laptop"}, f.GetLabelSelector().GetMatchLabels()) + assert.Equal(t, map[string]string{"reported/os": "darwin"}, f.GetLabelSelector().GetMatchLabels()) require.Len(t, out.Endpoints, 1) assert.Equal(t, []ToolPolicy{ {Tool: "pmg", Version: "2.3.1", Revision: 47, State: "stale", ReportedAt: out.Endpoints[0].ToolPolicies[0].ReportedAt}, diff --git a/internal/cmd/policy/change_preview.go b/internal/cmd/policy/change_preview.go index 40de860..44b31c9 100644 --- a/internal/cmd/policy/change_preview.go +++ b/internal/cmd/policy/change_preview.go @@ -4,8 +4,10 @@ import ( "fmt" "strings" + messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" recordv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/record/v1" policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "google.golang.org/protobuf/encoding/protojson" "github.com/safedep/cli/internal/cloudpolicy" "github.com/safedep/cli/internal/tui" @@ -82,8 +84,8 @@ func newPreviewView(res *policyv1.PreviewPolicyChangeResponse) *previewView { Old: c.GetOldValue(), New: c.GetNewValue(), Direction: directionToken(c.GetDirection()), - oldHuman: cloudpolicy.EmptyDash(c.GetOldValue()), - newHuman: cloudpolicy.EmptyDash(c.GetNewValue()), + oldHuman: overrideChangeValue(c.GetKind(), c.GetOldValue()), + newHuman: overrideChangeValue(c.GetKind(), c.GetNewValue()), }) } for _, op := range res.GetPackageRuleOperations() { @@ -116,6 +118,22 @@ func newPreviewView(res *policyv1.PreviewPolicyChangeResponse) *previewView { return v } +// overrideChangeValue gives the human form of a value of an override change. +// The server writes a selector as protojson. The table and the publish +// warning show it in the selector syntax of the CLI, as in +// custom/criticality=high. A value that does not parse stays as the server +// wrote it. +func overrideChangeValue(kind policyv1.OverrideChangeKind, value string) string { + if kind != policyv1.OverrideChangeKind_OVERRIDE_CHANGE_KIND_SELECTOR || value == "" { + return cloudpolicy.EmptyDash(value) + } + selector := &messagescontroltowerv1.LabelSelector{} + if err := protojson.Unmarshal([]byte(value), selector); err != nil { + return value + } + return cloudpolicy.FormatSelector(selector) +} + func ruleOperationItems(ops []*policyv1.PackageRuleOperation) []changeItem { out := make([]changeItem, 0, len(ops)) for _, op := range ops { diff --git a/internal/cmd/policy/change_test.go b/internal/cmd/policy/change_test.go index 839fe3c..cf46b68 100644 --- a/internal/cmd/policy/change_test.go +++ b/internal/cmd/policy/change_test.go @@ -68,8 +68,9 @@ func previewResponse() *policyv1.PreviewPolicyChangeResponse { selector := &policyv1.OverrideChange{} selector.SetOverrideName("payments") selector.SetKind(policyv1.OverrideChangeKind_OVERRIDE_CHANGE_KIND_SELECTOR) - selector.SetOldValue("scm-property/criticality=high") - selector.SetNewValue("custom/criticality=high") + // The server writes a selector as protojson. + selector.SetOldValue(`{"matchLabels":{"custom/team":"pay"}}`) + selector.SetNewValue(`{"matchLabels":{"custom/criticality":"high"}}`) selector.SetDirection(policyv1.ChangeDirection_CHANGE_DIRECTION_LOOSENS) coverage := &policyv1.CoverageSummary{} @@ -78,11 +79,6 @@ func previewResponse() *policyv1.PreviewPolicyChangeResponse { coverage.SetEnforceCount(2) coverage.SetPartialCount(1) - warning := &policyv1.PreviewWarning{} - warning.SetCode(policyv1.PreviewWarningCode_PREVIEW_WARNING_CODE_LOW_ENFORCED_COVERAGE) - warning.SetSubject("scan_gate.fail_on") - warning.SetMessage(`1 of 3 projects cannot enforce "medium" yet`) - res := &policyv1.PreviewPolicyChangeResponse{} res.SetHeadRevision(46) res.SetChanges([]*policyv1.PathChange{field, cooldown}) @@ -90,6 +86,17 @@ func previewResponse() *policyv1.PreviewPolicyChangeResponse { res.SetDirection(policyv1.ChangeDirection_CHANGE_DIRECTION_LOOSENS) res.SetMatchedProjectCount(3) res.SetCoverage([]*policyv1.CoverageSummary{coverage}) + return res +} + +// withEndpointLabelWarning moves the selector of "payments" to a label that an +// endpoint sends, and adds the warning that the server gives for it. +func withEndpointLabelWarning(res *policyv1.PreviewPolicyChangeResponse) *policyv1.PreviewPolicyChangeResponse { + res.GetOverrideChanges()[0].SetNewValue(`{"matchLabels":{"reported/os":"linux"}}`) + warning := &policyv1.PreviewWarning{} + warning.SetCode(policyv1.PreviewWarningCode_PREVIEW_WARNING_CODE_ENDPOINT_LABEL_LOOSENS) + warning.SetSubject("payments") + warning.SetMessage("a policy override that loosens selects on a label that an endpoint can send") res.SetWarnings([]*policyv1.PreviewWarning{warning}) return res } @@ -109,8 +116,8 @@ func TestRunChangeShow_PreviewsAnOpenChange(t *testing.T) { `override "payments"`, "high -> medium", "- -> 7d", - "scm-property/criticality=high -> custom/criticality=high", - "LOW_ENFORCED_COVERAGE", + "custom/team=pay -> custom/criticality=high", + "No warnings.", "subjects matched: 3 projects, 0 endpoints", "scan_gate.fail_on = medium", "LOOSENS. Only an Admin can publish it", @@ -123,7 +130,21 @@ func TestRunChangeShow_PreviewsAnOpenChange(t *testing.T) { plain := got.RenderPlain() assert.Contains(t, plain, "change_id\t18\ntitle\tpayments: medium + cooldown\nstate\topen\nbase_revision\t46") assert.Contains(t, plain, "change\toverride \"payments\"\tscan_gate.fail_on\thigh\tmedium\tTIGHTENS") - assert.Contains(t, plain, "warning\tLOW_ENFORCED_COVERAGE\tscan_gate.fail_on\t1 of 3 projects cannot enforce \"medium\" yet") + assert.Contains(t, plain, "change\toverride \"payments\"\tselector\t{\"matchLabels\":{\"custom/team\":\"pay\"}}\t", "plain keeps the value of the server") +} + +func TestRunChangeShow_Warnings(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicyChange(mock.Anything, mock.Anything).Return(changeResponse(openChange("18")), nil) + client.EXPECT().PreviewPolicyChange(mock.Anything, mock.Anything).Return(withEndpointLabelWarning(previewResponse()), nil) + + got, err := runChangeShow(context.Background(), client, "18") + require.NoError(t, err) + table := got.RenderTable() + assert.Contains(t, table, "custom/team=pay -> reported/os=linux") + assert.Contains(t, table, "ENDPOINT_LABEL_LOOSENS") + assert.Contains(t, got.RenderPlain(), + "warning\tENDPOINT_LABEL_LOOSENS\tpayments\ta policy override that loosens selects on a label that an endpoint can send") } func TestRunChangeShow_StaleChange(t *testing.T) { @@ -291,3 +312,24 @@ func TestChangeCreate(t *testing.T) { require.NoError(t, err) assert.Equal(t, "restores scan_gate from revision 46 · package rules stay at head", restoreSummary(got.GetRestore())) } + +func TestOverrideChangeValue(t *testing.T) { + selector := policyv1.OverrideChangeKind_OVERRIDE_CHANGE_KIND_SELECTOR + tests := []struct { + name string + kind policyv1.OverrideChangeKind + value string + want string + }{ + {"match labels", selector, `{"matchLabels":{"custom/team":"pay","custom/criticality":"high"}}`, "custom/criticality=high, custom/team=pay"}, + {"match expressions", selector, `{"matchExpressions":[{"key":"scm/owner","operator":"LABEL_SELECTOR_OPERATOR_IN","values":["acme"]}]}`, "scm/owner in (acme)"}, + {"no value", selector, "", "-"}, + {"not protojson", selector, "custom/team=pay", "custom/team=pay"}, + {"another kind", policyv1.OverrideChangeKind_OVERRIDE_CHANGE_KIND_PRIORITY, "200", "200"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, overrideChangeValue(tt.kind, tt.value)) + }) + } +} diff --git a/internal/cmd/policy/decision_test.go b/internal/cmd/policy/decision_test.go index b0a67c4..f683c69 100644 --- a/internal/cmd/policy/decision_test.go +++ b/internal/cmd/policy/decision_test.go @@ -116,11 +116,11 @@ func decision( func ruleDecisions() []*policyv1.PolicyDecision { return []*policyv1.PolicyDecision{ decision("d_pmg", policyv1.DecisionTool_DECISION_TOOL_PMG, policyv1.DecisionOutcome_DECISION_OUTCOME_BLOCKED, - "evil", "1.0.0", citation(47, 12, "", "r_9c1x4kq7dm", "", recordv1.Layer_LAYER_UNSPECIFIED), + "evil", "1.0.0", citation(47, 1, "", "r_9c1x4kq7dm", "", recordv1.Layer_LAYER_UNSPECIFIED), atEndpoint(endpointPoint("dev-laptop", "alice"))), decision("d_pr", policyv1.DecisionTool_DECISION_TOOL_PULL_REQUEST_CHECK, policyv1.DecisionOutcome_DECISION_OUTCOME_FAILED, "evil", "1.0.1", - citation(47, 12, "", "r_9c1x4kq7dm", "", recordv1.Layer_LAYER_UNSPECIFIED), + citation(47, 1, "", "r_9c1x4kq7dm", "", recordv1.Layer_LAYER_UNSPECIFIED), atPullRequest("acme/payments-api", 42, "https://github.com/acme/payments-api/runs/7")), } } @@ -355,31 +355,50 @@ func TestRunDecisionList_RuleListsBothToolsWithThePlace(t *testing.T) { } plain := strings.Split(got.RenderPlain(), "\n") require.Len(t, plain, 3) - assert.Contains(t, plain[1], "\td_pmg\tpmg\tblocked\tnpm\tevil\t1.0.0\t47\t12\t\t\tr_9c1x4kq7dm\t\tendpoint\tdev-laptop (alice)\t") + assert.Contains(t, plain[1], "\td_pmg\tpmg\tblocked\tnpm\tevil\t1.0.0\t47\t1\t\t\tr_9c1x4kq7dm\t\tendpoint\tdev-laptop (alice)\t") assert.Contains(t, plain[2], "\tpull-request\tacme/payments-api#42\thttps://github.com/acme/payments-api/runs/7") } -func TestRunDecisionList_CooldownShowsThePathAndTheDefaultRevision(t *testing.T) { +// The SafeDep default policy sets only the scan gate, so the pull request +// check is the tool whose decisions cite it. +func TestRunDecisionList_DefaultPolicyShowsThePathAndTheDefaultRevision(t *testing.T) { + failed := decision("d_gate", policyv1.DecisionTool_DECISION_TOOL_PULL_REQUEST_CHECK, + policyv1.DecisionOutcome_DECISION_OUTCOME_FAILED, "lodash", "4.17.20", + citation(47, 1, "scan_gate.fail_on", "", "", recordv1.Layer_LAYER_DEFAULT_POLICY), + atPullRequest("acme/payments-api", 42, "https://github.com/acme/payments-api/runs/7")) + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().ListPolicyDecisions(mock.Anything, mock.MatchedBy(func(r *policyv1.ListPolicyDecisionsRequest) bool { + return r.GetFilters().GetPath() == "scan_gate.fail_on" + })).Return(decisionsResponse("", failed), nil) + + got, err := runDecisionList(context.Background(), client, listQuery(t, decisionListInput{Path: "scan_gate.fail_on"})) + require.NoError(t, err) + table := got.RenderTable() + assert.Contains(t, table, "scan_gate.fail_on · default policy") + assert.Contains(t, table, "47 · default 1") + assert.Contains(t, got.RenderPlain(), "\t47\t1\tdefault-policy\tscan_gate.fail_on\t") +} + +func TestRunDecisionList_CooldownOfAnOverride(t *testing.T) { cooldown := decision("d_cool", policyv1.DecisionTool_DECISION_TOOL_PMG, policyv1.DecisionOutcome_DECISION_OUTCOME_BLOCKED, - "fresh", "0.0.1", citation(47, 12, "package_admission.cooldown.min_age", "", "", recordv1.Layer_LAYER_DEFAULT_POLICY), + "fresh", "0.0.1", citation(47, 1, "package_admission.cooldown.min_age", "", "ov_pay", recordv1.Layer_LAYER_OVERRIDE), atEndpoint(endpointPoint("dev-laptop", "alice"))) client := mocks.NewPolicyServiceClientMock(t) - client.EXPECT().ListPolicyDecisions(mock.Anything, mock.MatchedBy(func(r *policyv1.ListPolicyDecisionsRequest) bool { - return r.GetFilters().GetPath() == "package_admission.cooldown.min_age" - })).Return(decisionsResponse("", cooldown), nil) + client.EXPECT().ListPolicyDecisions(mock.Anything, mock.Anything).Return(decisionsResponse("", cooldown), nil) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(headResponse(), nil) - got, err := runDecisionList(context.Background(), client, listQuery(t, decisionListInput{Path: "package_admission.cooldown.min_age"})) + got, err := runDecisionList(context.Background(), client, + listQuery(t, decisionListInput{Path: "package_admission.cooldown.min_age"})) require.NoError(t, err) table := got.RenderTable() - assert.Contains(t, table, "package_admission.cooldown.min_age · default policy") - assert.Contains(t, table, "47 · default 12") + assert.Contains(t, table, "package_admission.cooldown.min_age · override payments") + assert.NotContains(t, table, "default 1", "the default policy did not decide") assert.NotContains(t, table, "LINK", "no decision has a link") - assert.Contains(t, got.RenderPlain(), "\t47\t12\tdefault-policy\tpackage_admission.cooldown.min_age\t") } func TestRunDecisionList_Override(t *testing.T) { overrideDecision := decision("d_ov", policyv1.DecisionTool_DECISION_TOOL_PMG, policyv1.DecisionOutcome_DECISION_OUTCOME_BLOCKED, - "fresh", "0.0.1", citation(47, 12, "package_admission.cooldown.min_age", "", "ov_pay", recordv1.Layer_LAYER_OVERRIDE), + "fresh", "0.0.1", citation(47, 1, "package_admission.cooldown.min_age", "", "ov_pay", recordv1.Layer_LAYER_OVERRIDE), atEndpoint(endpointPoint("dev-laptop", "alice"))) tests := []struct { name string @@ -454,7 +473,7 @@ func TestRunDecisionList_Override(t *testing.T) { func TestRunDecisionList_TheIDOfADeletedOverrideIsSentAsIs(t *testing.T) { const deleted = "ov_9c1x4kq7dm" d := decision("d_old", policyv1.DecisionTool_DECISION_TOOL_PMG, policyv1.DecisionOutcome_DECISION_OUTCOME_BLOCKED, - "fresh", "0.0.1", citation(49, 12, "package_admission.cooldown.min_age", "", deleted, recordv1.Layer_LAYER_OVERRIDE), + "fresh", "0.0.1", citation(49, 1, "package_admission.cooldown.min_age", "", deleted, recordv1.Layer_LAYER_OVERRIDE), atEndpoint(endpointPoint("dev-laptop", "alice"))) client := mocks.NewPolicyServiceClientMock(t) client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(headResponse(), nil).Once() @@ -498,7 +517,7 @@ func TestResolveOverrideID(t *testing.T) { func TestRunDecisionList_OverrideNameReadFailureKeepsTheID(t *testing.T) { d := decision("d_ov", policyv1.DecisionTool_DECISION_TOOL_PMG, policyv1.DecisionOutcome_DECISION_OUTCOME_BLOCKED, - "evil", "1.0.0", citation(47, 12, "", "r_1", "ov_gone", recordv1.Layer_LAYER_UNSPECIFIED), + "evil", "1.0.0", citation(47, 1, "", "r_1", "ov_gone", recordv1.Layer_LAYER_UNSPECIFIED), atEndpoint(endpointPoint("dev-laptop", ""))) client := mocks.NewPolicyServiceClientMock(t) client.EXPECT().ListPolicyDecisions(mock.Anything, mock.Anything).Return(decisionsResponse("", d), nil) @@ -560,7 +579,7 @@ func TestDescribePlace(t *testing.T) { func TestRunDecisionList_EscapesServerText(t *testing.T) { d := decision("d_x", policyv1.DecisionTool_DECISION_TOOL_PMG, policyv1.DecisionOutcome_DECISION_OUTCOME_BLOCKED, - "evil\x1b]0;owned\x07", "1.0.0", citation(47, 12, "a\nb", "", "", recordv1.Layer_LAYER_BASE), + "evil\x1b]0;owned\x07", "1.0.0", citation(47, 1, "a\nb", "", "", recordv1.Layer_LAYER_BASE), atEndpoint(endpointPoint("host\u202e", "mallory\tx"))) client := mocks.NewPolicyServiceClientMock(t) client.EXPECT().ListPolicyDecisions(mock.Anything, mock.Anything).Return(decisionsResponse("", d), nil) diff --git a/internal/cmd/policy/edit_test.go b/internal/cmd/policy/edit_test.go index 1ddf8f2..61de916 100644 --- a/internal/cmd/policy/edit_test.go +++ b/internal/cmd/policy/edit_test.go @@ -138,7 +138,7 @@ func TestRunEdit_CreatesAChangeFromTheHead(t *testing.T) { header := ed.seen[0] assert.Contains(t, header, "# Policy of platform-eng.acme.safedep.io · head revision 46") - assert.Contains(t, header, "# 1. SafeDep default policy (read-only, revision 12):") + assert.Contains(t, header, "# 1. SafeDep default policy (read-only, revision 1):") assert.Contains(t, header, "scan_gate.fail_on: high") assert.Contains(t, header, "# Package rules are not in this file: 211 rules") diff --git a/internal/cmd/policy/fixtures_test.go b/internal/cmd/policy/fixtures_test.go index e84131c..a434303 100644 --- a/internal/cmd/policy/fixtures_test.go +++ b/internal/cmd/policy/fixtures_test.go @@ -40,7 +40,7 @@ func headPolicy() *policyv1.Policy { p.SetBase(failOnSpec(scangatev1.Severity_SEVERITY_HIGH)) p.SetOverrides([]*policyv1.Override{ override("ov_pay", "payments", 200, "custom/criticality", "high", scangatev1.Severity_SEVERITY_HIGH), - override("ov_ci", "ci", 300, "managed/deployment-kind", "ci", scangatev1.Severity_SEVERITY_CRITICAL), + override("ov_ci", "ci", 300, "custom/environment", "ci", scangatev1.Severity_SEVERITY_CRITICAL), }) return p } @@ -65,9 +65,12 @@ func revision(n uint64, message string) *policyv1.PolicyRevision { } func headResponse() *policyv1.GetPolicyResponse { + // The SafeDep default policy of control-tower at revision 1. + defaultSpec := failOnSpec(scangatev1.Severity_SEVERITY_HIGH) + defaultSpec.GetScanGate().SetFailOnAttacks(scangatev1.AttackGate_ATTACK_GATE_FAIL) def := &policyv1.DefaultPolicy{} - def.SetRevision(12) - def.SetSpec(failOnSpec(scangatev1.Severity_SEVERITY_HIGH)) + def.SetRevision(1) + def.SetSpec(defaultSpec) counts := &policyv1.PackageRuleCounts{} counts.SetTrustCount(184) counts.SetBlockCount(27) diff --git a/internal/cmd/policy/publish_test.go b/internal/cmd/policy/publish_test.go index e8633fb..d7adafb 100644 --- a/internal/cmd/policy/publish_test.go +++ b/internal/cmd/policy/publish_test.go @@ -72,7 +72,7 @@ func TestRunChangePublish_ShowsTheDirectionAndEveryWarning(t *testing.T) { stderr := captureStderr(t) client := mocks.NewPolicyServiceClientMock(t) client.EXPECT().GetPolicyChange(mock.Anything, mock.Anything).Return(changeResponse(openChange("18")), nil) - client.EXPECT().PreviewPolicyChange(mock.Anything, mock.Anything).Return(previewResponse(), nil) + client.EXPECT().PreviewPolicyChange(mock.Anything, mock.Anything).Return(withEndpointLabelWarning(previewResponse()), nil) client.EXPECT().PublishPolicyChange(mock.Anything, mock.Anything). Return(publishResponse(policyv1.ChangeDirection_CHANGE_DIRECTION_LOOSENS), nil) @@ -86,8 +86,8 @@ func TestRunChangePublish_ShowsTheDirectionAndEveryWarning(t *testing.T) { out := stderr.String() assert.Contains(t, out, "Change 18 · LOOSENS. Only an Admin can publish it") - assert.Contains(t, out, "It loosens selector (scm-property/criticality=high -> custom/criticality=high) in override \"payments\"") - assert.Contains(t, out, `LOW_ENFORCED_COVERAGE scan_gate.fail_on: 1 of 3 projects cannot enforce "medium" yet`) + assert.Contains(t, out, "It loosens selector (custom/team=pay -> reported/os=linux) in override \"payments\"") + assert.Contains(t, out, "ENDPOINT_LABEL_LOOSENS payments: a policy override that loosens selects on a label that an endpoint can send") } func TestRunChangePublish_LooseningThatTheUserRefuses(t *testing.T) { @@ -140,7 +140,7 @@ func TestRunChangePublish_PreviewFails(t *testing.T) { func TestReportPreview_EscapesServerText(t *testing.T) { stderr := captureStderr(t) - preview := newPreviewView(previewResponse()) + preview := newPreviewView(withEndpointLabelWarning(previewResponse())) preview.Warnings[0].Message = "evil\x1b]0;title\x07" reportPreview("18", preview) assert.NotContains(t, stderr.String(), "\x1b") diff --git a/internal/cmd/policy/show_test.go b/internal/cmd/policy/show_test.go index 5d64bbd..a3b0089 100644 --- a/internal/cmd/policy/show_test.go +++ b/internal/cmd/policy/show_test.go @@ -22,7 +22,7 @@ func TestRunShow(t *testing.T) { require.Len(t, res.Overrides, 2) assert.Equal(t, "ci", res.Overrides[0].Name, "the highest priority comes first") - assert.Equal(t, "managed/deployment-kind=ci", res.Overrides[0].Selector) + assert.Equal(t, "custom/environment=ci", res.Overrides[0].Selector) table := res.RenderTable() for _, want := range []string{ @@ -30,7 +30,7 @@ func TestRunShow(t *testing.T) { `46 · published 2d ago by alice · "cooldown 5d for laptops"`, "Open changes none", "211 (184 trust, 27 block) · 23 expire in 7d", - "revision 12 · scan_gate.fail_on: high", + "revision 1 · scan_gate.fail_on: high · scan_gate.fail_on_attacks: fail", "Overrides (priority, highest first)", "payments", } { @@ -42,12 +42,12 @@ func TestRunShow(t *testing.T) { var out map[string]any require.NoError(t, json.Unmarshal(b, &out)) assert.InDelta(t, 46, out["head_revision"], 0) - assert.Equal(t, map[string]any{"scan_gate.fail_on": "high"}, out["default_policy"]) + assert.Equal(t, map[string]any{"scan_gate.fail_on": "high", "scan_gate.fail_on_attacks": "fail"}, out["default_policy"]) policy, ok := out["policy"].(map[string]any) require.True(t, ok) assert.Contains(t, policy, "overrides") - assert.Contains(t, res.RenderPlain(), "override\t300\tci\tmanaged/deployment-kind=ci") + assert.Contains(t, res.RenderPlain(), "override\t300\tci\tcustom/environment=ci") } func TestRunShow_NeverPublished(t *testing.T) { diff --git a/internal/cmd/project/label.go b/internal/cmd/project/label.go index 91900e3..0ed6a3e 100644 --- a/internal/cmd/project/label.go +++ b/internal/cmd/project/label.go @@ -26,8 +26,9 @@ func labelCmd(a *app.App) *cobra.Command { Use: "label", Short: "Set or delete the custom labels of projects", Long: "Set or delete the custom/ labels of projects. A policy override selects projects by their " + - "labels. An admin writes only custom/ labels. The forge sync writes scm/ labels, and the server " + - "writes safedep.io/ labels. A label change takes effect at the next check of each project.", + "labels. An admin writes only custom/ labels. The server sets the safedep.io/ labels, and the " + + "scm/ labels from the repository of a project. A label change takes effect at the next check of " + + "each project.", } parent.AddCommand(labelSetCmd(a), labelDeleteCmd(a)) return parent diff --git a/internal/cmd/project/policy_test.go b/internal/cmd/project/policy_test.go index 81b48e6..ca618bd 100644 --- a/internal/cmd/project/policy_test.go +++ b/internal/cmd/project/policy_test.go @@ -75,11 +75,11 @@ func projectsResponse(projects ...*controltowerv1.ProjectWithAttributes) *contro func TestNewProjectListRequest(t *testing.T) { req, err := newProjectListRequest(projectListInput{ - Selector: "scm-property/criticality=high", Sources: []string{"github", "bitbucket"}, PageSize: 10, + Selector: "scm/owner=acme", Sources: []string{"github", "bitbucket"}, PageSize: 10, }) require.NoError(t, err) f := req.GetFilterV2() - assert.Equal(t, map[string]string{"scm-property/criticality": "high"}, f.GetLabelSelector().GetMatchLabels()) + assert.Equal(t, map[string]string{"scm/owner": "acme"}, f.GetLabelSelector().GetMatchLabels()) assert.Equal(t, []messagescontroltowerv1.Project_Source{ messagescontroltowerv1.Project_SOURCE_GITHUB, messagescontroltowerv1.Project_SOURCE_BITBUCKET, }, f.GetSources()) @@ -98,17 +98,17 @@ func TestNewProjectListRequest(t *testing.T) { func TestRunProjectList(t *testing.T) { client := &fakeListProjectsClient{listFn: func(*controltowerv1.ListProjectsRequest) (*controltowerv1.ListProjectsResponse, error) { return projectsResponse(labeledProject("p_1", "acme/payments-api", messagescontroltowerv1.Project_SOURCE_GITHUB, - map[string]string{"scm-property/criticality": "high", "custom/team": "pay"})), nil + map[string]string{"scm/owner": "acme", "custom/team": "pay"})), nil }} - got, err := runProjectList(context.Background(), client, projectListInput{Selector: "scm-property/criticality=high"}) + got, err := runProjectList(context.Background(), client, projectListInput{Selector: "scm/owner=acme"}) require.NoError(t, err) require.Len(t, got.Projects, 1) - assert.Equal(t, []string{"custom/team=pay", "scm-property/criticality=high"}, got.Projects[0].Labels) + assert.Equal(t, []string{"custom/team=pay", "scm/owner=acme"}, got.Projects[0].Labels) table := got.RenderTable() assert.Contains(t, table, "acme/payments-api") - assert.Contains(t, table, "custom/team=pay, scm-property/criticality=high") - assert.Contains(t, got.RenderPlain(), "p_1\tacme/payments-api\tgithub\tcustom/team=pay,scm-property/criticality=high\t3\t-\t") + assert.Contains(t, table, "custom/team=pay, scm/owner=acme") + assert.Contains(t, got.RenderPlain(), "p_1\tacme/payments-api\tgithub\tcustom/team=pay,scm/owner=acme\t3\t-\t") } func TestRunShow_ProjectWithPolicy(t *testing.T) { @@ -204,7 +204,7 @@ func TestRunLabelSet(t *testing.T) { func TestRunLabelSet_RejectsOtherPrefixesBeforeAnyRPC(t *testing.T) { _, err := runLabelSet(context.Background(), nil, mocks.NewLabelServiceClientMock(t), labelInput{ - ProjectIDs: []string{"p_1"}, Labels: []string{"scm-property/criticality=high"}, + ProjectIDs: []string{"p_1"}, Labels: []string{"scm/owner=acme"}, }) require.Error(t, err) assert.Contains(t, err.Error(), `an admin writes only "custom/" labels`) From 53bec64dc09b88eb402402fed2c0c47c94c68814 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Thu, 5 Nov 2026 07:07:41 +0000 Subject: [PATCH 11/17] docs(cmd): match change directions and policy reports to the server A second review found three more examples that this release cannot give: - policy change publish showed change 18 as TIGHTENS, but policy change show showed it as LOOSENS. control-tower gives LOOSENS: a selector edit always loosens, and the first cooldown of an override loosens when the base and the default policy set none. The publish example now shows each part that loosens and the confirmation prompt. Revision 47 shows LOOSENS in revision show and revision list. Revision 51 deletes a trust entry, so it tightens. The impact of change 18 is now what the pull request check reports: it enforces scan_gate.fail_on and does not support the cooldown. - endpoint policy show showed a field that a shared managed file locks. That file is not in this release. The example shows no exception. The test fixture of the subject policy is now an endpoint, because only pmg sends a policy apply report, and it uses the detail that pmg sends for global_lockdown. - project policy show listed the tool scm-check. The pull request check registers coverage as pull-request-check and sends no policy apply report, so the applied table of a project is empty. The example and the text now say so. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MhRi597EX9odoSDXbVBsxz --- docs/cmd/endpoint-policy-show.md | 7 ++++--- docs/cmd/policy-change-publish.md | 10 ++++++++-- docs/cmd/policy-change-show.md | 13 ++++++++++--- docs/cmd/policy-revision-list.md | 4 ++-- docs/cmd/policy-revision-show.md | 2 +- docs/cmd/project-policy-show.md | 9 +++++---- internal/cloudpolicy/subject_test.go | 21 ++++++++++++--------- internal/cmd/policy/change_test.go | 17 +++++++++++++---- internal/cmd/policy/publish_test.go | 1 + 9 files changed, 56 insertions(+), 28 deletions(-) diff --git a/docs/cmd/endpoint-policy-show.md b/docs/cmd/endpoint-policy-show.md index 4dd05bf..7417a65 100644 --- a/docs/cmd/endpoint-policy-show.md +++ b/docs/cmd/endpoint-policy-show.md @@ -1,8 +1,9 @@ # safedep endpoint policy show Show the intended policy of one endpoint: each field, its value, and its source. -The output also shows the applied policy revision and the exceptions that each -tool reported, such as a field that a managed file locks. +The output also shows the policy that each tool applied, as the tool reported it +at its last check-in, and the fields that the tool did not apply as the policy +says. ## Synopsis @@ -29,7 +30,7 @@ Default policy revision 1 Package rules 211 (184 trust, 27 block) FIELD VALUE SOURCE EXCEPTIONS -package_admission.cooldown.min_age 5d override "laptops" (100) pmg: locked (floor in /etc/safedep/cloud.yml) +package_admission.cooldown.min_age 5d override "laptops" (100) - Applied policy, as each tool reported it TOOL VERSION REVISION STATE FETCHED REPORTED diff --git a/docs/cmd/policy-change-publish.md b/docs/cmd/policy-change-publish.md index d3e23f0..0e98030 100644 --- a/docs/cmd/policy-change-publish.md +++ b/docs/cmd/policy-change-publish.md @@ -27,12 +27,18 @@ safedep policy change publish 18 -m "payments: fail on medium, 7d cooldown (CUST ``` ``` -Change 18 · TIGHTENS. An Admin can publish it -✓ revision 47 published · TIGHTENS +Change 18 · LOOSENS. Only an Admin can publish it, and Admins and Owners get a notice +! It loosens package_admission.cooldown.min_age (- -> 7d) in override "payments" +! It loosens selector (custom/team=pay -> custom/criticality=high) in override "payments" +Change 18 loosens the policy. Publish it? [y/N]: y +✓ revision 47 published · LOOSENS Projects resolve it at their next check. Endpoints apply it after their next policy fetch Endpoints that have not applied it yet: safedep endpoint list --applied-revision '<47' ``` +In a script, pass `--yes` to publish a change that loosens the policy. A change +that only tightens publishes with no prompt. + When a part that the change edits moved since its base revision, the publish stops: ``` diff --git a/docs/cmd/policy-change-show.md b/docs/cmd/policy-change-show.md index e4f6427..e00d934 100644 --- a/docs/cmd/policy-change-show.md +++ b/docs/cmd/policy-change-show.md @@ -26,12 +26,13 @@ Updated 2m ago What changes WHERE WHAT OLD -> NEW DIRECTION override "payments" scan_gate.fail_on high -> medium TIGHTENS -override "payments" package_admission.cooldown.min_age - -> 7d TIGHTENS +override "payments" package_admission.cooldown.min_age - -> 7d LOOSENS override "payments" selector custom/team=pay -> custom/criticality=high LOOSENS Impact · subjects matched: 3 projects, 0 endpoints -FIELD ENFORCED PARTIAL DETECT ONLY NOT SUPPORTED -scan_gate.fail_on = medium 2 1 0 0 +FIELD ENFORCED PARTIAL DETECT ONLY NOT SUPPORTED +package_admission.cooldown.min_age = 168h 0 0 0 3 +scan_gate.fail_on = medium 3 0 0 0 Warnings No warnings. @@ -39,6 +40,12 @@ No warnings. Direction LOOSENS. Only an Admin can publish it, and Admins and Owners get a notice ``` +The policy base and the SafeDep default policy set no cooldown, so the server +counts the first cooldown of the override as a change that loosens: it does not +know what each tool did before. A selector edit always loosens, because it can +move subjects to another policy override. The impact counts only projects: the +pull request check enforces `scan_gate.fail_on` and does not support the cooldown. + A stale change shows `STALE: sync it before you publish` in the first line. A published or deleted change shows no preview. diff --git a/docs/cmd/policy-revision-list.md b/docs/cmd/policy-revision-list.md index 01e323c..dd8b09a 100644 --- a/docs/cmd/policy-revision-list.md +++ b/docs/cmd/policy-revision-list.md @@ -24,11 +24,11 @@ safedep policy revision list --limit 5 ``` Policy revisions REV PUBLISHED BY SOURCE DIRECTION MESSAGE -51 10m ago alice CLI LOOSENS delete r_80b +51 10m ago alice CLI TIGHTENS delete r_80b 50 12m ago alice CLI LOOSENS extend r_77e 49 1d ago alice CLI LOOSENS trust pkg:pypi/foo@1.0.3 48 1d ago carol CLI TIGHTENS block pkg:npm/evil (IR-2291) -47 2d ago alice CLI TIGHTENS payments: fail on medium, 7d cooldown (CUST-412) +47 2d ago alice CLI LOOSENS payments: fail on medium, 7d cooldown (CUST-412) ``` ## Output diff --git a/docs/cmd/policy-revision-show.md b/docs/cmd/policy-revision-show.md index 07efd58..7f95aa1 100644 --- a/docs/cmd/policy-revision-show.md +++ b/docs/cmd/policy-revision-show.md @@ -18,7 +18,7 @@ safedep policy revision show 47 ``` Revision 47 · published 2d ago by alice · "payments: fail on medium, 7d cooldown (CUST-412)" Source CLI -Direction TIGHTENS +Direction LOOSENS Change 18 · safedep policy change show 18 Policy settings diff --git a/docs/cmd/project-policy-show.md b/docs/cmd/project-policy-show.md index 673c2a4..7126d42 100644 --- a/docs/cmd/project-policy-show.md +++ b/docs/cmd/project-policy-show.md @@ -2,8 +2,10 @@ Show the intended policy of one project: each field, its value, and its source. The source is the SafeDep default policy, the policy base, or a policy override. -The output also shows the applied policy revision and the exceptions that each -tool or check reported. +The output also has a table for the policy that each tool applied. In this +release no tool reports it for a project: the pull request check +(`pull-request-check`) resolves the policy at each check and sends no report, so +the table is empty. ## Synopsis @@ -36,8 +38,7 @@ package_admission.cooldown.min_age 7d override "payments" (200) - scan_gate.fail_on medium override "payments" (200) - Applied policy, as each tool reported it -TOOL VERSION REVISION STATE FETCHED REPORTED -scm-check - 47 applied 3h ago 3h ago +No tool or check reported the policy that it applies for this project yet. ``` ## Output diff --git a/internal/cloudpolicy/subject_test.go b/internal/cloudpolicy/subject_test.go index 6b8041a..7a7851f 100644 --- a/internal/cloudpolicy/subject_test.go +++ b/internal/cloudpolicy/subject_test.go @@ -60,7 +60,7 @@ func subjectPolicyResponse() *policyv1.GetSubjectPolicyResponse { matched.SetPriority(200) header := &specv1.ResolvedPolicyHeader{} header.SetRevision(47) - header.SetDefaultPolicyRevision(12) + header.SetDefaultPolicyRevision(1) header.SetMatchedOverrides([]*specv1.MatchedOverride{matched}) intended := &specv1.ResolvedPolicy{} @@ -74,7 +74,9 @@ func subjectPolicyResponse() *policyv1.GetSubjectPolicyResponse { exception := &recordv1.FieldException{} exception.SetPath("package_admission.cooldown.min_age") exception.SetReason(recordv1.FieldExceptionReason_FIELD_EXCEPTION_REASON_LOCKED) - exception.SetDetail("floor in /etc/safedep/cloud.yml") + // The detail that pmg sends when global_lockdown of its managed config + // file keeps a value. + exception.SetDetail("global_lockdown keeps the value of the managed config file") report := &recordv1.ApplyReport{} report.SetRevision(46) report.SetState(recordv1.ApplyState_APPLY_STATE_APPLIED) @@ -98,14 +100,15 @@ func subjectPolicyResponse() *policyv1.GetSubjectPolicyResponse { func TestGetSubjectPolicy(t *testing.T) { client := &fakeSubjectPolicyClient{res: subjectPolicyResponse()} - subject := NewSubject(specv1.SubjectKind_SUBJECT_KIND_PROJECT, "p_1") + // Only an endpoint has policy apply reports: pmg sends them at check-in. + subject := NewSubject(specv1.SubjectKind_SUBJECT_KIND_ENDPOINT, "01KR0EKN6PMW0ZRFRN992H1PKX") - got, err := GetSubjectPolicy(context.Background(), client, subject, "acme/payments-api", nil) + got, err := GetSubjectPolicy(context.Background(), client, subject, "arjuns-mbp", nil) require.NoError(t, err) - assert.Equal(t, specv1.SubjectKind_SUBJECT_KIND_PROJECT, client.req.GetSubject().GetKind()) - assert.Equal(t, "p_1", client.req.GetSubject().GetId()) - assert.Equal(t, "project", got.Kind) + assert.Equal(t, specv1.SubjectKind_SUBJECT_KIND_ENDPOINT, client.req.GetSubject().GetKind()) + assert.Equal(t, "01KR0EKN6PMW0ZRFRN992H1PKX", client.req.GetSubject().GetId()) + assert.Equal(t, "endpoint", got.Kind) assert.Equal(t, uint64(47), got.Revision) assert.Equal(t, 1, got.TrustRules) assert.Equal(t, 2, got.BlockRules) @@ -114,7 +117,7 @@ func TestGetSubjectPolicy(t *testing.T) { require.Len(t, got.Fields, 2) assert.Equal(t, SubjectField{ Path: "package_admission.cooldown.min_age", Value: "168h", Human: "7d", Source: "base", - Exceptions: []string{"pmg: locked (floor in /etc/safedep/cloud.yml)"}, + Exceptions: []string{"pmg: locked (global_lockdown keeps the value of the managed config file)"}, }, got.Fields[0]) assert.Equal(t, `override "payments" (200)`, got.Fields[1].Source) require.Len(t, got.Applied, 1) @@ -128,7 +131,7 @@ func TestGetSubjectPolicy(t *testing.T) { b, err := got.RenderJSON() require.NoError(t, err) require.NoError(t, json.Unmarshal(b, &decoded)) - assert.Equal(t, "p_1", decoded["id"]) + assert.Equal(t, "01KR0EKN6PMW0ZRFRN992H1PKX", decoded["id"]) assert.Contains(t, got.RenderPlain(), "scan_gate.fail_on\tmedium\toverride \"payments\" (200)") } diff --git a/internal/cmd/policy/change_test.go b/internal/cmd/policy/change_test.go index cf46b68..c2fa438 100644 --- a/internal/cmd/policy/change_test.go +++ b/internal/cmd/policy/change_test.go @@ -49,6 +49,11 @@ func TestRunChangeList(t *testing.T) { assert.ErrorContains(t, err, `unknown --state value "draft": allowed values are open, published, deleted`) } +// previewResponse is the preview that control-tower gives for change 18. The +// policy base and the default policy set no cooldown, so a cooldown that an +// override sets for the first time loosens: the server cannot know what a +// tool did before. A selector edit always loosens. The pull request check +// enforces scan_gate.fail_on and does not support the cooldown. func previewResponse() *policyv1.PreviewPolicyChangeResponse { field := &policyv1.PathChange{} field.SetPath("scan_gate.fail_on") @@ -63,7 +68,7 @@ func previewResponse() *policyv1.PreviewPolicyChangeResponse { cooldown.SetLayer(recordv1.Layer_LAYER_OVERRIDE) cooldown.SetOverrideName("payments") cooldown.SetNewValue(`"604800s"`) - cooldown.SetDirection(policyv1.ChangeDirection_CHANGE_DIRECTION_TIGHTENS) + cooldown.SetDirection(policyv1.ChangeDirection_CHANGE_DIRECTION_LOOSENS) selector := &policyv1.OverrideChange{} selector.SetOverrideName("payments") @@ -73,11 +78,14 @@ func previewResponse() *policyv1.PreviewPolicyChangeResponse { selector.SetNewValue(`{"matchLabels":{"custom/criticality":"high"}}`) selector.SetDirection(policyv1.ChangeDirection_CHANGE_DIRECTION_LOOSENS) + cooldownCoverage := &policyv1.CoverageSummary{} + cooldownCoverage.SetPath("package_admission.cooldown.min_age") + cooldownCoverage.SetValue(`"604800s"`) + cooldownCoverage.SetUnsupportedCount(3) coverage := &policyv1.CoverageSummary{} coverage.SetPath("scan_gate.fail_on") coverage.SetValue(`"SEVERITY_MEDIUM"`) - coverage.SetEnforceCount(2) - coverage.SetPartialCount(1) + coverage.SetEnforceCount(3) res := &policyv1.PreviewPolicyChangeResponse{} res.SetHeadRevision(46) @@ -85,7 +93,7 @@ func previewResponse() *policyv1.PreviewPolicyChangeResponse { res.SetOverrideChanges([]*policyv1.OverrideChange{selector}) res.SetDirection(policyv1.ChangeDirection_CHANGE_DIRECTION_LOOSENS) res.SetMatchedProjectCount(3) - res.SetCoverage([]*policyv1.CoverageSummary{coverage}) + res.SetCoverage([]*policyv1.CoverageSummary{cooldownCoverage, coverage}) return res } @@ -120,6 +128,7 @@ func TestRunChangeShow_PreviewsAnOpenChange(t *testing.T) { "No warnings.", "subjects matched: 3 projects, 0 endpoints", "scan_gate.fail_on = medium", + "package_admission.cooldown.min_age = 168h", "LOOSENS. Only an Admin can publish it", } { assert.Contains(t, table, want) diff --git a/internal/cmd/policy/publish_test.go b/internal/cmd/policy/publish_test.go index d7adafb..3696ec1 100644 --- a/internal/cmd/policy/publish_test.go +++ b/internal/cmd/policy/publish_test.go @@ -86,6 +86,7 @@ func TestRunChangePublish_ShowsTheDirectionAndEveryWarning(t *testing.T) { out := stderr.String() assert.Contains(t, out, "Change 18 · LOOSENS. Only an Admin can publish it") + assert.Contains(t, out, "It loosens package_admission.cooldown.min_age (- -> 7d) in override \"payments\"") assert.Contains(t, out, "It loosens selector (custom/team=pay -> reported/os=linux) in override \"payments\"") assert.Contains(t, out, "ENDPOINT_LABEL_LOOSENS payments: a policy override that loosens selects on a label that an endpoint can send") } From e370e10d1f70f54911f7a0b4902a090eff7fab67 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Thu, 5 Nov 2026 08:04:11 +0000 Subject: [PATCH 12/17] feat(policy): show every settings field in the policy edit document A user ran safedep policy edit on a tenant with no revision and got a file with only the header and {}. The file did not say which fields exist or which values they take. The edit document of policy edit and policy change edit is now a template of the policy settings: - The CLI walks the descriptor of the contract, as the YAML codec does, so a new field shows after an SDK bump with no change in the CLI. - A set field keeps its YAML line. An unset field is a commented line at its nesting. A tenant with no settings gets a commented base skeleton. - Each commented field has a note: the enum tokens that the codec reads, or the duration form with the range from the protovalidate rules, and the value that the subjects get now with the layer that sets it (the base or the default policy and its revision). A long note goes on its own line above the field. - A policy with no override gets a commented example override. The codec writes it, so its keys are the ones that the codec reads. - The header points to the field reference: https://docs.safedep.io/reference/cloud-policy-settings A save of the template as it is still changes nothing. The comments are never values. A message key with only commented lines below it now reads as a set message with no fields, so a set but empty spec round trips. A label selector stays unset, because an empty selector selects every subject. A file with only comments reads as an empty policy only when the policy was empty. The comment warning now ignores every comment that the CLI wrote, also the note of a line that the user uncomments. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MhRi597EX9odoSDXbVBsxz --- docs/cmd/policy-change-edit.md | 5 +- docs/cmd/policy-edit.md | 66 ++- go.mod | 2 +- internal/cloudpolicy/document.go | 24 -- internal/cloudpolicy/document_test.go | 2 +- internal/cloudpolicy/protoyaml.go | 7 + internal/cloudpolicy/template.go | 574 ++++++++++++++++++++++++++ internal/cloudpolicy/template_test.go | 211 ++++++++++ internal/cmd/policy/change_edit.go | 2 +- internal/cmd/policy/edit.go | 8 +- internal/cmd/policy/edit_test.go | 173 +++++++- internal/cmd/policy/settings.go | 44 +- 12 files changed, 1071 insertions(+), 47 deletions(-) create mode 100644 internal/cloudpolicy/template.go create mode 100644 internal/cloudpolicy/template_test.go diff --git a/docs/cmd/policy-change-edit.md b/docs/cmd/policy-change-edit.md index 9ab0b8b..0cf5dad 100644 --- a/docs/cmd/policy-change-edit.md +++ b/docs/cmd/policy-change-edit.md @@ -18,8 +18,9 @@ safedep policy change edit CHANGE [-m TITLE] [--override NAME] A change that does not edit the settings yet starts from the head settings. For a change that restores a revision, saving replaces the settings that the restore -made, and the command warns first. The editor behaves as in -[`safedep policy edit`](./policy-edit.md). +made, and the command warns first. The document has the same form, with every +settings field and a note for each field that the change does not set, and the +editor behaves as in [`safedep policy edit`](./policy-edit.md). ## Examples diff --git a/docs/cmd/policy-edit.md b/docs/cmd/policy-edit.md index 9cd6d42..6a68de3 100644 --- a/docs/cmd/policy-edit.md +++ b/docs/cmd/policy-edit.md @@ -25,10 +25,18 @@ command needs a terminal. safedep policy edit -m "payments: medium + cooldown" ``` -The file starts with a header that shows the layers: +The document has every policy settings field of the contract. A field that the +policy sets is a YAML line. A field that it does not set is a commented line at +its nesting, with a note: the values that the field accepts, and the value that +the subjects get now and the layer that sets it. To set a field, remove the `# ` +at the start of its line and of the lines of its parents. A save of the document +as it is changes nothing. When the policy has no override, the document ends +with a commented example of one. + +The document of a tenant that has not published a policy yet: ```yaml -# Policy of platform-eng.acme.safedep.io · head revision 46 +# Policy of acme.safedep.io · head revision 0 # Saving creates a draft change. Nothing applies until you publish it. # # Layers, from low to high, for each subject: @@ -39,8 +47,58 @@ The file starts with a header that shows the layers: # For each field, the highest priority that sets it wins. # # Keep the id of each override. A new override has no id. -# Package rules are not in this file: 211 rules (safedep policy rule list) +# Package rules are not in this file: 0 rules (safedep policy rule list) # The policy keeps no comments. Write the reason for a value in a description field. +# To set a field, remove the "# " at the start of its line and of the lines of its parents. +# Fields and values: https://docs.safedep.io/reference/cloud-policy-settings + +# base: + # package_admission: + # cooldown: + # min_age: 7d # a duration, as 7d or 12h, from 0s to 365d. Now: not set + # 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) + +# An example policy override. It applies to the subjects that its selector matches. +# Remove the "# " at the start of each line to use it, then change the values. +# overrides: +# - name: payments +# priority: 100 +# selector: +# matchLabels: {custom/team: payments} +# spec: +# package_admission: +# cooldown: +# min_age: 168h +``` + +To set a cooldown of 7 days for the whole tenant, remove the `# ` from the +`base:`, `package_admission:`, `cooldown:` and `min_age:` lines, then save. + +The start of the document of a tenant with values, after the header: + +```yaml +base: + # package_admission: + # cooldown: + # min_age: 7d # a duration, as 7d or 12h, from 0s to 365d. Now: not set + scan_gate: + fail_on: high + # fail_on_attacks: fail # report, fail. Now: fail (default policy, revision 1) +overrides: + - id: ov_pay + name: payments + priority: 200 + selector: + matchLabels: {custom/criticality: high} + spec: + # package_admission: + # cooldown: + # min_age: 7d # a duration, as 7d or 12h, from 0s to 365d. Now: not set + scan_gate: + fail_on: high + # fail_on_attacks: fail # report, fail. Now: fail (default policy, revision 1) ``` ``` @@ -66,7 +124,7 @@ safedep policy edit --override payments - When you close the editor with no change, the command saves nothing. - When the file does not parse, or the server rejects it as invalid, the editor opens again with the error at the top. Close it with no change to stop. -- The command warns when the file holds a comment other than its header. The +- The command warns when the file holds a comment that it did not write. The policy keeps no comments. - When the save fails for another reason, the command keeps the file and prints its path. diff --git a/go.mod b/go.mod index a54d020..08c5e11 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/safedep/cli 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-20261104174030-9113dd6a8ea6.1 buf.build/gen/go/safedep/api/protocolbuffers/go v1.36.12-20261104174030-9113dd6a8ea6.2 github.com/charmbracelet/huh v1.0.0 @@ -28,7 +29,6 @@ require ( ) require ( - buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.12-20260709200747-435963d16310.1 // indirect github.com/atotto/clipboard v0.1.4 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/brunoga/deep v1.3.1 // indirect diff --git a/internal/cloudpolicy/document.go b/internal/cloudpolicy/document.go index 5a7d5df..fdd0332 100644 --- a/internal/cloudpolicy/document.go +++ b/internal/cloudpolicy/document.go @@ -108,30 +108,6 @@ func PolicyMap(p *policyv1.Policy) (any, error) { return out, nil } -// HasUserComments reports whether the saved file holds a comment other than -// the header that the CLI wrote. The policy keeps no comments, so a person -// loses them on save. -func HasUserComments(data []byte, header string) bool { - body := bytes.TrimPrefix(data, []byte(header)) - var root yaml.Node - if err := yaml.Unmarshal(body, &root); err != nil { - return false - } - return hasComment(&root) -} - -func hasComment(n *yaml.Node) bool { - if n.HeadComment != "" || n.LineComment != "" || n.FootComment != "" { - return true - } - for _, child := range n.Content { - if hasComment(child) { - return true - } - } - return false -} - func marshalNode(node *yaml.Node, header string) ([]byte, error) { var buf bytes.Buffer buf.WriteString(header) diff --git a/internal/cloudpolicy/document_test.go b/internal/cloudpolicy/document_test.go index 4cec783..7f26c7b 100644 --- a/internal/cloudpolicy/document_test.go +++ b/internal/cloudpolicy/document_test.go @@ -226,7 +226,7 @@ func TestHasUserComments(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assert.Equal(t, tt.want, HasUserComments([]byte(tt.text), header)) + assert.Equal(t, tt.want, HasUserComments([]byte(tt.text), []byte(header))) }) } } diff --git a/internal/cloudpolicy/protoyaml.go b/internal/cloudpolicy/protoyaml.go index ae6cd77..f0548f8 100644 --- a/internal/cloudpolicy/protoyaml.go +++ b/internal/cloudpolicy/protoyaml.go @@ -310,6 +310,13 @@ func (c *yamlCodec) decodeMessage(n *yaml.Node, m protoreflect.Message, path str } seen[fd.Name()] = struct{}{} 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. + if !fd.IsList() && !fd.IsMap() && isMessageKind(fd) && !isFormattedMessage(fd.Message()) { + m.Mutable(fd) + } continue } if err := c.decodeField(value, m, fd, fieldPath); err != nil { diff --git a/internal/cloudpolicy/template.go b/internal/cloudpolicy/template.go new file mode 100644 index 0000000..94769d0 --- /dev/null +++ b/internal/cloudpolicy/template.go @@ -0,0 +1,574 @@ +package cloudpolicy + +import ( + "bytes" + "fmt" + "strings" + "time" + + validate "buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go/buf/validate" + messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/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" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" + "google.golang.org/protobuf/types/known/durationpb" + "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/safedep/cli/internal/duration" + "github.com/safedep/cli/internal/tui" +) + +// The edit template is the policy settings document with every settings +// field of the contract. A field that the document sets is a YAML line. A +// field that it does not set is a commented YAML line at its nesting, so a +// person removes the "# " to set it. The walk reads the descriptor, so a new +// contract field shows after an SDK bump with no change here. The decoder +// skips the comments, so a save of the template as it is changes nothing. + +const ( + // templateWidth is the longest line that a field note shares. A longer + // note goes on its own comment line above the field. + templateWidth = 100 + + // examplePlaceholderDuration is the value of a duration field that no + // layer sets, as an example of the form. + examplePlaceholderDuration = 7 * 24 * time.Hour +) + +var ( + policySpecFullName = (&specv1.PolicySpec{}).ProtoReflect().Descriptor().FullName() + policyFullName = (&policyv1.Policy{}).ProtoReflect().Descriptor().FullName() +) + +// DefaultLayer is the SafeDep default policy, the layer below the base. +type DefaultLayer struct { + Revision uint64 + Spec *specv1.PolicySpec +} + +// belowLayer is a layer below the one that the template writes, with its +// name for the field notes. +type belowLayer struct { + name string + spec *specv1.PolicySpec +} + +type templateWriter struct { + def DefaultLayer + base *specv1.PolicySpec + lines []string +} + +// MarshalPolicyTemplate writes the policy settings document for an edit: +// the header, the set fields, every other settings field as a commented line +// with a note, and an example policy override when the policy has none. +func MarshalPolicyTemplate(p *policyv1.Policy, header string, def DefaultLayer) ([]byte, error) { + if p == nil { + p = &policyv1.Policy{} + } + w := &templateWriter{def: def, base: p.GetBase()} + if err := w.messageFields(p.ProtoReflect(), 0); err != nil { + return nil, err + } + if len(p.GetOverrides()) == 0 { + if err := w.overrideExample(); err != nil { + return nil, err + } + } + return w.bytes(header), nil +} + +// MarshalOverrideTemplate writes one policy override for an edit, in the +// form of MarshalPolicyTemplate. base is the policy base of the document, +// for the notes of the fields that the override does not set. +func MarshalOverrideTemplate(o *policyv1.Override, header string, def DefaultLayer, base *specv1.PolicySpec) ([]byte, error) { + w := &templateWriter{def: def, base: base} + if err := w.messageFields(o.ProtoReflect(), 0); err != nil { + return nil, err + } + return w.bytes(header), nil +} + +func (w *templateWriter) bytes(header string) []byte { + var b bytes.Buffer + b.WriteString(header) + for _, line := range w.lines { + b.WriteString(line) + b.WriteByte('\n') + } + return b.Bytes() +} + +func (w *templateWriter) real(indent int, text string) { + w.lines = append(w.lines, strings.Repeat(" ", indent)+text) +} + +func (w *templateWriter) comment(indent int, text string) { + w.lines = append(w.lines, strings.Repeat(" ", indent)+"# "+text) +} + +// messageFields writes the fields of a document message: a policy settings +// spec as a template, a list of messages item by item, and each other set +// field in the form of the codec. +func (w *templateWriter) messageFields(m protoreflect.Message, indent int) error { + fields := m.Descriptor().Fields() + for i := 0; i < fields.Len(); i++ { + fd := fields.Get(i) + if _, skipped := documentCodec.skip[fd.FullName()]; skipped { + continue + } + key := documentCodec.key(fd) + switch { + case isSpecField(fd): + below := w.belowFor(m.Descriptor().FullName()) + if m.Has(fd) { + w.real(indent, key+":") + if err := w.specFields(fd.Message(), m.Get(fd).Message(), "", indent+2, below); err != nil { + return err + } + continue + } + w.comment(indent, key+":") + if err := w.specFields(fd.Message(), nil, "", indent+2, below); err != nil { + return err + } + case !m.Has(fd): + case fd.IsList() && isMessageKind(fd) && !isFormattedMessage(fd.Message()): + w.real(indent, key+":") + list := m.Get(fd).List() + for j := 0; j < list.Len(); j++ { + if err := w.listItem(list.Get(j).Message(), indent+2); err != nil { + return err + } + } + default: + lines, err := fieldYAML(fd, m.Get(fd)) + if err != nil { + return err + } + for _, line := range lines { + w.real(indent, line) + } + } + } + return nil +} + +// listItem writes one item of a list of messages. The first YAML line of the +// item carries the "- " of the list. +func (w *templateWriter) listItem(m protoreflect.Message, indent int) error { + start := len(w.lines) + if err := w.messageFields(m, indent+2); err != nil { + return err + } + itemIndent := strings.Repeat(" ", indent+2) + for i := start; i < len(w.lines); i++ { + line := w.lines[i] + if strings.HasPrefix(strings.TrimSpace(line), "#") { + continue + } + w.lines[i] = strings.Repeat(" ", indent) + "- " + strings.TrimPrefix(line, itemIndent) + return nil + } + // An item with no set field is an empty message. + w.lines = append(w.lines[:start], append([]string{strings.Repeat(" ", indent) + "- {}"}, w.lines[start:]...)...) + return nil +} + +// belowFor gives the layers below a policy settings spec of a message: the +// default policy for the base, and the base and the default policy for an +// override. +func (w *templateWriter) belowFor(owner protoreflect.FullName) []belowLayer { + def := belowLayer{ + name: fmt.Sprintf("default policy, revision %d", w.def.Revision), + spec: w.def.Spec, + } + if owner == policyFullName { + return []belowLayer{def} + } + return []belowLayer{{name: "base", spec: w.base}, def} +} + +// specFields writes the fields of a policy settings message. msg is nil when +// the document does not set the message, and then every line is a comment. +func (w *templateWriter) specFields( + md protoreflect.MessageDescriptor, + msg protoreflect.Message, + path string, + indent int, + below []belowLayer, +) error { + fields := md.Fields() + for i := 0; i < fields.Len(); i++ { + fd := fields.Get(i) + if _, skipped := documentCodec.skip[fd.FullName()]; skipped { + continue + } + fieldPath := joinPath(path, string(fd.Name())) + set := msg != nil && msg.Has(fd) + if isTemplateLeaf(fd) { + if err := w.leaf(fd, msg, set, fieldPath, indent, below); err != nil { + return err + } + continue + } + key := documentCodec.key(fd) + var child protoreflect.Message + if set { + w.real(indent, key+":") + child = msg.Get(fd).Message() + } else { + w.comment(indent, key+":") + } + if err := w.specFields(fd.Message(), child, fieldPath, indent+2, below); err != nil { + return err + } + } + return nil +} + +// leaf writes one settings field. An unset field shows the value that the +// subjects get now, or an example of the form, with a note. +func (w *templateWriter) leaf( + fd protoreflect.FieldDescriptor, + msg protoreflect.Message, + set bool, + path string, + indent int, + below []belowLayer, +) error { + if set { + lines, err := fieldYAML(fd, msg.Get(fd)) + if err != nil { + return err + } + for _, line := range lines { + w.real(indent, line) + } + return nil + } + + value := placeholderValue(fd) + now := "Now: not set" + for _, layer := range below { + if v, ok := valueAtPath(layer.spec, path); ok { + value = v + _, human := formatFieldValue(fd, v) + now = fmt.Sprintf("Now: %s (%s)", human, layer.name) + break + } + } + lines, err := commentedFieldYAML(fd, value) + if err != nil { + return err + } + note := tui.EscapeLine(valueForm(fd) + ". " + now) + first := strings.Repeat(" ", indent) + "# " + lines[0] + if len(first)+len(" # ")+len(note) <= templateWidth { + w.lines = append(w.lines, first+" # "+note) + } else { + w.comment(indent, note) + w.lines = append(w.lines, first) + } + for _, line := range lines[1:] { + w.comment(indent, line) + } + return nil +} + +// overrideExample writes a commented policy override after the base, for a +// policy that has none. The codec writes it, so the keys are the ones that +// it reads. +func (w *templateWriter) overrideExample() error { + selector := &messagescontroltowerv1.LabelSelector{} + selector.SetMatchLabels(map[string]string{"custom/team": "payments"}) + spec := &specv1.PolicySpec{} + if path, ok := firstLeafPath(spec.ProtoReflect().Descriptor(), ""); ok { + setPlaceholder(spec.ProtoReflect(), path) + } + o := &policyv1.Override{} + o.SetName("payments") + o.SetPriority(100) + o.SetSelector(selector) + o.SetSpec(spec) + example := &policyv1.Policy{} + example.SetOverrides([]*policyv1.Override{o}) + + text, err := MarshalPolicy(example, "") + if err != nil { + return err + } + w.lines = append(w.lines, + "", + "# An example policy override. It applies to the subjects that its selector matches.", + "# Remove the \"# \" at the start of each line to use it, then change the values.", + ) + for _, line := range strings.Split(strings.TrimRight(string(text), "\n"), "\n") { + w.lines = append(w.lines, "# "+line) + } + return nil +} + +// HasUserComments reports whether the saved file holds a comment that the +// CLI did not write. The policy keeps no comments, so a person loses them on +// save. written is the text that the CLI wrote: its header, the commented +// fields and their notes. A field line that a person uncomments keeps its +// note, so each part of a written comment line from a "#" on counts too. +func HasUserComments(data, written []byte) bool { + var root yaml.Node + if err := yaml.Unmarshal(data, &root); err != nil { + return false + } + known := writtenComments(written) + var comments []string + collectComments(&root, &comments) + for _, c := range comments { + for _, line := range strings.Split(c, "\n") { + line = strings.TrimSpace(line) + if line == "" { + continue + } + if _, ok := known[line]; !ok { + return true + } + } + } + return false +} + +func writtenComments(written []byte) map[string]struct{} { + known := map[string]struct{}{} + for _, line := range strings.Split(string(written), "\n") { + for i := 0; i < len(line); i++ { + if line[i] == '#' && (i == 0 || line[i-1] == ' ' || line[i-1] == '\t') { + known[strings.TrimSpace(line[i:])] = struct{}{} + } + } + } + return known +} + +func collectComments(n *yaml.Node, out *[]string) { + for _, c := range []string{n.HeadComment, n.LineComment, n.FootComment} { + if c != "" { + *out = append(*out, c) + } + } + for _, child := range n.Content { + collectComments(child, out) + } +} + +func isSpecField(fd protoreflect.FieldDescriptor) bool { + return !fd.IsList() && !fd.IsMap() && isMessageKind(fd) && fd.Message().FullName() == policySpecFullName +} + +// isFormattedMessage reports a message type that the codec writes in a form +// for people instead of field by field. +func isFormattedMessage(md protoreflect.MessageDescriptor) bool { + switch md.FullName() { + case durationFullName, timestampFullName, labelSelectorFullName: + return true + } + return false +} + +func isTemplateLeaf(fd protoreflect.FieldDescriptor) bool { + return isLeaf(fd) || isFormattedMessage(fd.Message()) +} + +// fieldYAML writes one field as the codec does, as "key: value" lines. +func fieldYAML(fd protoreflect.FieldDescriptor, v protoreflect.Value) ([]string, error) { + node := &yaml.Node{Kind: yaml.MappingNode} + node.Content = append(node.Content, scalarNode(documentCodec.key(fd)), documentCodec.encodeField(fd, v)) + text, err := marshalNode(node, "") + if err != nil { + return nil, err + } + return strings.Split(strings.TrimRight(string(text), "\n"), "\n"), nil +} + +// commentedFieldYAML writes a commented field as fieldYAML does, but a +// duration in days when that keeps the value, as 7d for 168h. The codec reads +// both forms. +func commentedFieldYAML(fd protoreflect.FieldDescriptor, v protoreflect.Value) ([]string, error) { + if fd.IsList() || fd.IsMap() || !isMessageKind(fd) || fd.Message().FullName() != durationFullName { + return fieldYAML(fd, v) + } + if d, ok := v.Message().Interface().(*durationpb.Duration); ok { + text := humanDuration(d.AsDuration()) + if parsed, err := duration.Parse(text); err != nil || parsed != d.AsDuration() { + text = duration.Format(d.AsDuration()) + } + return []string{documentCodec.key(fd) + ": " + text}, nil + } + return fieldYAML(fd, v) +} + +// placeholderValue is an example value of a field that no layer sets: the +// first value of an enum, 7d for a duration, or the zero value. +func placeholderValue(fd protoreflect.FieldDescriptor) protoreflect.Value { + if fd.IsList() || fd.IsMap() { + return newField(fd) + } + switch fd.Kind() { + case protoreflect.EnumKind: + for i := 0; i < fd.Enum().Values().Len(); i++ { + if v := fd.Enum().Values().Get(i); v.Number() != 0 { + return protoreflect.ValueOfEnum(v.Number()) + } + } + return fd.Default() + case protoreflect.MessageKind, protoreflect.GroupKind: + switch fd.Message().FullName() { + case durationFullName: + return protoreflect.ValueOfMessage(durationpb.New(examplePlaceholderDuration).ProtoReflect()) + case timestampFullName: + return protoreflect.ValueOfMessage(timestamppb.New(time.Unix(0, 0)).ProtoReflect()) + } + return newField(fd) + default: + return fd.Default() + } +} + +// newField makes an empty value of a list, map or message field, through +// the type of the message that holds the field. +func newField(fd protoreflect.FieldDescriptor) protoreflect.Value { + mt, err := protoregistry.GlobalTypes.FindMessageByName(fd.ContainingMessage().FullName()) + if err != nil { + return fd.Default() + } + return mt.New().NewField(fd) +} + +// valueForm describes the values that a field accepts, in the words of the +// codec. +func valueForm(fd protoreflect.FieldDescriptor) string { + form := singularForm(fd) + switch { + case fd.IsList(): + return "a list of: " + form + case fd.IsMap(): + return "a mapping of: " + form + } + return form +} + +func singularForm(fd protoreflect.FieldDescriptor) string { + switch fd.Kind() { + case protoreflect.EnumKind: + return strings.Join(enumTokens(fd.Enum()), ", ") + case protoreflect.BoolKind: + return "true or false" + case protoreflect.StringKind: + return "text" + case protoreflect.FloatKind, protoreflect.DoubleKind: + return "a number" + case protoreflect.MessageKind, protoreflect.GroupKind: + switch fd.Message().FullName() { + case durationFullName: + return "a duration, as 7d or 12h" + durationRange(fd) + case timestampFullName: + return "a time, as 2027-01-26 or 2027-01-26T00:00:00Z" + case labelSelectorFullName: + return "a label selector, with matchLabels or matchExpressions" + } + return "a mapping" + default: + return "a whole number" + } +} + +// durationRange reads the bounds of a duration field from its protovalidate +// rules, as ", from 0s to 365d". +func durationRange(fd protoreflect.FieldDescriptor) string { + rules, ok := proto.GetExtension(fd.Options(), validate.E_Field).(*validate.FieldRules) + if !ok || !rules.HasDuration() { + return "" + } + d := rules.GetDuration() + var low, high string + switch { + case d.HasGte(): + low = humanDuration(d.GetGte().AsDuration()) + case d.HasGt(): + low = "more than " + humanDuration(d.GetGt().AsDuration()) + } + switch { + case d.HasLte(): + high = humanDuration(d.GetLte().AsDuration()) + case d.HasLt(): + high = "less than " + humanDuration(d.GetLt().AsDuration()) + } + switch { + case low != "" && high != "": + return ", from " + low + " to " + high + case low != "": + return ", at least " + low + case high != "": + return ", at most " + high + } + return "" +} + +// valueAtPath reads a set settings field of spec by its contract path. +func valueAtPath(spec *specv1.PolicySpec, path string) (protoreflect.Value, bool) { + if spec == nil { + return protoreflect.Value{}, false + } + m := spec.ProtoReflect() + segments := strings.Split(path, ".") + for i, segment := range segments { + fd := m.Descriptor().Fields().ByName(protoreflect.Name(segment)) + if fd == nil || !m.Has(fd) { + return protoreflect.Value{}, false + } + if i == len(segments)-1 { + return m.Get(fd), true + } + m = m.Get(fd).Message() + } + return protoreflect.Value{}, false +} + +// firstLeafPath finds the first settings field in descriptor order. +func firstLeafPath(md protoreflect.MessageDescriptor, path string) (string, bool) { + fields := md.Fields() + for i := 0; i < fields.Len(); i++ { + fd := fields.Get(i) + if _, skipped := documentCodec.skip[fd.FullName()]; skipped { + continue + } + fieldPath := joinPath(path, string(fd.Name())) + if isTemplateLeaf(fd) { + return fieldPath, true + } + if p, ok := firstLeafPath(fd.Message(), fieldPath); ok { + return p, true + } + } + return "", false +} + +// setPlaceholder sets the field at path to its placeholder value. +func setPlaceholder(m protoreflect.Message, path string) { + segments := strings.Split(path, ".") + for i, segment := range segments { + fd := m.Descriptor().Fields().ByName(protoreflect.Name(segment)) + if fd == nil { + return + } + if i == len(segments)-1 { + if fd.IsList() || fd.IsMap() { + return + } + m.Set(fd, placeholderValue(fd)) + return + } + m = m.Mutable(fd).Message() + } +} diff --git a/internal/cloudpolicy/template_test.go b/internal/cloudpolicy/template_test.go new file mode 100644 index 0000000..462a9bc --- /dev/null +++ b/internal/cloudpolicy/template_test.go @@ -0,0 +1,211 @@ +package cloudpolicy + +import ( + "strings" + "testing" + + messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/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" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" +) + +// defaultPolicy is the SafeDep default policy of control-tower at revision 1. +func defaultPolicy() DefaultLayer { + spec := specWith(scangatev1.Severity_SEVERITY_HIGH, 0) + spec.GetScanGate().SetFailOnAttacks(scangatev1.AttackGate_ATTACK_GATE_FAIL) + return DefaultLayer{Revision: 1, Spec: spec} +} + +func TestMarshalPolicyTemplate_NewTenant(t *testing.T) { + b, err := MarshalPolicyTemplate(&policyv1.Policy{}, "", defaultPolicy()) + require.NoError(t, err) + + want := `# base: + # package_admission: + # cooldown: + # min_age: 7d # a duration, as 7d or 12h, from 0s to 365d. Now: not set + # 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) + +# An example policy override. It applies to the subjects that its selector matches. +# Remove the "# " at the start of each line to use it, then change the values. +# overrides: +# - name: payments +# priority: 100 +# selector: +# matchLabels: {custom/team: payments} +# spec: +# package_admission: +# cooldown: +# min_age: 168h +` + assert.Equal(t, want, string(b)) +} + +func TestMarshalPolicyTemplate_SetAndUnsetFields(t *testing.T) { + p := &policyv1.Policy{} + p.SetBase(specWith(scangatev1.Severity_SEVERITY_MEDIUM, 0)) + selector := &messagescontroltowerv1.LabelSelector{} + selector.SetMatchLabels(map[string]string{"custom/team": "pay"}) + o := &policyv1.Override{} + o.SetOverrideId("ov_1") + o.SetName("payments") + o.SetPriority(200) + o.SetSelector(selector) + o.SetSpec(specWith(scangatev1.Severity_SEVERITY_LOW, 0)) + p.SetOverrides([]*policyv1.Override{o}) + + b, err := MarshalPolicyTemplate(p, "", defaultPolicy()) + require.NoError(t, err) + text := string(b) + + for _, want := range []string{ + "base:\n", + "\n scan_gate:\n fail_on: medium\n", + " # fail_on_attacks: fail # report, fail. Now: fail (default policy, revision 1)\n", + " # package_admission:\n # cooldown:\n # min_age: 7d #", + "overrides:\n - id: ov_1\n name: payments\n priority: 200\n", + " matchLabels: {custom/team: pay}\n", + " fail_on: low\n", + " # fail_on_attacks: fail # report, fail. Now: fail (default policy, revision 1)\n", + } { + assert.Contains(t, text, want) + } + assert.NotContains(t, text, "An example policy override", "the policy has an override") + for _, line := range strings.Split(text, "\n") { + assert.LessOrEqual(t, len(line), templateWidth, line) + } +} + +func TestMarshalPolicyTemplate_TheOverrideNoteReadsTheBase(t *testing.T) { + p := &policyv1.Policy{} + p.SetBase(specWith(scangatev1.Severity_SEVERITY_MEDIUM, 0)) + o := &policyv1.Override{} + o.SetName("payments") + o.SetPriority(200) + o.SetSelector(&messagescontroltowerv1.LabelSelector{}) + p.SetOverrides([]*policyv1.Override{o}) + + b, err := MarshalPolicyTemplate(p, "", defaultPolicy()) + require.NoError(t, err) + assert.Contains(t, string(b), " # fail_on: medium # critical, high, medium, low, info. Now: medium (base)\n") + assert.Contains(t, string(b), " # spec:\n", "an override with no spec gets a commented spec") +} + +func TestMarshalPolicyTemplate_RoundTrips(t *testing.T) { + emptyBase := &policyv1.Policy{} + emptyBase.SetBase(&specv1.PolicySpec{}) + + emptyCapability := &policyv1.Policy{} + emptyCapability.SetBase(&specv1.PolicySpec{}) + emptyCapability.GetBase().SetScanGate(&scangatev1.ScanGate{}) + + emptySpec := samplePolicy() + emptySpec.GetOverrides()[0].SetSpec(&specv1.PolicySpec{}) + + noSpec := samplePolicy() + noSpec.GetOverrides()[1].ClearSpec() + + tests := []struct { + name string + policy *policyv1.Policy + }{ + {"set fields", samplePolicy()}, + {"a base with no fields", emptyBase}, + {"a capability with no fields", emptyCapability}, + {"an override spec with no fields", emptySpec}, + {"an override with no spec", noSpec}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + b, err := MarshalPolicyTemplate(tt.policy, "", defaultPolicy()) + require.NoError(t, err) + got, err := UnmarshalPolicy(b) + require.NoError(t, err) + assert.True(t, proto.Equal(tt.policy, got), "got %v\n%s", got, b) + assert.False(t, HasUserComments(b, b), "the template holds only the comments of the CLI") + }) + } +} + +func TestMarshalPolicyTemplate_NewTenantHasNoValues(t *testing.T) { + b, err := MarshalPolicyTemplate(&policyv1.Policy{}, "# header\n\n", defaultPolicy()) + require.NoError(t, err) + _, err = UnmarshalPolicy(b) + assert.ErrorIs(t, err, ErrEmptyDocument, "a comment is never a value") +} + +func TestMarshalPolicyTemplate_UncommentOneField(t *testing.T) { + b, err := MarshalPolicyTemplate(&policyv1.Policy{}, "", defaultPolicy()) + require.NoError(t, err) + text := string(b) + for _, line := range []string{"# base:", " # scan_gate:", " # fail_on_attacks: fail"} { + uncommented := strings.Replace(line, "# ", "", 1) + text = strings.Replace(text, line, uncommented, 1) + } + + got, err := UnmarshalPolicy([]byte(text)) + require.NoError(t, err) + gate := &scangatev1.ScanGate{} + gate.SetFailOnAttacks(scangatev1.AttackGate_ATTACK_GATE_FAIL) + want := &policyv1.Policy{} + want.SetBase(&specv1.PolicySpec{}) + want.GetBase().SetScanGate(gate) + assert.True(t, proto.Equal(want, got), "got %v", got) + assert.False(t, HasUserComments([]byte(text), b), "the note of an uncommented line is the CLI's") +} + +func TestMarshalOverrideTemplate(t *testing.T) { + p := samplePolicy() + b, err := MarshalOverrideTemplate(p.GetOverrides()[0], "", defaultPolicy(), p.GetBase()) + require.NoError(t, err) + assert.True(t, strings.HasPrefix(string(b), "id: ov_2\nname: ci\n")) + assert.Contains(t, string(b), "\n # fail_on: high # critical, high, medium, low, info. Now: high (base)\n") + + got, err := UnmarshalOverride(b) + require.NoError(t, err) + assert.True(t, proto.Equal(p.GetOverrides()[0], got)) +} + +func TestHasUserComments_Template(t *testing.T) { + written, err := MarshalPolicyTemplate(samplePolicy(), CommentBlock([]string{"Policy of acme"}), defaultPolicy()) + require.NoError(t, err) + text := string(written) + tests := []struct { + name string + text string + want bool + }{ + {"unchanged", text, false}, + {"a comment of the user", strings.Replace(text, "fail_on: high\n", "fail_on: high # CUST-412\n", 1), true}, + {"a changed note", strings.Replace(text, "Now: fail", "Now: maybe", 1), true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, HasUserComments([]byte(tt.text), written)) + }) + } +} + +func TestValueForm(t *testing.T) { + md := (&specv1.PolicySpec{}).ProtoReflect().Descriptor() + tests := []struct { + path string + want string + }{ + {"scan_gate.fail_on", "critical, high, medium, low, info"}, + {"package_admission.cooldown.min_age", "a duration, as 7d or 12h, from 0s to 365d"}, + } + for _, tt := range tests { + t.Run(tt.path, func(t *testing.T) { + fd := fieldByPath(tt.path) + require.NotNil(t, fd, md.FullName()) + assert.Equal(t, tt.want, valueForm(fd)) + }) + } +} diff --git a/internal/cmd/policy/change_edit.go b/internal/cmd/policy/change_edit.go index db1fd7b..a2374a9 100644 --- a/internal/cmd/policy/change_edit.go +++ b/internal/cmd/policy/change_edit.go @@ -86,7 +86,7 @@ func runChangeEdit( } var updated *policyv1.PolicyChange - err = editSettings(ctx, open, start, editHeader(intro, head), in.Override, func(p *policyv1.Policy) error { + err = editSettings(ctx, open, start, editHeader(intro, head), defaultLayer(head), in.Override, func(p *policyv1.Policy) error { req := &policyv1.UpdatePolicyChangeRequest{} req.SetChangeId(id) req.SetEtag(change.GetEtag()) diff --git a/internal/cmd/policy/edit.go b/internal/cmd/policy/edit.go index 002fd6e..437e0c3 100644 --- a/internal/cmd/policy/edit.go +++ b/internal/cmd/policy/edit.go @@ -18,6 +18,10 @@ import ( clitui "github.com/safedep/cli/internal/tui" ) +// settingsReferenceURL is the page that describes each policy settings field +// and its values. +const settingsReferenceURL = "https://docs.safedep.io/reference/cloud-policy-settings" + type editInput struct { Title string Override string @@ -92,7 +96,7 @@ func runEdit( header := editHeader(intro, head) var change *policyv1.PolicyChange - err = editSettings(ctx, open, head.GetPolicy(), header, in.Override, func(p *policyv1.Policy) error { + err = editSettings(ctx, open, head.GetPolicy(), header, defaultLayer(head), in.Override, func(p *policyv1.Policy) error { req := &policyv1.CreatePolicyChangeRequest{} req.SetTitle(in.Title) req.SetSettings(p) @@ -145,6 +149,8 @@ func editHeader(intro []string, head *policyv1.GetPolicyResponse) string { fmt.Sprintf("Package rules are not in this file: %d %s (safedep policy rule list)", rules, cloudpolicy.Plural(int(rules), "rule", "rules")), "The policy keeps no comments. Write the reason for a value in a description field.", + "To set a field, remove the \"# \" at the start of its line and of the lines of its parents.", + "Fields and values: "+settingsReferenceURL, ) return cloudpolicy.CommentBlock(lines) } diff --git a/internal/cmd/policy/edit_test.go b/internal/cmd/policy/edit_test.go index 61de916..29ff114 100644 --- a/internal/cmd/policy/edit_test.go +++ b/internal/cmd/policy/edit_test.go @@ -6,8 +6,11 @@ import ( "os" "strings" "testing" + "time" + 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" "github.com/safedep/dry/usefulerror" "github.com/stretchr/testify/assert" @@ -17,6 +20,8 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/durationpb" "github.com/safedep/cli/internal/cloudpolicy/mocks" ) @@ -128,8 +133,8 @@ func TestRunEdit_CreatesAChangeFromTheHead(t *testing.T) { }) ed := &scriptedEditor{edits: []func(string) string{ - replace("custom/criticality: high}\n spec:\n scan_gate:\n fail_on: high", - "custom/criticality: high}\n spec:\n scan_gate:\n fail_on: medium"), + // The first field at this depth is the one of override "payments". + replace("\n fail_on: high\n", "\n fail_on: medium\n"), }} change, err := runEdit(context.Background(), client, ed.open, "platform-eng.acme.safedep.io", editInput{Title: "payments: medium"}) @@ -325,9 +330,171 @@ func TestRunChangeEdit_RestoreChange(t *testing.T) { return r.HasSettings() && r.GetSettings().GetBase().GetScanGate().GetFailOn() == scangatev1.Severity_SEVERITY_LOW })).Return(res, nil) - ed := &scriptedEditor{edits: []func(string) string{replace("base:\n scan_gate:\n fail_on: high", "base:\n scan_gate:\n fail_on: low")}} + ed := &scriptedEditor{edits: []func(string) string{replace("\n scan_gate:\n fail_on: high", "\n scan_gate:\n fail_on: low")}} _, err := runChangeEdit(context.Background(), client, ed.open, "", "20", editInput{}) require.NoError(t, err) assert.Contains(t, stderr.String(), "Change 20 restores from revision 46. Saving replaces the settings that the restore made") assert.Contains(t, ed.seen[0], "fail_on: high", "a change with no settings starts from head") } + +// newTenantResponse is GetPolicy for a tenant that never published: no +// revision and no settings, only the SafeDep default policy. +func newTenantResponse() *policyv1.GetPolicyResponse { + res := &policyv1.GetPolicyResponse{} + res.SetDefaultPolicy(headResponse().GetDefaultPolicy()) + return res +} + +// uncomment removes the "# " of the first line that starts with line. +func uncomment(lines ...string) func(string) string { + return func(s string) string { + for _, line := range lines { + s = strings.Replace(s, "\n"+line, "\n"+strings.Replace(line, "# ", "", 1), 1) + } + return s + } +} + +func createdSettings(client *mocks.PolicyServiceClientMock, out **policyv1.Policy) { + client.EXPECT().CreatePolicyChange(mock.Anything, mock.Anything). + RunAndReturn(func(_ context.Context, r *policyv1.CreatePolicyChangeRequest, _ ...grpc.CallOption) (*policyv1.CreatePolicyChangeResponse, error) { + *out = r.GetSettings() + res := &policyv1.CreatePolicyChangeResponse{} + res.SetChange(openChange("18")) + return res, nil + }) +} + +func TestRunEdit_NewTenantDocument(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(newTenantResponse(), nil) + ed := &scriptedEditor{edits: []func(string) string{keep}} + + _, err := runEdit(context.Background(), client, ed.open, "acme.safedep.io", editInput{}) + require.ErrorIs(t, err, errNoChange, "a save of the template as it is changes nothing") + + // docs/cmd/policy-edit.md shows this document. + want := `# Policy of acme.safedep.io · head revision 0 +# Saving creates a draft change. Nothing applies until you publish it. +# +# Layers, from low to high, for each subject: +# 1. SafeDep default policy (read-only, revision 1): +# scan_gate.fail_on: high · scan_gate.fail_on_attacks: fail +# 2. base - applies to every endpoint and project of this tenant +# 3. overrides - apply to the subjects that their selector matches. +# For each field, the highest priority that sets it wins. +# +# Keep the id of each override. A new override has no id. +# Package rules are not in this file: 0 rules (safedep policy rule list) +# The policy keeps no comments. Write the reason for a value in a description field. +# To set a field, remove the "# " at the start of its line and of the lines of its parents. +# Fields and values: https://docs.safedep.io/reference/cloud-policy-settings + +# base: + # package_admission: + # cooldown: + # min_age: 7d # a duration, as 7d or 12h, from 0s to 365d. Now: not set + # 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) + +# An example policy override. It applies to the subjects that its selector matches. +# Remove the "# " at the start of each line to use it, then change the values. +# overrides: +# - name: payments +# priority: 100 +# selector: +# matchLabels: {custom/team: payments} +# spec: +# package_admission: +# cooldown: +# min_age: 168h +` + require.Len(t, ed.seen, 1) + assert.Equal(t, want, ed.seen[0]) +} + +func TestRunEdit_TemplateEdits(t *testing.T) { + cooldown := func() *policyv1.Policy { + p := &policyv1.Policy{} + p.SetBase(&specv1.PolicySpec{}) + c := &packageadmissionv1.Cooldown{} + c.SetMinAge(durationpb.New(7 * 24 * time.Hour)) + pa := &packageadmissionv1.PackageAdmission{} + pa.SetCooldown(c) + p.GetBase().SetPackageAdmission(pa) + return p + } + attacksAtHead := func() *policyv1.Policy { + p := headPolicy() + p.GetBase().GetScanGate().SetFailOnAttacks(scangatev1.AttackGate_ATTACK_GATE_REPORT) + return p + } + tests := []struct { + name string + head *policyv1.GetPolicyResponse + edit func(string) string + want *policyv1.Policy + }{ + { + name: "a new tenant sets one field", + head: newTenantResponse(), + edit: uncomment("# base:", " # package_admission:", " # cooldown:", " # min_age: 7d"), + want: cooldown(), + }, + { + name: "a tenant with values sets one more field", + head: headResponse(), + edit: func(s string) string { + return strings.Replace(s, "\n # fail_on_attacks: fail", "\n fail_on_attacks: report", 1) + }, + want: attacksAtHead(), + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + stderr := captureStderr(t) + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(tt.head, nil) + var got *policyv1.Policy + createdSettings(client, &got) + + _, err := runEdit(context.Background(), client, (&scriptedEditor{edits: []func(string) string{tt.edit}}).open, + "", editInput{}) + require.NoError(t, err) + assert.True(t, proto.Equal(tt.want, got), "got %v", got) + assert.NotContains(t, stderr.String(), "The file holds comments", "the notes are the comments of the CLI") + }) + } +} + +func TestRunEdit_TemplateWithAWrongValueReopens(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(newTenantResponse(), nil) + var got *policyv1.Policy + createdSettings(client, &got) + + ed := &scriptedEditor{edits: []func(string) string{ + func(s string) string { + s = uncomment("# base:", " # scan_gate:")(s) + return strings.Replace(s, "\n # fail_on: high", "\n fail_on: severe", 1) + }, + replace("fail_on: severe", "fail_on: medium"), + }} + _, err := runEdit(context.Background(), client, ed.open, "", editInput{}) + require.NoError(t, err) + require.Len(t, ed.seen, 2) + assert.Contains(t, ed.seen[1], "# ! The last save failed:") + assert.Contains(t, ed.seen[1], `unknown value "severe". Use one of: critical, high, medium, low, info`) + assert.Equal(t, scangatev1.Severity_SEVERITY_MEDIUM, got.GetBase().GetScanGate().GetFailOn()) +} + +func TestRunEdit_TemplateOfATenantWithValuesIsNoChange(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(headResponse(), nil) + ed := &scriptedEditor{edits: []func(string) string{keep}} + _, err := runEdit(context.Background(), client, ed.open, "", editInput{}) + require.ErrorIs(t, err, errNoChange) + assert.Contains(t, ed.seen[0], " # fail_on_attacks: fail # report, fail. Now: fail (default policy, revision 1)\n") + assert.NotContains(t, ed.seen[0], "An example policy override", "the policy has overrides") +} diff --git a/internal/cmd/policy/settings.go b/internal/cmd/policy/settings.go index 4687a5e..47ec53a 100644 --- a/internal/cmd/policy/settings.go +++ b/internal/cmd/policy/settings.go @@ -21,6 +21,7 @@ func editSettings( open openEditorFunc, start *policyv1.Policy, header string, + def cloudpolicy.DefaultLayer, overrideName string, commit func(*policyv1.Policy) error, ) error { @@ -31,9 +32,30 @@ func editSettings( return err } if overrideName == "" { - return editWholeDocument(ctx, open, start, header, commit) + return editWholeDocument(ctx, open, start, header, def, commit) } - return editOneOverride(ctx, open, start, header, overrideName, commit) + return editOneOverride(ctx, open, start, header, def, overrideName, commit) +} + +// defaultLayer is the SafeDep default policy of a GetPolicy reply, for the +// notes of the edit template. +func defaultLayer(head *policyv1.GetPolicyResponse) cloudpolicy.DefaultLayer { + return cloudpolicy.DefaultLayer{ + Revision: head.GetDefaultPolicy().GetRevision(), + Spec: head.GetDefaultPolicy().GetSpec(), + } +} + +// decodeDocument reads a saved document. The template of a policy with no +// settings has only comments, so a save of it as it is reads as that empty +// policy. A file with only comments for a policy with settings stays an +// error, so a person never clears the policy by accident. +func decodeDocument(saved []byte, start *policyv1.Policy) (*policyv1.Policy, error) { + edited, err := cloudpolicy.UnmarshalPolicy(saved) + if errors.Is(err, cloudpolicy.ErrEmptyDocument) && proto.Size(start) == 0 { + return &policyv1.Policy{}, nil + } + return edited, err } func editWholeDocument( @@ -41,25 +63,26 @@ func editWholeDocument( open openEditorFunc, start *policyv1.Policy, header string, + def cloudpolicy.DefaultLayer, commit func(*policyv1.Policy) error, ) error { - text, err := cloudpolicy.MarshalPolicy(start, header) + text, err := cloudpolicy.MarshalPolicyTemplate(start, header, def) if err != nil { return err } unchanged := func(saved []byte) bool { - edited, err := cloudpolicy.UnmarshalPolicy(saved) + edited, err := decodeDocument(saved, start) return err == nil && proto.Equal(edited, start) } return editLoop(ctx, open, text, unchanged, func(saved []byte) error { - edited, err := cloudpolicy.UnmarshalPolicy(saved) + edited, err := decodeDocument(saved, start) if err != nil { return retryable(err) } if err := checkEditedSettings(start, edited); err != nil { return retryable(err) } - warnComments(saved, header) + warnComments(saved, text) return commit(edited) }) } @@ -69,6 +92,7 @@ func editOneOverride( open openEditorFunc, start *policyv1.Policy, header string, + def cloudpolicy.DefaultLayer, overrideName string, commit func(*policyv1.Policy) error, ) error { @@ -76,7 +100,7 @@ func editOneOverride( if err != nil { return err } - text, err := cloudpolicy.MarshalOverride(current, header) + text, err := cloudpolicy.MarshalOverrideTemplate(current, header, def, start.GetBase()) if err != nil { return err } @@ -103,7 +127,7 @@ func editOneOverride( if err := checkEditedSettings(start, full); err != nil { return retryable(err) } - warnComments(saved, header) + warnComments(saved, text) return commit(full) }) } @@ -184,8 +208,8 @@ func validateSettings(p *policyv1.Policy) error { return nil } -func warnComments(saved []byte, header string) { - if cloudpolicy.HasUserComments(saved, header) { +func warnComments(saved, written []byte) { + if cloudpolicy.HasUserComments(saved, written) { tui.Warning("The file holds comments. The policy keeps no comments, so they are lost. " + "Write the reason in a description field") } From 6d8f6fa1781be7ef767f69bb1c6bcaed357dd1ee Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Thu, 5 Nov 2026 08:16:41 +0000 Subject: [PATCH 13/17] fix(policy): make the edit template safe to clear and honest in its notes A review of the policy edit template found these problems: - A tenant with values that saved a file with only comments got "the file is empty", with no way to clear the policy. The editor now opens again with: the file sets no field. To remove every setting, write {} on one line. - A parent key that a person uncommented alone, as base:, made a change with an empty message. The edit now compares the documents with their empty messages pruned, so that is no change. A field that a person removes still makes a change. A label selector, a duration and a time are never pruned, because their empty value has a meaning. - The note of an override field said "Now: medium (base)", but an override of a lower priority can also set the field. It now says "Below this override". A base field with no value in any layer now says that each tool uses its local value. - The example override wrote min_age: 168h while the notes wrote 7d. The template writer now writes it in days. The generated setters build it, so a removed field fails the build. - The header asks for the reason in a description field, but the template showed none. It now shows base_description and the description of the example override. Also: MarshalOverride had no caller and is removed. isLeaf and the codec read one predicate, isFormattedMessage. The comment check reads only comment lines of the written text, so a "#" in a value is not a comment. A note that is longer than the line wraps. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MhRi597EX9odoSDXbVBsxz --- docs/cmd/policy-edit.md | 28 ++- internal/cloudpolicy/document.go | 5 - internal/cloudpolicy/document_test.go | 35 --- internal/cloudpolicy/fields.go | 6 +- internal/cloudpolicy/protoyaml.go | 30 ++- internal/cloudpolicy/template.go | 334 +++++++++++++++----------- internal/cloudpolicy/template_test.go | 98 +++++++- internal/cmd/policy/edit_test.go | 139 ++++++++--- internal/cmd/policy/settings.go | 26 +- 9 files changed, 450 insertions(+), 251 deletions(-) diff --git a/docs/cmd/policy-edit.md b/docs/cmd/policy-edit.md index 6a68de3..21483eb 100644 --- a/docs/cmd/policy-edit.md +++ b/docs/cmd/policy-edit.md @@ -27,8 +27,9 @@ safedep policy edit -m "payments: medium + cooldown" The document has every policy settings field of the contract. A field that the policy sets is a YAML line. A field that it does not set is a commented line at -its nesting, with a note: the values that the field accepts, and the value that -the subjects get now and the layer that sets it. To set a field, remove the `# ` +its nesting, with a note: the values that the field accepts, and the value of +the layers below and the layer that sets it. When no layer sets a field, each +tool uses its local value. To set a field, remove the `# ` at the start of its line and of the lines of its parents. A save of the document as it is changes nothing. When the policy has no override, the document ends with a commented example of one. @@ -55,22 +56,25 @@ The document of a tenant that has not published a policy yet: # base: # package_admission: # cooldown: - # min_age: 7d # a duration, as 7d or 12h, from 0s to 365d. Now: not set + # a duration, as 7d or 12h, from 0s to 365d. Now: not set, each tool uses its local value + # min_age: 7d # 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) +# base_description: Why the base has these values # text # An example policy override. It applies to the subjects that its selector matches. # Remove the "# " at the start of each line to use it, then change the values. # overrides: # - name: payments +# description: A longer cooldown for the payments team # priority: 100 # selector: # matchLabels: {custom/team: payments} # spec: # package_admission: # cooldown: -# min_age: 168h +# min_age: 7d ``` To set a cooldown of 7 days for the whole tenant, remove the `# ` from the @@ -82,10 +86,12 @@ The start of the document of a tenant with values, after the header: base: # package_admission: # cooldown: - # min_age: 7d # a duration, as 7d or 12h, from 0s to 365d. Now: not set + # a duration, as 7d or 12h, from 0s to 365d. Now: not set, each tool uses its local value + # min_age: 7d scan_gate: fail_on: high # fail_on_attacks: fail # report, fail. Now: fail (default policy, revision 1) +# base_description: Why the base has these values # text overrides: - id: ov_pay name: payments @@ -95,12 +101,17 @@ overrides: spec: # package_admission: # cooldown: - # min_age: 7d # a duration, as 7d or 12h, from 0s to 365d. Now: not set + # min_age: 7d # a duration, as 7d or 12h, from 0s to 365d. Below this override: not set scan_gate: fail_on: high - # fail_on_attacks: fail # report, fail. Now: fail (default policy, revision 1) + # report, fail. Below this override: fail (default policy, revision 1) + # fail_on_attacks: fail ``` +A note of a base field says the value that the subjects get now. A note of an +override field says the value of the base or the default policy below it. An +override of a lower priority can also set the field for some subjects. + ``` ✓ change 18 saved from revision 46 Review it: safedep policy change show 18 @@ -126,6 +137,9 @@ safedep policy edit --override payments opens again with the error at the top. Close it with no change to stop. - 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. +- When the policy has settings and the saved file sets no field, the editor + opens again with the error. To remove every setting, write `{}` on one line. - When the save fails for another reason, the command keeps the file and prints its path. diff --git a/internal/cloudpolicy/document.go b/internal/cloudpolicy/document.go index fdd0332..0138251 100644 --- a/internal/cloudpolicy/document.go +++ b/internal/cloudpolicy/document.go @@ -77,11 +77,6 @@ func UnmarshalPolicy(data []byte) (*policyv1.Policy, error) { return p, nil } -// MarshalOverride writes one policy override as YAML, after the header. -func MarshalOverride(o *policyv1.Override, header string) ([]byte, error) { - return marshalNode(documentCodec.encodeMessage(o.ProtoReflect()), header) -} - // UnmarshalOverride reads one policy override. func UnmarshalOverride(data []byte) (*policyv1.Override, error) { node, err := parseDocument(data) diff --git a/internal/cloudpolicy/document_test.go b/internal/cloudpolicy/document_test.go index 7f26c7b..4355609 100644 --- a/internal/cloudpolicy/document_test.go +++ b/internal/cloudpolicy/document_test.go @@ -5,9 +5,7 @@ import ( "testing" "time" - messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" scangatev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/scangate/v1" - policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/protobuf/encoding/protowire" @@ -138,39 +136,6 @@ func TestUnmarshalPolicy_Errors(t *testing.T) { } } -func TestSelectorExpressions_RoundTrip(t *testing.T) { - sel, err := ParseSelector("scm/forge=github, custom/tier in (a,b), !custom/legacy, custom/owner") - require.NoError(t, err) - o := &policyv1.Override{} - o.SetName("mixed") - o.SetPriority(10) - o.SetSelector(sel) - o.SetExpiresAt(timestamppb.New(time.Date(2027, 1, 26, 0, 0, 0, 0, time.UTC))) - - b, err := MarshalOverride(o, "") - require.NoError(t, err) - assert.Contains(t, string(b), "operator: In") - assert.Contains(t, string(b), "expires_at: 2027-01-26T00:00:00Z") - - got, err := UnmarshalOverride(b) - require.NoError(t, err) - assert.True(t, proto.Equal(o, got), "got %v", got) -} - -func TestEmptySelectorKeepsItsPresence(t *testing.T) { - o := &policyv1.Override{} - o.SetName("all") - o.SetPriority(1) - o.SetSelector(&messagescontroltowerv1.LabelSelector{}) - b, err := MarshalOverride(o, "") - require.NoError(t, err) - assert.Contains(t, string(b), "selector: {}") - - got, err := UnmarshalOverride(b) - require.NoError(t, err) - assert.True(t, got.HasSelector(), "selector: {} selects every subject and must stay set") -} - func TestUnmarshalPolicy_KeepsTheIDThatTheUserLeaves(t *testing.T) { got, err := UnmarshalPolicy([]byte(` overrides: diff --git a/internal/cloudpolicy/fields.go b/internal/cloudpolicy/fields.go index 9529a78..572cf13 100644 --- a/internal/cloudpolicy/fields.go +++ b/internal/cloudpolicy/fields.go @@ -134,11 +134,7 @@ func isLeaf(fd protoreflect.FieldDescriptor) bool { if fd.Kind() != protoreflect.MessageKind || fd.IsList() || fd.IsMap() { return true } - switch fd.Message().FullName() { - case durationFullName, timestampFullName: - return true - } - return false + return isFormattedMessage(fd.Message()) } func formatFieldValue(fd protoreflect.FieldDescriptor, v protoreflect.Value) (string, string) { diff --git a/internal/cloudpolicy/protoyaml.go b/internal/cloudpolicy/protoyaml.go index f0548f8..cde6bb0 100644 --- a/internal/cloudpolicy/protoyaml.go +++ b/internal/cloudpolicy/protoyaml.go @@ -70,11 +70,11 @@ func (c *yamlCodec) fieldByKey(md protoreflect.MessageDescriptor, key string) pr } func (c *yamlCodec) encodeMessage(m protoreflect.Message) *yaml.Node { - switch m.Descriptor().FullName() { - case durationFullName, timestampFullName: + if isFormattedMessage(m.Descriptor()) { + if m.Descriptor().FullName() == labelSelectorFullName { + return encodeSelector(m) + } return scalarNode(c.formatWellKnown(m)) - case labelSelectorFullName: - return encodeSelector(m) } out := &yaml.Node{Kind: yaml.MappingNode} @@ -282,13 +282,8 @@ func (c *yamlCodec) decodeMessage(n *yaml.Node, m protoreflect.Message, path str if isNull(n) { return nil } - switch m.Descriptor().FullName() { - case durationFullName: - return decodeDuration(n, m, path) - case timestampFullName: - return decodeTimestamp(n, m, path) - case labelSelectorFullName: - return decodeSelector(n, m, path) + if isFormattedMessage(m.Descriptor()) { + return decodeFormatted(n, m, path) } if n.Kind != yaml.MappingNode { return errAt(n, path, "expected a mapping of fields") @@ -464,6 +459,19 @@ func decodeScalar(n *yaml.Node, fd protoreflect.FieldDescriptor, path string) (p } } +// decodeFormatted reads a message type that the codec writes in a form for +// people. +func decodeFormatted(n *yaml.Node, m protoreflect.Message, path string) error { + switch m.Descriptor().FullName() { + case durationFullName: + return decodeDuration(n, m, path) + case timestampFullName: + return decodeTimestamp(n, m, path) + default: + return decodeSelector(n, m, path) + } +} + func decodeDuration(n *yaml.Node, m protoreflect.Message, path string) error { if n.Kind != yaml.ScalarNode { return errAt(n, path, "expected a duration, as in 168h or 7d") diff --git a/internal/cloudpolicy/template.go b/internal/cloudpolicy/template.go index 94769d0..d399308 100644 --- a/internal/cloudpolicy/template.go +++ b/internal/cloudpolicy/template.go @@ -8,14 +8,13 @@ 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" 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" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" - "google.golang.org/protobuf/reflect/protoregistry" "google.golang.org/protobuf/types/known/durationpb" - "google.golang.org/protobuf/types/known/timestamppb" "github.com/safedep/cli/internal/duration" "github.com/safedep/cli/internal/tui" @@ -33,14 +32,19 @@ const ( // note goes on its own comment line above the field. templateWidth = 100 - // examplePlaceholderDuration is the value of a duration field that no - // layer sets, as an example of the form. - examplePlaceholderDuration = 7 * 24 * time.Hour + // placeholderDuration is the value of a duration field that no layer + // sets, as an example of the form. + placeholderDuration = 7 * 24 * time.Hour ) var ( policySpecFullName = (&specv1.PolicySpec{}).ProtoReflect().Descriptor().FullName() policyFullName = (&policyv1.Policy{}).ProtoReflect().Descriptor().FullName() + + // baseDescriptionFullName is the field that holds the reason for the + // 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") ) // DefaultLayer is the SafeDep default policy, the layer below the base. @@ -56,10 +60,33 @@ type belowLayer struct { spec *specv1.PolicySpec } +// notePrefix opens the part of a note that names the value below a field. +// A field of the base gets the value that its subjects get now. A field of +// an override gets only the value of the base or the default policy: an +// override of a lower priority can also set it, for some subjects. +type notePrefix struct { + label string + notSet string +} + +var ( + baseNote = notePrefix{ + label: "Now", + notSet: "not set, each tool uses its local value", + } + overrideNote = notePrefix{ + label: "Below this override", + notSet: "not set", + } +) + type templateWriter struct { def DefaultLayer base *specv1.PolicySpec lines []string + // example writes only the set fields, with durations in days, for the + // commented example override. + example bool } // MarshalPolicyTemplate writes the policy settings document for an edit: @@ -123,19 +150,13 @@ func (w *templateWriter) messageFields(m protoreflect.Message, indent int) error key := documentCodec.key(fd) switch { case isSpecField(fd): - below := w.belowFor(m.Descriptor().FullName()) - if m.Has(fd) { - w.real(indent, key+":") - if err := w.specFields(fd.Message(), m.Get(fd).Message(), "", indent+2, below); err != nil { - return err - } - continue - } - w.comment(indent, key+":") - if err := w.specFields(fd.Message(), nil, "", indent+2, below); err != nil { + if err := w.spec(key, fd, m, indent); err != nil { return err } case !m.Has(fd): + if fd.FullName() == baseDescriptionFullName && !w.example { + w.comment(indent, key+": Why the base has these values # text") + } case fd.IsList() && isMessageKind(fd) && !isFormattedMessage(fd.Message()): w.real(indent, key+":") list := m.Get(fd).List() @@ -145,18 +166,42 @@ func (w *templateWriter) messageFields(m protoreflect.Message, indent int) error } } default: - lines, err := fieldYAML(fd, m.Get(fd)) - if err != nil { + if err := w.realField(fd, m.Get(fd), indent); err != nil { return err } - for _, line := range lines { - w.real(indent, line) - } } } return nil } +// spec writes a policy settings spec field of m. An unset spec is a +// commented block. +func (w *templateWriter) spec(key string, fd protoreflect.FieldDescriptor, m protoreflect.Message, indent int) error { + below, note := w.belowFor(m.Descriptor().FullName()) + var msg protoreflect.Message + switch { + case m.Has(fd): + w.real(indent, key+":") + msg = m.Get(fd).Message() + case w.example: + return nil + default: + w.comment(indent, key+":") + } + return w.specFields(fd.Message(), msg, "", indent+2, below, note) +} + +func (w *templateWriter) realField(fd protoreflect.FieldDescriptor, v protoreflect.Value, indent int) error { + lines, err := fieldYAML(fd, v, w.example) + if err != nil { + return err + } + for _, line := range lines { + w.real(indent, line) + } + return nil +} + // listItem writes one item of a list of messages. The first YAML line of the // item carries the "- " of the list. func (w *templateWriter) listItem(m protoreflect.Message, indent int) error { @@ -181,15 +226,15 @@ func (w *templateWriter) listItem(m protoreflect.Message, indent int) error { // belowFor gives the layers below a policy settings spec of a message: the // default policy for the base, and the base and the default policy for an // override. -func (w *templateWriter) belowFor(owner protoreflect.FullName) []belowLayer { +func (w *templateWriter) belowFor(owner protoreflect.FullName) ([]belowLayer, notePrefix) { def := belowLayer{ name: fmt.Sprintf("default policy, revision %d", w.def.Revision), spec: w.def.Spec, } if owner == policyFullName { - return []belowLayer{def} + return []belowLayer{def}, baseNote } - return []belowLayer{{name: "base", spec: w.base}, def} + return []belowLayer{{name: "base", spec: w.base}, def}, overrideNote } // specFields writes the fields of a policy settings message. msg is nil when @@ -200,6 +245,7 @@ func (w *templateWriter) specFields( path string, indent int, below []belowLayer, + note notePrefix, ) error { fields := md.Fields() for i := 0; i < fields.Len(); i++ { @@ -209,8 +255,17 @@ func (w *templateWriter) specFields( } fieldPath := joinPath(path, string(fd.Name())) set := msg != nil && msg.Has(fd) - if isTemplateLeaf(fd) { - if err := w.leaf(fd, msg, set, fieldPath, indent, below); err != nil { + if w.example && !set { + continue + } + if isLeaf(fd) { + if set { + if err := w.realField(fd, msg.Get(fd), indent); err != nil { + return err + } + continue + } + if err := w.commentedLeaf(fd, fieldPath, indent, below, note); err != nil { return err } continue @@ -223,54 +278,48 @@ func (w *templateWriter) specFields( } else { w.comment(indent, key+":") } - if err := w.specFields(fd.Message(), child, fieldPath, indent+2, below); err != nil { + if err := w.specFields(fd.Message(), child, fieldPath, indent+2, below, note); err != nil { return err } } return nil } -// leaf writes one settings field. An unset field shows the value that the -// subjects get now, or an example of the form, with a note. -func (w *templateWriter) leaf( +// commentedLeaf writes one unset settings field as a comment. It shows the +// value of the nearest layer below that sets it, or an example of the form, +// with a note. +func (w *templateWriter) commentedLeaf( fd protoreflect.FieldDescriptor, - msg protoreflect.Message, - set bool, path string, indent int, below []belowLayer, + note notePrefix, ) error { - if set { - lines, err := fieldYAML(fd, msg.Get(fd)) - if err != nil { - return err - } - for _, line := range lines { - w.real(indent, line) - } - return nil - } - - value := placeholderValue(fd) - now := "Now: not set" + value, hasValue := placeholderValue(fd) + now := note.label + ": " + note.notSet for _, layer := range below { if v, ok := valueAtPath(layer.spec, path); ok { - value = v + value, hasValue = v, true _, human := formatFieldValue(fd, v) - now = fmt.Sprintf("Now: %s (%s)", human, layer.name) + now = fmt.Sprintf("%s: %s (%s)", note.label, human, layer.name) break } } - lines, err := commentedFieldYAML(fd, value) - if err != nil { - return err + lines := []string{documentCodec.key(fd) + ":"} + if hasValue { + var err error + if lines, err = fieldYAML(fd, value, true); err != nil { + return err + } } - note := tui.EscapeLine(valueForm(fd) + ". " + now) + text := tui.EscapeLine(valueForm(fd) + ". " + now) first := strings.Repeat(" ", indent) + "# " + lines[0] - if len(first)+len(" # ")+len(note) <= templateWidth { - w.lines = append(w.lines, first+" # "+note) + if len(first)+len(" # ")+len(text) <= templateWidth { + w.lines = append(w.lines, first+" # "+text) } else { - w.comment(indent, note) + for _, line := range wrapWords(text, templateWidth-indent-len("# ")) { + w.comment(indent, line) + } w.lines = append(w.lines, first) } for _, line := range lines[1:] { @@ -279,26 +328,51 @@ func (w *templateWriter) leaf( return nil } +// wrapWords splits text into lines of at most width bytes, at spaces. A word +// longer than width gets a line of its own. +func wrapWords(text string, width int) []string { + var lines []string + line := "" + for _, word := range strings.Fields(text) { + switch { + case line == "": + line = word + case len(line)+1+len(word) <= width: + line += " " + word + default: + lines = append(lines, line) + line = word + } + } + if line != "" { + lines = append(lines, line) + } + return lines +} + // overrideExample writes a commented policy override after the base, for a -// policy that has none. The codec writes it, so the keys are the ones that -// it reads. +// policy that has none. The generated setters build it, so a field that the +// contract removes fails the build here. func (w *templateWriter) overrideExample() error { selector := &messagescontroltowerv1.LabelSelector{} selector.SetMatchLabels(map[string]string{"custom/team": "payments"}) + cooldown := &packageadmissionv1.Cooldown{} + cooldown.SetMinAge(durationpb.New(placeholderDuration)) + admission := &packageadmissionv1.PackageAdmission{} + admission.SetCooldown(cooldown) spec := &specv1.PolicySpec{} - if path, ok := firstLeafPath(spec.ProtoReflect().Descriptor(), ""); ok { - setPlaceholder(spec.ProtoReflect(), path) - } + spec.SetPackageAdmission(admission) o := &policyv1.Override{} o.SetName("payments") + o.SetDescription("A longer cooldown for the payments team") o.SetPriority(100) o.SetSelector(selector) o.SetSpec(spec) example := &policyv1.Policy{} example.SetOverrides([]*policyv1.Override{o}) - text, err := MarshalPolicy(example, "") - if err != nil { + ex := &templateWriter{example: true} + if err := ex.messageFields(example.ProtoReflect(), 0); err != nil { return err } w.lines = append(w.lines, @@ -306,7 +380,7 @@ func (w *templateWriter) overrideExample() error { "# An example policy override. It applies to the subjects that its selector matches.", "# Remove the \"# \" at the start of each line to use it, then change the values.", ) - for _, line := range strings.Split(strings.TrimRight(string(text), "\n"), "\n") { + for _, line := range ex.lines { w.lines = append(w.lines, "# "+line) } return nil @@ -339,9 +413,17 @@ func HasUserComments(data, written []byte) bool { return false } +// writtenComments reads only the lines of written that start with "#", so a +// "#" in a value, as in a description, never counts. A line that starts with +// "#" in a block scalar can count as a comment: then the check misses only a +// user comment with the same text, and the save stays correct. func writtenComments(written []byte) map[string]struct{} { known := map[string]struct{}{} for _, line := range strings.Split(string(written), "\n") { + line = strings.TrimSpace(line) + if !strings.HasPrefix(line, "#") { + continue + } for i := 0; i < len(line); i++ { if line[i] == '#' && (i == 0 || line[i-1] == ' ' || line[i-1] == '\t') { known[strings.TrimSpace(line[i:])] = struct{}{} @@ -376,14 +458,22 @@ func isFormattedMessage(md protoreflect.MessageDescriptor) bool { return false } -func isTemplateLeaf(fd protoreflect.FieldDescriptor) bool { - return isLeaf(fd) || isFormattedMessage(fd.Message()) -} - -// fieldYAML writes one field as the codec does, as "key: value" lines. -func fieldYAML(fd protoreflect.FieldDescriptor, v protoreflect.Value) ([]string, error) { +// fieldYAML writes one field as the codec does, as "key: value" lines. With +// days, a duration is in days when that keeps the value, as 7d for 168h. The +// codec reads both forms. +func fieldYAML(fd protoreflect.FieldDescriptor, v protoreflect.Value, days bool) ([]string, error) { + key := documentCodec.key(fd) + if days && !fd.IsList() && !fd.IsMap() && isMessageKind(fd) && fd.Message().FullName() == durationFullName { + if d, ok := v.Message().Interface().(*durationpb.Duration); ok { + text := humanDuration(d.AsDuration()) + if parsed, err := duration.Parse(text); err != nil || parsed != d.AsDuration() { + text = duration.Format(d.AsDuration()) + } + return []string{key + ": " + text}, nil + } + } node := &yaml.Node{Kind: yaml.MappingNode} - node.Content = append(node.Content, scalarNode(documentCodec.key(fd)), documentCodec.encodeField(fd, v)) + node.Content = append(node.Content, scalarNode(key), documentCodec.encodeField(fd, v)) text, err := marshalNode(node, "") if err != nil { return nil, err @@ -391,58 +481,29 @@ func fieldYAML(fd protoreflect.FieldDescriptor, v protoreflect.Value) ([]string, return strings.Split(strings.TrimRight(string(text), "\n"), "\n"), nil } -// commentedFieldYAML writes a commented field as fieldYAML does, but a -// duration in days when that keeps the value, as 7d for 168h. The codec reads -// both forms. -func commentedFieldYAML(fd protoreflect.FieldDescriptor, v protoreflect.Value) ([]string, error) { - if fd.IsList() || fd.IsMap() || !isMessageKind(fd) || fd.Message().FullName() != durationFullName { - return fieldYAML(fd, v) - } - if d, ok := v.Message().Interface().(*durationpb.Duration); ok { - text := humanDuration(d.AsDuration()) - if parsed, err := duration.Parse(text); err != nil || parsed != d.AsDuration() { - text = duration.Format(d.AsDuration()) - } - return []string{documentCodec.key(fd) + ": " + text}, nil - } - return fieldYAML(fd, v) -} - // placeholderValue is an example value of a field that no layer sets: the -// first value of an enum, 7d for a duration, or the zero value. -func placeholderValue(fd protoreflect.FieldDescriptor) protoreflect.Value { +// first value of an enum, 7d for a duration, or the zero value of a scalar. +// Other fields get no example value. +func placeholderValue(fd protoreflect.FieldDescriptor) (protoreflect.Value, bool) { if fd.IsList() || fd.IsMap() { - return newField(fd) + return protoreflect.Value{}, false } switch fd.Kind() { case protoreflect.EnumKind: for i := 0; i < fd.Enum().Values().Len(); i++ { if v := fd.Enum().Values().Get(i); v.Number() != 0 { - return protoreflect.ValueOfEnum(v.Number()) + return protoreflect.ValueOfEnum(v.Number()), true } } - return fd.Default() + return protoreflect.Value{}, false case protoreflect.MessageKind, protoreflect.GroupKind: - switch fd.Message().FullName() { - case durationFullName: - return protoreflect.ValueOfMessage(durationpb.New(examplePlaceholderDuration).ProtoReflect()) - case timestampFullName: - return protoreflect.ValueOfMessage(timestamppb.New(time.Unix(0, 0)).ProtoReflect()) + if fd.Message().FullName() == durationFullName { + return protoreflect.ValueOfMessage(durationpb.New(placeholderDuration).ProtoReflect()), true } - return newField(fd) + return protoreflect.Value{}, false default: - return fd.Default() - } -} - -// newField makes an empty value of a list, map or message field, through -// the type of the message that holds the field. -func newField(fd protoreflect.FieldDescriptor) protoreflect.Value { - mt, err := protoregistry.GlobalTypes.FindMessageByName(fd.ContainingMessage().FullName()) - if err != nil { - return fd.Default() + return fd.Default(), true } - return mt.New().NewField(fd) } // valueForm describes the values that a field accepts, in the words of the @@ -535,40 +596,37 @@ func valueAtPath(spec *specv1.PolicySpec, path string) (protoreflect.Value, bool return protoreflect.Value{}, false } -// firstLeafPath finds the first settings field in descriptor order. -func firstLeafPath(md protoreflect.MessageDescriptor, path string) (string, bool) { - fields := md.Fields() - for i := 0; i < fields.Len(); i++ { - fd := fields.Get(i) - if _, skipped := documentCodec.skip[fd.FullName()]; skipped { - continue - } - fieldPath := joinPath(path, string(fd.Name())) - if isTemplateLeaf(fd) { - return fieldPath, true - } - if p, ok := firstLeafPath(fd.Message(), fieldPath); ok { - return p, true - } - } - return "", false +// 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. +// 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 { + out := proto.Clone(m) + pruneMessage(out.ProtoReflect()) + return out } -// setPlaceholder sets the field at path to its placeholder value. -func setPlaceholder(m protoreflect.Message, path string) { - segments := strings.Split(path, ".") - for i, segment := range segments { - fd := m.Descriptor().Fields().ByName(protoreflect.Name(segment)) - if fd == nil { - return - } - if i == len(segments)-1 { - if fd.IsList() || fd.IsMap() { - return +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 fd.IsList(): + list := v.List() + for i := 0; i < list.Len(); i++ { + pruneMessage(list.Get(i).Message()) + } + case !isFormattedMessage(fd.Message()): + child := v.Message() + pruneMessage(child) + if proto.Size(child.Interface()) == 0 { + empty = append(empty, fd) } - m.Set(fd, placeholderValue(fd)) - return } - m = m.Mutable(fd).Message() + return true + }) + for _, fd := range empty { + m.Clear(fd) } } diff --git a/internal/cloudpolicy/template_test.go b/internal/cloudpolicy/template_test.go index 462a9bc..f1a860e 100644 --- a/internal/cloudpolicy/template_test.go +++ b/internal/cloudpolicy/template_test.go @@ -3,6 +3,7 @@ package cloudpolicy import ( "strings" "testing" + "time" messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" scangatev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/scangate/v1" @@ -11,6 +12,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/durationpb" + "google.golang.org/protobuf/types/known/timestamppb" ) // defaultPolicy is the SafeDep default policy of control-tower at revision 1. @@ -24,25 +27,29 @@ func TestMarshalPolicyTemplate_NewTenant(t *testing.T) { b, err := MarshalPolicyTemplate(&policyv1.Policy{}, "", defaultPolicy()) require.NoError(t, err) + // docs/cmd/policy-edit.md shows this document after the header. want := `# base: # package_admission: # cooldown: - # min_age: 7d # a duration, as 7d or 12h, from 0s to 365d. Now: not set + # a duration, as 7d or 12h, from 0s to 365d. Now: not set, each tool uses its local value + # min_age: 7d # 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) +# base_description: Why the base has these values # text # An example policy override. It applies to the subjects that its selector matches. # Remove the "# " at the start of each line to use it, then change the values. # overrides: # - name: payments +# description: A longer cooldown for the payments team # priority: 100 # selector: # matchLabels: {custom/team: payments} # spec: # package_admission: # cooldown: -# min_age: 168h +# min_age: 7d ` assert.Equal(t, want, string(b)) } @@ -68,11 +75,13 @@ func TestMarshalPolicyTemplate_SetAndUnsetFields(t *testing.T) { "base:\n", "\n scan_gate:\n fail_on: medium\n", " # fail_on_attacks: fail # report, fail. Now: fail (default policy, revision 1)\n", - " # package_admission:\n # cooldown:\n # min_age: 7d #", + " # package_admission:\n # cooldown:\n # a duration, as 7d or 12h, from 0s to 365d. Now: not set, each tool uses its local value\n # min_age: 7d\n", + "# base_description: Why the base has these values # text\n", "overrides:\n - id: ov_1\n name: payments\n priority: 200\n", " matchLabels: {custom/team: pay}\n", " fail_on: low\n", - " # fail_on_attacks: fail # report, fail. Now: fail (default policy, revision 1)\n", + " # min_age: 7d # a duration, as 7d or 12h, from 0s to 365d. Below this override: not set\n", + " # report, fail. Below this override: fail (default policy, revision 1)\n # fail_on_attacks: fail\n", } { assert.Contains(t, text, want) } @@ -93,7 +102,7 @@ func TestMarshalPolicyTemplate_TheOverrideNoteReadsTheBase(t *testing.T) { b, err := MarshalPolicyTemplate(p, "", defaultPolicy()) require.NoError(t, err) - assert.Contains(t, string(b), " # fail_on: medium # critical, high, medium, low, info. Now: medium (base)\n") + assert.Contains(t, string(b), " # fail_on: medium # critical, high, medium, low, info. Below this override: medium (base)\n") assert.Contains(t, string(b), " # spec:\n", "an override with no spec gets a commented spec") } @@ -165,7 +174,7 @@ func TestMarshalOverrideTemplate(t *testing.T) { b, err := MarshalOverrideTemplate(p.GetOverrides()[0], "", defaultPolicy(), p.GetBase()) require.NoError(t, err) assert.True(t, strings.HasPrefix(string(b), "id: ov_2\nname: ci\n")) - assert.Contains(t, string(b), "\n # fail_on: high # critical, high, medium, low, info. Now: high (base)\n") + assert.Contains(t, string(b), "\n # fail_on: high # critical, high, medium, low, info. Below this override: high (base)\n") got, err := UnmarshalOverride(b) require.NoError(t, err) @@ -209,3 +218,80 @@ func TestValueForm(t *testing.T) { }) } } + +func TestSelectorExpressions_RoundTrip(t *testing.T) { + sel, err := ParseSelector("scm/forge=github, custom/tier in (a,b), !custom/legacy, custom/owner") + require.NoError(t, err) + o := &policyv1.Override{} + o.SetName("mixed") + o.SetPriority(10) + o.SetSelector(sel) + o.SetExpiresAt(timestamppb.New(time.Date(2027, 1, 26, 0, 0, 0, 0, time.UTC))) + + b, err := MarshalOverrideTemplate(o, "", DefaultLayer{}, nil) + require.NoError(t, err) + assert.Contains(t, string(b), "operator: In") + assert.Contains(t, string(b), "expires_at: 2027-01-26T00:00:00Z") + + got, err := UnmarshalOverride(b) + require.NoError(t, err) + assert.True(t, proto.Equal(o, got), "got %v", got) +} + +func TestEmptySelectorKeepsItsPresence(t *testing.T) { + o := &policyv1.Override{} + o.SetName("all") + o.SetPriority(1) + o.SetSelector(&messagescontroltowerv1.LabelSelector{}) + b, err := MarshalOverrideTemplate(o, "", DefaultLayer{}, nil) + require.NoError(t, err) + assert.Contains(t, string(b), "selector: {}") + + got, err := UnmarshalOverride(b) + require.NoError(t, err) + assert.True(t, got.HasSelector(), "selector: {} selects every subject and must stay set") +} + +func TestPruneEmpty(t *testing.T) { + emptyBase := &policyv1.Policy{} + emptyBase.SetBase(&specv1.PolicySpec{}) + emptyBase.GetBase().SetScanGate(&scangatev1.ScanGate{}) + + zeroCooldown := &policyv1.Policy{} + cooldownSpec := samplePolicy().GetBase() + cooldownSpec.GetPackageAdmission().GetCooldown().SetMinAge(durationpb.New(0)) + zeroCooldown.SetBase(cooldownSpec) + + everySubject := &policyv1.Policy{} + o := &policyv1.Override{} + o.SetName("all") + o.SetSelector(&messagescontroltowerv1.LabelSelector{}) + o.SetSpec(&specv1.PolicySpec{}) + everySubject.SetOverrides([]*policyv1.Override{o}) + + tests := []struct { + name string + in *policyv1.Policy + check func(t *testing.T, got *policyv1.Policy) + }{ + {"empty messages go", emptyBase, func(t *testing.T, got *policyv1.Policy) { + assert.False(t, got.HasBase()) + }}, + {"a zero duration stays", zeroCooldown, func(t *testing.T, got *policyv1.Policy) { + assert.True(t, got.GetBase().GetPackageAdmission().GetCooldown().HasMinAge(), "0s turns the cooldown off") + }}, + {"an empty selector stays", everySubject, func(t *testing.T, got *policyv1.Policy) { + assert.True(t, got.GetOverrides()[0].HasSelector(), "an empty selector selects every subject") + assert.False(t, got.GetOverrides()[0].HasSpec()) + }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + before := proto.Clone(tt.in) + got, ok := PruneEmpty(tt.in).(*policyv1.Policy) + require.True(t, ok) + tt.check(t, got) + assert.True(t, proto.Equal(before, tt.in), "PruneEmpty does not change its input") + }) + } +} diff --git a/internal/cmd/policy/edit_test.go b/internal/cmd/policy/edit_test.go index 29ff114..e19d8cc 100644 --- a/internal/cmd/policy/edit_test.go +++ b/internal/cmd/policy/edit_test.go @@ -373,45 +373,17 @@ func TestRunEdit_NewTenantDocument(t *testing.T) { _, err := runEdit(context.Background(), client, ed.open, "acme.safedep.io", editInput{}) require.ErrorIs(t, err, errNoChange, "a save of the template as it is changes nothing") - // docs/cmd/policy-edit.md shows this document. - want := `# Policy of acme.safedep.io · head revision 0 -# Saving creates a draft change. Nothing applies until you publish it. -# -# Layers, from low to high, for each subject: -# 1. SafeDep default policy (read-only, revision 1): -# scan_gate.fail_on: high · scan_gate.fail_on_attacks: fail -# 2. base - applies to every endpoint and project of this tenant -# 3. overrides - apply to the subjects that their selector matches. -# For each field, the highest priority that sets it wins. -# -# Keep the id of each override. A new override has no id. -# Package rules are not in this file: 0 rules (safedep policy rule list) -# The policy keeps no comments. Write the reason for a value in a description field. -# To set a field, remove the "# " at the start of its line and of the lines of its parents. -# Fields and values: https://docs.safedep.io/reference/cloud-policy-settings - -# base: - # package_admission: - # cooldown: - # min_age: 7d # a duration, as 7d or 12h, from 0s to 365d. Now: not set - # 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) - -# An example policy override. It applies to the subjects that its selector matches. -# Remove the "# " at the start of each line to use it, then change the values. -# overrides: -# - name: payments -# priority: 100 -# selector: -# matchLabels: {custom/team: payments} -# spec: -# package_admission: -# cooldown: -# min_age: 168h -` + // The template test in internal/cloudpolicy owns the body of the document. require.Len(t, ed.seen, 1) - assert.Equal(t, want, ed.seen[0]) + doc := ed.seen[0] + for _, want := range []string{ + "# Policy of acme.safedep.io · head revision 0\n", + "# 1. SafeDep default policy (read-only, revision 1):\n", + "# To set a field, remove the \"# \" at the start of its line and of the lines of its parents.\n", + "# Fields and values: https://docs.safedep.io/reference/cloud-policy-settings\n\n# base:\n", + } { + assert.Contains(t, doc, want) + } } func TestRunEdit_TemplateEdits(t *testing.T) { @@ -498,3 +470,94 @@ func TestRunEdit_TemplateOfATenantWithValuesIsNoChange(t *testing.T) { assert.Contains(t, ed.seen[0], " # fail_on_attacks: fail # report, fail. Now: fail (default policy, revision 1)\n") assert.NotContains(t, ed.seen[0], "An example policy override", "the policy has overrides") } + +func TestRunEdit_TemplateCases(t *testing.T) { + uncommentExample := func(s string) string { + i := strings.Index(s, "# overrides:") + return s[:i] + strings.ReplaceAll(s[i:], "\n# ", "\n")[len("# "):] + } + tests := []struct { + name string + head *policyv1.GetPolicyResponse + edits []func(string) string + check func(t *testing.T, err error, got *policyv1.Policy, seen []string) + }{ + { + name: "a parent key alone is no change", + head: newTenantResponse(), + edits: []func(string) string{uncomment("# base:", " # scan_gate:")}, + check: func(t *testing.T, err error, got *policyv1.Policy, _ []string) { + assert.ErrorIs(t, err, errNoChange) + assert.Nil(t, got, "no change request") + }, + }, + { + name: "a tenant with values that saves only comments gets the way to clear the policy", + head: headResponse(), + edits: []func(string) string{ + func(s string) string { + var kept []string + for _, line := range strings.Split(s, "\n") { + if strings.HasPrefix(strings.TrimSpace(line), "#") { + kept = append(kept, line) + } + } + return strings.Join(kept, "\n") + }, + keep, + }, + check: func(t *testing.T, err error, got *policyv1.Policy, seen []string) { + require.Error(t, err) + assert.Nil(t, got, "no change request") + require.Len(t, seen, 2) + assert.Contains(t, seen[1], "the file sets no field. To remove every setting, write {} on one line") + }, + }, + { + name: "a tenant with values removes a set field", + head: headResponse(), + edits: []func(string) string{replace("\n scan_gate:\n fail_on: high\n", "\n scan_gate:\n")}, + check: func(t *testing.T, err error, got *policyv1.Policy, _ []string) { + require.NoError(t, err) + require.NotNil(t, got) + assert.False(t, got.GetBase().GetScanGate().HasFailOn(), "the change clears the field") + assert.Len(t, got.GetOverrides(), 2, "the overrides stay") + }, + }, + { + name: "the example override, uncommented", + head: newTenantResponse(), + edits: []func(string) string{uncommentExample}, + check: func(t *testing.T, err error, got *policyv1.Policy, _ []string) { + require.NoError(t, err) + require.Len(t, got.GetOverrides(), 1) + o := got.GetOverrides()[0] + assert.Equal(t, "payments", o.GetName()) + assert.Equal(t, uint32(100), o.GetPriority()) + assert.NotEmpty(t, o.GetDescription()) + assert.Equal(t, map[string]string{"custom/team": "payments"}, o.GetSelector().GetMatchLabels()) + assert.Equal(t, 7*24*time.Hour, o.GetSpec().GetPackageAdmission().GetCooldown().GetMinAge().AsDuration()) + assert.Empty(t, o.GetOverrideId(), "the example is a new override") + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + captureStderr(t) + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(tt.head, nil) + var got *policyv1.Policy + client.EXPECT().CreatePolicyChange(mock.Anything, mock.Anything). + RunAndReturn(func(_ context.Context, r *policyv1.CreatePolicyChangeRequest, _ ...grpc.CallOption) (*policyv1.CreatePolicyChangeResponse, error) { + got = r.GetSettings() + res := &policyv1.CreatePolicyChangeResponse{} + res.SetChange(openChange("18")) + return res, nil + }).Maybe() + ed := &scriptedEditor{edits: tt.edits} + + _, err := runEdit(context.Background(), client, ed.open, "", editInput{}) + tt.check(t, err, got, ed.seen) + }) + } +} diff --git a/internal/cmd/policy/settings.go b/internal/cmd/policy/settings.go index 47ec53a..4a0ee1c 100644 --- a/internal/cmd/policy/settings.go +++ b/internal/cmd/policy/settings.go @@ -46,18 +46,32 @@ func defaultLayer(head *policyv1.GetPolicyResponse) cloudpolicy.DefaultLayer { } } +// errNoSettings is the error for a file with no field, of a policy with +// settings. It tells how to clear the policy on purpose. +var errNoSettings = errors.New("the file sets no field. To remove every setting, write {} on one line") + // decodeDocument reads a saved document. The template of a policy with no // settings has only comments, so a save of it as it is reads as that empty -// policy. A file with only comments for a policy with settings stays an -// error, so a person never clears the policy by accident. +// policy. A file with only comments for a policy with settings is an error, +// so a person never clears the policy by accident. func decodeDocument(saved []byte, start *policyv1.Policy) (*policyv1.Policy, error) { edited, err := cloudpolicy.UnmarshalPolicy(saved) - if errors.Is(err, cloudpolicy.ErrEmptyDocument) && proto.Size(start) == 0 { - return &policyv1.Policy{}, nil + if errors.Is(err, cloudpolicy.ErrEmptyDocument) { + if proto.Size(start) == 0 { + return &policyv1.Policy{}, nil + } + return nil, errNoSettings } return edited, err } +// sameSettings compares two documents with their empty messages pruned. A +// parent key that a person uncomments with no field below it is no change. +// A field that a person removes still is a change. +func sameSettings(a, b proto.Message) bool { + return proto.Equal(cloudpolicy.PruneEmpty(a), cloudpolicy.PruneEmpty(b)) +} + func editWholeDocument( ctx context.Context, open openEditorFunc, @@ -72,7 +86,7 @@ func editWholeDocument( } unchanged := func(saved []byte) bool { edited, err := decodeDocument(saved, start) - return err == nil && proto.Equal(edited, start) + return err == nil && sameSettings(edited, start) } return editLoop(ctx, open, text, unchanged, func(saved []byte) error { edited, err := decodeDocument(saved, start) @@ -106,7 +120,7 @@ func editOneOverride( } unchanged := func(saved []byte) bool { edited, err := cloudpolicy.UnmarshalOverride(saved) - return err == nil && proto.Equal(edited, current) + return err == nil && sameSettings(edited, current) } return editLoop(ctx, open, text, unchanged, func(saved []byte) error { edited, err := cloudpolicy.UnmarshalOverride(saved) From 5ccf75e89230dcf14687da03c7f6fd09484c3c73 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Thu, 5 Nov 2026 08:22:17 +0000 Subject: [PATCH 14/17] docs: write the help, warnings and errors of the policy commands in STE The owner found a flag help that joined two sentences with ";": "the publish message; the change title becomes the title when it is empty". A sweep of the text that this pull request adds found more: - 27 flag usages joined two ideas with ";". Each is now one phrase, as in "the publish message, or the title of the change when empty" and "a label as custom/KEY=VALUE (repeatable)". - An error joined two sentences with ";". It now uses two sentences. - Help, warnings and errors used the passive voice or jargon: "was not saved", "could not", "rebased", "never merges", "endpoints reporting". They now use the active voice and simple words. - The help of endpoint policy show said that a managed file locks a field, and the help of project policy show named a check that reports. Neither happens in this release. The help now says what the output shows. The behaviour, the JSON and plain output, and the contract tokens do not change. A test that asserts a changed error is updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MhRi597EX9odoSDXbVBsxz --- docs/cmd/endpoint-list.md | 2 +- docs/cmd/policy-change-sync.md | 4 ++-- internal/cmd/audit/list.go | 4 ++-- internal/cmd/endpoint/cmd.go | 2 +- internal/cmd/endpoint/label.go | 4 ++-- internal/cmd/endpoint/list.go | 8 ++++---- internal/cmd/endpoint/policy.go | 6 +++--- internal/cmd/policy/change_create.go | 5 +++-- internal/cmd/policy/change_list.go | 2 +- internal/cmd/policy/change_ops.go | 6 +++--- internal/cmd/policy/change_publish.go | 2 +- internal/cmd/policy/change_test.go | 2 +- internal/cmd/policy/decision_list.go | 2 +- internal/cmd/policy/editor.go | 6 +++--- internal/cmd/policy/get.go | 2 +- internal/cmd/policy/revision.go | 2 +- internal/cmd/policy/rule_create.go | 10 +++++----- internal/cmd/policy/rule_delete.go | 2 +- internal/cmd/policy/rule_list.go | 2 +- internal/cmd/policy/rule_update.go | 2 +- internal/cmd/policy/settings.go | 2 +- internal/cmd/project/cmd.go | 4 ++-- internal/cmd/project/inventory.go | 6 +++--- internal/cmd/project/label.go | 8 ++++---- internal/cmd/project/policy.go | 4 ++-- internal/cmd/project/resolver.go | 2 +- internal/cmd/project/show.go | 2 +- 27 files changed, 52 insertions(+), 51 deletions(-) diff --git a/docs/cmd/endpoint-list.md b/docs/cmd/endpoint-list.md index b8142f8..4ca970e 100644 --- a/docs/cmd/endpoint-list.md +++ b/docs/cmd/endpoint-list.md @@ -1,6 +1,6 @@ # safedep endpoint list -List endpoints reporting to SafeDep Cloud, with optional filters for capability, blocked installs, silent duration, identity search, labels, and the applied policy revision. +List the endpoints that report to SafeDep Cloud, with filters for capability, blocked installs, silent duration, identity search, labels and the applied policy revision. ## Synopsis diff --git a/docs/cmd/policy-change-sync.md b/docs/cmd/policy-change-sync.md index 230f87f..c83b933 100644 --- a/docs/cmd/policy-change-sync.md +++ b/docs/cmd/policy-change-sync.md @@ -1,7 +1,7 @@ # safedep policy change sync Move the base of an open policy change to the head revision. The change keeps its -settings as you wrote them. The server never merges, so review the change again +settings as you wrote them. The server does not merge. Review the change again before you publish it. ## Synopsis @@ -17,7 +17,7 @@ safedep policy change sync 19 ``` ``` -✓ change 19 rebased on revision 51 · review it: safedep policy change show 19 +✓ change 19 now has base revision 51 · review it: safedep policy change show 19 ``` Sync a change when its publish stops because the policy moved. diff --git a/internal/cmd/audit/list.go b/internal/cmd/audit/list.go index 69d9c17..179e48d 100644 --- a/internal/cmd/audit/list.go +++ b/internal/cmd/audit/list.go @@ -74,11 +74,11 @@ func eventListCmd(a *app.App) *cobra.Command { f := cmd.Flags() f.Var(duration.NewValue(&in.Since, 0), "since", "only events in this time before now, as in 7d or 12h") f.Var(duration.NewValue(&in.Until, 0), "until", "only events older than this time before now, as in 1d") - f.StringVar(&in.Action, "action", "", "only events whose action starts with this text; policy. lists the policy actions") + f.StringVar(&in.Action, "action", "", "only events whose action starts with this text, as in policy. for the policy actions") f.StringVar(&in.Resource, "resource", "", "only events about a resource: KIND (policy_change, package_rule, endpoint, project) or KIND/ID, as in policy_change/18") f.StringVar(&in.Actor, "actor", "", "only events of this actor id or display name, as in alice@acme.io") - f.Uint32Var(&in.PageSize, "limit", 0, "page size; server default when 0") + f.Uint32Var(&in.PageSize, "limit", 0, "page size, or the server default when 0") f.StringVar(&in.PageToken, "page-token", "", "continuation token from a prior response") return cmd } diff --git a/internal/cmd/endpoint/cmd.go b/internal/cmd/endpoint/cmd.go index 572da96..19b21c9 100644 --- a/internal/cmd/endpoint/cmd.go +++ b/internal/cmd/endpoint/cmd.go @@ -12,7 +12,7 @@ func Register(root *cobra.Command, a *app.App) { parent := &cobra.Command{ Use: "endpoint", Short: "Inspect endpoints reporting to SafeDep Cloud", - Long: "View fleet health, inspect individual endpoints, audit recent activity, inspect inventory, and manage the labels and policy of endpoints reporting to SafeDep Cloud (Endpoint Hub).", + Long: "View fleet health, inspect individual endpoints, audit recent activity, inspect inventory, and manage the labels and policy of the endpoints that report to SafeDep Cloud (Endpoint Hub).", } parent.AddCommand( statusCmd(a), diff --git a/internal/cmd/endpoint/label.go b/internal/cmd/endpoint/label.go index f8d7e3f..a199586 100644 --- a/internal/cmd/endpoint/label.go +++ b/internal/cmd/endpoint/label.go @@ -63,7 +63,7 @@ func labelSetCmd(a *app.App) *cobra.Command { return nil }, } - cmd.Flags().StringArrayVar(&labels, "label", nil, "a label as custom/KEY=VALUE; repeatable") + cmd.Flags().StringArrayVar(&labels, "label", nil, "a label as custom/KEY=VALUE (repeatable)") return cmd } @@ -97,7 +97,7 @@ func labelDeleteCmd(a *app.App) *cobra.Command { return nil }, } - cmd.Flags().StringArrayVar(&keys, "key", nil, "a label key as custom/KEY; repeatable") + cmd.Flags().StringArrayVar(&keys, "key", nil, "a label key as custom/KEY (repeatable)") return cmd } diff --git a/internal/cmd/endpoint/list.go b/internal/cmd/endpoint/list.go index 134d90e..0db75dd 100644 --- a/internal/cmd/endpoint/list.go +++ b/internal/cmd/endpoint/list.go @@ -53,10 +53,10 @@ func listCmd(a *app.App) *cobra.Command { cmd := &cobra.Command{ Use: "list", Short: "List endpoints with filters", - Long: "List endpoints reporting to SafeDep Cloud, with filters for capability, blocked installs, silent duration, identity search, " + - "labels, and the applied policy revision. --applied-revision '<48' keeps the endpoints where a tool applies a policy " + - "revision lower than 48, so you can see which endpoints have not applied a publish yet. The POLICY column shows the " + - "applied policy revision that each tool reported.", + Long: "List the endpoints that report to SafeDep Cloud, with filters for capability, blocked installs, silent duration, " + + "identity search, labels and the applied policy revision. --applied-revision '<48' keeps the endpoints where a tool " + + "applies a policy revision lower than 48. Use it to find the endpoints that have not applied a publish yet. The " + + "Policy column shows the applied policy revision that each tool reported.", RunE: func(cmd *cobra.Command, _ []string) error { selector, applied, err := parsePolicyFilters(selectorFlag, appliedFlag) if err != nil { diff --git a/internal/cmd/endpoint/policy.go b/internal/cmd/endpoint/policy.go index 08e229b..0d8b1c7 100644 --- a/internal/cmd/endpoint/policy.go +++ b/internal/cmd/endpoint/policy.go @@ -31,8 +31,8 @@ func policyShowCmd(a *app.App) *cobra.Command { Short: "Show the policy of an endpoint and the source of each value", Long: "Show the intended policy of one endpoint: each field, its value, and its source, which is " + "the SafeDep default policy, the policy base, or a policy override. The output also shows the " + - "applied policy revision and the exceptions that each tool reported, such as a field that a " + - "managed file locks. Use --field to show some fields only.", + "applied policy revision that each tool reported, and the fields that a tool did not apply " + + "as the policy says. Use --field to show some fields only.", Args: func(cmd *cobra.Command, args []string) error { if err := cobra.ExactArgs(1)(cmd, args); err != nil { return err @@ -55,7 +55,7 @@ func policyShowCmd(a *app.App) *cobra.Command { return a.Output.Print(res) }, } - cmd.Flags().StringSliceVar(&fields, "field", nil, "show only these contract paths, as in package_admission.cooldown.min_age; repeatable") + cmd.Flags().StringSliceVar(&fields, "field", nil, "show only this contract path and the paths below it, as in package_admission.cooldown.min_age (repeatable)") return cmd } diff --git a/internal/cmd/policy/change_create.go b/internal/cmd/policy/change_create.go index 3fbf440..ab28d24 100644 --- a/internal/cmd/policy/change_create.go +++ b/internal/cmd/policy/change_create.go @@ -66,7 +66,8 @@ func changeCreateCmd(a *app.App) *cobra.Command { f := cmd.Flags() f.Uint64Var(&in.FromRevision, "from-revision", 0, "the policy revision to restore from (required)") f.StringSliceVar(&in.Capabilities, "capability", nil, - "a capability to restore ("+strings.Join(cloudpolicy.Capabilities(), ", ")+"); repeatable; every capability when absent") + "a capability to restore, one of "+strings.Join(cloudpolicy.Capabilities(), ", ")+ + " (repeatable, every capability when not set)") f.StringVar(&in.PackageRules, "package-rules", packageRulesKeepHead, "the package rules after the restore: head keeps them, revision restores the set of --from-revision") f.StringVarP(&in.Title, "message", "m", "", "the title of the policy change") @@ -131,7 +132,7 @@ func runChangeCreate( func reportRestoreDirection(ctx context.Context, client policyv1grpc.PolicyServiceClient, id string) { preview, err := previewChange(ctx, client, id) if err != nil { - tui.Warning("Could not preview change %s: %s", clitui.EscapeLine(id), clitui.EscapeLine(err.Error())) + tui.Warning("Cannot preview change %s: %s", clitui.EscapeLine(id), clitui.EscapeLine(err.Error())) return } reportLoosening(preview) diff --git a/internal/cmd/policy/change_list.go b/internal/cmd/policy/change_list.go index c999f81..74419d0 100644 --- a/internal/cmd/policy/change_list.go +++ b/internal/cmd/policy/change_list.go @@ -57,7 +57,7 @@ func changeListCmd(a *app.App) *cobra.Command { } f := cmd.Flags() f.StringVar(&in.State, "state", "", "filter: change state ("+strings.Join(changeStateTokens(), ", ")+")") - f.Uint32Var(&in.PageSize, "limit", 0, "page size; server default when 0") + f.Uint32Var(&in.PageSize, "limit", 0, "page size, or the server default when 0") f.StringVar(&in.PageToken, "page-token", "", "continuation token from a prior response") return cmd } diff --git a/internal/cmd/policy/change_ops.go b/internal/cmd/policy/change_ops.go index c5965e7..1c7c52c 100644 --- a/internal/cmd/policy/change_ops.go +++ b/internal/cmd/policy/change_ops.go @@ -20,7 +20,7 @@ func requireOpen(change *policyv1.PolicyChange) error { } view := newChangeView(change) return invalidInputError( - fmt.Errorf("change %s is %s: only an open change can change", view.ID, view.State), + fmt.Errorf("change %s is %s: you can change only an open change", view.ID, view.State), "List the open changes: safedep policy change list --state open") } @@ -29,7 +29,7 @@ func changeSyncCmd(a *app.App) *cobra.Command { Use: "sync CHANGE", Short: "Move the base of a policy change to the head revision", Long: "Move the base of an open policy change to the head revision. The change keeps its settings " + - "as you wrote them. The server never merges, so review the change again before you publish: " + + "as you wrote them. The server does not merge. Review the change again before you publish it: " + "the preview shows every difference against head.", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { @@ -42,7 +42,7 @@ func changeSyncCmd(a *app.App) *cobra.Command { return err } id := clitui.EscapeLine(change.GetChangeId()) - tui.Success("change %s rebased on revision %d%sreview it: safedep policy change show %s", + tui.Success("change %s now has base revision %d%sreview it: safedep policy change show %s", id, change.GetBaseRevision(), sep, id) return nil }, diff --git a/internal/cmd/policy/change_publish.go b/internal/cmd/policy/change_publish.go index 0d29c63..f36e8c3 100644 --- a/internal/cmd/policy/change_publish.go +++ b/internal/cmd/policy/change_publish.go @@ -58,7 +58,7 @@ func changePublishCmd(a *app.App) *cobra.Command { return nil }, } - cmd.Flags().StringVarP(&message, "message", "m", "", "the publish message; the change title becomes the title when it is empty") + cmd.Flags().StringVarP(&message, "message", "m", "", "the publish message, or the title of the change when empty") cmd.Flags().BoolVarP(&yes, "yes", "y", false, "publish a change that loosens the policy with no prompt") return cmd } diff --git a/internal/cmd/policy/change_test.go b/internal/cmd/policy/change_test.go index c2fa438..9b8d7cf 100644 --- a/internal/cmd/policy/change_test.go +++ b/internal/cmd/policy/change_test.go @@ -239,7 +239,7 @@ func TestRunChangePublish_OnlyAnOpenChange(t *testing.T) { client.EXPECT().GetPolicyChange(mock.Anything, mock.Anything).Return(changeResponse(c), nil) _, err := runChangePublish(context.Background(), client, "17", "", refuseConfirm(t)) - assert.ErrorContains(t, err, "change 17 is deleted: only an open change can change") + assert.ErrorContains(t, err, "change 17 is deleted: you can change only an open change") } func TestRunChangeGet_NotFound(t *testing.T) { diff --git a/internal/cmd/policy/decision_list.go b/internal/cmd/policy/decision_list.go index e7d9206..84e66b6 100644 --- a/internal/cmd/policy/decision_list.go +++ b/internal/cmd/policy/decision_list.go @@ -106,7 +106,7 @@ func decisionListCmd(a *app.App) *cobra.Command { f.StringVar(&in.Package, "package", "", "filter: decisions about this package in all its versions, as in pkg:npm/lodash") f.StringVar(&in.Project, "project", "", "filter: decisions at a repository that is bound to this project id") f.StringVar(&in.Endpoint, "endpoint", "", "filter: decisions that pmg made on this endpoint id") - f.Uint32Var(&in.PageSize, "limit", 0, "page size; server default when 0") + f.Uint32Var(&in.PageSize, "limit", 0, "page size, or the server default when 0") f.StringVar(&in.PageToken, "page-token", "", "continuation token from a prior response") return cmd } diff --git a/internal/cmd/policy/editor.go b/internal/cmd/policy/editor.go index 17ce5f6..b022ec2 100644 --- a/internal/cmd/policy/editor.go +++ b/internal/cmd/policy/editor.go @@ -90,7 +90,7 @@ func editLoop( err = save(saved) if err == nil { if rmErr := os.Remove(path); rmErr != nil { - tui.Warning("could not remove the temporary file %s: %v", path, rmErr) + tui.Warning("cannot remove the temporary file %s: %v", path, rmErr) } return nil } @@ -130,9 +130,9 @@ func stripErrorLines(text []byte) []byte { // error, such as the one for a role that cannot change the policy, and adds // the path of the kept file. func keptEditError(path string, cause error) error { - code, human, help := usefulerror.ErrBadRequest, "The policy edit was not saved: "+cause.Error(), "" + code, human, help := usefulerror.ErrBadRequest, "The command did not save the policy edit: "+cause.Error(), "" if ue, ok := usefulerror.AsUsefulError(cause); ok { - code, human = ue.Code(), "The policy edit was not saved: "+ue.HumanError() + code, human = ue.Code(), "The command did not save the policy edit: "+ue.HumanError() if ue.Help() != "" { help = ue.Help() + ". " } diff --git a/internal/cmd/policy/get.go b/internal/cmd/policy/get.go index 28dc77a..6c0ed1f 100644 --- a/internal/cmd/policy/get.go +++ b/internal/cmd/policy/get.go @@ -49,7 +49,7 @@ func getCmd(a *app.App) *cobra.Command { return a.Output.Print(res) }, } - cmd.Flags().Uint64Var(&in.Revision, "revision", 0, "the policy revision to write; the head revision when 0") + cmd.Flags().Uint64Var(&in.Revision, "revision", 0, "the policy revision to write, or the head revision when 0") return cmd } diff --git a/internal/cmd/policy/revision.go b/internal/cmd/policy/revision.go index 846b8a0..46abedb 100644 --- a/internal/cmd/policy/revision.go +++ b/internal/cmd/policy/revision.go @@ -49,7 +49,7 @@ func revisionListCmd(a *app.App) *cobra.Command { return a.Output.Print(res) }, } - cmd.Flags().Uint32Var(&in.PageSize, "limit", 0, "page size; server default when 0") + cmd.Flags().Uint32Var(&in.PageSize, "limit", 0, "page size, or the server default when 0") cmd.Flags().StringVar(&in.PageToken, "page-token", "", "continuation token from a prior response") return cmd } diff --git a/internal/cmd/policy/rule_create.go b/internal/cmd/policy/rule_create.go index 8a8e871..6724420 100644 --- a/internal/cmd/policy/rule_create.go +++ b/internal/cmd/policy/rule_create.go @@ -85,16 +85,16 @@ func ruleCreateCmd(a *app.App) *cobra.Command { f := cmd.Flags() f.BoolVar(&in.Block, "block", false, "create block entries") f.BoolVar(&in.Trust, "trust", false, "create a trust entry") - f.StringVarP(&in.File, "file", "f", "", "with --block: a file of selectors, one on each line; - reads stdin") + 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: the verdicts to waive ("+strings.Join(trustScopeTokens(), ", ")+", or all); repeatable") - f.StringVar(&in.Reason, "reason", "", "why the rule exists (required); tools show it in a block message") + "with --trust: a verdict to waive, one of "+strings.Join(trustScopeTokens(), ", ")+", or all (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") f.StringVar(&in.Expires, "expires", "", "when the rule stops: a duration, as in 30d, or a date (required with --trust)") - f.StringVar(&in.Override, "override", "", "attach the rule to the policy override with this name; the policy base when empty") - f.StringVarP(&in.Message, "message", "m", "", "the publish message; the server writes one when it is empty") + f.StringVar(&in.Override, "override", "", "the policy override that the rule attaches to, or the policy base when empty") + f.StringVarP(&in.Message, "message", "m", "", "the publish message, or a message that the server writes when empty") return cmd } diff --git a/internal/cmd/policy/rule_delete.go b/internal/cmd/policy/rule_delete.go index 420effe..f3dba42 100644 --- a/internal/cmd/policy/rule_delete.go +++ b/internal/cmd/policy/rule_delete.go @@ -45,7 +45,7 @@ func ruleDeleteCmd(a *app.App) *cobra.Command { }, } cmd.Flags().StringVar(&reason, "reason", "", "why the rule goes (required)") - cmd.Flags().StringVarP(&message, "message", "m", "", "the publish message; the server writes one when it is empty") + cmd.Flags().StringVarP(&message, "message", "m", "", "the publish message, or a message that the server writes when empty") return cmd } diff --git a/internal/cmd/policy/rule_list.go b/internal/cmd/policy/rule_list.go index b7d59ec..546584f 100644 --- a/internal/cmd/policy/rule_list.go +++ b/internal/cmd/policy/rule_list.go @@ -73,7 +73,7 @@ func ruleListCmd(a *app.App) *cobra.Command { f.StringVar(&in.Override, "override", "", "filter: rules that attach to the policy override with this name") f.BoolVar(&in.Base, "base", false, "filter: rules that attach to the policy base") f.Uint64Var(&in.AtRevision, "at-revision", 0, "list the rules that were active at this policy revision") - f.Uint32Var(&in.PageSize, "limit", 0, "page size; server default when 0") + f.Uint32Var(&in.PageSize, "limit", 0, "page size, or the server default when 0") f.StringVar(&in.PageToken, "page-token", "", "continuation token from a prior response") return cmd } diff --git a/internal/cmd/policy/rule_update.go b/internal/cmd/policy/rule_update.go index d67ba6e..4986504 100644 --- a/internal/cmd/policy/rule_update.go +++ b/internal/cmd/policy/rule_update.go @@ -65,7 +65,7 @@ func ruleUpdateCmd(a *app.App) *cobra.Command { f.StringVar(&in.Expires, "expires", "", "the new expiry: a duration from now, as in 90d, or a date") f.StringVar(&in.Ticket, "ticket", "", "the new ticket or incident reference") f.StringVar(&in.RequestedBy, "requested-by", "", "the new team or person that asked for the rule") - f.StringVarP(&in.Message, "message", "m", "", "the publish message; the server writes one when it is empty") + f.StringVarP(&in.Message, "message", "m", "", "the publish message, or a message that the server writes when empty") return cmd } diff --git a/internal/cmd/policy/settings.go b/internal/cmd/policy/settings.go index 4a0ee1c..a2275b4 100644 --- a/internal/cmd/policy/settings.go +++ b/internal/cmd/policy/settings.go @@ -224,7 +224,7 @@ func validateSettings(p *policyv1.Policy) error { func warnComments(saved, written []byte) { if cloudpolicy.HasUserComments(saved, written) { - tui.Warning("The file holds comments. The policy keeps no comments, so they are lost. " + + tui.Warning("The file holds comments. The policy keeps no comments, so the save drops them. " + "Write the reason in a description field") } } diff --git a/internal/cmd/project/cmd.go b/internal/cmd/project/cmd.go index 9e521c4..858264d 100644 --- a/internal/cmd/project/cmd.go +++ b/internal/cmd/project/cmd.go @@ -10,8 +10,8 @@ func Register(root *cobra.Command, a *app.App) { parent := &cobra.Command{ Use: "project", Short: "Work with SafeDep projects", - Long: "Work with SafeDep projects, including syncing them from linked source code hosts, " + - "their labels and policy, and scans performed by SafeDep Cloud-hosted scanners.", + Long: "Work with SafeDep projects: sync them from linked source code hosts, manage their labels " + + "and policy, and run scans with the scanners of SafeDep Cloud.", } scan := &cobra.Command{ Use: "scan", diff --git a/internal/cmd/project/inventory.go b/internal/cmd/project/inventory.go index f049109..4b2a7b5 100644 --- a/internal/cmd/project/inventory.go +++ b/internal/cmd/project/inventory.go @@ -69,10 +69,10 @@ func projectListCmd(a *app.App) *cobra.Command { f := cmd.Flags() f.StringVar(&in.Selector, "selector", "", "filter: a label selector, as in custom/criticality=high,scm/forge=github") f.StringArrayVar(&in.Sources, "source", nil, - "filter: project source ("+strings.Join(projectSourceTokens(), ", ")+"); repeatable") + "filter: project source, one of "+strings.Join(projectSourceTokens(), ", ")+" (repeatable)") f.StringArrayVar(&in.Names, "name", nil, - fmt.Sprintf("filter: exact project name; repeat for up to %d names", maxScanFilterValues)) - f.Uint32Var(&in.PageSize, "limit", 0, "page size; server default when 0") + fmt.Sprintf("filter: exact project name (repeat for up to %d names)", maxScanFilterValues)) + f.Uint32Var(&in.PageSize, "limit", 0, "page size, or the server default when 0") f.StringVar(&in.PageToken, "page-token", "", "continuation token from a prior response") return cmd } diff --git a/internal/cmd/project/label.go b/internal/cmd/project/label.go index 0ed6a3e..6c7cd07 100644 --- a/internal/cmd/project/label.go +++ b/internal/cmd/project/label.go @@ -64,8 +64,8 @@ func labelSetCmd(a *app.App) *cobra.Command { return nil }, } - cmd.Flags().StringArrayVar(&in.Labels, "label", nil, "a label as custom/KEY=VALUE; repeatable") - cmd.Flags().StringArrayVar(&in.ProjectIDs, "project-id", nil, "a project ID instead of a name; repeatable") + cmd.Flags().StringArrayVar(&in.Labels, "label", nil, "a label as custom/KEY=VALUE (repeatable)") + cmd.Flags().StringArrayVar(&in.ProjectIDs, "project-id", nil, "a project ID instead of a name (repeatable)") return cmd } @@ -98,8 +98,8 @@ func labelDeleteCmd(a *app.App) *cobra.Command { return nil }, } - cmd.Flags().StringArrayVar(&in.Keys, "key", nil, "a label key as custom/KEY; repeatable") - cmd.Flags().StringArrayVar(&in.ProjectIDs, "project-id", nil, "a project ID instead of a name; repeatable") + cmd.Flags().StringArrayVar(&in.Keys, "key", nil, "a label key as custom/KEY (repeatable)") + cmd.Flags().StringArrayVar(&in.ProjectIDs, "project-id", nil, "a project ID instead of a name (repeatable)") return cmd } diff --git a/internal/cmd/project/policy.go b/internal/cmd/project/policy.go index a7d3cad..03d709b 100644 --- a/internal/cmd/project/policy.go +++ b/internal/cmd/project/policy.go @@ -34,7 +34,7 @@ func policyShowCmd(a *app.App) *cobra.Command { Short: "Show the policy of a project and the source of each value", Long: "Show the intended policy of one project: each field, its value, and its source, which is " + "the SafeDep default policy, the policy base, or a policy override. The output also shows the " + - "exceptions and the applied policy revision that each tool or check reported. Use --field to " + + "applied policy revision that each tool reported. Use --field to " + "show some fields only.", Args: func(cmd *cobra.Command, args []string) error { if err := cobra.MaximumNArgs(1)(cmd, args); err != nil { @@ -63,7 +63,7 @@ func policyShowCmd(a *app.App) *cobra.Command { }, } cmd.Flags().StringVar(&in.ProjectID, "project-id", "", "the project ID instead of a name") - cmd.Flags().StringSliceVar(&in.Fields, "field", nil, "show only these contract paths, as in scan_gate.fail_on; repeatable") + cmd.Flags().StringSliceVar(&in.Fields, "field", nil, "show only this contract path and the paths below it, as in scan_gate.fail_on (repeatable)") return cmd } diff --git a/internal/cmd/project/resolver.go b/internal/cmd/project/resolver.go index 6ccf4f1..c77cbaa 100644 --- a/internal/cmd/project/resolver.go +++ b/internal/cmd/project/resolver.go @@ -203,7 +203,7 @@ func ambiguousProjectNameError(op, name string, byID map[string]projectMatch) er labels = append(labels, fmt.Sprintf("%s (%s)", item.id, details)) } cause := fmt.Errorf( - "%s: project name %q is ambiguous: %s; use a project ID", + "%s: project name %q is ambiguous: %s. Use a project ID", op, name, strings.Join(labels, ", "), diff --git a/internal/cmd/project/show.go b/internal/cmd/project/show.go index f96a3bc..b69a295 100644 --- a/internal/cmd/project/show.go +++ b/internal/cmd/project/show.go @@ -97,7 +97,7 @@ func runShow( if err != nil { // The project data is still useful when the policy service does not // answer, so the command warns and shows the rest. - tui.Warning("Could not read the policy of project %s: %s", clitui.EscapeLine(name), clitui.EscapeLine(err.Error())) + tui.Warning("Cannot read the policy of project %s: %s", clitui.EscapeLine(name), clitui.EscapeLine(err.Error())) return out, nil } out.Policy = policy From 13db8a6db20e79eaf9ec1dd64fdcec8eb8e520ab Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Thu, 5 Nov 2026 08:24:34 +0000 Subject: [PATCH 15/17] fix(policy): name each override change in a plain sentence The owner published a change that adds a policy override and got: "It loosens added (- -> policy-test) in override "policy-test"". The CLI wrote every override change in the form "<kind> (<old> -> <new>)", and that form does not read well for an added or a removed override. Each kind of override change now has its own sentence in the publish warning, as in "It adds policy override "policy-test"." and "It changes the selector of policy override "payments" from custom/team=pay to custom/criticality=high.". In the table of policy change show, an added or removed override shows "new policy override" or "removed policy override", and an expiry shows "none" when there is none. The JSON and plain output keep the values of the server. The --limit help of packages list, project scan list and the endpoint list commands now has the same form as the other commands: "page size, or the server default when 0". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MhRi597EX9odoSDXbVBsxz --- docs/cmd/policy-change-publish.md | 2 +- internal/cmd/endpoint/activity.go | 2 +- internal/cmd/endpoint/inventory.go | 2 +- internal/cmd/endpoint/list.go | 2 +- internal/cmd/packages/list.go | 2 +- internal/cmd/policy/change_preview.go | 96 ++++++++++++++++++++++++--- internal/cmd/policy/change_publish.go | 4 ++ internal/cmd/policy/change_show.go | 2 +- internal/cmd/policy/change_test.go | 60 +++++++++++++++++ internal/cmd/policy/publish_test.go | 2 +- internal/cmd/project/list.go | 2 +- 11 files changed, 158 insertions(+), 18 deletions(-) diff --git a/docs/cmd/policy-change-publish.md b/docs/cmd/policy-change-publish.md index 0e98030..4894a08 100644 --- a/docs/cmd/policy-change-publish.md +++ b/docs/cmd/policy-change-publish.md @@ -29,7 +29,7 @@ safedep policy change publish 18 -m "payments: fail on medium, 7d cooldown (CUST ``` Change 18 · LOOSENS. Only an Admin can publish it, and Admins and Owners get a notice ! It loosens package_admission.cooldown.min_age (- -> 7d) in override "payments" -! It loosens selector (custom/team=pay -> custom/criticality=high) in override "payments" +! It changes the selector of policy override "payments" from custom/team=pay to custom/criticality=high. Change 18 loosens the policy. Publish it? [y/N]: y ✓ revision 47 published · LOOSENS Projects resolve it at their next check. Endpoints apply it after their next policy fetch diff --git a/internal/cmd/endpoint/activity.go b/internal/cmd/endpoint/activity.go index 64ca865..1fdda56 100644 --- a/internal/cmd/endpoint/activity.go +++ b/internal/cmd/endpoint/activity.go @@ -102,7 +102,7 @@ func activityListCmd(a *app.App) *cobra.Command { f.StringSliceVar(&actionsRaw, "action", nil, "guard-only action filter: blocked|confirmed|trusted|cooldown-blocked. Setting this implies --type=guard unless --type is set explicitly.") f.StringVar(&toolFlag, "tool", "", "client-side filter by tool_name") f.StringVar(&invFlag, "invocation", "", "scope to a single tool run; pass an invocation_id from JSON output") - f.Uint32Var(&pageSize, "limit", 0, "page size; server default when 0") + f.Uint32Var(&pageSize, "limit", 0, "page size, or the server default when 0") f.StringVar(&pageTokenFlag, "page-token", "", "continuation token from a prior response") return cmd } diff --git a/internal/cmd/endpoint/inventory.go b/internal/cmd/endpoint/inventory.go index 363cf5e..eb02fe2 100644 --- a/internal/cmd/endpoint/inventory.go +++ b/internal/cmd/endpoint/inventory.go @@ -151,7 +151,7 @@ func inventoryListCmd(a *app.App) *cobra.Command { f.StringSliceVar(&kindsRaw, "kind", nil, "filter by inventory kind (mcp-server|coding-agent|ai-extension|cli-tool|project-config|browser-extension|ide-extension|agent-plugin|agent-skill); repeatable") f.StringVar(&scopeFlag, "scope", "", "filter by scope: system|project") f.BoolVar(&allPagesFlag, "all", false, "fetch all pages before dedupe for a complete snapshot") - f.Uint32Var(&pageSize, "limit", 0, "page size; server default when 0") + f.Uint32Var(&pageSize, "limit", 0, "page size, or the server default when 0") f.StringVar(&pageTokenFlag, "page-token", "", "continuation token from a prior response") return cmd } diff --git a/internal/cmd/endpoint/list.go b/internal/cmd/endpoint/list.go index 0db75dd..30a46a8 100644 --- a/internal/cmd/endpoint/list.go +++ b/internal/cmd/endpoint/list.go @@ -96,7 +96,7 @@ func listCmd(a *app.App) *cobra.Command { f.StringVar(&searchFlag, "search", "", "case-insensitive substring match on hostname/name (client-side; best-effort within --limit)") f.StringVar(&selectorFlag, "selector", "", "filter: a label selector, as in reported/os=darwin,custom/team=release") f.StringVar(&appliedFlag, "applied-revision", "", "filter: '<N' keeps endpoints where a tool applies a policy revision lower than N, as in '<48'") - f.Uint32Var(&pageSize, "limit", 0, "page size; server default when 0") + f.Uint32Var(&pageSize, "limit", 0, "page size, or the server default when 0") f.StringVar(&pageTokenFlag, "page-token", "", "continuation token from a prior response") return cmd } diff --git a/internal/cmd/packages/list.go b/internal/cmd/packages/list.go index 9c04a90..7567979 100644 --- a/internal/cmd/packages/list.go +++ b/internal/cmd/packages/list.go @@ -49,7 +49,7 @@ func listCmd(a *app.App) *cobra.Command { f.StringVar(&flags.Ecosystem, "ecosystem", "", "filter: package ecosystem (requires --name and --version)") f.StringVar(&flags.Name, "name", "", "filter: package name") f.StringVar(&flags.Version, "version", "", "filter: package version") - f.Uint32Var(&pageSize, "limit", 0, "page size; server default when 0") + f.Uint32Var(&pageSize, "limit", 0, "page size, or the server default when 0") f.StringVar(&pageToken, "page-token", "", "continuation token from a prior response") return cmd } diff --git a/internal/cmd/policy/change_preview.go b/internal/cmd/policy/change_preview.go index 44b31c9..2387fa2 100644 --- a/internal/cmd/policy/change_preview.go +++ b/internal/cmd/policy/change_preview.go @@ -1,8 +1,10 @@ package policy import ( + "encoding/json" "fmt" "strings" + "time" messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" recordv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/record/v1" @@ -26,6 +28,29 @@ type changeItem struct { Direction string `json:"direction"` oldHuman string newHuman string + // whatHuman and changeHuman replace What and "old -> new" in the table + // when a plain value reads badly, as for an added override. + whatHuman string + changeHuman string + // sentence names the change for the publish warning. Empty means the + // generic form. + sentence string +} + +// whatCell is the WHAT cell of the table. +func (it changeItem) whatCell() string { + if it.whatHuman != "" { + return it.whatHuman + } + return it.What +} + +// changeCell is the OLD -> NEW cell of the table. +func (it changeItem) changeCell() string { + if it.changeHuman != "" { + return it.changeHuman + } + return it.oldHuman + " -> " + it.newHuman } type coverageView struct { @@ -78,15 +103,7 @@ func newPreviewView(res *policyv1.PreviewPolicyChangeResponse) *previewView { }) } for _, c := range res.GetOverrideChanges() { - v.Items = append(v.Items, changeItem{ - Where: fmt.Sprintf("override %q", c.GetOverrideName()), - What: tui.EnumToken(c.GetKind().String(), overrideKindPrefix), - Old: c.GetOldValue(), - New: c.GetNewValue(), - Direction: directionToken(c.GetDirection()), - oldHuman: overrideChangeValue(c.GetKind(), c.GetOldValue()), - newHuman: overrideChangeValue(c.GetKind(), c.GetNewValue()), - }) + v.Items = append(v.Items, overrideChangeItem(c)) } for _, op := range res.GetPackageRuleOperations() { item := ruleOperationItem(op.GetOperation()) @@ -124,7 +141,10 @@ func newPreviewView(res *policyv1.PreviewPolicyChangeResponse) *previewView { // custom/criticality=high. A value that does not parse stays as the server // wrote it. func overrideChangeValue(kind policyv1.OverrideChangeKind, value string) string { - if kind != policyv1.OverrideChangeKind_OVERRIDE_CHANGE_KIND_SELECTOR || value == "" { + switch { + case kind == policyv1.OverrideChangeKind_OVERRIDE_CHANGE_KIND_EXPIRY: + return expiryValue(value) + case kind != policyv1.OverrideChangeKind_OVERRIDE_CHANGE_KIND_SELECTOR || value == "": return cloudpolicy.EmptyDash(value) } selector := &messagescontroltowerv1.LabelSelector{} @@ -134,6 +154,62 @@ func overrideChangeValue(kind policyv1.OverrideChangeKind, value string) string return cloudpolicy.FormatSelector(selector) } +// expiryValue reads an expiry that the server writes as a protojson time, +// as "2027-01-26T00:00:00Z" with its quotes. No expiry is "none". +func expiryValue(value string) string { + if value == "" { + return "none" + } + var text string + if err := json.Unmarshal([]byte(value), &text); err != nil { + return value + } + t, err := time.Parse(time.RFC3339Nano, text) + if err != nil { + return text + } + return t.UTC().Format(time.RFC3339Nano) +} + +// overrideChangeItem turns one change to a policy override into a row. Each +// kind gets its own sentence for the publish warning. An added or removed +// override has no old and new values to show, so its row says what happens. +func overrideChangeItem(c *policyv1.OverrideChange) changeItem { + kind := c.GetKind() + item := changeItem{ + Where: fmt.Sprintf("override %q", c.GetOverrideName()), + What: tui.EnumToken(kind.String(), overrideKindPrefix), + Old: c.GetOldValue(), + New: c.GetNewValue(), + Direction: directionToken(c.GetDirection()), + oldHuman: overrideChangeValue(kind, c.GetOldValue()), + newHuman: overrideChangeValue(kind, c.GetNewValue()), + } + name := c.GetOverrideName() + changes := func(what string) string { + return fmt.Sprintf("It changes the %s of policy override %q from %s to %s.", what, name, item.oldHuman, item.newHuman) + } + switch kind { + case policyv1.OverrideChangeKind_OVERRIDE_CHANGE_KIND_ADDED: + item.whatHuman, item.changeHuman = "new policy override", "-" + item.sentence = fmt.Sprintf("It adds policy override %q.", name) + case policyv1.OverrideChangeKind_OVERRIDE_CHANGE_KIND_REMOVED: + item.whatHuman, item.changeHuman = "removed policy override", "-" + item.sentence = fmt.Sprintf("It removes policy override %q.", name) + case policyv1.OverrideChangeKind_OVERRIDE_CHANGE_KIND_SELECTOR: + item.sentence = changes("selector") + case policyv1.OverrideChangeKind_OVERRIDE_CHANGE_KIND_PRIORITY: + item.sentence = changes("priority") + case policyv1.OverrideChangeKind_OVERRIDE_CHANGE_KIND_EXPIRY: + item.sentence = changes("expiry") + case policyv1.OverrideChangeKind_OVERRIDE_CHANGE_KIND_NAME: + item.sentence = fmt.Sprintf("It renames policy override %q to %q.", item.oldHuman, item.newHuman) + case policyv1.OverrideChangeKind_OVERRIDE_CHANGE_KIND_DESCRIPTION: + item.sentence = fmt.Sprintf("It changes the description of policy override %q.", name) + } + return item +} + func ruleOperationItems(ops []*policyv1.PackageRuleOperation) []changeItem { out := make([]changeItem, 0, len(ops)) for _, op := range ops { diff --git a/internal/cmd/policy/change_publish.go b/internal/cmd/policy/change_publish.go index f36e8c3..4243886 100644 --- a/internal/cmd/policy/change_publish.go +++ b/internal/cmd/policy/change_publish.go @@ -149,6 +149,10 @@ func reportLoosening(p *previewView) { if item.Direction != directionLoosens { continue } + if item.sentence != "" { + tui.Warning("%s", clitui.EscapeLine(item.sentence)) + continue + } tui.Warning("It loosens %s (%s -> %s) in %s", clitui.EscapeLine(item.What), clitui.EscapeLine(item.oldHuman), clitui.EscapeLine(item.newHuman), clitui.EscapeLine(item.Where)) } diff --git a/internal/cmd/policy/change_show.go b/internal/cmd/policy/change_show.go index 59714d8..e983c98 100644 --- a/internal/cmd/policy/change_show.go +++ b/internal/cmd/policy/change_show.go @@ -147,7 +147,7 @@ func (r *changeShowResult) RenderTable() string { } rows := make([][]string, 0, len(items)) for _, it := range items { - rows = append(rows, []string{it.Where, it.What, it.oldHuman + " -> " + it.newHuman, cloudpolicy.EmptyDash(it.Direction)}) + rows = append(rows, []string{it.Where, it.whatCell(), it.changeCell(), cloudpolicy.EmptyDash(it.Direction)}) } sections = append(sections, table.New(). Title("What changes"). diff --git a/internal/cmd/policy/change_test.go b/internal/cmd/policy/change_test.go index 9b8d7cf..bd89269 100644 --- a/internal/cmd/policy/change_test.go +++ b/internal/cmd/policy/change_test.go @@ -342,3 +342,63 @@ func TestOverrideChangeValue(t *testing.T) { }) } } + +func TestOverrideChangeItem(t *testing.T) { + change := func(kind policyv1.OverrideChangeKind, old, new string) *policyv1.OverrideChange { + c := &policyv1.OverrideChange{} + c.SetOverrideName("payments") + c.SetKind(kind) + c.SetOldValue(old) + c.SetNewValue(new) + c.SetDirection(policyv1.ChangeDirection_CHANGE_DIRECTION_LOOSENS) + return c + } + tests := []struct { + name string + change *policyv1.OverrideChange + what string + cell string + sentence string + }{ + {"added", change(policyv1.OverrideChangeKind_OVERRIDE_CHANGE_KIND_ADDED, "", "payments"), + "new policy override", "-", `It adds policy override "payments".`}, + {"removed", change(policyv1.OverrideChangeKind_OVERRIDE_CHANGE_KIND_REMOVED, "payments", ""), + "removed policy override", "-", `It removes policy override "payments".`}, + {"selector", change(policyv1.OverrideChangeKind_OVERRIDE_CHANGE_KIND_SELECTOR, + `{"matchLabels":{"custom/team":"pay"}}`, `{"matchLabels":{"custom/criticality":"high"}}`), + "selector", "custom/team=pay -> custom/criticality=high", + `It changes the selector of policy override "payments" from custom/team=pay to custom/criticality=high.`}, + {"priority", change(policyv1.OverrideChangeKind_OVERRIDE_CHANGE_KIND_PRIORITY, "100", "200"), + "priority", "100 -> 200", `It changes the priority of policy override "payments" from 100 to 200.`}, + {"expiry", change(policyv1.OverrideChangeKind_OVERRIDE_CHANGE_KIND_EXPIRY, "", `"2027-01-26T00:00:00Z"`), + "expiry", "none -> 2027-01-26T00:00:00Z", + `It changes the expiry of policy override "payments" from none to 2027-01-26T00:00:00Z.`}, + {"name", change(policyv1.OverrideChangeKind_OVERRIDE_CHANGE_KIND_NAME, "pay", "payments"), + "name", "pay -> payments", `It renames policy override "pay" to "payments".`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + item := overrideChangeItem(tt.change) + assert.Equal(t, tt.what, item.whatCell()) + assert.Equal(t, tt.cell, item.changeCell()) + assert.Equal(t, tt.sentence, item.sentence) + assert.Equal(t, tt.change.GetOldValue(), item.Old, "plain and JSON keep the value of the server") + }) + } +} + +func TestReportLoosening_AnAddedOverride(t *testing.T) { + stderr := captureStderr(t) + c := &policyv1.OverrideChange{} + c.SetOverrideName("policy-test") + c.SetKind(policyv1.OverrideChangeKind_OVERRIDE_CHANGE_KIND_ADDED) + c.SetNewValue("policy-test") + c.SetDirection(policyv1.ChangeDirection_CHANGE_DIRECTION_LOOSENS) + res := &policyv1.PreviewPolicyChangeResponse{} + res.SetOverrideChanges([]*policyv1.OverrideChange{c}) + res.SetDirection(policyv1.ChangeDirection_CHANGE_DIRECTION_LOOSENS) + + reportLoosening(newPreviewView(res)) + assert.Contains(t, stderr.String(), `It adds policy override "policy-test".`) + assert.NotContains(t, stderr.String(), "It loosens added") +} diff --git a/internal/cmd/policy/publish_test.go b/internal/cmd/policy/publish_test.go index 3696ec1..cf053b3 100644 --- a/internal/cmd/policy/publish_test.go +++ b/internal/cmd/policy/publish_test.go @@ -87,7 +87,7 @@ func TestRunChangePublish_ShowsTheDirectionAndEveryWarning(t *testing.T) { out := stderr.String() assert.Contains(t, out, "Change 18 · LOOSENS. Only an Admin can publish it") assert.Contains(t, out, "It loosens package_admission.cooldown.min_age (- -> 7d) in override \"payments\"") - assert.Contains(t, out, "It loosens selector (custom/team=pay -> reported/os=linux) in override \"payments\"") + assert.Contains(t, out, "It changes the selector of policy override \"payments\" from custom/team=pay to reported/os=linux.") assert.Contains(t, out, "ENDPOINT_LABEL_LOOSENS payments: a policy override that loosens selects on a label that an endpoint can send") } diff --git a/internal/cmd/project/list.go b/internal/cmd/project/list.go index e778549..402beb2 100644 --- a/internal/cmd/project/list.go +++ b/internal/cmd/project/list.go @@ -122,7 +122,7 @@ func listCmd(a *app.App) *cobra.Command { "filter: scan status ("+strings.Join(scanStatusTokens(), ", ")+")") f.StringVar(&in.Trigger, "trigger", "", "filter: scan trigger ("+strings.Join(scanTriggerTokens(), ", ")+")") - f.Uint32Var(&in.PageSize, "limit", 0, "page size; server default when 0") + f.Uint32Var(&in.PageSize, "limit", 0, "page size, or the server default when 0") f.StringVar(&in.PageToken, "page-token", "", "continuation token from a prior response") return cmd } From 565967646418b621eb26cbc748bf7889b487c06e Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Thu, 5 Nov 2026 14:50:19 +0000 Subject: [PATCH 16/17] fix(policy): fix the findings of a review against a live tenant A reviewer ran the CLI against a live tenant and found these problems: 1. endpoint list --since 7d failed: the duration flags of the endpoint commands did not accept days. They now read durations as the policy commands do. The docs now give the real default of --since, 168h. 2. change create --from-revision above head showed "Invalid request". The server refuses it as an invalid restore.from_revision, and the CLI now says that the revision does not exist. --from-revision 0 now says that revision 0 has no policy. 3. A FAILED_PRECONDITION of a change or a rule showed raw gRPC text. The CLI now shows the detail of the server with a hint: for a change, how to handle the package rules of a removed override, and for a rule, how to list the rules. 4. The editor opened again for each INVALID_ARGUMENT, also for a title that is too long, which no edit can fix. The CLI now checks the length of -m before the RPC, from the protovalidate rule of the request. The editor opens again only for an error in the document. 5. The preview showed enum values as SEVERITY_MEDIUM. The server writes an enum by its value name with no quotes, and the CLI now shows the short form of the document, as medium. 6. The editor did not warn about an override that selects on a label that a tool sets. It now warns, with no block, for each added or changed override that selects on a managed/, reported/ or scm-property/ label. 7. After revision 1, the CLI told the user to run endpoint list --applied-revision '<1', which endpoint list refuses. The hint now starts at revision 2. 8. A decision of the verified malware guard or the license rule of the pull request check showed "-". The check cites only the revisions for both, so the CLI shows "a fixed rule of the check". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MhRi597EX9odoSDXbVBsxz --- docs/cmd/endpoint-activity-list.md | 2 +- docs/cmd/endpoint-inventory-list.md | 2 +- docs/cmd/endpoint-list.md | 4 +- docs/cmd/endpoint-show.md | 2 +- docs/cmd/endpoint-status.md | 2 +- docs/cmd/policy-decision-list.md | 2 +- docs/cmd/policy-edit.md | 3 + internal/cloudpolicy/fields.go | 8 +- internal/cloudpolicy/fields_test.go | 3 + internal/cmd/endpoint/activity.go | 3 +- internal/cmd/endpoint/inventory.go | 3 +- internal/cmd/endpoint/list.go | 6 +- internal/cmd/endpoint/list_test.go | 7 ++ internal/cmd/endpoint/show.go | 3 +- internal/cmd/endpoint/status.go | 3 +- internal/cmd/policy/change_create.go | 15 ++- internal/cmd/policy/change_edit.go | 3 + internal/cmd/policy/change_publish.go | 13 +++ internal/cmd/policy/change_test.go | 7 +- internal/cmd/policy/decision_view.go | 13 +++ internal/cmd/policy/edit.go | 3 + internal/cmd/policy/editor.go | 57 +++++++++- internal/cmd/policy/errors.go | 46 +++++++- internal/cmd/policy/review_test.go | 147 ++++++++++++++++++++++++++ internal/cmd/policy/rule_create.go | 2 +- internal/cmd/policy/settings.go | 45 ++++++++ 26 files changed, 376 insertions(+), 28 deletions(-) create mode 100644 internal/cmd/policy/review_test.go diff --git a/docs/cmd/endpoint-activity-list.md b/docs/cmd/endpoint-activity-list.md index 55d6a99..0082082 100644 --- a/docs/cmd/endpoint-activity-list.md +++ b/docs/cmd/endpoint-activity-list.md @@ -39,7 +39,7 @@ Guard events carry one of the following actions: | Flag | Default | Description | |------|---------|-------------| | `--type` | `guard` | Activity type: `all`, `guard`, or `inventory` | -| `--since` | `168h` | Trailing time window length, e.g. `24h`, `168h`, `30m` | +| `--since` | `168h` | Trailing time window length, as `7d`, `24h` or `30m` | | `--endpoint` | _(none)_ | Filter by endpoint ULID or cached hostname; repeatable | | `--action` | `blocked,cooldown-blocked` (when type includes guard) | Package action filter for guard events: `blocked`, `confirmed`, `trusted`, `cooldown-blocked`; repeatable | | `--tool` | _(none)_ | Client-side filter by tool name (e.g. `claude-code`) | diff --git a/docs/cmd/endpoint-inventory-list.md b/docs/cmd/endpoint-inventory-list.md index 9a9458d..967a7a3 100644 --- a/docs/cmd/endpoint-inventory-list.md +++ b/docs/cmd/endpoint-inventory-list.md @@ -24,7 +24,7 @@ By default, dedupe is performed over the fetched page only. For a complete snaps | Flag | Default | Description | |------|---------|-------------| -| `--since` | `168h` | Trailing time window length, e.g. `24h`, `168h`, `30m` | +| `--since` | `168h` | Trailing time window length, as `7d`, `24h` or `30m` | | `--endpoint` | _(none)_ | Filter by endpoint ULID or cached hostname; repeatable | | `--kind` | _(none)_ | Filter by inventory kind (see Kind vocabulary below); repeatable | | `--scope` | _(none)_ | Filter by scope: `system` or `project` | diff --git a/docs/cmd/endpoint-list.md b/docs/cmd/endpoint-list.md index 4ca970e..b1b05ac 100644 --- a/docs/cmd/endpoint-list.md +++ b/docs/cmd/endpoint-list.md @@ -12,10 +12,10 @@ safedep endpoint list [flags] [--output table|plain|json] [--profile <name>] | Flag | Description | |---|---| -| `--since <duration>` | Trailing window length for event counts (default `24h`). Accepts Go duration strings: `24h`, `168h`, `30m`. | +| `--since <duration>` | Trailing window length for event counts (default `168h`, 7 days). Accepts a number and a unit, as `7d`, `24h` or `30m`. | | `--capability <name>` | Filter to endpoints that advertise this capability. Repeatable. Accepted values: `guard`, `tracer`, `advisor`, `inventory`. | | `--blocked` | Only endpoints with at least one blocked package-guard install in the window. | -| `--silent-for <duration>` | Only endpoints whose last sync is older than this duration (client-side filter; best-effort within `--limit`). | +| `--silent-for <duration>` | Only endpoints whose last sync is older than this duration, as `7d` (client-side filter, best-effort within `--limit`). | | `--search <substring>` | Case-insensitive substring match on hostname or name (client-side filter; best-effort within `--limit`). | | `--selector <selector>` | Only endpoints whose labels match this label selector, as `reported/os=darwin,custom/team=release`. The syntax is the one of [`safedep project list`](./project-list.md). | | `--applied-revision '<N'` | Only endpoints where a tool applies a policy revision lower than `N`, as `'<48'`. Quote the value, because the shell reads `<`. | diff --git a/docs/cmd/endpoint-show.md b/docs/cmd/endpoint-show.md index 816aee8..cd7603b 100644 --- a/docs/cmd/endpoint-show.md +++ b/docs/cmd/endpoint-show.md @@ -24,7 +24,7 @@ The `<endpoint>` argument is resolved as follows: if it is a ULID it is used dir | Flag | Default | Description | |------|---------|-------------| -| `--since DURATION` | `168h` | Trailing window length used for per-tool event volumes and recent block lookup. Accepts Go duration strings, e.g. `24h`, `168h`, `720h`. | +| `--since DURATION` | `168h` | Trailing window length used for per-tool event volumes and recent block lookup. Accepts a number and a unit, as `7d`, `24h` or `30d`. | ## Examples diff --git a/docs/cmd/endpoint-status.md b/docs/cmd/endpoint-status.md index 8774945..86f6781 100644 --- a/docs/cmd/endpoint-status.md +++ b/docs/cmd/endpoint-status.md @@ -18,7 +18,7 @@ The response includes total registered endpoints, those that have synced at leas | Flag | Default | Description | |---|---|---| -| `--since` | `24h` | Trailing window length parsed as a Go duration string (e.g. `24h`, `168h`, `30m`). A non-positive value lets the server apply its own default window. | +| `--since` | `168h` | Trailing window length, a number and a unit, as `7d`, `24h` or `30m`. A non-positive value lets the server apply its own default window. | | `--output` | `table` | Output format: `table`, `plain`, or `json`. Inherited from the root command. | | `--profile` | `default` | Credential profile to use. Inherited from the root command. | | `--insecure-keychain-fallback` | `false` | Allow falling back to an unencrypted credential store. Inherited from the root command. | diff --git a/docs/cmd/policy-decision-list.md b/docs/cmd/policy-decision-list.md index 63b7124..7a5ff54 100644 --- a/docs/cmd/policy-decision-list.md +++ b/docs/cmd/policy-decision-list.md @@ -62,7 +62,7 @@ form that pmg and vet store: | `TOOL` | `pmg`, `pull-request-check` or `vet`. | | `PACKAGE` | The ecosystem, the name and the version. | | `OUTCOME` | `blocked`, `failed` or `allowed`. | -| `DECIDED BY` | The package rule, or the field path, and the layer or the override that set it: `default policy`, `base` or `override NAME`. | +| `DECIDED BY` | The package rule, or the field path, and the layer or the override that set it: `default policy`, `base` or `override NAME`. The pull request check cites no rule and no path for its verified malware guard and its license rule. These show as `a fixed rule of the check`. | | `REV` | The tenant policy revision. When the default policy decided, also its revision, as `47 · default 1`. | | `WHERE` | For pmg, the hostname and the user, and one hint: the CI repository, else the Kubernetes namespace and workload, else the agent. For a check, the repository and the pull request number. For a scan, the repository and the branch or the commit. | | `LINK` | The check run, the pull request or the CI run. The table has this column only when a row has a link. | diff --git a/docs/cmd/policy-edit.md b/docs/cmd/policy-edit.md index 21483eb..1c203d2 100644 --- a/docs/cmd/policy-edit.md +++ b/docs/cmd/policy-edit.md @@ -138,6 +138,9 @@ 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. +- 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. - When the policy has settings and the saved file sets no field, the editor opens again with the error. To remove every setting, write `{}` on one line. - When the save fails for another reason, the command keeps the file and prints diff --git a/internal/cloudpolicy/fields.go b/internal/cloudpolicy/fields.go index 572cf13..ca0b858 100644 --- a/internal/cloudpolicy/fields.go +++ b/internal/cloudpolicy/fields.go @@ -196,8 +196,10 @@ func humanDuration(d time.Duration) string { return humanize.Duration(d) } -// FormatJSONValue turns a value of a contract path in protojson form, as a -// preview returns it, into the document form and the table form. An empty +// FormatJSONValue turns a value of a contract path, as a preview returns it, +// into the document form and the table form. The server writes a message in +// protojson and an enum by its value name with no quotes, as SEVERITY_MEDIUM. +// Both get the short form of the document, as "7d" and "medium". An empty // raw value means that the layer did not set the field, and shows as "-". func FormatJSONValue(path, raw string) (string, string) { if raw == "" { @@ -205,7 +207,7 @@ func FormatJSONValue(path, raw string) (string, string) { } var value any if err := json.Unmarshal([]byte(raw), &value); err != nil { - return raw, raw + value = raw } fd := fieldByPath(path) diff --git a/internal/cloudpolicy/fields_test.go b/internal/cloudpolicy/fields_test.go index 557e49e..0178b86 100644 --- a/internal/cloudpolicy/fields_test.go +++ b/internal/cloudpolicy/fields_test.go @@ -48,6 +48,9 @@ func TestFormatJSONValue(t *testing.T) { path, raw, value, human string }{ {"scan_gate.fail_on", `"SEVERITY_MEDIUM"`, "medium", "medium"}, + // The server writes an enum by its value name, with no quotes. + {"scan_gate.fail_on", "SEVERITY_MEDIUM", "medium", "medium"}, + {"scan_gate.fail_on_attacks", "ATTACK_GATE_FAIL", "fail", "fail"}, {"package_admission.cooldown.min_age", `"604800s"`, "168h", "7d"}, {"package_admission.cooldown.min_age", `"0s"`, "0s", "0s"}, {"scan_gate.fail_on", "", "-", "-"}, diff --git a/internal/cmd/endpoint/activity.go b/internal/cmd/endpoint/activity.go index 1fdda56..b58f56e 100644 --- a/internal/cmd/endpoint/activity.go +++ b/internal/cmd/endpoint/activity.go @@ -10,6 +10,7 @@ import ( messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/duration" "github.com/safedep/dry/tui/humanize" "github.com/safedep/dry/tui/section" "github.com/safedep/dry/tui/table" @@ -97,7 +98,7 @@ func activityListCmd(a *app.App) *cobra.Command { } f := cmd.Flags() f.StringVar(&typeFlag, "type", string(ActivityTypeGuard), "activity type: all|guard|inventory") - f.DurationVar(&since, "since", 7*24*time.Hour, "trailing window length, e.g. 24h, 168h, 30m") + f.Var(duration.NewValue(&since, 7*24*time.Hour), "since", "trailing window length, as in 7d, 24h or 30m") f.StringSliceVar(&endpoints, "endpoint", nil, "filter by endpoint (ULID or cached hostname); repeatable") f.StringSliceVar(&actionsRaw, "action", nil, "guard-only action filter: blocked|confirmed|trusted|cooldown-blocked. Setting this implies --type=guard unless --type is set explicitly.") f.StringVar(&toolFlag, "tool", "", "client-side filter by tool_name") diff --git a/internal/cmd/endpoint/inventory.go b/internal/cmd/endpoint/inventory.go index eb02fe2..109d626 100644 --- a/internal/cmd/endpoint/inventory.go +++ b/internal/cmd/endpoint/inventory.go @@ -10,6 +10,7 @@ import ( messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/duration" "github.com/safedep/dry/tui" "github.com/safedep/dry/tui/humanize" "github.com/safedep/dry/tui/table" @@ -146,7 +147,7 @@ func inventoryListCmd(a *app.App) *cobra.Command { }, } f := cmd.Flags() - f.DurationVar(&since, "since", 7*24*time.Hour, "trailing window length, e.g. 168h, 24h, 30m") + f.Var(duration.NewValue(&since, 7*24*time.Hour), "since", "trailing window length, as in 7d, 24h or 30m") f.StringSliceVar(&endpoints, "endpoint", nil, "filter by endpoint (ULID or cached hostname); repeatable") f.StringSliceVar(&kindsRaw, "kind", nil, "filter by inventory kind (mcp-server|coding-agent|ai-extension|cli-tool|project-config|browser-extension|ide-extension|agent-plugin|agent-skill); repeatable") f.StringVar(&scopeFlag, "scope", "", "filter by scope: system|project") diff --git a/internal/cmd/endpoint/list.go b/internal/cmd/endpoint/list.go index 30a46a8..3f5f471 100644 --- a/internal/cmd/endpoint/list.go +++ b/internal/cmd/endpoint/list.go @@ -12,6 +12,7 @@ import ( controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" "github.com/safedep/cli/internal/app" "github.com/safedep/cli/internal/cloudpolicy" + "github.com/safedep/cli/internal/duration" "github.com/safedep/cli/internal/tui" "github.com/safedep/dry/tui/humanize" "github.com/safedep/dry/tui/table" @@ -89,10 +90,11 @@ func listCmd(a *app.App) *cobra.Command { }, } f := cmd.Flags() - f.DurationVar(&since, "since", 7*24*time.Hour, "trailing window length, e.g. 168h, 24h, 30m") + f.Var(duration.NewValue(&since, 7*24*time.Hour), "since", "trailing window length, as in 7d, 24h or 30m") f.StringSliceVar(&capabilitiesRaw, "capability", nil, "filter by capability (guard|tracer|advisor|inventory); repeatable") f.BoolVar(&onlyBlocked, "blocked", false, "only endpoints with at least one blocked install in the window") - f.DurationVar(&silentFor, "silent-for", 0, "only endpoints not seen for at least this duration (client-side; best-effort within --limit)") + f.Var(duration.NewValue(&silentFor, 0), "silent-for", + "only endpoints not seen for at least this duration, as in 7d (client-side, best-effort within --limit)") f.StringVar(&searchFlag, "search", "", "case-insensitive substring match on hostname/name (client-side; best-effort within --limit)") f.StringVar(&selectorFlag, "selector", "", "filter: a label selector, as in reported/os=darwin,custom/team=release") f.StringVar(&appliedFlag, "applied-revision", "", "filter: '<N' keeps endpoints where a tool applies a policy revision lower than N, as in '<48'") diff --git a/internal/cmd/endpoint/list_test.go b/internal/cmd/endpoint/list_test.go index 806ee03..5e112eb 100644 --- a/internal/cmd/endpoint/list_test.go +++ b/internal/cmd/endpoint/list_test.go @@ -68,3 +68,10 @@ func newNopDirectory(t *testing.T) *Directory { t.Helper() return NewDirectory(newFakeStore(), time.Now) } + +func TestListCmd_DurationFlagsAcceptDays(t *testing.T) { + cmd := listCmd(nil) + require.NoError(t, cmd.ParseFlags([]string{"--since", "7d", "--silent-for", "2d"})) + assert.Equal(t, "168h", cmd.Flags().Lookup("since").Value.String()) + assert.Equal(t, "48h", cmd.Flags().Lookup("silent-for").Value.String()) +} diff --git a/internal/cmd/endpoint/show.go b/internal/cmd/endpoint/show.go index 595b007..4de73bb 100644 --- a/internal/cmd/endpoint/show.go +++ b/internal/cmd/endpoint/show.go @@ -9,6 +9,7 @@ import ( messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/duration" "github.com/safedep/dry/log" "github.com/safedep/dry/tui/humanize" "github.com/safedep/dry/tui/panel" @@ -86,7 +87,7 @@ func showCmd(a *app.App) *cobra.Command { }, } f := cmd.Flags() - f.DurationVar(&since, "since", 7*24*time.Hour, "trailing window length for per-tool counts and guard events, e.g. 168h, 24h") + f.Var(duration.NewValue(&since, 7*24*time.Hour), "since", "trailing window length for per-tool counts and guard events, as in 7d or 24h") f.Uint32Var(&blocks, "blocks", defaultGuardPageSize, "max guard events to fetch in the window (server caps page size)") f.StringSliceVar(&actionsRaw, "actions", nil, "guard event actions to render: blocked|cooldown-blocked|confirmed|trusted|all (default: blocked,cooldown-blocked)") f.BoolVar(&inventoryFlag, "inventory", false, "render the inventory item list, not just the count") diff --git a/internal/cmd/endpoint/status.go b/internal/cmd/endpoint/status.go index ba74002..1cf24a6 100644 --- a/internal/cmd/endpoint/status.go +++ b/internal/cmd/endpoint/status.go @@ -7,6 +7,7 @@ import ( "time" "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/duration" "github.com/safedep/dry/tui/stat" "github.com/safedep/dry/tui/theme" "github.com/spf13/cobra" @@ -35,7 +36,7 @@ func statusCmd(a *app.App) *cobra.Command { return a.Output.Print(res) }, } - cmd.Flags().DurationVar(&since, "since", 7*24*time.Hour, "trailing window length, e.g. 168h, 24h, 30m") + cmd.Flags().Var(duration.NewValue(&since, 7*24*time.Hour), "since", "trailing window length, as in 7d, 24h or 30m") return cmd } diff --git a/internal/cmd/policy/change_create.go b/internal/cmd/policy/change_create.go index ab28d24..be2ca13 100644 --- a/internal/cmd/policy/change_create.go +++ b/internal/cmd/policy/change_create.go @@ -24,9 +24,11 @@ const ( type changeCreateInput struct { FromRevision uint64 - Capabilities []string - PackageRules string - Title string + // FromRevisionSet tells a missing --from-revision from --from-revision 0. + FromRevisionSet bool + Capabilities []string + PackageRules string + Title string } func changeCreateCmd(a *app.App) *cobra.Command { @@ -43,6 +45,7 @@ func changeCreateCmd(a *app.App) *cobra.Command { if err := cobra.NoArgs(cmd, args); err != nil { return err } + in.FromRevisionSet = cmd.Flags().Changed("from-revision") return validateChangeCreate(in) }, RunE: func(cmd *cobra.Command, _ []string) error { @@ -75,7 +78,11 @@ func changeCreateCmd(a *app.App) *cobra.Command { } func validateChangeCreate(in changeCreateInput) error { - if in.FromRevision == 0 { + switch { + case in.FromRevision == 0 && in.FromRevisionSet: + return invalidInputError(errors.New("revision 0 has no policy. Use 1 or more"), + "Find the revision in: safedep policy revision list") + case in.FromRevision == 0: return invalidInputError(errors.New("--from-revision is required"), "Find the revision in: safedep policy revision list") } diff --git a/internal/cmd/policy/change_edit.go b/internal/cmd/policy/change_edit.go index a2374a9..e2ed3a7 100644 --- a/internal/cmd/policy/change_edit.go +++ b/internal/cmd/policy/change_edit.go @@ -59,6 +59,9 @@ func runChangeEdit( tenant, id string, in editInput, ) (*policyv1.PolicyChange, error) { + if err := checkMaxLength("-m", in.Title, &policyv1.UpdatePolicyChangeRequest{}, "title"); err != nil { + return nil, err + } change, err := getChange(ctx, client, id) if err != nil { return nil, err diff --git a/internal/cmd/policy/change_publish.go b/internal/cmd/policy/change_publish.go index 4243886..1a260bc 100644 --- a/internal/cmd/policy/change_publish.go +++ b/internal/cmd/policy/change_publish.go @@ -85,6 +85,9 @@ func runChangePublish( id, message string, confirm confirmFunc, ) (*policyv1.PolicyRevision, error) { + if err := checkMaxLength("-m", message, &policyv1.PublishPolicyChangeRequest{}, "message"); err != nil { + return nil, err + } change, err := getChange(ctx, client, id) if err != nil { return nil, err @@ -163,5 +166,15 @@ func reportLoosening(p *previewView) { func reportPublish(revision uint64, direction string) { tui.Success("revision %d published%s%s", revision, sep, direction) tui.Info(" Projects resolve it at their next check. Endpoints apply it after their next policy fetch") + reportLaggingEndpoints(revision) +} + +// reportLaggingEndpoints tells how to find the endpoints that have not +// applied revision yet. Before revision 1 no endpoint had a revision, so +// endpoint list refuses '<1' and the hint starts at revision 2. +func reportLaggingEndpoints(revision uint64) { + if revision < 2 { + return + } tui.Info(" Endpoints that have not applied it yet: safedep endpoint list --applied-revision '<%d'", revision) } diff --git a/internal/cmd/policy/change_test.go b/internal/cmd/policy/change_test.go index bd89269..7e2485e 100644 --- a/internal/cmd/policy/change_test.go +++ b/internal/cmd/policy/change_test.go @@ -59,8 +59,9 @@ func previewResponse() *policyv1.PreviewPolicyChangeResponse { field.SetPath("scan_gate.fail_on") field.SetLayer(recordv1.Layer_LAYER_OVERRIDE) field.SetOverrideName("payments") - field.SetOldValue(`"SEVERITY_HIGH"`) - field.SetNewValue(`"SEVERITY_MEDIUM"`) + // The server writes an enum by its value name, with no quotes. + field.SetOldValue("SEVERITY_HIGH") + field.SetNewValue("SEVERITY_MEDIUM") field.SetDirection(policyv1.ChangeDirection_CHANGE_DIRECTION_TIGHTENS) cooldown := &policyv1.PathChange{} @@ -84,7 +85,7 @@ func previewResponse() *policyv1.PreviewPolicyChangeResponse { cooldownCoverage.SetUnsupportedCount(3) coverage := &policyv1.CoverageSummary{} coverage.SetPath("scan_gate.fail_on") - coverage.SetValue(`"SEVERITY_MEDIUM"`) + coverage.SetValue("SEVERITY_MEDIUM") coverage.SetEnforceCount(3) res := &policyv1.PreviewPolicyChangeResponse{} diff --git a/internal/cmd/policy/decision_view.go b/internal/cmd/policy/decision_view.go index b77d72e..e07ea33 100644 --- a/internal/cmd/policy/decision_view.go +++ b/internal/cmd/policy/decision_view.go @@ -155,6 +155,8 @@ func (v decisionView) decidedBy() string { parts = append(parts, "rule "+v.RuleID) case v.Path != "": parts = append(parts, v.Path) + default: + parts = append(parts, fixedRuleText(v.Tool)) } switch { case v.override != "": @@ -167,6 +169,17 @@ func (v decisionView) decidedBy() string { return cloudpolicy.EmptyDash(strings.Join(parts, sep)) } +// fixedRuleText names a decision whose citation has no rule and no path. +// The pull request check cites only the revisions for its verified malware +// guard and for its fixed license rule, because they are outside the policy +// contract. A stored decision does not tell the two apart. +func fixedRuleText(tool string) string { + if tool == tui.EnumToken(policyv1.DecisionTool_DECISION_TOOL_PULL_REQUEST_CHECK.String(), decisionToolPrefix) { + return "a fixed rule of the check" + } + return "a fixed rule of the tool" +} + // revisionCell gives the tenant revision, and the default policy revision // when the default policy decided or the tenant has no revision. func (v decisionView) revisionCell() string { diff --git a/internal/cmd/policy/edit.go b/internal/cmd/policy/edit.go index 437e0c3..25fc073 100644 --- a/internal/cmd/policy/edit.go +++ b/internal/cmd/policy/edit.go @@ -85,6 +85,9 @@ func runEdit( tenant string, in editInput, ) (*policyv1.PolicyChange, error) { + if err := checkMaxLength("-m", in.Title, &policyv1.CreatePolicyChangeRequest{}, "title"); err != nil { + return nil, err + } head, err := getPolicy(ctx, client) if err != nil { return nil, err diff --git a/internal/cmd/policy/editor.go b/internal/cmd/policy/editor.go index b022ec2..3b7d885 100644 --- a/internal/cmd/policy/editor.go +++ b/internal/cmd/policy/editor.go @@ -8,10 +8,14 @@ import ( "os" "strings" + validate "buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go/buf/validate" "github.com/safedep/dry/tui" "github.com/safedep/dry/usefulerror" + "google.golang.org/genproto/googleapis/rpc/errdetails" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" ) const ( @@ -36,13 +40,64 @@ func (e *retryableError) Unwrap() error { return e.err } func retryable(err error) error { return &retryableError{err: err} } +// documentFields are the request fields that the edit document holds. An +// INVALID_ARGUMENT about one of them is an error that an edit can fix. +var documentFields = []string{"settings", "base", "base_description", "overrides"} + func isRetryable(err error) bool { var r *retryableError if errors.As(err, &r) { return true } st, ok := status.FromError(err) - return ok && st.Code() == codes.InvalidArgument + if !ok || st.Code() != codes.InvalidArgument { + return false + } + if bad, ok := usefulerror.DetailAs[*errdetails.BadRequest](err); ok && len(bad.GetFieldViolations()) > 0 { + for _, v := range bad.GetFieldViolations() { + if isDocumentField(v.GetField()) { + return true + } + } + return false + } + // With no field detail, the message starts with the field, as in + // "title: must be at most 200 characters". + field, _, found := strings.Cut(st.Message(), ":") + return !found || strings.ContainsAny(field, " ") || isDocumentField(field) +} + +func isDocumentField(field string) bool { + for _, f := range documentFields { + if field == f || strings.HasPrefix(field, f+".") || strings.HasPrefix(field, f+"[") { + return true + } + } + return false +} + +// checkMaxLength refuses a flag value that the server refuses for its +// length, from the protovalidate rule of the request field, before the RPC. +// An edit cannot fix such a value, so the editor must not open again for it. +func checkMaxLength(flag, value string, request proto.Message, field protoreflect.Name) error { + fd := request.ProtoReflect().Descriptor().Fields().ByName(field) + if fd == nil { + return nil + } + rules, ok := proto.GetExtension(fd.Options(), validate.E_Field).(*validate.FieldRules) + if !ok || !rules.GetString().HasMaxLen() { + return nil + } + limit := rules.GetString().GetMaxLen() + var n uint64 + for range value { + n++ + } + if n > limit { + return invalidInputError(fmt.Errorf("%s is %d characters long: the limit is %d", flag, n, limit), + fmt.Sprintf("Give a %s of at most %d characters", flag, limit)) + } + return nil } // editLoop writes text to a temporary file, opens the editor on it, and diff --git a/internal/cmd/policy/errors.go b/internal/cmd/policy/errors.go index 5b3e326..909177d 100644 --- a/internal/cmd/policy/errors.go +++ b/internal/cmd/policy/errors.go @@ -24,6 +24,27 @@ func invalidInputError(cause error, help string) error { return newPolicyError(usefulerror.ErrBadRequest, cause.Error(), help, cause) } +// failedPreconditionError shows the detail of a FAILED_PRECONDITION. The +// server sends no reason with it, so the hint covers the cases of the RPC. +func failedPreconditionError(st *status.Status, help string, cause error) error { + return newPolicyError(usefulerror.ErrConflict, + "The server refused the request: "+tui.EscapeLine(st.Message()), help, cause) +} + +// violatesField reports whether a BadRequest detail of err names field. +func violatesField(err error, field string) bool { + bad, ok := usefulerror.DetailAs[*errdetails.BadRequest](err) + if !ok { + return false + } + for _, v := range bad.GetFieldViolations() { + if v.GetField() == field { + return true + } + } + return false +} + // mapChangeError gives the recovery for the errors of a policy change RPC: // a stale base, an old etag, or a change that does not exist. func mapChangeError(op, changeID string, err error) error { @@ -55,16 +76,33 @@ func mapChangeError(op, changeID string, err error) error { "Your role cannot change the policy", "Ask an Admin of the tenant to do it", cause) + case codes.FailedPrecondition: + return failedPreconditionError(st, changePreconditionHelp(changeID), cause) } } return cause } +// changePreconditionHelp covers the refusals of a change: a change that is +// not open, and a change that removes a policy override that package rules +// still use. +func changePreconditionHelp(changeID string) string { + review := "Review the change: safedep policy change show" + if changeID != "" { + review += " " + changeID + } + return review + ". If it removes a policy override, delete the package rules of that override first, " + + "or attach them to another one: safedep policy rule list --override NAME" +} + // mapRestoreError gives the recovery for the errors of a create that -// restores an old revision. A missing revision is the usual cause of -// NotFound. +// restores an old revision. The server refuses a revision above head as an +// invalid restore.from_revision. func mapRestoreError(fromRevision uint64, err error) error { - if st, ok := status.FromError(err); ok && st.Code() == codes.NotFound { + st, ok := status.FromError(err) + missing := ok && (st.Code() == codes.NotFound || + (st.Code() == codes.InvalidArgument && violatesField(err, "restore.from_revision"))) + if missing { return newPolicyError(usefulerror.ErrNotFound, fmt.Sprintf("Policy revision %d does not exist", fromRevision), "List the revisions: safedep policy revision list", @@ -88,6 +126,8 @@ func mapRuleError(op, ruleID string, err error) error { "Your role cannot change package rules", "Ask an Admin of the tenant to do it", cause) + case codes.FailedPrecondition: + return failedPreconditionError(st, "List the rules: safedep policy rule list", cause) } } return cause diff --git a/internal/cmd/policy/review_test.go b/internal/cmd/policy/review_test.go new file mode 100644 index 0000000..a0fbec3 --- /dev/null +++ b/internal/cmd/policy/review_test.go @@ -0,0 +1,147 @@ +package policy + +import ( + "context" + "strings" + "testing" + + messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" + recordv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/record/v1" + policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" + "github.com/safedep/dry/usefulerror" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + "google.golang.org/genproto/googleapis/rpc/errdetails" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/safedep/cli/internal/cloudpolicy/mocks" +) + +func badRequest(field, description string) error { + return usefulerror.NewStatus(codes.InvalidArgument, description). + WithDetail(&errdetails.BadRequest{FieldViolations: []*errdetails.BadRequest_FieldViolation{ + {Field: field, Description: description}, + }}).Err() +} + +func TestServerErrorMapping(t *testing.T) { + tests := []struct { + name string + err error + wantCode string + wantHuman string + wantHelp string + }{ + { + name: "a revision above head", + err: mapRestoreError(99, badRequest("restore.from_revision", "the revision to restore does not exist")), + wantCode: usefulerror.ErrNotFound, + wantHuman: "Policy revision 99 does not exist", + wantHelp: "safedep policy revision list", + }, + { + name: "a publish that removes an override with rules", + err: mapChangeError("publish", "3", status.Error(codes.FailedPrecondition, + "the change removes a policy override that active package rules attach to: r_1\x1b[2J")), + wantCode: usefulerror.ErrConflict, + wantHuman: `The server refused the request: the change removes a policy override that active package rules attach to: r_1\x1b[2J`, + wantHelp: "safedep policy rule list --override NAME", + }, + { + name: "a rule that is already deleted", + err: mapRuleError("delete", "r_1", status.Error(codes.FailedPrecondition, "package rule r_1 does not exist at head")), + wantCode: usefulerror.ErrConflict, + wantHuman: "The server refused the request: package rule r_1 does not exist at head", + wantHelp: "safedep policy rule list", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ue, ok := usefulerror.AsUsefulError(tt.err) + require.True(t, ok) + assert.Equal(t, tt.wantCode, ue.Code()) + assert.Equal(t, tt.wantHuman, ue.HumanError()) + assert.Contains(t, ue.Help(), tt.wantHelp) + }) + } +} + +func TestValidateChangeCreate_RevisionZero(t *testing.T) { + err := validateChangeCreate(changeCreateInput{FromRevisionSet: true, PackageRules: "head"}) + assert.ErrorContains(t, err, "revision 0 has no policy. Use 1 or more") +} + +func TestIsRetryable(t *testing.T) { + tests := []struct { + name string + err error + want bool + }{ + {"a field of the document", badRequest("settings.overrides[0].name", "value is required"), true}, + {"an override of the document", badRequest("overrides[1].priority", "must be unique"), true}, + {"the title", badRequest("title", "must be at most 200 characters"), false}, + {"the title with no detail", status.Error(codes.InvalidArgument, "title: must be at most 200 characters"), false}, + {"a message with no field", status.Error(codes.InvalidArgument, "override priorities must be unique"), true}, + {"another code", status.Error(codes.Unavailable, "down"), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, isRetryable(tt.err)) + }) + } +} + +func TestRunEdit_RefusesALongTitleBeforeTheEditor(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + _, err := runEdit(context.Background(), client, (&scriptedEditor{}).open, "", editInput{Title: strings.Repeat("t", 201)}) + require.Error(t, err) + assert.Contains(t, err.Error(), "-m is 201 characters long: the limit is 200") +} + +func TestRunEdit_WarnsAboutALabelThatAToolSets(t *testing.T) { + stderr := captureStderr(t) + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(headResponse(), nil) + createdSettings(client, new(*policyv1.Policy)) + + ed := &scriptedEditor{edits: []func(string) string{replace("{custom/environment: ci}", "{reported/os: linux}")}} + _, err := runEdit(context.Background(), client, ed.open, "", editInput{}) + require.NoError(t, err) + assert.Contains(t, stderr.String(), + `Policy override "ci" selects on reported/os. A tool sets this label, so a person on the endpoint can change it.`) + assert.NotContains(t, stderr.String(), `"payments" selects`, "an override with no change gets no warning") +} + +func TestSettableSelectorKeys(t *testing.T) { + selector := &messagescontroltowerv1.LabelSelector{} + selector.SetMatchLabels(map[string]string{"custom/team": "pay", "managed/kind": "ci"}) + expr := &messagescontroltowerv1.LabelSelectorRequirement{} + expr.SetKey("scm-property/criticality") + selector.SetMatchExpressions([]*messagescontroltowerv1.LabelSelectorRequirement{expr}) + assert.Equal(t, []string{"managed/kind", "scm-property/criticality"}, settableSelectorKeys(selector)) +} + +func TestReportLaggingEndpoints(t *testing.T) { + tests := []struct { + revision uint64 + want bool + }{ + {1, false}, + {2, true}, + } + for _, tt := range tests { + stderr := captureStderr(t) + reportLaggingEndpoints(tt.revision) + assert.Equal(t, tt.want, strings.Contains(stderr.String(), "--applied-revision"), "revision %d", tt.revision) + } +} + +func TestDecidedBy_AFixedRuleOfTheCheck(t *testing.T) { + d := decision("d_fixed", policyv1.DecisionTool_DECISION_TOOL_PULL_REQUEST_CHECK, + policyv1.DecisionOutcome_DECISION_OUTCOME_FAILED, "evil", "1.0.0", + citation(47, 1, "", "", "", recordv1.Layer_LAYER_UNSPECIFIED), + atPullRequest("acme/api", 7, "")) + assert.Equal(t, "a fixed rule of the check", newDecisionView(d, nil).decidedBy()) +} diff --git a/internal/cmd/policy/rule_create.go b/internal/cmd/policy/rule_create.go index 6724420..08a1561 100644 --- a/internal/cmd/policy/rule_create.go +++ b/internal/cmd/policy/rule_create.go @@ -176,5 +176,5 @@ func reportRuleCreate(in ruleCreateInput, res *ruleCreateResult, now time.Time) } } tui.Info(" Each endpoint applies it after its next policy fetch. Pull request checks apply it at once.") - tui.Info(" Endpoints that have not applied it yet: safedep endpoint list --applied-revision '<%d'", res.Revision) + reportLaggingEndpoints(res.Revision) } diff --git a/internal/cmd/policy/settings.go b/internal/cmd/policy/settings.go index a2275b4..724b874 100644 --- a/internal/cmd/policy/settings.go +++ b/internal/cmd/policy/settings.go @@ -4,7 +4,10 @@ import ( "context" "errors" "fmt" + "slices" + "strings" + messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" "github.com/safedep/dry/tui" "github.com/safedep/dry/usefulerror" @@ -187,6 +190,7 @@ func checkEditedSettings(start, edited *policyv1.Policy) error { } kept[id] = struct{}{} } + warnSettableLabels(known, edited) for _, o := range start.GetOverrides() { if _, ok := kept[o.GetOverrideId()]; !ok { tui.Warning("This removes policy override %q (id %s). The server refuses the removal while package rules attach to it", @@ -196,6 +200,47 @@ func checkEditedSettings(start, edited *policyv1.Policy) error { return nil } +// settableLabelPrefixes are the label prefixes that a tool or a source +// outside SafeDep sets. A person on an endpoint can change a reported/ or a +// managed/ label, so an override that loosens the policy must not trust them +// (parent spec 6.7). The server warns too, but only in a preview, which a +// publish with --yes does not show. +var settableLabelPrefixes = []string{"managed/", "reported/", "scm-property/"} + +// warnSettableLabels warns, with no block, for each added or changed policy +// override whose selector names a label of settableLabelPrefixes. +func warnSettableLabels(known map[string]*policyv1.Override, edited *policyv1.Policy) { + for _, o := range edited.GetOverrides() { + if before, ok := known[o.GetOverrideId()]; ok && o.GetOverrideId() != "" && proto.Equal(before, o) { + continue + } + for _, key := range settableSelectorKeys(o.GetSelector()) { + tui.Warning("Policy override %q selects on %s. A tool sets this label, so a person on the endpoint can "+ + "change it. If the override loosens the policy, review it before you publish", + clitui.EscapeLine(o.GetName()), clitui.EscapeLine(key)) + } + } +} + +func settableSelectorKeys(selector *messagescontroltowerv1.LabelSelector) []string { + var keys []string + add := func(key string) { + for _, prefix := range settableLabelPrefixes { + if strings.HasPrefix(key, prefix) && !slices.Contains(keys, key) { + keys = append(keys, key) + } + } + } + for key := range selector.GetMatchLabels() { + add(key) + } + for _, expr := range selector.GetMatchExpressions() { + add(expr.GetKey()) + } + slices.Sort(keys) + return keys +} + func validateSettings(p *policyv1.Policy) error { names := map[string]struct{}{} priorities := map[uint32]string{} From 3727038f5ab9353d7f51ec6c99a2c3c42ce4f0df Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Thu, 5 Nov 2026 14:51:48 +0000 Subject: [PATCH 17/17] fix(policy): save a new title of a change when the settings do not change policy change edit -m "new title" lost the title when the user closed the editor with no edit. The editor stops before the save when the document has no change, so the title never reached the server, and the command said "No change. Nothing is saved". When -m differs from the title of the change and the document has no change, the command now sends an update with only the title and the etag. The server keeps the settings of the change. The success line says that the title changed and that the settings did not. policy edit -m keeps its behaviour: it creates a change only when the document changes, because a title alone is not a policy change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MhRi597EX9odoSDXbVBsxz --- docs/cmd/policy-change-edit.md | 10 +++++++ internal/cmd/policy/change_edit.go | 46 ++++++++++++++++++++++++++---- internal/cmd/policy/change_test.go | 43 +++++++++++++++++++++++++++- 3 files changed, 93 insertions(+), 6 deletions(-) diff --git a/docs/cmd/policy-change-edit.md b/docs/cmd/policy-change-edit.md index 0cf5dad..44b7052 100644 --- a/docs/cmd/policy-change-edit.md +++ b/docs/cmd/policy-change-edit.md @@ -33,6 +33,16 @@ safedep policy change edit 18 Review it: safedep policy change show 18 ``` +To change only the title, pass `-m` and close the editor with no change: + +```bash +safedep policy change edit 18 -m "payments: medium only" +``` + +``` +✓ change 18: the title is now "payments: medium only". The settings did not change +``` + When another admin updated the change after the command read it, the update stops. Run `safedep policy change show 18` and edit again. diff --git a/internal/cmd/policy/change_edit.go b/internal/cmd/policy/change_edit.go index e2ed3a7..4d78f30 100644 --- a/internal/cmd/policy/change_edit.go +++ b/internal/cmd/policy/change_edit.go @@ -32,7 +32,7 @@ func changeEditCmd(a *app.App) *cobra.Command { if err != nil { return err } - change, err := runChangeEdit(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), + res, err := runChangeEdit(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), openEditor, a.Tenant(), args[0], in) if errors.Is(err, errNoChange) { tui.Info("No change. Nothing is saved") @@ -41,8 +41,13 @@ func changeEditCmd(a *app.App) *cobra.Command { if err != nil { return err } - id := clitui.EscapeLine(change.GetChangeId()) - tui.Success("change %s updated", id) + id := clitui.EscapeLine(res.change.GetChangeId()) + if res.titleOnly { + tui.Success("change %s: the title is now %q. The settings did not change", id, + clitui.EscapeLine(res.change.GetTitle())) + } else { + tui.Success("change %s updated", id) + } tui.Info(" Review it: safedep policy change show %s", id) return nil }, @@ -52,13 +57,20 @@ func changeEditCmd(a *app.App) *cobra.Command { return cmd } +// changeEditResult is the change after an edit. titleOnly reports an edit +// that changed only the title, because the document had no change. +type changeEditResult struct { + change *policyv1.PolicyChange + titleOnly bool +} + func runChangeEdit( ctx context.Context, client policyv1grpc.PolicyServiceClient, open openEditorFunc, tenant, id string, in editInput, -) (*policyv1.PolicyChange, error) { +) (*changeEditResult, error) { if err := checkMaxLength("-m", in.Title, &policyv1.UpdatePolicyChangeRequest{}, "title"); err != nil { return nil, err } @@ -104,8 +116,32 @@ func runChangeEdit( updated = res.GetChange() return nil }) + // The editor stops with no save when the document has no change. A new + // -m title must still reach the server, or the edit loses it. + if errors.Is(err, errNoChange) && in.Title != "" && in.Title != change.GetTitle() { + return updateTitle(ctx, client, change, in.Title) + } if err != nil { return nil, err } - return updated, nil + return &changeEditResult{change: updated}, nil +} + +// updateTitle changes only the title of a change. The request has no +// settings, so the server keeps the settings of the change. +func updateTitle( + ctx context.Context, + client policyv1grpc.PolicyServiceClient, + change *policyv1.PolicyChange, + title string, +) (*changeEditResult, error) { + req := &policyv1.UpdatePolicyChangeRequest{} + req.SetChangeId(change.GetChangeId()) + req.SetEtag(change.GetEtag()) + req.SetTitle(title) + res, err := client.UpdatePolicyChange(ctx, req) + if err != nil { + return nil, mapChangeError("update", change.GetChangeId(), err) + } + return &changeEditResult{change: res.GetChange(), titleOnly: true}, nil } diff --git a/internal/cmd/policy/change_test.go b/internal/cmd/policy/change_test.go index 7e2485e..c86e3fe 100644 --- a/internal/cmd/policy/change_test.go +++ b/internal/cmd/policy/change_test.go @@ -290,11 +290,52 @@ func TestRunChangeEdit_UpdatesWithTheEtag(t *testing.T) { })).Return(res, nil) ed := &scriptedEditor{edits: []func(string) string{replace(" name: payments\n", " name: payments\n description: why\n")}} - _, err := runChangeEdit(context.Background(), client, ed.open, "", "18", editInput{Title: "new title"}) + got, err := runChangeEdit(context.Background(), client, ed.open, "", "18", editInput{Title: "new title"}) require.NoError(t, err) + assert.False(t, got.titleOnly) assert.Contains(t, ed.seen[0], "# Change 18 of this tenant · base revision 46 · head revision 46") } +func TestRunChangeEdit_TitleWithNoDocumentChange(t *testing.T) { + tests := []struct { + name string + title string + wantUpdate bool + }{ + {"a new title is saved", "new title", true}, + {"the same title is no change", "payments: medium + cooldown", false}, + {"no title is no change", "", false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + c := openChange("14") + c.SetSettings(headPolicy()) + client.EXPECT().GetPolicyChange(mock.Anything, mock.Anything).Return(changeResponse(c), nil) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(headResponse(), nil) + if tt.wantUpdate { + renamed := openChange("14") + renamed.SetTitle(tt.title) + res := &policyv1.UpdatePolicyChangeResponse{} + res.SetChange(renamed) + client.EXPECT().UpdatePolicyChange(mock.Anything, mock.MatchedBy(func(r *policyv1.UpdatePolicyChangeRequest) bool { + return r.GetChangeId() == "14" && r.GetEtag() == "etag-1" && r.GetTitle() == tt.title && !r.HasSettings() + })).Return(res, nil) + } + + got, err := runChangeEdit(context.Background(), client, (&scriptedEditor{edits: []func(string) string{keep}}).open, + "", "14", editInput{Title: tt.title}) + if !tt.wantUpdate { + assert.ErrorIs(t, err, errNoChange) + return + } + require.NoError(t, err) + assert.True(t, got.titleOnly) + assert.Equal(t, tt.title, got.change.GetTitle()) + }) + } +} + func TestChangeCreate(t *testing.T) { assert.ErrorContains(t, validateChangeCreate(changeCreateInput{PackageRules: "head"}), "--from-revision is required") assert.ErrorContains(t, validateChangeCreate(changeCreateInput{FromRevision: 46, PackageRules: "head", Capabilities: []string{"core"}}),