-
Notifications
You must be signed in to change notification settings - Fork 937
/
Copy pathauth.go
2189 lines (1744 loc) · 54.5 KB
/
auth.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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/url"
"os"
"sort"
"strings"
"github.com/google/uuid"
"github.com/spf13/cobra"
"gopkg.in/yaml.v2"
"github.com/canonical/lxd/client"
"github.com/canonical/lxd/shared"
"github.com/canonical/lxd/shared/api"
cli "github.com/canonical/lxd/shared/cmd"
"github.com/canonical/lxd/shared/entity"
"github.com/canonical/lxd/shared/i18n"
"github.com/canonical/lxd/shared/termios"
"github.com/canonical/lxd/shared/version"
)
type cmdAuth struct {
global *cmdGlobal
}
func (c *cmdAuth) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("auth")
cmd.Short = i18n.G("Manage user authorization")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Manage user authorization`))
groupCmd := cmdGroup{global: c.global}
cmd.AddCommand(groupCmd.command())
permissionCmd := cmdPermission{global: c.global}
cmd.AddCommand(permissionCmd.command())
identityCmd := cmdIdentity{global: c.global}
cmd.AddCommand(identityCmd.command())
identityProviderGroupCmd := cmdIdentityProviderGroup{global: c.global}
cmd.AddCommand(identityProviderGroupCmd.command())
// Workaround for subcommand usage errors. See: https://github.com/spf13/cobra/issues/706
cmd.Args = cobra.NoArgs
cmd.Run = func(cmd *cobra.Command, args []string) { _ = cmd.Usage() }
return cmd
}
type cmdGroup struct {
global *cmdGlobal
}
func (c *cmdGroup) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("group")
cmd.Short = i18n.G("Manage groups")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Manage groups`))
groupCreateCmd := cmdGroupCreate{global: c.global}
cmd.AddCommand(groupCreateCmd.command())
groupDeleteCmd := cmdGroupDelete{global: c.global}
cmd.AddCommand(groupDeleteCmd.command())
groupEditCmd := cmdGroupEdit{global: c.global}
cmd.AddCommand(groupEditCmd.command())
groupShowCmd := cmdGroupShow{global: c.global}
cmd.AddCommand(groupShowCmd.command())
groupListCmd := cmdGroupList{global: c.global}
cmd.AddCommand(groupListCmd.command())
groupRenameCmd := cmdGroupRename{global: c.global}
cmd.AddCommand(groupRenameCmd.command())
permissionCmd := cmdGroupPermission{global: c.global}
cmd.AddCommand(permissionCmd.command())
// Workaround for subcommand usage errors. See: https://github.com/spf13/cobra/issues/706
cmd.Args = cobra.NoArgs
cmd.Run = func(cmd *cobra.Command, args []string) { _ = cmd.Usage() }
return cmd
}
type cmdGroupCreate struct {
global *cmdGlobal
flagDescription string
}
func (c *cmdGroupCreate) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("create", i18n.G("[<remote>:]<group>"))
cmd.Short = i18n.G("Create groups")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Create groups`))
cmd.Flags().StringVarP(&c.flagDescription, "description", "d", "", "Group description")
cmd.RunE = c.run
return cmd
}
func (c *cmdGroupCreate) run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 1, 1)
if exit {
return err
}
// Parse remote
resources, err := c.global.ParseServers(args[0])
if err != nil {
return err
}
resource := resources[0]
if resource.name == "" {
return errors.New(i18n.G("Missing group name"))
}
// Create the group
group := api.AuthGroupsPost{}
group.Name = resource.name
group.Description = c.flagDescription
err = resource.server.CreateAuthGroup(group)
if err != nil {
return err
}
if !c.global.flagQuiet {
fmt.Printf(i18n.G("Group %s created")+"\n", resource.name)
}
return nil
}
// Delete.
type cmdGroupDelete struct {
global *cmdGlobal
}
func (c *cmdGroupDelete) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("delete", i18n.G("[<remote>:]<group>"))
cmd.Aliases = []string{"rm"}
cmd.Short = i18n.G("Delete groups")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Delete groups`))
cmd.RunE = c.run
return cmd
}
func (c *cmdGroupDelete) run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 1, 1)
if exit {
return err
}
// Parse remote
resources, err := c.global.ParseServers(args[0])
if err != nil {
return err
}
resource := resources[0]
if resource.name == "" {
return errors.New(i18n.G("Missing group name"))
}
// Delete the group
err = resource.server.DeleteAuthGroup(resource.name)
if err != nil {
return err
}
if !c.global.flagQuiet {
fmt.Printf(i18n.G("Group %s deleted")+"\n", resource.name)
}
return nil
}
// Edit.
type cmdGroupEdit struct {
global *cmdGlobal
}
func (c *cmdGroupEdit) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("edit", i18n.G("[<remote>:]<group>"))
cmd.Short = i18n.G("Edit groups as YAML")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Edit groups as YAML`))
cmd.Example = cli.FormatSection("", i18n.G(
`lxc auth group edit <group> < group.yaml
Update a group using the content of group.yaml`))
cmd.RunE = c.run
return cmd
}
func (c *cmdGroupEdit) helpTemplate() string {
return i18n.G(
`### This is a YAML representation of the group.
### Any line starting with a '# will be ignored.
###
### NOTE: All group information is shown but only the description and permissions can be modified.
###
### name: my-first-group
### description: My first group.
### permissions:
### - entity_type: project
### url: /1.0/projects/default
### entitlement: can_view
### identities:
### oidc:
### - [email protected]
### tls:
### - eaa46a1b73827350e0543949fb161410c50e950d4cb9802fc58dbfbd5700e508
### identity_provider_groups:
### - sales
### - operations
`)
}
func (c *cmdGroupEdit) run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 1, 1)
if exit {
return err
}
// Parse remote
resources, err := c.global.ParseServers(args[0])
if err != nil {
return err
}
resource := resources[0]
if resource.name == "" {
return errors.New(i18n.G("Missing group name"))
}
// If stdin isn't a terminal, read text from it
if !termios.IsTerminal(getStdinFd()) {
contents, err := io.ReadAll(os.Stdin)
if err != nil {
return err
}
newdata := api.AuthGroupPut{}
err = yaml.Unmarshal(contents, &newdata)
if err != nil {
return err
}
return resource.server.UpdateAuthGroup(resource.name, newdata, "")
}
// Extract the current value
group, etag, err := resource.server.GetAuthGroup(resource.name)
if err != nil {
return err
}
data, err := yaml.Marshal(&group)
if err != nil {
return err
}
// Spawn the editor
content, err := shared.TextEditor("", []byte(c.helpTemplate()+"\n\n"+string(data)))
if err != nil {
return err
}
for {
// Parse the text received from the editor
newdata := api.AuthGroupPut{}
err = yaml.Unmarshal(content, &newdata)
if err == nil {
err = resource.server.UpdateAuthGroup(resource.name, newdata, etag)
}
// Respawn the editor
if err != nil {
fmt.Fprintf(os.Stderr, i18n.G("Could not parse group: %s")+"\n", err)
fmt.Println(i18n.G("Press enter to open the editor again or ctrl+c to abort change"))
_, err := os.Stdin.Read(make([]byte, 1))
if err != nil {
return err
}
content, err = shared.TextEditor("", content)
if err != nil {
return err
}
continue
}
break
}
return nil
}
type cmdGroupList struct {
global *cmdGlobal
flagFormat string
}
func (c *cmdGroupList) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("list", i18n.G("[<remote>:]"))
cmd.Aliases = []string{"ls"}
cmd.Short = i18n.G("List groups")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`List groups`))
cmd.RunE = c.run
cmd.Flags().StringVarP(&c.flagFormat, "format", "f", "table", i18n.G("Format (csv|json|table|yaml|compact)")+"``")
return cmd
}
func (c *cmdGroupList) run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 0, 1)
if exit {
return err
}
// Parse remote
remote := ""
if len(args) > 0 {
remote = args[0]
}
resources, err := c.global.ParseServers(remote)
if err != nil {
return err
}
resource := resources[0]
// List groups
groups, err := resource.server.GetAuthGroups()
if err != nil {
return err
}
data := [][]string{}
for _, group := range groups {
data = append(data, []string{group.Name, group.Description})
}
sort.Sort(cli.SortColumnsNaturally(data))
header := []string{
i18n.G("NAME"),
i18n.G("DESCRIPTION"),
}
return cli.RenderTable(c.flagFormat, header, data, groups)
}
// Rename.
type cmdGroupRename struct {
global *cmdGlobal
}
func (c *cmdGroupRename) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("rename", i18n.G("[<remote>:]<group> <new_name>"))
cmd.Aliases = []string{"mv"}
cmd.Short = i18n.G("Rename groups")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Rename groups`))
cmd.RunE = c.run
return cmd
}
func (c *cmdGroupRename) run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 2, 2)
if exit {
return err
}
// Parse remote
resources, err := c.global.ParseServers(args[0])
if err != nil {
return err
}
resource := resources[0]
if resource.name == "" {
return errors.New(i18n.G("Missing group name"))
}
// Rename the group
err = resource.server.RenameAuthGroup(resource.name, api.AuthGroupPost{Name: args[1]})
if err != nil {
return err
}
if !c.global.flagQuiet {
fmt.Printf(i18n.G("Group %s renamed to %s")+"\n", resource.name, args[1])
}
return nil
}
// Show.
type cmdGroupShow struct {
global *cmdGlobal
}
func (c *cmdGroupShow) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("show", i18n.G("[<remote>:]<group>"))
cmd.Short = i18n.G("Show group configurations")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Show group configurations`))
cmd.RunE = c.run
return cmd
}
func (c *cmdGroupShow) run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 1, 1)
if exit {
return err
}
// Parse remote
resources, err := c.global.ParseServers(args[0])
if err != nil {
return err
}
resource := resources[0]
if resource.name == "" {
return errors.New(i18n.G("Missing group name"))
}
// Show the group
group, _, err := resource.server.GetAuthGroup(resource.name)
if err != nil {
return err
}
data, err := yaml.Marshal(&group)
if err != nil {
return err
}
fmt.Printf("%s", data)
return nil
}
type cmdGroupPermission struct {
global *cmdGlobal
}
func (c *cmdGroupPermission) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("permission")
cmd.Aliases = []string{"perm"}
cmd.Short = i18n.G("Manage permissions")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Manage permissions`))
groupCreateCmd := cmdGroupPermissionAdd{global: c.global}
cmd.AddCommand(groupCreateCmd.command())
groupDeleteCmd := cmdGroupPermissionRemove{global: c.global}
cmd.AddCommand(groupDeleteCmd.command())
// Workaround for subcommand usage errors. See: https://github.com/spf13/cobra/issues/706
cmd.Args = cobra.NoArgs
cmd.Run = func(cmd *cobra.Command, args []string) { _ = cmd.Usage() }
return cmd
}
type cmdGroupPermissionAdd struct {
global *cmdGlobal
}
func (c *cmdGroupPermissionAdd) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("add", i18n.G("[<remote>:]<group> <entity_type> [<entity_name>] <entitlement> [<key>=<value>...]"))
cmd.Short = i18n.G("Add permissions to groups")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Add permissions to groups`))
cmd.RunE = c.run
return cmd
}
func (c *cmdGroupPermissionAdd) run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 3, -1)
if exit {
return err
}
// Parse remote
resources, err := c.global.ParseServers(args[0])
if err != nil {
return err
}
resource := resources[0]
if resource.name == "" {
return errors.New(i18n.G("Missing group name"))
}
group, eTag, err := resource.server.GetAuthGroup(resource.name)
if err != nil {
return err
}
permission, err := parsePermissionArgs(args)
if err != nil {
return err
}
added := false
if !shared.ValueInSlice(*permission, group.Permissions) {
group.Permissions = append(group.Permissions, *permission)
added = true
}
if !added {
return fmt.Errorf("Group %q already has entitlement %q on entity %q", resource.name, permission.Entitlement, permission.EntityReference)
}
return resource.server.UpdateAuthGroup(resource.name, group.Writable(), eTag)
}
type cmdGroupPermissionRemove struct {
global *cmdGlobal
}
func (c *cmdGroupPermissionRemove) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("remove", i18n.G("[<remote>:]<group> <entity_type> [<entity_name>] <entitlement> [<key>=<value>...]"))
cmd.Aliases = []string{"rm"}
cmd.Short = i18n.G("Remove permissions from groups")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Remove permissions from groups`))
cmd.RunE = c.run
return cmd
}
func (c *cmdGroupPermissionRemove) run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 3, -1)
if exit {
return err
}
// Parse remote
resources, err := c.global.ParseServers(args[0])
if err != nil {
return err
}
resource := resources[0]
if resource.name == "" {
return errors.New(i18n.G("Missing group name"))
}
group, eTag, err := resource.server.GetAuthGroup(resource.name)
if err != nil {
return err
}
permission, err := parsePermissionArgs(args)
if err != nil {
return err
}
if len(group.Permissions) == 0 {
return fmt.Errorf("Group %q does not have any permissions", resource.name)
}
permissions := make([]api.Permission, 0, len(group.Permissions)-1)
removed := false
for _, existingPermission := range group.Permissions {
if *permission == existingPermission {
removed = true
continue
}
permissions = append(permissions, existingPermission)
}
if !removed {
return fmt.Errorf("Group %q does not have entitlement %q on entity %q", resource.name, permission.Entitlement, permission.EntityReference)
}
group.Permissions = permissions
return resource.server.UpdateAuthGroup(resource.name, group.Writable(), eTag)
}
// parsePermissionArgs parses the `<entity_type> [<entity_name>] <entitlement> [<key>=<value>...]` arguments of
// `lxc auth group permission add/remove` and returns an api.Permission that can be appended/removed from the list of
// permissions belonging to a group.
func parsePermissionArgs(args []string) (*api.Permission, error) {
entityType := entity.Type(args[1])
err := entityType.Validate()
if err != nil {
return nil, err
}
if entityType == entity.TypeServer {
if len(args) != 3 {
return nil, fmt.Errorf("Expected three arguments: `lxc auth group grant [<remote>:]<group> server <entitlement>`")
}
return &api.Permission{
EntityType: string(entityType),
EntityReference: entity.ServerURL().String(),
Entitlement: args[2],
}, nil
}
if len(args) < 4 {
return nil, fmt.Errorf("Expected at least four arguments: `lxc auth group grant [<remote>:]<group> <object_type> <object_name> <entitlement> [<key>=<value>...]`")
}
entityName := args[2]
entitlement := args[3]
kv := make(map[string]string)
if len(args) > 4 {
for _, arg := range args[4:] {
k, v, ok := strings.Cut(arg, "=")
if !ok {
return nil, fmt.Errorf("Supplementary arguments must be of the form <key>=<value>")
}
kv[k] = v
}
}
pathArgs := []string{entityName}
if entityType == entity.TypeIdentity {
authenticationMethod, identifier, ok := strings.Cut(entityName, "/")
if !ok {
return nil, fmt.Errorf("Malformed identity argument, expected `<authentication_method>/<identifier>`, got %q", entityName)
}
pathArgs = []string{authenticationMethod, identifier}
}
projectName, ok := kv["project"]
requiresProject, _ := entityType.RequiresProject()
if requiresProject && !ok {
return nil, fmt.Errorf("Entities of type %q require a supplementary project argument `project=<project_name>`", entityType)
}
if entityType == entity.TypeStorageVolume {
storageVolumeType, ok := kv["type"]
if !ok {
return nil, fmt.Errorf("Entities of type %q require a supplementary storage volume type argument `type=<storage volume type>`", entityType)
}
pathArgs = append([]string{storageVolumeType}, pathArgs...)
}
if entityType == entity.TypeStorageVolume || entityType == entity.TypeStorageBucket {
storagePool, ok := kv["pool"]
if !ok {
return nil, fmt.Errorf("Entities of type %q require a supplementary storage pool argument `pool=<pool_name>`", entityType)
}
pathArgs = append([]string{storagePool}, pathArgs...)
}
entityURL, err := entityType.URL(projectName, kv["location"], pathArgs...)
if err != nil {
return nil, err
}
return &api.Permission{
EntityType: string(entityType),
EntityReference: entityURL.String(),
Entitlement: entitlement,
}, nil
}
type cmdIdentity struct {
global *cmdGlobal
}
func (c *cmdIdentity) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("identity")
cmd.Aliases = []string{"user"}
cmd.Short = i18n.G("Manage identities")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Manage identities`))
identityCreateCmd := cmdIdentityCreate{global: c.global}
cmd.AddCommand(identityCreateCmd.command())
identityListCmd := cmdIdentityList{global: c.global}
cmd.AddCommand(identityListCmd.command())
identityShowCmd := cmdIdentityShow{global: c.global}
cmd.AddCommand(identityShowCmd.command())
identityInfoCmd := cmdIdentityInfo{global: c.global}
cmd.AddCommand(identityInfoCmd.command())
identityEditCmd := cmdIdentityEdit{global: c.global}
cmd.AddCommand(identityEditCmd.command())
identityDeleteCmd := cmdIdentityDelete{global: c.global}
cmd.AddCommand(identityDeleteCmd.command())
identityGroupCmd := cmdIdentityGroup{global: c.global}
cmd.AddCommand(identityGroupCmd.command())
// Workaround for subcommand usage errors. See: https://github.com/spf13/cobra/issues/706
cmd.Args = cobra.NoArgs
cmd.Run = func(cmd *cobra.Command, args []string) { _ = cmd.Usage() }
return cmd
}
type cmdIdentityCreate struct {
global *cmdGlobal
flagGroups []string
}
func (c *cmdIdentityCreate) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("create", i18n.G("[<remote>:]<authentication_method>/<name> [<path to PEM encoded certificate>] [[--group <group_name>]]"))
cmd.Short = i18n.G("Create an identity")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Create a TLS identity`))
cmd.RunE = c.run
cmd.Flags().StringSliceVarP(&c.flagGroups, "group", "g", []string{}, "Groups to add to the identity")
return cmd
}
func (c *cmdIdentityCreate) run(cmd *cobra.Command, args []string) error {
var stdinData api.IdentitiesTLSPost
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 1, 2)
if exit {
return err
}
// If stdin isn't a terminal, read text from it
if !termios.IsTerminal(getStdinFd()) {
contents, err := io.ReadAll(os.Stdin)
if err != nil {
return err
}
err = yaml.Unmarshal(contents, &stdinData)
if err != nil {
return err
}
}
// Parse remote
remoteName, resourceName, err := c.global.conf.ParseRemote(args[0])
if err != nil {
return err
}
transporter, wrapper := newLocationHeaderTransportWrapper()
client, err := c.global.conf.GetInstanceServerWithTransportWrapper(remoteName, wrapper)
if err != nil {
return err
}
if resourceName == "" {
return errors.New(i18n.G("Missing identity argument"))
}
authMethod, name, ok := strings.Cut(resourceName, "/")
if !ok {
return errors.New(i18n.G("Malformed argument, expected `[<remote>:]<authentication_method>/<name>`, got ") + args[0])
}
if authMethod != api.AuthenticationMethodTLS {
return errors.New(i18n.G("Identity creation only supported for TLS identities"))
}
// Add name and groups to any stdin data
stdinData.Name = name
for _, group := range c.flagGroups {
if !shared.ValueInSlice(group, stdinData.Groups) {
stdinData.Groups = append(stdinData.Groups, group)
}
}
// If the certificate argument is provided, read it and add it to the stdin data.
if len(args) == 2 {
pemEncodedX509Cert, err := os.ReadFile(args[1])
if err != nil {
return err
}
stdinData.Certificate = string(pemEncodedX509Cert)
}
// Expect that if the caller did not provide a certificate then they want to get a token.
if stdinData.Certificate == "" {
stdinData.Token = true
token, err := client.CreateIdentityTLSToken(stdinData)
if err != nil {
return err
}
if !c.global.flagQuiet {
pendingIdentityURL, err := url.Parse(transporter.location)
if err != nil {
return fmt.Errorf("Received invalid location header %q: %w", transporter.location, err)
}
var pendingIdentityUUIDStr string
identityURLPrefix := api.NewURL().Path(version.APIVersion, "auth", "identities", authMethod).String()
_, err = fmt.Sscanf(pendingIdentityURL.Path, identityURLPrefix+"/%s", &pendingIdentityUUIDStr)
if err != nil {
return fmt.Errorf("Received unexpected location header %q: %w", transporter.location, err)
}
pendingIdentityUUID, err := uuid.Parse(pendingIdentityUUIDStr)
if err != nil {
return fmt.Errorf("Received invalid pending identity UUID %q: %w", pendingIdentityUUIDStr, err)
}
fmt.Printf(i18n.G("TLS identity %q (%s) pending identity token:")+"\n", resourceName, pendingIdentityUUID.String())
}
// Encode certificate add token to JSON.
tokenJSON, err := json.Marshal(token)
if err != nil {
return fmt.Errorf("Failed to encode identity token: %w", err)
}
// Print the base64 encoded token.
fmt.Println(base64.StdEncoding.EncodeToString(tokenJSON))
return nil
}
fingerprint, err := shared.CertFingerprintStr(stdinData.Certificate)
if err != nil {
return err
}
// Otherwise create the identity directly.
err = client.CreateIdentityTLS(stdinData)
if err != nil {
return err
}
if !c.global.flagQuiet {
fmt.Printf(i18n.G("TLS identity %q created with fingerprint %q")+"\n", resourceName, fingerprint)
}
return nil
}
type cmdIdentityList struct {
global *cmdGlobal
flagFormat string
}
func (c *cmdIdentityList) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("list", i18n.G("[<remote>:]"))
cmd.Aliases = []string{"ls"}
cmd.Short = i18n.G("List identities")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`List identities`))
cmd.RunE = c.run
cmd.Flags().StringVarP(&c.flagFormat, "format", "f", "table", i18n.G("Format (csv|json|table|yaml|compact)")+"``")
return cmd
}
func (c *cmdIdentityList) run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 0, 1)
if exit {
return err
}
// Parse remote
remote := ""
if len(args) > 0 {
remote = args[0]
}
resources, err := c.global.ParseServers(remote)
if err != nil {
return err
}
resource := resources[0]
// List identities
identities, err := resource.server.GetIdentities()
if err != nil {
return err
}
data := [][]string{}
delimiter := "\n"
if c.flagFormat == cli.TableFormatCSV {
delimiter = ","
}
for _, identity := range identities {
data = append(data, []string{identity.AuthenticationMethod, identity.Type, identity.Name, identity.Identifier, strings.Join(identity.Groups, delimiter)})
}
sort.Sort(cli.SortColumnsNaturally(data))
header := []string{
i18n.G("AUTHENTICATION METHOD"),
i18n.G("TYPE"),
i18n.G("NAME"),
i18n.G("IDENTIFIER"),
i18n.G("GROUPS"),
}
return cli.RenderTable(c.flagFormat, header, data, identities)
}
// Show.
type cmdIdentityShow struct {
global *cmdGlobal
}
func (c *cmdIdentityShow) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("show", i18n.G("[<remote>:]<authentication_method>/<name_or_identifier>"))
cmd.Short = i18n.G("View an identity")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Show identity configurations
The argument must be a concatenation of the authentication method and either the
name or identifier of the identity, delimited by a forward slash. This command
will fail if an identity name is used that is not unique within the authentication
method. Use the identifier instead if this occurs.
`))
cmd.RunE = c.run
return cmd
}
func (c *cmdIdentityShow) run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 1, 1)
if exit {