|
| 1 | +// Copyright 2021-2024 Zenauth Ltd. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +package inspect |
| 5 | + |
| 6 | +import ( |
| 7 | + "context" |
| 8 | + "fmt" |
| 9 | + "strings" |
| 10 | + |
| 11 | + "github.com/alecthomas/kong" |
| 12 | + "github.com/cerbos/cerbos-sdk-go/cerbos" |
| 13 | + |
| 14 | + "github.com/cerbos/cerbos/cmd/cerbosctl/inspect/internal/flagset" |
| 15 | + "github.com/cerbos/cerbos/cmd/cerbosctl/internal/client" |
| 16 | + "github.com/cerbos/cerbos/cmd/cerbosctl/internal/printer" |
| 17 | +) |
| 18 | + |
| 19 | +const ( |
| 20 | + help = `# Inspect policies |
| 21 | +
|
| 22 | +cerbosctl inspect policies |
| 23 | +
|
| 24 | +# Inspect policies, print no headers |
| 25 | +
|
| 26 | +cerbosctl inspect policies` |
| 27 | + separator = "," |
| 28 | +) |
| 29 | + |
| 30 | +type PoliciesCmd struct { |
| 31 | + flagset.Filters |
| 32 | + flagset.Format |
| 33 | +} |
| 34 | + |
| 35 | +func (c *PoliciesCmd) Run(k *kong.Kong, cctx *client.Context) error { |
| 36 | + var opts []cerbos.FilterOption |
| 37 | + if c.Filters.IncludeDisabled { |
| 38 | + opts = append(opts, cerbos.WithIncludeDisabled()) |
| 39 | + } |
| 40 | + if c.Filters.NameRegexp != "" { |
| 41 | + opts = append(opts, cerbos.WithNameRegexp(c.Filters.NameRegexp)) |
| 42 | + } |
| 43 | + if c.Filters.ScopeRegexp != "" { |
| 44 | + opts = append(opts, cerbos.WithScopeRegexp(c.Filters.ScopeRegexp)) |
| 45 | + } |
| 46 | + if c.Filters.VersionRegexp != "" { |
| 47 | + opts = append(opts, cerbos.WithVersionRegexp(c.Filters.VersionRegexp)) |
| 48 | + } |
| 49 | + |
| 50 | + response, err := cctx.AdminClient.InspectPolicies(context.Background(), opts...) |
| 51 | + if err != nil { |
| 52 | + return fmt.Errorf("error while inspecting policies: %w", err) |
| 53 | + } |
| 54 | + |
| 55 | + tw := printer.NewTableWriter(k.Stdout) |
| 56 | + if !c.Format.NoHeaders { |
| 57 | + tw.SetHeader([]string{"POLICY ID", "ACTIONS"}) |
| 58 | + } |
| 59 | + |
| 60 | + for policyKey, result := range response.Results { |
| 61 | + actions := strings.Join(result.Actions, separator) |
| 62 | + tw.Append([]string{policyKey, actions}) |
| 63 | + } |
| 64 | + |
| 65 | + tw.Render() |
| 66 | + return nil |
| 67 | +} |
| 68 | + |
| 69 | +func (c *PoliciesCmd) Help() string { |
| 70 | + return help |
| 71 | +} |
0 commit comments