From a5318d170299af00d52dd7e6992fe7c8df5cf4e8 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 09:25:35 +0000 Subject: [PATCH 1/5] build(deps): bump the SafeDep API SDK to the WorkloadAdminService build The workload commands need WorkloadAdminService and its messages, which the build 20261120125025-1b99964cacca holds. The grpc and protocolbuffers modules move to that build. The CLI does not use the connectrpc module. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MhRi597EX9odoSDXbVBsxz --- go.mod | 4 ++-- go.sum | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/go.mod b/go.mod index 71fa4af..476625e 100644 --- a/go.mod +++ b/go.mod @@ -4,8 +4,8 @@ go 1.26.2 require ( buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.12-20260709200747-435963d16310.1 - buf.build/gen/go/safedep/api/grpc/go v1.6.2-20261107111754-29a1adb160aa.1 - buf.build/gen/go/safedep/api/protocolbuffers/go v1.36.12-20261107111754-29a1adb160aa.2 + buf.build/gen/go/safedep/api/grpc/go v1.6.2-20261120125025-1b99964cacca.1 + buf.build/gen/go/safedep/api/protocolbuffers/go v1.36.12-20261120125025-1b99964cacca.2 github.com/charmbracelet/huh v1.0.0 github.com/charmbracelet/lipgloss v1.1.0 github.com/cli/browser v1.3.0 diff --git a/go.sum b/go.sum index 3e27fb3..9ab5444 100644 --- a/go.sum +++ b/go.sum @@ -1,9 +1,9 @@ buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.12-20260709200747-435963d16310.1 h1:6nlcxMOui23ZRVAfJM451duu79P1npA5JRdZqMilrrQ= buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.12-20260709200747-435963d16310.1/go.mod h1:TCt1lluMFnctISJXvkIQ4x3ABrPuUKCWKyjKdkJNBpw= -buf.build/gen/go/safedep/api/grpc/go v1.6.2-20261107111754-29a1adb160aa.1 h1:4uXBhgLhLEn7IOW9avcfYIYKNOI77vOcYm9XQbvfRHo= -buf.build/gen/go/safedep/api/grpc/go v1.6.2-20261107111754-29a1adb160aa.1/go.mod h1:4i7HWcBq17WJ1/i+2RMe/hFwUloX8o4PaviS3I9gd5I= -buf.build/gen/go/safedep/api/protocolbuffers/go v1.36.12-20261107111754-29a1adb160aa.2 h1:1VyJgN+9Z4T+dEVSffnJV/ETVLPsqKkYEvWHguZ/jzc= -buf.build/gen/go/safedep/api/protocolbuffers/go v1.36.12-20261107111754-29a1adb160aa.2/go.mod h1:LfbopTmazyAppwhYT2vdRDLDH8ZTm4QNbp9yFjGRbHs= +buf.build/gen/go/safedep/api/grpc/go v1.6.2-20261120125025-1b99964cacca.1 h1:VtJ6nUMMnUpBHZEbkZ2UyKc3JOzhkaOyVSNj4xxlMe4= +buf.build/gen/go/safedep/api/grpc/go v1.6.2-20261120125025-1b99964cacca.1/go.mod h1:UE5WVYoUtyjgfgzogSIDq8XcImrD9Y5rBxcHIGGJr38= +buf.build/gen/go/safedep/api/protocolbuffers/go v1.36.12-20261120125025-1b99964cacca.2 h1:ozXNHk9+cxf2kVk/G+pCqTOEAbZ7fqFYZ6o1N0X/WYs= +buf.build/gen/go/safedep/api/protocolbuffers/go v1.36.12-20261120125025-1b99964cacca.2/go.mod h1:LfbopTmazyAppwhYT2vdRDLDH8ZTm4QNbp9yFjGRbHs= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ= From 5c14a1ef9614a9569dbe099bca6801e877215279 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 09:25:35 +0000 Subject: [PATCH 2/5] refactor(policy): move the gRPC status text helpers to internal/rpcerror The workload commands show server errors with the same text as the policy commands: the status message without the service prefix, and each field violation with a readable field path. Sibling command packages cannot import each other, so the helpers move to internal/rpcerror. The policy package keeps its document paths and duration text on top of them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MhRi597EX9odoSDXbVBsxz --- internal/cmd/policy/editor.go | 8 +- internal/cmd/policy/errors.go | 134 +++---------------------------- internal/rpcerror/rpcerror.go | 144 ++++++++++++++++++++++++++++++++++ 3 files changed, 161 insertions(+), 125 deletions(-) create mode 100644 internal/rpcerror/rpcerror.go diff --git a/internal/cmd/policy/editor.go b/internal/cmd/policy/editor.go index 136985b..5675dcb 100644 --- a/internal/cmd/policy/editor.go +++ b/internal/cmd/policy/editor.go @@ -15,6 +15,8 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" + + "github.com/safedep/cli/internal/rpcerror" ) const ( @@ -48,13 +50,13 @@ func isRetryable(err error) bool { if errors.As(err, &r) { return true } - st, ok := innerStatus(err) + st, ok := rpcerror.InnerStatus(err) if !ok || st.Code() != codes.InvalidArgument { return false } if bad, ok := usefulerror.DetailAs[*errdetails.BadRequest](err); ok && len(bad.GetFieldViolations()) > 0 { for _, v := range bad.GetFieldViolations() { - if isDocumentField(violationField(v)) { + if isDocumentField(rpcerror.ViolationField(v)) { return true } } @@ -62,7 +64,7 @@ func isRetryable(err error) bool { } // With no field detail, the message starts with the field, as in // "title: must be at most 200 characters". - field, _, found := strings.Cut(stripServicePrefix(st.Message()), ":") + field, _, found := strings.Cut(rpcerror.StripServicePrefix(st.Message()), ":") return !found || strings.ContainsAny(field, " ") || isDocumentField(field) } diff --git a/internal/cmd/policy/errors.go b/internal/cmd/policy/errors.go index 051238f..4c17624 100644 --- a/internal/cmd/policy/errors.go +++ b/internal/cmd/policy/errors.go @@ -3,18 +3,16 @@ package policy import ( "errors" "fmt" - "strconv" "strings" - validate "buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go/buf/validate" errorv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/error/v1" "github.com/safedep/dry/usefulerror" "google.golang.org/genproto/googleapis/rpc/errdetails" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - "google.golang.org/protobuf/encoding/prototext" "github.com/safedep/cli/internal/cloudpolicy" + "github.com/safedep/cli/internal/rpcerror" "github.com/safedep/cli/internal/tui" ) @@ -44,131 +42,23 @@ func invalidArgumentError(err error, help string, cause error) error { return newPolicyError(usefulerror.ErrBadRequest, describeStatus(err), help, cause) } -// serviceFailedPrefix is the text that the server puts before the message of -// a service error. It names no field and no fix, so the CLI removes it. -const serviceFailedPrefix = "service execution failed: " - -// stripServicePrefix removes each leading serviceFailedPrefix of a status -// message. A server that wraps an error two times sends the prefix two -// times, and a field name after one prefix must still read as the field. -func stripServicePrefix(msg string) string { - msg = strings.TrimSpace(msg) - for strings.HasPrefix(msg, serviceFailedPrefix) { - msg = strings.TrimSpace(strings.TrimPrefix(msg, serviceFailedPrefix)) - } - return msg -} - -// noReasonText is the text of a status that has no message and no field -// violation. -const noReasonText = "The server gave no reason" - // describeStatus is the text of a gRPC status error for a person, with each // field path in the form of the edit document. See describeStatusAt. func describeStatus(err error) string { return describeStatusAt(err, documentPath) } -// describeStatusAt is the text of a gRPC status error for a person: the -// status message, then each field violation of a BadRequest detail as -// "field: description", with the field from path. The text of -// status.FromError on a wrapped error starts with "rpc error: code = ... -// desc =", so this reads the status of the innermost error. When the -// message already holds the description of each violation, the violations -// replace it, so no text shows two times. +// describeStatusAt is the text of a gRPC status error for a person, with the +// field of each violation from path. A duration in the description of a +// duration field reads as in the edit document. func describeStatusAt(err error, path func(string) (string, bool)) string { - st, ok := innerStatus(err) - if !ok { - return tui.EscapeText(err.Error()) - } - msg := stripServicePrefix(st.Message()) - var lines []string - covered := true - if bad, ok := usefulerror.DetailAs[*errdetails.BadRequest](err); ok { - for _, v := range bad.GetFieldViolations() { - field, isDuration := path(violationField(v)) - description := v.GetDescription() - if isDuration { - description = cloudpolicy.DocumentDurations(description) - } - if line := violationLine(field, description); line != "" { - lines = append(lines, tui.EscapeLine(line)) - } - covered = covered && v.GetDescription() != "" && strings.Contains(msg, v.GetDescription()) - } - } - if msg != "" && (len(lines) == 0 || !covered) { - lines = append([]string{tui.EscapeText(msg)}, lines...) - } - if len(lines) == 0 { - return noReasonText - } - return strings.Join(lines, "\n") -} - -func violationLine(field, description string) string { - switch { - case field == "": - return description - case description == "": - return field - } - return field + ": " + description -} - -// innerStatus is the status of the innermost gRPC error in the chain of err, -// with its message as the server sent it. -func innerStatus(err error) (*status.Status, bool) { - var gs interface{ GRPCStatus() *status.Status } - if !errors.As(err, &gs) { - return nil, false - } - st := gs.GRPCStatus() - return st, st != nil -} - -// violationField is the field of a violation as a dotted path, as in -// "settings.overrides[0].name". The server sends the protovalidate field -// path of a request as the protobuf text of a buf.validate.FieldPath, which -// no person can read. A field that does not parse as that text stays as it -// is. -func violationField(v *errdetails.BadRequest_FieldViolation) string { - field := v.GetField() - path := &validate.FieldPath{} - if err := prototext.Unmarshal([]byte(field), path); err != nil || len(path.GetElements()) == 0 { - return field - } - return fieldPathString(path) -} - -// fieldPathString writes a field path as protovalidate.FieldPathString -// does. The CLI does not import protovalidate, because its CEL runtime makes -// the binary 18% larger. -func fieldPathString(path *validate.FieldPath) string { - var b strings.Builder - for i, el := range path.GetElements() { - if i > 0 { - b.WriteByte('.') - } - b.WriteString(el.GetFieldName()) - var key string - switch el.WhichSubscript() { - case validate.FieldPathElement_Index_case: - key = strconv.FormatUint(el.GetIndex(), 10) - case validate.FieldPathElement_BoolKey_case: - key = strconv.FormatBool(el.GetBoolKey()) - case validate.FieldPathElement_IntKey_case: - key = strconv.FormatInt(el.GetIntKey(), 10) - case validate.FieldPathElement_UintKey_case: - key = strconv.FormatUint(el.GetUintKey(), 10) - case validate.FieldPathElement_StringKey_case: - key = strconv.Quote(el.GetStringKey()) - default: - continue + return rpcerror.Describe(err, func(field, description string) (string, string) { + field, isDuration := path(field) + if isDuration { + description = cloudpolicy.DocumentDurations(description) } - b.WriteString("[" + key + "]") - } - return b.String() + return field, description + }) } // documentFieldPrefix is the request field that holds the edit document. @@ -216,7 +106,7 @@ func (e *overrideFieldError) path(field string) (string, bool) { // useful error in the chain, else the text of describeStatus. func errorText(err error) string { var oe *overrideFieldError - if st, ok := innerStatus(err); ok && st.Code() == codes.InvalidArgument && errors.As(err, &oe) { + if st, ok := rpcerror.InnerStatus(err); ok && st.Code() == codes.InvalidArgument && errors.As(err, &oe) { return describeStatusAt(err, oe.path) } var ue usefulerror.UsefulError @@ -233,7 +123,7 @@ func violatesField(err error, field string) bool { return false } for _, v := range bad.GetFieldViolations() { - if violationField(v) == field { + if rpcerror.ViolationField(v) == field { return true } } diff --git a/internal/rpcerror/rpcerror.go b/internal/rpcerror/rpcerror.go new file mode 100644 index 0000000..11cca4d --- /dev/null +++ b/internal/rpcerror/rpcerror.go @@ -0,0 +1,144 @@ +// Package rpcerror turns a gRPC status error from SafeDep Cloud into text +// for a person: the status message without the service prefix of the +// server, and each field violation of a BadRequest detail with a readable +// field path. It lives outside internal/cmd because sibling command +// packages must not import each other. +package rpcerror + +import ( + "errors" + "strconv" + "strings" + + validate "buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go/buf/validate" + "github.com/safedep/dry/usefulerror" + "google.golang.org/genproto/googleapis/rpc/errdetails" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/encoding/prototext" + + "github.com/safedep/cli/internal/tui" +) + +// serviceFailedPrefix is the text that the server puts before the message of +// a service error. It names no field and no fix, so the CLI removes it. +const serviceFailedPrefix = "service execution failed: " + +// NoReasonText is the text of a status that has no message and no field +// violation. +const NoReasonText = "The server gave no reason" + +// ViolationText gives the field and the description that a person sees for +// one field violation. The field is the dotted path of ViolationField. +type ViolationText func(field, description string) (string, string) + +// AsIs shows each field violation as the server sent it. +func AsIs(field, description string) (string, string) { return field, description } + +// Describe is the text of a gRPC status error for a person: the status +// message, then each field violation of a BadRequest detail as +// "field: description", with the text from text. The text of +// status.FromError on a wrapped error starts with "rpc error: code = ... +// desc =", so this reads the status of the innermost error. When the +// message already holds the description of each violation, the violations +// replace it, so no text shows two times. +func Describe(err error, text ViolationText) string { + st, ok := InnerStatus(err) + if !ok { + return tui.EscapeText(err.Error()) + } + msg := StripServicePrefix(st.Message()) + var lines []string + covered := true + if bad, ok := usefulerror.DetailAs[*errdetails.BadRequest](err); ok { + for _, v := range bad.GetFieldViolations() { + field, description := text(ViolationField(v), v.GetDescription()) + if line := violationLine(field, description); line != "" { + lines = append(lines, tui.EscapeLine(line)) + } + covered = covered && v.GetDescription() != "" && strings.Contains(msg, v.GetDescription()) + } + } + if msg != "" && (len(lines) == 0 || !covered) { + lines = append([]string{tui.EscapeText(msg)}, lines...) + } + if len(lines) == 0 { + return NoReasonText + } + return strings.Join(lines, "\n") +} + +func violationLine(field, description string) string { + switch { + case field == "": + return description + case description == "": + return field + } + return field + ": " + description +} + +// StripServicePrefix removes each leading service prefix of a status +// message. A server that wraps an error two times sends the prefix two +// times, and a field name after one prefix must still read as the field. +func StripServicePrefix(msg string) string { + msg = strings.TrimSpace(msg) + for strings.HasPrefix(msg, serviceFailedPrefix) { + msg = strings.TrimSpace(strings.TrimPrefix(msg, serviceFailedPrefix)) + } + return msg +} + +// InnerStatus is the status of the innermost gRPC error in the chain of err, +// with its message as the server sent it. +func InnerStatus(err error) (*status.Status, bool) { + var gs interface{ GRPCStatus() *status.Status } + if !errors.As(err, &gs) { + return nil, false + } + st := gs.GRPCStatus() + return st, st != nil +} + +// ViolationField is the field of a violation as a dotted path, as in +// "settings.overrides[0].name". The server sends the protovalidate field +// path of a request as the protobuf text of a buf.validate.FieldPath, which +// no person can read. A field that does not parse as that text stays as it +// is. +func ViolationField(v *errdetails.BadRequest_FieldViolation) string { + field := v.GetField() + path := &validate.FieldPath{} + if err := prototext.Unmarshal([]byte(field), path); err != nil || len(path.GetElements()) == 0 { + return field + } + return fieldPathString(path) +} + +// fieldPathString writes a field path as protovalidate.FieldPathString +// does. The CLI does not import protovalidate, because its CEL runtime makes +// the binary 18% larger. +func fieldPathString(path *validate.FieldPath) string { + var b strings.Builder + for i, el := range path.GetElements() { + if i > 0 { + b.WriteByte('.') + } + b.WriteString(el.GetFieldName()) + var key string + switch el.WhichSubscript() { + case validate.FieldPathElement_Index_case: + key = strconv.FormatUint(el.GetIndex(), 10) + case validate.FieldPathElement_BoolKey_case: + key = strconv.FormatBool(el.GetBoolKey()) + case validate.FieldPathElement_IntKey_case: + key = strconv.FormatInt(el.GetIntKey(), 10) + case validate.FieldPathElement_UintKey_case: + key = strconv.FormatUint(el.GetUintKey(), 10) + case validate.FieldPathElement_StringKey_case: + key = strconv.Quote(el.GetStringKey()) + default: + continue + } + b.WriteString("[" + key + "]") + } + return b.String() +} From 03935a991186f98c135d0cce9c37904d1fadb335 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 09:25:35 +0000 Subject: [PATCH 3/5] feat(workload): add the workload provider, rule and exchange commands Admins need a CLI for workload identity, so a GitHub Actions job can call SafeDep Cloud with no API key. The new commands call WorkloadAdminService: - safedep workload provider list - safedep workload rule create NAME --provider PROVIDER --grant tool [--repository OWNER/NAME...] [--ref REF...] [--event EVENT...] - safedep workload rule list | show | delete - safedep workload exchange list [--denied] [--since D] [--rule RULE] rule create never picks a provider. With no --provider, or an unknown one, it fails and lists the providers of the tenant. --provider takes a provider id or KIND:ACCOUNT, as in github-actions:acme. The command prints the rule with the numeric id of each repository that the server stored, and warns when the rule covers every repository of the account. A repository that the installation cannot see fails with each repository that the server named. rule show, rule delete and exchange list --rule take a rule id or a rule name. Each leaf command has a doc page, and the README links to each one. Closes #77 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MhRi597EX9odoSDXbVBsxz --- .mockery.yml | 9 + README.md | 11 + docs/cmd/workload-exchange-list.md | 63 ++ docs/cmd/workload-provider-list.md | 60 ++ docs/cmd/workload-rule-create.md | 116 ++++ docs/cmd/workload-rule-delete.md | 41 ++ docs/cmd/workload-rule-list.md | 55 ++ docs/cmd/workload-rule-show.md | 56 ++ internal/cmd/safedep.go | 2 + internal/cmd/workload/cmd.go | 61 ++ internal/cmd/workload/errors.go | 123 ++++ internal/cmd/workload/exchange.go | 159 ++++++ internal/cmd/workload/exchange_test.go | 101 ++++ internal/cmd/workload/exchange_view.go | 78 +++ internal/cmd/workload/fixtures_test.go | 94 +++ .../mocks/WorkloadAdminServiceClient_mock.go | 538 ++++++++++++++++++ internal/cmd/workload/provider.go | 158 +++++ internal/cmd/workload/provider_resolve.go | 92 +++ internal/cmd/workload/rule_create.go | 100 ++++ internal/cmd/workload/rule_create_test.go | 364 ++++++++++++ internal/cmd/workload/rule_delete.go | 51 ++ internal/cmd/workload/rule_input.go | 169 ++++++ internal/cmd/workload/rule_list.go | 134 +++++ internal/cmd/workload/rule_show.go | 96 ++++ internal/cmd/workload/rule_test.go | 140 +++++ internal/cmd/workload/rule_view.go | 273 +++++++++ 26 files changed, 3144 insertions(+) create mode 100644 docs/cmd/workload-exchange-list.md create mode 100644 docs/cmd/workload-provider-list.md create mode 100644 docs/cmd/workload-rule-create.md create mode 100644 docs/cmd/workload-rule-delete.md create mode 100644 docs/cmd/workload-rule-list.md create mode 100644 docs/cmd/workload-rule-show.md create mode 100644 internal/cmd/workload/cmd.go create mode 100644 internal/cmd/workload/errors.go create mode 100644 internal/cmd/workload/exchange.go create mode 100644 internal/cmd/workload/exchange_test.go create mode 100644 internal/cmd/workload/exchange_view.go create mode 100644 internal/cmd/workload/fixtures_test.go create mode 100644 internal/cmd/workload/mocks/WorkloadAdminServiceClient_mock.go create mode 100644 internal/cmd/workload/provider.go create mode 100644 internal/cmd/workload/provider_resolve.go create mode 100644 internal/cmd/workload/rule_create.go create mode 100644 internal/cmd/workload/rule_create_test.go create mode 100644 internal/cmd/workload/rule_delete.go create mode 100644 internal/cmd/workload/rule_input.go create mode 100644 internal/cmd/workload/rule_list.go create mode 100644 internal/cmd/workload/rule_show.go create mode 100644 internal/cmd/workload/rule_test.go create mode 100644 internal/cmd/workload/rule_view.go diff --git a/.mockery.yml b/.mockery.yml index 5d0b56c..0a275bb 100644 --- a/.mockery.yml +++ b/.mockery.yml @@ -21,3 +21,12 @@ packages: interfaces: PolicyServiceClient: LabelServiceClient: + buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/v1/controltowerv1grpc: + config: + include-auto-generated: true + dir: "internal/cmd/workload/mocks" + pkgname: "mocks" + structname: "{{.InterfaceName}}Mock" + filename: "{{.InterfaceName}}_mock.go" + interfaces: + WorkloadAdminServiceClient: diff --git a/README.md b/README.md index 7c3faca..1838731 100644 --- a/README.md +++ b/README.md @@ -91,6 +91,11 @@ to a project and why. **Audit log**: `safedep audit` See who changed the policy, what, and when. +**Workload identity**: `safedep workload` +Let GitHub Actions jobs call SafeDep Cloud with no API key. Create the trust rules +that say which repositories, refs and events get a credential, and see why a job +got none. + **Security telemetry queries**: `safedep query` Run SQL against SafeDep Cloud's query service. Inspect packages, events, and findings across your entire fleet. @@ -153,6 +158,12 @@ Push SafeDep malware findings to external security tools. JFrog XRay is supporte | [`safedep policy rule delete`](./docs/cmd/policy-rule-delete.md) | Delete a package rule | | [`safedep policy decision list`](./docs/cmd/policy-decision-list.md) | List the decisions that the policy made, and where | | [`safedep audit event list`](./docs/cmd/audit-event-list.md) | List audit events of the tenant | +| [`safedep workload provider list`](./docs/cmd/workload-provider-list.md) | List the workload identity providers of the tenant | +| [`safedep workload rule create`](./docs/cmd/workload-rule-create.md) | Create a workload trust rule | +| [`safedep workload rule list`](./docs/cmd/workload-rule-list.md) | List workload trust rules | +| [`safedep workload rule show`](./docs/cmd/workload-rule-show.md) | Show one workload trust rule | +| [`safedep workload rule delete`](./docs/cmd/workload-rule-delete.md) | Delete a workload trust rule | +| [`safedep workload exchange list`](./docs/cmd/workload-exchange-list.md) | List workload exchanges, newest first | | [`safedep query exec`](./docs/cmd/query-exec.md) | Execute a SQL query against SafeDep Cloud | | [`safedep query schema list`](./docs/cmd/query-schema-list.md) | List tables in the query schema | | [`safedep query schema show`](./docs/cmd/query-schema-show.md) | Show one table from the query schema | diff --git a/docs/cmd/workload-exchange-list.md b/docs/cmd/workload-exchange-list.md new file mode 100644 index 0000000..fa51e83 --- /dev/null +++ b/docs/cmd/workload-exchange-list.md @@ -0,0 +1,63 @@ +# safedep workload exchange list + +List the workload exchanges of the tenant, newest first. Each exchange is one +request of a CI job for a credential: SafeDep issued it or denied it. The server +keeps an exchange for 30 days. + +## Synopsis + +``` +safedep workload exchange list [--denied] [--since DURATION] [--rule RULE] + [--limit N] [--page-token TOKEN] [--output table|plain|json] +``` + +## Flags + +| Flag | Description | +|------|-------------| +| `--denied` | Only the exchanges that the server denied. | +| `--since ` | Only exchanges in this time before now, as `7d` or `12h`. | +| `--rule ` | Only exchanges that this rule matched: a rule id, or the name of a live rule. The id of a deleted rule also works. | +| `--limit ` | Page size. The server default applies when 0. | +| `--page-token ` | Continuation token from a prior response. | + +## Examples + +A CI job got no credential. Find out why: + +```bash +safedep workload exchange list --denied --since 1d +``` + +``` +Workload exchanges +WHEN OUTCOME WORKLOAD RULE DETAIL +5m ago denied github:acme/web@refs/heads/feature-x run 987/1 - no workload trust rule gives TOOL to acme/web on refs/heads/feature-x +1 exchange +``` + +The reason names the missing rule. Create a rule that covers the job with +[`safedep workload rule create`](./workload-rule-create.md). For an issued +exchange, `DETAIL` says when the credential expires, or when it was revoked. + +## Output + +`json` holds `exchanges` (exchange id, outcome, denial reason, rule id, provider +id, grant, display identity, the kept claims, endpoint id, and the times of the +exchange, the expiry and the revocation) and `next_page_token`. `plain` writes a +tab-separated header and one row for each exchange. + +## Permissions + +Needs the Admin role. + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The page was read. | +| non-zero | Validation or the request failed. | diff --git a/docs/cmd/workload-provider-list.md b/docs/cmd/workload-provider-list.md new file mode 100644 index 0000000..e85dfa2 --- /dev/null +++ b/docs/cmd/workload-provider-list.md @@ -0,0 +1,60 @@ +# safedep workload provider list + +List the workload identity providers of the tenant. A provider trusts the +identity tokens of one platform account, such as the GitHub Actions tokens of +the GitHub organization `acme`. A verified link of the SafeDep GitHub App +creates the provider of its account. No command creates a provider. + +## Synopsis + +``` +safedep workload provider list [--limit N] [--page-token TOKEN] [--output table|plain|json] +``` + +## Flags + +| Flag | Description | +|------|-------------| +| `--limit ` | Page size. The server default applies when 0. | +| `--page-token ` | Continuation token from a prior response. | + +## Examples + +```bash +safedep workload provider list +``` + +``` +Workload identity providers +PROVIDER ID OWNER ID LINK CREATED +github-actions:acme wip_7a1 1001 active 2d ago +1 provider +``` + +`PROVIDER` is the `KIND:ACCOUNT` name that +[`safedep workload rule create --provider`](./workload-rule-create.md) takes. +`OWNER ID` is the immutable id of the account. A rule matches this id, never the +account name. A CI job gets a credential only through a provider whose `LINK` is +`active`. `suspended` means that GitHub suspended the installation of the +SafeDep GitHub App. `unlinked` means that the link is gone. + +## Output + +`json` holds `providers` (provider id, name, kind, account login, owner id, link +state, link id, creation time) and `next_page_token`. `plain` writes a +tab-separated header and one row for each provider. + +## Permissions + +Needs the Admin role. + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The page was read. | +| non-zero | Authentication or the request failed. | diff --git a/docs/cmd/workload-rule-create.md b/docs/cmd/workload-rule-create.md new file mode 100644 index 0000000..ed6c944 --- /dev/null +++ b/docs/cmd/workload-rule-create.md @@ -0,0 +1,116 @@ +# safedep workload rule create + +Create a workload trust rule. The rule gives one credential grant to the CI jobs +of one provider whose claims meet every condition of the rule. A job of a GitHub +Actions workflow then calls SafeDep with no API key in the CI secrets. + +## Synopsis + +``` +safedep workload rule create NAME --provider PROVIDER --grant GRANT + [--repository OWNER/NAME...] [--ref REF...] [--event EVENT...] + [--output table|plain|json] +``` + +`NAME` is unique in the tenant: 1 to 63 lowercase letters, digits and hyphens, +as in `org` or `web-release`. + +## Flags + +| Flag | Description | +|------|-------------| +| `--provider ` | The provider of the rule: a provider id or `KIND:ACCOUNT`, as in `github-actions:acme`. Required. | +| `--grant ` | The grant that the rule gives. `tool` lets the job call the RPCs that pmg, vet and the `safedep` CLI use. Required. | +| `--repository ` | A repository by its full name, as in `acme/web`. Repeat the flag, or separate names with commas. | +| `--ref ` | A full ref, as in `refs/heads/main`, or a prefix that ends with `/*`, as in `refs/heads/release/*`. Repeat the flag for more refs. | +| `--event ` | An event name of the platform, as in `push` or `pull_request_target`. Repeat the flag for more events. | + +## The provider is required + +The CLI never picks a provider, even when the tenant has one provider. With no +`--provider`, the command fails and lists the providers of the tenant: + +``` +--provider is required. The CLI never picks a provider. The providers of the tenant: + github-actions:acme id wip_7a1, link active +Run the command again with --provider github-actions:acme +``` + +## Repositories + +The server finds each `--repository` in the account of the provider, through the +installation of the SafeDep GitHub App, and stores its numeric id. The rule +matches the id, so a rename of the repository does not change the rule. The +server refuses a repository that the installation cannot see: + +``` +the GitHub installation of the provider cannot see a repository +other/web is not a repository of the provider account that the installation can see +``` + +A rule with no `--repository` covers every repository of the account, also the +repositories that the installation does not select. The command says so when +it creates such a rule. + +## Conditions + +- `--ref` takes full refs or prefixes, not both. A prefix ends at a `/`, so + `refs/heads/main*` is refused: it would also match `refs/heads/main-evil`. +- A rule with no `--event` covers only the default events of the provider. For + GitHub Actions they are `push`, `pull_request`, `merge_group`, `schedule`, + `workflow_dispatch` and `release`. Any other event, such as `issues` or + `pull_request_target`, matches only a rule that lists it with `--event`. + +The server sets how a repository with no project gets a project. A rule with no +repository creates the project at the first tool session of the repository +(`auto`). A rule with repositories needs a project first (`manual`). + +## Examples + +One rule for every repository of the organization: + +```bash +safedep workload rule create org --provider github-actions:acme --grant tool +``` + +One rule for the release branches of one repository: + +```bash +safedep workload rule create web-release --provider github-actions:acme --grant tool \ + --repository acme/web --ref 'refs/heads/release/*' +``` + +``` +✓ rule web-release created +Rule wtr_9d1 +Name web-release +Provider github-actions:acme +Grant tool +Repositories acme/web (123456) +Conditions ref matches refs/heads/release/* +Projects manual: a repository with no project needs a project before a tool session +Max lifetime 6h +Created now +Last used never +``` + +## Output + +The command prints the rule as [`safedep workload rule show`](./workload-rule-show.md) +does. `json` holds `rule`, with each repository as `repository_id` and +`full_name`, and `every_repository`. + +## Permissions + +Needs the Admin role. The server records an audit event. + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The rule was created. | +| non-zero | Validation failed, the provider is missing or unknown, the server refused a repository, or the request failed. | diff --git a/docs/cmd/workload-rule-delete.md b/docs/cmd/workload-rule-delete.md new file mode 100644 index 0000000..127902b --- /dev/null +++ b/docs/cmd/workload-rule-delete.md @@ -0,0 +1,41 @@ +# safedep workload rule delete + +Delete a workload trust rule by its id or its name. Every workload credential +that the rule gave stops working within 30 seconds, and the CI jobs that the +rule covered get no new credential. + +## Synopsis + +``` +safedep workload rule delete RULE +``` + +## Examples + +```bash +safedep workload rule delete web +``` + +``` +✓ rule wtr_9d1 deleted +Every workload credential that the rule gave stops working within 30 seconds +``` + +The exchanges of the rule stay in +[`safedep workload exchange list --rule`](./workload-exchange-list.md), by the +rule id. + +## Permissions + +Needs the Admin role. The server records an audit event. + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The rule was deleted. | +| non-zero | The rule does not exist, or the request failed. | diff --git a/docs/cmd/workload-rule-list.md b/docs/cmd/workload-rule-list.md new file mode 100644 index 0000000..1c07e4b --- /dev/null +++ b/docs/cmd/workload-rule-list.md @@ -0,0 +1,55 @@ +# safedep workload rule list + +List the workload trust rules of the tenant, oldest first. + +## Synopsis + +``` +safedep workload rule list [--provider PROVIDER] [--limit N] [--page-token TOKEN] + [--output table|plain|json] +``` + +## Flags + +| Flag | Description | +|------|-------------| +| `--provider ` | Only the rules of this provider: a provider id or `KIND:ACCOUNT`, as in `github-actions:acme`. | +| `--limit ` | Page size. The server default applies when 0. | +| `--page-token ` | Continuation token from a prior response. | + +## Examples + +```bash +safedep workload rule list +``` + +``` +Workload trust rules +RULE NAME PROVIDER GRANT REPOSITORIES CONDITIONS LAST USED +wtr_4c2 org github-actions:acme tool every repository of acme - 3m ago +wtr_9d1 web github-actions:acme tool acme/web ref matches refs/heads/release/* never +2 rules +``` + +`CONDITIONS` leaves out the repositories, which `REPOSITORIES` shows. + +## Output + +`json` holds `rules` (each as [`safedep workload rule show`](./workload-rule-show.md) +writes it) and `next_page_token`. `plain` writes a tab-separated header and one +row for each rule. Its `repositories` value has the form `acme/web=123456`. + +## Permissions + +Needs the Admin role. + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The page was read. | +| non-zero | The provider is unknown, or the request failed. | diff --git a/docs/cmd/workload-rule-show.md b/docs/cmd/workload-rule-show.md new file mode 100644 index 0000000..63fde87 --- /dev/null +++ b/docs/cmd/workload-rule-show.md @@ -0,0 +1,56 @@ +# safedep workload rule show + +Show one workload trust rule by its id or its name. + +## Synopsis + +``` +safedep workload rule show RULE [--output table|plain|json] +``` + +## Examples + +```bash +safedep workload rule show web +``` + +``` +Rule wtr_9d1 +Name web +Provider github-actions:acme +Grant tool +Repositories acme/web (123456) +Conditions ref matches refs/heads/release/* +Projects manual: a repository with no project needs a project before a tool session +Max lifetime 6h +Created 10m ago +Last used never +``` + +`Repositories` shows each repository with its numeric id, which the rule +matches. A rule with no repository shows `every repository of acme`. `Projects` +says how a repository with no project gets a project at its first tool session. +`Max lifetime` is the longest life of a credential that the rule gives. + +## Output + +`json` holds `rule`: rule id, name, provider name and id, grant, `repositories` +(`repository_id` and `full_name`), `every_repository`, `conditions` (claim, +operator and values, the `repository_id` condition included), project binding, +max lifetime, creation time and last use. `plain` writes one tab-separated key +and value on each line. + +## Permissions + +Needs the Admin role. + +## Authentication + +Requires a control-plane OAuth session. Run `safedep auth login` first. + +## Exit codes + +| Code | Meaning | +|------|---------| +| `0` | The rule was read. | +| non-zero | The rule does not exist, or the request failed. | diff --git a/internal/cmd/safedep.go b/internal/cmd/safedep.go index f96ac81..f33ea79 100644 --- a/internal/cmd/safedep.go +++ b/internal/cmd/safedep.go @@ -14,6 +14,7 @@ import ( "github.com/safedep/cli/internal/cmd/setup" "github.com/safedep/cli/internal/cmd/subscription" "github.com/safedep/cli/internal/cmd/version" + "github.com/safedep/cli/internal/cmd/workload" "github.com/spf13/cobra" ) @@ -33,5 +34,6 @@ func NewSafedep(a *app.App) *cobra.Command { setup.Register(root, a) subscription.Register(root, a) version.Register(root, a) + workload.Register(root, a) return root } diff --git a/internal/cmd/workload/cmd.go b/internal/cmd/workload/cmd.go new file mode 100644 index 0000000..2dd20db --- /dev/null +++ b/internal/cmd/workload/cmd.go @@ -0,0 +1,61 @@ +// Package workload registers the `safedep workload` command tree. It manages +// workload identity in SafeDep Cloud: the workload identity providers of the +// tenant, the workload trust rules that let CI jobs of a provider call +// SafeDep with no long-lived key, and the record of each workload exchange. +// Every verb needs control plane credentials and the Admin role. +package workload + +import ( + controltowerv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/v1/controltowerv1grpc" + "github.com/spf13/cobra" + + "github.com/safedep/cli/internal/app" +) + +func Register(root *cobra.Command, a *app.App) { + parent := &cobra.Command{ + Use: "workload", + Short: "Manage workload identity for CI jobs", + Long: "Manage workload identity in your SafeDep Cloud tenant. A CI job, such as a GitHub Actions job, " + + "trades the identity token of its platform for a short-lived SafeDep credential, with no API key " + + "in the CI secrets. A workload identity provider trusts the tokens of one platform account. A " + + "workload trust rule says which jobs of a provider get a credential. Every command needs the Admin role.", + } + + provider := &cobra.Command{ + Use: "provider", + Short: "Inspect workload identity providers", + Long: "Inspect the workload identity providers of the tenant. A verified GitHub App link creates the " + + "provider of its GitHub account. No command creates a provider.", + } + provider.AddCommand(providerListCmd(a)) + + rule := &cobra.Command{ + Use: "rule", + Short: "Manage workload trust rules", + Long: "Manage workload trust rules. A rule gives one credential grant to the jobs of one provider whose " + + "verified claims meet every condition of the rule. A rule stays live until you delete it.", + } + rule.AddCommand(ruleCreateCmd(a), ruleListCmd(a), ruleShowCmd(a), ruleDeleteCmd(a)) + + exchange := &cobra.Command{ + Use: "exchange", + Short: "Inspect workload exchanges", + Long: "Inspect the workload exchanges of the tenant: each time a CI job asked for a credential, and " + + "whether SafeDep issued or denied it.", + } + exchange.AddCommand(exchangeListCmd(a)) + + parent.AddCommand(provider, rule, exchange) + root.AddCommand(parent) +} + +// adminClient connects to the workload admin service with the control plane +// credentials of the active profile. +func adminClient(a *app.App) (controltowerv1grpc.WorkloadAdminServiceClient, error) { + client, err := a.ControlPlane() + if err != nil { + return nil, err + } + return controltowerv1grpc.NewWorkloadAdminServiceClient(client.Connection()), nil +} diff --git a/internal/cmd/workload/errors.go b/internal/cmd/workload/errors.go new file mode 100644 index 0000000..13eac2e --- /dev/null +++ b/internal/cmd/workload/errors.go @@ -0,0 +1,123 @@ +package workload + +import ( + "errors" + "fmt" + "strings" + + errorv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/error/v1" + "github.com/safedep/dry/usefulerror" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/safedep/cli/internal/rpcerror" + "github.com/safedep/cli/internal/tui" +) + +func newWorkloadError(code, humanError, help string, cause error) error { + return usefulerror.NewUsefulError(). + WithCode(code). + WithHumanError(humanError). + WithHelp(help). + Wrap(cause) +} + +func invalidInputError(humanError, help string) error { + return newWorkloadError(usefulerror.ErrBadRequest, humanError, help, errors.New(humanError)) +} + +// mapError gives the recovery for the errors that every workload admin RPC +// can return. command is the command path after "safedep workload", as in +// "rule create". +func mapError(command string, err error) error { + cause := fmt.Errorf("workload %s: %w", command, err) + st, ok := status.FromError(err) + if !ok { + return cause + } + switch st.Code() { + case codes.PermissionDenied: + return newWorkloadError(usefulerror.ErrAuthorizationFailed, + "Only an Admin can manage workload identity", + "Ask an Admin of the tenant to run the command", + cause) + case codes.InvalidArgument: + // The generic conversion shows only "Invalid request", and the user + // cannot find the value to fix. + return newWorkloadError(usefulerror.ErrBadRequest, + rpcerror.Describe(err, rpcerror.AsIs), + "See the flags: safedep workload "+command+" --help", + cause) + } + return cause +} + +// mapRuleError gives the recovery for a rule that the tenant does not have. +func mapRuleError(command, rule string, err error) error { + if status.Code(err) == codes.NotFound { + return newWorkloadError(usefulerror.ErrNotFound, + fmt.Sprintf("Workload trust rule %s does not exist", tui.EscapeLine(rule)), + "List the rules: safedep workload rule list", + fmt.Errorf("workload %s: %w", command, err)) + } + return mapError(command, err) +} + +// mapRuleCreateError gives the recovery for each refusal of a rule create. +// provider is the provider of the rule as the user knows it, as in +// github-actions:acme. +func mapRuleCreateError(name, provider string, err error) error { + cause := fmt.Errorf("workload rule create: %w", err) + provider = tui.EscapeLine(provider) + switch reason, _ := usefulerror.ReasonOf(err); reason { + case errorv1.ErrorReason_ERROR_REASON_GITHUB_REPOSITORY_NOT_ACCESSIBLE: + return newWorkloadError(usefulerror.ErrNotFound, + repositoriesNotAccessible(err), + fmt.Sprintf("Name only repositories of %s that the SafeDep GitHub App installation can see. "+ + "An owner of the GitHub organization can add a repository to the installation in the GitHub "+ + "settings of the organization", provider), + cause) + case errorv1.ErrorReason_ERROR_REASON_GITHUB_INSTALLATION_SUSPENDED: + return newWorkloadError(usefulerror.ErrConflict, + fmt.Sprintf("GitHub suspended the SafeDep GitHub App installation of %s", provider), + "An owner of the GitHub organization can end the suspension in the GitHub settings of the "+ + "organization. Then run the command again", + cause) + } + switch status.Code(err) { + case codes.NotFound: + return newWorkloadError(usefulerror.ErrNotFound, + fmt.Sprintf("Workload identity provider %s is not a provider of the tenant", provider), + "List the providers: safedep workload provider list", + cause) + case codes.FailedPrecondition: + return newWorkloadError(usefulerror.ErrConflict, + "The server refused the rule: "+rpcerror.Describe(err, rpcerror.AsIs), + "Link the GitHub organization again with the SafeDep GitHub App in SafeDep Cloud. "+ + "See the link state: safedep workload provider list", + cause) + case codes.AlreadyExists: + return newWorkloadError(usefulerror.ErrConflict, + fmt.Sprintf("A workload trust rule with the name %s exists", tui.EscapeLine(name)), + "See it with: safedep workload rule show "+tui.EscapeLine(name), + cause) + case codes.Unavailable: + return newWorkloadError(usefulerror.ErrServiceUnavailable, + "The server could not read the repositories from GitHub: "+rpcerror.Describe(err, rpcerror.AsIs), + "Run the command again later", + cause) + } + return mapError("rule create", err) +} + +// repositoriesNotAccessible lists each repository that the installation +// cannot see. The server names each one in the description of a field +// violation on repositories[i], so the field adds nothing. +func repositoriesNotAccessible(err error) string { + return rpcerror.Describe(err, func(field, description string) (string, string) { + if strings.HasPrefix(field, "repositories[") { + return "", description + } + return field, description + }) +} diff --git a/internal/cmd/workload/exchange.go b/internal/cmd/workload/exchange.go new file mode 100644 index 0000000..4026293 --- /dev/null +++ b/internal/cmd/workload/exchange.go @@ -0,0 +1,159 @@ +package workload + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "time" + + controltowerv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/v1/controltowerv1grpc" + controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" + "github.com/safedep/dry/tui/humanize" + "github.com/safedep/dry/tui/table" + "github.com/spf13/cobra" + "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" + "github.com/safedep/cli/internal/duration" + "github.com/safedep/cli/internal/paging" + "github.com/safedep/cli/internal/tui" +) + +const outcomePrefix = "WORKLOAD_EXCHANGE_OUTCOME_" + +type exchangeListInput struct { + Denied bool + Since time.Duration + Rule string + PageSize uint32 + PageToken string +} + +type exchangeListResult struct { + Exchanges []exchangeView `json:"exchanges"` + NextPageToken string `json:"next_page_token,omitempty"` +} + +func exchangeListCmd(a *app.App) *cobra.Command { + var in exchangeListInput + cmd := &cobra.Command{ + Use: "list", + Short: "List workload exchanges, newest first", + Long: "List the workload exchanges of the tenant, newest first: each time a CI job asked for a " + + "credential, the workload, the rule that matched, and the state of the credential. A denied " + + "exchange says which rule is missing. --since takes a duration before now, as in 7d or 12h. " + + "--rule takes a rule id or the name of a live rule. The server keeps an exchange for 30 days. " + + "The command reads one page. Pass --page-token to read the next page.", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + client, err := adminClient(a) + if err != nil { + return err + } + res, err := runExchangeList(cmd.Context(), client, in, time.Now()) + if err != nil { + return err + } + return a.Output.Print(res) + }, + } + f := cmd.Flags() + f.BoolVar(&in.Denied, "denied", false, "only the exchanges that the server denied") + f.Var(duration.NewValue(&in.Since, 0), "since", "only exchanges in this time before now, as in 7d or 12h") + f.StringVar(&in.Rule, "rule", "", "only exchanges that this rule matched, by rule id or name") + f.Uint32Var(&in.PageSize, "limit", 0, "page size, or the server default when 0") + f.StringVar(&in.PageToken, "page-token", "", "continuation token from a prior response") + return cmd +} + +func runExchangeList( + ctx context.Context, + client controltowerv1grpc.WorkloadAdminServiceClient, + in exchangeListInput, + now time.Time, +) (*exchangeListResult, error) { + filters := &controltowerv1.ListWorkloadExchangesRequest_Filters{} + set := false + after, _, err := duration.Window(in.Since, 0, now, "exchanges") + if err != nil { + return nil, err + } + if after != nil { + filters.SetSince(timestamppb.New(*after)) + set = true + } + if in.Denied { + filters.SetOutcome(controltowerv1.WorkloadExchangeOutcome_WORKLOAD_EXCHANGE_OUTCOME_DENIED) + set = true + } + if in.Rule != "" { + id, err := ruleIDOf(ctx, client, "exchange list", in.Rule) + if err != nil { + return nil, err + } + filters.SetRuleId(id) + set = true + } + + req := &controltowerv1.ListWorkloadExchangesRequest{} + req.SetPagination(paging.NewPaginationRequest(in.PageSize, in.PageToken)) + if set { + req.SetFilters(filters) + } + res, err := client.ListWorkloadExchanges(ctx, req) + if err != nil { + return nil, mapError("exchange list", err) + } + out := &exchangeListResult{ + Exchanges: make([]exchangeView, 0, len(res.GetExchanges())), + NextPageToken: res.GetPagination().GetNextPageToken(), + } + for _, e := range res.GetExchanges() { + out.Exchanges = append(out.Exchanges, newExchangeView(e)) + } + return out, nil +} + +func (r *exchangeListResult) RenderJSON() ([]byte, error) { + return json.MarshalIndent(r, "", " ") +} + +func (r *exchangeListResult) RenderTable() string { + now := time.Now() + rows := make([][]string, 0, len(r.Exchanges)) + for _, e := range r.Exchanges { + when := "-" + if e.created != nil { + when = humanize.Time(*e.created, now) + } + rows = append(rows, []string{ + when, e.Outcome, cloudpolicy.EmptyDash(e.DisplayIdentity), cloudpolicy.EmptyDash(e.RuleID), e.detail(now), + }) + } + t := table.New(). + Title("Workload exchanges"). + Headers("WHEN", "OUTCOME", "WORKLOAD", "RULE", "DETAIL"). + Rows(tui.EscapeCells(rows)...). + EmptyMessage("No workload exchanges match. Try a wider --since window.") + if len(rows) > 0 { + footer := fmt.Sprintf("%d %s", len(rows), cloudpolicy.Plural(len(rows), "exchange", "exchanges")) + if r.NextPageToken != "" { + footer += ". More available: --page-token " + r.NextPageToken + } + t = t.Footer(footer) + } + return t.Render() +} + +func (r *exchangeListResult) RenderPlain() string { + var b strings.Builder + b.WriteString("created_at\texchange_id\toutcome\tdisplay_identity\trule_id\tprovider_id\tgrant\tendpoint_id\t" + + "expires_at\trevoked_at\tdenial_reason") + for _, e := range r.Exchanges { + b.WriteString("\n" + tui.PlainRow(e.CreatedAt, e.ID, e.Outcome, e.DisplayIdentity, e.RuleID, e.ProviderID, + e.Grant, e.EndpointID, e.ExpiresAt, e.RevokedAt, e.DenialReason)) + } + return b.String() +} diff --git a/internal/cmd/workload/exchange_test.go b/internal/cmd/workload/exchange_test.go new file mode 100644 index 0000000..c11994b --- /dev/null +++ b/internal/cmd/workload/exchange_test.go @@ -0,0 +1,101 @@ +package workload + +import ( + "context" + "testing" + "time" + + controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + "github.com/safedep/cli/internal/cmd/workload/mocks" +) + +func TestRunExchangeList_Filters(t *testing.T) { + now := time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC) + tests := []struct { + name string + in exchangeListInput + rules *controltowerv1.ListWorkloadTrustRulesResponse + check func(t *testing.T, f *controltowerv1.ListWorkloadExchangesRequest_Filters, hasFilters bool) + }{ + { + name: "no filter", + check: func(t *testing.T, _ *controltowerv1.ListWorkloadExchangesRequest_Filters, hasFilters bool) { + assert.False(t, hasFilters) + }, + }, + { + name: "denied since 7d", + in: exchangeListInput{Denied: true, Since: 7 * 24 * time.Hour}, + check: func(t *testing.T, f *controltowerv1.ListWorkloadExchangesRequest_Filters, _ bool) { + assert.Equal(t, controltowerv1.WorkloadExchangeOutcome_WORKLOAD_EXCHANGE_OUTCOME_DENIED, f.GetOutcome()) + assert.Equal(t, now.Add(-7*24*time.Hour), f.GetSince().AsTime()) + assert.False(t, f.HasRuleId()) + }, + }, + { + name: "a rule by name", + in: exchangeListInput{Rule: "org"}, + rules: rulesResponse(trustRule("r_web", "web", nil), trustRule("r_org", "org", nil)), + check: func(t *testing.T, f *controltowerv1.ListWorkloadExchangesRequest_Filters, _ bool) { + assert.Equal(t, "r_org", f.GetRuleId()) + assert.False(t, f.HasOutcome()) + assert.False(t, f.HasSince()) + }, + }, + { + name: "a deleted rule by id", + in: exchangeListInput{Rule: "r_gone"}, + rules: rulesResponse(trustRule("r_org", "org", nil)), + check: func(t *testing.T, f *controltowerv1.ListWorkloadExchangesRequest_Filters, _ bool) { + assert.Equal(t, "r_gone", f.GetRuleId()) + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + client := mocks.NewWorkloadAdminServiceClientMock(t) + if tt.rules != nil { + client.EXPECT().ListWorkloadTrustRules(mock.Anything, mock.Anything).Return(tt.rules, nil) + } + var sent *controltowerv1.ListWorkloadExchangesRequest + client.EXPECT().ListWorkloadExchanges(mock.Anything, mock.MatchedBy(func(r *controltowerv1.ListWorkloadExchangesRequest) bool { + sent = r + return true + })).Return(&controltowerv1.ListWorkloadExchangesResponse{}, nil) + + _, err := runExchangeList(context.Background(), client, tt.in, now) + + require.NoError(t, err) + require.NotNil(t, sent) + tt.check(t, sent.GetFilters(), sent.HasFilters()) + }) + } +} + +func TestExchangeView_Detail(t *testing.T) { + now := time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC) + at := func(d time.Duration) *time.Time { + t := now.Add(d) + return &t + } + tests := []struct { + name string + view exchangeView + want string + }{ + {name: "denied", view: exchangeView{DenialReason: "no workload trust rule gives TOOL to acme/web on refs/heads/x"}, + want: "no workload trust rule gives TOOL to acme/web on refs/heads/x"}, + {name: "revoked before its expiry", view: exchangeView{expires: at(time.Hour), revoked: at(-2 * time.Minute)}, want: "revoked 2m ago"}, + {name: "live", view: exchangeView{expires: at(5 * time.Minute)}, want: "expires in 5m"}, + {name: "expired", view: exchangeView{expires: at(-3 * time.Hour)}, want: "expired 3h ago"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, tt.view.detail(now)) + }) + } +} diff --git a/internal/cmd/workload/exchange_view.go b/internal/cmd/workload/exchange_view.go new file mode 100644 index 0000000..e80a1ad --- /dev/null +++ b/internal/cmd/workload/exchange_view.go @@ -0,0 +1,78 @@ +package workload + +import ( + "time" + + controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" + "github.com/safedep/dry/tui/humanize" + + "github.com/safedep/cli/internal/cloudpolicy" + "github.com/safedep/cli/internal/tui" +) + +type exchangeView struct { + ID string `json:"exchange_id"` + Outcome string `json:"outcome"` + DenialReason string `json:"denial_reason,omitempty"` + RuleID string `json:"rule_id,omitempty"` + ProviderID string `json:"provider_id,omitempty"` + Grant string `json:"grant"` + DisplayIdentity string `json:"display_identity"` + Claims map[string]string `json:"claims,omitempty"` + EndpointID string `json:"endpoint_id,omitempty"` + CreatedAt string `json:"created_at,omitempty"` + ExpiresAt string `json:"expires_at,omitempty"` + RevokedAt string `json:"revoked_at,omitempty"` + created *time.Time + expires *time.Time + revoked *time.Time +} + +func newExchangeView(e *controltowerv1.WorkloadExchange) exchangeView { + v := exchangeView{ + ID: e.GetExchangeId(), + Outcome: tui.EnumToken(e.GetOutcome().String(), outcomePrefix), + DenialReason: e.GetDenialReason(), + RuleID: e.GetRuleId(), + ProviderID: e.GetProviderId(), + Grant: grantToken(e.GetGrant()), + DisplayIdentity: e.GetClaimSummary().GetDisplayIdentity(), + EndpointID: e.GetEndpointId(), + created: cloudpolicy.TimeOf(e.GetCreatedAt()), + expires: cloudpolicy.TimeOf(e.GetExpiresAt()), + revoked: cloudpolicy.TimeOf(e.GetRevokedAt()), + } + if claims := e.GetClaimSummary().GetClaims(); len(claims) > 0 { + v.Claims = make(map[string]string, len(claims)) + for _, c := range claims { + v.Claims[c.GetName()] = c.GetValue() + } + } + v.CreatedAt = rfc3339(v.created) + v.ExpiresAt = rfc3339(v.expires) + v.RevokedAt = rfc3339(v.revoked) + return v +} + +func rfc3339(t *time.Time) string { + if t == nil { + return "" + } + return t.Format(time.RFC3339) +} + +// detail is what a person needs from one exchange: why the server denied +// it, or the state of the credential that it issued. +func (v exchangeView) detail(now time.Time) string { + switch { + case v.DenialReason != "": + return v.DenialReason + case v.revoked != nil: + return "revoked " + humanize.Time(*v.revoked, now) + case v.expires != nil && v.expires.After(now): + return "expires " + humanize.Time(*v.expires, now) + case v.expires != nil: + return "expired " + humanize.Time(*v.expires, now) + } + return "-" +} diff --git a/internal/cmd/workload/fixtures_test.go b/internal/cmd/workload/fixtures_test.go new file mode 100644 index 0000000..c528736 --- /dev/null +++ b/internal/cmd/workload/fixtures_test.go @@ -0,0 +1,94 @@ +package workload + +import ( + "bytes" + "os" + "testing" + + messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" + controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" + "github.com/safedep/dry/tui/output" + "github.com/safedep/dry/usefulerror" + "github.com/stretchr/testify/require" +) + +const githubActions = controltowerv1.WorkloadIdentityProviderKind_WORKLOAD_IDENTITY_PROVIDER_KIND_GITHUB_ACTIONS + +func githubProvider(id, login string, state controltowerv1.WorkloadIdentityProviderLinkState) *controltowerv1.WorkloadIdentityProvider { + return controltowerv1.WorkloadIdentityProvider_builder{ + ProviderId: id, + Kind: githubActions, + OwnerId: "1001", + AccountLogin: login, + LinkState: state, + LinkId: "link-" + id, + }.Build() +} + +func activeProvider(id, login string) *controltowerv1.WorkloadIdentityProvider { + return githubProvider(id, login, controltowerv1.WorkloadIdentityProviderLinkState_WORKLOAD_IDENTITY_PROVIDER_LINK_STATE_ACTIVE) +} + +func providersResponse(providers ...*controltowerv1.WorkloadIdentityProvider) *controltowerv1.ListWorkloadIdentityProvidersResponse { + return controltowerv1.ListWorkloadIdentityProvidersResponse_builder{Providers: providers}.Build() +} + +func condition(claim string, operator controltowerv1.ClaimConditionOperator, values ...string) *controltowerv1.WorkloadClaimCondition { + return controltowerv1.WorkloadClaimCondition_builder{Claim: claim, Operator: operator, Values: values}.Build() +} + +const ( + equals = controltowerv1.ClaimConditionOperator_CLAIM_CONDITION_OPERATOR_EQUALS + prefix = controltowerv1.ClaimConditionOperator_CLAIM_CONDITION_OPERATOR_PREFIX +) + +// trustRule is a rule of the provider prov_acme. repositories maps full +// names to ids. A rule with repositories has the repository_id condition +// that the server makes from them. +func trustRule(id, name string, repositories map[string]string, conditions ...*controltowerv1.WorkloadClaimCondition) *controltowerv1.WorkloadTrustRule { + var repos []*controltowerv1.WorkloadRepository + var ids []string + for fullName, repoID := range repositories { + repos = append(repos, controltowerv1.WorkloadRepository_builder{RepositoryId: repoID, FullName: fullName}.Build()) + ids = append(ids, repoID) + } + if len(ids) > 0 { + conditions = append(conditions, condition(claimRepositoryID, equals, ids...)) + } + return controltowerv1.WorkloadTrustRule_builder{ + RuleId: id, + Name: name, + ProviderId: "prov_acme", + Grant: messagescontroltowerv1.CredentialGrant_CREDENTIAL_GRANT_TOOL, + Conditions: conditions, + Repositories: repos, + ProjectBinding: controltowerv1.WorkloadProjectBinding_WORKLOAD_PROJECT_BINDING_MANUAL, + }.Build() +} + +func rulesResponse(rules ...*controltowerv1.WorkloadTrustRule) *controltowerv1.ListWorkloadTrustRulesResponse { + return controltowerv1.ListWorkloadTrustRulesResponse_builder{Rules: rules}.Build() +} + +type usefulErrorWant struct { + code string + human string + help string +} + +func requireUsefulError(t require.TestingT, err error, want usefulErrorWant) { + ue, ok := usefulerror.AsUsefulError(err) + require.True(t, ok, "want a useful error, got %v", err) + require.Equal(t, want.code, ue.Code()) + require.Equal(t, want.human, ue.HumanError()) + require.Equal(t, want.help, ue.Help()) +} + +// captureStderr sends the messages of dry/tui to a buffer for one test. +func captureStderr(t *testing.T) *bytes.Buffer { + t.Helper() + var buf bytes.Buffer + output.SetWriters(os.Stdout, &buf) + t.Cleanup(func() { output.SetWriters(os.Stdout, os.Stderr) }) + return &buf +} diff --git a/internal/cmd/workload/mocks/WorkloadAdminServiceClient_mock.go b/internal/cmd/workload/mocks/WorkloadAdminServiceClient_mock.go new file mode 100644 index 0000000..eaac239 --- /dev/null +++ b/internal/cmd/workload/mocks/WorkloadAdminServiceClient_mock.go @@ -0,0 +1,538 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mocks + +import ( + "context" + + "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" + mock "github.com/stretchr/testify/mock" + "google.golang.org/grpc" +) + +// NewWorkloadAdminServiceClientMock creates a new instance of WorkloadAdminServiceClientMock. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewWorkloadAdminServiceClientMock(t interface { + mock.TestingT + Cleanup(func()) +}) *WorkloadAdminServiceClientMock { + mock := &WorkloadAdminServiceClientMock{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// WorkloadAdminServiceClientMock is an autogenerated mock type for the WorkloadAdminServiceClient type +type WorkloadAdminServiceClientMock struct { + mock.Mock +} + +type WorkloadAdminServiceClientMock_Expecter struct { + mock *mock.Mock +} + +func (_m *WorkloadAdminServiceClientMock) EXPECT() *WorkloadAdminServiceClientMock_Expecter { + return &WorkloadAdminServiceClientMock_Expecter{mock: &_m.Mock} +} + +// CreateWorkloadTrustRule provides a mock function for the type WorkloadAdminServiceClientMock +func (_mock *WorkloadAdminServiceClientMock) CreateWorkloadTrustRule(ctx context.Context, in *controltowerv1.CreateWorkloadTrustRuleRequest, opts ...grpc.CallOption) (*controltowerv1.CreateWorkloadTrustRuleResponse, error) { + var tmpRet mock.Arguments + if len(opts) > 0 { + tmpRet = _mock.Called(ctx, in, opts) + } else { + tmpRet = _mock.Called(ctx, in) + } + ret := tmpRet + + if len(ret) == 0 { + panic("no return value specified for CreateWorkloadTrustRule") + } + + var r0 *controltowerv1.CreateWorkloadTrustRuleResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *controltowerv1.CreateWorkloadTrustRuleRequest, ...grpc.CallOption) (*controltowerv1.CreateWorkloadTrustRuleResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *controltowerv1.CreateWorkloadTrustRuleRequest, ...grpc.CallOption) *controltowerv1.CreateWorkloadTrustRuleResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*controltowerv1.CreateWorkloadTrustRuleResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *controltowerv1.CreateWorkloadTrustRuleRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// WorkloadAdminServiceClientMock_CreateWorkloadTrustRule_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateWorkloadTrustRule' +type WorkloadAdminServiceClientMock_CreateWorkloadTrustRule_Call struct { + *mock.Call +} + +// CreateWorkloadTrustRule is a helper method to define mock.On call +// - ctx context.Context +// - in *controltowerv1.CreateWorkloadTrustRuleRequest +// - opts ...grpc.CallOption +func (_e *WorkloadAdminServiceClientMock_Expecter) CreateWorkloadTrustRule(ctx interface{}, in interface{}, opts ...interface{}) *WorkloadAdminServiceClientMock_CreateWorkloadTrustRule_Call { + return &WorkloadAdminServiceClientMock_CreateWorkloadTrustRule_Call{Call: _e.mock.On("CreateWorkloadTrustRule", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *WorkloadAdminServiceClientMock_CreateWorkloadTrustRule_Call) Run(run func(ctx context.Context, in *controltowerv1.CreateWorkloadTrustRuleRequest, opts ...grpc.CallOption)) *WorkloadAdminServiceClientMock_CreateWorkloadTrustRule_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *controltowerv1.CreateWorkloadTrustRuleRequest + if args[1] != nil { + arg1 = args[1].(*controltowerv1.CreateWorkloadTrustRuleRequest) + } + var arg2 []grpc.CallOption + var variadicArgs []grpc.CallOption + if len(args) > 2 { + variadicArgs = args[2].([]grpc.CallOption) + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *WorkloadAdminServiceClientMock_CreateWorkloadTrustRule_Call) Return(createWorkloadTrustRuleResponse *controltowerv1.CreateWorkloadTrustRuleResponse, err error) *WorkloadAdminServiceClientMock_CreateWorkloadTrustRule_Call { + _c.Call.Return(createWorkloadTrustRuleResponse, err) + return _c +} + +func (_c *WorkloadAdminServiceClientMock_CreateWorkloadTrustRule_Call) RunAndReturn(run func(ctx context.Context, in *controltowerv1.CreateWorkloadTrustRuleRequest, opts ...grpc.CallOption) (*controltowerv1.CreateWorkloadTrustRuleResponse, error)) *WorkloadAdminServiceClientMock_CreateWorkloadTrustRule_Call { + _c.Call.Return(run) + return _c +} + +// DeleteWorkloadTrustRule provides a mock function for the type WorkloadAdminServiceClientMock +func (_mock *WorkloadAdminServiceClientMock) DeleteWorkloadTrustRule(ctx context.Context, in *controltowerv1.DeleteWorkloadTrustRuleRequest, opts ...grpc.CallOption) (*controltowerv1.DeleteWorkloadTrustRuleResponse, error) { + var tmpRet mock.Arguments + if len(opts) > 0 { + tmpRet = _mock.Called(ctx, in, opts) + } else { + tmpRet = _mock.Called(ctx, in) + } + ret := tmpRet + + if len(ret) == 0 { + panic("no return value specified for DeleteWorkloadTrustRule") + } + + var r0 *controltowerv1.DeleteWorkloadTrustRuleResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *controltowerv1.DeleteWorkloadTrustRuleRequest, ...grpc.CallOption) (*controltowerv1.DeleteWorkloadTrustRuleResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *controltowerv1.DeleteWorkloadTrustRuleRequest, ...grpc.CallOption) *controltowerv1.DeleteWorkloadTrustRuleResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*controltowerv1.DeleteWorkloadTrustRuleResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *controltowerv1.DeleteWorkloadTrustRuleRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// WorkloadAdminServiceClientMock_DeleteWorkloadTrustRule_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeleteWorkloadTrustRule' +type WorkloadAdminServiceClientMock_DeleteWorkloadTrustRule_Call struct { + *mock.Call +} + +// DeleteWorkloadTrustRule is a helper method to define mock.On call +// - ctx context.Context +// - in *controltowerv1.DeleteWorkloadTrustRuleRequest +// - opts ...grpc.CallOption +func (_e *WorkloadAdminServiceClientMock_Expecter) DeleteWorkloadTrustRule(ctx interface{}, in interface{}, opts ...interface{}) *WorkloadAdminServiceClientMock_DeleteWorkloadTrustRule_Call { + return &WorkloadAdminServiceClientMock_DeleteWorkloadTrustRule_Call{Call: _e.mock.On("DeleteWorkloadTrustRule", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *WorkloadAdminServiceClientMock_DeleteWorkloadTrustRule_Call) Run(run func(ctx context.Context, in *controltowerv1.DeleteWorkloadTrustRuleRequest, opts ...grpc.CallOption)) *WorkloadAdminServiceClientMock_DeleteWorkloadTrustRule_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *controltowerv1.DeleteWorkloadTrustRuleRequest + if args[1] != nil { + arg1 = args[1].(*controltowerv1.DeleteWorkloadTrustRuleRequest) + } + var arg2 []grpc.CallOption + var variadicArgs []grpc.CallOption + if len(args) > 2 { + variadicArgs = args[2].([]grpc.CallOption) + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *WorkloadAdminServiceClientMock_DeleteWorkloadTrustRule_Call) Return(deleteWorkloadTrustRuleResponse *controltowerv1.DeleteWorkloadTrustRuleResponse, err error) *WorkloadAdminServiceClientMock_DeleteWorkloadTrustRule_Call { + _c.Call.Return(deleteWorkloadTrustRuleResponse, err) + return _c +} + +func (_c *WorkloadAdminServiceClientMock_DeleteWorkloadTrustRule_Call) RunAndReturn(run func(ctx context.Context, in *controltowerv1.DeleteWorkloadTrustRuleRequest, opts ...grpc.CallOption) (*controltowerv1.DeleteWorkloadTrustRuleResponse, error)) *WorkloadAdminServiceClientMock_DeleteWorkloadTrustRule_Call { + _c.Call.Return(run) + return _c +} + +// GetWorkloadTrustRule provides a mock function for the type WorkloadAdminServiceClientMock +func (_mock *WorkloadAdminServiceClientMock) GetWorkloadTrustRule(ctx context.Context, in *controltowerv1.GetWorkloadTrustRuleRequest, opts ...grpc.CallOption) (*controltowerv1.GetWorkloadTrustRuleResponse, error) { + var tmpRet mock.Arguments + if len(opts) > 0 { + tmpRet = _mock.Called(ctx, in, opts) + } else { + tmpRet = _mock.Called(ctx, in) + } + ret := tmpRet + + if len(ret) == 0 { + panic("no return value specified for GetWorkloadTrustRule") + } + + var r0 *controltowerv1.GetWorkloadTrustRuleResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *controltowerv1.GetWorkloadTrustRuleRequest, ...grpc.CallOption) (*controltowerv1.GetWorkloadTrustRuleResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *controltowerv1.GetWorkloadTrustRuleRequest, ...grpc.CallOption) *controltowerv1.GetWorkloadTrustRuleResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*controltowerv1.GetWorkloadTrustRuleResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *controltowerv1.GetWorkloadTrustRuleRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// WorkloadAdminServiceClientMock_GetWorkloadTrustRule_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetWorkloadTrustRule' +type WorkloadAdminServiceClientMock_GetWorkloadTrustRule_Call struct { + *mock.Call +} + +// GetWorkloadTrustRule is a helper method to define mock.On call +// - ctx context.Context +// - in *controltowerv1.GetWorkloadTrustRuleRequest +// - opts ...grpc.CallOption +func (_e *WorkloadAdminServiceClientMock_Expecter) GetWorkloadTrustRule(ctx interface{}, in interface{}, opts ...interface{}) *WorkloadAdminServiceClientMock_GetWorkloadTrustRule_Call { + return &WorkloadAdminServiceClientMock_GetWorkloadTrustRule_Call{Call: _e.mock.On("GetWorkloadTrustRule", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *WorkloadAdminServiceClientMock_GetWorkloadTrustRule_Call) Run(run func(ctx context.Context, in *controltowerv1.GetWorkloadTrustRuleRequest, opts ...grpc.CallOption)) *WorkloadAdminServiceClientMock_GetWorkloadTrustRule_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *controltowerv1.GetWorkloadTrustRuleRequest + if args[1] != nil { + arg1 = args[1].(*controltowerv1.GetWorkloadTrustRuleRequest) + } + var arg2 []grpc.CallOption + var variadicArgs []grpc.CallOption + if len(args) > 2 { + variadicArgs = args[2].([]grpc.CallOption) + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *WorkloadAdminServiceClientMock_GetWorkloadTrustRule_Call) Return(getWorkloadTrustRuleResponse *controltowerv1.GetWorkloadTrustRuleResponse, err error) *WorkloadAdminServiceClientMock_GetWorkloadTrustRule_Call { + _c.Call.Return(getWorkloadTrustRuleResponse, err) + return _c +} + +func (_c *WorkloadAdminServiceClientMock_GetWorkloadTrustRule_Call) RunAndReturn(run func(ctx context.Context, in *controltowerv1.GetWorkloadTrustRuleRequest, opts ...grpc.CallOption) (*controltowerv1.GetWorkloadTrustRuleResponse, error)) *WorkloadAdminServiceClientMock_GetWorkloadTrustRule_Call { + _c.Call.Return(run) + return _c +} + +// ListWorkloadExchanges provides a mock function for the type WorkloadAdminServiceClientMock +func (_mock *WorkloadAdminServiceClientMock) ListWorkloadExchanges(ctx context.Context, in *controltowerv1.ListWorkloadExchangesRequest, opts ...grpc.CallOption) (*controltowerv1.ListWorkloadExchangesResponse, error) { + var tmpRet mock.Arguments + if len(opts) > 0 { + tmpRet = _mock.Called(ctx, in, opts) + } else { + tmpRet = _mock.Called(ctx, in) + } + ret := tmpRet + + if len(ret) == 0 { + panic("no return value specified for ListWorkloadExchanges") + } + + var r0 *controltowerv1.ListWorkloadExchangesResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *controltowerv1.ListWorkloadExchangesRequest, ...grpc.CallOption) (*controltowerv1.ListWorkloadExchangesResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *controltowerv1.ListWorkloadExchangesRequest, ...grpc.CallOption) *controltowerv1.ListWorkloadExchangesResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*controltowerv1.ListWorkloadExchangesResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *controltowerv1.ListWorkloadExchangesRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// WorkloadAdminServiceClientMock_ListWorkloadExchanges_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListWorkloadExchanges' +type WorkloadAdminServiceClientMock_ListWorkloadExchanges_Call struct { + *mock.Call +} + +// ListWorkloadExchanges is a helper method to define mock.On call +// - ctx context.Context +// - in *controltowerv1.ListWorkloadExchangesRequest +// - opts ...grpc.CallOption +func (_e *WorkloadAdminServiceClientMock_Expecter) ListWorkloadExchanges(ctx interface{}, in interface{}, opts ...interface{}) *WorkloadAdminServiceClientMock_ListWorkloadExchanges_Call { + return &WorkloadAdminServiceClientMock_ListWorkloadExchanges_Call{Call: _e.mock.On("ListWorkloadExchanges", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *WorkloadAdminServiceClientMock_ListWorkloadExchanges_Call) Run(run func(ctx context.Context, in *controltowerv1.ListWorkloadExchangesRequest, opts ...grpc.CallOption)) *WorkloadAdminServiceClientMock_ListWorkloadExchanges_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *controltowerv1.ListWorkloadExchangesRequest + if args[1] != nil { + arg1 = args[1].(*controltowerv1.ListWorkloadExchangesRequest) + } + var arg2 []grpc.CallOption + var variadicArgs []grpc.CallOption + if len(args) > 2 { + variadicArgs = args[2].([]grpc.CallOption) + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *WorkloadAdminServiceClientMock_ListWorkloadExchanges_Call) Return(listWorkloadExchangesResponse *controltowerv1.ListWorkloadExchangesResponse, err error) *WorkloadAdminServiceClientMock_ListWorkloadExchanges_Call { + _c.Call.Return(listWorkloadExchangesResponse, err) + return _c +} + +func (_c *WorkloadAdminServiceClientMock_ListWorkloadExchanges_Call) RunAndReturn(run func(ctx context.Context, in *controltowerv1.ListWorkloadExchangesRequest, opts ...grpc.CallOption) (*controltowerv1.ListWorkloadExchangesResponse, error)) *WorkloadAdminServiceClientMock_ListWorkloadExchanges_Call { + _c.Call.Return(run) + return _c +} + +// ListWorkloadIdentityProviders provides a mock function for the type WorkloadAdminServiceClientMock +func (_mock *WorkloadAdminServiceClientMock) ListWorkloadIdentityProviders(ctx context.Context, in *controltowerv1.ListWorkloadIdentityProvidersRequest, opts ...grpc.CallOption) (*controltowerv1.ListWorkloadIdentityProvidersResponse, error) { + var tmpRet mock.Arguments + if len(opts) > 0 { + tmpRet = _mock.Called(ctx, in, opts) + } else { + tmpRet = _mock.Called(ctx, in) + } + ret := tmpRet + + if len(ret) == 0 { + panic("no return value specified for ListWorkloadIdentityProviders") + } + + var r0 *controltowerv1.ListWorkloadIdentityProvidersResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *controltowerv1.ListWorkloadIdentityProvidersRequest, ...grpc.CallOption) (*controltowerv1.ListWorkloadIdentityProvidersResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *controltowerv1.ListWorkloadIdentityProvidersRequest, ...grpc.CallOption) *controltowerv1.ListWorkloadIdentityProvidersResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*controltowerv1.ListWorkloadIdentityProvidersResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *controltowerv1.ListWorkloadIdentityProvidersRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// WorkloadAdminServiceClientMock_ListWorkloadIdentityProviders_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListWorkloadIdentityProviders' +type WorkloadAdminServiceClientMock_ListWorkloadIdentityProviders_Call struct { + *mock.Call +} + +// ListWorkloadIdentityProviders is a helper method to define mock.On call +// - ctx context.Context +// - in *controltowerv1.ListWorkloadIdentityProvidersRequest +// - opts ...grpc.CallOption +func (_e *WorkloadAdminServiceClientMock_Expecter) ListWorkloadIdentityProviders(ctx interface{}, in interface{}, opts ...interface{}) *WorkloadAdminServiceClientMock_ListWorkloadIdentityProviders_Call { + return &WorkloadAdminServiceClientMock_ListWorkloadIdentityProviders_Call{Call: _e.mock.On("ListWorkloadIdentityProviders", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *WorkloadAdminServiceClientMock_ListWorkloadIdentityProviders_Call) Run(run func(ctx context.Context, in *controltowerv1.ListWorkloadIdentityProvidersRequest, opts ...grpc.CallOption)) *WorkloadAdminServiceClientMock_ListWorkloadIdentityProviders_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *controltowerv1.ListWorkloadIdentityProvidersRequest + if args[1] != nil { + arg1 = args[1].(*controltowerv1.ListWorkloadIdentityProvidersRequest) + } + var arg2 []grpc.CallOption + var variadicArgs []grpc.CallOption + if len(args) > 2 { + variadicArgs = args[2].([]grpc.CallOption) + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *WorkloadAdminServiceClientMock_ListWorkloadIdentityProviders_Call) Return(listWorkloadIdentityProvidersResponse *controltowerv1.ListWorkloadIdentityProvidersResponse, err error) *WorkloadAdminServiceClientMock_ListWorkloadIdentityProviders_Call { + _c.Call.Return(listWorkloadIdentityProvidersResponse, err) + return _c +} + +func (_c *WorkloadAdminServiceClientMock_ListWorkloadIdentityProviders_Call) RunAndReturn(run func(ctx context.Context, in *controltowerv1.ListWorkloadIdentityProvidersRequest, opts ...grpc.CallOption) (*controltowerv1.ListWorkloadIdentityProvidersResponse, error)) *WorkloadAdminServiceClientMock_ListWorkloadIdentityProviders_Call { + _c.Call.Return(run) + return _c +} + +// ListWorkloadTrustRules provides a mock function for the type WorkloadAdminServiceClientMock +func (_mock *WorkloadAdminServiceClientMock) ListWorkloadTrustRules(ctx context.Context, in *controltowerv1.ListWorkloadTrustRulesRequest, opts ...grpc.CallOption) (*controltowerv1.ListWorkloadTrustRulesResponse, error) { + var tmpRet mock.Arguments + if len(opts) > 0 { + tmpRet = _mock.Called(ctx, in, opts) + } else { + tmpRet = _mock.Called(ctx, in) + } + ret := tmpRet + + if len(ret) == 0 { + panic("no return value specified for ListWorkloadTrustRules") + } + + var r0 *controltowerv1.ListWorkloadTrustRulesResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *controltowerv1.ListWorkloadTrustRulesRequest, ...grpc.CallOption) (*controltowerv1.ListWorkloadTrustRulesResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *controltowerv1.ListWorkloadTrustRulesRequest, ...grpc.CallOption) *controltowerv1.ListWorkloadTrustRulesResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*controltowerv1.ListWorkloadTrustRulesResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *controltowerv1.ListWorkloadTrustRulesRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// WorkloadAdminServiceClientMock_ListWorkloadTrustRules_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListWorkloadTrustRules' +type WorkloadAdminServiceClientMock_ListWorkloadTrustRules_Call struct { + *mock.Call +} + +// ListWorkloadTrustRules is a helper method to define mock.On call +// - ctx context.Context +// - in *controltowerv1.ListWorkloadTrustRulesRequest +// - opts ...grpc.CallOption +func (_e *WorkloadAdminServiceClientMock_Expecter) ListWorkloadTrustRules(ctx interface{}, in interface{}, opts ...interface{}) *WorkloadAdminServiceClientMock_ListWorkloadTrustRules_Call { + return &WorkloadAdminServiceClientMock_ListWorkloadTrustRules_Call{Call: _e.mock.On("ListWorkloadTrustRules", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *WorkloadAdminServiceClientMock_ListWorkloadTrustRules_Call) Run(run func(ctx context.Context, in *controltowerv1.ListWorkloadTrustRulesRequest, opts ...grpc.CallOption)) *WorkloadAdminServiceClientMock_ListWorkloadTrustRules_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *controltowerv1.ListWorkloadTrustRulesRequest + if args[1] != nil { + arg1 = args[1].(*controltowerv1.ListWorkloadTrustRulesRequest) + } + var arg2 []grpc.CallOption + var variadicArgs []grpc.CallOption + if len(args) > 2 { + variadicArgs = args[2].([]grpc.CallOption) + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *WorkloadAdminServiceClientMock_ListWorkloadTrustRules_Call) Return(listWorkloadTrustRulesResponse *controltowerv1.ListWorkloadTrustRulesResponse, err error) *WorkloadAdminServiceClientMock_ListWorkloadTrustRules_Call { + _c.Call.Return(listWorkloadTrustRulesResponse, err) + return _c +} + +func (_c *WorkloadAdminServiceClientMock_ListWorkloadTrustRules_Call) RunAndReturn(run func(ctx context.Context, in *controltowerv1.ListWorkloadTrustRulesRequest, opts ...grpc.CallOption) (*controltowerv1.ListWorkloadTrustRulesResponse, error)) *WorkloadAdminServiceClientMock_ListWorkloadTrustRules_Call { + _c.Call.Return(run) + return _c +} diff --git a/internal/cmd/workload/provider.go b/internal/cmd/workload/provider.go new file mode 100644 index 0000000..64ab34a --- /dev/null +++ b/internal/cmd/workload/provider.go @@ -0,0 +1,158 @@ +package workload + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "time" + + controltowerv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/v1/controltowerv1grpc" + controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" + "github.com/safedep/dry/tui/humanize" + "github.com/safedep/dry/tui/table" + "github.com/spf13/cobra" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" + "github.com/safedep/cli/internal/paging" + "github.com/safedep/cli/internal/tui" +) + +const ( + providerKindPrefix = "WORKLOAD_IDENTITY_PROVIDER_KIND_" + linkStatePrefix = "WORKLOAD_IDENTITY_PROVIDER_LINK_STATE_" + noProvidersHelp = "Link a GitHub organization with the SafeDep GitHub App in SafeDep Cloud. " + + "A verified link creates the provider of its account" +) + +type providerView struct { + ID string `json:"provider_id"` + Name string `json:"name"` + Kind string `json:"kind"` + AccountLogin string `json:"account_login"` + OwnerID string `json:"owner_id"` + LinkState string `json:"link_state"` + LinkID string `json:"link_id"` + CreatedAt string `json:"created_at,omitempty"` + created *time.Time +} + +func newProviderView(p *controltowerv1.WorkloadIdentityProvider) providerView { + v := providerView{ + ID: p.GetProviderId(), + Name: providerName(p), + Kind: tui.EnumToken(p.GetKind().String(), providerKindPrefix), + AccountLogin: p.GetAccountLogin(), + OwnerID: p.GetOwnerId(), + LinkState: tui.EnumToken(p.GetLinkState().String(), linkStatePrefix), + LinkID: p.GetLinkId(), + created: cloudpolicy.TimeOf(p.GetCreatedAt()), + } + if v.created != nil { + v.CreatedAt = v.created.Format(time.RFC3339) + } + return v +} + +// providerName is the KIND:ACCOUNT form that --provider takes, as in +// github-actions:acme. +func providerName(p *controltowerv1.WorkloadIdentityProvider) string { + return tui.EnumToken(p.GetKind().String(), providerKindPrefix) + ":" + p.GetAccountLogin() +} + +type providerListInput struct { + PageSize uint32 + PageToken string +} + +type providerListResult struct { + Providers []providerView `json:"providers"` + NextPageToken string `json:"next_page_token,omitempty"` +} + +func providerListCmd(a *app.App) *cobra.Command { + var in providerListInput + cmd := &cobra.Command{ + Use: "list", + Short: "List the workload identity providers of the tenant", + Long: "List the workload identity providers of the tenant, with the KIND:ACCOUNT name that " + + "`safedep workload rule create --provider` takes, and the state of the link that each provider " + + "trusts. A CI job gets a credential only through a provider whose link is active. The command " + + "reads one page. Pass --page-token to read the next page.", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + client, err := adminClient(a) + if err != nil { + return err + } + res, err := runProviderList(cmd.Context(), client, in) + if err != nil { + return err + } + return a.Output.Print(res) + }, + } + cmd.Flags().Uint32Var(&in.PageSize, "limit", 0, "page size, or the server default when 0") + cmd.Flags().StringVar(&in.PageToken, "page-token", "", "continuation token from a prior response") + return cmd +} + +func runProviderList( + ctx context.Context, + client controltowerv1grpc.WorkloadAdminServiceClient, + in providerListInput, +) (*providerListResult, error) { + req := &controltowerv1.ListWorkloadIdentityProvidersRequest{} + req.SetPagination(paging.NewPaginationRequest(in.PageSize, in.PageToken)) + res, err := client.ListWorkloadIdentityProviders(ctx, req) + if err != nil { + return nil, mapError("provider list", err) + } + out := &providerListResult{ + Providers: make([]providerView, 0, len(res.GetProviders())), + NextPageToken: res.GetPagination().GetNextPageToken(), + } + for _, p := range res.GetProviders() { + out.Providers = append(out.Providers, newProviderView(p)) + } + return out, nil +} + +func (r *providerListResult) RenderJSON() ([]byte, error) { + return json.MarshalIndent(r, "", " ") +} + +func (r *providerListResult) RenderTable() string { + now := time.Now() + rows := make([][]string, 0, len(r.Providers)) + for _, p := range r.Providers { + created := "-" + if p.created != nil { + created = humanize.Time(*p.created, now) + } + rows = append(rows, []string{p.Name, p.ID, p.OwnerID, p.LinkState, created}) + } + t := table.New(). + Title("Workload identity providers"). + Headers("PROVIDER", "ID", "OWNER ID", "LINK", "CREATED"). + Rows(tui.EscapeCells(rows)...). + EmptyMessage("No workload identity providers. " + noProvidersHelp + ".") + if len(rows) > 0 { + footer := fmt.Sprintf("%d %s", len(rows), cloudpolicy.Plural(len(rows), "provider", "providers")) + if r.NextPageToken != "" { + footer += ". More available: --page-token " + r.NextPageToken + } + t = t.Footer(footer) + } + return t.Render() +} + +func (r *providerListResult) RenderPlain() string { + var b strings.Builder + b.WriteString("provider_id\tname\tkind\taccount_login\towner_id\tlink_state\tlink_id\tcreated_at") + for _, p := range r.Providers { + b.WriteString("\n" + tui.PlainRow(p.ID, p.Name, p.Kind, p.AccountLogin, p.OwnerID, p.LinkState, p.LinkID, p.CreatedAt)) + } + return b.String() +} diff --git a/internal/cmd/workload/provider_resolve.go b/internal/cmd/workload/provider_resolve.go new file mode 100644 index 0000000..3f3426c --- /dev/null +++ b/internal/cmd/workload/provider_resolve.go @@ -0,0 +1,92 @@ +package workload + +import ( + "context" + "fmt" + "strings" + + controltowerv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/v1/controltowerv1grpc" + controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" + + "github.com/safedep/cli/internal/paging" + "github.com/safedep/cli/internal/tui" +) + +// listAllProviders reads every page of the providers of the tenant. A tenant +// has one provider for each linked account, so the list is short. +func listAllProviders( + ctx context.Context, + client controltowerv1grpc.WorkloadAdminServiceClient, + command string, +) ([]*controltowerv1.WorkloadIdentityProvider, error) { + var providers []*controltowerv1.WorkloadIdentityProvider + err := paging.Paginate(ctx, "workload "+command, func(ctx context.Context, pageToken string) (string, error) { + req := &controltowerv1.ListWorkloadIdentityProvidersRequest{} + req.SetPagination(paging.NewPaginationRequest(0, pageToken)) + res, err := client.ListWorkloadIdentityProviders(ctx, req) + if err != nil { + return "", mapError(command, err) + } + providers = append(providers, res.GetProviders()...) + return res.GetPagination().GetNextPageToken(), nil + }) + return providers, err +} + +// providerNames maps each provider id of the tenant to its KIND:ACCOUNT name. +func providerNames(providers []*controltowerv1.WorkloadIdentityProvider) map[string]string { + names := make(map[string]string, len(providers)) + for _, p := range providers { + names[p.GetProviderId()] = providerName(p) + } + return names +} + +// resolveProvider finds the provider that ref names: a provider id, or a +// KIND:ACCOUNT name, as in github-actions:acme. The account matches with no +// regard to case, as a GitHub login does. The CLI never picks a provider on +// its own, even when the tenant has one provider: a rule then names its +// provider in every script that creates it. +func resolveProvider( + providers []*controltowerv1.WorkloadIdentityProvider, + ref string, +) (*controltowerv1.WorkloadIdentityProvider, error) { + ref = strings.TrimSpace(ref) + if ref == "" { + return nil, providerError("--provider is required. The CLI never picks a provider", providers) + } + for _, p := range providers { + if p.GetProviderId() == ref { + return p, nil + } + } + var matches []*controltowerv1.WorkloadIdentityProvider + for _, p := range providers { + if strings.EqualFold(providerName(p), ref) { + matches = append(matches, p) + } + } + switch len(matches) { + case 1: + return matches[0], nil + case 0: + return nil, providerError(fmt.Sprintf("--provider %s is not a provider of the tenant", tui.EscapeLine(ref)), providers) + } + return nil, providerError(fmt.Sprintf("--provider %s names more than one provider. Pass the provider id", + tui.EscapeLine(ref)), matches) +} + +// providerError lists the providers that --provider can take, so the user +// can run the command again with one of them. +func providerError(problem string, providers []*controltowerv1.WorkloadIdentityProvider) error { + if len(providers) == 0 { + return invalidInputError(problem+". The tenant has no workload identity provider", noProvidersHelp) + } + lines := []string{problem + ". The providers of the tenant:"} + for _, p := range providers { + lines = append(lines, fmt.Sprintf(" %s id %s, link %s", tui.EscapeLine(providerName(p)), + tui.EscapeLine(p.GetProviderId()), tui.EnumToken(p.GetLinkState().String(), linkStatePrefix))) + } + return invalidInputError(strings.Join(lines, "\n"), + "Run the command again with --provider "+tui.EscapeLine(providerName(providers[0]))) +} diff --git a/internal/cmd/workload/rule_create.go b/internal/cmd/workload/rule_create.go new file mode 100644 index 0000000..842f506 --- /dev/null +++ b/internal/cmd/workload/rule_create.go @@ -0,0 +1,100 @@ +package workload + +import ( + "context" + "strings" + + controltowerv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/v1/controltowerv1grpc" + "github.com/safedep/dry/tui" + "github.com/spf13/cobra" + + "github.com/safedep/cli/internal/app" + clitui "github.com/safedep/cli/internal/tui" +) + +type ruleCreateInput struct { + Name string + Provider string + Grant string + Repositories []string + Refs []string + Events []string +} + +func ruleCreateCmd(a *app.App) *cobra.Command { + var in ruleCreateInput + cmd := &cobra.Command{ + Use: "create NAME --provider PROVIDER --grant GRANT", + Short: "Create a workload trust rule", + Long: "Create a workload trust rule. The rule gives the grant to the CI jobs of the provider whose " + + "claims meet every condition of the rule. --provider is required: the CLI never picks a provider, " + + "and with no --provider the command lists the providers of the tenant. --repository names a " + + "repository by its full name. The server finds it in the account of the provider and stores its " + + "numeric id, so a rename does not change the rule. A rule with no --repository covers every " + + "repository of the account. --ref takes a full ref, as in refs/heads/main, or a prefix that ends " + + "with /*, as in refs/heads/release/*. A rule with no --event covers only the default events of " + + "the provider. For GitHub Actions they are push, pull_request, merge_group, schedule, " + + "workflow_dispatch and release.", + Args: func(cmd *cobra.Command, args []string) error { + if err := cobra.ExactArgs(1)(cmd, args); err != nil { + return err + } + in.Name = args[0] + _, err := newRuleCreateRequest(in) + return err + }, + RunE: func(cmd *cobra.Command, _ []string) error { + client, err := adminClient(a) + if err != nil { + return err + } + res, err := runRuleCreate(cmd.Context(), client, in) + if err != nil { + return err + } + reportRuleCreate(res.Rule) + return a.Output.Print(res) + }, + } + f := cmd.Flags() + f.StringVar(&in.Provider, "provider", "", "the provider of the rule: a provider id or KIND:ACCOUNT, as in github-actions:acme (required)") + f.StringVar(&in.Grant, "grant", "", "the grant that the rule gives: "+strings.Join(grantTokens(), ", ")+" (required)") + f.StringSliceVar(&in.Repositories, "repository", nil, "a repository by full name, as in acme/web. Repeat it for more repositories") + f.StringArrayVar(&in.Refs, "ref", nil, "a full ref, as in refs/heads/main, or a prefix, as in refs/heads/release/*. Repeat it for more refs") + f.StringSliceVar(&in.Events, "event", nil, "an event name, as in push or pull_request_target. Repeat it for more events") + return cmd +} + +func runRuleCreate( + ctx context.Context, + client controltowerv1grpc.WorkloadAdminServiceClient, + in ruleCreateInput, +) (*ruleResult, error) { + req, err := newRuleCreateRequest(in) + if err != nil { + return nil, err + } + providers, err := listAllProviders(ctx, client, "rule create") + if err != nil { + return nil, err + } + provider, err := resolveProvider(providers, in.Provider) + if err != nil { + return nil, err + } + req.SetProviderId(provider.GetProviderId()) + res, err := client.CreateWorkloadTrustRule(ctx, req) + if err != nil { + return nil, mapRuleCreateError(in.Name, providerName(provider), err) + } + return &ruleResult{Rule: newRuleView(res.GetRule(), providerNames(providers))}, nil +} + +func reportRuleCreate(rule ruleView) { + tui.Success("rule %s created", clitui.EscapeLine(rule.Name)) + if rule.EveryRepository { + tui.Warning("Rule %s covers every repository of %s, also the repositories that the SafeDep GitHub App "+ + "installation does not select. Pass --repository to name repositories", + clitui.EscapeLine(rule.Name), clitui.EscapeLine(rule.account())) + } +} diff --git a/internal/cmd/workload/rule_create_test.go b/internal/cmd/workload/rule_create_test.go new file mode 100644 index 0000000..90aac27 --- /dev/null +++ b/internal/cmd/workload/rule_create_test.go @@ -0,0 +1,364 @@ +package workload + +import ( + "context" + "encoding/json" + "regexp" + "strings" + "testing" + + messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" + errorv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/error/v1" + controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" + "github.com/safedep/dry/usefulerror" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + "google.golang.org/genproto/googleapis/rpc/errdetails" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/safedep/cli/internal/cmd/workload/mocks" +) + +func TestRunRuleCreate_Provider(t *testing.T) { + acme := activeProvider("prov_acme", "acme") + beta := githubProvider("prov_beta", "Beta", + controltowerv1.WorkloadIdentityProviderLinkState_WORKLOAD_IDENTITY_PROVIDER_LINK_STATE_SUSPENDED) + listed := "The providers of the tenant:\n" + + " github-actions:acme id prov_acme, link active\n" + + " github-actions:Beta id prov_beta, link suspended" + tests := []struct { + name string + providers []*controltowerv1.WorkloadIdentityProvider + provider string + wantID string + wantErr usefulErrorWant + }{ + { + name: "no provider with one provider in the tenant", + providers: []*controltowerv1.WorkloadIdentityProvider{acme}, + wantErr: usefulErrorWant{ + code: usefulerror.ErrBadRequest, + human: "--provider is required. The CLI never picks a provider. The providers of the tenant:\n" + + " github-actions:acme id prov_acme, link active", + help: "Run the command again with --provider github-actions:acme", + }, + }, + { + name: "no provider with two providers", + providers: []*controltowerv1.WorkloadIdentityProvider{acme, beta}, + wantErr: usefulErrorWant{ + code: usefulerror.ErrBadRequest, + human: "--provider is required. The CLI never picks a provider. " + listed, + help: "Run the command again with --provider github-actions:acme", + }, + }, + { + name: "no provider in a tenant with none", + wantErr: usefulErrorWant{ + code: usefulerror.ErrBadRequest, + human: "--provider is required. The CLI never picks a provider. The tenant has no workload identity provider", + help: noProvidersHelp, + }, + }, + { + name: "a provider that the tenant does not have", + providers: []*controltowerv1.WorkloadIdentityProvider{acme, beta}, + provider: "github-actions:gamma", + wantErr: usefulErrorWant{ + code: usefulerror.ErrBadRequest, + human: "--provider github-actions:gamma is not a provider of the tenant. " + listed, + help: "Run the command again with --provider github-actions:acme", + }, + }, + { + name: "KIND:ACCOUNT with the account in another case", + providers: []*controltowerv1.WorkloadIdentityProvider{acme, beta}, + provider: "github-actions:beta", + wantID: "prov_beta", + }, + { + name: "a provider id", + providers: []*controltowerv1.WorkloadIdentityProvider{acme, beta}, + provider: "prov_acme", + wantID: "prov_acme", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + client := mocks.NewWorkloadAdminServiceClientMock(t) + client.EXPECT().ListWorkloadIdentityProviders(mock.Anything, mock.Anything).Return(providersResponse(tt.providers...), nil) + if tt.wantID != "" { + client.EXPECT().CreateWorkloadTrustRule(mock.Anything, mock.MatchedBy(func(r *controltowerv1.CreateWorkloadTrustRuleRequest) bool { + return r.GetProviderId() == tt.wantID + })).Return(controltowerv1.CreateWorkloadTrustRuleResponse_builder{Rule: trustRule("r1", "org", nil)}.Build(), nil) + } + + _, err := runRuleCreate(context.Background(), client, ruleCreateInput{Name: "org", Provider: tt.provider, Grant: "tool"}) + + if tt.wantID != "" { + require.NoError(t, err) + return + } + requireUsefulError(t, err, tt.wantErr) + }) + } +} + +func TestRunRuleCreate_ReturnsTheRepositoryID(t *testing.T) { + client := mocks.NewWorkloadAdminServiceClientMock(t) + client.EXPECT().ListWorkloadIdentityProviders(mock.Anything, mock.Anything). + Return(providersResponse(activeProvider("prov_acme", "acme")), nil) + var sent *controltowerv1.CreateWorkloadTrustRuleRequest + client.EXPECT().CreateWorkloadTrustRule(mock.Anything, mock.Anything). + Run(func(_ context.Context, r *controltowerv1.CreateWorkloadTrustRuleRequest, _ ...grpc.CallOption) { + sent = r + }). + Return(controltowerv1.CreateWorkloadTrustRuleResponse_builder{ + Rule: trustRule("r1", "web", map[string]string{"acme/web": "123456"}, + condition(claimRef, equals, "refs/heads/main"), condition(claimEventName, equals, "push")), + }.Build(), nil) + + res, err := runRuleCreate(context.Background(), client, ruleCreateInput{ + Name: "web", Provider: "github-actions:acme", Grant: "tool", + Repositories: []string{"acme/web", "acme/web"}, Refs: []string{"refs/heads/main"}, Events: []string{"push"}, + }) + require.NoError(t, err) + + require.NotNil(t, sent) + assert.Equal(t, "web", sent.GetName()) + assert.Equal(t, "prov_acme", sent.GetProviderId()) + assert.Equal(t, messagescontroltowerv1.CredentialGrant_CREDENTIAL_GRANT_TOOL, sent.GetGrant()) + assert.Equal(t, []string{"acme/web"}, sent.GetRepositories()) + require.Len(t, sent.GetConditions(), 2) + assert.Equal(t, claimRef, sent.GetConditions()[0].GetClaim()) + assert.Equal(t, equals, sent.GetConditions()[0].GetOperator()) + assert.Equal(t, claimEventName, sent.GetConditions()[1].GetClaim()) + + assert.Equal(t, []repositoryView{{ID: "123456", FullName: "acme/web"}}, res.Rule.Repositories) + assert.False(t, res.Rule.EveryRepository) + assert.Equal(t, "github-actions:acme", res.Rule.Provider) + out, err := res.RenderJSON() + require.NoError(t, err) + var decoded struct { + Rule struct { + Repositories []map[string]string `json:"repositories"` + } `json:"rule"` + } + require.NoError(t, json.Unmarshal(out, &decoded)) + assert.Equal(t, []map[string]string{{"repository_id": "123456", "full_name": "acme/web"}}, decoded.Rule.Repositories) +} + +func TestRunRuleCreate_ServerErrors(t *testing.T) { + notAccessible := usefulerror.NewStatus(codes.NotFound, "the GitHub installation of the provider cannot see a repository"). + WithReason(errorv1.ErrorReason_ERROR_REASON_GITHUB_REPOSITORY_NOT_ACCESSIBLE). + WithDetail(&errdetails.BadRequest{FieldViolations: []*errdetails.BadRequest_FieldViolation{{ + Field: "repositories[1]", + Description: "other/web is not a repository of the provider account that the installation can see", + }}}).Err() + suspended := usefulerror.NewStatus(codes.FailedPrecondition, "the GitHub App installation of the provider is suspended"). + WithReason(errorv1.ErrorReason_ERROR_REASON_GITHUB_INSTALLATION_SUSPENDED).Err() + badClaim := usefulerror.NewStatus(codes.InvalidArgument, "service execution failed: invalid condition"). + WithDetail(&errdetails.BadRequest{FieldViolations: []*errdetails.BadRequest_FieldViolation{{ + Field: "conditions[1].claim", Description: "the preset does not allow the claim", + }}}).Err() + tests := []struct { + name string + err error + want usefulErrorWant + }{ + { + name: "a repository outside the installation", + err: notAccessible, + want: usefulErrorWant{ + code: usefulerror.ErrNotFound, + human: "the GitHub installation of the provider cannot see a repository\n" + + "other/web is not a repository of the provider account that the installation can see", + help: "Name only repositories of github-actions:acme that the SafeDep GitHub App installation can see. " + + "An owner of the GitHub organization can add a repository to the installation in the GitHub settings of the organization", + }, + }, + { + name: "a suspended installation", + err: suspended, + want: usefulErrorWant{ + code: usefulerror.ErrConflict, + human: "GitHub suspended the SafeDep GitHub App installation of github-actions:acme", + help: "An owner of the GitHub organization can end the suspension in the GitHub settings of the organization. Then run the command again", + }, + }, + { + name: "an unlinked provider", + err: status.Error(codes.FailedPrecondition, "service execution failed: the GitHub App link of the provider is unlinked"), + want: usefulErrorWant{ + code: usefulerror.ErrConflict, + human: "The server refused the rule: the GitHub App link of the provider is unlinked", + help: "Link the GitHub organization again with the SafeDep GitHub App in SafeDep Cloud. " + + "See the link state: safedep workload provider list", + }, + }, + { + name: "a name that a rule has", + err: status.Error(codes.AlreadyExists, "a workload trust rule with this name exists"), + want: usefulErrorWant{ + code: usefulerror.ErrConflict, + human: "A workload trust rule with the name web exists", + help: "See it with: safedep workload rule show web", + }, + }, + { + name: "a claim that the preset does not allow", + err: badClaim, + want: usefulErrorWant{ + code: usefulerror.ErrBadRequest, + human: "invalid condition\nconditions[1].claim: the preset does not allow the claim", + help: "See the flags: safedep workload rule create --help", + }, + }, + { + name: "a member", + err: status.Error(codes.PermissionDenied, "admin role required"), + want: usefulErrorWant{ + code: usefulerror.ErrAuthorizationFailed, + human: "Only an Admin can manage workload identity", + help: "Ask an Admin of the tenant to run the command", + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + client := mocks.NewWorkloadAdminServiceClientMock(t) + client.EXPECT().ListWorkloadIdentityProviders(mock.Anything, mock.Anything). + Return(providersResponse(activeProvider("prov_acme", "acme")), nil) + client.EXPECT().CreateWorkloadTrustRule(mock.Anything, mock.Anything).Return(nil, tt.err) + + _, err := runRuleCreate(context.Background(), client, ruleCreateInput{ + Name: "web", Provider: "github-actions:acme", Grant: "tool", Repositories: []string{"acme/web", "other/web"}, + }) + + requireUsefulError(t, err, tt.want) + }) + } +} + +func TestNewRuleCreateRequest(t *testing.T) { + valid := ruleCreateInput{Name: "web-release", Grant: "tool"} + tests := []struct { + name string + mutate func(*ruleCreateInput) + wantErr string + check func(t *testing.T, r *controltowerv1.CreateWorkloadTrustRuleRequest) + }{ + {name: "an org-wide rule", mutate: func(*ruleCreateInput) {}, check: func(t *testing.T, r *controltowerv1.CreateWorkloadTrustRuleRequest) { + assert.Empty(t, r.GetRepositories()) + assert.Empty(t, r.GetConditions()) + }}, + {name: "a name in upper case", mutate: func(in *ruleCreateInput) { in.Name = "Web" }, wantErr: `rule name "Web"`}, + {name: "a name that ends with a hyphen", mutate: func(in *ruleCreateInput) { in.Name = "web-" }, wantErr: `rule name "web-"`}, + {name: "no grant", mutate: func(in *ruleCreateInput) { in.Grant = "" }, wantErr: "--grant is required"}, + {name: "an unknown grant", mutate: func(in *ruleCreateInput) { in.Grant = "admin" }, wantErr: `--grant "admin" is not a grant`}, + {name: "a repository with no owner", mutate: func(in *ruleCreateInput) { in.Repositories = []string{"web"} }, wantErr: `--repository "web": write OWNER/NAME`}, + {name: "a repository path", mutate: func(in *ruleCreateInput) { in.Repositories = []string{"acme/web/x"} }, wantErr: "write OWNER/NAME"}, + {name: "a dot segment", mutate: func(in *ruleCreateInput) { in.Repositories = []string{"acme/.."} }, wantErr: "write OWNER/NAME"}, + {name: "a short ref", mutate: func(in *ruleCreateInput) { in.Refs = []string{"main"} }, wantErr: `--ref "main": write the full ref`}, + {name: "a prefix that ends in a name", mutate: func(in *ruleCreateInput) { in.Refs = []string{"refs/heads/main*"} }, wantErr: "a prefix is refs/heads/"}, + {name: "a star inside a ref", mutate: func(in *ruleCreateInput) { in.Refs = []string{"refs/heads/*/x"} }, wantErr: "a prefix is refs/heads/"}, + {name: "full refs and prefixes", mutate: func(in *ruleCreateInput) { in.Refs = []string{"refs/heads/main", "refs/heads/release/*"} }, wantErr: "full refs or prefixes, not both"}, + {name: "an event in upper case", mutate: func(in *ruleCreateInput) { in.Events = []string{"Push"} }, wantErr: `--event "Push"`}, + {name: "prefixes", mutate: func(in *ruleCreateInput) { in.Refs = []string{"refs/heads/release/*", "refs/tags/*"} }, + check: func(t *testing.T, r *controltowerv1.CreateWorkloadTrustRuleRequest) { + require.Len(t, r.GetConditions(), 1) + assert.Equal(t, prefix, r.GetConditions()[0].GetOperator()) + assert.Equal(t, []string{"refs/heads/release/*", "refs/tags/*"}, r.GetConditions()[0].GetValues()) + }}, + {name: "repeated events", mutate: func(in *ruleCreateInput) { in.Events = []string{"push", "release", "push"} }, + check: func(t *testing.T, r *controltowerv1.CreateWorkloadTrustRuleRequest) { + require.Len(t, r.GetConditions(), 1) + assert.Equal(t, claimEventName, r.GetConditions()[0].GetClaim()) + assert.Equal(t, []string{"push", "release"}, r.GetConditions()[0].GetValues()) + }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + in := valid + tt.mutate(&in) + req, err := newRuleCreateRequest(in) + if tt.wantErr != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantErr) + return + } + require.NoError(t, err) + tt.check(t, req) + }) + } +} + +// serverPrefixPattern is the protovalidate rule of a PREFIX value in +// WorkloadClaimCondition. +var serverPrefixPattern = regexp.MustCompile(`^refs/(heads|tags)/([^*]*/)?[*]$`) + +// FuzzRefCondition checks that each condition that the CLI sends meets the +// rules of the server: a PREFIX value has one final "*" after a "/", an +// EQUALS value has no "*", and no value repeats. +func FuzzRefCondition(f *testing.F) { + for _, seed := range [][2]string{ + {"refs/heads/main", "refs/tags/v1"}, + {"refs/heads/release/*", "refs/tags/*"}, + {"refs/heads/main*", ""}, + {"refs/heads/*", "refs/heads/*"}, + {"main", "refs/heads/a/*/b"}, + {"refs/pull/1/merge", "refs/heads/**"}, + } { + f.Add(seed[0], seed[1]) + } + f.Fuzz(func(t *testing.T, a, b string) { + refs := []string{a} + if b != "" { + refs = append(refs, b) + } + c, err := refCondition(refs) + if err != nil { + return + } + require.NotNil(t, c) + assert.Equal(t, claimRef, c.GetClaim()) + seen := map[string]bool{} + for _, v := range c.GetValues() { + assert.False(t, seen[v], "value %q repeats", v) + seen[v] = true + switch c.GetOperator() { + case prefix: + assert.Regexp(t, serverPrefixPattern, v) + case equals: + assert.False(t, strings.Contains(v, "*"), "EQUALS value %q has a star", v) + assert.True(t, strings.HasPrefix(v, "refs/")) + default: + t.Fatalf("operator %v", c.GetOperator()) + } + } + }) +} + +func TestReportRuleCreate(t *testing.T) { + tests := []struct { + name string + rule *controltowerv1.WorkloadTrustRule + wantCover bool + }{ + {name: "a rule with no repository", rule: trustRule("r1", "org", nil), wantCover: true}, + {name: "a rule with a ref only", rule: trustRule("r1", "main", nil, condition(claimRef, equals, "refs/heads/main")), wantCover: true}, + {name: "a rule with a repository", rule: trustRule("r1", "web", map[string]string{"acme/web": "123456"}), wantCover: false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + stderr := captureStderr(t) + reportRuleCreate(newRuleView(tt.rule, map[string]string{"prov_acme": "github-actions:acme"})) + covers := strings.Contains(stderr.String(), "covers every repository of acme, also the repositories "+ + "that the SafeDep GitHub App installation does not select") + assert.Equal(t, tt.wantCover, covers, stderr.String()) + }) + } +} diff --git a/internal/cmd/workload/rule_delete.go b/internal/cmd/workload/rule_delete.go new file mode 100644 index 0000000..85a234c --- /dev/null +++ b/internal/cmd/workload/rule_delete.go @@ -0,0 +1,51 @@ +package workload + +import ( + "context" + + controltowerv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/v1/controltowerv1grpc" + controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" + "github.com/safedep/dry/tui" + "github.com/spf13/cobra" + + "github.com/safedep/cli/internal/app" + clitui "github.com/safedep/cli/internal/tui" +) + +func ruleDeleteCmd(a *app.App) *cobra.Command { + return &cobra.Command{ + Use: "delete RULE", + Short: "Delete a workload trust rule", + Long: "Delete a workload trust rule by its id or its name. Every workload credential that the rule " + + "gave stops working within 30 seconds, and the CI jobs that the rule covered get no new credential. " + + "The exchanges of the rule stay in `safedep workload exchange list`.", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + client, err := adminClient(a) + if err != nil { + return err + } + id, err := runRuleDelete(cmd.Context(), client, args[0]) + if err != nil { + return err + } + tui.Success("rule %s deleted", clitui.EscapeLine(id)) + tui.Info("Every workload credential that the rule gave stops working within 30 seconds") + return nil + }, + } +} + +// runRuleDelete deletes the rule that ref names and returns its id. +func runRuleDelete(ctx context.Context, client controltowerv1grpc.WorkloadAdminServiceClient, ref string) (string, error) { + id, err := ruleIDOf(ctx, client, "rule delete", ref) + if err != nil { + return "", err + } + req := &controltowerv1.DeleteWorkloadTrustRuleRequest{} + req.SetRuleId(id) + if _, err := client.DeleteWorkloadTrustRule(ctx, req); err != nil { + return "", mapRuleError("rule delete", ref, err) + } + return id, nil +} diff --git a/internal/cmd/workload/rule_input.go b/internal/cmd/workload/rule_input.go new file mode 100644 index 0000000..5daa50c --- /dev/null +++ b/internal/cmd/workload/rule_input.go @@ -0,0 +1,169 @@ +package workload + +import ( + "fmt" + "regexp" + "strings" + + messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" + controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" + + clitui "github.com/safedep/cli/internal/tui" +) + +// The patterns match the protovalidate rules of CreateWorkloadTrustRuleRequest +// and WorkloadClaimCondition, so a bad flag fails before any RPC with the +// flag in the message. +var ( + ruleNamePattern = regexp.MustCompile(`^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$`) + refPrefixPattern = regexp.MustCompile(`^refs/(heads|tags)/([^*]*/)?[*]$`) + eventPattern = regexp.MustCompile(`^[a-z][a-z0-9_]*$`) +) + +func grantTokens() []string { + return clitui.EnumTokens(messagescontroltowerv1.CredentialGrant_name, grantPrefix) +} + +// newRuleCreateRequest checks the flags and builds the request with no +// provider id. The provider id needs the providers of the tenant. +func newRuleCreateRequest(in ruleCreateInput) (*controltowerv1.CreateWorkloadTrustRuleRequest, error) { + if !ruleNamePattern.MatchString(in.Name) { + return nil, invalidInputError( + fmt.Sprintf("rule name %q: use 1 to 63 lowercase letters, digits and hyphens, with a letter or a digit at each end", in.Name), + "As in: safedep workload rule create org or safedep workload rule create web-release") + } + grant, err := parseGrant(in.Grant) + if err != nil { + return nil, err + } + repositories, err := repositoryNames(in.Repositories) + if err != nil { + return nil, err + } + var conditions []*controltowerv1.WorkloadClaimCondition + ref, err := refCondition(in.Refs) + if err != nil { + return nil, err + } + if ref != nil { + conditions = append(conditions, ref) + } + event, err := eventCondition(in.Events) + if err != nil { + return nil, err + } + if event != nil { + conditions = append(conditions, event) + } + + req := &controltowerv1.CreateWorkloadTrustRuleRequest{} + req.SetName(in.Name) + req.SetGrant(grant) + req.SetRepositories(repositories) + req.SetConditions(conditions) + return req, nil +} + +func parseGrant(token string) (messagescontroltowerv1.CredentialGrant, error) { + help := "Pass --grant " + strings.Join(grantTokens(), " or --grant ") + if token == "" { + return 0, invalidInputError("--grant is required", help) + } + n, ok := clitui.ParseEnumToken(messagescontroltowerv1.CredentialGrant_name, grantPrefix, token) + if !ok { + return 0, invalidInputError(fmt.Sprintf("--grant %q is not a grant", token), help) + } + return messagescontroltowerv1.CredentialGrant(n), nil +} + +// repositoryNames checks each --repository value. An owner or a name of "." +// or ".." is never a GitHub repository, and the server refuses it. +func repositoryNames(values []string) ([]string, error) { + for _, v := range values { + owner, name, ok := strings.Cut(v, "/") + if !ok || owner == "" || name == "" || strings.Contains(name, "/") || + isDotSegment(owner) || isDotSegment(name) { + return nil, invalidInputError(fmt.Sprintf("--repository %q: write OWNER/NAME", v), + "As in --repository acme/web") + } + } + return unique(values), nil +} + +func isDotSegment(s string) bool { + return s == "." || s == ".." +} + +// refCondition builds the condition on the claim ref. A rule has at most one +// condition for each claim, and a condition has one operator, so the values +// are all full refs or all prefixes. +func refCondition(refs []string) (*controltowerv1.WorkloadClaimCondition, error) { + if len(refs) == 0 { + return nil, nil + } + prefixes := 0 + for _, ref := range refs { + if strings.Contains(ref, "*") { + if !refPrefixPattern.MatchString(ref) { + return nil, invalidInputError(fmt.Sprintf("--ref %q: a prefix is refs/heads/ or refs/tags/, then path "+ + "parts that end with /, then one *", ref), + "As in --ref refs/heads/release/*. A prefix that ends in a name, as refs/heads/main*, "+ + "also matches refs/heads/main-evil") + } + prefixes++ + continue + } + if !strings.HasPrefix(ref, "refs/") { + // A GitHub token holds the full ref, so a short name such as main + // would make a rule that never matches. + return nil, invalidInputError(fmt.Sprintf("--ref %q: write the full ref", ref), + "As in --ref refs/heads/main or --ref refs/tags/v1.2.0") + } + } + operator := controltowerv1.ClaimConditionOperator_CLAIM_CONDITION_OPERATOR_EQUALS + switch prefixes { + case 0: + case len(refs): + operator = controltowerv1.ClaimConditionOperator_CLAIM_CONDITION_OPERATOR_PREFIX + default: + return nil, invalidInputError("--ref takes full refs or prefixes, not both", + "Create one rule for the full refs and one rule for the prefixes") + } + return newCondition(claimRef, operator, refs), nil +} + +func eventCondition(events []string) (*controltowerv1.WorkloadClaimCondition, error) { + if len(events) == 0 { + return nil, nil + } + for _, e := range events { + if !eventPattern.MatchString(e) { + return nil, invalidInputError(fmt.Sprintf("--event %q: write the event name of the platform", e), + "As in --event push or --event pull_request_target") + } + } + return newCondition(claimEventName, controltowerv1.ClaimConditionOperator_CLAIM_CONDITION_OPERATOR_EQUALS, events), nil +} + +func newCondition(claim string, operator controltowerv1.ClaimConditionOperator, values []string) *controltowerv1.WorkloadClaimCondition { + c := &controltowerv1.WorkloadClaimCondition{} + c.SetClaim(claim) + c.SetOperator(operator) + c.SetValues(unique(values)) + return c +} + +// unique drops repeated values and keeps the order. The server refuses a +// list with a repeated value. +func unique(values []string) []string { + seen := make(map[string]struct{}, len(values)) + out := make([]string, 0, len(values)) + for _, v := range values { + if _, ok := seen[v]; ok { + continue + } + seen[v] = struct{}{} + out = append(out, v) + } + return out +} diff --git a/internal/cmd/workload/rule_list.go b/internal/cmd/workload/rule_list.go new file mode 100644 index 0000000..35e17a0 --- /dev/null +++ b/internal/cmd/workload/rule_list.go @@ -0,0 +1,134 @@ +package workload + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "time" + + controltowerv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/v1/controltowerv1grpc" + controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" + "github.com/safedep/dry/tui/table" + "github.com/spf13/cobra" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/cloudpolicy" + "github.com/safedep/cli/internal/paging" + "github.com/safedep/cli/internal/tui" +) + +type ruleListInput struct { + Provider string + PageSize uint32 + PageToken string +} + +type ruleListResult struct { + Rules []ruleView `json:"rules"` + NextPageToken string `json:"next_page_token,omitempty"` +} + +func ruleListCmd(a *app.App) *cobra.Command { + var in ruleListInput + cmd := &cobra.Command{ + Use: "list", + Short: "List workload trust rules", + Long: "List the workload trust rules of the tenant, oldest first, with the repositories and the " + + "conditions of each rule. --provider takes a provider id or KIND:ACCOUNT, as in " + + "github-actions:acme. The command reads one page. Pass --page-token to read the next page.", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + client, err := adminClient(a) + if err != nil { + return err + } + res, err := runRuleList(cmd.Context(), client, in) + if err != nil { + return err + } + return a.Output.Print(res) + }, + } + f := cmd.Flags() + f.StringVar(&in.Provider, "provider", "", "filter: rules of this provider, as in github-actions:acme") + f.Uint32Var(&in.PageSize, "limit", 0, "page size, or the server default when 0") + f.StringVar(&in.PageToken, "page-token", "", "continuation token from a prior response") + return cmd +} + +// runRuleList reads the providers first, to resolve --provider and to show +// each rule with the KIND:ACCOUNT name of its provider. +func runRuleList( + ctx context.Context, + client controltowerv1grpc.WorkloadAdminServiceClient, + in ruleListInput, +) (*ruleListResult, error) { + providers, err := listAllProviders(ctx, client, "rule list") + if err != nil { + return nil, err + } + req := &controltowerv1.ListWorkloadTrustRulesRequest{} + req.SetPagination(paging.NewPaginationRequest(in.PageSize, in.PageToken)) + if in.Provider != "" { + provider, err := resolveProvider(providers, in.Provider) + if err != nil { + return nil, err + } + filters := &controltowerv1.ListWorkloadTrustRulesRequest_Filters{} + filters.SetProviderId(provider.GetProviderId()) + req.SetFilters(filters) + } + res, err := client.ListWorkloadTrustRules(ctx, req) + if err != nil { + return nil, mapError("rule list", err) + } + names := providerNames(providers) + out := &ruleListResult{ + Rules: make([]ruleView, 0, len(res.GetRules())), + NextPageToken: res.GetPagination().GetNextPageToken(), + } + for _, r := range res.GetRules() { + out.Rules = append(out.Rules, newRuleView(r, names)) + } + return out, nil +} + +func (r *ruleListResult) RenderJSON() ([]byte, error) { + return json.MarshalIndent(r, "", " ") +} + +func (r *ruleListResult) RenderTable() string { + now := time.Now() + rows := make([][]string, 0, len(r.Rules)) + for _, rule := range r.Rules { + rows = append(rows, []string{ + rule.ID, rule.Name, rule.provider(), rule.Grant, rule.repositorySummary(), + cloudpolicy.EmptyDash(strings.Join(rule.otherConditions(), " and ")), rule.lastUsedCell(now), + }) + } + t := table.New(). + Title("Workload trust rules"). + Headers("RULE", "NAME", "PROVIDER", "GRANT", "REPOSITORIES", "CONDITIONS", "LAST USED"). + Rows(tui.EscapeCells(rows)...). + EmptyMessage("No workload trust rules. Create one with: safedep workload rule create NAME --provider PROVIDER --grant tool") + if len(rows) > 0 { + footer := fmt.Sprintf("%d %s", len(rows), cloudpolicy.Plural(len(rows), "rule", "rules")) + if r.NextPageToken != "" { + footer += ". More available: --page-token " + r.NextPageToken + } + t = t.Footer(footer) + } + return t.Render() +} + +func (r *ruleListResult) RenderPlain() string { + var b strings.Builder + b.WriteString("rule_id\tname\tprovider\tprovider_id\tgrant\trepositories\tconditions\tproject_binding\tlast_used_at") + for _, rule := range r.Rules { + b.WriteString("\n" + tui.PlainRow(rule.ID, rule.Name, rule.Provider, rule.ProviderID, rule.Grant, + rule.repositoryPairs(), strings.Join(rule.otherConditions(), " and "), + rule.ProjectBinding, rule.LastUsedAt)) + } + return b.String() +} diff --git a/internal/cmd/workload/rule_show.go b/internal/cmd/workload/rule_show.go new file mode 100644 index 0000000..9698fcd --- /dev/null +++ b/internal/cmd/workload/rule_show.go @@ -0,0 +1,96 @@ +package workload + +import ( + "context" + + controltowerv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/v1/controltowerv1grpc" + controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" + "github.com/spf13/cobra" + + "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/paging" +) + +func ruleShowCmd(a *app.App) *cobra.Command { + return &cobra.Command{ + Use: "show RULE", + Short: "Show one workload trust rule", + Long: "Show one workload trust rule by its id or its name: the provider, the grant, each repository " + + "with its numeric id, the conditions, how a repository with no project gets a project, the " + + "longest life of a credential, and when the rule last gave a credential.", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + client, err := adminClient(a) + if err != nil { + return err + } + res, err := runRuleShow(cmd.Context(), client, args[0]) + if err != nil { + return err + } + return a.Output.Print(res) + }, + } +} + +func runRuleShow( + ctx context.Context, + client controltowerv1grpc.WorkloadAdminServiceClient, + ref string, +) (*ruleResult, error) { + id, err := ruleIDOf(ctx, client, "rule show", ref) + if err != nil { + return nil, err + } + req := &controltowerv1.GetWorkloadTrustRuleRequest{} + req.SetRuleId(id) + res, err := client.GetWorkloadTrustRule(ctx, req) + if err != nil { + return nil, mapRuleError("rule show", ref, err) + } + providers, err := listAllProviders(ctx, client, "rule show") + if err != nil { + return nil, err + } + return &ruleResult{Rule: newRuleView(res.GetRule(), providerNames(providers))}, nil +} + +// ruleIDOf finds the id of the rule that ref names: a rule id, or else the +// name of a live rule. A ref that names no live rule stays as it is, so the +// server decides. ListWorkloadExchanges finds the exchanges of a deleted +// rule by its id. +func ruleIDOf( + ctx context.Context, + client controltowerv1grpc.WorkloadAdminServiceClient, + command, ref string, +) (string, error) { + id, named := "", "" + err := paging.Paginate(ctx, "workload "+command, func(ctx context.Context, pageToken string) (string, error) { + req := &controltowerv1.ListWorkloadTrustRulesRequest{} + req.SetPagination(paging.NewPaginationRequest(0, pageToken)) + res, err := client.ListWorkloadTrustRules(ctx, req) + if err != nil { + return "", mapError(command, err) + } + for _, r := range res.GetRules() { + if r.GetRuleId() == ref { + id = ref + return "", nil + } + if r.GetName() == ref && named == "" { + named = r.GetRuleId() + } + } + return res.GetPagination().GetNextPageToken(), nil + }) + if err != nil { + return "", err + } + switch { + case id != "": + return id, nil + case named != "": + return named, nil + } + return ref, nil +} diff --git a/internal/cmd/workload/rule_test.go b/internal/cmd/workload/rule_test.go new file mode 100644 index 0000000..c68384a --- /dev/null +++ b/internal/cmd/workload/rule_test.go @@ -0,0 +1,140 @@ +package workload + +import ( + "context" + "testing" + + controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" + "github.com/safedep/dry/usefulerror" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/safedep/cli/internal/cmd/workload/mocks" +) + +func TestRunRuleDelete(t *testing.T) { + rules := rulesResponse(trustRule("r_web", "web", nil), trustRule("r_org", "org", nil)) + tests := []struct { + name string + ref string + wantID string + delErr error + wantErr *usefulErrorWant + }{ + {name: "by name", ref: "org", wantID: "r_org"}, + {name: "by id", ref: "r_web", wantID: "r_web"}, + { + name: "a rule that the tenant does not have", + ref: "gone", + wantID: "gone", + delErr: status.Error(codes.NotFound, "workload trust rule not found"), + wantErr: &usefulErrorWant{ + code: usefulerror.ErrNotFound, + human: "Workload trust rule gone does not exist", + help: "List the rules: safedep workload rule list", + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + client := mocks.NewWorkloadAdminServiceClientMock(t) + client.EXPECT().ListWorkloadTrustRules(mock.Anything, mock.Anything).Return(rules, nil) + client.EXPECT().DeleteWorkloadTrustRule(mock.Anything, mock.MatchedBy(func(r *controltowerv1.DeleteWorkloadTrustRuleRequest) bool { + return r.GetRuleId() == tt.wantID + })).Return(&controltowerv1.DeleteWorkloadTrustRuleResponse{}, tt.delErr) + + id, err := runRuleDelete(context.Background(), client, tt.ref) + + if tt.wantErr != nil { + requireUsefulError(t, err, *tt.wantErr) + return + } + require.NoError(t, err) + assert.Equal(t, tt.wantID, id) + }) + } +} + +func TestRunRuleShow_ByNameWithTheProviderName(t *testing.T) { + rule := trustRule("r_web", "web", map[string]string{"acme/web": "123456"}) + client := mocks.NewWorkloadAdminServiceClientMock(t) + client.EXPECT().ListWorkloadTrustRules(mock.Anything, mock.Anything).Return(rulesResponse(rule), nil) + client.EXPECT().GetWorkloadTrustRule(mock.Anything, mock.MatchedBy(func(r *controltowerv1.GetWorkloadTrustRuleRequest) bool { + return r.GetRuleId() == "r_web" + })).Return(controltowerv1.GetWorkloadTrustRuleResponse_builder{Rule: rule}.Build(), nil) + client.EXPECT().ListWorkloadIdentityProviders(mock.Anything, mock.Anything). + Return(providersResponse(activeProvider("prov_acme", "acme")), nil) + + res, err := runRuleShow(context.Background(), client, "web") + + require.NoError(t, err) + assert.Equal(t, "r_web", res.Rule.ID) + assert.Equal(t, "github-actions:acme", res.Rule.Provider) +} + +func TestRunRuleList_ProviderFilter(t *testing.T) { + client := mocks.NewWorkloadAdminServiceClientMock(t) + client.EXPECT().ListWorkloadIdentityProviders(mock.Anything, mock.Anything). + Return(providersResponse(activeProvider("prov_acme", "acme")), nil) + client.EXPECT().ListWorkloadTrustRules(mock.Anything, mock.MatchedBy(func(r *controltowerv1.ListWorkloadTrustRulesRequest) bool { + return r.GetFilters().GetProviderId() == "prov_acme" + })).Return(rulesResponse(trustRule("r_org", "org", nil)), nil) + + res, err := runRuleList(context.Background(), client, ruleListInput{Provider: "github-actions:acme"}) + + require.NoError(t, err) + require.Len(t, res.Rules, 1) + assert.Equal(t, "github-actions:acme", res.Rules[0].Provider) +} + +func TestRuleResult_RenderTable(t *testing.T) { + names := map[string]string{"prov_acme": "github-actions:acme"} + unknownOperator := condition("environment", controltowerv1.ClaimConditionOperator(9), "prod") + tests := []struct { + name string + rule *controltowerv1.WorkloadTrustRule + names map[string]string + want []string + notWant []string + }{ + { + name: "a rule with a repository and a ref prefix", + rule: trustRule("r1", "web", map[string]string{"acme/web": "123456"}, + condition(claimRef, prefix, "refs/heads/release/*")), + names: names, + want: []string{"github-actions:acme", "acme/web (123456)", "ref matches refs/heads/release/*", "manual: "}, + notWant: []string{"every repository", "repository_id"}, + }, + { + name: "an org-wide rule", + rule: trustRule("r1", "org", nil, condition(claimEventName, equals, "push", "release")), + names: names, + want: []string{"every repository of acme", "event_name = push, release"}, + }, + { + name: "a provider that the CLI cannot name", + rule: trustRule("r1", "org", nil), + want: []string{"prov_acme", "every repository of the provider account"}, + }, + { + name: "an operator that the CLI does not know", + rule: trustRule("r1", "prod", nil, unknownOperator), + names: names, + want: []string{"environment: a condition that this CLI cannot show"}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + out := (&ruleResult{Rule: newRuleView(tt.rule, tt.names)}).RenderTable() + for _, w := range tt.want { + assert.Contains(t, out, w) + } + for _, w := range tt.notWant { + assert.NotContains(t, out, w) + } + }) + } +} diff --git a/internal/cmd/workload/rule_view.go b/internal/cmd/workload/rule_view.go new file mode 100644 index 0000000..8697f7a --- /dev/null +++ b/internal/cmd/workload/rule_view.go @@ -0,0 +1,273 @@ +package workload + +import ( + "encoding/json" + "strconv" + "strings" + "time" + + messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" + controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" + "github.com/safedep/dry/tui/humanize" + + "github.com/safedep/cli/internal/cloudpolicy" + "github.com/safedep/cli/internal/tui" +) + +const ( + grantPrefix = "CREDENTIAL_GRANT_" + operatorPrefix = "CLAIM_CONDITION_OPERATOR_" + projectBindingPrefix = "WORKLOAD_PROJECT_BINDING_" + + claimRepositoryID = "repository_id" + claimRef = "ref" + claimEventName = "event_name" +) + +type repositoryView struct { + ID string `json:"repository_id"` + FullName string `json:"full_name"` +} + +type conditionView struct { + Claim string `json:"claim"` + Operator string `json:"operator"` + Values []string `json:"values"` +} + +// text is the condition for a person, as in "ref = refs/heads/main" or +// "ref matches refs/heads/release/*". The operator enum is open, and the CLI +// does not guess the meaning of an operator that it does not know. +func (c conditionView) text() string { + values := strings.Join(c.Values, ", ") + switch c.Operator { + case "equals": + return c.Claim + " = " + values + case "prefix": + return c.Claim + " matches " + values + } + return c.Claim + ": a condition that this CLI cannot show" +} + +type ruleView struct { + ID string `json:"rule_id"` + Name string `json:"name"` + Provider string `json:"provider,omitempty"` + // ProviderID stays even when the provider name is known, because a + // script matches the id. + ProviderID string `json:"provider_id"` + Grant string `json:"grant"` + Repositories []repositoryView `json:"repositories"` + // EveryRepository is true for a rule with no repository_id condition. It + // covers every repository of the account of its provider, also those + // that the GitHub App installation does not select. + EveryRepository bool `json:"every_repository"` + Conditions []conditionView `json:"conditions"` + ProjectBinding string `json:"project_binding"` + MaxLifetime string `json:"max_lifetime,omitempty"` + CreatedAt string `json:"created_at,omitempty"` + LastUsedAt string `json:"last_used_at,omitempty"` + maxLifetime time.Duration + created *time.Time + lastUsed *time.Time +} + +// newRuleView builds the view of a rule. names maps provider ids to their +// KIND:ACCOUNT names, and may be nil. +func newRuleView(r *controltowerv1.WorkloadTrustRule, names map[string]string) ruleView { + v := ruleView{ + ID: r.GetRuleId(), + Name: r.GetName(), + Provider: names[r.GetProviderId()], + ProviderID: r.GetProviderId(), + Grant: grantToken(r.GetGrant()), + Repositories: make([]repositoryView, 0, len(r.GetRepositories())), + EveryRepository: true, + Conditions: make([]conditionView, 0, len(r.GetConditions())), + ProjectBinding: tui.EnumToken(r.GetProjectBinding().String(), projectBindingPrefix), + created: cloudpolicy.TimeOf(r.GetCreatedAt()), + lastUsed: cloudpolicy.TimeOf(r.GetLastUsedAt()), + } + for _, repo := range r.GetRepositories() { + v.Repositories = append(v.Repositories, repositoryView{ID: repo.GetRepositoryId(), FullName: repo.GetFullName()}) + } + for _, c := range r.GetConditions() { + if c.GetClaim() == claimRepositoryID { + v.EveryRepository = false + } + v.Conditions = append(v.Conditions, conditionView{ + Claim: c.GetClaim(), + Operator: tui.EnumToken(c.GetOperator().String(), operatorPrefix), + Values: c.GetValues(), + }) + } + if r.HasMaxLifetime() { + v.maxLifetime = r.GetMaxLifetime().AsDuration() + v.MaxLifetime = v.maxLifetime.String() + } + if v.created != nil { + v.CreatedAt = v.created.Format(time.RFC3339) + } + if v.lastUsed != nil { + v.LastUsedAt = v.lastUsed.Format(time.RFC3339) + } + return v +} + +func grantToken(g messagescontroltowerv1.CredentialGrant) string { + return tui.EnumToken(g.String(), grantPrefix) +} + +// provider is the provider for a person: the KIND:ACCOUNT name when the CLI +// knows it, else the id. +func (v ruleView) provider() string { + if v.Provider != "" { + return v.Provider + } + return v.ProviderID +} + +// account is the account of the provider, as in acme, for the text about a +// rule that covers every repository. +func (v ruleView) account() string { + if _, account, ok := strings.Cut(v.Provider, ":"); ok { + return account + } + return "the provider account" +} + +// repositoryNames lists the repositories of the rule, or says that the rule +// covers every repository of the account. +func (v ruleView) repositoryNames() []string { + if v.EveryRepository { + return []string{"every repository of " + v.account()} + } + names := make([]string, 0, len(v.Repositories)) + for _, r := range v.Repositories { + names = append(names, r.FullName+" ("+r.ID+")") + } + return names +} + +// repositorySummary is the repositories of the rule on one line, by full +// name, or the text for a rule that covers every repository. +func (v ruleView) repositorySummary() string { + if v.EveryRepository { + return "every repository of " + v.account() + } + names := make([]string, 0, len(v.Repositories)) + for _, r := range v.Repositories { + names = append(names, r.FullName) + } + return strings.Join(names, ", ") +} + +// repositoryPairs is the repositories of the rule as FULL_NAME=ID items, for +// the plain output. +func (v ruleView) repositoryPairs() string { + pairs := make([]string, 0, len(v.Repositories)) + for _, r := range v.Repositories { + pairs = append(pairs, r.FullName+"="+r.ID) + } + return strings.Join(pairs, ",") +} + +// otherConditions are the conditions besides repository_id, which the +// repositories already show. +func (v ruleView) otherConditions() []string { + var out []string + for _, c := range v.Conditions { + if c.Claim == claimRepositoryID { + continue + } + out = append(out, c.text()) + } + return out +} + +func (v ruleView) lastUsedCell(now time.Time) string { + if v.lastUsed == nil { + return "never" + } + return humanize.Time(*v.lastUsed, now) +} + +func (v ruleView) projectBindingText() string { + switch v.ProjectBinding { + case "auto": + return "auto: the first tool session of a repository with no project creates its project" + case "manual": + return "manual: a repository with no project needs a project before a tool session" + } + return v.ProjectBinding +} + +// ruleResult shows one rule. Rule create and rule show print it. +type ruleResult struct { + Rule ruleView `json:"rule"` +} + +func (r *ruleResult) RenderJSON() ([]byte, error) { + return json.MarshalIndent(r, "", " ") +} + +func (r *ruleResult) RenderTable() string { + v := r.Rule + now := time.Now() + rows := [][2]string{ + {"Rule", v.ID}, + {"Name", v.Name}, + {"Provider", v.provider()}, + {"Grant", v.Grant}, + } + rows = appendRows(rows, "Repositories", v.repositoryNames()) + rows = appendRows(rows, "Conditions", v.otherConditions()) + created := "-" + if v.created != nil { + created = humanize.Time(*v.created, now) + } + maxLifetime := "-" + if v.MaxLifetime != "" { + maxLifetime = humanize.Duration(v.maxLifetime) + } + rows = append(rows, + [2]string{"Projects", v.projectBindingText()}, + [2]string{"Max lifetime", maxLifetime}, + [2]string{"Created", created}, + [2]string{"Last used", v.lastUsedCell(now)}, + ) + return cloudpolicy.KeyValues(rows) +} + +// appendRows writes one value on each row. A row after the first has an +// empty label, so it reads as part of the row above. +func appendRows(rows [][2]string, label string, values []string) [][2]string { + if len(values) == 0 { + return append(rows, [2]string{label, "-"}) + } + for i, value := range values { + if i > 0 { + label = "" + } + rows = append(rows, [2]string{label, value}) + } + return rows +} + +func (r *ruleResult) RenderPlain() string { + v := r.Rule + return strings.Join([]string{ + tui.PlainRow("rule_id", v.ID), + tui.PlainRow("name", v.Name), + tui.PlainRow("provider", v.Provider), + tui.PlainRow("provider_id", v.ProviderID), + tui.PlainRow("grant", v.Grant), + tui.PlainRow("repositories", v.repositoryPairs()), + tui.PlainRow("every_repository", strconv.FormatBool(v.EveryRepository)), + tui.PlainRow("conditions", strings.Join(v.otherConditions(), " and ")), + tui.PlainRow("project_binding", v.ProjectBinding), + tui.PlainRow("max_lifetime", v.MaxLifetime), + tui.PlainRow("created_at", v.CreatedAt), + tui.PlainRow("last_used_at", v.LastUsedAt), + }, "\n") +} From d72fb11a7ee4581b3f39072ec6cc93b416631913 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 09:36:38 +0000 Subject: [PATCH 4/5] test(rpcerror): test the status text in its own package internal/rpcerror had no test of its own, so the policy tests guarded it. The cases that do not depend on the policy document paths move to TestDescribe, which calls Describe directly. The policy tests keep the cases of the document paths. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MhRi597EX9odoSDXbVBsxz --- internal/cmd/policy/errors_test.go | 42 ---------- internal/rpcerror/rpcerror_test.go | 124 +++++++++++++++++++++++++++++ 2 files changed, 124 insertions(+), 42 deletions(-) create mode 100644 internal/rpcerror/rpcerror_test.go diff --git a/internal/cmd/policy/errors_test.go b/internal/cmd/policy/errors_test.go index ca1a791..3781b82 100644 --- a/internal/cmd/policy/errors_test.go +++ b/internal/cmd/policy/errors_test.go @@ -2,7 +2,6 @@ package policy import ( "context" - "errors" "fmt" "strings" "testing" @@ -78,22 +77,6 @@ func TestDescribeStatus(t *testing.T) { err error want string }{ - { - name: "a status with no detail", - err: status.Error(codes.InvalidArgument, "override priorities must be unique"), - want: "override priorities must be unique", - }, - { - name: "the service prefix of the server", - err: status.Error(codes.InvalidArgument, "service execution failed: override priorities must be unique"), - want: "override priorities must be unique", - }, - { - name: "a wrapped status", - err: usefulerror.NewUsefulError().WithHumanError("x"). - Wrap(fmt.Errorf("policy change create: %w", status.Error(codes.InvalidArgument, "bad title"))), - want: "bad title", - }, { name: "a violation with the message as its description", err: statusWithViolations(codes.InvalidArgument, @@ -118,37 +101,12 @@ func TestDescribeStatus(t *testing.T) { want: "the request is not valid\ntitle: must be at most 200 characters\n" + "base_description: must be at most 1000 characters", }, - { - name: "a doubled service prefix", - err: status.Error(codes.InvalidArgument, "service execution failed: service execution failed: bad"), - want: "bad", - }, - { - name: "a status with no message", - err: status.Error(codes.InvalidArgument, ""), - want: "The server gave no reason", - }, - { - name: "a violation with no description", - err: statusWithViolations(codes.InvalidArgument, "", violation("title", "")), - want: "title", - }, { name: "map key subscripts", err: statusWithViolations(codes.InvalidArgument, "", violation(prototext.Format(mapKeyPath()), "unknown label prefix")), want: `overrides[2].selector.matchLabels["team/x"]: unknown label prefix`, }, - { - name: "control characters from the server", - err: status.Error(codes.InvalidArgument, "bad\x1b[2J"), - want: `bad\x1b[2J`, - }, - { - name: "an error that is not a status", - err: errors.New("line 1: bad\x1b[2J\nline 2"), - want: "line 1: bad\\x1b[2J\nline 2", - }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/internal/rpcerror/rpcerror_test.go b/internal/rpcerror/rpcerror_test.go new file mode 100644 index 0000000..da09663 --- /dev/null +++ b/internal/rpcerror/rpcerror_test.go @@ -0,0 +1,124 @@ +package rpcerror + +import ( + "errors" + "fmt" + "testing" + + validate "buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go/buf/validate" + "github.com/safedep/dry/usefulerror" + "github.com/stretchr/testify/assert" + "google.golang.org/genproto/googleapis/rpc/errdetails" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/encoding/prototext" +) + +func statusWithViolations(code codes.Code, message string, violations ...*errdetails.BadRequest_FieldViolation) error { + st, err := status.New(code, message).WithDetails(&errdetails.BadRequest{FieldViolations: violations}) + if err != nil { + panic(err) + } + return st.Err() +} + +func violation(field, description string) *errdetails.BadRequest_FieldViolation { + return &errdetails.BadRequest_FieldViolation{Field: field, Description: description} +} + +// fieldPath is settings.overrides[2].selector.match_labels["team/x"] as +// the protobuf text of a protovalidate FieldPath, as the server sends it. +func fieldPath() string { + el := func(name string) *validate.FieldPathElement { + e := &validate.FieldPathElement{} + e.SetFieldName(name) + return e + } + overrides, labels := el("overrides"), el("match_labels") + overrides.SetIndex(2) + labels.SetStringKey("team/x") + path := &validate.FieldPath{} + path.SetElements([]*validate.FieldPathElement{el("settings"), overrides, el("selector"), labels}) + return prototext.Format(path) +} + +func TestDescribe(t *testing.T) { + tests := []struct { + name string + err error + want string + }{ + { + name: "a status with no detail", + err: status.Error(codes.InvalidArgument, "override priorities must be unique"), + want: "override priorities must be unique", + }, + { + name: "the service prefix of the server", + err: status.Error(codes.InvalidArgument, "service execution failed: override priorities must be unique"), + want: "override priorities must be unique", + }, + { + name: "a doubled service prefix", + err: status.Error(codes.InvalidArgument, "service execution failed: service execution failed: bad"), + want: "bad", + }, + { + name: "a wrapped status", + err: usefulerror.NewUsefulError().WithHumanError("x"). + Wrap(fmt.Errorf("policy change create: %w", status.Error(codes.InvalidArgument, "bad title"))), + want: "bad title", + }, + { + name: "a violation with the message as its description", + err: statusWithViolations(codes.InvalidArgument, "service execution failed: name: too long", + violation("name", "too long")), + want: "name: too long", + }, + { + name: "a message that the violations do not hold", + err: statusWithViolations(codes.InvalidArgument, "the request is not valid", + violation("title", "must be at most 200 characters"), violation("repositories[1]", "acme/x is not visible")), + want: "the request is not valid\ntitle: must be at most 200 characters\nrepositories[1]: acme/x is not visible", + }, + { + name: "an encoded field path with subscripts", + err: statusWithViolations(codes.InvalidArgument, "", violation(fieldPath(), "unknown label prefix")), + want: `settings.overrides[2].selector.match_labels["team/x"]: unknown label prefix`, + }, + { + name: "a status with no message", + err: status.Error(codes.InvalidArgument, ""), + want: NoReasonText, + }, + { + name: "a violation with no description", + err: statusWithViolations(codes.InvalidArgument, "", violation("title", "")), + want: "title", + }, + { + name: "control characters from the server", + err: status.Error(codes.InvalidArgument, "bad\x1b[2J"), + want: `bad\x1b[2J`, + }, + { + name: "an error that is not a status", + err: errors.New("line 1: bad\x1b[2J\nline 2"), + want: "line 1: bad\\x1b[2J\nline 2", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := Describe(tt.err, AsIs) + assert.Equal(t, tt.want, got) + assert.NotContains(t, got, "rpc error") + }) + } +} + +func TestDescribe_ViolationText(t *testing.T) { + err := statusWithViolations(codes.NotFound, "the installation cannot see a repository", + violation("repositories[0]", "acme/x is not visible")) + got := Describe(err, func(_, description string) (string, string) { return "", description }) + assert.Equal(t, "the installation cannot see a repository\nacme/x is not visible", got) +} From d4a29928ae83e8952e092b41a233eabd39eb78e3 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 09:36:38 +0000 Subject: [PATCH 5/5] feat(workload): confirm a rule delete and set binding and lifetime on create rule delete asks in a terminal and needs --yes with no terminal, as policy rule delete does. The question says that the CI jobs of the rule lose access to SafeDep Cloud, and that a rule with no repository covers every repository of the account. rule create takes --project-binding auto|manual and --max-lifetime from 1m to 6h. Each stays unset unless given, so the server default applies. Other fixes: - A KIND:ACCOUNT that names two providers now suggests a provider id, not the same name again. - exchange list says when --rule names no live rule and no exchange matches, because the value went to the server as a rule id. - An UNAVAILABLE on rule create shows the server message. A transport failure or a gateway also sends that code, so the text does not blame GitHub. - --repository uses the pattern, length and count limits of the API, so a value such as "acme/web app" fails at the flag. The tests cover a name on a second page of rules and of providers, the three list renderers, and rule list with a provider id. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MhRi597EX9odoSDXbVBsxz --- docs/cmd/workload-exchange-list.md | 4 + docs/cmd/workload-rule-create.md | 18 +++- docs/cmd/workload-rule-delete.md | 25 +++++- internal/cmd/workload/errors.go | 5 +- internal/cmd/workload/exchange.go | 33 ++++++- internal/cmd/workload/exchange_test.go | 52 +++++++++++ internal/cmd/workload/fixtures_test.go | 44 ++++++++++ internal/cmd/workload/provider_resolve.go | 23 +++-- internal/cmd/workload/render_test.go | 89 +++++++++++++++++++ internal/cmd/workload/rule_create.go | 15 +++- internal/cmd/workload/rule_create_test.go | 79 +++++++++++++++-- internal/cmd/workload/rule_delete.go | 101 ++++++++++++++++++++-- internal/cmd/workload/rule_input.go | 69 ++++++++++++--- internal/cmd/workload/rule_show.go | 22 ++--- internal/cmd/workload/rule_test.go | 99 ++++++++++++++++++++- 15 files changed, 617 insertions(+), 61 deletions(-) create mode 100644 internal/cmd/workload/render_test.go diff --git a/docs/cmd/workload-exchange-list.md b/docs/cmd/workload-exchange-list.md index fa51e83..e70baab 100644 --- a/docs/cmd/workload-exchange-list.md +++ b/docs/cmd/workload-exchange-list.md @@ -40,6 +40,10 @@ The reason names the missing rule. Create a rule that covers the job with [`safedep workload rule create`](./workload-rule-create.md). For an issued exchange, `DETAIL` says when the credential expires, or when it was revoked. +When `--rule` names no live rule, the CLI sends the value as a rule id. If no +exchange matches, the command says that no live rule has that name or id. To list +the exchanges of a deleted rule, pass its rule id. + ## Output `json` holds `exchanges` (exchange id, outcome, denial reason, rule id, provider diff --git a/docs/cmd/workload-rule-create.md b/docs/cmd/workload-rule-create.md index ed6c944..e890556 100644 --- a/docs/cmd/workload-rule-create.md +++ b/docs/cmd/workload-rule-create.md @@ -9,6 +9,7 @@ Actions workflow then calls SafeDep with no API key in the CI secrets. ``` safedep workload rule create NAME --provider PROVIDER --grant GRANT [--repository OWNER/NAME...] [--ref REF...] [--event EVENT...] + [--project-binding auto|manual] [--max-lifetime DURATION] [--output table|plain|json] ``` @@ -21,9 +22,11 @@ as in `org` or `web-release`. |------|-------------| | `--provider ` | The provider of the rule: a provider id or `KIND:ACCOUNT`, as in `github-actions:acme`. Required. | | `--grant ` | The grant that the rule gives. `tool` lets the job call the RPCs that pmg, vet and the `safedep` CLI use. Required. | -| `--repository ` | A repository by its full name, as in `acme/web`. Repeat the flag, or separate names with commas. | +| `--repository ` | A repository by its full name, as in `acme/web`. Repeat the flag, or separate names with commas. At most 100 repositories. | | `--ref ` | A full ref, as in `refs/heads/main`, or a prefix that ends with `/*`, as in `refs/heads/release/*`. Repeat the flag for more refs. | | `--event ` | An event name of the platform, as in `push` or `pull_request_target`. Repeat the flag for more events. | +| `--project-binding ` | How a repository with no project gets a project: `auto` or `manual`. See [Projects](#projects). | +| `--max-lifetime ` | The longest life of a credential that the rule gives, from `1m` to `6h`, as in `30m`. The server default is `6h`. | ## The provider is required @@ -61,9 +64,16 @@ it creates such a rule. `workflow_dispatch` and `release`. Any other event, such as `issues` or `pull_request_target`, matches only a rule that lists it with `--event`. -The server sets how a repository with no project gets a project. A rule with no -repository creates the project at the first tool session of the repository -(`auto`). A rule with repositories needs a project first (`manual`). +## Projects + +`--project-binding` says how a repository with no project gets a project: + +- `auto`: the first tool session of the repository creates its project. +- `manual`: a member adds the repository as a project first. A tool session + from a repository with no project fails. Policy fetch and event sync still work. + +With no `--project-binding`, the server picks: `auto` for a rule with no +repository, and `manual` for a rule with repositories. ## Examples diff --git a/docs/cmd/workload-rule-delete.md b/docs/cmd/workload-rule-delete.md index 127902b..6d3b0f1 100644 --- a/docs/cmd/workload-rule-delete.md +++ b/docs/cmd/workload-rule-delete.md @@ -2,20 +2,39 @@ Delete a workload trust rule by its id or its name. Every workload credential that the rule gave stops working within 30 seconds, and the CI jobs that the -rule covered get no new credential. +rule admits lose access to SafeDep Cloud. ## Synopsis ``` -safedep workload rule delete RULE +safedep workload rule delete RULE [--yes] ``` +## Flags + +| Flag | Description | +|------|-------------| +| `-y`, `--yes` | Delete the rule with no prompt. | + ## Examples ```bash safedep workload rule delete web ``` +The command asks first. With no terminal, pass `--yes`. + +``` +The CI jobs that rule web admits, in acme/web, lose access to SafeDep Cloud. Delete it? [y/N]: +``` + +For a rule with no repository, the question says that the rule covers every +repository of the account: + +``` +Rule org covers every repository of acme. The CI jobs of every repository that it admits lose access to SafeDep Cloud. Delete it? [y/N]: +``` + ``` ✓ rule wtr_9d1 deleted Every workload credential that the rule gave stops working within 30 seconds @@ -37,5 +56,5 @@ Requires a control-plane OAuth session. Run `safedep auth login` first. | Code | Meaning | |------|---------| -| `0` | The rule was deleted. | +| `0` | The rule was deleted, or you answered no and nothing was deleted. | | non-zero | The rule does not exist, or the request failed. | diff --git a/internal/cmd/workload/errors.go b/internal/cmd/workload/errors.go index 13eac2e..8b4a36e 100644 --- a/internal/cmd/workload/errors.go +++ b/internal/cmd/workload/errors.go @@ -102,8 +102,11 @@ func mapRuleCreateError(name, provider string, err error) error { "See it with: safedep workload rule show "+tui.EscapeLine(name), cause) case codes.Unavailable: + // The server sends UNAVAILABLE when GitHub does not answer, but a + // transport failure or a gateway has the same code, so the text does + // not name the cause. return newWorkloadError(usefulerror.ErrServiceUnavailable, - "The server could not read the repositories from GitHub: "+rpcerror.Describe(err, rpcerror.AsIs), + rpcerror.Describe(err, rpcerror.AsIs), "Run the command again later", cause) } diff --git a/internal/cmd/workload/exchange.go b/internal/cmd/workload/exchange.go index 4026293..9a43485 100644 --- a/internal/cmd/workload/exchange.go +++ b/internal/cmd/workload/exchange.go @@ -9,6 +9,7 @@ import ( controltowerv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/v1/controltowerv1grpc" controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" + drytui "github.com/safedep/dry/tui" "github.com/safedep/dry/tui/humanize" "github.com/safedep/dry/tui/table" "github.com/spf13/cobra" @@ -34,6 +35,8 @@ type exchangeListInput struct { type exchangeListResult struct { Exchanges []exchangeView `json:"exchanges"` NextPageToken string `json:"next_page_token,omitempty"` + // unknownRule is the --rule value when it names no live rule. + unknownRule string } func exchangeListCmd(a *app.App) *cobra.Command { @@ -56,6 +59,9 @@ func exchangeListCmd(a *app.App) *cobra.Command { if err != nil { return err } + if notice := res.notice(); notice != "" { + drytui.Info("%s", notice) + } return a.Output.Print(res) }, } @@ -88,11 +94,15 @@ func runExchangeList( filters.SetOutcome(controltowerv1.WorkloadExchangeOutcome_WORKLOAD_EXCHANGE_OUTCOME_DENIED) set = true } + unknownRule := "" if in.Rule != "" { - id, err := ruleIDOf(ctx, client, "exchange list", in.Rule) + id, live, err := ruleIDOf(ctx, client, "exchange list", in.Rule) if err != nil { return nil, err } + if !live { + unknownRule = in.Rule + } filters.SetRuleId(id) set = true } @@ -109,6 +119,7 @@ func runExchangeList( out := &exchangeListResult{ Exchanges: make([]exchangeView, 0, len(res.GetExchanges())), NextPageToken: res.GetPagination().GetNextPageToken(), + unknownRule: unknownRule, } for _, e := range res.GetExchanges() { out.Exchanges = append(out.Exchanges, newExchangeView(e)) @@ -116,6 +127,17 @@ func runExchangeList( return out, nil } +// notice explains an empty list for a --rule that names no live rule. The +// CLI sent such a value as a rule id, so a name of a deleted rule, or a +// typing error, matches nothing. +func (r *exchangeListResult) notice() string { + if len(r.Exchanges) > 0 || r.unknownRule == "" { + return "" + } + return fmt.Sprintf("No live rule has the name or id %s. To list the exchanges of a deleted rule, pass its rule id", + tui.EscapeLine(r.unknownRule)) +} + func (r *exchangeListResult) RenderJSON() ([]byte, error) { return json.MarshalIndent(r, "", " ") } @@ -136,7 +158,7 @@ func (r *exchangeListResult) RenderTable() string { Title("Workload exchanges"). Headers("WHEN", "OUTCOME", "WORKLOAD", "RULE", "DETAIL"). Rows(tui.EscapeCells(rows)...). - EmptyMessage("No workload exchanges match. Try a wider --since window.") + EmptyMessage(r.emptyMessage()) if len(rows) > 0 { footer := fmt.Sprintf("%d %s", len(rows), cloudpolicy.Plural(len(rows), "exchange", "exchanges")) if r.NextPageToken != "" { @@ -147,6 +169,13 @@ func (r *exchangeListResult) RenderTable() string { return t.Render() } +func (r *exchangeListResult) emptyMessage() string { + if r.unknownRule != "" { + return "No workload exchanges match." + } + return "No workload exchanges match. Try a wider --since window." +} + func (r *exchangeListResult) RenderPlain() string { var b strings.Builder b.WriteString("created_at\texchange_id\toutcome\tdisplay_identity\trule_id\tprovider_id\tgrant\tendpoint_id\t" + diff --git a/internal/cmd/workload/exchange_test.go b/internal/cmd/workload/exchange_test.go index c11994b..7fa44fa 100644 --- a/internal/cmd/workload/exchange_test.go +++ b/internal/cmd/workload/exchange_test.go @@ -99,3 +99,55 @@ func TestExchangeView_Detail(t *testing.T) { }) } } + +func TestRunExchangeList_RuleThatNamesNoLiveRule(t *testing.T) { + issued := controltowerv1.WorkloadExchange_builder{ + ExchangeId: "x1", + Outcome: controltowerv1.WorkloadExchangeOutcome_WORKLOAD_EXCHANGE_OUTCOME_ISSUED, + RuleId: "r_gone", + }.Build() + tests := []struct { + name string + rule string + exchanges []*controltowerv1.WorkloadExchange + wantNotice string + wantEmpty string + }{ + { + name: "a name of no live rule and no exchange", + rule: "web-old", + wantNotice: "No live rule has the name or id web-old. To list the exchanges of a deleted rule, pass its rule id", + wantEmpty: "No workload exchanges match.", + }, + { + name: "the id of a deleted rule with exchanges", + rule: "r_gone", + exchanges: []*controltowerv1.WorkloadExchange{issued}, + }, + { + name: "a live rule with no exchange", + rule: "org", + wantEmpty: "No workload exchanges match. Try a wider --since window.", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + client := mocks.NewWorkloadAdminServiceClientMock(t) + expectRulePages(client, []*controltowerv1.WorkloadTrustRule{trustRule("r_org", "org", nil)}) + client.EXPECT().ListWorkloadExchanges(mock.Anything, mock.Anything). + Return(controltowerv1.ListWorkloadExchangesResponse_builder{Exchanges: tt.exchanges}.Build(), nil) + + res, err := runExchangeList(context.Background(), client, exchangeListInput{Rule: tt.rule}, time.Now()) + + require.NoError(t, err) + assert.Equal(t, tt.wantNotice, res.notice()) + if tt.wantEmpty != "" { + assert.Contains(t, res.RenderTable(), tt.wantEmpty) + } + if tt.wantNotice != "" { + // A wider window cannot help a rule that the server does not know. + assert.NotContains(t, res.RenderTable(), "--since") + } + }) + } +} diff --git a/internal/cmd/workload/fixtures_test.go b/internal/cmd/workload/fixtures_test.go index c528736..bd28fdc 100644 --- a/internal/cmd/workload/fixtures_test.go +++ b/internal/cmd/workload/fixtures_test.go @@ -2,6 +2,7 @@ package workload import ( "bytes" + "fmt" "os" "testing" @@ -9,7 +10,10 @@ import ( controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" "github.com/safedep/dry/tui/output" "github.com/safedep/dry/usefulerror" + "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + + "github.com/safedep/cli/internal/cmd/workload/mocks" ) const githubActions = controltowerv1.WorkloadIdentityProviderKind_WORKLOAD_IDENTITY_PROVIDER_KIND_GITHUB_ACTIONS @@ -92,3 +96,43 @@ func captureStderr(t *testing.T) *bytes.Buffer { t.Cleanup(func() { output.SetWriters(os.Stdout, os.Stderr) }) return &buf } + +// pageTokens gives the page token that asks for page i and the next page +// token that page i returns. The first page has no token and the last page +// has no next page token. +func pageTokens(i, pages int) (token, next string) { + if i > 0 { + token = fmt.Sprintf("p%d", i) + } + if i < pages-1 { + next = fmt.Sprintf("p%d", i+1) + } + return token, next +} + +// expectRulePages serves the rules in pages. A command that finds what it +// needs on an early page may not read the later ones. +func expectRulePages(client *mocks.WorkloadAdminServiceClientMock, pages ...[]*controltowerv1.WorkloadTrustRule) { + for i, page := range pages { + token, next := pageTokens(i, len(pages)) + client.EXPECT().ListWorkloadTrustRules(mock.Anything, mock.MatchedBy(func(r *controltowerv1.ListWorkloadTrustRulesRequest) bool { + return r.GetPagination().GetPageToken() == token + })).Return(controltowerv1.ListWorkloadTrustRulesResponse_builder{ + Rules: page, + Pagination: messagescontroltowerv1.PaginationResponse_builder{NextPageToken: next}.Build(), + }.Build(), nil).Maybe() + } +} + +// expectProviderPages serves the providers in pages. +func expectProviderPages(client *mocks.WorkloadAdminServiceClientMock, pages ...[]*controltowerv1.WorkloadIdentityProvider) { + for i, page := range pages { + token, next := pageTokens(i, len(pages)) + client.EXPECT().ListWorkloadIdentityProviders(mock.Anything, mock.MatchedBy(func(r *controltowerv1.ListWorkloadIdentityProvidersRequest) bool { + return r.GetPagination().GetPageToken() == token + })).Return(controltowerv1.ListWorkloadIdentityProvidersResponse_builder{ + Providers: page, + Pagination: messagescontroltowerv1.PaginationResponse_builder{NextPageToken: next}.Build(), + }.Build(), nil).Once() + } +} diff --git a/internal/cmd/workload/provider_resolve.go b/internal/cmd/workload/provider_resolve.go index 3f3426c..c8d3732 100644 --- a/internal/cmd/workload/provider_resolve.go +++ b/internal/cmd/workload/provider_resolve.go @@ -53,7 +53,7 @@ func resolveProvider( ) (*controltowerv1.WorkloadIdentityProvider, error) { ref = strings.TrimSpace(ref) if ref == "" { - return nil, providerError("--provider is required. The CLI never picks a provider", providers) + return nil, providerError("--provider is required. The CLI never picks a provider", providers, false) } for _, p := range providers { if p.GetProviderId() == ref { @@ -70,23 +70,30 @@ func resolveProvider( case 1: return matches[0], nil case 0: - return nil, providerError(fmt.Sprintf("--provider %s is not a provider of the tenant", tui.EscapeLine(ref)), providers) + return nil, providerError(fmt.Sprintf("--provider %s is not a provider of the tenant", tui.EscapeLine(ref)), + providers, false) } - return nil, providerError(fmt.Sprintf("--provider %s names more than one provider. Pass the provider id", - tui.EscapeLine(ref)), matches) + return nil, providerError(fmt.Sprintf("--provider %s names more than one provider", tui.EscapeLine(ref)), + matches, true) } // providerError lists the providers that --provider can take, so the user -// can run the command again with one of them. -func providerError(problem string, providers []*controltowerv1.WorkloadIdentityProvider) error { +// can run the command again with one of them. ambiguous lists the providers +// that one KIND:ACCOUNT name matches, and suggests a provider id, because the +// name cannot select one of them. +func providerError(problem string, providers []*controltowerv1.WorkloadIdentityProvider, ambiguous bool) error { if len(providers) == 0 { return invalidInputError(problem+". The tenant has no workload identity provider", noProvidersHelp) } - lines := []string{problem + ". The providers of the tenant:"} + title, suggestion := "The providers of the tenant:", providerName(providers[0]) + if ambiguous { + title, suggestion = "Pass the id of one of them:", providers[0].GetProviderId() + } + lines := []string{problem + ". " + title} for _, p := range providers { lines = append(lines, fmt.Sprintf(" %s id %s, link %s", tui.EscapeLine(providerName(p)), tui.EscapeLine(p.GetProviderId()), tui.EnumToken(p.GetLinkState().String(), linkStatePrefix))) } return invalidInputError(strings.Join(lines, "\n"), - "Run the command again with --provider "+tui.EscapeLine(providerName(providers[0]))) + "Run the command again with --provider "+tui.EscapeLine(suggestion)) } diff --git a/internal/cmd/workload/render_test.go b/internal/cmd/workload/render_test.go new file mode 100644 index 0000000..73b1943 --- /dev/null +++ b/internal/cmd/workload/render_test.go @@ -0,0 +1,89 @@ +package workload + +import ( + "encoding/json" + "strings" + "testing" + "time" + + controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/safedep/cli/internal/tui" +) + +func TestListResults_Render(t *testing.T) { + created := timestamppb.New(time.Date(2026, 11, 20, 9, 0, 0, 0, time.UTC)) + provider := activeProvider("prov_acme", "acme") + provider.SetCreatedAt(created) + rule := trustRule("r_web", "web", map[string]string{"acme/web": "123456"}, condition(claimRef, equals, "refs/heads/main")) + exchange := controltowerv1.WorkloadExchange_builder{ + ExchangeId: "x1", + Outcome: controltowerv1.WorkloadExchangeOutcome_WORKLOAD_EXCHANGE_OUTCOME_DENIED, + DenialReason: "no workload trust rule gives TOOL to acme/web on refs/heads/x", + ClaimSummary: controltowerv1.WorkloadClaimSummary_builder{DisplayIdentity: "github:acme/web\x1b[2J run 1/1"}.Build(), + CreatedAt: created, + }.Build() + names := map[string]string{"prov_acme": "github-actions:acme"} + + tests := []struct { + name string + result tui.Renderable + itemsKey string + wantTable []string + wantPlain []string + }{ + { + name: "providers", + result: &providerListResult{Providers: []providerView{newProviderView(provider)}, NextPageToken: "tok"}, + itemsKey: "providers", + wantTable: []string{"Workload identity providers", "github-actions:acme", "prov_acme", "active", "More available: --page-token tok"}, + wantPlain: []string{ + "provider_id\tname\tkind\taccount_login\towner_id\tlink_state\tlink_id\tcreated_at", + "prov_acme\tgithub-actions:acme\tgithub-actions\tacme\t1001\tactive\tlink-prov_acme\t2026-11-20T09:00:00Z", + }, + }, + { + name: "rules", + result: &ruleListResult{Rules: []ruleView{newRuleView(rule, names)}, NextPageToken: "tok"}, + itemsKey: "rules", + wantTable: []string{"Workload trust rules", "r_web", "acme/web", "ref = refs/heads/main", "never", "More available: --page-token tok"}, + wantPlain: []string{ + "rule_id\tname\tprovider\tprovider_id\tgrant\trepositories\tconditions\tproject_binding\tlast_used_at", + "r_web\tweb\tgithub-actions:acme\tprov_acme\ttool\tacme/web=123456\tref = refs/heads/main\tmanual\t", + }, + }, + { + name: "exchanges", + result: &exchangeListResult{Exchanges: []exchangeView{newExchangeView(exchange)}, NextPageToken: "tok"}, + itemsKey: "exchanges", + wantTable: []string{"Workload exchanges", "denied", `github:acme/web\x1b[2J run 1/1`, "no workload trust rule gives TOOL", "More available: --page-token tok"}, + wantPlain: []string{ + "created_at\texchange_id\toutcome\tdisplay_identity\trule_id\tprovider_id\tgrant\tendpoint_id\texpires_at\trevoked_at\tdenial_reason", + "2026-11-20T09:00:00Z\tx1\tdenied\tgithub:acme/web\\x1b[2J run 1/1\t\t\tunknown\t\t\t\tno workload trust rule gives TOOL to acme/web on refs/heads/x", + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + out, err := tt.result.RenderJSON() + require.NoError(t, err) + var decoded map[string]json.RawMessage + require.NoError(t, json.Unmarshal(out, &decoded)) + var items []json.RawMessage + require.NoError(t, json.Unmarshal(decoded[tt.itemsKey], &items)) + assert.Len(t, items, 1) + assert.JSONEq(t, `"tok"`, string(decoded["next_page_token"])) + + table := tt.result.RenderTable() + for _, w := range tt.wantTable { + assert.Contains(t, table, w) + } + assert.NotContains(t, table, "\x1b[2J") + + assert.Equal(t, tt.wantPlain, strings.Split(tt.result.RenderPlain(), "\n")) + }) + } +} diff --git a/internal/cmd/workload/rule_create.go b/internal/cmd/workload/rule_create.go index 842f506..1b28ccb 100644 --- a/internal/cmd/workload/rule_create.go +++ b/internal/cmd/workload/rule_create.go @@ -3,12 +3,14 @@ package workload import ( "context" "strings" + "time" controltowerv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/v1/controltowerv1grpc" "github.com/safedep/dry/tui" "github.com/spf13/cobra" "github.com/safedep/cli/internal/app" + "github.com/safedep/cli/internal/duration" clitui "github.com/safedep/cli/internal/tui" ) @@ -19,6 +21,11 @@ type ruleCreateInput struct { Repositories []string Refs []string Events []string + // ProjectBinding and MaxLifetime stay unset unless the flag is given, so + // the server default applies. + ProjectBinding string + MaxLifetime time.Duration + MaxLifetimeSet bool } func ruleCreateCmd(a *app.App) *cobra.Command { @@ -34,12 +41,14 @@ func ruleCreateCmd(a *app.App) *cobra.Command { "repository of the account. --ref takes a full ref, as in refs/heads/main, or a prefix that ends " + "with /*, as in refs/heads/release/*. A rule with no --event covers only the default events of " + "the provider. For GitHub Actions they are push, pull_request, merge_group, schedule, " + - "workflow_dispatch and release.", + "workflow_dispatch and release. --project-binding and --max-lifetime take the server default " + + "when you do not give them.", Args: func(cmd *cobra.Command, args []string) error { if err := cobra.ExactArgs(1)(cmd, args); err != nil { return err } in.Name = args[0] + in.MaxLifetimeSet = cmd.Flags().Changed("max-lifetime") _, err := newRuleCreateRequest(in) return err }, @@ -62,6 +71,10 @@ func ruleCreateCmd(a *app.App) *cobra.Command { f.StringSliceVar(&in.Repositories, "repository", nil, "a repository by full name, as in acme/web. Repeat it for more repositories") f.StringArrayVar(&in.Refs, "ref", nil, "a full ref, as in refs/heads/main, or a prefix, as in refs/heads/release/*. Repeat it for more refs") f.StringSliceVar(&in.Events, "event", nil, "an event name, as in push or pull_request_target. Repeat it for more events") + f.StringVar(&in.ProjectBinding, "project-binding", "", "how a repository with no project gets a project: "+ + strings.Join(projectBindingTokens(), " or ")+". The server default is auto for a rule with no --repository, else manual") + f.Var(duration.NewValue(&in.MaxLifetime, 0), "max-lifetime", + "the longest life of a credential that the rule gives, from 1m to 6h. The server default is 6h") return cmd } diff --git a/internal/cmd/workload/rule_create_test.go b/internal/cmd/workload/rule_create_test.go index 90aac27..ded14d1 100644 --- a/internal/cmd/workload/rule_create_test.go +++ b/internal/cmd/workload/rule_create_test.go @@ -3,9 +3,11 @@ package workload import ( "context" "encoding/json" + "fmt" "regexp" "strings" "testing" + "time" messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" errorv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/error/v1" @@ -29,12 +31,14 @@ func TestRunRuleCreate_Provider(t *testing.T) { listed := "The providers of the tenant:\n" + " github-actions:acme id prov_acme, link active\n" + " github-actions:Beta id prov_beta, link suspended" + acmeTwin := activeProvider("prov_acme2", "ACME") tests := []struct { - name string - providers []*controltowerv1.WorkloadIdentityProvider - provider string - wantID string - wantErr usefulErrorWant + name string + providers []*controltowerv1.WorkloadIdentityProvider + secondPage []*controltowerv1.WorkloadIdentityProvider + provider string + wantID string + wantErr usefulErrorWant }{ { name: "no provider with one provider in the tenant", @@ -79,6 +83,25 @@ func TestRunRuleCreate_Provider(t *testing.T) { provider: "github-actions:beta", wantID: "prov_beta", }, + { + name: "KIND:ACCOUNT that names two providers", + providers: []*controltowerv1.WorkloadIdentityProvider{acme, acmeTwin, beta}, + provider: "github-actions:acme", + wantErr: usefulErrorWant{ + code: usefulerror.ErrBadRequest, + human: "--provider github-actions:acme names more than one provider. Pass the id of one of them:\n" + + " github-actions:acme id prov_acme, link active\n" + + " github-actions:ACME id prov_acme2, link active", + help: "Run the command again with --provider prov_acme", + }, + }, + { + name: "a provider on the second page", + providers: []*controltowerv1.WorkloadIdentityProvider{acme}, + secondPage: []*controltowerv1.WorkloadIdentityProvider{beta}, + provider: "github-actions:Beta", + wantID: "prov_beta", + }, { name: "a provider id", providers: []*controltowerv1.WorkloadIdentityProvider{acme, beta}, @@ -89,7 +112,11 @@ func TestRunRuleCreate_Provider(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { client := mocks.NewWorkloadAdminServiceClientMock(t) - client.EXPECT().ListWorkloadIdentityProviders(mock.Anything, mock.Anything).Return(providersResponse(tt.providers...), nil) + if tt.secondPage != nil { + expectProviderPages(client, tt.providers, tt.secondPage) + } else { + client.EXPECT().ListWorkloadIdentityProviders(mock.Anything, mock.Anything).Return(providersResponse(tt.providers...), nil) + } if tt.wantID != "" { client.EXPECT().CreateWorkloadTrustRule(mock.Anything, mock.MatchedBy(func(r *controltowerv1.CreateWorkloadTrustRuleRequest) bool { return r.GetProviderId() == tt.wantID @@ -217,6 +244,15 @@ func TestRunRuleCreate_ServerErrors(t *testing.T) { help: "See the flags: safedep workload rule create --help", }, }, + { + name: "a server that does not answer", + err: status.Error(codes.Unavailable, "upstream connect error"), + want: usefulErrorWant{ + code: usefulerror.ErrServiceUnavailable, + human: "upstream connect error", + help: "Run the command again later", + }, + }, { name: "a member", err: status.Error(codes.PermissionDenied, "admin role required"), @@ -254,6 +290,8 @@ func TestNewRuleCreateRequest(t *testing.T) { {name: "an org-wide rule", mutate: func(*ruleCreateInput) {}, check: func(t *testing.T, r *controltowerv1.CreateWorkloadTrustRuleRequest) { assert.Empty(t, r.GetRepositories()) assert.Empty(t, r.GetConditions()) + assert.Equal(t, controltowerv1.WorkloadProjectBinding_WORKLOAD_PROJECT_BINDING_UNSPECIFIED, r.GetProjectBinding()) + assert.False(t, r.HasMaxLifetime()) }}, {name: "a name in upper case", mutate: func(in *ruleCreateInput) { in.Name = "Web" }, wantErr: `rule name "Web"`}, {name: "a name that ends with a hyphen", mutate: func(in *ruleCreateInput) { in.Name = "web-" }, wantErr: `rule name "web-"`}, @@ -262,6 +300,35 @@ func TestNewRuleCreateRequest(t *testing.T) { {name: "a repository with no owner", mutate: func(in *ruleCreateInput) { in.Repositories = []string{"web"} }, wantErr: `--repository "web": write OWNER/NAME`}, {name: "a repository path", mutate: func(in *ruleCreateInput) { in.Repositories = []string{"acme/web/x"} }, wantErr: "write OWNER/NAME"}, {name: "a dot segment", mutate: func(in *ruleCreateInput) { in.Repositories = []string{"acme/.."} }, wantErr: "write OWNER/NAME"}, + {name: "a space in a repository", mutate: func(in *ruleCreateInput) { in.Repositories = []string{"acme/web app"} }, wantErr: `--repository "acme/web app"`}, + {name: "a repository name over 256 characters", mutate: func(in *ruleCreateInput) { + in.Repositories = []string{"acme/" + strings.Repeat("a", 252)} + }, wantErr: "in at most 256 characters"}, + {name: "101 repositories", mutate: func(in *ruleCreateInput) { + for i := range 101 { + in.Repositories = append(in.Repositories, fmt.Sprintf("acme/r%d", i)) + } + }, wantErr: "a rule names at most 100 repositories"}, + {name: "repository names with dots", mutate: func(in *ruleCreateInput) { in.Repositories = []string{"acme/.github", "acme/web.js"} }, + check: func(t *testing.T, r *controltowerv1.CreateWorkloadTrustRuleRequest) { + assert.Equal(t, []string{"acme/.github", "acme/web.js"}, r.GetRepositories()) + }}, + {name: "an unknown project binding", mutate: func(in *ruleCreateInput) { in.ProjectBinding = "always" }, wantErr: `--project-binding "always"`}, + {name: "a project binding", mutate: func(in *ruleCreateInput) { in.ProjectBinding = "manual" }, + check: func(t *testing.T, r *controltowerv1.CreateWorkloadTrustRuleRequest) { + assert.Equal(t, controltowerv1.WorkloadProjectBinding_WORKLOAD_PROJECT_BINDING_MANUAL, r.GetProjectBinding()) + assert.False(t, r.HasMaxLifetime()) + }}, + {name: "a lifetime under one minute", mutate: func(in *ruleCreateInput) { in.MaxLifetime, in.MaxLifetimeSet = 59*time.Second, true }, + wantErr: "--max-lifetime 59s: use a duration from 1m to 6h"}, + {name: "a lifetime over six hours", mutate: func(in *ruleCreateInput) { in.MaxLifetime, in.MaxLifetimeSet = 6*time.Hour+time.Second, true }, + wantErr: "use a duration from 1m to 6h"}, + {name: "a lifetime of zero", mutate: func(in *ruleCreateInput) { in.MaxLifetimeSet = true }, wantErr: "use a duration from 1m to 6h"}, + {name: "a lifetime at the bounds", mutate: func(in *ruleCreateInput) { in.MaxLifetime, in.MaxLifetimeSet = 6*time.Hour, true }, + check: func(t *testing.T, r *controltowerv1.CreateWorkloadTrustRuleRequest) { + assert.Equal(t, 6*time.Hour, r.GetMaxLifetime().AsDuration()) + assert.Equal(t, controltowerv1.WorkloadProjectBinding_WORKLOAD_PROJECT_BINDING_UNSPECIFIED, r.GetProjectBinding()) + }}, {name: "a short ref", mutate: func(in *ruleCreateInput) { in.Refs = []string{"main"} }, wantErr: `--ref "main": write the full ref`}, {name: "a prefix that ends in a name", mutate: func(in *ruleCreateInput) { in.Refs = []string{"refs/heads/main*"} }, wantErr: "a prefix is refs/heads/"}, {name: "a star inside a ref", mutate: func(in *ruleCreateInput) { in.Refs = []string{"refs/heads/*/x"} }, wantErr: "a prefix is refs/heads/"}, diff --git a/internal/cmd/workload/rule_delete.go b/internal/cmd/workload/rule_delete.go index 85a234c..7c71514 100644 --- a/internal/cmd/workload/rule_delete.go +++ b/internal/cmd/workload/rule_delete.go @@ -2,30 +2,50 @@ package workload import ( "context" + "errors" + "fmt" controltowerv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/v1/controltowerv1grpc" controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" "github.com/safedep/dry/tui" + "github.com/safedep/dry/tui/prompt" + "github.com/safedep/dry/usefulerror" "github.com/spf13/cobra" "github.com/safedep/cli/internal/app" clitui "github.com/safedep/cli/internal/tui" ) +// confirmFunc asks the user to confirm an action and returns the answer. +type confirmFunc func(question string) (bool, error) + +// errDeleteCancelled stops a delete that the user did not confirm. +var errDeleteCancelled = errors.New("delete cancelled") + func ruleDeleteCmd(a *app.App) *cobra.Command { - return &cobra.Command{ + var yes bool + cmd := &cobra.Command{ Use: "delete RULE", Short: "Delete a workload trust rule", Long: "Delete a workload trust rule by its id or its name. Every workload credential that the rule " + - "gave stops working within 30 seconds, and the CI jobs that the rule covered get no new credential. " + - "The exchanges of the rule stay in `safedep workload exchange list`.", + "gave stops working within 30 seconds, and the CI jobs that the rule admits lose access to SafeDep " + + "Cloud. The command asks for a confirmation in a terminal, and needs --yes when no terminal is " + + "present. The exchanges of the rule stay in `safedep workload exchange list`.", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { client, err := adminClient(a) if err != nil { return err } - id, err := runRuleDelete(cmd.Context(), client, args[0]) + var confirm confirmFunc + if !yes { + confirm = terminalConfirm(clitui.IsInteractive(), args[0]) + } + id, err := runRuleDelete(cmd.Context(), client, args[0], confirm) + if errors.Is(err, errDeleteCancelled) { + tui.Info("Nothing is deleted") + return nil + } if err != nil { return err } @@ -34,14 +54,42 @@ func ruleDeleteCmd(a *app.App) *cobra.Command { return nil }, } + cmd.Flags().BoolVarP(&yes, "yes", "y", false, "delete the rule with no prompt") + return cmd +} + +// terminalConfirm asks in a terminal. With no terminal it refuses, because a +// script that deletes a rule must say so with --yes. +func terminalConfirm(interactive bool, ref string) confirmFunc { + return func(question string) (bool, error) { + if !interactive { + problem := "the delete of a workload trust rule needs a confirmation, and no terminal is present to confirm it" + return false, newWorkloadError(usefulerror.ErrBadRequest, problem, + fmt.Sprintf("Review it with safedep workload rule show %s, then pass --yes to delete it", clitui.EscapeLine(ref)), + errors.New(problem)) + } + return prompt.Confirm(question, false) + } } -// runRuleDelete deletes the rule that ref names and returns its id. -func runRuleDelete(ctx context.Context, client controltowerv1grpc.WorkloadAdminServiceClient, ref string) (string, error) { - id, err := ruleIDOf(ctx, client, "rule delete", ref) +// runRuleDelete deletes the rule that ref names and returns its id. A nil +// confirm means that the user gave --yes, so the command reads nothing to +// ask about. +func runRuleDelete( + ctx context.Context, + client controltowerv1grpc.WorkloadAdminServiceClient, + ref string, + confirm confirmFunc, +) (string, error) { + id, _, err := ruleIDOf(ctx, client, "rule delete", ref) if err != nil { return "", err } + if confirm != nil { + if err := confirmRuleDelete(ctx, client, id, ref, confirm); err != nil { + return "", err + } + } req := &controltowerv1.DeleteWorkloadTrustRuleRequest{} req.SetRuleId(id) if _, err := client.DeleteWorkloadTrustRule(ctx, req); err != nil { @@ -49,3 +97,42 @@ func runRuleDelete(ctx context.Context, client controltowerv1grpc.WorkloadAdminS } return id, nil } + +// confirmRuleDelete reads the rule, so the question says which jobs lose +// access: every repository of the account for a rule with no repository +// condition. +func confirmRuleDelete( + ctx context.Context, + client controltowerv1grpc.WorkloadAdminServiceClient, + id, ref string, + confirm confirmFunc, +) error { + get := &controltowerv1.GetWorkloadTrustRuleRequest{} + get.SetRuleId(id) + res, err := client.GetWorkloadTrustRule(ctx, get) + if err != nil { + return mapRuleError("rule delete", ref, err) + } + providers, err := listAllProviders(ctx, client, "rule delete") + if err != nil { + return err + } + ok, err := confirm(deleteQuestion(newRuleView(res.GetRule(), providerNames(providers)))) + if err != nil { + return err + } + if !ok { + return errDeleteCancelled + } + return nil +} + +func deleteQuestion(rule ruleView) string { + name := clitui.EscapeLine(rule.Name) + if rule.EveryRepository { + return fmt.Sprintf("Rule %s covers every repository of %s. The CI jobs of every repository that it "+ + "admits lose access to SafeDep Cloud. Delete it?", name, clitui.EscapeLine(rule.account())) + } + return fmt.Sprintf("The CI jobs that rule %s admits, in %s, lose access to SafeDep Cloud. Delete it?", + name, clitui.EscapeLine(rule.repositorySummary())) +} diff --git a/internal/cmd/workload/rule_input.go b/internal/cmd/workload/rule_input.go index 5daa50c..0813e8e 100644 --- a/internal/cmd/workload/rule_input.go +++ b/internal/cmd/workload/rule_input.go @@ -4,20 +4,34 @@ import ( "fmt" "regexp" "strings" + "time" messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" + "google.golang.org/protobuf/types/known/durationpb" clitui "github.com/safedep/cli/internal/tui" ) -// The patterns match the protovalidate rules of CreateWorkloadTrustRuleRequest -// and WorkloadClaimCondition, so a bad flag fails before any RPC with the -// flag in the message. +// The name, ref prefix and repository patterns and the lifetime bounds match +// the protovalidate rules of CreateWorkloadTrustRuleRequest and +// WorkloadClaimCondition, so a bad flag fails before any RPC with the flag in +// the message. The event pattern is the form of a GitHub Actions event name: +// a value of another form never matches a token. var ( ruleNamePattern = regexp.MustCompile(`^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$`) refPrefixPattern = regexp.MustCompile(`^refs/(heads|tags)/([^*]*/)?[*]$`) eventPattern = regexp.MustCompile(`^[a-z][a-z0-9_]*$`) + // repositoryPattern holds at least one character that is not a dot in + // each part, so neither part is "." or "..". + repositoryPattern = regexp.MustCompile(`^[A-Za-z0-9_.-]*[A-Za-z0-9_-][A-Za-z0-9_.-]*/[A-Za-z0-9_.-]*[A-Za-z0-9_-][A-Za-z0-9_.-]*$`) +) + +const ( + maxRepositoryLength = 256 + maxRepositories = 100 + minMaxLifetime = time.Minute + maxMaxLifetime = 6 * time.Hour ) func grantTokens() []string { @@ -61,9 +75,36 @@ func newRuleCreateRequest(in ruleCreateInput) (*controltowerv1.CreateWorkloadTru req.SetGrant(grant) req.SetRepositories(repositories) req.SetConditions(conditions) + if in.ProjectBinding != "" { + binding, err := parseProjectBinding(in.ProjectBinding) + if err != nil { + return nil, err + } + req.SetProjectBinding(binding) + } + if in.MaxLifetimeSet { + if in.MaxLifetime < minMaxLifetime || in.MaxLifetime > maxMaxLifetime { + return nil, invalidInputError(fmt.Sprintf("--max-lifetime %s: use a duration from 1m to 6h", in.MaxLifetime), + "As in --max-lifetime 30m or --max-lifetime 2h") + } + req.SetMaxLifetime(durationpb.New(in.MaxLifetime)) + } return req, nil } +func projectBindingTokens() []string { + return clitui.EnumTokens(controltowerv1.WorkloadProjectBinding_name, projectBindingPrefix) +} + +func parseProjectBinding(token string) (controltowerv1.WorkloadProjectBinding, error) { + n, ok := clitui.ParseEnumToken(controltowerv1.WorkloadProjectBinding_name, projectBindingPrefix, token) + if !ok { + return 0, invalidInputError(fmt.Sprintf("--project-binding %q is not a project binding", token), + "Pass --project-binding "+strings.Join(projectBindingTokens(), " or --project-binding ")) + } + return controltowerv1.WorkloadProjectBinding(n), nil +} + func parseGrant(token string) (messagescontroltowerv1.CredentialGrant, error) { help := "Pass --grant " + strings.Join(grantTokens(), " or --grant ") if token == "" { @@ -76,22 +117,22 @@ func parseGrant(token string) (messagescontroltowerv1.CredentialGrant, error) { return messagescontroltowerv1.CredentialGrant(n), nil } -// repositoryNames checks each --repository value. An owner or a name of "." -// or ".." is never a GitHub repository, and the server refuses it. +// repositoryNames checks each --repository value against the protovalidate +// rules of CreateWorkloadTrustRuleRequest.repositories. func repositoryNames(values []string) ([]string, error) { for _, v := range values { - owner, name, ok := strings.Cut(v, "/") - if !ok || owner == "" || name == "" || strings.Contains(name, "/") || - isDotSegment(owner) || isDotSegment(name) { - return nil, invalidInputError(fmt.Sprintf("--repository %q: write OWNER/NAME", v), + if len(v) > maxRepositoryLength || !repositoryPattern.MatchString(v) { + return nil, invalidInputError(fmt.Sprintf("--repository %q: write OWNER/NAME with letters, digits, "+ + "'-', '_' and '.', in at most %d characters", v, maxRepositoryLength), "As in --repository acme/web") } } - return unique(values), nil -} - -func isDotSegment(s string) bool { - return s == "." || s == ".." + names := unique(values) + if len(names) > maxRepositories { + return nil, invalidInputError(fmt.Sprintf("--repository: a rule names at most %d repositories", maxRepositories), + "Split the repositories over more rules, or create a rule with no --repository for every repository") + } + return names, nil } // refCondition builds the condition on the claim ref. A rule has at most one diff --git a/internal/cmd/workload/rule_show.go b/internal/cmd/workload/rule_show.go index 9698fcd..1d8519f 100644 --- a/internal/cmd/workload/rule_show.go +++ b/internal/cmd/workload/rule_show.go @@ -38,7 +38,7 @@ func runRuleShow( client controltowerv1grpc.WorkloadAdminServiceClient, ref string, ) (*ruleResult, error) { - id, err := ruleIDOf(ctx, client, "rule show", ref) + id, _, err := ruleIDOf(ctx, client, "rule show", ref) if err != nil { return nil, err } @@ -56,16 +56,16 @@ func runRuleShow( } // ruleIDOf finds the id of the rule that ref names: a rule id, or else the -// name of a live rule. A ref that names no live rule stays as it is, so the -// server decides. ListWorkloadExchanges finds the exchanges of a deleted -// rule by its id. +// name of a live rule. live is false when ref names no live rule. Such a ref +// stays as it is, so the server decides. ListWorkloadExchanges finds the +// exchanges of a deleted rule by its id. func ruleIDOf( ctx context.Context, client controltowerv1grpc.WorkloadAdminServiceClient, command, ref string, -) (string, error) { - id, named := "", "" - err := paging.Paginate(ctx, "workload "+command, func(ctx context.Context, pageToken string) (string, error) { +) (id string, live bool, err error) { + named := "" + err = paging.Paginate(ctx, "workload "+command, func(ctx context.Context, pageToken string) (string, error) { req := &controltowerv1.ListWorkloadTrustRulesRequest{} req.SetPagination(paging.NewPaginationRequest(0, pageToken)) res, err := client.ListWorkloadTrustRules(ctx, req) @@ -84,13 +84,13 @@ func ruleIDOf( return res.GetPagination().GetNextPageToken(), nil }) if err != nil { - return "", err + return "", false, err } switch { case id != "": - return id, nil + return id, true, nil case named != "": - return named, nil + return named, true, nil } - return ref, nil + return ref, false, nil } diff --git a/internal/cmd/workload/rule_test.go b/internal/cmd/workload/rule_test.go index c68384a..1a967ce 100644 --- a/internal/cmd/workload/rule_test.go +++ b/internal/cmd/workload/rule_test.go @@ -16,7 +16,10 @@ import ( ) func TestRunRuleDelete(t *testing.T) { - rules := rulesResponse(trustRule("r_web", "web", nil), trustRule("r_org", "org", nil)) + pages := [][]*controltowerv1.WorkloadTrustRule{ + {trustRule("r_web", "web", nil)}, + {trustRule("r_org", "org", nil)}, + } tests := []struct { name string ref string @@ -24,7 +27,7 @@ func TestRunRuleDelete(t *testing.T) { delErr error wantErr *usefulErrorWant }{ - {name: "by name", ref: "org", wantID: "r_org"}, + {name: "by name on the second page", ref: "org", wantID: "r_org"}, {name: "by id", ref: "r_web", wantID: "r_web"}, { name: "a rule that the tenant does not have", @@ -41,12 +44,13 @@ func TestRunRuleDelete(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { client := mocks.NewWorkloadAdminServiceClientMock(t) - client.EXPECT().ListWorkloadTrustRules(mock.Anything, mock.Anything).Return(rules, nil) + expectRulePages(client, pages...) client.EXPECT().DeleteWorkloadTrustRule(mock.Anything, mock.MatchedBy(func(r *controltowerv1.DeleteWorkloadTrustRuleRequest) bool { return r.GetRuleId() == tt.wantID })).Return(&controltowerv1.DeleteWorkloadTrustRuleResponse{}, tt.delErr) - id, err := runRuleDelete(context.Background(), client, tt.ref) + // A nil confirm is --yes: the command reads no rule to ask about. + id, err := runRuleDelete(context.Background(), client, tt.ref, nil) if tt.wantErr != nil { requireUsefulError(t, err, *tt.wantErr) @@ -58,6 +62,79 @@ func TestRunRuleDelete(t *testing.T) { } } +func TestRunRuleDelete_Confirm(t *testing.T) { + orgWide := trustRule("r_org", "org", nil) + scoped := trustRule("r_web", "web", map[string]string{"acme/web": "123456"}) + tests := []struct { + name string + rule *controltowerv1.WorkloadTrustRule + answer bool + interactive bool + wantQuestion string + wantDeleted bool + wantErr *usefulErrorWant + }{ + { + name: "a rule with no repository, confirmed", + rule: orgWide, + answer: true, + interactive: true, + wantQuestion: "Rule org covers every repository of acme. The CI jobs of every repository that it " + + "admits lose access to SafeDep Cloud. Delete it?", + wantDeleted: true, + }, + { + name: "a rule with a repository, refused", + rule: scoped, + interactive: true, + wantQuestion: "The CI jobs that rule web admits, in acme/web, lose access to SafeDep Cloud. Delete it?", + }, + { + name: "no terminal", + rule: scoped, + wantErr: &usefulErrorWant{ + code: usefulerror.ErrBadRequest, + human: "the delete of a workload trust rule needs a confirmation, and no terminal is present to confirm it", + help: "Review it with safedep workload rule show web, then pass --yes to delete it", + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + client := mocks.NewWorkloadAdminServiceClientMock(t) + expectRulePages(client, []*controltowerv1.WorkloadTrustRule{tt.rule}) + client.EXPECT().GetWorkloadTrustRule(mock.Anything, mock.Anything). + Return(controltowerv1.GetWorkloadTrustRuleResponse_builder{Rule: tt.rule}.Build(), nil) + client.EXPECT().ListWorkloadIdentityProviders(mock.Anything, mock.Anything). + Return(providersResponse(activeProvider("prov_acme", "acme")), nil) + if tt.wantDeleted { + client.EXPECT().DeleteWorkloadTrustRule(mock.Anything, mock.Anything). + Return(&controltowerv1.DeleteWorkloadTrustRuleResponse{}, nil) + } + question := "" + confirm := terminalConfirm(tt.interactive, tt.rule.GetName()) + if tt.interactive { + confirm = func(q string) (bool, error) { + question = q + return tt.answer, nil + } + } + + _, err := runRuleDelete(context.Background(), client, tt.rule.GetName(), confirm) + + switch { + case tt.wantErr != nil: + requireUsefulError(t, err, *tt.wantErr) + case tt.wantDeleted: + require.NoError(t, err) + default: + require.ErrorIs(t, err, errDeleteCancelled) + } + assert.Equal(t, tt.wantQuestion, question) + }) + } +} + func TestRunRuleShow_ByNameWithTheProviderName(t *testing.T) { rule := trustRule("r_web", "web", map[string]string{"acme/web": "123456"}) client := mocks.NewWorkloadAdminServiceClientMock(t) @@ -138,3 +215,17 @@ func TestRuleResult_RenderTable(t *testing.T) { }) } } + +func TestRunRuleList_ProviderID(t *testing.T) { + client := mocks.NewWorkloadAdminServiceClientMock(t) + client.EXPECT().ListWorkloadIdentityProviders(mock.Anything, mock.Anything). + Return(providersResponse(activeProvider("prov_acme", "acme"), activeProvider("prov_beta", "beta")), nil) + client.EXPECT().ListWorkloadTrustRules(mock.Anything, mock.MatchedBy(func(r *controltowerv1.ListWorkloadTrustRulesRequest) bool { + return r.GetFilters().GetProviderId() == "prov_beta" + })).Return(rulesResponse(), nil) + + res, err := runRuleList(context.Background(), client, ruleListInput{Provider: "prov_beta"}) + + require.NoError(t, err) + assert.Empty(t, res.Rules) +}