-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathapi_keys.go
More file actions
392 lines (334 loc) · 10.1 KB
/
Copy pathapi_keys.go
File metadata and controls
392 lines (334 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
package cmd
import (
"context"
"fmt"
"github.com/kernel/cli/pkg/util"
"github.com/kernel/kernel-go-sdk"
"github.com/kernel/kernel-go-sdk/option"
"github.com/kernel/kernel-go-sdk/packages/pagination"
"github.com/pterm/pterm"
"github.com/spf13/cobra"
)
type APIKeysService interface {
New(ctx context.Context, body kernel.APIKeyNewParams, opts ...option.RequestOption) (*kernel.CreatedAPIKey, error)
Get(ctx context.Context, id string, query kernel.APIKeyGetParams, opts ...option.RequestOption) (*kernel.APIKey, error)
Update(ctx context.Context, id string, body kernel.APIKeyUpdateParams, opts ...option.RequestOption) (*kernel.APIKey, error)
List(ctx context.Context, query kernel.APIKeyListParams, opts ...option.RequestOption) (*pagination.OffsetPagination[kernel.APIKey], error)
Delete(ctx context.Context, id string, opts ...option.RequestOption) error
}
type APIKeysCmd struct {
apiKeys APIKeysService
}
type APIKeysCreateInput struct {
Name string
DaysToExpire Int64Flag
ProjectID string
Output string
}
type APIKeysListInput struct {
Limit int
Offset int
Output string
}
type APIKeysGetInput struct {
ID string
Output string
}
type APIKeysUpdateInput struct {
ID string
Name string
Output string
}
type APIKeysDeleteInput struct {
ID string
SkipConfirm bool
}
func (c APIKeysCmd) Create(ctx context.Context, in APIKeysCreateInput) error {
if err := validateJSONOutput(in.Output); err != nil {
return err
}
if in.Name == "" {
return fmt.Errorf("--name is required")
}
params := kernel.APIKeyNewParams{Name: in.Name}
if in.DaysToExpire.Set {
if in.DaysToExpire.Value < 1 || in.DaysToExpire.Value > 3650 {
return fmt.Errorf("--days-to-expire must be between 1 and 3650")
}
params.DaysToExpire = kernel.Int(in.DaysToExpire.Value)
}
if in.ProjectID != "" {
params.ProjectID = kernel.String(in.ProjectID)
}
key, err := c.apiKeys.New(ctx, params)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if in.Output == "json" {
return util.PrintPrettyJSON(key)
}
pterm.Success.Printf("Created API key: %s\n", key.ID)
renderCreatedAPIKey(key)
return nil
}
func (c APIKeysCmd) List(ctx context.Context, in APIKeysListInput) error {
if err := validateJSONOutput(in.Output); err != nil {
return err
}
if in.Limit < 0 {
return fmt.Errorf("--limit must be non-negative")
}
if in.Offset < 0 {
return fmt.Errorf("--offset must be non-negative")
}
params := kernel.APIKeyListParams{}
if in.Limit > 0 {
params.Limit = kernel.Int(int64(in.Limit))
}
if in.Offset > 0 {
params.Offset = kernel.Int(int64(in.Offset))
}
page, err := c.apiKeys.List(ctx, params)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
var keys []kernel.APIKey
if page != nil {
keys = page.Items
}
if in.Output == "json" {
return util.PrintPrettyJSONSlice(keys)
}
if len(keys) == 0 {
pterm.Info.Println("No API keys found")
return nil
}
table := pterm.TableData{{"ID", "Name", "Scope", "Project", "Masked Key", "Expires At", "Created At"}}
for _, key := range keys {
table = append(table, []string{
key.ID,
key.Name,
formatAPIKeyScope(key),
formatAPIKeyProject(key),
key.MaskedKey,
formatAPIKeyExpiresAt(key),
util.FormatLocal(key.CreatedAt),
})
}
PrintTableNoPad(table, true)
return nil
}
func (c APIKeysCmd) Get(ctx context.Context, in APIKeysGetInput) error {
if err := validateJSONOutput(in.Output); err != nil {
return err
}
key, err := c.apiKeys.Get(ctx, in.ID, kernel.APIKeyGetParams{})
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if in.Output == "json" {
return util.PrintPrettyJSON(key)
}
renderAPIKeyDetails(key)
return nil
}
func (c APIKeysCmd) Update(ctx context.Context, in APIKeysUpdateInput) error {
if err := validateJSONOutput(in.Output); err != nil {
return err
}
if in.Name == "" {
return fmt.Errorf("--name is required")
}
key, err := c.apiKeys.Update(ctx, in.ID, kernel.APIKeyUpdateParams{Name: in.Name})
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if in.Output == "json" {
return util.PrintPrettyJSON(key)
}
pterm.Success.Printf("Updated API key: %s\n", key.ID)
return nil
}
func (c APIKeysCmd) Delete(ctx context.Context, in APIKeysDeleteInput) error {
if !in.SkipConfirm {
msg := fmt.Sprintf("Are you sure you want to delete API key '%s'?", in.ID)
pterm.DefaultInteractiveConfirm.DefaultText = msg
ok, _ := pterm.DefaultInteractiveConfirm.Show()
if !ok {
pterm.Info.Println("Deletion cancelled")
return nil
}
}
if err := c.apiKeys.Delete(ctx, in.ID); err != nil {
if util.IsNotFound(err) {
return fmt.Errorf("API key %q not found", in.ID)
}
return util.CleanedUpSdkError{Err: err}
}
pterm.Success.Printf("Deleted API key: %s\n", in.ID)
return nil
}
func renderCreatedAPIKey(key *kernel.CreatedAPIKey) {
rows := pterm.TableData{
{"Field", "Value"},
{"ID", key.ID},
{"Name", key.Name},
{"Key", key.Key},
{"Scope", formatAPIKeyScope(key.APIKey)},
{"Project", formatAPIKeyProject(key.APIKey)},
{"Masked Key", key.MaskedKey},
{"Expires At", formatAPIKeyExpiresAt(key.APIKey)},
}
PrintTableNoPad(rows, true)
}
func renderAPIKeyDetails(key *kernel.APIKey) {
rows := pterm.TableData{
{"Field", "Value"},
{"ID", key.ID},
{"Name", key.Name},
{"Scope", formatAPIKeyScope(*key)},
{"Project", formatAPIKeyProject(*key)},
{"Masked Key", key.MaskedKey},
{"Created By", formatAPIKeyCreator(*key)},
{"Expires At", formatAPIKeyExpiresAt(*key)},
{"Created At", util.FormatLocal(key.CreatedAt)},
}
PrintTableNoPad(rows, true)
}
func formatAPIKeyProject(key kernel.APIKey) string {
if key.JSON.ProjectName.Valid() && key.ProjectName != "" {
return key.ProjectName
}
if key.JSON.ProjectID.Valid() && key.ProjectID != "" {
return key.ProjectID
}
return "-"
}
func formatAPIKeyScope(key kernel.APIKey) string {
if key.JSON.ProjectID.Valid() && key.ProjectID != "" {
return "Project"
}
return "Org"
}
func formatAPIKeyCreator(key kernel.APIKey) string {
if key.CreatedBy.JSON.Name.Valid() && key.CreatedBy.Name != "" {
return key.CreatedBy.Name
}
if key.CreatedBy.JSON.Email.Valid() && key.CreatedBy.Email != "" {
return key.CreatedBy.Email
}
return "-"
}
func formatAPIKeyExpiresAt(key kernel.APIKey) string {
if !key.JSON.ExpiresAt.Valid() {
return "Never"
}
return util.FormatLocal(key.ExpiresAt)
}
func getAPIKeysHandler(cmd *cobra.Command) APIKeysCmd {
client := getKernelClient(cmd)
return APIKeysCmd{apiKeys: &client.APIKeys}
}
func runAPIKeysCreate(cmd *cobra.Command, args []string) error {
c := getAPIKeysHandler(cmd)
name, _ := cmd.Flags().GetString("name")
daysToExpire, _ := cmd.Flags().GetInt64("days-to-expire")
projectID, _ := cmd.Flags().GetString("project-id")
output, _ := cmd.Flags().GetString("output")
return c.Create(cmd.Context(), APIKeysCreateInput{
Name: name,
DaysToExpire: Int64Flag{
Set: cmd.Flags().Changed("days-to-expire"),
Value: daysToExpire,
},
ProjectID: projectID,
Output: output,
})
}
func runAPIKeysList(cmd *cobra.Command, args []string) error {
c := getAPIKeysHandler(cmd)
limit, _ := cmd.Flags().GetInt("limit")
offset, _ := cmd.Flags().GetInt("offset")
output, _ := cmd.Flags().GetString("output")
return c.List(cmd.Context(), APIKeysListInput{
Limit: limit,
Offset: offset,
Output: output,
})
}
func runAPIKeysGet(cmd *cobra.Command, args []string) error {
c := getAPIKeysHandler(cmd)
output, _ := cmd.Flags().GetString("output")
return c.Get(cmd.Context(), APIKeysGetInput{ID: args[0], Output: output})
}
func runAPIKeysUpdate(cmd *cobra.Command, args []string) error {
c := getAPIKeysHandler(cmd)
name, _ := cmd.Flags().GetString("name")
output, _ := cmd.Flags().GetString("output")
return c.Update(cmd.Context(), APIKeysUpdateInput{ID: args[0], Name: name, Output: output})
}
func runAPIKeysDelete(cmd *cobra.Command, args []string) error {
c := getAPIKeysHandler(cmd)
skip, _ := cmd.Flags().GetBool("yes")
return c.Delete(cmd.Context(), APIKeysDeleteInput{ID: args[0], SkipConfirm: skip})
}
var apiKeysCmd = &cobra.Command{
Use: "api-keys",
Aliases: []string{"api-key", "apikeys", "apikey"},
Short: "Manage API keys",
Run: func(cmd *cobra.Command, args []string) {
_ = cmd.Help()
},
}
var apiKeysCreateCmd = &cobra.Command{
Use: "create",
Short: "Create an API key",
Long: "Create an API key.\n\nBy default the new key is org-wide. Use --project-id to create a key whose own access is scoped to that project. The global --project flag only scopes this CLI request.",
Args: cobra.NoArgs,
RunE: runAPIKeysCreate,
}
var apiKeysListCmd = &cobra.Command{
Use: "list",
Short: "List API keys",
Args: cobra.NoArgs,
RunE: runAPIKeysList,
}
var apiKeysGetCmd = &cobra.Command{
Use: "get <id>",
Short: "Get an API key",
Args: cobra.ExactArgs(1),
RunE: runAPIKeysGet,
}
var apiKeysUpdateCmd = &cobra.Command{
Use: "update <id>",
Short: "Update an API key",
Args: cobra.ExactArgs(1),
RunE: runAPIKeysUpdate,
}
var apiKeysDeleteCmd = &cobra.Command{
Use: "delete <id>",
Short: "Delete an API key",
Args: cobra.ExactArgs(1),
RunE: runAPIKeysDelete,
}
func init() {
addJSONOutputFlag(apiKeysCreateCmd)
apiKeysCreateCmd.Flags().String("name", "", "API key name (required)")
apiKeysCreateCmd.Flags().Int64("days-to-expire", 0, "Number of days until expiry (1-3650); omit for never")
apiKeysCreateCmd.Flags().String("project-id", "", "Create a project-scoped API key for this project ID; omit for org-wide")
_ = apiKeysCreateCmd.MarkFlagRequired("name")
addJSONOutputFlag(apiKeysListCmd)
apiKeysListCmd.Flags().Int("limit", 0, "Maximum number of results to return")
apiKeysListCmd.Flags().Int("offset", 0, "Number of results to skip")
addJSONOutputFlag(apiKeysGetCmd)
addJSONOutputFlag(apiKeysUpdateCmd)
apiKeysUpdateCmd.Flags().String("name", "", "New API key name (required)")
_ = apiKeysUpdateCmd.MarkFlagRequired("name")
apiKeysDeleteCmd.Flags().BoolP("yes", "y", false, "Skip confirmation prompt")
apiKeysCmd.AddCommand(apiKeysCreateCmd)
apiKeysCmd.AddCommand(apiKeysListCmd)
apiKeysCmd.AddCommand(apiKeysGetCmd)
apiKeysCmd.AddCommand(apiKeysUpdateCmd)
apiKeysCmd.AddCommand(apiKeysDeleteCmd)
rootCmd.AddCommand(apiKeysCmd)
}