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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 58 additions & 7 deletions docs/cmd/policy-show.md
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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:
Expand Down
38 changes: 38 additions & 0 deletions internal/cloudpolicy/fields_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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))
})
}
}
31 changes: 29 additions & 2 deletions internal/cloudpolicy/render.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 == "" {
Expand Down
24 changes: 1 addition & 23 deletions internal/cloudpolicy/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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.
Expand Down
66 changes: 30 additions & 36 deletions internal/cmd/policy/show.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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
Expand All @@ -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()
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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 {
Expand Down
Loading
Loading