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 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..7c3faca 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,19 @@ 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. +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 +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. @@ -118,11 +131,38 @@ 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 | +| [`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 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 | | [`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..993f747 --- /dev/null +++ b/docs/cmd/audit-event-list.md @@ -0,0 +1,64 @@ +# 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 ` | Only events in this time before now, as `7d` or `12h`. | +| `--until ` | Only events older than this time before now, as `1d`. It must be shorter than `--since`. | +| `--action ` | Only events whose action starts with this text. `policy.` lists every policy action, and `policy.rule.` lists the package rule actions. | +| `--resource ` | 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 ` | Only events of this actor. The server matches the actor id or the display name exactly. | +| `--limit ` | Page size. The server default applies when 0. | +| `--page-token ` | Continuation token from a prior response. | + +Actions have the form `..`, as `policy.change.publish`. +To list the policy events, use `--action policy.`. `--resource` takes a resource +kind, not a domain. + +## 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-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-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 ` | 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..2226e20 --- /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 ` | 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. 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. + +## 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..b1b05ac 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 the endpoints that report to SafeDep Cloud, with filters for capability, blocked installs, silent duration, identity search, labels and the applied policy revision. ## Synopsis @@ -12,11 +12,13 @@ safedep endpoint list [flags] [--output table|plain|json] [--profile ] | Flag | Description | |---|---| -| `--since ` | Trailing window length for event counts (default `24h`). Accepts Go duration strings: `24h`, `168h`, `30m`. | +| `--since ` | Trailing window length for event counts (default `168h`, 7 days). Accepts a number and a unit, as `7d`, `24h` or `30m`. | | `--capability ` | 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 ` | Only endpoints whose last sync is older than this duration (client-side filter; best-effort within `--limit`). | +| `--silent-for ` | Only endpoints whose last sync is older than this duration, as `7d` (client-side filter, best-effort within `--limit`). | | `--search ` | Case-insensitive substring match on hostname or name (client-side filter; best-effort within `--limit`). | +| `--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 '` | Page size. Server default applies when `0` (the default). | | `--page-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..7417a65 --- /dev/null +++ b/docs/cmd/endpoint-policy-show.md @@ -0,0 +1,52 @@ +# safedep endpoint policy show + +Show the intended policy of one endpoint: each field, its value, and its source. +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 + +``` +safedep endpoint policy show ENDPOINT [--field PATH]... [--output table|plain|json] +``` + +## Flags + +| Flag | Description | +|------|-------------| +| `--field ` | 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 1 +Package rules 211 (184 trust, 27 block) + +FIELD VALUE SOURCE EXCEPTIONS +package_admission.cooldown.min_age 5d override "laptops" (100) - + +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/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 `` 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-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..44b7052 --- /dev/null +++ b/docs/cmd/policy-change-edit.md @@ -0,0 +1,58 @@ +# 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 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 + +```bash +safedep policy change edit 18 +``` + +``` +✓ change 18 updated + 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. + +## 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..4894a08 --- /dev/null +++ b/docs/cmd/policy-change-publish.md @@ -0,0 +1,61 @@ +# 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] [--yes] +``` + +## Flags + +| 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 + +```bash +safedep policy change publish 18 -m "payments: fail on medium, 7d cooldown (CUST-412)" +``` + +``` +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 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 + 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: + +``` +✗ 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..e00d934 --- /dev/null +++ b/docs/cmd/policy-change-show.md @@ -0,0 +1,69 @@ +# 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 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 +package_admission.cooldown.min_age = 168h 0 0 0 3 +scan_gate.fail_on = medium 3 0 0 0 + +Warnings +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. + +## 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`, and a selector is the protojson +that the server sends. The table humanizes them, as `7d` and `custom/criticality=high`. + +## 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..c83b933 --- /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 does not merge. Review the change again +before you publish it. + +## Synopsis + +``` +safedep policy change sync CHANGE +``` + +## Examples + +```bash +safedep policy change sync 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. + +## 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-decision-list.md b/docs/cmd/policy-decision-list.md new file mode 100644 index 0000000..7a5ff54 --- /dev/null +++ b/docs/cmd/policy-decision-list.md @@ -0,0 +1,144 @@ +# 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 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, 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. | +| `--page-token <token>` | Continuation token from a prior response. | + +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 | +|--------|---------| +| `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`. 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. | + +## 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 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 +``` + +``` +Policy decisions +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 +``` + +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/docs/cmd/policy-edit.md b/docs/cmd/policy-edit.md new file mode 100644 index 0000000..1c203d2 --- /dev/null +++ b/docs/cmd/policy-edit.md @@ -0,0 +1,158 @@ +# 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 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 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. + +The document of a tenant that has not published a policy yet: + +```yaml +# 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: + # 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: 7d +``` + +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: + # 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 + priority: 200 + selector: + matchLabels: {custom/criticality: high} + spec: + # package_admission: + # cooldown: + # min_age: 7d # a duration, as 7d or 12h, from 0s to 365d. Below this override: not set + scan_gate: + fail_on: high + # 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 +``` + +Edit one policy override: + +```bash +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. +- 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 + 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..7e85038 --- /dev/null +++ b/docs/cmd/policy-get.md @@ -0,0 +1,76 @@ +# 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: + - id: ov_7c2 + 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`. +- 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 + +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..dd8b09a --- /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 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 LOOSENS 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..7f95aa1 --- /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 LOOSENS +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..1b71f19 --- /dev/null +++ b/docs/cmd/policy-rule-create.md @@ -0,0 +1,97 @@ +# 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`, 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. | +| `--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. +- 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. + +## 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..0c32d6d --- /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. A trust entry expires at most 90 days from now. The command reads the rule to check it before the request. + +## 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..a2e74db --- /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 1 · scan_gate.fail_on: high · scan_gate.fail_on_attacks: fail + +Overrides (priority, highest first) +PRIORITY NAME SELECTOR EXPIRES DESCRIPTION +300 ci custom/environment=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/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..fa734c1 --- /dev/null +++ b/docs/cmd/project-label-set.md @@ -0,0 +1,44 @@ +# 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 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 + +```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..40cab51 --- /dev/null +++ b/docs/cmd/project-list.md @@ -0,0 +1,68 @@ +# 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 custom/criticality=high +``` + +``` +Projects +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, +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..7126d42 --- /dev/null +++ b/docs/cmd/project-policy-show.md @@ -0,0 +1,60 @@ +# 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 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 + +``` +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 1 +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 +No tool or check reported the policy that it applies for this project yet. +``` + +## 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..e1ead42 --- /dev/null +++ b/docs/cmd/project-show.md @@ -0,0 +1,47 @@ +# 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 01K88WX3G9RGAK8T3N5YJMFQN1 +Source bitbucket · https://bitbucket.org/acme/settlement +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 - +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/go.mod b/go.mod index afc7c01..08c5e11 100644 --- a/go.mod +++ b/go.mod @@ -3,8 +3,9 @@ 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/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 github.com/charmbracelet/lipgloss v1.1.0 github.com/cli/browser v1.3.0 @@ -16,6 +17,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 @@ -27,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 @@ -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..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-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-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/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..0138251 --- /dev/null +++ b/internal/cloudpolicy/document.go @@ -0,0 +1,184 @@ +// 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/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. 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") + +// 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 +} + +// 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 +} + +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 +} + +// 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 new file mode 100644 index 0000000..4355609 --- /dev/null +++ b/internal/cloudpolicy/document_test.go @@ -0,0 +1,223 @@ +package cloudpolicy + +import ( + "strings" + "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" + "google.golang.org/protobuf/encoding/protowire" + "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: + - id: ov_2 + name: ci + priority: 300 + selector: + matchLabels: {custom/environment: ci} + spec: + package_admission: + cooldown: + min_age: 168h + - id: ov_1 + 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)) +} + +func TestUnmarshalPolicy_RoundTrips(t *testing.T) { + original := samplePolicy() + b, err := MarshalPolicy(original, "") + require.NoError(t, err) + + got, err := UnmarshalPolicy(b) + require.NoError(t, err) + 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 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) { + 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), []byte(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"]) +} + +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 new file mode 100644 index 0000000..ca0b858 --- /dev/null +++ b/internal/cloudpolicy/fields.go @@ -0,0 +1,252 @@ +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 + } + return isFormattedMessage(fd.Message()) +} + +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.RFC3339Nano), 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, 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 == "" { + return "-", "-" + } + var value any + if err := json.Unmarshal([]byte(raw), &value); err != nil { + value = 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..0178b86 --- /dev/null +++ b/internal/cloudpolicy/fields_test.go @@ -0,0 +1,66 @@ +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"}, + // 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", "", "-", "-"}, + {"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..4a8a80a --- /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{"custom/environment": "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..34b844b --- /dev/null +++ b/internal/cloudpolicy/mocks/PolicyServiceClient_mock.go @@ -0,0 +1,1617 @@ +// 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 +} + +// 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 + 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..cde6bb0 --- /dev/null +++ b/internal/cloudpolicy/protoyaml.go @@ -0,0 +1,604 @@ +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, 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 + 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 { + if isFormattedMessage(m.Descriptor()) { + if m.Descriptor().FullName() == labelSelectorFullName { + return encodeSelector(m) + } + return scalarNode(c.formatWellKnown(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(c.key(fd)), 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: + // 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 "" + } +} + +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 + } + if isFormattedMessage(m.Descriptor()) { + return decodeFormatted(n, m, path) + } + if n.Kind != yaml.MappingNode { + return errAt(n, path, "expected a mapping of 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 := 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 { + 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) { + // "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 { + 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, c.key(fd)) + } + 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") + } +} + +// 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") + } + 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..891d0d3 --- /dev/null +++ b/internal/cloudpolicy/render.go @@ -0,0 +1,70 @@ +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. 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, lipgloss.Width(r[0])) + } + var b strings.Builder + for i, r := range rows { + if i > 0 { + b.WriteByte('\n') + } + b.WriteString(r[0]) + 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 new file mode 100644 index 0000000..56e9fc0 --- /dev/null +++ b/internal/cloudpolicy/subject.go @@ -0,0 +1,403 @@ +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" + + "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: TimeOf(report.GetFetchedAt()), + AppliedAt: TimeOf(report.GetAppliedAt()), + ReportedAt: TimeOf(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) +} + +// 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 { + 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, "; "))}) + } + 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(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, + 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(tui.EscapeCells(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 { + b.WriteString("\n" + tui.PlainRow(f.Path, f.Value, f.Source, strings.Join(f.Exceptions, "; "))) + } + for _, a := range p.Applied { + b.WriteString("\n" + tui.PlainRow("applied:"+a.Implementer, fmt.Sprint(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) +} diff --git a/internal/cloudpolicy/subject_test.go b/internal/cloudpolicy/subject_test.go new file mode 100644 index 0000000..7a7851f --- /dev/null +++ b/internal/cloudpolicy/subject_test.go @@ -0,0 +1,186 @@ +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(1) + 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) + // 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) + 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()} + // 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, "arjuns-mbp", nil) + require.NoError(t, err) + + 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) + 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 (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) + 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, "01KR0EKN6PMW0ZRFRN992H1PKX", decoded["id"]) + 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") + + 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/cloudpolicy/template.go b/internal/cloudpolicy/template.go new file mode 100644 index 0000000..d399308 --- /dev/null +++ b/internal/cloudpolicy/template.go @@ -0,0 +1,632 @@ +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" + 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/types/known/durationpb" + + "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 + + // 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. +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 +} + +// 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: +// 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): + 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() + for j := 0; j < list.Len(); j++ { + if err := w.listItem(list.Get(j).Message(), indent+2); err != nil { + return err + } + } + default: + if err := w.realField(fd, m.Get(fd), indent); err != nil { + return err + } + } + } + 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 { + 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, notePrefix) { + def := belowLayer{ + name: fmt.Sprintf("default policy, revision %d", w.def.Revision), + spec: w.def.Spec, + } + if owner == policyFullName { + return []belowLayer{def}, baseNote + } + return []belowLayer{{name: "base", spec: w.base}, def}, overrideNote +} + +// 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, + note notePrefix, +) 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 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 + } + 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, note); err != nil { + return err + } + } + return nil +} + +// 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, + path string, + indent int, + below []belowLayer, + note notePrefix, +) error { + value, hasValue := placeholderValue(fd) + now := note.label + ": " + note.notSet + for _, layer := range below { + if v, ok := valueAtPath(layer.spec, path); ok { + value, hasValue = v, true + _, human := formatFieldValue(fd, v) + now = fmt.Sprintf("%s: %s (%s)", note.label, human, layer.name) + break + } + } + lines := []string{documentCodec.key(fd) + ":"} + if hasValue { + var err error + if lines, err = fieldYAML(fd, value, true); err != nil { + return err + } + } + text := tui.EscapeLine(valueForm(fd) + ". " + now) + first := strings.Repeat(" ", indent) + "# " + lines[0] + if len(first)+len(" # ")+len(text) <= templateWidth { + w.lines = append(w.lines, first+" # "+text) + } else { + for _, line := range wrapWords(text, templateWidth-indent-len("# ")) { + w.comment(indent, line) + } + w.lines = append(w.lines, first) + } + for _, line := range lines[1:] { + w.comment(indent, line) + } + 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 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{} + 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}) + + ex := &templateWriter{example: true} + if err := ex.messageFields(example.ProtoReflect(), 0); 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 ex.lines { + 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 +} + +// 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{}{} + } + } + } + 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 +} + +// 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(key), documentCodec.encodeField(fd, v)) + text, err := marshalNode(node, "") + if err != nil { + return nil, err + } + return strings.Split(strings.TrimRight(string(text), "\n"), "\n"), nil +} + +// 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 of a scalar. +// Other fields get no example value. +func placeholderValue(fd protoreflect.FieldDescriptor) (protoreflect.Value, bool) { + if fd.IsList() || fd.IsMap() { + 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()), true + } + } + return protoreflect.Value{}, false + case protoreflect.MessageKind, protoreflect.GroupKind: + if fd.Message().FullName() == durationFullName { + return protoreflect.ValueOfMessage(durationpb.New(placeholderDuration).ProtoReflect()), true + } + return protoreflect.Value{}, false + default: + return fd.Default(), true + } +} + +// 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 +} + +// 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 +} + +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) + } + } + return true + }) + for _, fd := range empty { + m.Clear(fd) + } +} diff --git a/internal/cloudpolicy/template_test.go b/internal/cloudpolicy/template_test.go new file mode 100644 index 0000000..f1a860e --- /dev/null +++ b/internal/cloudpolicy/template_test.go @@ -0,0 +1,297 @@ +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" + 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" + "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. +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) + + // docs/cmd/policy-edit.md shows this document after the header. + want := `# base: + # package_admission: + # cooldown: + # 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: 7d +` + 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 # 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", + " # 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) + } + 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. Below this override: 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. Below this override: 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)) + }) + } +} + +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/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..179e48d --- /dev/null +++ b/internal/cmd/audit/list.go @@ -0,0 +1,167 @@ +package audit + +import ( + "context" + "fmt" + "strings" + "time" + + auditv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/audit/v1/auditv1grpc" + auditv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/audit/v1" + "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" +) + +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 +} + +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: --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 + } + _, 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. 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, or the 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 + after, before, err := duration.Window(in.Since, in.Until, now, "events") + if err != nil { + return nil, err + } + if after != nil { + filters.SetOccurredAfter(timestamppb.New(*after)) + set = true + } + if before != nil { + filters.SetOccurredBefore(timestamppb.New(*before)) + 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 +} diff --git a/internal/cmd/audit/list_test.go b/internal/cmd/audit/list_test.go new file mode 100644 index 0000000..1f6bf47 --- /dev/null +++ b/internal/cmd/audit/list_test.go @@ -0,0 +1,162 @@ +package audit + +import ( + "context" + "strings" + "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()) +} + +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/activity.go b/internal/cmd/endpoint/activity.go index 64ca865..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,12 +98,12 @@ 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") 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/cmd.go b/internal/cmd/endpoint/cmd.go index 4dbd98a..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, 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 the endpoints that report 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/inventory.go b/internal/cmd/endpoint/inventory.go index 363cf5e..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,12 +147,12 @@ 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") 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/label.go b/internal/cmd/endpoint/label.go new file mode 100644 index 0000000..a199586 --- /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. 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 +} + +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 0d0a1b6..3f5f471 100644 --- a/internal/cmd/endpoint/list.go +++ b/internal/cmd/endpoint/list.go @@ -4,25 +4,32 @@ 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/cli/internal/duration" + "github.com/safedep/cli/internal/tui" "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 +44,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 +54,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 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 { + return err + } client, err := a.ControlPlane() if err != nil { return err @@ -64,6 +79,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) @@ -74,12 +90,15 @@ 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.Uint32Var(&pageSize, "limit", 0, "page size; server default when 0") + 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, or the server default when 0") f.StringVar(&pageTokenFlag, "page-token", "", "continuation token from a prior response") return cmd } @@ -91,6 +110,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 +198,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,12 +235,10 @@ 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", - e.ID, e.Hostname, e.OS, e.Arch, strings.Join(capabilityNames(e.Capabilities), ","), - formatTime(e.LastSync), e.PMGBlockedEvents, e.InventoryEvents, - ) + 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") } @@ -224,12 +253,13 @@ 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"). - Rows(rows...). + Headers("ID", "Hostname", "OS/Arch", "Capabilities", "Last Sync", "Blocked", "Inventory", "Policy"). + 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")) @@ -366,3 +396,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/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/policy.go b/internal/cmd/endpoint/policy.go new file mode 100644 index 0000000..0d8b1c7 --- /dev/null +++ b/internal/cmd/endpoint/policy.go @@ -0,0 +1,79 @@ +package endpoint + +import ( + "context" + + 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" +) + +// 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{ + 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 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 + } + 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 this contract path and the paths below it, 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..763b3b6 --- /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("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{"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}, + {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/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/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_create.go b/internal/cmd/policy/change_create.go new file mode 100644 index 0000000..be2ca13 --- /dev/null +++ b/internal/cmd/policy/change_create.go @@ -0,0 +1,146 @@ +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" + clitui "github.com/safedep/cli/internal/tui" +) + +const ( + packageRulesKeepHead = "head" + packageRulesFromRevision = "revision" +) + +type changeCreateInput struct { + FromRevision uint64 + // 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 { + 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 + } + in.FromRevisionSet = cmd.Flags().Changed("from-revision") + 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 + } + 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", id) + tui.Info(" Publish it: safedep policy change publish %s", id) + 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, 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") + return cmd +} + +func validateChangeCreate(in changeCreateInput) error { + 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") + } + 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, mapRestoreError(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("Cannot preview change %s: %s", clitui.EscapeLine(id), clitui.EscapeLine(err.Error())) + return + } + reportLoosening(preview) +} diff --git a/internal/cmd/policy/change_edit.go b/internal/cmd/policy/change_edit.go new file mode 100644 index 0000000..4d78f30 --- /dev/null +++ b/internal/cmd/policy/change_edit.go @@ -0,0 +1,147 @@ +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 + } + 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") + return nil + } + if err != nil { + return err + } + 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 + }, + } + 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 +} + +// 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, +) (*changeEditResult, 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 + } + 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), defaultLayer(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 + }) + // 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 &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_list.go b/internal/cmd/policy/change_list.go new file mode 100644 index 0000000..74419d0 --- /dev/null +++ b/internal/cmd/policy/change_list.go @@ -0,0 +1,152 @@ +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 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. 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 := 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, or the 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(), cloudpolicy.EmptyDash(c.Author), humanTimeCell(c.updatedAt, now), + }) + } + t := table.New(). + Title("Policy changes"). + Headers("CHANGE", "TITLE", "STATE", "BASE REV", "EDITS", "AUTHOR", "UPDATED"). + 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), cloudpolicy.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 { + 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 new file mode 100644 index 0000000..1c7c52c --- /dev/null +++ b/internal/cmd/policy/change_ops.go @@ -0,0 +1,97 @@ +package policy + +import ( + "context" + "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 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: you can change only an open 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 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 { + 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 + } + id := clitui.EscapeLine(change.GetChangeId()) + tui.Success("change %s now has base revision %d%sreview it: safedep policy change show %s", + id, change.GetBaseRevision(), sep, id) + 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", clitui.EscapeLine(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 +} diff --git a/internal/cmd/policy/change_preview.go b/internal/cmd/policy/change_preview.go new file mode 100644 index 0000000..2387fa2 --- /dev/null +++ b/internal/cmd/policy/change_preview.go @@ -0,0 +1,237 @@ +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" + "google.golang.org/protobuf/encoding/protojson" + + "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 + // 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 { + 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, overrideChangeItem(c)) + } + 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 +} + +// 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 { + 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{} + if err := protojson.Unmarshal([]byte(value), selector); err != nil { + return value + } + 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 { + 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..1a260bc --- /dev/null +++ b/internal/cmd/policy/change_publish.go @@ -0,0 +1,180 @@ +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, 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 +} + +// 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) { + 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 + } + 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 + } + 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)) + } +} + +// 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") + 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_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 new file mode 100644 index 0000000..e983c98 --- /dev/null +++ b/internal/cmd/policy/change_show.go @@ -0,0 +1,164 @@ +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/tui" +) + +const ( + overrideKindPrefix = "OVERRIDE_CHANGE_KIND_" + warningCodePrefix = "PREVIEW_WARNING_CODE_" +) + +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 (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 \"%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)) + } + 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", cloudpolicy.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.whatCell(), it.changeCell(), cloudpolicy.EmptyDash(it.Direction)}) + } + sections = append(sections, table.New(). + Title("What changes"). + Headers("WHERE", "WHAT", "OLD -> NEW", "DIRECTION"). + Rows(tui.EscapeCells(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") +} diff --git a/internal/cmd/policy/change_test.go b/internal/cmd/policy/change_test.go new file mode 100644 index 0000000..c86e3fe --- /dev/null +++ b/internal/cmd/policy/change_test.go @@ -0,0 +1,446 @@ +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`) +} + +// 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") + field.SetLayer(recordv1.Layer_LAYER_OVERRIDE) + field.SetOverrideName("payments") + // 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{} + 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_LOOSENS) + + selector := &policyv1.OverrideChange{} + selector.SetOverrideName("payments") + selector.SetKind(policyv1.OverrideChangeKind_OVERRIDE_CHANGE_KIND_SELECTOR) + // 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) + + 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(3) + + 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{cooldownCoverage, 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 +} + +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", + "custom/team=pay -> custom/criticality=high", + "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) + } + b, err := got.RenderJSON() + require.NoError(t, err) + assert.Contains(t, string(b), `"direction": "LOOSENS"`) + 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, "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) { + 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_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) { + 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", "", refuseConfirm(t)) + 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", "", refuseConfirm(t)) + assert.ErrorContains(t, err, "change 17 is deleted: you can change only an open 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")}} + 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"}}), + `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())) +} + +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)) + }) + } +} + +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/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/cmd.go b/internal/cmd/policy/cmd.go new file mode 100644 index 0000000..b896e2a --- /dev/null +++ b/internal/cmd/policy/cmd.go @@ -0,0 +1,68 @@ +// Package policy registers the `safedep policy` command tree, the CLI for +// policy management in SafeDep Cloud: the policy settings document, policy +// changes, policy revisions, package rules and the decision log. 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)) + + 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..84e66b6 --- /dev/null +++ b/internal/cmd/policy/decision_list.go @@ -0,0 +1,313 @@ +package policy + +import ( + "context" + "fmt" + "strings" + "time" + "unicode/utf8" + + 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/log" + "github.com/spf13/cobra" + "google.golang.org/protobuf/proto" + "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_" + + // 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 { + 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 +} + +// 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 + query *decisionQuery + ) + 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 + } + var err error + query, err = newDecisionQuery(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()), query) + 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, or the 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 +} + +// 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)) + } + return nil +} + +// 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{} + 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)) + } + if before != nil { + filters.SetDecidedBefore(timestamppb.New(*before)) + } + 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)) + } + 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)) + } + if in.Revision > 0 { + filters.SetRevision(in.Revision) + } + if in.Package != "" { + pkg, err := parseDecisionPackage(in.Package) + if err != nil { + return nil, err + } + filters.SetPackage(pkg) + } + // 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) + }{ + {"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 == "" { + continue + } + if err := checkLength(text.flag, text.value, text.limit); err != nil { + return nil, err + } + text.apply(text.value) + } + 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 +// 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, + q *decisionQuery, +) (*decisionListResult, error) { + var snapshot *policyv1.Policy + if q.override != "" { + _, p, err := readPolicyAt(ctx, client, q.revision) + if err != nil { + return nil, err + } + snapshot = p + id, err := resolveOverrideID(p, q.override) + if err != nil { + return nil, err + } + q.filters.SetOverrideId(id) + } + req := &policyv1.ListPolicyDecisionsRequest{} + 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 { + return nil, mapDecisionListError(err) + } + + names := map[string]string{} + if citesOverride(res.GetDecisions()) { + if snapshot == nil { + _, 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. + 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 +} + +// 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.GetOverrideId(), nil + } + for _, o := range p.GetOverrides() { + if o.GetOverrideId() == ref { + 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 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 new file mode 100644 index 0000000..f683c69 --- /dev/null +++ b/internal/cmd/policy/decision_test.go @@ -0,0 +1,713 @@ +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, 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, 1, "", "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 TestNewDecisionQuery(t *testing.T) { + day := 24 * time.Hour + tests := []struct { + name string + in decisionListInput + check func(*testing.T, *policyv1.ListPolicyDecisionsRequest_Filters) + wantErr string + }{ + { + 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 waits for the policy read", + in: decisionListInput{Override: "payments"}, + check: func(t *testing.T, f *policyv1.ListPolicyDecisionsRequest_Filters) { + assert.False(t, f.HasOverrideId()) + }, + }, + { + 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: "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) { + 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) + 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.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, listQuery(t, decisionListInput{Rule: "r_9c1x4kq7dm"})) + 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\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") +} + +// 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, 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.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"})) + require.NoError(t, err) + table := got.RenderTable() + 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") +} + +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, 1, "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, listQuery(t, tt.in)) + 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_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, 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() + 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, 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) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(nil, status.Error(codes.Unavailable, "down")) + + got, err := runDecisionList(context.Background(), client, listQuery(t, decisionListInput{})) + 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, 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) + + 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") + 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, 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") + 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, 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() + 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, listQuery(t, decisionListInput{})) + 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, listQuery(t, decisionListInput{})) + 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..e07ea33 --- /dev/null +++ b/internal/cmd/policy/decision_view.go @@ -0,0 +1,266 @@ +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) + default: + parts = append(parts, fixedRuleText(v.Tool)) + } + 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)) +} + +// 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 { + 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/edit.go b/internal/cmd/policy/edit.go new file mode 100644 index 0000000..25fc073 --- /dev/null +++ b/internal/cmd/policy/edit.go @@ -0,0 +1,159 @@ +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" + + "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" +) + +// 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 +} + +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 + } + 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 + }, + } + 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) { + 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 + } + 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, defaultLayer(head), 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 mapChangeError("create", "", 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.", + "", + "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.", + "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 new file mode 100644 index 0000000..e19d8cc --- /dev/null +++ b/internal/cmd/policy/edit_test.go @@ -0,0 +1,563 @@ +package policy + +import ( + "context" + "errors" + "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" + "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" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/durationpb" + + "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 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"), sameAs("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"), 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")) + } + 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"), sameAs("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"), sameAs("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"), sameAs("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{ + // 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"}) + 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 1):") + 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) + }) + } +} + +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("\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") + + // The template test in internal/cloudpolicy owns the body of the document. + require.Len(t, ed.seen, 1) + 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) { + 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") +} + +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/editor.go b/internal/cmd/policy/editor.go new file mode 100644 index 0000000..3b7d885 --- /dev/null +++ b/internal/cmd/policy/editor.go @@ -0,0 +1,200 @@ +package policy + +import ( + "bytes" + "context" + "errors" + "fmt" + "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 ( + 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} } + +// 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) + 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 +// 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, + 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) + } + 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 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")) + } + + err = save(saved) + if err == nil { + if rmErr := os.Remove(path); rmErr != nil { + tui.Warning("cannot 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 +} + +// 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 command did not save the policy edit: "+cause.Error(), "" + if ue, ok := usefulerror.AsUsefulError(cause); ok { + code, human = ue.Code(), "The command did not save the policy edit: "+ue.HumanError() + if ue.Help() != "" { + help = ue.Help() + ". " + } + } + return usefulerror.NewUsefulError(). + 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 new file mode 100644 index 0000000..909177d --- /dev/null +++ b/internal/cmd/policy/errors.go @@ -0,0 +1,180 @@ +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/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 { + 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) +} + +// 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 { + cause := fmt.Errorf("policy change %s: %w", op, 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), + 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: + if changeID == "" { + return cause + } + 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) + 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. The server refuses a revision above head as an +// invalid restore.from_revision. +func mapRestoreError(fromRevision uint64, err error) error { + 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", + 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) + 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) + case codes.FailedPrecondition: + return failedPreconditionError(st, "List the rules: safedep policy rule list", cause) + } + } + 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 +} diff --git a/internal/cmd/policy/fixtures_test.go b/internal/cmd/policy/fixtures_test.go new file mode 100644 index 0000000..a434303 --- /dev/null +++ b/internal/cmd/policy/fixtures_test.go @@ -0,0 +1,108 @@ +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, "custom/environment", "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 { + // 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(1) + def.SetSpec(defaultSpec) + 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..6c0ed1f --- /dev/null +++ b/internal/cmd/policy/get.go @@ -0,0 +1,129 @@ +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" + clitui "github.com/safedep/cli/internal/tui" +) + +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, or 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}, "", " ") +} + +// 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 { + for len(b) > 0 && b[len(b)-1] == '\n' { + b = b[:len(b)-1] + } + return b +} diff --git a/internal/cmd/policy/publish_test.go b/internal/cmd/policy/publish_test.go new file mode 100644 index 0000000..cf053b3 --- /dev/null +++ b/internal/cmd/policy/publish_test.go @@ -0,0 +1,149 @@ +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(withEndpointLabelWarning(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 package_admission.cooldown.min_age (- -> 7d) 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") +} + +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(withEndpointLabelWarning(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/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/revision.go b/internal/cmd/policy/revision.go new file mode 100644 index 0000000..46abedb --- /dev/null +++ b/internal/cmd/policy/revision.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/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" + clitui "github.com/safedep/cli/internal/tui" +) + +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. 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() + 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, or the 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), 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(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) + } + 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 { + b.WriteString("\n" + clitui.PlainRow(fmt.Sprint(rev.Revision), rev.Published, rev.Author, rev.Source, + rev.Direction, rev.ChangeID, rev.Message)) + } + return b.String() +} 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/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..08a1561 --- /dev/null +++ b/internal/cmd/policy/rule_create.go @@ -0,0 +1,180 @@ +package policy + +import ( + "context" + "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" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" + clitui "github.com/safedep/cli/internal/tui" +) + +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, or - for stdin") + f.StringVar(&in.Vers, "vers", "", "a version range, as in '>=1.2.0' or 'vers:npm/>=1.2.0|<2.0.0'") + f.StringSliceVar(&in.Scopes, "scope", nil, + "with --trust: a verdict to waive, one of "+strings.Join(trustScopeTokens(), ", ")+", or all (repeatable)") + 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", "", "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 +} + +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.", 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), clitui.EscapeLine(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", 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 := cloudpolicy.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.") + reportLaggingEndpoints(res.Revision) +} diff --git a/internal/cmd/policy/rule_delete.go b/internal/cmd/policy/rule_delete.go new file mode 100644 index 0000000..f3dba42 --- /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, or a message that the server writes when 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 new file mode 100644 index 0000000..546584f --- /dev/null +++ b/internal/cmd/policy/rule_list.go @@ -0,0 +1,191 @@ +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/duration" + "github.com/safedep/cli/internal/paging" + "github.com/safedep/cli/internal/tui" +) + +const baseAttachment = "base" + +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. 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 := 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, or the server default when 0") + f.StringVar(&in.PageToken, "page-token", "", "continuation token from a prior response") + 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 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 != "" { + p, err := loadSnapshot() + if err != nil { + return nil, err + } + o, err := findOverride(p, in.Override) + if err != nil { + return nil, err + } + overrideID = o.GetOverrideId() + } + 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) + } + + var names map[string]string + if in.Override != "" || attachesToOverride(res.GetRules()) { + p, err := loadSnapshot() + if err != nil { + return nil, err + } + names = overrideNames(p) + } + 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, 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(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), cloudpolicy.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 { + 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_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 new file mode 100644 index 0000000..2049db7 --- /dev/null +++ b/internal/cmd/policy/rule_test.go @@ -0,0 +1,482 @@ +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", fixedNow) + 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) +} + +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()) +} + +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) +} diff --git a/internal/cmd/policy/rule_update.go b/internal/cmd/policy/rule_update.go new file mode 100644 index 0000000..4986504 --- /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, or a message that the server writes when 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/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/settings.go b/internal/cmd/policy/settings.go new file mode 100644 index 0000000..724b874 --- /dev/null +++ b/internal/cmd/policy/settings.go @@ -0,0 +1,275 @@ +package policy + +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" + "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, + def cloudpolicy.DefaultLayer, + 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, def, 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(), + } +} + +// 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 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) { + 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, + start *policyv1.Policy, + header string, + def cloudpolicy.DefaultLayer, + commit func(*policyv1.Policy) error, +) error { + text, err := cloudpolicy.MarshalPolicyTemplate(start, header, def) + if err != nil { + return err + } + unchanged := func(saved []byte) bool { + edited, err := decodeDocument(saved, start) + return err == nil && sameSettings(edited, start) + } + return editLoop(ctx, open, text, unchanged, func(saved []byte) error { + edited, err := decodeDocument(saved, start) + if err != nil { + return retryable(err) + } + if err := checkEditedSettings(start, edited); err != nil { + return retryable(err) + } + warnComments(saved, text) + return commit(edited) + }) +} + +func editOneOverride( + ctx context.Context, + open openEditorFunc, + start *policyv1.Policy, + header string, + def cloudpolicy.DefaultLayer, + overrideName string, + commit func(*policyv1.Policy) error, +) error { + current, err := findOverride(start, overrideName) + if err != nil { + return err + } + text, err := cloudpolicy.MarshalOverrideTemplate(current, header, def, start.GetBase()) + if err != nil { + return err + } + unchanged := func(saved []byte) bool { + edited, err := cloudpolicy.UnmarshalOverride(saved) + return err == nil && sameSettings(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, text) + 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{}{} + } + 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", + clitui.EscapeLine(o.GetName()), clitui.EscapeLine(o.GetOverrideId())) + } + } + 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{} + 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, written []byte) { + if cloudpolicy.HasUserComments(saved, written) { + 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/policy/show.go b/internal/cmd/policy/show.go new file mode 100644 index 0000000..3e53a58 --- /dev/null +++ b/internal/cmd/policy/show.go @@ -0,0 +1,200 @@ +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" + clitui "github.com/safedep/cli/internal/tui" +) + +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, cloudpolicy.EmptyDash(o.Description), + }) + } + overrides := table.New(). + Title("Overrides (priority, highest first)"). + Headers("PRIORITY", "NAME", "SELECTOR", "EXPIRES", "DESCRIPTION"). + 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 +} + +func (r *showResult) RenderPlain() string { + var b strings.Builder + 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) + 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 { + 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 new file mode 100644 index 0000000..a3b0089 --- /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, "custom/environment=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 1 · scan_gate.fail_on: high · scan_gate.fail_on_attacks: fail", + "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", "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\tcustom/environment=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 - id: ov_pay\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..e72c795 --- /dev/null +++ b/internal/cmd/policy/view.go @@ -0,0 +1,165 @@ +package policy + +import ( + "context" + "fmt" + "slices" + "sort" + "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/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 := cloudpolicy.TimeOf(r.GetPublishedAt()) + return &revisionView{ + Revision: r.GetRevision(), + ChangeID: r.GetChangeId(), + Author: cloudpolicy.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, "\""+tui.EscapeLine(r.Message)+"\"") + } + return strings.Join(parts, sep) +} + +func directionToken(d policyv1.ChangeDirection) string { + return strings.ToUpper(tui.EnumToken(d.String(), directionPrefix)) +} + +func humanTimeCell(t *time.Time, now time.Time) string { + if t == nil { + return "-" + } + return humanize.Time(*t, now) +} + +// 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 := cloudpolicy.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/project/cmd.go b/internal/cmd/project/cmd.go index a558388..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 " + - "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", @@ -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..4b2a7b5 --- /dev/null +++ b/internal/cmd/project/inventory.go @@ -0,0 +1,191 @@ +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 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. 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 := 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, 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, or the 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 (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(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))) + 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 { + 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() +} + +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..6c7cd07 --- /dev/null +++ b/internal/cmd/project/label.go @@ -0,0 +1,170 @@ +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 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 +} + +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/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 } diff --git a/internal/cmd/project/policy.go b/internal/cmd/project/policy.go new file mode 100644 index 0000000..03d709b --- /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 " + + "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 { + 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 this contract path and the paths below it, 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..ca618bd --- /dev/null +++ b/internal/cmd/project/policy_test.go @@ -0,0 +1,244 @@ +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/owner=acme", Sources: []string{"github", "bitbucket"}, PageSize: 10, + }) + require.NoError(t, err) + f := req.GetFilterV2() + 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()) + 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/owner": "acme", "custom/team": "pay"})), nil + }} + 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/owner=acme"}, got.Projects[0].Labels) + + table := got.RenderTable() + assert.Contains(t, table, "acme/payments-api") + 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) { + 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/owner=acme"}, + }) + 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"`) +} + +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/resolver.go b/internal/cmd/project/resolver.go index 6975b69..c77cbaa 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..b69a295 --- /dev/null +++ b/internal/cmd/project/show.go @@ -0,0 +1,184 @@ +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" + clitui "github.com/safedep/cli/internal/tui" +) + +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("Cannot read the policy of project %s: %s", clitui.EscapeLine(name), clitui.EscapeLine(err.Error())) + 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()) + } + rows := [][2]string{ + {"Project", p.Name}, + {"ID", p.ID}, + {"Source", source}, + } + 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}, + }...) + return cloudpolicy.KeyValues(rows) + "\n\nPolicy of each field: safedep project policy show " + clitui.EscapeLine(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{ + 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/safedep.go b/internal/cmd/safedep.go index cc9c94d..f96ac81 100644 --- a/internal/cmd/safedep.go +++ b/internal/cmd/safedep.go @@ -2,10 +2,12 @@ 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" "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" @@ -19,9 +21,11 @@ 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) + 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..f0bdb54 100644 --- a/internal/cmd/subscription/service.go +++ b/internal/cmd/subscription/service.go @@ -12,6 +12,7 @@ import ( 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/tui" + "github.com/safedep/dry/usefulerror" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -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 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: @@ -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 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: @@ -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/duration/window.go b/internal/duration/window.go new file mode 100644 index 0000000..76d9ddc --- /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. 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 "+noun+" 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..1b1a015 --- /dev/null +++ b/internal/duration/window_test.go @@ -0,0 +1,49 @@ +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, "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) + assert.Equal(t, tt.wantAfter, after) + assert.Equal(t, tt.wantBefore, before) + }) + } +} 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"`) +} 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"}})) +}