From fee1c36bb874fcd0124b019d3986eae7711346b8 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 13:37:18 +0000 Subject: [PATCH 1/2] feat(policy): show the policy settings one per row in policy show The table view of `safedep policy show` put every setting of the SafeDep default policy on one "Default policy" line, joined by middle dots. A license deny list made the line run far past an 80 column terminal, and each new setting made it longer. The view also never showed the settings of the tenant base, so a base value hid behind the default value on that line, and it did not say which settings a policy override changes. The view now has a Settings section with one setting on each row, grouped by the parent of its path, as scan_gate.licenses. Each row shows the value that every subject gets and its layer, base or default policy, in the source words of the subject policy views. Each policy override that sets the field adds a row below it, from the highest priority to the lowest. A list value wraps after an item to the terminal width. The head revision line, the empty messages and the override description also wrap, so no line passes the terminal width. The summary keeps a short "Default policy revision N" row and points to `safedep policy rule list` and `safedep policy get`. The JSON and plain output do not change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MhRi597EX9odoSDXbVBsxz --- docs/cmd/policy-show.md | 34 +++- internal/cmd/policy/show.go | 60 +++--- internal/cmd/policy/show_render.go | 294 +++++++++++++++++++++++++++++ internal/cmd/policy/show_test.go | 178 ++++++++++++++++- internal/cmd/policy/view.go | 5 +- 5 files changed, 529 insertions(+), 42 deletions(-) create mode 100644 internal/cmd/policy/show_render.go diff --git a/docs/cmd/policy-show.md b/docs/cmd/policy-show.md index a2e74db..9f45f55 100644 --- a/docs/cmd/policy-show.md +++ b/docs/cmd/policy-show.md @@ -1,8 +1,16 @@ # 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 one setting on each 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`, `default policy` (the SafeDep default +policy), or `-` when no layer sets it. Below the row, each policy override that +sets the field shows its value, from the highest priority to the lowest. An +override value applies only to the subjects that its selector matches. A long +value, such as a license list, wraps to the terminal width. ## Synopsis @@ -25,8 +33,26 @@ 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 +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 + 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 diff --git a/internal/cmd/policy/show.go b/internal/cmd/policy/show.go index 3e53a58..eb8a8ee 100644 --- a/internal/cmd/policy/show.go +++ b/internal/cmd/policy/show.go @@ -8,7 +8,7 @@ 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/safedep/dry/tui/output" "github.com/spf13/cobra" "github.com/safedep/cli/internal/app" @@ -22,6 +22,7 @@ type showResult struct { Head *revisionView DefaultRevision uint64 DefaultFields []cloudpolicy.FieldValue + BaseFields []cloudpolicy.FieldValue OpenChanges uint32 TrustRules uint32 BlockRules uint32 @@ -48,8 +49,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 +83,7 @@ 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()), OpenChanges: res.GetOpenChangeCount(), TrustRules: counts.GetTrustCount(), BlockRules: counts.GetBlockCount(), @@ -133,55 +136,40 @@ 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 terminal width, so a long value, such as +// a license list or a publish message, wraps instead of running off the line. +func (r *showResult) RenderTable() string { + return r.render(time.Now(), output.Width()) } -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(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..8ab7391 --- /dev/null +++ b/internal/cmd/policy/show_render.go @@ -0,0 +1,294 @@ +package policy + +import ( + "fmt" + "strings" + "time" + + "github.com/charmbracelet/lipgloss" + "github.com/safedep/dry/tui/section" + "github.com/safedep/dry/tui/style" + "github.com/safedep/dry/tui/table" + + "github.com/safedep/cli/internal/cloudpolicy" + clitui "github.com/safedep/cli/internal/tui" +) + +const ( + // columnGap is the space between the columns of the settings section, + // 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 = ", " + notSetValue = "not set, each tool uses its local value" + sourceDefault = "default policy" + sourceBase = "base" +) + +// 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. Source is empty when neither the base nor the default policy sets +// the path. +type settingView struct { + Path string + Human string + Source string + Overrides []settingOverride +} + +type settingOverride struct { + Source string + Human string +} + +// settingViews lists each path that a layer sets, in contract order. The +// base wins over the default policy. The override values follow the +// override order, from the highest priority to the lowest. +func settingViews(def, base []cloudpolicy.FieldValue, overrides []overrideView) []settingView { + byPath := map[string]*settingView{} + get := func(path string) *settingView { + if v, ok := byPath[path]; ok { + return v + } + v := &settingView{Path: path} + byPath[path] = v + return v + } + for _, f := range def { + v := get(f.Path) + v.Human, v.Source = f.Human, sourceDefault + } + for _, f := range base { + v := get(f.Path) + v.Human, v.Source = f.Human, sourceBase + } + for _, o := range overrides { + source := fmt.Sprintf("override %q (%d)", o.Name, o.Priority) + for _, f := range o.settings { + v := get(f.Path) + v.Overrides = append(v.Overrides, settingOverride{Source: source, Human: f.Human}) + } + } + out := make([]settingView, 0, len(byPath)) + for _, path := range cloudpolicy.LeafPaths() { + if v, ok := byPath[path]; ok { + out = append(out, *v) + } + } + return out +} + +// settingLine is one row of the settings section. An empty label continues +// the setting above. +type settingLine struct { + label, source, value string + // wrapAt is the separator that the value breaks after first. + wrapAt string +} + +// settingsSection groups the settings by the path of their parent message, +// as scan_gate.licenses, with one setting per row. A value that does not fit +// the width wraps after a list item. +func (r *showResult) settingsSection(width int) string { + settings := settingViews(r.DefaultFields, r.BaseFields, r.Overrides) + parts := []string{style.Heading("Settings")} + if r.BaseDescription != "" { + parts = append(parts, wrapText("Base: "+clitui.EscapeLine(r.BaseDescription), width)) + } + if len(settings) == 0 { + parts = append(parts, section.Empty(wrapText("The policy sets no settings. Each tool uses its local values. "+ + "Set them with: safedep policy edit", width))) + return strings.Join(parts, "\n") + } + + groups := []string{} + lines := map[string][]settingLine{} + hasOverride := false + for _, s := range settings { + group, leaf := splitPath(s.Path) + if _, ok := lines[group]; !ok { + groups = append(groups, group) + } + if group != "" { + leaf = " " + leaf + } + first := settingLine{label: leaf, source: s.Source, value: s.Human, wrapAt: listSeparator} + if s.Source == "" { + first = settingLine{label: leaf, source: "-", value: notSetValue, wrapAt: " "} + } + lines[group] = append(lines[group], first) + for _, o := range s.Overrides { + lines[group] = append(lines[group], settingLine{source: o.Source, value: o.Human, wrapAt: listSeparator}) + hasOverride = true + } + } + + labelW, sourceW := lipgloss.Width("SETTING"), lipgloss.Width("SOURCE") + for _, group := range groups { + for _, l := range lines[group] { + labelW = max(labelW, lipgloss.Width(l.label)) + sourceW = max(sourceW, lipgloss.Width(clitui.EscapeLine(l.source))) + } + } + valueW := max(width-labelW-sourceW-2*len(columnGap), minWrapWidth) + + rows := []string{padRight("SETTING", labelW) + columnGap + padRight("SOURCE", sourceW) + columnGap + "VALUE"} + for _, group := range groups { + if group != "" { + rows = append(rows, group) + } + for _, l := range lines[group] { + label, source := l.label, clitui.EscapeLine(l.source) + for _, value := range wrapValue(clitui.EscapeLine(l.value), l.wrapAt, valueW) { + rows = append(rows, padRight(label, labelW)+columnGap+padRight(source, sourceW)+columnGap+value) + label, source = "", "" + } + } + } + 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 + } + parts = append(parts, wrapText(note, width)) + return strings.Join(parts, "\n") +} + +// 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) { + 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 := 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 +} + +// 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, because a broken word reads as two values. +func wrapValue(value, separator string, width int) []string { + if 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 := wrapWords(part, width) + lines = append(lines, words[:len(words)-1]...) + line = words[len(words)-1] + } + return append(lines, line) +} + +// 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") +} + +func wrapWords(text string, width int) []string { + var lines []string + line := "" + for i, word := range strings.Split(text, " ") { + switch { + case i == 0: + line = word + case lipgloss.Width(line+" "+word) <= width: + line += " " + word + default: + lines = append(lines, line) + line = word + } + } + return append(lines, line) +} + +// 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:] +} + +func padRight(s string, width int) string { + return s + strings.Repeat(" ", max(width-lipgloss.Width(s), 0)) +} diff --git a/internal/cmd/policy/show_test.go b/internal/cmd/policy/show_test.go index a3b0089..9d86395 100644 --- a/internal/cmd/policy/show_test.go +++ b/internal/cmd/policy/show_test.go @@ -3,12 +3,20 @@ package policy import ( "context" "encoding/json" + "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/charmbracelet/lipgloss" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "google.golang.org/protobuf/types/known/durationpb" + "google.golang.org/protobuf/types/known/timestamppb" "github.com/safedep/cli/internal/cloudpolicy/mocks" ) @@ -30,7 +38,8 @@ func TestRunShow(t *testing.T) { `46 · published 2d ago by alice · "cooldown 5d for laptops"`, "Open changes none", "211 (184 trust, 27 block) · 23 expire in 7d", - "revision 1 · scan_gate.fail_on: high · scan_gate.fail_on_attacks: fail", + "Default policy revision 1", + " fail_on_attacks default policy fail", "Overrides (priority, highest first)", "payments", } { @@ -50,6 +59,173 @@ 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", +} + +// 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 +} + +func showResponse(def *specv1.PolicySpec, policy *policyv1.Policy) *policyv1.GetPolicyResponse { + head := revision(4, "update package rule r_p0jz0vqmxa") + 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 TestShowRenderTable(t *testing.T) { + noOverrides := &policyv1.Policy{} + + baseOnly := &policyv1.Policy{} + baseOnly.SetBase(failOnSpec(scangatev1.Severity_SEVERITY_MEDIUM)) + baseOnly.SetBaseDescription("Every repository gates on medium findings") + + cooldownCI := override("ov_ci", "ci", 300, "custom/environment", "ci", scangatev1.Severity_SEVERITY_CRITICAL) + cooldownCI.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) + cooldownCI.GetSpec().SetPackageAdmission(admission) + severalOverrides := &policyv1.Policy{} + severalOverrides.SetBase(failOnSpec(scangatev1.Severity_SEVERITY_MEDIUM)) + severalOverrides.SetOverrides([]*policyv1.Override{ + override("ov_pay", "payments", 200, "custom/criticality", "high", scangatev1.Severity_SEVERITY_HIGH), + cooldownCI, + override("ov_lab", "lab", 100, "custom/environment", "lab", scangatev1.Severity_SEVERITY_LOW), + }) + + tests := []struct { + name string + res *policyv1.GetPolicyResponse + width int + want []string + wantNot []string + }{ + { + name: "long license list at 80 columns", + res: showResponse(defaultPolicySpec(), noOverrides), + width: 80, + want: []string{ + "Head revision 4 · published 14d ago by alice ·\n" + + " \"update package rule r_p0jz0vqmxa\"\n", + "Package rules 1 (0 trust, 1 block) · safedep policy rule list\n", + "Settings\n" + + "SETTING SOURCE VALUE\n" + + "scan_gate\n" + + " fail_on default policy high\n" + + " fail_on_attacks default policy fail\n" + + "scan_gate.licenses\n" + + " deny default policy GPL-2.0, GPL-2.0-only, GPL-2.0-or-later,\n" + + " GPL-3.0, GPL-3.0-only, GPL-3.0-or-later,\n" + + " AGPL-3.0, AGPL-3.0-only, AGPL-3.0-or-later\n" + + " unknown default policy allow\n" + + "See the settings document: safedep policy get\n", + }, + }, + { + name: "long license list at 140 columns", + res: showResponse(defaultPolicySpec(), noOverrides), + width: 140, + want: []string{ + "Head revision 4 · published 14d ago by alice · \"update package rule r_p0jz0vqmxa\"\n", + " 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,\n" + + " AGPL-3.0-only, AGPL-3.0-or-later\n", + }, + }, + { + name: "empty base and default policy", + res: showResponse(nil, noOverrides), + width: 80, + want: []string{ + "Settings\nThe policy sets no settings. Each tool uses its local values.\n" + + "Set them with: safedep policy edit\n", + "No policy overrides.", + }, + wantNot: []string{"SETTING", "safedep policy get"}, + }, + { + name: "no overrides", + res: showResponse(defaultPolicySpec(), baseOnly), + width: 80, + want: []string{ + "Settings\nBase: Every repository gates on medium findings\nSETTING", + " fail_on base medium\n" + + " fail_on_attacks default policy fail\n", + "No policy overrides. The policy base applies to every subject.", + }, + wantNot: []string{"override \"", "An override sets its value"}, + }, + { + name: "several overrides", + res: showResponse(defaultPolicySpec(), severalOverrides), + width: 80, + want: []string{ + "SETTING SOURCE VALUE\n" + + "package_admission.cooldown\n" + + " min_age - not set, each tool uses its local\n" + + " value\n" + + " override \"ci\" (300) 7d\n" + + "scan_gate\n" + + " fail_on base medium\n" + + " override \"ci\" (300) critical\n" + + " override \"payments\" (200) high\n" + + " override \"lab\" (100) low\n" + + " fail_on_attacks default policy fail\n", + "An override sets its value only for the subjects that its selector matches.\n" + + "See the settings document: safedep policy get\n", + "CI runners build", + }, + wantNot: []string{"CI runners build release artifacts, so the gate"}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + client := mocks.NewPolicyServiceClientMock(t) + client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(tt.res, nil) + res, err := runShow(context.Background(), client, "default-team.safedep-io.safedep.io") + require.NoError(t, err) + + out := res.render(fixedNow, tt.width) + for _, want := range tt.want { + assert.Contains(t, out, want) + } + for _, notWant := range tt.wantNot { + assert.NotContains(t, out, notWant) + } + 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{} 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 }) From 8f2d9c5326e8f20614a7c28841f7e45d4bb61126 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 13:49:50 +0000 Subject: [PATCH 2/2] fix(policy): list every setting and fit long sources in policy show The first version of the settings section in `safedep policy show` had gaps: - One long override name widened the SOURCE column for every row, so each row passed the terminal edge. A name can have 63 characters. - An override past its expiry showed its value as if it still applied. - The section listed only the settings that a layer sets, and it hid a setting that this CLI's SDK does not know without a word. - The view read the width of stderr, so output to a file wrapped at the terminal width, and output on a wide terminal with stderr redirected wrapped at 80 columns. - The word wrap copied the one of the edit template. Now 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, with the value on the next line. An expired override keeps its row, with ", expired" after its source. The section lists every settings path of the contract, with "-" and "not set" when no layer sets it, and a note when the policy holds settings that this CLI does not know. The view wraps to the width of stdout, and does not wrap when stdout is not a terminal. cloudpolicy.WrapWords is now the one word wrap. It counts display columns, and the edit template output does not change. A cloudpolicy test fails when a settings path stops to merge by replace, because the SOURCE column assumes that the nearest layer wins. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MhRi597EX9odoSDXbVBsxz --- docs/cmd/policy-show.md | 45 +++- internal/cloudpolicy/fields_test.go | 38 ++++ internal/cloudpolicy/render.go | 31 ++- internal/cloudpolicy/template.go | 24 +- internal/cmd/policy/show.go | 16 +- internal/cmd/policy/show_render.go | 193 +++------------- internal/cmd/policy/show_settings.go | 158 +++++++++++++ internal/cmd/policy/show_test.go | 329 +++++++++++++++++++-------- internal/tui/width.go | 20 ++ 9 files changed, 557 insertions(+), 297 deletions(-) create mode 100644 internal/cmd/policy/show_settings.go create mode 100644 internal/tui/width.go diff --git a/docs/cmd/policy-show.md b/docs/cmd/policy-show.md index 9f45f55..213e429 100644 --- a/docs/cmd/policy-show.md +++ b/docs/cmd/policy-show.md @@ -4,13 +4,29 @@ Show a summary of the policy of the tenant: the head policy revision, the open policy changes, the package rules, the policy settings and the policy overrides in priority order. -The settings section lists one setting on each 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`, `default policy` (the SafeDep default -policy), or `-` when no layer sets it. Below the row, each policy override that -sets the field shows its value, from the highest priority to the lowest. An -override value applies only to the subjects that its selector matches. A long -value, such as a license list, wraps to the terminal width. +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 @@ -39,6 +55,10 @@ 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 @@ -50,14 +70,19 @@ scan_gate.licenses 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 eb8a8ee..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/output" "github.com/spf13/cobra" "github.com/safedep/cli/internal/app" @@ -23,6 +22,10 @@ type showResult struct { 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 @@ -84,6 +87,8 @@ func runShow(ctx context.Context, client policyv1grpc.PolicyServiceClient, tenan 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(), @@ -147,10 +152,11 @@ func (r *showResult) rulesLine() string { return line } -// RenderTable fits the view to the terminal width, so a long value, such as -// a license list or a publish message, wraps instead of running off the line. +// 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(), output.Width()) + return r.render(time.Now(), clitui.StdoutWidth()) } func (r *showResult) render(now time.Time, width int) string { @@ -167,7 +173,7 @@ func (r *showResult) render(now time.Time, width int) string { }, width) return strings.Join([]string{ cloudpolicy.KeyValues(summary), - r.settingsSection(width), + r.settingsSection(now, width), r.overridesTable(now, width), }, "\n\n") } diff --git a/internal/cmd/policy/show_render.go b/internal/cmd/policy/show_render.go index 8ab7391..5d03eae 100644 --- a/internal/cmd/policy/show_render.go +++ b/internal/cmd/policy/show_render.go @@ -6,17 +6,16 @@ import ( "time" "github.com/charmbracelet/lipgloss" - "github.com/safedep/dry/tui/section" - "github.com/safedep/dry/tui/style" "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 space between the columns of the settings section, - // the gap of cloudpolicy.KeyValues. + // 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. @@ -24,140 +23,8 @@ const ( // listSeparator joins the items of a list value, as FieldValue.Human // writes them. listSeparator = ", " - notSetValue = "not set, each tool uses its local value" - sourceDefault = "default policy" - sourceBase = "base" ) -// 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. Source is empty when neither the base nor the default policy sets -// the path. -type settingView struct { - Path string - Human string - Source string - Overrides []settingOverride -} - -type settingOverride struct { - Source string - Human string -} - -// settingViews lists each path that a layer sets, in contract order. The -// base wins over the default policy. The override values follow the -// override order, from the highest priority to the lowest. -func settingViews(def, base []cloudpolicy.FieldValue, overrides []overrideView) []settingView { - byPath := map[string]*settingView{} - get := func(path string) *settingView { - if v, ok := byPath[path]; ok { - return v - } - v := &settingView{Path: path} - byPath[path] = v - return v - } - for _, f := range def { - v := get(f.Path) - v.Human, v.Source = f.Human, sourceDefault - } - for _, f := range base { - v := get(f.Path) - v.Human, v.Source = f.Human, sourceBase - } - for _, o := range overrides { - source := fmt.Sprintf("override %q (%d)", o.Name, o.Priority) - for _, f := range o.settings { - v := get(f.Path) - v.Overrides = append(v.Overrides, settingOverride{Source: source, Human: f.Human}) - } - } - out := make([]settingView, 0, len(byPath)) - for _, path := range cloudpolicy.LeafPaths() { - if v, ok := byPath[path]; ok { - out = append(out, *v) - } - } - return out -} - -// settingLine is one row of the settings section. An empty label continues -// the setting above. -type settingLine struct { - label, source, value string - // wrapAt is the separator that the value breaks after first. - wrapAt string -} - -// settingsSection groups the settings by the path of their parent message, -// as scan_gate.licenses, with one setting per row. A value that does not fit -// the width wraps after a list item. -func (r *showResult) settingsSection(width int) string { - settings := settingViews(r.DefaultFields, r.BaseFields, r.Overrides) - parts := []string{style.Heading("Settings")} - if r.BaseDescription != "" { - parts = append(parts, wrapText("Base: "+clitui.EscapeLine(r.BaseDescription), width)) - } - if len(settings) == 0 { - parts = append(parts, section.Empty(wrapText("The policy sets no settings. Each tool uses its local values. "+ - "Set them with: safedep policy edit", width))) - return strings.Join(parts, "\n") - } - - groups := []string{} - lines := map[string][]settingLine{} - hasOverride := false - for _, s := range settings { - group, leaf := splitPath(s.Path) - if _, ok := lines[group]; !ok { - groups = append(groups, group) - } - if group != "" { - leaf = " " + leaf - } - first := settingLine{label: leaf, source: s.Source, value: s.Human, wrapAt: listSeparator} - if s.Source == "" { - first = settingLine{label: leaf, source: "-", value: notSetValue, wrapAt: " "} - } - lines[group] = append(lines[group], first) - for _, o := range s.Overrides { - lines[group] = append(lines[group], settingLine{source: o.Source, value: o.Human, wrapAt: listSeparator}) - hasOverride = true - } - } - - labelW, sourceW := lipgloss.Width("SETTING"), lipgloss.Width("SOURCE") - for _, group := range groups { - for _, l := range lines[group] { - labelW = max(labelW, lipgloss.Width(l.label)) - sourceW = max(sourceW, lipgloss.Width(clitui.EscapeLine(l.source))) - } - } - valueW := max(width-labelW-sourceW-2*len(columnGap), minWrapWidth) - - rows := []string{padRight("SETTING", labelW) + columnGap + padRight("SOURCE", sourceW) + columnGap + "VALUE"} - for _, group := range groups { - if group != "" { - rows = append(rows, group) - } - for _, l := range lines[group] { - label, source := l.label, clitui.EscapeLine(l.source) - for _, value := range wrapValue(clitui.EscapeLine(l.value), l.wrapAt, valueW) { - rows = append(rows, padRight(label, labelW)+columnGap+padRight(source, sourceW)+columnGap+value) - label, source = "", "" - } - } - } - 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 - } - parts = append(parts, wrapText(note, width)) - return strings.Join(parts, "\n") -} - // 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 { @@ -188,6 +55,9 @@ func (r *showResult) overridesTable(now time.Time, width int) string { // 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 { @@ -212,7 +82,10 @@ func wrapRows(rows [][2]string, width int) [][2]string { for _, r := range rows { labelW = max(labelW, lipgloss.Width(r[0])) } - valueW := max(width-labelW-len(columnGap), minWrapWidth) + 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] @@ -224,13 +97,19 @@ func wrapRows(rows [][2]string, width int) [][2]string { 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, because a broken word reads as two values. +// of its own. func wrapValue(value, separator string, width int) []string { - if lipgloss.Width(value) <= width { + if width <= 0 || lipgloss.Width(value) <= width { return []string{value} } mark := strings.TrimRight(separator, " ") @@ -249,34 +128,18 @@ func wrapValue(value, separator string, width int) []string { if line != "" { lines = append(lines, line) } - words := wrapWords(part, width) + words := cloudpolicy.WrapWords(part, width) + if len(words) == 0 { + line = "" + continue + } lines = append(lines, words[:len(words)-1]...) line = words[len(words)-1] } - return append(lines, line) -} - -// 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") -} - -func wrapWords(text string, width int) []string { - var lines []string - line := "" - for i, word := range strings.Split(text, " ") { - switch { - case i == 0: - line = word - case lipgloss.Width(line+" "+word) <= width: - line += " " + word - default: - lines = append(lines, line) - line = word - } + if line != "" || len(lines) == 0 { + lines = append(lines, line) } - return append(lines, line) + return lines } // splitPath splits a settings path into the path of its parent message and @@ -288,7 +151,3 @@ func splitPath(path string) (string, string) { } return path[:i], path[i+1:] } - -func padRight(s string, width int) string { - return s + strings.Repeat(" ", max(width-lipgloss.Width(s), 0)) -} 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 9d86395..9bf4b9b 100644 --- a/internal/cmd/policy/show_test.go +++ b/internal/cmd/policy/show_test.go @@ -3,10 +3,12 @@ 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" @@ -15,6 +17,7 @@ import ( "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" @@ -22,8 +25,10 @@ import ( ) 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) @@ -32,19 +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", - "Default policy revision 1", - " fail_on_attacks default policy 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) @@ -66,6 +68,9 @@ var riskyLicenses = []string{ "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 { @@ -80,8 +85,13 @@ func defaultPolicySpec() *specv1.PolicySpec { 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) @@ -97,128 +107,267 @@ func showResponse(def *specv1.PolicySpec, policy *policyv1.Policy) *policyv1.Get return res } -func TestShowRenderTable(t *testing.T) { - noOverrides := &policyv1.Policy{} +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") - cooldownCI := override("ov_ci", "ci", 300, "custom/environment", "ci", scangatev1.Severity_SEVERITY_CRITICAL) - cooldownCI.SetDescription("CI runners build release artifacts, so the gate fails on critical 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) - cooldownCI.GetSpec().SetPackageAdmission(admission) + 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{ - override("ov_pay", "payments", 200, "custom/criticality", "high", scangatev1.Severity_SEVERITY_HIGH), - cooldownCI, - override("ov_lab", "lab", 100, "custom/environment", "lab", scangatev1.Severity_SEVERITY_LOW), + 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 int - want []string - wantNot []string + 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 80 columns", - res: showResponse(defaultPolicySpec(), noOverrides), - width: 80, - want: []string{ - "Head revision 4 · published 14d ago by alice ·\n" + - " \"update package rule r_p0jz0vqmxa\"\n", - "Package rules 1 (0 trust, 1 block) · safedep policy rule list\n", - "Settings\n" + - "SETTING SOURCE VALUE\n" + - "scan_gate\n" + - " fail_on default policy high\n" + - " fail_on_attacks default policy fail\n" + - "scan_gate.licenses\n" + - " deny default policy GPL-2.0, GPL-2.0-only, GPL-2.0-or-later,\n" + - " GPL-3.0, GPL-3.0-only, GPL-3.0-or-later,\n" + - " AGPL-3.0, AGPL-3.0-only, AGPL-3.0-or-later\n" + - " unknown default policy allow\n" + - "See the settings document: safedep policy get\n", + 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: "long license list at 140 columns", - res: showResponse(defaultPolicySpec(), noOverrides), - width: 140, - want: []string{ - "Head revision 4 · published 14d ago by alice · \"update package rule r_p0jz0vqmxa\"\n", - " 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,\n" + - " AGPL-3.0-only, AGPL-3.0-or-later\n", + 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, noOverrides), + res: showResponse(nil, &policyv1.Policy{}), width: 80, - want: []string{ - "Settings\nThe policy sets no settings. Each tool uses its local values.\n" + - "Set them with: safedep policy edit\n", - "No policy overrides.", + 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{"SETTING", "safedep policy get"}, + wantNot: []string{"default policy ", "base "}, }, { name: "no overrides", res: showResponse(defaultPolicySpec(), baseOnly), width: 80, - want: []string{ - "Settings\nBase: Every repository gates on medium findings\nSETTING", - " fail_on base medium\n" + - " fail_on_attacks default policy fail\n", - "No policy overrides. The policy base applies to every subject.", + lines: []string{ + `Settings`, + `Base: Every repository gates on medium findings`, + `SETTING +SOURCE +VALUE`, + ` fail_on +base +medium`, + ` fail_on_attacks +default policy +fail`, }, - wantNot: []string{"override \"", "An override sets its value"}, + want: []string{"No policy overrides. The policy base applies to every subject."}, + wantNot: []string{`override "`, "An override sets its value", unknownNote}, }, { - name: "several overrides", + name: "several overrides in priority order with an expired one", res: showResponse(defaultPolicySpec(), severalOverrides), width: 80, - want: []string{ - "SETTING SOURCE VALUE\n" + - "package_admission.cooldown\n" + - " min_age - not set, each tool uses its local\n" + - " value\n" + - " override \"ci\" (300) 7d\n" + - "scan_gate\n" + - " fail_on base medium\n" + - " override \"ci\" (300) critical\n" + - " override \"payments\" (200) high\n" + - " override \"lab\" (100) low\n" + - " fail_on_attacks default policy fail\n", - "An override sets its value only for the subjects that its selector matches.\n" + - "See the settings document: safedep policy get\n", - "CI runners build", + 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`, }, - wantNot: []string{"CI runners build release artifacts, so the gate"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - client := mocks.NewPolicyServiceClientMock(t) - client.EXPECT().GetPolicy(mock.Anything, mock.Anything).Return(tt.res, nil) - res, err := runShow(context.Background(), client, "default-team.safedep-io.safedep.io") - require.NoError(t, err) - - out := res.render(fixedNow, tt.width) + 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) } @@ -234,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/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 +}