-
Notifications
You must be signed in to change notification settings - Fork 7
feat: add service-account api-keys commands #938
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
7
commits into
main
Choose a base branch
from
20260606_feat_api_keys
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
7 commits
Select commit
Hold shift + click to select a range
4aa6ce0
feat: add service-account api-keys commands
mbevc1 90c8f8e
fix: enforce new keys feature and address feedback
mbevc1 bf048c5
fix: be moreo verbose about partial revocation failures
mbevc1 e83ac79
fix: remove erorr colouring, use logger consistently and remove hard-…
mbevc1 151b470
chore: remove unnecessary comments
mbevc1 98ee4a1
chore: print which keys were revoked
mbevc1 19b4e79
chore: consistent erorr handling when rotating keys
mbevc1 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
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,113 @@ | ||
| 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 createApiKeyShortDesc = `Create an API key for a service account.` | ||
|
|
||
| const createApiKeyLongDesc = createApiKeyShortDesc + ` | ||
|
|
||
| The key value is only returned once, at creation time, so make sure to store it securely.` | ||
|
|
||
| const createApiKeyExample = ` | ||
| # create an API key for a service account: | ||
| kosli service-account api-keys create \ | ||
| --service-account yourServiceAccountName \ | ||
| --description "key for CI" \ | ||
| --api-token yourAPIToken \ | ||
| --org yourOrgName | ||
|
|
||
| # create an API key that expires on a given date: | ||
| kosli service-account api-keys create \ | ||
| --service-account yourServiceAccountName \ | ||
| --description "key for CI" \ | ||
| --expires-at 2026-12-31 \ | ||
| --api-token yourAPIToken \ | ||
| --org yourOrgName | ||
| ` | ||
|
|
||
| type createApiKeyOptions struct { | ||
| serviceAccount string | ||
| expiresAt string | ||
| output string | ||
| payload createApiKeyPayload | ||
| } | ||
|
|
||
| type createApiKeyPayload struct { | ||
| Description string `json:"description"` | ||
| ExpiresAt *int64 `json:"expires_at,omitempty"` | ||
| } | ||
|
|
||
| func newCreateApiKeyCmd(out io.Writer) *cobra.Command { | ||
| o := new(createApiKeyOptions) | ||
| cmd := &cobra.Command{ | ||
| Use: "create", | ||
| Aliases: []string{"c", "cr"}, | ||
| Short: createApiKeyShortDesc, | ||
| Long: createApiKeyLongDesc, | ||
| Example: createApiKeyExample, | ||
| Args: cobra.NoArgs, | ||
| 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.serviceAccount, "service-account", "s", "", serviceAccountNameFlag) | ||
| cmd.Flags().StringVarP(&o.payload.Description, "description", "d", "", apiKeyDescriptionFlag) | ||
| cmd.Flags().StringVarP(&o.expiresAt, "expires-at", "e", "", apiKeyExpiresAtFlag) | ||
| cmd.Flags().StringVarP(&o.output, "output", "o", "table", outputFlag) | ||
| addDryRunFlag(cmd) | ||
|
|
||
| err := RequireFlags(cmd, []string{"service-account", "description"}) | ||
| if err != nil { | ||
| logger.Error("failed to configure required flags: %v", err) | ||
| } | ||
|
|
||
| return cmd | ||
| } | ||
|
|
||
| func (o *createApiKeyOptions) run(out io.Writer, args []string) error { | ||
| url, err := url.JoinPath(global.Host, "api/v2/service-accounts", global.Org, o.serviceAccount, "api-keys") | ||
|
mbevc1 marked this conversation as resolved.
|
||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| if o.expiresAt != "" { | ||
| expiresAt, err := parseExpiresAt(o.expiresAt) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| o.payload.ExpiresAt = &expiresAt | ||
| } | ||
|
|
||
| reqParams := &requests.RequestParams{ | ||
| Method: http.MethodPost, | ||
| URL: url, | ||
| Payload: o.payload, | ||
| DryRun: global.DryRun, | ||
| Token: global.ApiToken, | ||
| } | ||
| response, err := kosliClient.Do(reqParams) | ||
| if err != nil || global.DryRun { | ||
| return err | ||
| } | ||
|
|
||
| return output.FormattedPrint(response.Body, o.output, out, 0, | ||
| map[string]output.FormatOutputFunc{ | ||
| "table": printApiKeyAsTable, | ||
| "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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,121 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "encoding/json" | ||
| "fmt" | ||
| "io" | ||
| "net/http" | ||
| "net/url" | ||
|
|
||
| "github.com/kosli-dev/cli/internal/output" | ||
| "github.com/kosli-dev/cli/internal/requests" | ||
| "github.com/spf13/cobra" | ||
| ) | ||
|
|
||
| const listApiKeysShortDesc = `List API keys for a service account.` | ||
|
|
||
| const listApiKeysLongDesc = listApiKeysShortDesc + ` | ||
|
|
||
| Only the metadata of each active API key is returned; the key values themselves are never | ||
| listed (they are only shown once, at creation or rotation time).` | ||
|
|
||
| const listApiKeysExample = ` | ||
| # list the API keys for a service account: | ||
| kosli service-account api-keys list \ | ||
| --service-account yourServiceAccountName \ | ||
| --api-token yourAPIToken \ | ||
| --org yourOrgName | ||
| ` | ||
|
|
||
| type listApiKeysOptions struct { | ||
| serviceAccount string | ||
| output string | ||
| } | ||
|
|
||
| func newListApiKeysCmd(out io.Writer) *cobra.Command { | ||
| o := new(listApiKeysOptions) | ||
| cmd := &cobra.Command{ | ||
| Use: "list", | ||
| Aliases: []string{"l", "ls"}, | ||
| Short: listApiKeysShortDesc, | ||
| Long: listApiKeysLongDesc, | ||
| Example: listApiKeysExample, | ||
| Args: cobra.NoArgs, | ||
| 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.serviceAccount, "service-account", "s", "", serviceAccountNameFlag) | ||
| cmd.Flags().StringVarP(&o.output, "output", "o", "table", outputFlag) | ||
|
|
||
| err := RequireFlags(cmd, []string{"service-account"}) | ||
| if err != nil { | ||
| logger.Error("failed to configure required flags: %v", err) | ||
| } | ||
|
|
||
| return cmd | ||
| } | ||
|
|
||
| func (o *listApiKeysOptions) run(out io.Writer, args []string) error { | ||
| url, err := url.JoinPath(global.Host, "api/v2/service-accounts", global.Org, o.serviceAccount, "api-keys") | ||
|
mbevc1 marked this conversation as resolved.
|
||
| 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": printApiKeysListAsTable, | ||
| "json": output.PrintJson, | ||
| }) | ||
| } | ||
|
|
||
| func printApiKeysListAsTable(raw string, out io.Writer, page int) error { | ||
|
mbevc1 marked this conversation as resolved.
|
||
| var keys []map[string]interface{} | ||
| if err := json.Unmarshal([]byte(raw), &keys); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| if len(keys) == 0 { | ||
| logger.Info("No API keys were found.") | ||
| return nil | ||
| } | ||
|
|
||
| header := []string{"ID", "DESCRIPTION", "CREATED", "EXPIRES", "LAST USED"} | ||
| rows := []string{} | ||
| for _, key := range keys { | ||
| createdAt, err := formattedTimestamp(key["created_at"], false) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| expiresAt, err := optionalTimestamp(key["expires_at"]) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| lastUsedAt, err := optionalTimestamp(key["last_used_at"]) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
|
mbevc1 marked this conversation as resolved.
|
||
| row := fmt.Sprintf("%s\t%s\t%s\t%s\t%s", key["id"], key["description"], createdAt, expiresAt, lastUsedAt) | ||
| rows = append(rows, row) | ||
| } | ||
| tabFormattedPrint(out, header, rows) | ||
| return nil | ||
| } | ||
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.