diff --git a/docs/cmd/policy-rule-delete.md b/docs/cmd/policy-rule-delete.md index 5402e44..d207eab 100644 --- a/docs/cmd/policy-rule-delete.md +++ b/docs/cmd/policy-rule-delete.md @@ -6,7 +6,7 @@ The rule stays in the history of the revisions. ## Synopsis ``` -safedep policy rule delete RULE --reason TEXT [-m MESSAGE] +safedep policy rule delete RULE --reason TEXT [-m MESSAGE] [--yes] ``` ## Flags @@ -15,6 +15,7 @@ safedep policy rule delete RULE --reason TEXT [-m MESSAGE] |------|-------------| | `--reason ` | Why the rule goes. Required. | | `-m`, `--message ` | The publish message. | +| `-y`, `--yes` | Delete a block entry with no prompt. | ## Examples @@ -26,7 +27,12 @@ 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. +The delete of a block entry loosens the policy, so the command asks first. With no +terminal, pass `--yes`. The delete of a trust entry does not ask. + +``` +Rule r_77e blocks pkg:npm/left-pad. The delete loosens the policy. Delete it? [y/N]: +``` ## Authentication diff --git a/docs/cmd/project-show.md b/docs/cmd/project-show.md index e1ead42..34f2476 100644 --- a/docs/cmd/project-show.md +++ b/docs/cmd/project-show.md @@ -1,14 +1,20 @@ # 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. +Show one project by its exact name or by its ID: 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] +safedep project show (PROJECT_NAME | --project-id ID) [--output table|plain|json] ``` +## Flags + +| Flag | Description | +|------|-------------| +| `--project-id ` | The project ID instead of a name. Use it when two projects have the same name. | + ## Examples ```bash @@ -33,7 +39,8 @@ 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. +When two projects have the name, the command lists their IDs. Run it again with +`--project-id` and one of them. ## Authentication diff --git a/internal/cmd/audit/list.go b/internal/cmd/audit/list.go index 179e48d..7803e15 100644 --- a/internal/cmd/audit/list.go +++ b/internal/cmd/audit/list.go @@ -18,6 +18,7 @@ import ( "github.com/safedep/cli/internal/app" "github.com/safedep/cli/internal/duration" "github.com/safedep/cli/internal/paging" + clitui "github.com/safedep/cli/internal/tui" ) const resultPrefix = "AUDIT_RESULT_" @@ -154,14 +155,32 @@ func runList(ctx context.Context, client eventLister, in listInput, now time.Tim return out, nil } +// serviceFailedPrefix is the text that the server puts before the message of +// a service error. It names no filter and no fix. +const serviceFailedPrefix = "service execution failed: " + func mapListError(err error) error { cause := fmt.Errorf("audit event list: %w", err) - if st, ok := status.FromError(err); ok && st.Code() == codes.PermissionDenied { + st, ok := status.FromError(err) + if !ok { + return cause + } + switch st.Code() { + case 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) + case codes.InvalidArgument: + // The generic conversion shows only "Invalid request", and the user + // cannot find the flag to fix. + reason := strings.TrimPrefix(st.Message(), serviceFailedPrefix) + return usefulerror.NewUsefulError(). + WithCode(usefulerror.ErrBadRequest). + WithHumanError("The server refused the request: " + clitui.EscapeLine(reason)). + WithHelp("Correct the flag that the message names. See the flags: safedep audit event list --help"). + Wrap(cause) } return cause } diff --git a/internal/cmd/audit/list_test.go b/internal/cmd/audit/list_test.go index 1f6bf47..3104a55 100644 --- a/internal/cmd/audit/list_test.go +++ b/internal/cmd/audit/list_test.go @@ -142,6 +142,17 @@ func TestRunList_MemberIsDenied(t *testing.T) { assert.Equal(t, "Only an Admin can read the audit log", ue.HumanError()) } +func TestRunList_ShowsWhyTheServerRefusedTheRequest(t *testing.T) { + client := &fakeLister{err: status.Error(codes.InvalidArgument, + `service execution failed: invalid audit event list request: audit: unknown resource kind: "bogus"`)} + _, err := runList(context.Background(), client, listInput{Resource: "bogus"}, now) + ue, ok := usefulerror.AsUsefulError(err) + require.True(t, ok) + assert.Equal(t, usefulerror.ErrBadRequest, ue.Code()) + assert.Equal(t, `The server refused the request: invalid audit event list request: audit: unknown resource kind: "bogus"`, ue.HumanError()) + assert.Equal(t, "Correct the flag that the message names. See the flags: safedep audit event list --help", ue.Help()) +} + func TestRender_EscapesServerText(t *testing.T) { e := auditEvent() e.GetActor().SetDisplayName("mallory\x1b]0;owned\x07") diff --git a/internal/cmd/policy/change_publish.go b/internal/cmd/policy/change_publish.go index 217918a..bae8a95 100644 --- a/internal/cmd/policy/change_publish.go +++ b/internal/cmd/policy/change_publish.go @@ -46,7 +46,9 @@ func changePublishCmd(a *app.App) *cobra.Command { return err } rev, err := runChangePublish(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), - args[0], message, publishConfirm(yes, clitui.IsInteractive())) + args[0], message, publishConfirm(yes, clitui.IsInteractive(), + "the change loosens the policy, and no terminal is present to confirm it", + "Review it with safedep policy change show, then pass --yes to publish it")) if errors.Is(err, errPublishCancelled) { tui.Info("Nothing is published") return nil @@ -65,15 +67,13 @@ func changePublishCmd(a *app.App) *cobra.Command { // 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 { +func publishConfirm(yes, interactive bool, noTerminal, help string) 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 false, newPolicyError(usefulerror.ErrBadRequest, noTerminal, help, errors.New(noTerminal)) } return prompt.Confirm(question, false) } diff --git a/internal/cmd/policy/change_show.go b/internal/cmd/policy/change_show.go index e983c98..0811e13 100644 --- a/internal/cmd/policy/change_show.go +++ b/internal/cmd/policy/change_show.go @@ -132,6 +132,20 @@ func (r *changeShowResult) headline() string { return strings.Join(parts, sep) } +// settingsNote says where the edits of the settings are. The server previews +// only an open change, so a closed change that edited the settings has no +// field rows. It is empty when the rows show the edits. +func (r *changeShowResult) settingsNote() string { + c := r.Change + if r.Preview != nil || !c.EditsSettings { + return "" + } + if c.PublishedRevision > 0 { + return fmt.Sprintf("The change edited the policy settings. See them: safedep policy revision show %d", c.PublishedRevision) + } + return "The change edited the policy settings. Only an open change has a preview of them." +} + func (r *changeShowResult) RenderTable() string { now := time.Now() sections := []string{r.headline()} @@ -149,12 +163,20 @@ func (r *changeShowResult) RenderTable() string { for _, it := range items { rows = append(rows, []string{it.Where, it.whatCell(), it.changeCell(), cloudpolicy.EmptyDash(it.Direction)}) } + note := r.settingsNote() + empty := note + if empty == "" { + empty = "The change edits nothing." + } sections = append(sections, table.New(). Title("What changes"). Headers("WHERE", "WHAT", "OLD -> NEW", "DIRECTION"). Rows(tui.EscapeCells(rows)...). - EmptyMessage("The change edits nothing."). + EmptyMessage(empty). Render()) + if note != "" && len(rows) > 0 { + sections = append(sections, note) + } if p := r.Preview; p != nil { sections = append(sections, r.impactTable(p), r.warningTable(p), diff --git a/internal/cmd/policy/change_test.go b/internal/cmd/policy/change_test.go index 5d1eb4e..bddaa07 100644 --- a/internal/cmd/policy/change_test.go +++ b/internal/cmd/policy/change_test.go @@ -293,6 +293,53 @@ func TestRunChangeShow_PublishedChangeHasNoPreview(t *testing.T) { assert.Contains(t, got.RenderTable(), "published as rev 47") } +func TestRunChangeShow_ClosedChangeThatEditedTheSettings(t *testing.T) { + tests := []struct { + name string + state policyv1.PolicyChangeState + published uint64 + settings bool + rules bool + want string + }{ + {"published", policyv1.PolicyChangeState_POLICY_CHANGE_STATE_PUBLISHED, 47, true, false, + "The change edited the policy settings. See them: safedep policy revision show 47"}, + {"published with rule operations", policyv1.PolicyChangeState_POLICY_CHANGE_STATE_PUBLISHED, 47, true, true, + "The change edited the policy settings. See them: safedep policy revision show 47"}, + {"deleted", policyv1.PolicyChangeState_POLICY_CHANGE_STATE_DELETED, 0, true, false, + "Only an open change has a preview of them."}, + {"no edit", policyv1.PolicyChangeState_POLICY_CHANGE_STATE_DELETED, 0, false, false, + "The change edits nothing."}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + c := openChange("17") + c.SetState(tt.state) + c.SetPublishedRevision(tt.published) + if tt.settings { + c.SetSettings(headPolicy()) + } + if tt.rules { + 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) + table := got.RenderTable() + assert.Contains(t, table, tt.want) + if tt.rules { + assert.Contains(t, table, "r_80b") + } + }) + } +} + func TestRunChangePublish_Errors(t *testing.T) { tests := []struct { name string @@ -380,6 +427,17 @@ func TestRunChangeDelete(t *testing.T) { require.NoError(t, runChangeDelete(context.Background(), client, "19")) } +func TestRunChangeDelete_ChangeThatIsNotOpen(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().DeletePolicyChange(mock.Anything, mock.Anything). + Return(nil, status.Error(codes.FailedPrecondition, "policy change 19 is not open")) + err := runChangeDelete(context.Background(), client, "19") + ue, ok := usefulerror.AsUsefulError(err) + require.True(t, ok) + assert.Equal(t, "The server refused the request: policy change 19 is not open", ue.HumanError()) + assert.Equal(t, "List the open changes: safedep policy change list --state open", ue.Help()) +} + func TestRunChangeEdit_UpdatesWithTheEtag(t *testing.T) { client := mocks.NewPolicyServiceClientMock(t) c := openChange("18") diff --git a/internal/cmd/policy/errors.go b/internal/cmd/policy/errors.go index ebf7ef9..051238f 100644 --- a/internal/cmd/policy/errors.go +++ b/internal/cmd/policy/errors.go @@ -287,7 +287,7 @@ func mapChangeError(op, changeID string, err error) error { "Ask an Admin of the tenant to do it", cause) case codes.FailedPrecondition: - return failedPreconditionError(err, changePreconditionHelp(changeID), cause) + return failedPreconditionError(err, changePreconditionHelp(op, changeID), cause) case codes.InvalidArgument: return invalidArgumentError(err, "Correct the values and run the command again", cause) case codes.AlreadyExists: @@ -300,7 +300,11 @@ func mapChangeError(op, changeID string, err error) error { // 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 { +func changePreconditionHelp(op, changeID string) string { + // A delete has one refusal: the change is not open. + if op == "delete" { + return "List the open changes: safedep policy change list --state open" + } review := "Review the change: safedep policy change show" if changeID != "" { review += " " + changeID @@ -317,14 +321,28 @@ func mapRestoreError(fromRevision uint64, err error) error { 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 revisionNotFoundError(fromRevision, fmt.Errorf("policy change create: %w", err)) } return mapChangeError("create", "", err) } +// mapRevisionError gives the recovery for a read of a policy revision that +// does not exist. +func mapRevisionError(op string, revision uint64, err error) error { + cause := fmt.Errorf("%s: %w", op, err) + if st, ok := status.FromError(err); ok && st.Code() == codes.NotFound { + return revisionNotFoundError(revision, cause) + } + return cause +} + +func revisionNotFoundError(revision uint64, cause error) error { + return newPolicyError(usefulerror.ErrNotFound, + fmt.Sprintf("Policy revision %d does not exist", revision), + "List the revisions: safedep policy revision list", + cause) +} + // mapRuleError gives the recovery for the errors of a package rule RPC. func mapRuleError(op, ruleID string, err error) error { cause := fmt.Errorf("package rule %s: %w", op, err) diff --git a/internal/cmd/policy/get.go b/internal/cmd/policy/get.go index 6c0ed1f..fe7fa9e 100644 --- a/internal/cmd/policy/get.go +++ b/internal/cmd/policy/get.go @@ -91,7 +91,7 @@ func readPolicyAt( 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 0, nil, mapRevisionError(fmt.Sprintf("policy: get revision %d", revision), revision, err) } return revision, res.GetPolicy(), nil } diff --git a/internal/cmd/policy/publish_test.go b/internal/cmd/policy/publish_test.go index bc67e48..dfd4cc6 100644 --- a/internal/cmd/policy/publish_test.go +++ b/internal/cmd/policy/publish_test.go @@ -102,11 +102,11 @@ func TestRunChangePublish_LooseningThatTheUserRefuses(t *testing.T) { } func TestPublishConfirm(t *testing.T) { - ok, err := publishConfirm(true, false)("q") + ok, err := publishConfirm(true, false, "", "")("q") require.NoError(t, err) assert.True(t, ok, "--yes confirms with no terminal") - _, err = publishConfirm(false, false)("q") + _, err = publishConfirm(false, false, "no terminal is present to confirm it", "pass --yes")("q") require.Error(t, err) ue, isUseful := usefulerror.AsUsefulError(err) require.True(t, isUseful) diff --git a/internal/cmd/policy/revision_show.go b/internal/cmd/policy/revision_show.go index 3a24387..5608454 100644 --- a/internal/cmd/policy/revision_show.go +++ b/internal/cmd/policy/revision_show.go @@ -62,7 +62,7 @@ func runRevisionShow(ctx context.Context, client policyv1grpc.PolicyServiceClien req.SetRevision(revision) res, err := client.GetPolicyRevision(ctx, req) if err != nil { - return nil, fmt.Errorf("policy revision show: %w", err) + return nil, mapRevisionError("policy revision show", revision, err) } doc, err := cloudpolicy.PolicyMap(res.GetPolicy()) if err != nil { diff --git a/internal/cmd/policy/revision_test.go b/internal/cmd/policy/revision_test.go index 6510739..532c305 100644 --- a/internal/cmd/policy/revision_test.go +++ b/internal/cmd/policy/revision_test.go @@ -5,9 +5,12 @@ import ( "testing" 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" ) @@ -48,6 +51,23 @@ func TestRunRevisionShow(t *testing.T) { assert.Contains(t, string(b), `"change_id": "18"`) } +func TestReadRevision_NotFound(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicyRevision(mock.Anything, mock.Anything). + Return(nil, status.Error(codes.NotFound, "policy revision 99 not found")) + + _, err := runRevisionShow(context.Background(), client, 99) + 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()) + + _, err = runGet(context.Background(), client, getInput{Revision: 99}, "") + ue, ok = usefulerror.AsUsefulError(err) + require.True(t, ok) + assert.Equal(t, "Policy revision 99 does not exist", ue.HumanError()) +} + func TestParseRevision(t *testing.T) { n, err := parseRevision("47") require.NoError(t, err) diff --git a/internal/cmd/policy/rule_delete.go b/internal/cmd/policy/rule_delete.go index f3dba42..99203cf 100644 --- a/internal/cmd/policy/rule_delete.go +++ b/internal/cmd/policy/rule_delete.go @@ -3,9 +3,11 @@ package policy import ( "context" "errors" + "fmt" "strings" 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" @@ -16,12 +18,16 @@ import ( ) func ruleDeleteCmd(a *app.App) *cobra.Command { - var reason, message string + var ( + reason, message string + yes bool + ) 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.", + "stays in the history of the revisions. The delete of a block entry loosens the policy, so it " + + "needs a confirmation: the command asks in a terminal, and needs --yes when no terminal is present.", Args: func(cmd *cobra.Command, args []string) error { if err := cobra.ExactArgs(1)(cmd, args); err != nil { return err @@ -36,7 +42,17 @@ func ruleDeleteCmd(a *app.App) *cobra.Command { if err != nil { return err } - rev, err := runRuleDelete(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), args[0], reason, message) + var confirm confirmFunc + if !yes { + confirm = publishConfirm(false, clitui.IsInteractive(), + "the delete of a block entry loosens the policy, and no terminal is present to confirm it", + "Review it with safedep policy rule show, then pass --yes to delete it") + } + rev, err := runRuleDelete(cmd.Context(), cloudpolicy.NewPolicyClient(client.Connection()), args[0], reason, message, confirm) + if errors.Is(err, errPublishCancelled) { + tui.Info("Nothing is deleted") + return nil + } if err != nil { return err } @@ -46,10 +62,24 @@ func ruleDeleteCmd(a *app.App) *cobra.Command { } cmd.Flags().StringVar(&reason, "reason", "", "why the rule goes (required)") cmd.Flags().StringVarP(&message, "message", "m", "", "the publish message, or a message that the server writes when empty") + cmd.Flags().BoolVarP(&yes, "yes", "y", false, "delete a block entry with no prompt") return cmd } -func runRuleDelete(ctx context.Context, client policyv1grpc.PolicyServiceClient, id, reason, message string) (uint64, error) { +// runRuleDelete reads the rule first, because only the delete of a block +// entry loosens the policy and needs a confirmation. A nil confirm means that +// the user gave --yes, so the read has no use. +func runRuleDelete( + ctx context.Context, + client policyv1grpc.PolicyServiceClient, + id, reason, message string, + confirm confirmFunc, +) (uint64, error) { + if confirm != nil { + if err := confirmBlockDelete(ctx, client, id, confirm); err != nil { + return 0, err + } + } del := &policyv1.PackageRuleDelete{} del.SetRuleId(id) del.SetReason(reason) @@ -62,3 +92,23 @@ func runRuleDelete(ctx context.Context, client policyv1grpc.PolicyServiceClient, } return res.GetRevision().GetRevision(), nil } + +func confirmBlockDelete(ctx context.Context, client policyv1grpc.PolicyServiceClient, id string, confirm confirmFunc) error { + get := &policyv1.GetPackageRuleRequest{} + get.SetRuleId(id) + rule, err := client.GetPackageRule(ctx, get) + if err != nil { + return mapRuleError("delete", id, err) + } + if r := rule.GetRule().GetRule(); r.GetEffect() == corev1.Effect_EFFECT_BLOCK { + ok, err := confirm(fmt.Sprintf("Rule %s blocks %s. The delete loosens the policy. Delete it?", + clitui.EscapeLine(id), clitui.EscapeLine(r.GetSelector().GetPurl()))) + if err != nil { + return err + } + if !ok { + return errPublishCancelled + } + } + return nil +} diff --git a/internal/cmd/policy/rule_test.go b/internal/cmd/policy/rule_test.go index 2c22f95..f535464 100644 --- a/internal/cmd/policy/rule_test.go +++ b/internal/cmd/policy/rule_test.go @@ -412,16 +412,47 @@ func TestRunRuleUpdateAndDelete(t *testing.T) { require.NoError(t, err) assert.Equal(t, uint64(50), res.GetRevision().GetRevision()) + trust := &policyv1.GetPackageRuleResponse{} + trust.SetRule(ruleWithAttributes("r_80b", corev1.Effect_EFFECT_TRUST, "")) + client.EXPECT().GetPackageRule(mock.Anything, mock.Anything).Return(trust, nil) 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", "") + noPrompt := func(string) (bool, error) { + t.Fatal("the delete of a trust entry must not ask") + return false, nil + } + rev, err := runRuleDelete(context.Background(), client, "r_80b", "no longer needed", "", noPrompt) require.NoError(t, err) assert.Equal(t, uint64(51), rev) } +func TestRunRuleDelete_BlockNeedsAConfirmation(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + block := &policyv1.GetPackageRuleResponse{} + block.SetRule(ruleWithAttributes("r_77e", corev1.Effect_EFFECT_BLOCK, "")) + client.EXPECT().GetPackageRule(mock.Anything, mock.Anything).Return(block, nil) + + var question string + refuse := func(q string) (bool, error) { + question = q + return false, nil + } + _, err := runRuleDelete(context.Background(), client, "r_77e", "no longer needed", "", refuse) + require.ErrorIs(t, err, errPublishCancelled) + assert.Equal(t, "Rule r_77e blocks pkg:npm/leftpad. The delete loosens the policy. Delete it?", question) + + // With --yes the command does not read the rule. + del := &policyv1.DeletePackageRuleResponse{} + del.SetRevision(revision(52, "")) + client.EXPECT().DeletePackageRule(mock.Anything, mock.Anything).Return(del, nil) + rev, err := runRuleDelete(context.Background(), client, "r_77e", "no longer needed", "", nil) + require.NoError(t, err) + assert.Equal(t, uint64(52), rev) +} + func TestExpandScopes_AllMixedWithANamedScope(t *testing.T) { for _, in := range [][]string{{"malware", "all"}, {"all", "cooldown"}, {"ALL"}} { got, err := expandScopes(in) diff --git a/internal/cmd/project/policy.go b/internal/cmd/project/policy.go index 03d709b..0352f65 100644 --- a/internal/cmd/project/policy.go +++ b/internal/cmd/project/policy.go @@ -2,7 +2,6 @@ package project import ( "context" - "errors" specv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/spec/v1" "github.com/spf13/cobra" @@ -40,9 +39,8 @@ func policyShowCmd(a *app.App) *cobra.Command { 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") + if err := requireOneProject(args, in.ProjectID, "As in: safedep project policy show acme/payments-api"); err != nil { + return err } return cloudpolicy.ValidateFieldPaths(in.Fields) }, diff --git a/internal/cmd/project/policy_test.go b/internal/cmd/project/policy_test.go index 0081a67..8860208 100644 --- a/internal/cmd/project/policy_test.go +++ b/internal/cmd/project/policy_test.go @@ -17,6 +17,7 @@ import ( "google.golang.org/grpc" "google.golang.org/protobuf/types/known/timestamppb" + "github.com/safedep/cli/internal/cloudpolicy" "github.com/safedep/cli/internal/cloudpolicy/mocks" ) @@ -122,7 +123,7 @@ func TestRunShow_ProjectWithPolicy(t *testing.T) { ), nil }} policies := &fakeSubjectPolicyClient{} - got, err := runShow(context.Background(), client, policies, "PAY/settlement") + got, err := runShow(context.Background(), client, policies, showInput{Name: "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()) @@ -140,7 +141,7 @@ 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") + got, err := runShow(context.Background(), client, &fakeSubjectPolicyClient{err: errors.New("unimplemented")}, showInput{Name: "x"}) require.NoError(t, err) assert.Contains(t, got.RenderTable(), "unknown: the policy service did not answer") } @@ -163,6 +164,33 @@ func TestFindProject(t *testing.T) { assert.Contains(t, err.Error(), `project show: project name "shared" is ambiguous`) } +func TestRunShow_ByProjectID(t *testing.T) { + client := &fakeListProjectsClient{listFn: func(req *controltowerv1.ListProjectsRequest) (*controltowerv1.ListProjectsResponse, error) { + assert.Empty(t, req.GetFilterV2().GetProjectNames()) + assert.Equal(t, "safedep.io/project-id=p_2", cloudpolicy.FormatSelector(req.GetFilterV2().GetLabelSelector())) + return projectsResponse(labeledProject("p_2", "shared", messagescontroltowerv1.Project_SOURCE_BITBUCKET, nil)), nil + }} + policies := &fakeSubjectPolicyClient{} + got, err := runShow(context.Background(), client, policies, showInput{ProjectID: "p_2"}) + require.NoError(t, err) + assert.Equal(t, "p_2", policies.req.GetSubject().GetId()) + assert.Equal(t, "shared", got.Project.Name) + assert.Contains(t, got.RenderTable(), "safedep project policy show --project-id p_2") + + empty := &fakeListProjectsClient{listFn: func(*controltowerv1.ListProjectsRequest) (*controltowerv1.ListProjectsResponse, error) { + return projectsResponse(), nil + }} + _, err = runShow(context.Background(), empty, policies, showInput{ProjectID: "p_missing"}) + requireUsefulError(t, err, "not_found", "Project not found", "Find the project ID with: safedep project list") +} + +func TestRequireOneProject(t *testing.T) { + assert.NoError(t, requireOneProject([]string{"a"}, "", "help")) + assert.NoError(t, requireOneProject(nil, "p_1", "help")) + assert.Error(t, requireOneProject(nil, "", "help")) + assert.Error(t, requireOneProject([]string{"a"}, "p_1", "help")) +} + func TestRunPolicyShow(t *testing.T) { policies := &fakeSubjectPolicyClient{} got, err := runPolicyShow(context.Background(), nil, policies, policyShowInput{ProjectID: "p_7", Fields: []string{"scan_gate"}}) diff --git a/internal/cmd/project/resolver.go b/internal/cmd/project/resolver.go index a59443d..a7a5458 100644 --- a/internal/cmd/project/resolver.go +++ b/internal/cmd/project/resolver.go @@ -229,7 +229,7 @@ func ambiguousProjectNameError(op, name string, byID map[string]projectMatch) er return newProjectError( usefulerror.ErrBadRequest, "Project name is ambiguous", - "Retry with one of these project IDs: "+strings.Join(labels, ", ")+".", + "Retry with --project-id and one of these project IDs: "+strings.Join(labels, ", ")+".", cause, ) } diff --git a/internal/cmd/project/resolver_test.go b/internal/cmd/project/resolver_test.go index 72c4e2e..b0f017b 100644 --- a/internal/cmd/project/resolver_test.go +++ b/internal/cmd/project/resolver_test.go @@ -268,7 +268,7 @@ func TestResolveProjectNames_RejectsAmbiguousName(t *testing.T) { err, usefulerror.ErrBadRequest, "Project name is ambiguous", - "Retry with one of these project IDs: id-github (github, https://github.com/acme/shared), "+ + "Retry with --project-id and one of these project IDs: id-github (github, https://github.com/acme/shared), "+ "id-gitlab (gitlab, https://gitlab.com/acme/shared).", ) } diff --git a/internal/cmd/project/show.go b/internal/cmd/project/show.go index 5b2c9e8..8676fa7 100644 --- a/internal/cmd/project/show.go +++ b/internal/cmd/project/show.go @@ -3,6 +3,7 @@ package project import ( "context" "encoding/json" + "errors" "fmt" "strings" "time" @@ -22,28 +23,86 @@ import ( type projectShowResult struct { Project projectView `json:"project"` Policy *cloudpolicy.SubjectPolicy `json:"-"` + // byID is true for a read with --project-id. The name can be ambiguous + // then, so the footer gives the ID. + byID bool +} + +type showInput struct { + Name string + ProjectID string } func showCmd(a *app.App) *cobra.Command { - return &cobra.Command{ - Use: "show PROJECT_NAME", + var in showInput + cmd := &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), + Long: "Show one project by its exact name, or by --project-id when two projects have the 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: func(cmd *cobra.Command, args []string) error { + if err := cobra.MaximumNArgs(1)(cmd, args); err != nil { + return err + } + return requireOneProject(args, in.ProjectID, "As in: safedep project show acme/payments-api") + }, 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 := runShow(cmd.Context(), newListProjectsClient(conn), cloudpolicy.NewPolicyClient(conn), args[0]) + res, err := runShow(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") + return cmd +} + +// requireOneProject checks that the command line names one project, by a +// name or by --project-id. +func requireOneProject(args []string, projectID, help string) error { + if (len(args) == 1) == (projectID != "") { + return invalidProjectSelectionError(errors.New("give a project name or --project-id"), help) + } + return nil +} + +// projectIDLabel is the label that the server sets on each project. The +// ListProjects filter has no project ID field, so a read by ID selects on it. +const projectIDLabel = "safedep.io/project-id" + +// findProjectByID reads one project by its ID. +func findProjectByID(ctx context.Context, client listProjectsClient, op, id string) (*controltowerv1.ProjectWithAttributes, error) { + notFound := newProjectError(usefulerror.ErrNotFound, "Project not found", + "Find the project ID with: safedep project list", + fmt.Errorf("%s: project ID %q not found", op, id)) + selector, err := cloudpolicy.ParseSelector(projectIDLabel + "=" + id) + if err != nil { + return nil, notFound + } + filter := &controltowerv1.ListProjectsRequest_Filter{} + filter.SetLabelSelector(selector) + req := &controltowerv1.ListProjectsRequest{} + req.SetFilterV2(filter) + res, err := client.ListProjects(ctx, req) + if err != nil { + return nil, fmt.Errorf("%s: %w", op, err) + } + for _, p := range res.GetProjects() { + if p.GetProject().GetProjectId() == id { + return p, nil + } + } + return nil, notFound } // findProject reads one project by its exact name. @@ -81,13 +140,20 @@ func runShow( ctx context.Context, projects listProjectsClient, policies cloudpolicy.SubjectPolicyClient, - name string, + in showInput, ) (*projectShowResult, error) { - project, err := findProject(ctx, projects, "project show", name) + var project *controltowerv1.ProjectWithAttributes + var err error + if in.ProjectID != "" { + project, err = findProjectByID(ctx, projects, "project show", in.ProjectID) + } else { + project, err = findProject(ctx, projects, "project show", in.Name) + } if err != nil { return nil, err } - out := &projectShowResult{Project: newProjectView(project)} + out := &projectShowResult{Project: newProjectView(project), byID: in.ProjectID != ""} + name := out.Project.Name subject := cloudpolicy.NewSubject(specv1.SubjectKind_SUBJECT_KIND_PROJECT, out.Project.ID) policy, err := cloudpolicy.GetSubjectPolicy(ctx, policies, subject, name, nil) if err != nil { @@ -159,7 +225,11 @@ func (r *projectShowResult) RenderTable() string { {"Violations", countCell(p.PolicyViolations)}, {"Created", created}, }...) - return cloudpolicy.KeyValues(rows) + "\n\nPolicy of each field: safedep project policy show " + clitui.EscapeLine(p.Name) + selection := p.Name + if r.byID { + selection = "--project-id " + p.ID + } + return cloudpolicy.KeyValues(rows) + "\n\nPolicy of each field: safedep project policy show " + clitui.EscapeLine(selection) } func (r *projectShowResult) RenderPlain() string {