/
instances.go
1146 lines (1066 loc) · 34.7 KB
/
instances.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 cmd
import (
"bufio"
"bytes"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"reflect"
"strings"
"text/tabwriter"
"time"
"github.com/cozy/cozy-stack/client"
"github.com/cozy/cozy-stack/client/request"
build "github.com/cozy/cozy-stack/pkg/config"
"github.com/cozy/cozy-stack/pkg/consts"
"github.com/cozy/cozy-stack/pkg/couchdb"
humanize "github.com/dustin/go-humanize"
"github.com/spf13/cobra"
)
var flagDomainAliases []string
var flagListFields []string
var flagLocale string
var flagTimezone string
var flagEmail string
var flagPublicName string
var flagSettings string
var flagDiskQuota string
var flagApps []string
var flagBlocked bool
var flagBlockingReason string
var flagDeleting bool
var flagDev bool
var flagTrace bool
var flagPassphrase string
var flagForce bool
var flagJSON bool
var flagSwiftLayout int
var flagCouchCluster int
var flagUUID string
var flagOIDCID string
var flagFranceConnectID string
var flagMagicLink bool
var flagTOSSigned string
var flagTOS string
var flagTOSLatest string
var flagContextName string
var flagSponsorships []string
var flagOnboardingFinished bool
var flagTTL time.Duration
var flagExpire time.Duration
var flagAllowLoginScope bool
var flagAvailableFields bool
var flagOnboardingSecret string
var flagOnboardingApp string
var flagOnboardingPermissions string
var flagOnboardingState string
var flagPath string
// instanceCmdGroup represents the instances command
var instanceCmdGroup = &cobra.Command{
Use: "instances <command>",
Aliases: []string{"instance"},
Short: "Manage instances of a stack",
Long: `
cozy-stack instances allows to manage the instances of this stack
An instance is a logical space owned by one user and identified by a domain.
For example, bob.cozycloud.cc is the instance of Bob. A single cozy-stack
process can manage several instances.
Each instance has a separate space for storing files and a prefix used to
create its CouchDB databases.
`,
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Usage()
},
}
var showInstanceCmd = &cobra.Command{
Use: "show <domain>",
Short: "Show the instance of the specified domain",
Long: `
cozy-stack instances show allows to show the instance on the cozy for a
given domain.
`,
Example: "$ cozy-stack instances show cozy.localhost:8080",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return cmd.Usage()
}
domain := args[0]
ac := newAdminClient()
in, err := ac.GetInstance(domain)
if err != nil {
return err
}
json, err := json.MarshalIndent(in, "", " ")
if err != nil {
return err
}
fmt.Println(string(json))
return nil
},
}
var showDBPrefixInstanceCmd = &cobra.Command{
Use: "show-db-prefix <domain>",
Short: "Show the instance DB prefix of the specified domain",
Long: `
cozy-stack instances show allows to show the instance prefix on the cozy for a
given domain. The prefix is used for databases and VFS prefixing.
It will also show the couch_cluster if it is not the default one.
`,
Example: "$ cozy-stack instances show-db-prefix cozy.localhost:8080",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return cmd.Usage()
}
domain := args[0]
ac := newAdminClient()
in, err := ac.GetInstance(domain)
if err != nil {
return err
}
if in.Attrs.Prefix != "" {
fmt.Println(in.Attrs.Prefix)
} else {
fmt.Println(couchdb.EscapeCouchdbName(in.Attrs.Domain))
}
if in.Attrs.CouchCluster != 0 {
fmt.Fprintf(os.Stdout, "couch_cluster: %d\n", in.Attrs.CouchCluster)
}
return nil
},
}
var addInstanceCmd = &cobra.Command{
Use: "add <domain>",
Aliases: []string{"create"},
Short: "Manage instances of a stack",
Long: `
cozy-stack instances add allows to create an instance on the cozy for a
given domain.
If the COZY_DISABLE_INSTANCES_ADD_RM env variable is set, creating and
destroying instances will be disabled and the content of this variable will
be used as the error message.
`,
Example: "$ cozy-stack instances add --passphrase cozy --apps drive,photos,settings,home,store cozy.localhost:8080",
RunE: func(cmd *cobra.Command, args []string) error {
if reason := os.Getenv("COZY_DISABLE_INSTANCES_ADD_RM"); reason != "" {
return fmt.Errorf("Sorry, instances add is disabled: %s", reason)
}
if len(args) == 0 {
return cmd.Usage()
}
if flagDev {
errPrintfln("The --dev flag has been deprecated")
}
var diskQuota int64
if flagDiskQuota != "" {
diskQuotaU, err := humanize.ParseBytes(flagDiskQuota)
if err != nil {
return err
}
diskQuota = int64(diskQuotaU)
}
domain := args[0]
fmt.Fprintf(os.Stdout, "Creating instance for domain \"%s\": please wait...\n", domain)
ac := newAdminClient()
in, err := ac.CreateInstance(&client.InstanceOptions{
Domain: domain,
DomainAliases: flagDomainAliases,
Locale: flagLocale,
UUID: flagUUID,
OIDCID: flagOIDCID,
FranceConnectID: flagFranceConnectID,
TOSSigned: flagTOSSigned,
Timezone: flagTimezone,
ContextName: flagContextName,
Sponsorships: flagSponsorships,
Email: flagEmail,
PublicName: flagPublicName,
Settings: flagSettings,
SwiftLayout: flagSwiftLayout,
CouchCluster: flagCouchCluster,
DiskQuota: diskQuota,
Apps: flagApps,
Passphrase: flagPassphrase,
MagicLink: &flagMagicLink,
Trace: &flagTrace,
})
if err != nil {
errPrintfln(
"Failed to create instance for domain %s", domain)
return err
}
fmt.Fprintf(os.Stdout, "Instance created with success for domain %s\n", in.Attrs.Domain)
myProtocol := "https"
if build.IsDevRelease() {
myProtocol = "http"
}
if in.Attrs.RegisterToken != nil {
fmt.Fprintf(os.Stdout, "Registration token: \"%s\"\n", hex.EncodeToString(in.Attrs.RegisterToken))
fmt.Fprintf(os.Stdout, "Define your password by visiting %s://%s/?registerToken=%s\n", myProtocol, in.Attrs.Domain, hex.EncodeToString(in.Attrs.RegisterToken))
}
if len(flagApps) == 0 {
return nil
}
c, err := ac.NewInstanceClient(domain, consts.Apps)
if err != nil {
errPrintfln("Could not generate access to domain %s", domain)
errPrintfln("%s", err)
os.Exit(1)
}
apps, err := c.ListApps(consts.Apps)
if err == nil && len(flagApps) != len(apps) {
for _, slug := range flagApps {
found := false
for _, app := range apps {
if app.Attrs.Slug == slug {
found = true
break
}
}
if !found {
fmt.Fprintf(os.Stdout, "/!\\ Application %s has not been installed\n", slug)
}
}
}
return nil
},
}
var modifyInstanceCmd = &cobra.Command{
Use: "modify <domain>",
Short: "Modify the instance properties",
Long: `
cozy-stack instances modify allows to change the instance properties and
settings for a specified domain.
`,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return cmd.Usage()
}
var diskQuota int64
if flagDiskQuota != "" {
diskQuotaU, err := humanize.ParseBytes(flagDiskQuota)
if err != nil {
return err
}
diskQuota = int64(diskQuotaU)
}
domain := args[0]
ac := newAdminClient()
opts := &client.InstanceOptions{
Domain: domain,
DomainAliases: flagDomainAliases,
Locale: flagLocale,
UUID: flagUUID,
OIDCID: flagOIDCID,
FranceConnectID: flagFranceConnectID,
TOSSigned: flagTOS,
TOSLatest: flagTOSLatest,
Timezone: flagTimezone,
ContextName: flagContextName,
Sponsorships: flagSponsorships,
Email: flagEmail,
PublicName: flagPublicName,
Settings: flagSettings,
BlockingReason: flagBlockingReason,
DiskQuota: diskQuota,
MagicLink: &flagMagicLink,
}
if flag := cmd.Flag("blocked"); flag.Changed {
opts.Blocked = &flagBlocked
}
if flag := cmd.Flag("deleting"); flag.Changed {
opts.Deleting = &flagDeleting
}
if flagOnboardingFinished {
opts.OnboardingFinished = &flagOnboardingFinished
}
in, err := ac.ModifyInstance(opts)
if err != nil {
errPrintfln(
"Failed to modify instance for domain %s", domain)
return err
}
json, err := json.MarshalIndent(in, "", " ")
if err != nil {
return err
}
fmt.Println(string(json))
return nil
},
}
var updateInstancePassphraseCmd = &cobra.Command{
Use: "set-passphrase <domain> <new-passphrase>",
Short: "Change the passphrase of the instance",
Example: "$ cozy-stack instances set-passphrase cozy.localhost:8080 myN3wP4ssowrd!",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 2 {
return cmd.Usage()
}
domain := args[0]
c := newClient(domain, consts.Settings)
body := struct {
New string `json:"new_passphrase"`
Force bool `json:"force"`
}{
New: args[1],
Force: true,
}
reqBody, err := json.Marshal(body)
if err != nil {
return err
}
res, err := c.Req(&request.Options{
Method: "PUT",
Path: "/settings/passphrase",
Body: bytes.NewReader(reqBody),
Headers: request.Headers{
"Content-Type": "application/json",
},
})
if err != nil {
return err
}
switch res.StatusCode {
case http.StatusNoContent:
fmt.Println("Passphrase has been changed for instance ", domain)
case http.StatusBadRequest:
return fmt.Errorf("Bad current passphrase for instance %s", domain)
case http.StatusInternalServerError:
return fmt.Errorf("%s", err)
}
return nil
},
}
var quotaInstanceCmd = &cobra.Command{
Use: "set-disk-quota <domain> <disk-quota>",
Short: "Change the disk-quota of the instance",
Long: `
cozy-stack instances set-disk-quota allows to change the disk-quota of the
instance of the given domain. Set the quota to 0 to remove the quota.
`,
Example: "$ cozy-stack instances set-disk-quota cozy.localhost:8080 3GB",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 2 {
return cmd.Usage()
}
parsed, err := humanize.ParseBytes(args[1])
if err != nil {
return fmt.Errorf("Could not parse disk-quota: %s", err)
}
diskQuota := int64(parsed)
if diskQuota == 0 {
diskQuota = -1
}
domain := args[0]
ac := newAdminClient()
_, err = ac.ModifyInstance(&client.InstanceOptions{
Domain: domain,
DiskQuota: diskQuota,
})
return err
},
}
var debugInstanceCmd = &cobra.Command{
Use: "debug <true/false>",
Short: "Activate or deactivate debugging of the instance",
Long: `
cozy-stack instances debug allows to activate or deactivate the debugging of a
specific domain.
`,
Example: "$ cozy-stack instances debug --domain cozy.localhost:8080 true",
RunE: func(cmd *cobra.Command, args []string) error {
action := "enable"
domain := flagDomain
switch len(args) {
case 0:
action = "get"
case 1:
if strings.ToLower(args[0]) == "false" {
action = "disable"
}
case 2:
deprecatedDomainArg()
domain = args[0]
if strings.ToLower(args[1]) == "false" {
action = "disable"
}
default:
action = ""
}
if action == "" || domain == "" {
return cmd.Usage()
}
ac := newAdminClient()
var err error
var debug bool
switch action {
case "get":
debug, err = ac.GetDebug(domain)
case "enable":
err = ac.EnableDebug(domain, flagTTL)
debug = true
case "disable":
err = ac.DisableDebug(domain)
debug = false
}
if debug {
fmt.Fprintf(os.Stdout, "Debug is enabled on %s\n", domain)
} else {
fmt.Fprintf(os.Stdout, "Debug is disabled on %s\n", domain)
}
return err
},
}
var countInstanceCmd = &cobra.Command{
Use: "count",
Short: "Count the instances",
Example: "$ cozy-stack instances count",
RunE: func(cmd *cobra.Command, args []string) error {
ac := newAdminClient()
count, err := ac.CountInstances()
if err != nil {
return err
}
if count == 1 {
fmt.Fprintf(os.Stdout, "%d instance\n", count)
} else {
fmt.Fprintf(os.Stdout, "%d instances\n", count)
}
return nil
},
}
var lsInstanceCmd = &cobra.Command{
Use: "ls",
Aliases: []string{"list"},
Short: "List instances",
Long: `
cozy-stack instances ls allows to list all the instances that can be served
by this server.
`,
Example: "$ cozy-stack instances ls",
RunE: func(cmd *cobra.Command, args []string) error {
if flagAvailableFields {
instance := &client.Instance{}
val := reflect.ValueOf(instance.Attrs)
t := val.Type()
for i := 0; i < t.NumField(); i++ {
param := t.Field(i).Tag.Get("json")
param = strings.TrimSuffix(param, ",omitempty")
param = strings.TrimSuffix(param, ",string")
fmt.Println(param)
}
fmt.Println("db_prefix")
return nil
}
ac := newAdminClient()
list, err := ac.ListInstances()
if err != nil {
return err
}
if flagJSON {
if len(flagListFields) > 0 {
for _, inst := range list {
var values map[string]interface{}
values, err = extractFields(inst.Attrs, flagListFields)
if err != nil {
return err
}
// Insert the db_prefix value if needed
for _, v := range flagListFields {
if v == "db_prefix" {
values["db_prefix"] = couchdb.EscapeCouchdbName(inst.DBPrefix())
}
}
m := make(map[string]interface{}, len(flagListFields))
for _, fieldName := range flagListFields {
if v, ok := values[fieldName]; ok {
m[fieldName] = v
} else {
m[fieldName] = nil
}
}
if err = json.NewEncoder(os.Stdout).Encode(m); err != nil {
return err
}
}
} else {
for _, inst := range list {
if err = json.NewEncoder(os.Stdout).Encode(inst.Attrs); err != nil {
return err
}
}
}
} else {
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
if len(flagListFields) > 0 {
format := strings.Repeat("%v\t", len(flagListFields))
format = format[:len(format)-1] + "\n"
for _, inst := range list {
var values map[string]interface{}
var instancesLines []interface{}
values, err = extractFields(inst.Attrs, flagListFields)
if err != nil {
return err
}
// Insert the db_prefix value if needed
for _, v := range flagListFields {
if v == "db_prefix" {
values["db_prefix"] = couchdb.EscapeCouchdbName(inst.DBPrefix())
}
}
// We append to a list to print in the same order as
// requested
for _, fieldName := range flagListFields {
instancesLines = append(instancesLines, values[fieldName])
}
fmt.Fprintf(w, format, instancesLines...)
}
} else {
for _, i := range list {
prefix := i.Attrs.Prefix
DBPrefix := prefix
if prefix == "" {
DBPrefix = couchdb.EscapeCouchdbName(i.Attrs.Domain)
}
fmt.Fprintf(w, "%s\t%s\t%s\t%s\tv%d\t%s\t%s\n",
i.Attrs.Domain,
i.Attrs.Locale,
formatSize(i.Attrs.BytesDiskQuota),
formatOnboarded(i),
i.Attrs.IndexViewsVersion,
prefix,
DBPrefix,
)
}
}
w.Flush()
}
return nil
},
}
func extractFields(data interface{}, fieldsNames []string) (values map[string]interface{}, err error) {
var m map[string]interface{}
var b []byte
b, err = json.Marshal(data)
if err != nil {
return
}
if err = json.Unmarshal(b, &m); err != nil {
return
}
values = make(map[string]interface{}, len(fieldsNames))
for _, fieldName := range fieldsNames {
if v, ok := m[fieldName]; ok {
values[fieldName] = v
}
}
return
}
func formatSize(size int64) string {
if size == 0 {
return "unlimited"
}
return humanize.Bytes(uint64(size))
}
func formatOnboarded(i *client.Instance) string {
if i.Attrs.OnboardingFinished {
return "onboarded"
}
if len(i.Attrs.RegisterToken) > 0 {
return "onboarding"
}
return "pending"
}
var destroyInstanceCmd = &cobra.Command{
Use: "destroy <domain>",
Short: "Remove instance",
Long: `
cozy-stack instances destroy allows to remove an instance
and all its data.
`,
Aliases: []string{"rm", "delete", "remove"},
RunE: func(cmd *cobra.Command, args []string) error {
if reason := os.Getenv("COZY_DISABLE_INSTANCES_ADD_RM"); reason != "" {
return fmt.Errorf("Sorry, instances add is disabled: %s", reason)
}
if len(args) == 0 {
return cmd.Usage()
}
domain := args[0]
if !flagForce {
if err := confirmDomain("remove", domain); err != nil {
return err
}
}
ac := newAdminClient()
err := ac.DestroyInstance(domain)
if err != nil {
errPrintfln(
"An error occurred while destroying instance for domain %s", domain)
return err
}
fmt.Fprintf(os.Stdout, "Instance for domain %s has been destroyed with success\n", domain)
return nil
},
}
func confirmDomain(action, domain string) error {
reader := bufio.NewReader(os.Stdin)
fmt.Fprintf(os.Stdout, `Are you sure you want to %s instance for domain %s?
All data associated with this domain will be permanently lost.
Type again the domain to confirm: `, action, domain)
str, err := reader.ReadString('\n')
if err != nil {
return err
}
str = strings.ToLower(strings.TrimSpace(str))
if str != domain {
return errors.New("Aborted")
}
fmt.Println()
return nil
}
var fsckInstanceCmd = &cobra.Command{
Use: "fsck <domain>",
Short: "Check a vfs",
Long: `
The cozy-stack fsck command checks that the files in the VFS are not
desynchronized, ie a file present in CouchDB but not swift/localfs, or present
in swift/localfs but not couchdb.
There are 2 steps:
- index integrity checks that there are nothing wrong in the index (CouchDB),
like a file present in a directory that has been deleted
- files consistency checks that the files are the same in the index (CouchDB)
and the storage (Swift or localfs).
By default, both operations are done, but you can choose one or the other via
the flags.
`,
RunE: func(cmd *cobra.Command, args []string) error {
errPrintfln("Please use cozy-stack check fs, this command has been deprecated")
if len(args) == 0 {
return cmd.Usage()
}
return fsck(args[0])
},
}
func appOrKonnectorTokenInstance(cmd *cobra.Command, args []string, appType string) error {
if len(args) < 2 {
return cmd.Usage()
}
ac := newAdminClient()
token, err := ac.GetToken(&client.TokenOptions{
Domain: args[0],
Subject: args[1],
Audience: appType,
Expire: &flagExpire,
})
if err != nil {
return err
}
_, err = fmt.Println(token)
return err
}
var appTokenInstanceCmd = &cobra.Command{
Use: "token-app <domain> <slug>",
Short: "Generate a new application token",
RunE: func(cmd *cobra.Command, args []string) error {
return appOrKonnectorTokenInstance(cmd, args, "app")
},
}
var konnectorTokenInstanceCmd = &cobra.Command{
Use: "token-konnector <domain> <slug>",
Short: "Generate a new konnector token",
RunE: func(cmd *cobra.Command, args []string) error {
return appOrKonnectorTokenInstance(cmd, args, "konn")
},
}
var cliTokenInstanceCmd = &cobra.Command{
Use: "token-cli <domain> <scopes>",
Short: "Generate a new CLI access token (global access)",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) < 2 {
return cmd.Usage()
}
ac := newAdminClient()
token, err := ac.GetToken(&client.TokenOptions{
Domain: args[0],
Scope: args[1:],
Audience: consts.CLIAudience,
})
if err != nil {
return err
}
_, err = fmt.Println(token)
return err
},
}
var oauthTokenInstanceCmd = &cobra.Command{
Use: "token-oauth <domain> <clientid> <scopes>",
Short: "Generate a new OAuth access token",
Example: "$ cozy-stack instances token-oauth cozy.localhost:8080 727e677187a51d14ccd59cc0bd000a1d io.cozy.files io.cozy.jobs:POST:sendmail:worker",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) < 3 {
return cmd.Usage()
}
if args[1] == "" {
return errors.New("Missing clientID")
}
if strings.Contains(args[2], ",") {
fmt.Fprintf(os.Stderr, "Warning: the delimiter for the scopes is a space!\n")
}
ac := newAdminClient()
token, err := ac.GetToken(&client.TokenOptions{
Domain: args[0],
Subject: args[1],
Audience: consts.AccessTokenAudience,
Scope: args[2:],
Expire: &flagExpire,
})
if err != nil {
return err
}
_, err = fmt.Println(token)
return err
},
}
var oauthRefreshTokenInstanceCmd = &cobra.Command{
Use: "refresh-token-oauth <domain> <clientid> <scopes>",
Short: "Generate a new OAuth refresh token",
Example: "$ cozy-stack instances refresh-token-oauth cozy.localhost:8080 727e677187a51d14ccd59cc0bd000a1d io.cozy.files io.cozy.jobs:POST:sendmail:worker",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) < 3 {
return cmd.Usage()
}
if strings.Contains(args[2], ",") {
fmt.Fprintf(os.Stderr, "Warning: the delimiter for the scopes is a space!\n")
}
ac := newAdminClient()
token, err := ac.GetToken(&client.TokenOptions{
Domain: args[0],
Subject: args[1],
Audience: consts.RefreshTokenAudience,
Scope: args[2:],
})
if err != nil {
return err
}
_, err = fmt.Println(token)
return err
},
}
var oauthClientInstanceCmd = &cobra.Command{
Use: "client-oauth <domain> <redirect_uri> <client_name> <software_id>",
Short: "Register a new OAuth client",
Long: `It registers a new OAuth client and returns its client_id`,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) < 4 {
return cmd.Usage()
}
ac := newAdminClient()
oauthClient, err := ac.RegisterOAuthClient(&client.OAuthClientOptions{
Domain: args[0],
RedirectURI: args[1],
ClientName: args[2],
SoftwareID: args[3],
AllowLoginScope: flagAllowLoginScope,
OnboardingSecret: flagOnboardingSecret,
OnboardingApp: flagOnboardingApp,
OnboardingPermissions: flagOnboardingPermissions,
OnboardingState: flagOnboardingState,
})
if err != nil {
return err
}
if flagJSON {
encoder := json.NewEncoder(os.Stdout)
encoder.SetIndent("", "\t")
err = encoder.Encode(oauthClient)
} else {
_, err = fmt.Println(oauthClient["client_id"])
}
return err
},
}
var findOauthClientCmd = &cobra.Command{
Use: "find-oauth-client <domain> <software_id>",
Short: "Find an OAuth client",
Long: `Search an OAuth client from its SoftwareID`,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) < 2 {
return cmd.Usage()
}
var v interface{}
ac := newAdminClient()
q := url.Values{
"domain": {args[0]},
"software_id": {args[1]},
}
req := &request.Options{
Method: "GET",
Path: "instances/oauth_client",
Queries: q,
}
res, err := ac.Req(req)
if err != nil {
return err
}
errd := json.NewDecoder(res.Body).Decode(&v)
if err != nil {
return errd
}
json, err := json.MarshalIndent(v, "", " ")
if err != nil {
return err
}
fmt.Println(string(json))
return err
},
}
var exportCmd = &cobra.Command{
Use: "export",
Short: "Export an instance",
Long: `Export the files, documents, and settings`,
RunE: func(cmd *cobra.Command, args []string) error {
ac := newAdminClient()
return ac.Export(&client.ExportOptions{
Domain: flagDomain,
LocalPath: flagPath,
})
},
}
var importCmd = &cobra.Command{
Use: "import <URL>",
Short: "Import data from an export link",
Long: "This command will reset the Cozy instance and import data from an export link",
RunE: func(cmd *cobra.Command, args []string) error {
ac := newAdminClient()
if len(args) < 1 {
return errors.New("The URL to the exported data is missing")
}
if !flagForce {
if err := confirmDomain("reset", flagDomain); err != nil {
return err
}
}
return ac.Import(flagDomain, &client.ImportOptions{
ManifestURL: args[0],
})
},
}
var showSwiftPrefixInstanceCmd = &cobra.Command{
Use: "show-swift-prefix <domain>",
Short: "Show the instance swift prefix of the specified domain",
Example: "$ cozy-stack instances show-swift-prefix cozy.localhost:8080",
RunE: func(cmd *cobra.Command, args []string) error {
var v map[string]string
ac := newAdminClient()
if len(args) < 1 {
return errors.New("The domain is missing")
}
req := &request.Options{
Method: "GET",
Path: "instances/" + args[0] + "/swift-prefix",
}
res, err := ac.Req(req)
if err != nil {
return err
}
errd := json.NewDecoder(res.Body).Decode(&v)
if errd != nil {
return errd
}
json, errj := json.MarshalIndent(v, "", " ")
if errj != nil {
return errj
}
fmt.Println(string(json))
return nil
},
}
var instanceAppVersionCmd = &cobra.Command{
Use: "show-app-version [app-slug] [version]",
Short: `Show instances that have a particular app version`,
Example: "$ cozy-stack instances show-app-version drive 1.0.1",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 2 {
return cmd.Usage()
}
ac := newAdminClient()
path := fmt.Sprintf("/instances/with-app-version/%s/%s", args[0], args[1])
res, err := ac.Req(&request.Options{
Method: "GET",
Path: path,
})
if err != nil {
return err
}
out := struct {
Instances []string `json:"instances"`
}{}
err = json.NewDecoder(res.Body).Decode(&out)
if err != nil {
return err
}
if len(out.Instances) == 0 {
return fmt.Errorf("No instances have application \"%s\" in version \"%s\"", args[0], args[1])
}
json, err := json.MarshalIndent(out.Instances, "", " ")
if err != nil {
return err
}
fmt.Println(string(json))
return nil
},
}
var setAuthModeCmd = &cobra.Command{
Use: "auth-mode [domain] [auth-mode]",
Short: `Set instance auth-mode`,
Example: "$ cozy-stack instances auth-mode cozy.localhost:8080 two_factor_mail",
Long: `Change the authentication mode for an instance. Two options are allowed:
- two_factor_mail
- basic
`,
RunE: func(cmd *cobra.Command, args []string) error {