-
Notifications
You must be signed in to change notification settings - Fork 23
/
realm_client.go
940 lines (773 loc) · 25.9 KB
/
realm_client.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
package api
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"mime"
"mime/multipart"
"net/http"
"os"
"strings"
"github.com/10gen/realm-cli/auth"
"github.com/10gen/realm-cli/hosting"
"github.com/10gen/realm-cli/models"
"github.com/10gen/realm-cli/secrets"
)
// ExportStrategy is the enumeration of possible strategies which can be used
// when exporting a realm application
type ExportStrategy string
const (
// default to the current realm config version
configVersion = "20200603"
// ExportStrategyNone will result in no extra configuration into the call to Export
ExportStrategyNone ExportStrategy = "none"
// ExportStrategyTemplate will result in the `template` querystring parameter getting added to the call to Export
ExportStrategyTemplate ExportStrategy = "template"
// ExportStrategySourceControl will result in the `source_control` querystring parameter getting added to the call to Export
ExportStrategySourceControl ExportStrategy = "source_control"
userProfileRoute = adminBaseURL + "/auth/profile"
authProviderLoginRoute = adminBaseURL + "/auth/providers/%s/login"
appsByGroupIDRoute = adminBaseURL + "/groups/%s/apps"
atlasAppsByGroupIDRoute = appsByGroupIDRoute + "?product=atlas"
appImportRoute = adminBaseURL + "/groups/%s/apps/%s/import"
appExportRoute = adminBaseURL + "/groups/%s/apps/%s/export?%s"
draftsRoute = adminBaseURL + "/groups/%s/apps/%s/drafts"
draftByIDRoute = adminBaseURL + "/groups/%s/apps/%s/drafts/%s"
deployDraftRoute = adminBaseURL + "/groups/%s/apps/%s/drafts/%s/deployment"
diffDraftRoute = adminBaseURL + "/groups/%s/apps/%s/drafts/%s/diff"
deploymentByIDRoute = adminBaseURL + "/groups/%s/apps/%s/deployments/%s"
hostingInvalidateCacheRoute = adminBaseURL + "/groups/%s/apps/%s/hosting/cache"
hostingAssetsRoute = adminBaseURL + "/groups/%s/apps/%s/hosting/assets"
hostingAssetRoute = adminBaseURL + "/groups/%s/apps/%s/hosting/assets/asset"
secretsRoute = adminBaseURL + "/groups/%s/apps/%s/secrets"
secretRoute = adminBaseURL + "/groups/%s/apps/%s/secrets/%s"
dependenciesRoute = adminBaseURL + "/groups/%s/apps/%s/dependencies"
dependenciesExportArchiveRoute = dependenciesRoute + "/archive"
)
var (
errExportMissingFilename = errors.New("the app export response did not specify a filename")
errGroupNotFound = errors.New("group could not be found")
)
const (
metadataParam = "meta"
fileParam = "file"
pathParam = "path"
)
type copyPayload struct {
CopyFrom string `json:"copy_from"`
CopyTo string `json:"copy_to"`
}
type movePayload struct {
MoveFrom string `json:"move_from"`
MoveTo string `json:"move_to"`
}
type setAttributesPayload struct {
Attributes []hosting.AssetAttribute `json:"attributes"`
}
type invalidateCachePayload struct {
Invalidate bool `json:"invalidate"`
Path string `json:"path"`
}
// RealmClient represents a Client that can be used to call the Realm Admin API
type RealmClient interface {
AddSecret(groupID, appID string, secret secrets.Secret) error
Authenticate(authProvider auth.AuthenticationProvider) (*auth.Response, error)
CopyAsset(groupID, appID, fromPath, toPath string) error
CreateDraft(groupID, appID string) (*models.AppDraft, error)
CreateEmptyApp(groupID, appName, location, deploymentModel string) (*models.App, error)
DeleteAsset(groupID, appID, path string) error
DeployDraft(groupID, appID, draftID string) (*models.Deployment, error)
Diff(groupID, appID string, appData []byte, strategy string) ([]string, error)
DiscardDraft(groupID, appID, draftID string) error
DraftDiff(groupID, appID, draftID string) (*models.DraftDiff, error)
Export(groupID, appID string, strategy ExportStrategy) (string, io.ReadCloser, error)
ExportDependencies(groupID, appID string) (string, io.ReadCloser, error)
FetchAppByClientAppID(clientAppID string) (*models.App, error)
FetchAppByGroupIDAndClientAppID(groupID, clientAppID string) (*models.App, error)
FetchAppsByGroupID(groupID string) ([]*models.App, error)
GetDeployment(groupID, appID, deploymentID string) (*models.Deployment, error)
GetDrafts(groupID, appID string) ([]models.AppDraft, error)
Import(groupID, appID string, appData []byte, strategy string) error
InvalidateCache(groupID, appID, path string) error
ListAssetsForAppID(groupID, appID string) ([]hosting.AssetMetadata, error)
ListSecrets(groupID, appID string) ([]secrets.Secret, error)
MoveAsset(groupID, appID, fromPath, toPath string) error
RemoveSecretByID(groupID, appID, secretID string) error
RemoveSecretByName(groupID, appID, secretName string) error
SetAssetAttributes(groupID, appID, path string, attributes ...hosting.AssetAttribute) error
UpdateSecretByID(groupID, appID, secretID, secretValue string) error
UpdateSecretByName(groupID, appID, secretName, secretValue string) error
UploadAsset(groupID, appID, path, hash string, size int64, body io.Reader, attributes ...hosting.AssetAttribute) error
UploadDependencies(groupID, appID, fullPath string) error
}
// NewRealmClient returns a new RealmClient to be used for making calls to the Realm Admin API
func NewRealmClient(client Client) RealmClient {
return &basicRealmClient{
Client: client,
}
}
type basicRealmClient struct {
Client
}
// Authenticate will authenticate a user given an api key and username
func (sc *basicRealmClient) Authenticate(authProvider auth.AuthenticationProvider) (*auth.Response, error) {
body, err := json.Marshal(authProvider.Payload())
if err != nil {
return nil, err
}
res, err := sc.Client.ExecuteRequest(http.MethodPost, fmt.Sprintf(authProviderLoginRoute, authProvider.Type()), RequestOptions{
Body: bytes.NewReader(body),
Header: http.Header{
"Content-Type": []string{"application/json"},
},
})
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s: failed to authenticate: %s", res.Status, UnmarshalRealmError(res))
}
decoder := json.NewDecoder(res.Body)
var authResponse auth.Response
if err := decoder.Decode(&authResponse); err != nil {
return nil, err
}
return &authResponse, nil
}
// Export will download a Realm app as a .zip
func (sc *basicRealmClient) Export(groupID, appID string, strategy ExportStrategy) (string, io.ReadCloser, error) {
queryParams := []string{fmt.Sprintf("version=%s", configVersion)}
if strategy == ExportStrategyTemplate {
queryParams = append(queryParams, "template=true")
} else if strategy == ExportStrategySourceControl {
queryParams = append(queryParams, "source_control=true")
}
url := fmt.Sprintf(appExportRoute, groupID, appID, strings.Join(queryParams, "&"))
res, err := sc.ExecuteRequest(http.MethodGet, url, RequestOptions{})
if err != nil {
return "", nil, err
}
if res.StatusCode != http.StatusOK {
defer res.Body.Close()
return "", nil, UnmarshalRealmError(res)
}
_, params, err := mime.ParseMediaType(res.Header.Get(hosting.AttributeContentDisposition))
if err != nil {
res.Body.Close()
return "", nil, err
}
filename := params["filename"]
if len(filename) == 0 {
res.Body.Close()
return "", nil, errExportMissingFilename
}
return filename, res.Body, nil
}
// Export will download the installed dependencies as a zip
func (sc *basicRealmClient) ExportDependencies(groupID, appID string) (string, io.ReadCloser, error) {
url := fmt.Sprintf(dependenciesExportArchiveRoute, groupID, appID)
res, err := sc.ExecuteRequest(http.MethodGet, url, RequestOptions{})
if err != nil {
return "", nil, err
}
if res.StatusCode != http.StatusOK {
defer res.Body.Close()
return "", nil, UnmarshalRealmError(res)
}
contentDisposition := res.Header.Get("Content-Disposition")
_, params, err := mime.ParseMediaType(contentDisposition)
if err != nil {
res.Body.Close()
return "", nil, err
}
filename := params["filename"]
if len(filename) == 0 {
res.Body.Close()
return "", nil, errExportMissingFilename
}
return filename, res.Body, nil
}
// Diff will execute a dry-run of an import, returning a diff of proposed changes
func (sc *basicRealmClient) Diff(groupID, appID string, appData []byte, strategy string) ([]string, error) {
res, err := sc.invokeImportRoute(groupID, appID, appData, strategy, true)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, UnmarshalRealmError(res)
}
var diffs []string
if err := json.NewDecoder(res.Body).Decode(&diffs); err != nil {
return nil, err
}
return diffs, nil
}
// Import will push a local Realm app to the server
func (sc *basicRealmClient) Import(groupID, appID string, appData []byte, strategy string) error {
res, err := sc.invokeImportRoute(groupID, appID, appData, strategy, false)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != http.StatusNoContent {
return UnmarshalRealmError(res)
}
return nil
}
func (sc *basicRealmClient) CreateDraft(groupID, appID string) (*models.AppDraft, error) {
res, err := sc.ExecuteRequest(http.MethodPost, fmt.Sprintf(draftsRoute, groupID, appID), RequestOptions{})
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusCreated {
return nil, UnmarshalRealmError(res)
}
bytes, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
var draft models.AppDraft
err = json.Unmarshal(bytes, &draft)
if err != nil {
return nil, err
}
return &draft, nil
}
func (sc *basicRealmClient) DeployDraft(groupID, appID, draftID string) (*models.Deployment, error) {
res, err := sc.ExecuteRequest(http.MethodPost, fmt.Sprintf(deployDraftRoute, groupID, appID, draftID), RequestOptions{})
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusCreated {
return nil, UnmarshalRealmError(res)
}
bytes, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
var deployment models.Deployment
err = json.Unmarshal(bytes, &deployment)
if err != nil {
return nil, err
}
return &deployment, nil
}
func (sc *basicRealmClient) DiscardDraft(groupID, appID, draftID string) error {
res, err := sc.ExecuteRequest(http.MethodDelete, fmt.Sprintf(draftByIDRoute, groupID, appID, draftID), RequestOptions{})
if err != nil {
return nil
}
defer res.Body.Close()
if res.StatusCode != http.StatusNoContent {
return UnmarshalRealmError(res)
}
return nil
}
func (sc *basicRealmClient) GetDeployment(groupID, appID, deploymentID string) (*models.Deployment, error) {
res, err := sc.ExecuteRequest(http.MethodGet, fmt.Sprintf(deploymentByIDRoute, groupID, appID, deploymentID), RequestOptions{})
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, UnmarshalRealmError(res)
}
bytes, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
var deployment models.Deployment
err = json.Unmarshal(bytes, &deployment)
if err != nil {
return nil, err
}
return &deployment, nil
}
func (sc *basicRealmClient) GetDrafts(groupID, appID string) ([]models.AppDraft, error) {
res, err := sc.ExecuteRequest(http.MethodGet, fmt.Sprintf(draftsRoute, groupID, appID), RequestOptions{})
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, UnmarshalRealmError(res)
}
bytes, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
var drafts []models.AppDraft
err = json.Unmarshal(bytes, &drafts)
if err != nil {
return nil, err
}
return drafts, nil
}
func (sc *basicRealmClient) DraftDiff(groupID, appID, draftID string) (*models.DraftDiff, error) {
res, err := sc.ExecuteRequest(http.MethodGet, fmt.Sprintf(diffDraftRoute, groupID, appID, draftID), RequestOptions{})
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, UnmarshalRealmError(res)
}
bytes, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
var diff models.DraftDiff
err = json.Unmarshal(bytes, &diff)
if err != nil {
return nil, err
}
return &diff, nil
}
func (sc *basicRealmClient) invokeImportRoute(groupID, appID string, appData []byte, strategy string, diff bool) (*http.Response, error) {
url := fmt.Sprintf(appImportRoute, groupID, appID)
url += fmt.Sprintf("?strategy=%s", strategy)
if diff {
url += "&diff=true"
}
return sc.ExecuteRequest(http.MethodPost, url, RequestOptions{Body: bytes.NewReader(appData)})
}
func (sc *basicRealmClient) FetchAppsByGroupID(groupID string) ([]*models.App, error) {
return sc.fetchAppsByGropuIDFromEndpoint(groupID, appsByGroupIDRoute)
}
func (sc *basicRealmClient) FetchAtlasAppsByGroupID(groupID string) ([]*models.App, error) {
return sc.fetchAppsByGropuIDFromEndpoint(groupID, atlasAppsByGroupIDRoute)
}
// FetchAppByGroupIDAndClientAppID fetches a Realm app given a groupID and clientAppID
func (sc *basicRealmClient) FetchAppByGroupIDAndClientAppID(groupID, clientAppID string) (*models.App, error) {
return sc.findProjectAppByClientAppID([]string{groupID}, clientAppID)
}
// FetchAppByClientAppID fetches a Realm app given a clientAppID
func (sc *basicRealmClient) FetchAppByClientAppID(clientAppID string) (*models.App, error) {
res, err := sc.ExecuteRequest(http.MethodGet, userProfileRoute, RequestOptions{})
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, UnmarshalRealmError(res)
}
dec := json.NewDecoder(res.Body)
var profileData models.UserProfile
if err := dec.Decode(&profileData); err != nil {
return nil, err
}
return sc.findProjectAppByClientAppID(profileData.AllGroupIDs(), clientAppID)
}
// UploadAsset creates a pipe and writes the asset to an http.POST along with its metadata
func (sc *basicRealmClient) UploadAsset(groupID, appID, path, hash string, size int64, body io.Reader, attributes ...hosting.AssetAttribute) error {
// The upload request consists of a multipart body with two parts:
// 1) the metadata, as json, and 2) the file data itself.
// First build the metadata part
metaPart, err := json.Marshal(hosting.AssetMetadata{
AppID: appID,
FilePath: path,
FileHash: hash,
FileSize: size,
Attrs: attributes,
})
if err != nil {
return err
}
// Construct a pipe stream: the reader side will be consumed and sent as the
// body of the outgoing request, and the writer side we can use to
// asynchronously populate it.
pipeReader, pipeWriter := io.Pipe()
bodyWriter := multipart.NewWriter(pipeWriter)
errChan := make(chan error, 2)
go func() {
defer func() {
bodyWriter.Close()
// If building the request failed, force the reader side to fail
// so that ExecuteRequest returns the error. This behaves equivalent to
// .Close() if err is nil.
errChan <- pipeWriter.CloseWithError(err)
}()
// Create the first part and write the metadata into it
metaWriter, formErr := bodyWriter.CreateFormField(metadataParam)
if err != nil {
errChan <- fmt.Errorf("failed to create metadata multipart field: %s", formErr)
}
if _, metaErr := metaWriter.Write(metaPart); metaErr != nil {
errChan <- fmt.Errorf("failed to write metadata to body: %s", metaErr)
}
// Create the second part, stream the file body into it, then close it.
fileWriter, fileErr := bodyWriter.CreateFormField(fileParam)
if fileErr != nil {
errChan <- fmt.Errorf("failed to create metadata multipart field: %s", fileErr)
}
if _, copyErr := io.Copy(fileWriter, body); copyErr != nil {
errChan <- fmt.Errorf("failed to write file to body: %s", copyErr)
}
errChan <- nil
}()
res, err := sc.ExecuteRequest(
http.MethodPut,
fmt.Sprintf(hostingAssetRoute, groupID, appID),
RequestOptions{
Body: pipeReader,
Header: http.Header{"Content-Type": {"multipart/mixed; boundary=" + bodyWriter.Boundary()}},
},
)
if err := <-errChan; err != nil {
return err
}
return checkStatusNoContent(res, err, "failed to upload asset")
}
// SetAssetAttributes sets the asset at the given path to have the provided AssetAttributes
func (sc *basicRealmClient) SetAssetAttributes(groupID, appID, path string, attributes ...hosting.AssetAttribute) error {
attrs, err := json.Marshal(setAttributesPayload{attributes})
if err != nil {
return err
}
res, err := sc.ExecuteRequest(
http.MethodPatch,
fmt.Sprintf(hostingAssetRoute+"?%s=%s", groupID, appID, pathParam, path),
RequestOptions{
Body: bytes.NewReader(attrs),
},
)
return checkStatusNoContent(res, err, "failed to update asset")
}
// CopyAsset moves an asset from location fromPath to location toPath
func (sc *basicRealmClient) CopyAsset(groupID, appID, fromPath, toPath string) error {
payload, err := json.Marshal(copyPayload{fromPath, toPath})
if err != nil {
return err
}
res, err := sc.invokePostRoute(groupID, appID, bytes.NewReader(payload))
return checkStatusNoContent(res, err, "failed to copy asset")
}
// MoveAsset moves an asset from location fromPath to location toPath
func (sc *basicRealmClient) MoveAsset(groupID, appID, fromPath, toPath string) error {
payload, err := json.Marshal(movePayload{fromPath, toPath})
if err != nil {
return err
}
res, err := sc.invokePostRoute(groupID, appID, bytes.NewReader(payload))
return checkStatusNoContent(res, err, "failed to move asset")
}
func (sc *basicRealmClient) invokePostRoute(groupID, appID string, payload io.Reader) (*http.Response, error) {
return sc.ExecuteRequest(
http.MethodPost,
fmt.Sprintf(hostingAssetsRoute, groupID, appID),
RequestOptions{
Body: payload,
},
)
}
// DeleteAsset deletes the asset at the given path
func (sc *basicRealmClient) DeleteAsset(groupID, appID, path string) error {
res, err := sc.ExecuteRequest(
http.MethodDelete,
fmt.Sprintf(hostingAssetRoute+"?%s=%s", groupID, appID, pathParam, path),
RequestOptions{},
)
return checkStatusNoContent(res, err, "failed to delete asset")
}
func (sc *basicRealmClient) findProjectAppByClientAppID(groupIDs []string, clientAppID string) (*models.App, error) {
for _, groupID := range groupIDs {
apps, err := sc.FetchAppsByGroupID(groupID)
if err != nil && err != errGroupNotFound {
return nil, err
}
if app := findAppByClientAppID(apps, clientAppID); app != nil {
return app, nil
}
// Check if the clientAppID is referring to an Atlas trigger
apps, err = sc.FetchAtlasAppsByGroupID(groupID)
if err != nil && err != errGroupNotFound {
return nil, err
}
if app := findAppByClientAppID(apps, clientAppID); app != nil {
return app, nil
}
}
return nil, ErrAppNotFound{clientAppID}
}
func (sc *basicRealmClient) CreateEmptyApp(groupID, appName, location, deploymentModel string) (*models.App, error) {
res, err := sc.ExecuteRequest(
http.MethodPost,
fmt.Sprintf(appsByGroupIDRoute, groupID),
RequestOptions{Body: strings.NewReader(fmt.Sprintf(`{"name":"%s","location":"%s","deployment_model":"%s"}`, appName, location, deploymentModel))},
)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusCreated {
return nil, UnmarshalRealmError(res)
}
dec := json.NewDecoder(res.Body)
var app models.App
if err := dec.Decode(&app); err != nil {
return nil, err
}
return &app, nil
}
func (sc *basicRealmClient) ListAssetsForAppID(groupID, appID string) ([]hosting.AssetMetadata, error) {
res, err := sc.ExecuteRequest(
http.MethodGet,
fmt.Sprintf(hostingAssetsRoute+"?recursive=true", groupID, appID),
RequestOptions{},
)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, UnmarshalRealmError(res)
}
dec := json.NewDecoder(res.Body)
var assetMetadata []hosting.AssetMetadata
if err := dec.Decode(&assetMetadata); err != nil {
return nil, err
}
return assetMetadata, nil
}
// InvalidateCache requests cache invalidation for the resource at the given
// path in the app's CloudFront distribution
func (sc *basicRealmClient) InvalidateCache(groupID, appID, path string) error {
payload, err := json.Marshal(invalidateCachePayload{Invalidate: true, Path: path})
if err != nil {
return err
}
res, err := sc.ExecuteRequest(
http.MethodPut,
fmt.Sprintf(hostingInvalidateCacheRoute, groupID, appID),
RequestOptions{
Body: bytes.NewReader(payload),
},
)
return checkStatusNoContent(res, err, "failed to invalidate cache")
}
// ListSecrets list secrets for the app
func (sc *basicRealmClient) ListSecrets(groupID, appID string) ([]secrets.Secret, error) {
res, err := sc.ExecuteRequest(
http.MethodGet,
fmt.Sprintf(secretsRoute, groupID, appID),
RequestOptions{},
)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, UnmarshalRealmError(res)
}
dec := json.NewDecoder(res.Body)
var secrets []secrets.Secret
if err := dec.Decode(&secrets); err != nil {
return nil, err
}
return secrets, nil
}
// AddSecret creates a secret for the app
func (sc *basicRealmClient) AddSecret(groupID, appID string, secret secrets.Secret) error {
payload, err := json.Marshal(secret)
if err != nil {
return err
}
res, err := sc.ExecuteRequest(
http.MethodPost,
fmt.Sprintf(secretsRoute, groupID, appID),
RequestOptions{
Body: bytes.NewReader(payload),
},
)
if err != nil {
return nil
}
defer res.Body.Close()
if res.StatusCode != http.StatusCreated {
return UnmarshalRealmError(res)
}
return nil
}
// UpdateSecretByID updates a secret's value from the app
func (sc *basicRealmClient) UpdateSecretByID(groupID, appID, secretID, secretValue string) error {
appSecrets, err := sc.ListSecrets(groupID, appID)
if err != nil {
return err
}
var secretToUpdate *secrets.Secret
for _, s := range appSecrets {
if s.ID == secretID {
secretToUpdate = &s
break
}
}
if secretToUpdate == nil {
return fmt.Errorf("secret not found: %s", secretID)
}
secretToUpdate.Value = secretValue
payload, err := json.Marshal(secretToUpdate)
if err != nil {
return err
}
res, err := sc.ExecuteRequest(
http.MethodPut,
fmt.Sprintf(secretRoute, groupID, appID, secretID),
RequestOptions{
Body: bytes.NewReader(payload),
},
)
if err != nil {
return err
}
return checkStatusNoContent(res, err, "failed to update secret")
}
// UpdateSecretByName updates a secret's value from the app
func (sc *basicRealmClient) UpdateSecretByName(groupID, appID, secretName, secretValue string) error {
appSecrets, err := sc.ListSecrets(groupID, appID)
if err != nil {
return err
}
var secretToUpdate *secrets.Secret
for _, s := range appSecrets {
if s.Name == secretName {
secretToUpdate = &s
break
}
}
if secretToUpdate == nil {
return fmt.Errorf("secret not found: %s", secretName)
}
secretToUpdate.Value = secretValue
payload, err := json.Marshal(secretToUpdate)
if err != nil {
return err
}
res, err := sc.ExecuteRequest(
http.MethodPut,
fmt.Sprintf(secretRoute, groupID, appID, secretToUpdate.ID),
RequestOptions{
Body: bytes.NewReader(payload),
},
)
if err != nil {
return err
}
return checkStatusNoContent(res, err, "failed to update secret")
}
// RemoveSecretByID deletes a secret from the app
func (sc *basicRealmClient) RemoveSecretByID(groupID, appID, secretID string) error {
res, err := sc.ExecuteRequest(
http.MethodDelete,
fmt.Sprintf(secretRoute, groupID, appID, secretID),
RequestOptions{},
)
if err != nil {
return err
}
return checkStatusNoContent(res, err, "failed to remove secret")
}
// RemoveSecretByName deletes a secret from the app
func (sc *basicRealmClient) RemoveSecretByName(groupID, appID, secretName string) error {
secrets, err := sc.ListSecrets(groupID, appID)
if err != nil {
return err
}
var secretID string
for _, s := range secrets {
if s.Name == secretName {
secretID = s.ID
break
}
}
if secretID == "" {
return fmt.Errorf("secret not found: %s", secretName)
}
return sc.RemoveSecretByID(groupID, appID, secretID)
}
func checkStatusNoContent(res *http.Response, requestErr error, errMessage string) error {
if requestErr != nil {
return requestErr
}
if res.StatusCode != http.StatusNoContent {
return fmt.Errorf("%s: %s: %s", res.Status, errMessage, UnmarshalRealmError(res))
}
return nil
}
func findAppByClientAppID(apps []*models.App, clientAppID string) *models.App {
for _, app := range apps {
if app.ClientAppID == clientAppID {
return app
}
}
return nil
}
func (sc *basicRealmClient) UploadDependencies(groupID, appID, fullPath string) error {
body, formatDataContentType, err := newMultipartMessage(fullPath)
if err != nil {
return err
}
res, err := sc.ExecuteRequest(
http.MethodPost,
fmt.Sprintf(dependenciesRoute, groupID, appID),
RequestOptions{
Body: body,
Header: http.Header{"Content-Type": {formatDataContentType}},
},
)
if err != nil {
return err
}
if res.StatusCode != http.StatusNoContent {
return UnmarshalRealmError(res)
}
return nil
}
func newMultipartMessage(fullPath string) (io.Reader, string, error) {
file, openErr := os.Open(fullPath)
if openErr != nil {
return nil, "", fmt.Errorf("failed to open the dependencies file '%s': %s", fullPath, openErr)
}
defer file.Close()
fileInfo, statErr := file.Stat()
if statErr != nil {
return nil, "", errors.New("failed to grab the dependencies file info")
}
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
defer writer.Close()
part, formErr := writer.CreateFormFile(fileParam, fileInfo.Name())
if formErr != nil {
return nil, "", fmt.Errorf("failed to create multipart form file: %s", formErr)
}
_, copyErr := io.Copy(part, file)
if copyErr != nil {
return nil, "", fmt.Errorf("failed to write file to body: %s", copyErr)
}
return body, writer.FormDataContentType(), nil
}
func (sc *basicRealmClient) fetchAppsByGropuIDFromEndpoint(groupID string, endpoint string) ([]*models.App, error) {
res, err := sc.ExecuteRequest(http.MethodGet, fmt.Sprintf(endpoint, groupID), RequestOptions{})
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
if res.StatusCode == http.StatusNotFound {
return nil, errGroupNotFound
}
return nil, UnmarshalRealmError(res)
}
dec := json.NewDecoder(res.Body)
var apps []*models.App
if err := dec.Decode(&apps); err != nil {
return nil, err
}
return apps, nil
}