-
Notifications
You must be signed in to change notification settings - Fork 351
/
controller.go
4793 lines (4394 loc) · 141 KB
/
controller.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 api
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"mime/multipart"
"net/http"
"net/mail"
"net/url"
"path/filepath"
"reflect"
"regexp"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/davecgh/go-spew/spew"
"github.com/go-openapi/swag"
"github.com/gorilla/sessions"
"github.com/treeverse/lakefs/pkg/actions"
"github.com/treeverse/lakefs/pkg/auth"
"github.com/treeverse/lakefs/pkg/auth/acl"
"github.com/treeverse/lakefs/pkg/auth/email"
"github.com/treeverse/lakefs/pkg/auth/model"
"github.com/treeverse/lakefs/pkg/auth/setup"
"github.com/treeverse/lakefs/pkg/block"
"github.com/treeverse/lakefs/pkg/catalog"
"github.com/treeverse/lakefs/pkg/cloud"
"github.com/treeverse/lakefs/pkg/config"
"github.com/treeverse/lakefs/pkg/graveler"
"github.com/treeverse/lakefs/pkg/graveler/ref"
"github.com/treeverse/lakefs/pkg/httputil"
"github.com/treeverse/lakefs/pkg/kv"
"github.com/treeverse/lakefs/pkg/logging"
"github.com/treeverse/lakefs/pkg/permissions"
tablediff "github.com/treeverse/lakefs/pkg/plugins/diff"
"github.com/treeverse/lakefs/pkg/samplerepo"
"github.com/treeverse/lakefs/pkg/stats"
"github.com/treeverse/lakefs/pkg/templater"
"github.com/treeverse/lakefs/pkg/upload"
"github.com/treeverse/lakefs/pkg/validator"
"github.com/treeverse/lakefs/pkg/version"
)
const (
// DefaultMaxPerPage is the maximum amount of results returned for paginated queries to the API
DefaultMaxPerPage int = 1000
lakeFSPrefix = "symlinks"
actionStatusCompleted = "completed"
actionStatusFailed = "failed"
actionStatusSkipped = "skipped"
entryTypeObject = "object"
entryTypeCommonPrefix = "common_prefix"
DefaultMaxDeleteObjects = 1000
DefaultResetPasswordExpiration = 20 * time.Minute
// httpStatusClientClosedRequest used as internal status code when request context is cancelled
httpStatusClientClosedRequest = 499
// httpStatusClientClosedRequestText text used for client closed request status code
httpStatusClientClosedRequestText = "Client closed request"
)
type actionsHandler interface {
GetRunResult(ctx context.Context, repositoryID, runID string) (*actions.RunResult, error)
GetTaskResult(ctx context.Context, repositoryID, runID, hookRunID string) (*actions.TaskResult, error)
ListRunResults(ctx context.Context, repositoryID, branchID, commitID, after string) (actions.RunResultIterator, error)
ListRunTaskResults(ctx context.Context, repositoryID, runID, after string) (actions.TaskResultIterator, error)
}
type Migrator interface {
Migrate(ctx context.Context) error
}
type Controller struct {
Config *config.Config
Catalog catalog.Interface
Authenticator auth.Authenticator
Auth auth.Service
BlockAdapter block.Adapter
MetadataManager auth.MetadataManager
Migrator Migrator
Collector stats.Collector
CloudMetadataProvider cloud.MetadataProvider
Actions actionsHandler
AuditChecker AuditChecker
Logger logging.Logger
Emailer *email.Emailer
Templater templater.Service
sessionStore sessions.Store
PathProvider upload.PathProvider
otfDiffService *tablediff.Service
}
func (c *Controller) PrepareGarbageCollectionUncommitted(w http.ResponseWriter, r *http.Request, body PrepareGarbageCollectionUncommittedJSONRequestBody, repository string) {
if !c.authorize(w, r, permissions.Node{
Permission: permissions.Permission{
Action: permissions.PrepareGarbageCollectionUncommittedAction,
Resource: permissions.RepoArn(repository),
},
}) {
return
}
ctx := r.Context()
c.LogAction(ctx, "prepare_garbage_collection_uncommitted", r, repository, "", "")
continuationToken := StringValue(body.ContinuationToken)
mark, err := decodeGCUncommittedMark(continuationToken)
if err != nil {
c.Logger.WithError(err).
WithFields(logging.Fields{"repository": repository, "continuation_token": continuationToken}).
Error("Failed to decode gc uncommitted continuation token")
writeError(w, r, http.StatusBadRequest, "invalid continuation token")
return
}
uncommittedInfo, err := c.Catalog.PrepareGCUncommitted(ctx, repository, mark)
if err != nil {
c.Logger.WithError(err).
WithFields(logging.Fields{"repository": repository, "continuation_token": continuationToken}).
Error("PrepareGCUncommitted failed")
c.handleAPIError(ctx, w, r, err)
return
}
nextContinuationToken, err := encodeGCUncommittedMark(uncommittedInfo.Mark)
if err != nil {
c.Logger.WithError(err).
WithFields(logging.Fields{
"repository": repository,
"mark": spew.Sdump(uncommittedInfo.Mark),
}).
Error("Failed encoding uncommitted gc mark")
writeError(w, r, http.StatusInternalServerError, "failed to encode uncommitted mark")
return
}
writeResponse(w, r, http.StatusCreated, PrepareGCUncommittedResponse{
RunId: uncommittedInfo.RunID,
GcUncommittedLocation: uncommittedInfo.Location,
ContinuationToken: nextContinuationToken,
})
}
func (c *Controller) GetAuthCapabilities(w http.ResponseWriter, r *http.Request) {
inviteSupported := c.Auth.IsInviteSupported()
emailSupported := c.Emailer.Params.SMTPHost != ""
writeResponse(w, r, http.StatusOK, AuthCapabilities{
InviteUser: &inviteSupported,
ForgotPassword: &emailSupported,
})
}
func (c *Controller) DeleteObjects(w http.ResponseWriter, r *http.Request, body DeleteObjectsJSONRequestBody, repository, branch string) {
ctx := r.Context()
c.LogAction(ctx, "delete_objects", r, repository, branch, "")
// limit check
if len(body.Paths) > DefaultMaxDeleteObjects {
err := fmt.Errorf("%w, max paths is set to %d", ErrRequestSizeExceeded, DefaultMaxDeleteObjects)
writeError(w, r, http.StatusInternalServerError, err)
return
}
// errs used to collect errors as part of the response, can't be nil
errs := make([]ObjectError, 0)
// check if we authorize to delete each object, prepare a list of paths we can delete
var pathsToDelete []string
for _, objectPath := range body.Paths {
if !c.authorize(w, r, permissions.Node{
Permission: permissions.Permission{
Action: permissions.DeleteObjectAction,
Resource: permissions.ObjectArn(repository, objectPath),
},
}) {
errs = append(errs, ObjectError{
Path: StringPtr(objectPath),
StatusCode: http.StatusUnauthorized,
Message: http.StatusText(http.StatusUnauthorized),
})
} else {
pathsToDelete = append(pathsToDelete, objectPath)
}
}
// batch delete the entries we allow to delete
delErr := c.Catalog.DeleteEntries(ctx, repository, branch, pathsToDelete)
delErrs := graveler.NewMapDeleteErrors(delErr)
for _, objectPath := range pathsToDelete {
// set err to the specific error when possible
err := delErrs[objectPath]
if err == nil {
err = delErr
}
lg := c.Logger.WithField("path", objectPath)
switch {
case errors.Is(err, graveler.ErrNotFound):
lg.WithError(err).Debug("tried to delete a non-existent object")
case errors.Is(err, graveler.ErrWriteToProtectedBranch):
errs = append(errs, ObjectError{
Path: StringPtr(objectPath),
StatusCode: http.StatusForbidden,
Message: err.Error(),
})
case errors.Is(err, catalog.ErrPathRequiredValue):
// issue #1706 - https://github.com/treeverse/lakeFS/issues/1706
// Spark trying to delete the path "main/", which we map to branch "main" with an empty path.
// Spark expects it to succeed (not deleting anything is a success), instead of returning an error.
lg.Debug("tried to delete with an empty branch")
case err != nil:
lg.WithError(err).Error("failed deleting object")
errs = append(errs, ObjectError{
Path: StringPtr(objectPath),
StatusCode: http.StatusInternalServerError,
Message: err.Error(),
})
default:
lg.Debug("object set for deletion")
}
}
response := ObjectErrorList{
Errors: errs,
}
writeResponse(w, r, http.StatusOK, response)
}
func (c *Controller) Login(w http.ResponseWriter, r *http.Request, body LoginJSONRequestBody) {
ctx := r.Context()
user, err := userByAuth(ctx, c.Logger, c.Authenticator, c.Auth, body.AccessKeyId, body.SecretAccessKey)
if errors.Is(err, ErrAuthenticatingRequest) {
writeResponse(w, r, http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized))
return
}
loginTime := time.Now()
duration := c.Config.Auth.LoginDuration
expires := loginTime.Add(duration)
secret := c.Auth.SecretStore().SharedSecret()
tokenString, err := GenerateJWTLogin(secret, user.Username, loginTime, expires)
if err != nil {
writeError(w, r, http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError))
return
}
internalAuthSession, _ := c.sessionStore.Get(r, InternalAuthSessionName)
internalAuthSession.Values[TokenSessionKeyName] = tokenString
err = c.sessionStore.Save(r, w, internalAuthSession)
if err != nil {
c.Logger.WithError(err).Error("Failed to save internal auth session")
writeError(w, r, http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError))
return
}
response := AuthenticationToken{
Token: tokenString,
TokenExpiration: Int64Ptr(expires.Unix()),
}
writeResponse(w, r, http.StatusOK, response)
}
func (c *Controller) GetPhysicalAddress(w http.ResponseWriter, r *http.Request, repository, branch string, params GetPhysicalAddressParams) {
if !c.authorize(w, r, permissions.Node{
Permission: permissions.Permission{
Action: permissions.WriteObjectAction,
Resource: permissions.ObjectArn(repository, params.Path),
},
}) {
return
}
ctx := r.Context()
c.LogAction(ctx, "generate_physical_address", r, repository, branch, "")
repo, err := c.Catalog.GetRepository(ctx, repository)
if errors.Is(err, graveler.ErrNotFound) {
writeError(w, r, http.StatusNotFound, err)
return
}
if err != nil {
writeError(w, r, http.StatusInternalServerError, err)
return
}
token, err := c.Catalog.GetStagingToken(ctx, repository, branch)
if errors.Is(err, graveler.ErrNotFound) {
writeError(w, r, http.StatusNotFound, err)
return
}
if err != nil {
writeError(w, r, http.StatusInternalServerError, err)
return
}
address := c.PathProvider.NewPath()
qk, err := c.BlockAdapter.ResolveNamespace(repo.StorageNamespace, address, block.IdentifierTypeRelative)
if err != nil {
writeError(w, r, http.StatusInternalServerError, err)
return
}
err = c.Catalog.SetLinkAddress(ctx, repository, address)
if err != nil {
c.handleAPIError(ctx, w, r, err)
return
}
response := &StagingLocation{
PhysicalAddress: StringPtr(qk.Format()),
Token: StringValue(token),
}
if swag.BoolValue(params.Presign) {
// generate a pre-signed PUT url for the given request
preSignedURL, err := c.BlockAdapter.GetPreSignedURL(ctx, block.ObjectPointer{
StorageNamespace: repo.StorageNamespace,
Identifier: address,
IdentifierType: block.IdentifierTypeRelative,
}, block.PreSignModeWrite)
if err != nil {
writeError(w, r, http.StatusInternalServerError, err)
return
}
response.PresignedUrl = &preSignedURL
}
writeResponse(w, r, http.StatusOK, response)
}
func (c *Controller) LinkPhysicalAddress(w http.ResponseWriter, r *http.Request, body LinkPhysicalAddressJSONRequestBody, repository, branch string, params LinkPhysicalAddressParams) {
if !c.authorize(w, r, permissions.Node{
Permission: permissions.Permission{
Action: permissions.WriteObjectAction,
Resource: permissions.ObjectArn(repository, params.Path),
},
}) {
return
}
ctx := r.Context()
c.LogAction(ctx, "stage_object", r, repository, branch, "")
repo, err := c.Catalog.GetRepository(ctx, repository)
if errors.Is(err, graveler.ErrNotFound) {
writeError(w, r, http.StatusNotFound, err)
return
}
if err != nil {
writeError(w, r, http.StatusInternalServerError, err)
return
}
// write metadata
qk, err := c.BlockAdapter.ResolveNamespace(repo.StorageNamespace, params.Path, block.IdentifierTypeRelative)
if err != nil {
writeError(w, r, http.StatusInternalServerError, err)
return
}
blockStoreType := c.BlockAdapter.BlockstoreType()
expectedType := qk.GetStorageType().BlockstoreType()
if expectedType != blockStoreType {
c.Logger.WithContext(ctx).WithFields(logging.Fields{
"expected_type": expectedType,
"blockstore_type": blockStoreType,
}).Error("invalid blockstore type")
c.handleAPIError(ctx, w, r, fmt.Errorf("invalid blockstore type: %w", block.ErrInvalidAddress))
return
}
writeTime := time.Now()
physicalAddress, addressType := normalizePhysicalAddress(repo.StorageNamespace, StringValue(body.Staging.PhysicalAddress))
// validate token
err = c.Catalog.VerifyLinkAddress(ctx, repository, physicalAddress)
if c.handleAPIError(ctx, w, r, err) {
return
}
// Because CreateEntry tracks staging on a database with atomic operations,
// _ignore_ the staging token here: no harm done even if a race was lost
// against a commit.
entryBuilder := catalog.NewDBEntryBuilder().
CommonLevel(false).
Path(params.Path).
PhysicalAddress(physicalAddress).
AddressType(addressType).
CreationDate(writeTime).
Size(body.SizeBytes).
Checksum(body.Checksum).
ContentType(StringValue(body.ContentType))
if body.UserMetadata != nil {
entryBuilder.Metadata(body.UserMetadata.AdditionalProperties)
}
entry := entryBuilder.Build()
err = c.Catalog.CreateEntry(ctx, repo.Name, branch, entry)
if c.handleAPIError(ctx, w, r, err) {
return
}
metadata := ObjectUserMetadata{AdditionalProperties: entry.Metadata}
response := ObjectStats{
Checksum: entry.Checksum,
ContentType: &entry.ContentType,
Metadata: &metadata,
Mtime: entry.CreationDate.Unix(),
Path: entry.Path,
PathType: entryTypeObject,
PhysicalAddress: entry.PhysicalAddress,
SizeBytes: Int64Ptr(entry.Size),
}
writeResponse(w, r, http.StatusOK, response)
}
// normalizePhysicalAddress return relative address based on storage namespace if possible. If address doesn't match
// the storage namespace prefix, the return address type is full.
func normalizePhysicalAddress(storageNamespace, physicalAddress string) (string, catalog.AddressType) {
prefix := storageNamespace
if !strings.HasSuffix(prefix, catalog.DefaultPathDelimiter) {
prefix += catalog.DefaultPathDelimiter
}
if strings.HasPrefix(physicalAddress, prefix) {
return physicalAddress[len(prefix):], catalog.AddressTypeRelative
}
return physicalAddress, catalog.AddressTypeFull
}
func (c *Controller) ListGroups(w http.ResponseWriter, r *http.Request, params ListGroupsParams) {
if !c.authorize(w, r, permissions.Node{
Permission: permissions.Permission{
Action: permissions.ListGroupsAction,
Resource: permissions.All,
},
}) {
return
}
ctx := r.Context()
c.LogAction(ctx, "list_groups", r, "", "", "")
groups, paginator, err := c.Auth.ListGroups(ctx, &model.PaginationParams{
After: paginationAfter(params.After),
Prefix: paginationPrefix(params.Prefix),
Amount: paginationAmount(params.Amount),
})
if c.handleAPIError(ctx, w, r, err) {
return
}
response := GroupList{
Results: make([]Group, 0, len(groups)),
Pagination: Pagination{
HasMore: paginator.NextPageToken != "",
NextOffset: paginator.NextPageToken,
Results: paginator.Amount,
},
}
for _, g := range groups {
response.Results = append(response.Results, Group{
Id: g.DisplayName,
CreationDate: g.CreatedAt.Unix(),
})
}
writeResponse(w, r, http.StatusOK, response)
}
func (c *Controller) CreateGroup(w http.ResponseWriter, r *http.Request, body CreateGroupJSONRequestBody) {
if !c.authorize(w, r, permissions.Node{
Permission: permissions.Permission{
Action: permissions.CreateGroupAction,
Resource: permissions.GroupArn(body.Id),
},
}) {
return
}
ctx := r.Context()
c.LogAction(ctx, "create_group", r, "", "", "")
// Check that group name is valid
valid, msg := c.isNameValid(body.Id, "Group")
if !valid {
writeError(w, r, http.StatusBadRequest, msg)
return
}
g := &model.Group{
CreatedAt: time.Now().UTC(),
DisplayName: body.Id,
}
err := c.Auth.CreateGroup(ctx, g)
if c.handleAPIError(ctx, w, r, err) {
return
}
response := Group{
CreationDate: g.CreatedAt.Unix(),
Id: g.DisplayName,
}
writeResponse(w, r, http.StatusCreated, response)
}
func (c *Controller) DeleteGroup(w http.ResponseWriter, r *http.Request, groupID string) {
if !c.authorize(w, r, permissions.Node{
Permission: permissions.Permission{
Action: permissions.DeleteGroupAction,
Resource: permissions.GroupArn(groupID),
},
}) {
return
}
ctx := r.Context()
c.LogAction(ctx, "delete_group", r, "", "", "")
err := c.Auth.DeleteGroup(ctx, groupID)
if errors.Is(err, auth.ErrNotFound) {
writeError(w, r, http.StatusNotFound, "group not found")
return
}
if c.handleAPIError(ctx, w, r, err) {
return
}
writeResponse(w, r, http.StatusNoContent, nil)
}
func (c *Controller) GetGroup(w http.ResponseWriter, r *http.Request, groupID string) {
if !c.authorize(w, r, permissions.Node{
Permission: permissions.Permission{
Action: permissions.ReadGroupAction,
Resource: permissions.GroupArn(groupID),
},
}) {
return
}
ctx := r.Context()
c.LogAction(ctx, "get_group", r, "", "", "")
g, err := c.Auth.GetGroup(ctx, groupID)
if errors.Is(err, auth.ErrNotFound) {
writeError(w, r, http.StatusNotFound, "group not found")
return
}
if c.handleAPIError(ctx, w, r, err) {
return
}
response := Group{
Id: g.DisplayName,
CreationDate: g.CreatedAt.Unix(),
}
writeResponse(w, r, http.StatusOK, response)
}
func (c *Controller) GetGroupACL(w http.ResponseWriter, r *http.Request, groupID string) {
aclPolicyName := acl.ACLPolicyName(groupID)
if !c.authorize(w, r, permissions.Node{
Type: permissions.NodeTypeAnd,
Nodes: []permissions.Node{
{
Permission: permissions.Permission{
Action: permissions.ReadGroupAction,
Resource: permissions.GroupArn(groupID),
},
},
{
Permission: permissions.Permission{
Action: permissions.ReadPolicyAction,
Resource: permissions.PolicyArn(aclPolicyName),
},
},
},
}) {
return
}
ctx := r.Context()
c.LogAction(ctx, "get_group_acl", r, "", "", "")
policies, _, err := c.Auth.ListGroupPolicies(ctx, groupID, &model.PaginationParams{
Amount: 2, //nolint:gomnd
})
if c.handleAPIError(ctx, w, r, err) {
return
}
var groupACL model.ACL
switch len(policies) {
case 0: // Blank ACL is valid and allows nothing
break
case 1:
groupACL = policies[0].ACL
if len(groupACL.Permission) == 0 {
c.Logger.
WithContext(ctx).
WithField("policy", fmt.Sprintf("%+v", policies[0])).
WithField("acl", fmt.Sprintf("%+v", groupACL)).
WithField("group", groupID).
Warn("Policy attached to group has no ACL")
response := NotFoundOrNoACL{
Message: "Policy attached to group has no ACL",
NoAcl: swag.Bool(true),
}
writeResponse(w, r, http.StatusNotFound, response)
return
}
default:
c.Logger.
WithContext(ctx).
WithField("num_policies", len(policies)).
WithField("group", groupID).
Warn("Wrong number of policies found")
response := NotFoundOrNoACL{
Message: "Multiple policies attached to group - no ACL",
NoAcl: swag.Bool(true),
}
writeResponse(w, r, http.StatusNotFound, response)
return
}
response := ACL{
Permission: string(groupACL.Permission),
}
writeResponse(w, r, http.StatusOK, response)
}
func (c *Controller) SetGroupACL(w http.ResponseWriter, r *http.Request, body SetGroupACLJSONRequestBody, groupID string) {
aclPolicyName := acl.ACLPolicyName(groupID)
if !c.authorize(w, r, permissions.Node{
Type: permissions.NodeTypeAnd,
Nodes: []permissions.Node{
{
Permission: permissions.Permission{
Action: permissions.ReadGroupAction,
Resource: permissions.GroupArn(groupID),
},
},
{
Permission: permissions.Permission{
Action: permissions.AttachPolicyAction,
Resource: permissions.PolicyArn(aclPolicyName),
},
},
{
Permission: permissions.Permission{
Action: permissions.UpdatePolicyAction,
Resource: permissions.PolicyArn(aclPolicyName),
},
},
},
}) {
return
}
ctx := r.Context()
c.LogAction(ctx, "set_group_acl", r, "", "", "")
newACL := model.ACL{
Permission: model.ACLPermission(body.Permission),
}
err := acl.WriteGroupACL(ctx, c.Auth, groupID, newACL, time.Now(), true)
if c.handleAPIError(ctx, w, r, err) {
return
}
writeResponse(w, r, http.StatusCreated, nil)
}
func (c *Controller) ListGroupMembers(w http.ResponseWriter, r *http.Request, groupID string, params ListGroupMembersParams) {
if !c.authorize(w, r, permissions.Node{
Permission: permissions.Permission{
Action: permissions.ReadGroupAction,
Resource: permissions.GroupArn(groupID),
},
}) {
return
}
ctx := r.Context()
c.LogAction(ctx, "list_group_users", r, "", "", "")
users, paginator, err := c.Auth.ListGroupUsers(ctx, groupID, &model.PaginationParams{
After: paginationAfter(params.After),
Prefix: paginationPrefix(params.Prefix),
Amount: paginationAmount(params.Amount),
})
if c.handleAPIError(ctx, w, r, err) {
return
}
response := UserList{
Results: make([]User, 0, len(users)),
Pagination: Pagination{
HasMore: paginator.NextPageToken != "",
NextOffset: paginator.NextPageToken,
Results: paginator.Amount,
},
}
for _, u := range users {
response.Results = append(response.Results, User{
Id: u.Username,
CreationDate: u.CreatedAt.Unix(),
Email: u.Email,
})
}
writeResponse(w, r, http.StatusOK, response)
}
func (c *Controller) DeleteGroupMembership(w http.ResponseWriter, r *http.Request, groupID, userID string) {
if !c.authorize(w, r, permissions.Node{
Permission: permissions.Permission{
Action: permissions.RemoveGroupMemberAction,
Resource: permissions.GroupArn(groupID),
},
}) {
return
}
ctx := r.Context()
c.LogAction(ctx, "remove_user_from_group", r, "", "", "")
err := c.Auth.RemoveUserFromGroup(ctx, userID, groupID)
if c.handleAPIError(ctx, w, r, err) {
return
}
writeResponse(w, r, http.StatusNoContent, nil)
}
func (c *Controller) AddGroupMembership(w http.ResponseWriter, r *http.Request, groupID, userID string) {
if !c.authorize(w, r, permissions.Node{
Permission: permissions.Permission{
Action: permissions.AddGroupMemberAction,
Resource: permissions.GroupArn(groupID),
},
}) {
return
}
ctx := r.Context()
c.LogAction(ctx, "add_user_to_group", r, "", "", "")
err := c.Auth.AddUserToGroup(ctx, userID, groupID)
if c.handleAPIError(ctx, w, r, err) {
return
}
writeResponse(w, r, http.StatusCreated, nil)
}
func (c *Controller) ListGroupPolicies(w http.ResponseWriter, r *http.Request, groupID string, params ListGroupPoliciesParams) {
if c.Config.IsAuthUISimplified() {
writeError(w, r, http.StatusNotImplemented, "Not implemented")
return
}
if !c.authorize(w, r, permissions.Node{
Permission: permissions.Permission{
Action: permissions.ReadGroupAction,
Resource: permissions.GroupArn(groupID),
},
}) {
return
}
ctx := r.Context()
c.LogAction(ctx, "list_group_policies", r, "", "", "")
policies, paginator, err := c.Auth.ListGroupPolicies(ctx, groupID, &model.PaginationParams{
After: paginationAfter(params.After),
Prefix: paginationPrefix(params.Prefix),
Amount: paginationAmount(params.Amount),
})
if c.handleAPIError(ctx, w, r, err) {
return
}
response := PolicyList{
Results: make([]Policy, 0, len(policies)),
Pagination: Pagination{
HasMore: paginator.NextPageToken != "",
NextOffset: paginator.NextPageToken,
Results: paginator.Amount,
},
}
for _, p := range policies {
response.Results = append(response.Results, serializePolicy(p))
}
writeResponse(w, r, http.StatusOK, response)
}
func serializePolicy(p *model.Policy) Policy {
stmts := make([]Statement, 0, len(p.Statement))
for _, s := range p.Statement {
stmts = append(stmts, Statement{
Action: s.Action,
Effect: s.Effect,
Resource: s.Resource,
})
}
createdAt := p.CreatedAt.Unix()
return Policy{
Id: p.DisplayName,
CreationDate: &createdAt, // TODO(barak): check if CreationDate should be required
Statement: stmts,
}
}
func (c *Controller) DetachPolicyFromGroup(w http.ResponseWriter, r *http.Request, groupID, policyID string) {
if c.Config.IsAuthUISimplified() {
writeError(w, r, http.StatusNotImplemented, "Not implemented")
return
}
if !c.authorize(w, r, permissions.Node{
Permission: permissions.Permission{
Action: permissions.DetachPolicyAction,
Resource: permissions.GroupArn(groupID),
},
}) {
return
}
ctx := r.Context()
c.LogAction(ctx, "detach_policy_from_group", r, "", "", "")
err := c.Auth.DetachPolicyFromGroup(ctx, policyID, groupID)
if c.handleAPIError(ctx, w, r, err) {
return
}
writeResponse(w, r, http.StatusNoContent, nil)
}
func (c *Controller) AttachPolicyToGroup(w http.ResponseWriter, r *http.Request, groupID, policyID string) {
if c.Config.IsAuthUISimplified() {
writeError(w, r, http.StatusNotImplemented, "Not implemented")
return
}
if !c.authorize(w, r, permissions.Node{
Permission: permissions.Permission{
Action: permissions.AttachPolicyAction,
Resource: permissions.GroupArn(groupID),
},
}) {
return
}
ctx := r.Context()
c.LogAction(ctx, "attach_policy_to_group", r, "", "", "")
err := c.Auth.AttachPolicyToGroup(ctx, policyID, groupID)
if c.handleAPIError(ctx, w, r, err) {
return
}
writeResponse(w, r, http.StatusCreated, nil)
}
func (c *Controller) ListPolicies(w http.ResponseWriter, r *http.Request, params ListPoliciesParams) {
if c.Config.IsAuthUISimplified() {
writeError(w, r, http.StatusNotImplemented, "Not implemented")
return
}
if !c.authorize(w, r, permissions.Node{
Permission: permissions.Permission{
Action: permissions.ListPoliciesAction,
Resource: permissions.All,
},
}) {
return
}
ctx := r.Context()
c.LogAction(ctx, "list_policies", r, "", "", "")
policies, paginator, err := c.Auth.ListPolicies(ctx, &model.PaginationParams{
After: paginationAfter(params.After),
Prefix: paginationPrefix(params.Prefix),
Amount: paginationAmount(params.Amount),
})
if c.handleAPIError(ctx, w, r, err) {
return
}
response := PolicyList{
Results: make([]Policy, 0, len(policies)),
Pagination: Pagination{
HasMore: paginator.NextPageToken != "",
NextOffset: paginator.NextPageToken,
Results: paginator.Amount,
},
}
for _, p := range policies {
response.Results = append(response.Results, serializePolicy(p))
}
writeResponse(w, r, http.StatusOK, response)
}
func (c *Controller) CreatePolicy(w http.ResponseWriter, r *http.Request, body CreatePolicyJSONRequestBody) {
if c.Config.IsAuthUISimplified() {
writeError(w, r, http.StatusNotImplemented, "Not implemented")
return
}
if !c.authorize(w, r, permissions.Node{
Permission: permissions.Permission{
Action: permissions.CreatePolicyAction,
Resource: permissions.PolicyArn(body.Id),
},
}) {
return
}
ctx := r.Context()
c.LogAction(ctx, "create_policy", r, "", "", "")
// Check that policy ID is valid
valid, msg := c.isNameValid(body.Id, "Policy")
if !valid {
writeError(w, r, http.StatusBadRequest, msg)
return
}
stmts := make(model.Statements, len(body.Statement))
for i, apiStatement := range body.Statement {
stmts[i] = model.Statement{
Effect: apiStatement.Effect,
Action: apiStatement.Action,
Resource: apiStatement.Resource,
}
}
p := &model.Policy{
CreatedAt: time.Now().UTC(),
DisplayName: body.Id,
Statement: stmts,
}
err := c.Auth.WritePolicy(ctx, p, false)
if c.handleAPIError(ctx, w, r, err) {
return
}
writeResponse(w, r, http.StatusCreated, serializePolicy(p))
}
func (c *Controller) DeletePolicy(w http.ResponseWriter, r *http.Request, policyID string) {
if c.Config.IsAuthUISimplified() {
writeError(w, r, http.StatusNotImplemented, "Not implemented")
return
}
if !c.authorize(w, r, permissions.Node{
Permission: permissions.Permission{
Action: permissions.DeletePolicyAction,
Resource: permissions.PolicyArn(policyID),
},
}) {
return
}
ctx := r.Context()
c.LogAction(ctx, "delete_policy", r, "", "", "")
err := c.Auth.DeletePolicy(ctx, policyID)
if errors.Is(err, auth.ErrNotFound) {
writeError(w, r, http.StatusNotFound, "policy not found")
return
}
if c.handleAPIError(ctx, w, r, err) {
return
}
writeResponse(w, r, http.StatusNoContent, nil)
}
func (c *Controller) GetPolicy(w http.ResponseWriter, r *http.Request, policyID string) {
if c.Config.IsAuthUISimplified() {
writeError(w, r, http.StatusNotImplemented, "Not implemented")
return
}
if !c.authorize(w, r, permissions.Node{
Permission: permissions.Permission{
Action: permissions.ReadPolicyAction,
Resource: permissions.PolicyArn(policyID),
},
}) {
return
}
ctx := r.Context()
c.LogAction(ctx, "get_policy", r, "", "", "")
p, err := c.Auth.GetPolicy(ctx, policyID)
if errors.Is(err, auth.ErrNotFound) {
writeError(w, r, http.StatusNotFound, "policy not found")
return
}
if c.handleAPIError(ctx, w, r, err) {
return
}
response := serializePolicy(p)
writeResponse(w, r, http.StatusOK, response)
}
func (c *Controller) UpdatePolicy(w http.ResponseWriter, r *http.Request, body UpdatePolicyJSONRequestBody, policyID string) {
if c.Config.IsAuthUISimplified() {
writeError(w, r, http.StatusNotImplemented, "Not implemented")
return
}
if !c.authorize(w, r, permissions.Node{
Permission: permissions.Permission{
Action: permissions.UpdatePolicyAction,
Resource: permissions.PolicyArn(policyID),
},
}) {