Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions docs/cmd/policy-rule-delete.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -15,6 +15,7 @@ safedep policy rule delete RULE --reason TEXT [-m MESSAGE]
|------|-------------|
| `--reason <text>` | Why the rule goes. Required. |
| `-m`, `--message <text>` | The publish message. |
| `-y`, `--yes` | Delete a block entry with no prompt. |

## Examples

Expand All @@ -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

Expand Down
15 changes: 11 additions & 4 deletions docs/cmd/project-show.md
Original file line number Diff line number Diff line change
@@ -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 <id>` | The project ID instead of a name. Use it when two projects have the same name. |

## Examples

```bash
Expand All @@ -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

Expand Down
21 changes: 20 additions & 1 deletion internal/cmd/audit/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -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_"
Expand Down Expand Up @@ -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
}
11 changes: 11 additions & 0 deletions internal/cmd/audit/list_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
10 changes: 5 additions & 5 deletions internal/cmd/policy/change_publish.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
}
Expand Down
24 changes: 23 additions & 1 deletion internal/cmd/policy/change_show.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()}
Expand All @@ -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),
Expand Down
58 changes: 58 additions & 0 deletions internal/cmd/policy/change_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand Down
30 changes: 24 additions & 6 deletions internal/cmd/policy/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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
Expand All @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion internal/cmd/policy/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
4 changes: 2 additions & 2 deletions internal/cmd/policy/publish_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion internal/cmd/policy/revision_show.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
20 changes: 20 additions & 0 deletions internal/cmd/policy/revision_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading