diff --git a/docs/cmd/policy-show.md b/docs/cmd/policy-show.md index a2e74db..213e429 100644 --- a/docs/cmd/policy-show.md +++ b/docs/cmd/policy-show.md @@ -1,8 +1,32 @@ # 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. +policy changes, the package rules, the policy settings and the policy overrides +in priority order. + +The settings section lists every setting of the policy contract on one row, +grouped by the parent of its path, as `scan_gate.licenses`. Each row shows the +value that every subject gets and the layer that sets it: + +- `base`: the base of the tenant policy. +- `default policy`: the SafeDep default policy, below the base. +- `-` with the value `not set, each tool uses its local value`, when neither + layer sets it. + +Below the row, each policy override that sets the field shows its source, as +`override "ci" (300)`, and its value, from the highest priority to the lowest. +An override value applies only to the subjects that its selector matches. An +override past its expiry keeps its row, with `, expired` after its source. An +override source wider than a third of the terminal takes a line of its own, +with the value on the next line. + +On a terminal, a long value wraps to the terminal width: a list wraps after an +item, and other text wraps at spaces. A single long word, such as a long +override name, can still pass the terminal edge. When stdout is not a terminal, +as in `safedep policy show > policy.txt`, nothing wraps. + +If the policy holds settings that this CLI does not know, the section says so. +Update the CLI to see them. ## Synopsis @@ -25,13 +49,40 @@ 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 +Package rules 211 (184 trust, 27 block) · 23 expire in 7d · + safedep policy rule list +Default policy revision 2 + +Settings +SETTING SOURCE VALUE +package_admission.cooldown + min_age - not set, each tool uses its local + value + override "ci" (300) 7d +scan_gate + fail_on base medium + override "ci" (300) critical + override "payments" (200) high + fail_on_attacks default policy fail +scan_gate.licenses + deny default policy GPL-2.0, GPL-2.0-only, + GPL-2.0-or-later, GPL-3.0, + GPL-3.0-only, GPL-3.0-or-later, + AGPL-3.0, AGPL-3.0-only, + AGPL-3.0-or-later + allow - not set, each tool uses its local + value + unknown default policy allow +An override sets its value only for the subjects that its selector matches. +See the settings document: safedep policy get Overrides (priority, highest first) -PRIORITY NAME SELECTOR EXPIRES DESCRIPTION -300 ci custom/environment=ci - - -200 payments custom/criticality=high - - +╭──────────┬──────────┬─────────────────────────┬─────────┬─────────────╮ +│ PRIORITY │ NAME │ SELECTOR │ EXPIRES │ DESCRIPTION │ +├──────────┼──────────┼─────────────────────────┼─────────┼─────────────┤ +│ 300 │ ci │ custom/environment=ci │ - │ - │ +│ 200 │ payments │ custom/criticality=high │ - │ - │ +╰──────────┴──────────┴─────────────────────────┴─────────┴─────────────╯ ``` Read the policy settings document as JSON: diff --git a/internal/cloudpolicy/fields_test.go b/internal/cloudpolicy/fields_test.go index 3e45ff5..19ee615 100644 --- a/internal/cloudpolicy/fields_test.go +++ b/internal/cloudpolicy/fields_test.go @@ -4,9 +4,11 @@ import ( "testing" "time" + optionsv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/options/v1" 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/proto" ) func TestFields(t *testing.T) { @@ -89,3 +91,39 @@ func TestFormatJSONValue(t *testing.T) { assert.Equal(t, tt.human, human, tt.raw) } } + +// TestLeafPathsMergeByReplace guards the source of a value in `safedep policy +// show`, which takes the value of the nearest layer that sets the path. A +// path that merges by union or by key gets items from more than one layer, +// so a new such path must change that view first. +func TestLeafPathsMergeByReplace(t *testing.T) { + paths := LeafPaths() + require.NotEmpty(t, paths) + for _, path := range paths { + fd := fieldByPath(path) + require.NotNil(t, fd, path) + contract, ok := proto.GetExtension(fd.Options(), optionsv1.E_Field).(*optionsv1.FieldContract) + require.True(t, ok, path) + assert.Equal(t, optionsv1.Merge_MERGE_REPLACE, contract.GetMerge(), path) + } +} + +func TestWrapWords(t *testing.T) { + tests := []struct { + name string + text string + width int + want []string + }{ + {name: "fits", text: "one two", width: 7, want: []string{"one two"}}, + {name: "breaks at spaces", text: "one two three", width: 7, want: []string{"one two", "three"}}, + {name: "long word keeps its own line", text: "a verylongword b", width: 5, want: []string{"a", "verylongword", "b"}}, + {name: "counts display columns, not bytes", text: "ab · cd · ef", width: 7, want: []string{"ab · cd", "· ef"}}, + {name: "empty", text: "", width: 5, want: nil}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, WrapWords(tt.text, tt.width)) + }) + } +} diff --git a/internal/cloudpolicy/render.go b/internal/cloudpolicy/render.go index 891d0d3..45411da 100644 --- a/internal/cloudpolicy/render.go +++ b/internal/cloudpolicy/render.go @@ -29,13 +29,40 @@ func KeyValues(rows [][2]string) string { if i > 0 { b.WriteByte('\n') } - b.WriteString(r[0]) - b.WriteString(strings.Repeat(" ", width-lipgloss.Width(r[0])+2)) + b.WriteString(PadRight(r[0], width) + " ") b.WriteString(tui.EscapeLine(r[1])) } return b.String() } +// PadRight pads s with spaces to width display columns. +func PadRight(s string, width int) string { + return s + strings.Repeat(" ", max(width-lipgloss.Width(s), 0)) +} + +// WrapWords splits text into lines of at most width display columns, at +// spaces. A word wider than width gets a line of its own, because a broken +// word reads as two values. +func WrapWords(text string, width int) []string { + var lines []string + line := "" + for _, word := range strings.Fields(text) { + switch { + case line == "": + line = word + case lipgloss.Width(line)+1+lipgloss.Width(word) <= width: + line += " " + word + default: + lines = append(lines, line) + line = word + } + } + if line != "" { + lines = append(lines, line) + } + return lines +} + // EmptyDash keeps a table cell readable when a value is absent. func EmptyDash(s string) string { if s == "" { diff --git a/internal/cloudpolicy/template.go b/internal/cloudpolicy/template.go index 86670c2..3e07d83 100644 --- a/internal/cloudpolicy/template.go +++ b/internal/cloudpolicy/template.go @@ -336,7 +336,7 @@ func (w *templateWriter) commentedLeaf( if len(first)+len(" # ")+len(text) <= templateWidth { w.lines = append(w.lines, first+" # "+text) } else { - for _, line := range wrapWords(text, templateWidth-indent-len("# ")) { + for _, line := range WrapWords(text, templateWidth-indent-len("# ")) { w.comment(indent, line) } w.lines = append(w.lines, first) @@ -347,28 +347,6 @@ func (w *templateWriter) commentedLeaf( 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. diff --git a/internal/cmd/policy/show.go b/internal/cmd/policy/show.go index 3e53a58..251f72f 100644 --- a/internal/cmd/policy/show.go +++ b/internal/cmd/policy/show.go @@ -8,7 +8,6 @@ import ( "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" @@ -22,6 +21,11 @@ type showResult struct { Head *revisionView DefaultRevision uint64 DefaultFields []cloudpolicy.FieldValue + BaseFields []cloudpolicy.FieldValue + // UnknownSettings is true when the policy or the default policy holds + // fields that the SDK of this CLI does not know. The settings section + // cannot show them, so it says so. + UnknownSettings bool OpenChanges uint32 TrustRules uint32 BlockRules uint32 @@ -48,8 +52,9 @@ func showCmd(a *app.App) *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.", + "policy settings and the policy overrides in priority order. Each setting shows its value, " + + "the layer that sets it (the base or the SafeDep default policy) and the value of each policy " + + "override that sets it. 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() @@ -81,6 +86,9 @@ func runShow(ctx context.Context, client policyv1grpc.PolicyServiceClient, tenan Head: newRevisionView(res.GetHead()), DefaultRevision: res.GetDefaultPolicy().GetRevision(), DefaultFields: cloudpolicy.Fields(res.GetDefaultPolicy().GetSpec()), + BaseFields: cloudpolicy.Fields(res.GetPolicy().GetBase()), + UnknownSettings: cloudpolicy.CheckKnownFields(res.GetPolicy()) != nil || + cloudpolicy.CheckKnownFields(res.GetDefaultPolicy().GetSpec()) != nil, OpenChanges: res.GetOpenChangeCount(), TrustRules: counts.GetTrustCount(), BlockRules: counts.GetBlockCount(), @@ -133,55 +141,41 @@ func (r *showResult) openLine() string { } func (r *showResult) rulesLine() string { - line := fmt.Sprintf("%d (%d trust, %d block)", r.TrustRules+r.BlockRules, r.TrustRules, r.BlockRules) + total := r.TrustRules + r.BlockRules + line := fmt.Sprintf("%d (%d trust, %d block)", total, r.TrustRules, r.BlockRules) if r.ExpiringSoon > 0 { line += fmt.Sprintf("%s%d expire in 7d", sep, r.ExpiringSoon) } + if total > 0 { + line += sep + "safedep policy rule list" + } 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) +// RenderTable fits the view to the width of the terminal on stdout, so a long +// value, such as a license list or a publish message, wraps instead of +// running off the line. Output to a file or a pipe does not wrap. +func (r *showResult) RenderTable() string { + return r.render(time.Now(), clitui.StdoutWidth()) } -func (r *showResult) RenderTable() string { - now := time.Now() +func (r *showResult) render(now time.Time, width int) string { tenant := r.Tenant if tenant == "" { tenant = "(this tenant)" } - rows := [][2]string{ + summary := wrapRows([][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 + {"Default policy", fmt.Sprintf("revision %d", r.DefaultRevision)}, + }, width) + return strings.Join([]string{ + cloudpolicy.KeyValues(summary), + r.settingsSection(now, width), + r.overridesTable(now, width), + }, "\n\n") } func (r *showResult) RenderPlain() string { diff --git a/internal/cmd/policy/show_render.go b/internal/cmd/policy/show_render.go new file mode 100644 index 0000000..5d03eae --- /dev/null +++ b/internal/cmd/policy/show_render.go @@ -0,0 +1,153 @@ +package policy + +import ( + "fmt" + "strings" + "time" + + "github.com/charmbracelet/lipgloss" + "github.com/safedep/dry/tui/table" + + "github.com/safedep/cli/internal/cloudpolicy" + clitui "github.com/safedep/cli/internal/tui" +) + +// A width of 0 or less means that stdout is not a terminal. The view then +// does not wrap, so a file or a pipe gets each value on one line. +const ( + // columnGap is the gap of cloudpolicy.KeyValues. + columnGap = " " + // minWrapWidth keeps a wrapped value readable on a very narrow terminal. + // Below it, a line runs past the terminal edge instead. + minWrapWidth = 20 + // listSeparator joins the items of a list value, as FieldValue.Human + // writes them. + listSeparator = ", " +) + +// overridesTable lists the policy overrides. The description is free text, +// so it wraps to the width that the other columns leave. +func (r *showResult) overridesTable(now time.Time, width int) string { + rows := make([][]string, 0, len(r.Overrides)) + for _, o := range r.Overrides { + expires := "-" + if o.expires != nil { + expires = humanTimeCell(o.expires, now) + } + rows = append(rows, []string{ + fmt.Sprintf("%d", o.Priority), o.Name, o.Selector, expires, cloudpolicy.EmptyDash(o.Description), + }) + } + headers := []string{"PRIORITY", "NAME", "SELECTOR", "EXPIRES", "DESCRIPTION"} + rows = clitui.EscapeCells(rows) + wrapLastColumn(headers, rows, width) + return table.New(). + Title("Overrides (priority, highest first)"). + Headers(headers...). + Rows(rows...). + EmptyMessage(wrapText("No policy overrides. The policy base applies to every subject. "+ + "Add one with: safedep policy edit", width)). + Render() +} + +// wrapLastColumn wraps the cells of the last column, so the table fits the +// width. A dry/tui table pads each cell with one space on each side and draws +// one border column between cells and at each edge. dry/tui has no width +// option for a table yet. +func wrapLastColumn(headers []string, rows [][]string, width int) { + if width <= 0 { + return + } + last := len(headers) - 1 + used := 1 + for col := range last { + w := lipgloss.Width(headers[col]) + for _, row := range rows { + w = max(w, lipgloss.Width(row[col])) + } + used += w + 3 + } + avail := max(width-used-3, lipgloss.Width(headers[last])) + for _, row := range rows { + row[last] = strings.Join(wrapValue(row[last], " ", avail), "\n") + } +} + +// wrapRows wraps the values of label and value rows to the width that the +// label column leaves. Each extra line is a row with an empty label, which +// cloudpolicy.KeyValues writes as a continuation of the row above. A value +// that is a summary line breaks after a separator first. +func wrapRows(rows [][2]string, width int) [][2]string { + labelW := 0 + for _, r := range rows { + labelW = max(labelW, lipgloss.Width(r[0])) + } + valueW := 0 + if width > 0 { + valueW = max(width-labelW-len(columnGap), minWrapWidth) + } + out := make([][2]string, 0, len(rows)) + for _, r := range rows { + label := r[0] + for _, line := range wrapValue(clitui.EscapeLine(r[1]), sep, valueW) { + out = append(out, [2]string{label, line}) + label = "" + } + } + return out +} + +// wrapText wraps sentences to the width. It breaks after a full stop +// first, so a sentence with a command stays on one line when it fits. +func wrapText(text string, width int) string { + return strings.Join(wrapValue(text, ". ", width), "\n") +} + +// wrapValue splits value into lines of at most width display columns. It +// breaks after a separator first, so a list item or a part of a summary line +// stays whole, and the line keeps the separator mark, as "GPL-2.0,". A part +// wider than width breaks at its spaces. A word wider than width gets a line +// of its own. +func wrapValue(value, separator string, width int) []string { + if width <= 0 || lipgloss.Width(value) <= width { + return []string{value} + } + mark := strings.TrimRight(separator, " ") + gap := separator[len(mark):] + parts := strings.Split(value, separator) + var lines []string + line := "" + for i, part := range parts { + if i < len(parts)-1 { + part += mark + } + if line != "" && lipgloss.Width(line+gap+part) <= width { + line += gap + part + continue + } + if line != "" { + lines = append(lines, line) + } + words := cloudpolicy.WrapWords(part, width) + if len(words) == 0 { + line = "" + continue + } + lines = append(lines, words[:len(words)-1]...) + line = words[len(words)-1] + } + if line != "" || len(lines) == 0 { + lines = append(lines, line) + } + return lines +} + +// splitPath splits a settings path into the path of its parent message and +// its field name, as "scan_gate.licenses" and "deny". +func splitPath(path string) (string, string) { + i := strings.LastIndex(path, ".") + if i < 0 { + return "", path + } + return path[:i], path[i+1:] +} diff --git a/internal/cmd/policy/show_settings.go b/internal/cmd/policy/show_settings.go new file mode 100644 index 0000000..11afa7f --- /dev/null +++ b/internal/cmd/policy/show_settings.go @@ -0,0 +1,158 @@ +package policy + +import ( + "fmt" + "strings" + "time" + + "github.com/charmbracelet/lipgloss" + "github.com/safedep/dry/tui/style" + + "github.com/safedep/cli/internal/cloudpolicy" + clitui "github.com/safedep/cli/internal/tui" +) + +const ( + notSetSource = "-" + notSetValue = "not set, each tool uses its local value" + sourceDefault = "default policy" + sourceBase = "base" + // wideSourceIndent starts the source line of a policy override whose + // source does not fit the SOURCE column, below the setting name. + wideSourceIndent = " " +) + +// settingView is one settings path: the value that every subject gets, the +// layer that gives it, and the value of each policy override that sets the +// path. +type settingView struct { + Path string + Human string + Source string + Overrides []settingOverride +} + +type settingOverride struct { + Source string + Human string +} + +// settingViews lists every settings path of the contract, in contract order. +// The base wins over the default policy. That holds because every settings +// path merges by replace (TestLeafPathsMergeByReplace). The override values +// follow the override order, from the highest priority to the lowest, and an +// override past its expiry keeps its row with a mark. +func settingViews(def, base []cloudpolicy.FieldValue, overrides []overrideView, now time.Time) []settingView { + layers := map[string]settingView{} + for _, f := range def { + layers[f.Path] = settingView{Human: f.Human, Source: sourceDefault} + } + for _, f := range base { + layers[f.Path] = settingView{Human: f.Human, Source: sourceBase} + } + setBy := map[string][]settingOverride{} + for _, o := range overrides { + source := fmt.Sprintf("override %q (%d)", o.Name, o.Priority) + if o.expires != nil && !o.expires.After(now) { + source += ", expired" + } + for _, f := range o.settings { + setBy[f.Path] = append(setBy[f.Path], settingOverride{Source: source, Human: f.Human}) + } + } + paths := cloudpolicy.LeafPaths() + out := make([]settingView, 0, len(paths)) + for _, path := range paths { + v, ok := layers[path] + if !ok { + v = settingView{Human: notSetValue, Source: notSetSource} + } + v.Path, v.Overrides = path, setBy[path] + out = append(out, v) + } + return out +} + +// settingsSection lists every setting on one row, grouped by the path of its +// parent message, as scan_gate.licenses. A value that does not fit the width +// wraps after a list item. The SOURCE column fits the layers and the +// override sources up to a third of the width. A longer override source +// takes a line of its own, so one long override name does not push every +// row past the terminal edge. +func (r *showResult) settingsSection(now time.Time, width int) string { + settings := settingViews(r.DefaultFields, r.BaseFields, r.Overrides, now) + parts := []string{style.Heading("Settings")} + if r.BaseDescription != "" { + parts = append(parts, wrapText("Base: "+clitui.EscapeLine(r.BaseDescription), width)) + } + + labelW, sourceW := lipgloss.Width("SETTING"), lipgloss.Width("SOURCE") + for _, s := range settings { + _, leaf := splitPath(s.Path) + labelW = max(labelW, lipgloss.Width(" "+leaf)) + sourceW = max(sourceW, lipgloss.Width(s.Source)) + } + fits := func(source string) bool { return width <= 0 || lipgloss.Width(source) <= width/3 } + for _, s := range settings { + for _, o := range s.Overrides { + if source := clitui.EscapeLine(o.Source); fits(source) { + sourceW = max(sourceW, lipgloss.Width(source)) + } + } + } + valueW := 0 + if width > 0 { + valueW = max(width-labelW-sourceW-2*len(columnGap), minWrapWidth) + } + row := func(label, source, value string) string { + return cloudpolicy.PadRight(label, labelW) + columnGap + cloudpolicy.PadRight(source, sourceW) + columnGap + value + } + values := func(label, source, value, wrapAt string) []string { + var out []string + for _, line := range wrapValue(clitui.EscapeLine(value), wrapAt, valueW) { + out = append(out, row(label, source, line)) + label, source = "", "" + } + return out + } + + rows := []string{row("SETTING", "SOURCE", "VALUE")} + group := "" + hasOverride := false + for _, s := range settings { + parent, leaf := splitPath(s.Path) + if parent != group { + rows = append(rows, parent) + group = parent + } + wrapAt := listSeparator + if s.Source == notSetSource { + wrapAt = " " + } + rows = append(rows, values(" "+leaf, s.Source, s.Human, wrapAt)...) + for _, o := range s.Overrides { + hasOverride = true + source := clitui.EscapeLine(o.Source) + if fits(source) { + rows = append(rows, values("", source, o.Human, listSeparator)...) + continue + } + for _, line := range wrapValue(source, " ", width-len(wideSourceIndent)) { + rows = append(rows, wideSourceIndent+line) + } + rows = append(rows, values("", "", o.Human, listSeparator)...) + } + } + parts = append(parts, strings.Join(rows, "\n")) + + note := "See the settings document: safedep policy get" + if hasOverride { + note = "An override sets its value only for the subjects that its selector matches. " + note + } + if r.UnknownSettings { + parts = append(parts, wrapText("This safedep CLI does not know some settings of this policy. "+ + "Update the CLI to the latest release to see them.", width)) + } + parts = append(parts, wrapText(note, width)) + return strings.Join(parts, "\n") +} diff --git a/internal/cmd/policy/show_test.go b/internal/cmd/policy/show_test.go index a3b0089..9bf4b9b 100644 --- a/internal/cmd/policy/show_test.go +++ b/internal/cmd/policy/show_test.go @@ -3,19 +3,32 @@ package policy import ( "context" "encoding/json" + "regexp" + "strings" "testing" + "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" + "github.com/charmbracelet/lipgloss" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/types/known/durationpb" + "google.golang.org/protobuf/types/known/timestamppb" "github.com/safedep/cli/internal/cloudpolicy/mocks" ) func TestRunShow(t *testing.T) { + head := headResponse() + head.GetHead().SetPublishedAt(timestamppb.New(fixedNow.Add(-49 * time.Hour))) client := mocks.NewPolicyServiceClientMock(t) - client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(headResponse(), nil) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(head, nil) res, err := runShow(context.Background(), client, "platform-eng.acme.safedep.io") require.NoError(t, err) @@ -24,18 +37,16 @@ func TestRunShow(t *testing.T) { 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) - } + assertLinesInOrder(t, res.render(fixedNow, 80), + `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`, + ` fail_on_attacks +default policy +fail`, + `Overrides \(priority, highest first\)`, + `.*payments.*`, + ) b, err := res.RenderJSON() require.NoError(t, err) @@ -50,6 +61,320 @@ func TestRunShow(t *testing.T) { assert.Contains(t, res.RenderPlain(), "override\t300\tci\tcustom/environment=ci") } +// riskyLicenses is the deny list of the SafeDep default policy. +var riskyLicenses = []string{ + "GPL-2.0", "GPL-2.0-only", "GPL-2.0-or-later", + "GPL-3.0", "GPL-3.0-only", "GPL-3.0-or-later", + "AGPL-3.0", "AGPL-3.0-only", "AGPL-3.0-or-later", +} + +// longOverrideName has the 63 characters that the API allows for a name. +const longOverrideName = "payments-team-release-freeze-exception-for-the-q4-2026-rollout1" + +// defaultPolicySpec is the SafeDep default policy at revision 2: the scan +// gate with the deny list of risky licenses. +func defaultPolicySpec() *specv1.PolicySpec { + spec := failOnSpec(scangatev1.Severity_SEVERITY_HIGH) + spec.GetScanGate().SetFailOnAttacks(scangatev1.AttackGate_ATTACK_GATE_FAIL) + deny := &scangatev1.LicenseList{} + deny.SetLicenses(riskyLicenses) + licenses := &scangatev1.LicenseGate{} + licenses.SetDeny(deny) + licenses.SetUnknown(scangatev1.UnknownLicenseGate_UNKNOWN_LICENSE_GATE_ALLOW) + spec.GetScanGate().SetLicenses(licenses) + return spec +} + +// showResponse is the reply of the example tenant: head revision 4, one +// block rule and the default policy at revision 2. +func showResponse(def *specv1.PolicySpec, policy *policyv1.Policy) *policyv1.GetPolicyResponse { + head := revision(4, "update package rule r_p0jz0vqmxa") + author := &messagescontroltowerv1.Actor{} + author.SetId("abhisek@safedep.io") + head.SetAuthor(author) + head.SetPublishedAt(timestamppb.New(fixedNow.Add(-14 * 24 * time.Hour))) + defaultPolicy := &policyv1.DefaultPolicy{} + defaultPolicy.SetRevision(2) + defaultPolicy.SetSpec(def) + counts := &policyv1.PackageRuleCounts{} + counts.SetBlockCount(1) + res := &policyv1.GetPolicyResponse{} + res.SetPolicy(policy) + res.SetHeadRevision(4) + res.SetHead(head) + res.SetDefaultPolicy(defaultPolicy) + res.SetPackageRuleCounts(counts) + return res +} + +func renderShow(t *testing.T, res *policyv1.GetPolicyResponse, width int) string { + t.Helper() + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(res, nil) + got, err := runShow(context.Background(), client, "default-team.safedep-io.safedep.io") + require.NoError(t, err) + return got.render(fixedNow, width) +} + +// assertLinesInOrder checks that each pattern matches a whole line, each one +// below the line of the pattern before it. +func assertLinesInOrder(t *testing.T, out string, patterns ...string) { + t.Helper() + lines := strings.Split(out, "\n") + next := 0 + for _, pattern := range patterns { + re := regexp.MustCompile("^" + pattern + "$") + found := false + for i := next; i < len(lines); i++ { + if re.MatchString(lines[i]) { + next, found = i+1, true + break + } + } + if !assert.True(t, found, "no line matches %q below line %d in:\n%s", pattern, next, out) { + return + } + } +} + +func TestShowRenderTable_Example(t *testing.T) { + out := renderShow(t, showResponse(defaultPolicySpec(), &policyv1.Policy{}), 80) + + settingsEnd := strings.Index(out, "\n\nOverrides") + require.Positive(t, settingsEnd) + assert.Equal(t, `Policy default-team.safedep-io.safedep.io +Head revision 4 · published 14d ago by abhisek@safedep.io · + "update package rule r_p0jz0vqmxa" +Open changes none +Package rules 1 (0 trust, 1 block) · safedep policy rule list +Default policy revision 2 + +Settings +SETTING SOURCE VALUE +package_admission.cooldown + min_age - not set, each tool uses its local value +scan_gate + fail_on default policy high + fail_on_attacks default policy fail +scan_gate.licenses + deny default policy GPL-2.0, GPL-2.0-only, GPL-2.0-or-later, + GPL-3.0, GPL-3.0-only, GPL-3.0-or-later, + AGPL-3.0, AGPL-3.0-only, AGPL-3.0-or-later + allow - not set, each tool uses its local value + unknown default policy allow +See the settings document: safedep policy get`, out[:settingsEnd]) + assert.Contains(t, out, "No policy overrides. The policy base applies to every subject.") +} + +func TestShowRenderTable(t *testing.T) { + baseOnly := &policyv1.Policy{} + baseOnly.SetBase(failOnSpec(scangatev1.Severity_SEVERITY_MEDIUM)) + baseOnly.SetBaseDescription("Every repository gates on medium findings") + + ci := override("ov_ci", "ci", 300, "custom/environment", "ci", scangatev1.Severity_SEVERITY_CRITICAL) + ci.SetDescription("CI runners build release artifacts, so the gate fails on critical findings " + + "only and the cooldown is longer than on laptops") + cooldown := &packageadmissionv1.Cooldown{} + cooldown.SetMinAge(durationpb.New(7 * 24 * time.Hour)) + admission := &packageadmissionv1.PackageAdmission{} + admission.SetCooldown(cooldown) + ci.GetSpec().SetPackageAdmission(admission) + lab := override("ov_lab", "lab", 100, "custom/environment", "lab", scangatev1.Severity_SEVERITY_LOW) + lab.SetExpiresAt(timestamppb.New(fixedNow.Add(-time.Hour))) + payments := override("ov_pay", "payments", 200, "custom/criticality", "high", scangatev1.Severity_SEVERITY_HIGH) + payments.SetExpiresAt(timestamppb.New(fixedNow.Add(time.Hour))) + severalOverrides := &policyv1.Policy{} + severalOverrides.SetBase(failOnSpec(scangatev1.Severity_SEVERITY_MEDIUM)) + severalOverrides.SetOverrides([]*policyv1.Override{payments, ci, lab}) + + longName := &policyv1.Policy{} + longName.SetOverrides([]*policyv1.Override{ + override("ov_long", longOverrideName, 1000000, "custom/team", "payments", scangatev1.Severity_SEVERITY_CRITICAL), + override("ov_ci", "ci", 300, "custom/environment", "ci", scangatev1.Severity_SEVERITY_LOW), + }) + + escaped := &policyv1.Policy{} + escaped.SetBaseDescription("\x1b[31mred\nline") + escaped.SetOverrides([]*policyv1.Override{ + override("ov_evil", "evil\x1b[2J", 100, "custom/environment", "ci", scangatev1.Severity_SEVERITY_LOW), + }) + + allowSpec := defaultPolicySpec() + allow := &scangatev1.LicenseList{} + allow.SetLicenses([]string{"MIT", "ISC", "Apache-2.0", "GPL-2.0-only WITH Classpath-exception-2.0"}) + allowSpec.GetScanGate().GetLicenses().SetAllow(allow) + + unknownBase := failOnSpec(scangatev1.Severity_SEVERITY_MEDIUM) + unknownField := protowire.AppendTag(nil, 99, protowire.VarintType) + unknownBase.GetScanGate().ProtoReflect().SetUnknown(protowire.AppendVarint(unknownField, 1)) + unknownPolicy := &policyv1.Policy{} + unknownPolicy.SetBase(unknownBase) + + unknownNote := "This safedep CLI does not know some settings of this policy." + tests := []struct { + name string + res *policyv1.GetPolicyResponse + // width 0 is a stdout that is not a terminal. + width int + // overflows is true when the width is below the narrowest value + // column, so lines can pass the width. + overflows bool + // tableOverflows checks the width only above the overrides table. + tableOverflows bool + lines []string + want []string + wantNot []string + }{ + { + name: "long license list at 140 columns", + res: showResponse(defaultPolicySpec(), &policyv1.Policy{}), + width: 140, + lines: []string{ + `Head revision 4 · published 14d ago by abhisek@safedep.io · "update package rule r_p0jz0vqmxa"`, + ` deny +default policy +GPL-2.0, GPL-2.0-only, GPL-2.0-or-later, GPL-3.0, GPL-3.0-only, GPL-3.0-or-later, AGPL-3.0,`, + ` +AGPL-3.0-only, AGPL-3.0-or-later`, + }, + }, + { + name: "no wrap when stdout is not a terminal", + res: showResponse(defaultPolicySpec(), longName), + width: 0, + lines: []string{ + `Head revision 4 · published 14d ago by abhisek@safedep.io · "update package rule r_p0jz0vqmxa"`, + ` +override "` + longOverrideName + `" \(1000000\) +critical`, + ` deny +default policy +` + strings.Join(riskyLicenses, ", "), + }, + }, + { + name: "empty base and default policy", + res: showResponse(nil, &policyv1.Policy{}), + width: 80, + lines: []string{ + ` min_age +- +not set, each tool uses its local value`, + ` fail_on +- +not set, each tool uses its local value`, + ` fail_on_attacks +- +not set, each tool uses its local value`, + ` deny +- +not set, each tool uses its local value`, + ` allow +- +not set, each tool uses its local value`, + ` unknown +- +not set, each tool uses its local value`, + }, + wantNot: []string{"default policy ", "base "}, + }, + { + name: "no overrides", + res: showResponse(defaultPolicySpec(), baseOnly), + width: 80, + lines: []string{ + `Settings`, + `Base: Every repository gates on medium findings`, + `SETTING +SOURCE +VALUE`, + ` fail_on +base +medium`, + ` fail_on_attacks +default policy +fail`, + }, + want: []string{"No policy overrides. The policy base applies to every subject."}, + wantNot: []string{`override "`, "An override sets its value", unknownNote}, + }, + { + name: "several overrides in priority order with an expired one", + res: showResponse(defaultPolicySpec(), severalOverrides), + width: 80, + lines: []string{ + ` min_age +- +not set, each tool uses its local`, + ` +value`, + ` +override "ci" \(300\) +7d`, + ` fail_on +base +medium`, + ` +override "ci" \(300\) +critical`, + ` +override "payments" \(200\) +high`, + ` override "lab" \(100\), expired`, + ` +low`, + ` fail_on_attacks +default policy +fail`, + `An override sets its value only for the subjects that its selector matches.`, + }, + want: []string{"CI runners build"}, + wantNot: []string{"CI runners build release artifacts, so the gate", `"payments" (200), expired`}, + }, + { + name: "override name of 63 characters at 80 columns", + res: showResponse(defaultPolicySpec(), longName), + width: 80, + // A name has no space to wrap at, and a dry/tui table has no + // width option, so the NAME column passes the width. + tableOverflows: true, + lines: []string{ + ` fail_on +default policy +high`, + ` override "` + longOverrideName + `"`, + ` \(1000000\)`, + ` +critical`, + ` +override "ci" \(300\) +low`, + ` fail_on_attacks +default policy +fail`, + }, + }, + { + name: "server text is escaped", + res: showResponse(nil, escaped), + width: 80, + lines: []string{ + `Base: \\x1b\[31mred\\nline`, + ` override "evil\\x1b\[2J" \(100\)`, + ` +low`, + }, + wantNot: []string{"\x1b", "red\nline"}, + }, + { + name: "list item with spaces stays whole at 80 columns", + res: showResponse(allowSpec, &policyv1.Policy{}), + width: 80, + lines: []string{ + ` allow +default policy +MIT, ISC, Apache-2.0,`, + ` +GPL-2.0-only WITH Classpath-exception-2.0`, + }, + }, + { + name: "value column keeps its minimum width on a narrow terminal", + res: showResponse(nil, &policyv1.Policy{}), + width: 30, + overflows: true, + lines: []string{ + ` min_age +- +not set, each tool`, + ` +uses its local value`, + }, + }, + { + name: "settings that this CLI does not know", + res: showResponse(defaultPolicySpec(), unknownPolicy), + width: 80, + lines: []string{ + ` fail_on +base +medium`, + `This safedep CLI does not know some settings of this policy.`, + `Update the CLI to the latest release to see them.`, + `See the settings document: safedep policy get`, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + out := renderShow(t, tt.res, tt.width) + assertLinesInOrder(t, out, tt.lines...) + for _, want := range tt.want { + assert.Contains(t, out, want) + } + for _, notWant := range tt.wantNot { + assert.NotContains(t, out, notWant) + } + if tt.width <= 0 || tt.overflows { + return + } + if tt.tableOverflows { + settings, _, found := strings.Cut(out, "\n\nOverrides") + require.True(t, found) + out = settings + } + for _, line := range strings.Split(out, "\n") { + assert.LessOrEqual(t, lipgloss.Width(line), tt.width, "line %q", line) + } + }) + } +} + func TestRunShow_NeverPublished(t *testing.T) { client := mocks.NewPolicyServiceClientMock(t) res := &policyv1.GetPolicyResponse{} @@ -58,7 +383,7 @@ func TestRunShow_NeverPublished(t *testing.T) { got, err := runShow(context.Background(), client, "") require.NoError(t, err) - table := got.RenderTable() + table := got.render(fixedNow, 80) 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") diff --git a/internal/cmd/policy/view.go b/internal/cmd/policy/view.go index e72c795..1e7767e 100644 --- a/internal/cmd/policy/view.go +++ b/internal/cmd/policy/view.go @@ -87,7 +87,8 @@ func humanTimeCell(t *time.Time, now time.Time) string { return humanize.Time(*t, now) } -// overrideView is a policy override without its values. +// overrideView is a policy override. Its JSON form has no values: the +// settings document of the JSON output holds them. type overrideView struct { ID string `json:"override_id"` Name string `json:"name"` @@ -96,6 +97,7 @@ type overrideView struct { Description string `json:"description,omitempty"` ExpiresAt string `json:"expires_at,omitempty"` expires *time.Time + settings []cloudpolicy.FieldValue } // overrideViews lists the policy overrides from the highest priority to the @@ -112,6 +114,7 @@ func overrideViews(p *policyv1.Policy) []overrideView { Description: o.GetDescription(), ExpiresAt: cloudpolicy.RFC3339(expires), expires: expires, + settings: cloudpolicy.Fields(o.GetSpec()), }) } sort.SliceStable(out, func(i, j int) bool { return out[i].Priority > out[j].Priority }) diff --git a/internal/tui/width.go b/internal/tui/width.go new file mode 100644 index 0000000..2978ee1 --- /dev/null +++ b/internal/tui/width.go @@ -0,0 +1,20 @@ +package tui + +import ( + "os" + + "golang.org/x/term" +) + +// StdoutWidth returns the width of the terminal on stdout, or 0 when stdout +// is not a terminal. A data view wraps to the width of the stream that it +// writes to: dry/tui output.Width reads stderr and falls back to 80 +// columns, so a view written to a file would wrap at a width that does not +// apply to it. +func StdoutWidth() int { + w, _, err := term.GetSize(int(os.Stdout.Fd())) + if err != nil || w <= 0 { + return 0 + } + return w +}