-
Notifications
You must be signed in to change notification settings - Fork 7
feat(cli): add Service Account commands #973
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mbevc1
wants to merge
3
commits into
main
Choose a base branch
from
20260625_cmd_sa
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "io" | ||
| "net/http" | ||
| "net/url" | ||
|
|
||
| "github.com/kosli-dev/cli/internal/requests" | ||
| "github.com/spf13/cobra" | ||
| ) | ||
|
|
||
| const createServiceAccountShortDesc = `Create a service account.` | ||
|
|
||
| const createServiceAccountLongDesc = createServiceAccountShortDesc + ` | ||
|
|
||
| A service account is a non-human identity in your organization. API keys are | ||
| created separately for it with ^kosli create api-key^.` | ||
|
|
||
| const createServiceAccountExample = ` | ||
| # create a service account: | ||
| kosli create service-account yourServiceAccountName \ | ||
| --privilege member \ | ||
| --description "CI service account" \ | ||
| --api-token yourAPIToken \ | ||
| --org yourOrgName | ||
| ` | ||
|
|
||
| type createServiceAccountOptions struct { | ||
| payload createServiceAccountPayload | ||
| } | ||
|
|
||
| type createServiceAccountPayload struct { | ||
| Name string `json:"name"` | ||
| Description string `json:"description,omitempty"` | ||
| Privilege string `json:"privilege"` | ||
| } | ||
|
|
||
| func newCreateServiceAccountCmd(out io.Writer) *cobra.Command { | ||
| o := new(createServiceAccountOptions) | ||
| cmd := &cobra.Command{ | ||
| Use: "service-account SERVICE-ACCOUNT-NAME", | ||
| Aliases: []string{"sa"}, | ||
| Short: createServiceAccountShortDesc, | ||
| Long: createServiceAccountLongDesc, | ||
| Example: createServiceAccountExample, | ||
| Args: cobra.ExactArgs(1), | ||
| PreRunE: func(cmd *cobra.Command, args []string) error { | ||
| if err := RequireGlobalFlags(global, []string{"Org", "ApiToken"}); err != nil { | ||
| return ErrorBeforePrintingUsage(cmd, err.Error()) | ||
| } | ||
| return nil | ||
| }, | ||
| RunE: func(cmd *cobra.Command, args []string) error { | ||
| return o.run(args) | ||
| }, | ||
| } | ||
|
|
||
| cmd.Flags().StringVarP(&o.payload.Description, "description", "d", "", serviceAccountDescriptionFlag) | ||
| cmd.Flags().StringVar(&o.payload.Privilege, "privilege", "", serviceAccountPrivilegeFlag) | ||
| addDryRunFlag(cmd) | ||
|
|
||
| err := RequireFlags(cmd, []string{"privilege"}) | ||
| if err != nil { | ||
| logger.Error("failed to configure required flags: %v", err) | ||
| } | ||
|
|
||
| return cmd | ||
| } | ||
|
|
||
| func (o *createServiceAccountOptions) run(args []string) error { | ||
| o.payload.Name = args[0] | ||
| url, err := url.JoinPath(global.Host, "api/v2/service-accounts", global.Org) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| reqParams := &requests.RequestParams{ | ||
| Method: http.MethodPost, | ||
| URL: url, | ||
| Payload: o.payload, | ||
| DryRun: global.DryRun, | ||
| Token: global.ApiToken, | ||
| } | ||
| _, err = kosliClient.Do(reqParams) | ||
| if err == nil && !global.DryRun { | ||
| logger.Info("service account %s was created", o.payload.Name) | ||
| } | ||
| return err | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "bufio" | ||
| "fmt" | ||
| "io" | ||
| "net/http" | ||
| "net/url" | ||
| "strings" | ||
|
|
||
| "github.com/kosli-dev/cli/internal/requests" | ||
| "github.com/spf13/cobra" | ||
| ) | ||
|
|
||
| const deleteServiceAccountShortDesc = `Delete one or more service accounts.` | ||
|
|
||
| const deleteServiceAccountLongDesc = deleteServiceAccountShortDesc + ` | ||
|
|
||
| This permanently removes the service account(s) identified by SERVICE-ACCOUNT-NAME | ||
| from the organization, along with their API keys. Deletion is immediate and | ||
| cannot be undone. You are asked to confirm before deletion; use | ||
| ^--assume-yes^/^--yes^ to skip the confirmation prompt.` | ||
|
|
||
| const deleteServiceAccountExample = ` | ||
| # delete a service account (asks for confirmation): | ||
| kosli delete service-account yourServiceAccountName \ | ||
| --api-token yourAPIToken \ | ||
| --org yourOrgName | ||
|
|
||
| # delete multiple service accounts at once: | ||
| kosli delete service-account sa1 sa2 \ | ||
| --api-token yourAPIToken \ | ||
| --org yourOrgName | ||
|
|
||
| # delete a service account without confirmation: | ||
| kosli delete service-account yourServiceAccountName \ | ||
| --assume-yes \ | ||
| --api-token yourAPIToken \ | ||
| --org yourOrgName | ||
| ` | ||
|
|
||
| type deleteServiceAccountOptions struct { | ||
| assumeYes bool | ||
| } | ||
|
|
||
| func newDeleteServiceAccountCmd(out io.Writer) *cobra.Command { | ||
| o := new(deleteServiceAccountOptions) | ||
| cmd := &cobra.Command{ | ||
| Use: "service-account SERVICE-ACCOUNT-NAME [SERVICE-ACCOUNT-NAME...]", | ||
| Aliases: []string{"sa"}, | ||
| Short: deleteServiceAccountShortDesc, | ||
| Long: deleteServiceAccountLongDesc, | ||
| Example: deleteServiceAccountExample, | ||
| Args: cobra.MinimumNArgs(1), | ||
| PreRunE: func(cmd *cobra.Command, args []string) error { | ||
| if err := RequireGlobalFlags(global, []string{"Org", "ApiToken"}); err != nil { | ||
| return ErrorBeforePrintingUsage(cmd, err.Error()) | ||
| } | ||
| return nil | ||
| }, | ||
| RunE: func(cmd *cobra.Command, args []string) error { | ||
| return o.run(cmd.InOrStdin(), args) | ||
| }, | ||
| } | ||
|
|
||
| cmd.Flags().BoolVarP(&o.assumeYes, "assume-yes", "y", false, serviceAccountAssumeYesFlag) | ||
| // keep --yes as a hidden alias for --assume-yes (bound to the same option) | ||
| cmd.Flags().BoolVar(&o.assumeYes, "yes", false, serviceAccountAssumeYesFlag) | ||
| if f := cmd.Flags().Lookup("yes"); f != nil { | ||
| f.Hidden = true | ||
| } | ||
| addDryRunFlag(cmd) | ||
|
|
||
| return cmd | ||
| } | ||
|
|
||
| func (o *deleteServiceAccountOptions) run(in io.Reader, args []string) error { | ||
| if !o.assumeYes && !global.DryRun { | ||
| confirmed, err := confirmServiceAccountDeletion(args, in) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| if !confirmed { | ||
| logger.Info("Deletion of service account(s) %s was cancelled.", strings.Join(styleServiceAccountNames(args), ", ")) | ||
| return nil | ||
| } | ||
| } | ||
|
|
||
| // deletion is destructive and one-way: on any failure mid-batch, make clear | ||
| // which service accounts were already deleted before it. | ||
| reportAlreadyDeleted := func(i int) { | ||
| if i > 0 { | ||
| logger.Info("Service accounts already deleted before this failure: %s", strings.Join(styleServiceAccountNames(args[:i]), ", ")) | ||
| } | ||
| } | ||
|
|
||
| for i, name := range args { | ||
| url, err := url.JoinPath(global.Host, "api/v2/service-accounts", global.Org, name) | ||
| if err != nil { | ||
| reportAlreadyDeleted(i) | ||
| return err | ||
| } | ||
|
|
||
| reqParams := &requests.RequestParams{ | ||
| Method: http.MethodDelete, | ||
| URL: url, | ||
| DryRun: global.DryRun, | ||
| Token: global.ApiToken, | ||
| } | ||
| if _, err := kosliClient.Do(reqParams); err != nil { | ||
| reportAlreadyDeleted(i) | ||
| return fmt.Errorf("failed to delete service account: %w", err) | ||
| } | ||
| if !global.DryRun { | ||
| logger.Info("service account %s was deleted!", style(logger.Out, name, ansiBold, ansiCyan)) | ||
| } | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| // styleServiceAccountNames styles service account names for user-facing | ||
| // messages printed via logger (bold cyan when styling is enabled). | ||
| func styleServiceAccountNames(names []string) []string { | ||
| styled := make([]string, len(names)) | ||
| for i, name := range names { | ||
| styled[i] = style(logger.Out, name, ansiBold, ansiCyan) | ||
| } | ||
| return styled | ||
| } | ||
|
|
||
| // confirmServiceAccountDeletion prompts the user to confirm deletion and | ||
| // returns true only when the answer is an affirmative "y"/"yes" | ||
| // (case-insensitive). The prompt has no trailing newline so the answer is | ||
| // typed on the same line. | ||
| func confirmServiceAccountDeletion(names []string, in io.Reader) (bool, error) { | ||
| logger.Print("Are you sure you want to delete service account(s) %s? [y/N] ", | ||
| strings.Join(styleServiceAccountNames(names), ", ")) | ||
|
|
||
| answer, err := bufio.NewReader(in).ReadString('\n') | ||
| if err != nil && err != io.EOF { | ||
| return false, err | ||
| } | ||
|
|
||
| answer = strings.ToLower(strings.TrimSpace(answer)) | ||
| return answer == "y" || answer == "yes", nil | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "io" | ||
| "net/http" | ||
| "net/url" | ||
|
|
||
| "github.com/kosli-dev/cli/internal/output" | ||
| "github.com/kosli-dev/cli/internal/requests" | ||
| "github.com/spf13/cobra" | ||
| ) | ||
|
|
||
| const getServiceAccountShortDesc = `Get a service account's metadata.` | ||
|
|
||
| const getServiceAccountLongDesc = getServiceAccountShortDesc + ` | ||
|
|
||
| The metadata includes the name, description, privilege, and creation time. The | ||
| secret values of the account's API keys are never returned. Use ^--output json^ | ||
| to get the raw response for scripting.` | ||
|
|
||
| const getServiceAccountExample = ` | ||
| # get the metadata of a service account: | ||
| kosli get service-account yourServiceAccountName \ | ||
| --api-token yourAPIToken \ | ||
| --org yourOrgName | ||
| ` | ||
|
|
||
| type getServiceAccountOptions struct { | ||
| output string | ||
| } | ||
|
|
||
| func newGetServiceAccountCmd(out io.Writer) *cobra.Command { | ||
| o := new(getServiceAccountOptions) | ||
| cmd := &cobra.Command{ | ||
| Use: "service-account SERVICE-ACCOUNT-NAME", | ||
| Aliases: []string{"sa"}, | ||
| Short: getServiceAccountShortDesc, | ||
| Long: getServiceAccountLongDesc, | ||
| Example: getServiceAccountExample, | ||
| Args: cobra.ExactArgs(1), | ||
| PreRunE: func(cmd *cobra.Command, args []string) error { | ||
| if err := RequireGlobalFlags(global, []string{"Org", "ApiToken"}); err != nil { | ||
| return ErrorBeforePrintingUsage(cmd, err.Error()) | ||
| } | ||
| return nil | ||
| }, | ||
| RunE: func(cmd *cobra.Command, args []string) error { | ||
| return o.run(out, args) | ||
| }, | ||
| } | ||
|
|
||
| cmd.Flags().StringVarP(&o.output, "output", "o", "table", outputFlag) | ||
|
|
||
| return cmd | ||
| } | ||
|
|
||
| func (o *getServiceAccountOptions) run(out io.Writer, args []string) error { | ||
| url, err := url.JoinPath(global.Host, "api/v2/service-accounts", global.Org, args[0]) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| reqParams := &requests.RequestParams{ | ||
| Method: http.MethodGet, | ||
| URL: url, | ||
| Token: global.ApiToken, | ||
| } | ||
| response, err := kosliClient.Do(reqParams) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| return output.FormattedPrint(response.Body, o.output, out, 0, | ||
| map[string]output.FormatOutputFunc{ | ||
| "table": printServiceAccountAsTable, | ||
| "json": output.PrintJson, | ||
| }) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.