-
Notifications
You must be signed in to change notification settings - Fork 218
/
create.go
669 lines (559 loc) · 16 KB
/
create.go
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
package tokens
import (
"context"
"errors"
"fmt"
"time"
"github.com/superfly/flyctl/gql"
"github.com/superfly/flyctl/internal/appconfig"
"github.com/superfly/flyctl/internal/command/orgs"
"github.com/superfly/flyctl/internal/config"
"github.com/superfly/flyctl/internal/flyutil"
"github.com/superfly/flyctl/internal/render"
"github.com/superfly/flyctl/iostreams"
"github.com/superfly/macaroon"
"github.com/superfly/macaroon/flyio"
"github.com/superfly/macaroon/resset"
"github.com/google/shlex"
"github.com/spf13/cobra"
"github.com/superfly/flyctl/internal/command"
"github.com/superfly/flyctl/internal/flag"
)
func newCreate() *cobra.Command {
const (
short = "Create Fly.io API tokens"
long = "Create Fly.io API tokens"
usage = "create"
)
cmd := command.New(usage, short, long, nil)
cmd.AddCommand(
newDeploy(),
newMachineExec(),
newOrg(),
newOrgRead(),
newLiteFSCloud(),
newSSH(),
)
return cmd
}
func newOrg() *cobra.Command {
const (
short = "Create org deploy tokens"
long = "Create an API token limited to managing a single org and its resources. Tokens are valid for 20 years by default. We recommend using a shorter expiry if practical."
usage = "org"
)
cmd := command.New(usage, short, long, runOrg,
command.RequireSession,
)
flag.Add(cmd,
flag.JSONOutput(),
flag.Duration{
Name: "expiry",
Shorthand: "x",
Description: "The duration that the token will be valid",
Default: time.Hour * 24 * 365 * 20,
},
flag.String{
Name: "name",
Shorthand: "n",
Description: "Token name",
Default: "Org deploy token",
},
flag.Org(),
)
return cmd
}
func newSSH() *cobra.Command {
const (
short = "Create token for SSH'ing to a single app"
long = "Create token for SSH'ing to a single app. To be able to SSH to an app, this token is also allowed to connect to the org's wireguard network."
usage = "ssh"
)
cmd := command.New(usage, short, long, runSSH,
command.RequireSession,
command.LoadAppNameIfPresent,
)
flag.Add(cmd,
flag.App(),
flag.AppConfig(),
flag.JSONOutput(),
flag.String{
Name: "name",
Shorthand: "n",
Description: "Token name",
Default: "flyctl ssh token",
},
flag.Duration{
Name: "expiry",
Shorthand: "x",
Description: "The duration that the token will be valid",
Default: time.Hour * 24 * 365 * 20,
},
)
return cmd
}
func newOrgRead() *cobra.Command {
const (
short = "Create read-only org tokens"
long = "Create an API token limited to reading a single org and its resources. Tokens are valid for 20 years by default. We recommend using a shorter expiry if practical."
usage = "readonly"
)
cmd := command.New(usage, short, long, runOrgRead,
command.RequireSession,
)
flag.Add(cmd,
flag.JSONOutput(),
flag.Bool{
Name: "from-existing",
Description: "Use an existing token as the basis for the read-only token",
},
flag.Duration{
Name: "expiry",
Shorthand: "x",
Description: "The duration that the token will be valid",
Default: time.Hour * 24 * 365 * 20,
},
flag.String{
Name: "name",
Shorthand: "n",
Description: "Token name",
Default: "Read-only org token",
},
)
return cmd
}
func newDeploy() *cobra.Command {
const (
short = "Create deploy tokens"
long = "Create an API token limited to managing a single app and its resources. Also available as TOKENS DEPLOY. Tokens are valid for 20 years by default. We recommend using a shorter expiry if practical."
usage = "deploy"
)
cmd := command.New(usage, short, long, runDeploy,
command.RequireSession,
command.LoadAppNameIfPresent,
)
flag.Add(cmd,
flag.App(),
flag.AppConfig(),
flag.JSONOutput(),
flag.String{
Name: "name",
Shorthand: "n",
Description: "Token name",
Default: "flyctl deploy token",
},
flag.Duration{
Name: "expiry",
Shorthand: "x",
Description: "The duration that the token will be valid",
Default: time.Hour * 24 * 365 * 20,
},
)
return cmd
}
func newLiteFSCloud() *cobra.Command {
const (
short = "Create LiteFS Cloud tokens"
long = "Create an API token limited to a single LiteFS Cloud cluster."
usage = "litefs-cloud"
)
cmd := command.New(usage, short, long, runLiteFSCloud,
command.RequireSession,
)
flag.Add(cmd,
flag.JSONOutput(),
flag.Org(),
flag.String{
Name: "name",
Shorthand: "n",
Description: "Token name",
Default: "LiteFS Cloud token",
},
flag.Duration{
Name: "expiry",
Shorthand: "x",
Description: "The duration that the token will be valid",
Default: time.Hour * 24 * 365 * 20,
},
flag.String{
Name: "cluster",
Shorthand: "c",
Description: "Cluster name",
},
)
return cmd
}
func newMachineExec() *cobra.Command {
const (
short = "Create a machine exec token"
long = "Create an API token that can execute a restricted set of commands on a machine. Commands can be specified on the command line or with the command and command-prefix flags. If no command is provided, all commands are allowed. Tokens are valid for 20 years by default. We recommend using a shorter expiry if practical."
usage = "machine-exec [command...]"
)
cmd := command.New(usage, short, long, runMachineExec,
command.RequireSession,
command.LoadAppNameIfPresent,
)
flag.Add(cmd,
flag.App(),
flag.AppConfig(),
flag.JSONOutput(),
flag.String{
Name: "name",
Shorthand: "n",
Description: "Token name",
Default: "flyctl machine-exec token",
},
flag.Duration{
Name: "expiry",
Shorthand: "x",
Description: "The duration that the token will be valid",
Default: time.Hour * 24 * 365 * 20,
},
flag.StringSlice{
Name: "command",
Shorthand: "C",
Description: "An allowed command with arguments. This command must match exactly",
},
flag.StringSlice{
Name: "command-prefix",
Shorthand: "p",
Description: "An allowed command with arguments. This command must match the prefix of a command",
},
)
return cmd
}
func makeToken(ctx context.Context, apiClient flyutil.Client, orgID string, expiry string, profile string, options *gql.LimitedAccessTokenOptions) (*gql.CreateLimitedAccessTokenResponse, error) {
resp, err := gql.CreateLimitedAccessToken(
ctx,
apiClient.GenqClient(),
flag.GetString(ctx, "name"),
orgID,
profile,
options,
expiry,
)
if err != nil {
return nil, fmt.Errorf("failed creating token: %w", err)
}
return resp, nil
}
func runOrg(ctx context.Context) error {
var token string
apiClient := flyutil.ClientFromContext(ctx)
expiry := ""
if expiryDuration := flag.GetDuration(ctx, "expiry"); expiryDuration != 0 {
expiry = expiryDuration.String()
}
org, err := orgs.OrgFromEnvVarOrFirstArgOrSelect(ctx)
if err != nil {
return fmt.Errorf("failed retrieving org %w", err)
}
resp, err := makeToken(ctx, apiClient, org.ID, expiry, "deploy_organization", &gql.LimitedAccessTokenOptions{})
if err != nil {
return err
}
token = resp.CreateLimitedAccessToken.LimitedAccessToken.TokenHeader
io := iostreams.FromContext(ctx)
if config.FromContext(ctx).JSONOutput {
render.JSON(io.Out, map[string]string{"token": token})
} else {
fmt.Fprintln(io.Out, token)
}
return nil
}
func runSSH(ctx context.Context) error {
var token string
apiClient := flyutil.ClientFromContext(ctx)
expiry := ""
if expiryDuration := flag.GetDuration(ctx, "expiry"); expiryDuration != 0 {
expiry = expiryDuration.String()
}
appName := appconfig.NameFromContext(ctx)
app, err := apiClient.GetAppCompact(ctx, appName)
if err != nil {
return fmt.Errorf("failed retrieving app %s: %w", appName, err)
}
// start with app deploy token and then pare it down.
resp, err := makeToken(ctx, apiClient, app.Organization.ID, expiry, "deploy", &gql.LimitedAccessTokenOptions{
"app_id": app.ID,
})
if err != nil {
return err
}
token = resp.CreateLimitedAccessToken.LimitedAccessToken.TokenHeader
macTok, disToks, err := flyio.ParsePermissionAndDischargeTokens(token)
if err != nil {
return fmt.Errorf("failed parsing token from API: %w", err)
}
// FindPermissionAndDischargeTokens returned parsed tokens, but we want to
// make two copies of the token and there's no API for doing a deep copy of
// a Macaroon.
orgAppReadMac, err := macaroon.Decode(macTok)
if err != nil {
return fmt.Errorf("failed decoding tokens from API: %w", err)
}
if err := orgAppReadMac.Add(ptr(resset.ActionRead)); err != nil {
return fmt.Errorf("failed to attenuate org-app-read token: %w", err)
}
orgAppReadTok, err := orgAppReadMac.Encode()
if err != nil {
return fmt.Errorf("failed encoding org-app-read token: %w", err)
}
mutationMac, err := macaroon.Decode(macTok)
if err != nil {
return fmt.Errorf("failed decoding tokens from API: %w", err)
}
if err := mutationMac.Add(&flyio.Mutations{Mutations: []string{"issueCertificate", "addWireGuardPeer"}}); err != nil {
return fmt.Errorf("failed to attenuate mutation token: %w", err)
}
mutationTok, err := mutationMac.Encode()
if err != nil {
return fmt.Errorf("failed encoding mutation token: %w", err)
}
token = macaroon.ToAuthorizationHeader(append([][]byte{orgAppReadTok, mutationTok}, disToks...)...)
io := iostreams.FromContext(ctx)
if config.FromContext(ctx).JSONOutput {
render.JSON(io.Out, map[string]string{"token": token})
} else {
fmt.Fprintln(io.Out, token)
}
return nil
}
func runOrgRead(ctx context.Context) error {
var (
token string
apiClient = flyutil.ClientFromContext(ctx)
expiry = ""
expiryDuration = flag.GetDuration(ctx, "expiry")
perm []byte
diss [][]byte
)
if expiryDuration != 0 {
expiry = expiryDuration.String()
}
if !flag.GetBool(ctx, "from-existing") {
org, err := orgs.OrgFromEnvVarOrFirstArgOrSelect(ctx)
if err != nil {
return fmt.Errorf("failed retrieving org %w", err)
}
resp, err := makeToken(ctx, apiClient, org.ID, expiry, "deploy_organization", &gql.LimitedAccessTokenOptions{})
if err != nil {
return err
}
token = resp.CreateLimitedAccessToken.LimitedAccessToken.TokenHeader
perm, diss, err = macaroon.ParsePermissionAndDischargeTokens(token, flyio.LocationPermission)
if err != nil {
return err
}
} else { /* see also below: we add expiry explicitly if this branch is taken */
toks, err := getTokens(ctx)
if err != nil {
return err
}
var perms [][]byte
_, perms, _, diss, err = macaroon.FindPermissionAndDischargeTokens(toks, flyio.LocationPermission)
if err != nil {
return err
}
if len(perms) > 1 {
return fmt.Errorf("the currently set token string has more than one permission token in it, can't proceed")
}
perm = perms[0]
}
mac, err := macaroon.Decode(perm)
if err != nil {
return err
}
// attenuate to read-only
var orgID *uint64
for _, cav := range macaroon.GetCaveats[*flyio.Organization](&mac.UnsafeCaveats) {
if orgID != nil {
return errors.New("multiple org caveats")
}
orgID = &cav.ID
}
if orgID == nil {
return errors.New("no org caveats")
}
if err := mac.Add(&flyio.Organization{ID: *orgID, Mask: resset.ActionRead}); err != nil {
return err
}
if expiryDuration != 0 && flag.GetBool(ctx, "from-existing") {
if err := mac.Add(&macaroon.ValidityWindow{
NotBefore: time.Now().Unix(),
NotAfter: time.Now().Add(expiryDuration).Unix(),
}); err != nil {
return err
}
}
if perm, err = mac.Encode(); err != nil {
return err
}
token = macaroon.ToAuthorizationHeader(append([][]byte{perm}, diss...)...)
io := iostreams.FromContext(ctx)
if config.FromContext(ctx).JSONOutput {
render.JSON(io.Out, map[string]string{"token": token})
} else {
fmt.Fprintln(io.Out, token)
}
return nil
}
func runDeploy(ctx context.Context) (err error) {
var token string
apiClient := flyutil.ClientFromContext(ctx)
expiry := ""
if expiryDuration := flag.GetDuration(ctx, "expiry"); expiryDuration != 0 {
expiry = expiryDuration.String()
}
appName := appconfig.NameFromContext(ctx)
app, err := apiClient.GetAppCompact(ctx, appName)
if err != nil {
return fmt.Errorf("failed retrieving app %s: %w", appName, err)
}
resp, err := makeToken(ctx, apiClient, app.Organization.ID, expiry, "deploy", &gql.LimitedAccessTokenOptions{
"app_id": app.ID,
})
if err != nil {
return err
}
token = resp.CreateLimitedAccessToken.LimitedAccessToken.TokenHeader
io := iostreams.FromContext(ctx)
if config.FromContext(ctx).JSONOutput {
render.JSON(io.Out, map[string]string{"token": token})
} else {
fmt.Fprintln(io.Out, token)
}
return nil
}
func runMachineExec(ctx context.Context) error {
var token string
apiClient := flyutil.ClientFromContext(ctx)
expiry := ""
if expiryDuration := flag.GetDuration(ctx, "expiry"); expiryDuration != 0 {
expiry = expiryDuration.String()
}
appName := appconfig.NameFromContext(ctx)
app, err := apiClient.GetAppCompact(ctx, appName)
if err != nil {
return fmt.Errorf("failed retrieving app %s: %w", appName, err)
}
resp, err := makeToken(ctx, apiClient, app.Organization.ID, expiry, "deploy", &gql.LimitedAccessTokenOptions{
"app_id": app.ID,
})
if err != nil {
return err
}
token = resp.CreateLimitedAccessToken.LimitedAccessToken.TokenHeader
cmdCav, err := getCommandCaveat(ctx)
if err != nil {
return err
}
token, err = attenuate(token, cmdCav)
if err != nil {
return err
}
io := iostreams.FromContext(ctx)
if config.FromContext(ctx).JSONOutput {
render.JSON(io.Out, map[string]string{"token": token})
} else {
fmt.Fprintln(io.Out, token)
}
return nil
}
func attenuate(token string, cavs ...macaroon.Caveat) (string, error) {
var atoken string
macTok, disToks, err := flyio.ParsePermissionAndDischargeTokens(token)
if err != nil {
return atoken, fmt.Errorf("failed parsing token from API: %w", err)
}
mac, err := macaroon.Decode(macTok)
if err != nil {
return atoken, err
}
if err := mac.Add(cavs...); err != nil {
return atoken, err
}
perm, err := mac.Encode()
if err != nil {
return atoken, err
}
atoken = macaroon.ToAuthorizationHeader(append([][]byte{perm}, disToks...)...)
return atoken, nil
}
func getCommandCaveat(ctx context.Context) (macaroon.Caveat, error) {
commands := flyio.Commands{}
if args := flag.Args(ctx); len(args) > 0 {
cav := flyio.Command{
Args: args,
Exact: true,
}
commands = append(commands, cav)
}
for _, cmd := range flag.GetStringSlice(ctx, "command") {
args, err := shlex.Split(cmd)
if err != nil {
return nil, fmt.Errorf("cant parse `%s`: %w", cmd, err)
}
cav := flyio.Command{
Args: args,
Exact: true,
}
commands = append(commands, cav)
}
for _, cmd := range flag.GetStringSlice(ctx, "command-prefix") {
args, err := shlex.Split(cmd)
if err != nil {
return nil, fmt.Errorf("cant parse `%s`: %w", cmd, err)
}
cav := flyio.Command{
Args: args,
Exact: false,
}
commands = append(commands, cav)
}
if len(commands) == 0 {
cav := flyio.Command{
Args: []string{},
Exact: false,
}
commands = append(commands, cav)
}
cav := &resset.IfPresent{
Ifs: macaroon.NewCaveatSet(&commands),
Else: resset.ActionRead,
}
return cav, nil
}
func runLiteFSCloud(ctx context.Context) (err error) {
var token string
apiClient := flyutil.ClientFromContext(ctx)
expiry := ""
if expiryDuration := flag.GetDuration(ctx, "expiry"); expiryDuration != 0 {
expiry = expiryDuration.String()
}
cluster := flag.GetString(ctx, "cluster")
if cluster == "" {
return fmt.Errorf("cluster name is not provided")
}
org, err := orgs.OrgFromFlagOrSelect(ctx)
if err != nil {
return fmt.Errorf("failed retrieving org %w", err)
}
resp, err := makeToken(ctx, apiClient, org.ID, expiry, "litefs_cloud", &gql.LimitedAccessTokenOptions{
"cluster": cluster,
})
if err != nil {
return err
}
token = resp.CreateLimitedAccessToken.LimitedAccessToken.TokenHeader
io := iostreams.FromContext(ctx)
if config.FromContext(ctx).JSONOutput {
render.JSON(io.Out, map[string]string{"token": token})
} else {
fmt.Fprintln(io.Out, token)
}
return nil
}
func ptr[T any](t T) *T {
return &t
}