-
Notifications
You must be signed in to change notification settings - Fork 180
/
rest.go
1339 lines (1205 loc) · 42.7 KB
/
rest.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
/*
* Copyright (c) 2018. Abstrium SAS <team (at) pydio.com>
* This file is part of Pydio Cells.
*
* Pydio Cells is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pydio Cells is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Pydio Cells. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <https://pydio.com>.
*/
// Package rest implements all the share logic for Cells and Links.
//
// It is a high-level service using many other services for crud-ing shares through the REST API.
package rest
import (
"context"
"fmt"
"strings"
"time"
"github.com/emicklei/go-restful"
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/any"
"github.com/gosimple/slug"
"github.com/micro/go-micro/errors"
"github.com/pborman/uuid"
"go.uber.org/zap"
"github.com/pydio/cells/common"
"github.com/pydio/cells/common/auth/claim"
"github.com/pydio/cells/common/log"
"github.com/pydio/cells/common/micro"
"github.com/pydio/cells/common/proto/idm"
"github.com/pydio/cells/common/proto/rest"
"github.com/pydio/cells/common/proto/tree"
"github.com/pydio/cells/common/service"
service2 "github.com/pydio/cells/common/service/proto"
"github.com/pydio/cells/common/service/resources"
"github.com/pydio/cells/common/utils"
"github.com/pydio/cells/common/views"
)
// SharesHandler implements handler methods for the share REST service.
type SharesHandler struct {
resources.ResourceProviderHandler
}
// NewSharesHandler simply creates a new SharesHandler.
func NewSharesHandler() *SharesHandler {
h := new(SharesHandler)
h.ServiceName = common.SERVICE_WORKSPACE
h.ResourceName = "rooms"
//h.PoliciesLoader = h.loadPoliciesForResource
return h
}
// SwaggerTags list the names of the service tags declared in the swagger json implemented by this service.
func (h *SharesHandler) SwaggerTags() []string {
return []string{"ShareService"}
}
// Filter returns a function to filter the swagger path.
func (h *SharesHandler) Filter() func(string) string {
return nil
}
// PutCell creates or updates a shared room (a.k.a a Cell) via REST API.
func (h *SharesHandler) PutCell(req *restful.Request, rsp *restful.Response) {
ctx := req.Request.Context()
var shareRequest rest.PutCellRequest
err := req.ReadEntity(&shareRequest)
if err != nil {
log.Logger(ctx).Error("cannot fetch rest.CellRequest", zap.Error(err))
service.RestError500(req, rsp, err)
return
}
log.Logger(ctx).Debug("Received Share.Cell API request", zap.Any("input", &shareRequest))
// Init Root Nodes and check permissions
err, createdCellNode, readonly := h.ParseRootNodes(ctx, &shareRequest)
if err != nil {
if errors.Parse(err.Error()).Code == 403 {
service.RestError403(req, rsp, err)
} else {
service.RestError500(req, rsp, err)
}
return
}
workspace, wsCreated, err := h.GetOrCreateWorkspace(ctx, shareRequest.Room.Uuid, idm.WorkspaceScope_ROOM, shareRequest.Room.Label, shareRequest.Room.Description, false)
if err != nil {
service.RestError500(req, rsp, err)
return
}
if !wsCreated && !h.IsContextEditable(ctx, workspace.UUID, workspace.Policies) {
service.RestError403(req, rsp, fmt.Errorf("you are not allowed to edit this cell"))
return
}
// Now set ACLs on Workspace
aclClient := idm.NewACLServiceClient(common.SERVICE_GRPC_NAMESPACE_+common.SERVICE_ACL, defaults.NewClient())
var currentAcls []*idm.ACL
var currentRoots []string
if !wsCreated {
var err error
currentAcls, currentRoots, err = h.CommonAclsForWorkspace(ctx, workspace.UUID)
if err != nil {
service.RestError500(req, rsp, err)
return
}
} else {
// New workspace, create "workspace-path" ACLs
for _, node := range shareRequest.Room.RootNodes {
aclClient.CreateACL(ctx, &idm.CreateACLRequest{
ACL: &idm.ACL{
NodeID: node.Uuid,
WorkspaceID: workspace.UUID,
Action: &idm.ACLAction{Name: utils.ACL_WSROOT_ACTION_NAME, Value: "uuid:" + node.Uuid},
},
})
}
// For new specific CellNode, set this node as a RecycleRoot
if createdCellNode != nil {
aclClient.CreateACL(ctx, &idm.CreateACLRequest{
ACL: &idm.ACL{
NodeID: createdCellNode.Uuid,
WorkspaceID: workspace.UUID,
Action: utils.ACL_RECYCLE_ROOT,
},
})
}
}
log.Logger(ctx).Debug("Current Roots", zap.Any("crt", currentRoots))
targetAcls := h.ComputeTargetAcls(ctx, &shareRequest, workspace.UUID, readonly)
log.Logger(ctx).Debug("Share ACLS", zap.Any("current", currentAcls), zap.Any("target", targetAcls))
add, remove := h.DiffAcls(ctx, currentAcls, targetAcls)
log.Logger(ctx).Debug("Diff ACLS", zap.Any("add", add), zap.Any("remove", remove))
for _, acl := range add {
_, err := aclClient.CreateACL(ctx, &idm.CreateACLRequest{ACL: acl})
if err != nil {
log.Logger(ctx).Error("Share: Error while creating ACLs", zap.Error(err))
}
}
for _, acl := range remove {
removeQuery, _ := ptypes.MarshalAny(&idm.ACLSingleQuery{
NodeIDs: []string{acl.NodeID},
RoleIDs: []string{acl.RoleID},
WorkspaceIDs: []string{acl.WorkspaceID},
Actions: []*idm.ACLAction{acl.Action},
})
_, err := aclClient.DeleteACL(ctx, &idm.DeleteACLRequest{Query: &service2.Query{SubQueries: []*any.Any{removeQuery}}})
if err != nil {
log.Logger(ctx).Error("Share: Error while deleting ACLs", zap.Error(err))
}
}
log.Logger(ctx).Debug("Share Policies", zap.Any("before", workspace.Policies))
h.UpdatePoliciesFromAcls(ctx, workspace, currentAcls, targetAcls)
// Now update workspace
log.Logger(ctx).Debug("Updating workspace", zap.Any("workspace", workspace))
wsClient := idm.NewWorkspaceServiceClient(common.SERVICE_GRPC_NAMESPACE_+common.SERVICE_WORKSPACE, defaults.NewClient())
if _, err := wsClient.CreateWorkspace(ctx, &idm.CreateWorkspaceRequest{Workspace: workspace}); err != nil {
service.RestError500(req, rsp, err)
return
}
// Put an Audit log if this cell has been newly created
if wsCreated {
log.Auditer(ctx).Info(
fmt.Sprintf("Created cell [%s]", shareRequest.Room.Label),
log.GetAuditId(common.AUDIT_CELL_CREATE),
zap.String(common.KEY_CELL_UUID, shareRequest.Room.Uuid),
)
} else {
log.Auditer(ctx).Info(
fmt.Sprintf("Updated cell [%s]", shareRequest.Room.Label),
log.GetAuditId(common.AUDIT_CELL_UPDATE),
zap.String(common.KEY_CELL_UUID, shareRequest.Room.Uuid),
)
}
if output, err := h.WorkspaceToCellObject(ctx, workspace); err != nil {
service.RestError500(req, rsp, err)
} else {
rsp.WriteEntity(output)
}
}
// GetCell simply retrieves a shared room from its UUID.
func (h *SharesHandler) GetCell(req *restful.Request, rsp *restful.Response) {
ctx := req.Request.Context()
id := req.PathParameter("Uuid")
workspace, _, err := h.GetOrCreateWorkspace(ctx, id, idm.WorkspaceScope_ROOM, "", "", false)
if err != nil {
if errors.Parse(err.Error()).Code == 404 {
service.RestError404(req, rsp, err)
} else {
service.RestError500(req, rsp, err)
}
return
}
if output, err := h.WorkspaceToCellObject(ctx, workspace); err != nil {
service.RestError500(req, rsp, err)
} else {
rsp.WriteEntity(output)
}
}
// DeleteCell loads the workspace and its root nodes and eventually removes room root totally.
func (h *SharesHandler) DeleteCell(req *restful.Request, rsp *restful.Response) {
ctx := req.Request.Context()
id := req.PathParameter("Uuid")
ws, _, e := h.GetOrCreateWorkspace(ctx, id, idm.WorkspaceScope_ROOM, "", "", false)
if e != nil || ws == nil {
service.RestError404(req, rsp, e)
return
} else if !h.IsContextEditable(ctx, id, ws.Policies) {
service.RestError403(req, rsp, fmt.Errorf("you are not allowed to edit this room"))
return
}
currWsLabel := ws.Label
log.Logger(ctx).Debug("Delete share room", zap.Any("workspaceId", id))
// This will load the workspace and its root, and eventually remove the Room root totally
if err := h.DeleteWorkspace(ctx, idm.WorkspaceScope_ROOM, id); err != nil {
service.RestError500(req, rsp, err)
return
}
// Put an Audit log if this cell has been removed without error
log.Auditer(ctx).Info(
fmt.Sprintf("Removed cell [%s]", currWsLabel),
log.GetAuditId(common.AUDIT_CELL_DELETE),
zap.String(common.KEY_CELL_UUID, id),
)
rsp.WriteEntity(&rest.DeleteCellResponse{
Success: true,
})
}
// PutShareLink creates or updates a link to a shared item.
func (h *SharesHandler) PutShareLink(req *restful.Request, rsp *restful.Response) {
ctx := req.Request.Context()
start := time.Now()
track := func(msg string) {
log.Logger(ctx).Debug(msg, zap.Duration("t", time.Since(start)))
}
var putRequest rest.PutShareLinkRequest
if err := req.ReadEntity(&putRequest); err != nil {
service.RestError500(req, rsp, err)
return
}
link := putRequest.ShareLink
if e := h.CheckLinkRootNodes(ctx, link); e != nil {
service.RestErrorDetect(req, rsp, e)
return
}
var workspace *idm.Workspace
var user *idm.User
var err error
var create bool
aclClient := idm.NewACLServiceClient(common.SERVICE_GRPC_NAMESPACE_+common.SERVICE_ACL, defaults.NewClient())
if link.Uuid == "" {
create = true
workspace, _, err = h.GetOrCreateWorkspace(ctx, "", idm.WorkspaceScope_LINK, link.Label, link.Description, false)
track("GetOrCreateWorkspace")
for _, node := range link.RootNodes {
aclClient.CreateACL(ctx, &idm.CreateACLRequest{
ACL: &idm.ACL{
NodeID: node.Uuid,
WorkspaceID: workspace.UUID,
Action: &idm.ACLAction{Name: "workspace-path", Value: "uuid:" + node.Uuid},
},
})
}
track("CreateACL")
link.Uuid = workspace.UUID
link.LinkHash = strings.Replace(uuid.NewUUID().String(), "-", "", -1)[0:12]
} else {
workspace, create, err = h.GetOrCreateWorkspace(ctx, link.Uuid, idm.WorkspaceScope_LINK, link.Label, link.Description, true)
}
if err != nil {
service.RestError500(req, rsp, err)
return
}
if !create && !h.IsContextEditable(ctx, workspace.UUID, workspace.Policies) {
service.RestError403(req, rsp, fmt.Errorf("you are not allowed to edit this link"))
return
}
track("IsContextEditable")
// Load Hidden User
user, err = h.GetOrCreateHiddenUser(ctx, link, putRequest.PasswordEnabled, putRequest.CreatePassword)
if err != nil {
service.RestError500(req, rsp, err)
return
}
track("GetOrCreateHiddenUser")
if create {
link.UserLogin = user.Login
link.UserUuid = user.Uuid
link.PasswordRequired = putRequest.PasswordEnabled
// Update Workspace Policies to make sure it's readable by the new user
workspace.Policies = append(workspace.Policies, &service2.ResourcePolicy{
Resource: workspace.UUID,
Subject: fmt.Sprintf("user:%s", user.Login),
Action: service2.ResourcePolicyAction_READ,
Effect: service2.ResourcePolicy_allow,
})
wsClient := idm.NewWorkspaceServiceClient(common.SERVICE_GRPC_NAMESPACE_+common.SERVICE_WORKSPACE, defaults.NewClient())
wsClient.CreateWorkspace(ctx, &idm.CreateWorkspaceRequest{Workspace: workspace})
track("CreateWorkspace")
} else {
// Manage password if status was updated
storedLink := &rest.ShareLink{Uuid: link.Uuid}
LoadHashDocumentData(ctx, storedLink, []*idm.ACL{})
link.PasswordRequired = storedLink.PasswordRequired
var saveUser bool
if putRequest.PasswordEnabled && !storedLink.PasswordRequired {
user.Password = putRequest.CreatePassword
link.PasswordRequired = true
saveUser = true
} else if !putRequest.PasswordEnabled && storedLink.PasswordRequired {
user.Password = user.Login + PasswordComplexitySuffix
link.PasswordRequired = false
saveUser = true
} else if putRequest.PasswordEnabled && storedLink.PasswordRequired && putRequest.UpdatePassword != "" {
user.Password = putRequest.UpdatePassword
saveUser = true
}
if saveUser {
uCli := idm.NewUserServiceClient(common.SERVICE_GRPC_NAMESPACE_+common.SERVICE_USER, defaults.NewClient())
_, err := uCli.CreateUser(ctx, &idm.CreateUserRequest{
User: user,
})
if err != nil {
service.RestError500(req, rsp, err)
}
}
}
err = h.UpdateACLsForHiddenUser(ctx, user.Uuid, workspace.UUID, link.RootNodes, link.Permissions, !create)
track("UpdateACLsForHiddenUser")
if err != nil {
service.RestError500(req, rsp, err)
return
}
if create {
log.Auditer(ctx).Info(
fmt.Sprintf("Created share link [%s]", link.Label),
log.GetAuditId(common.AUDIT_LINK_CREATE),
zap.String(common.KEY_LINK_UUID, link.Uuid),
)
track("Auditer")
} else {
log.Auditer(ctx).Info(
fmt.Sprintf("Updated share link [%s]", link.Label),
log.GetAuditId(common.AUDIT_LINK_UPDATE),
zap.String(common.KEY_LINK_UUID, link.Uuid),
)
}
// Update HashDocument
if err := StoreHashDocument(ctx, link, putRequest.UpdateCustomHash); err != nil {
service.RestError500(req, rsp, err)
return
}
track("StoreHashDocument")
// Reload
if output, e := h.WorkspaceToShareLinkObject(ctx, workspace); e != nil {
service.RestError500(req, rsp, e)
} else {
rsp.WriteEntity(output)
}
track("WorkspaceToShareLinkObject")
}
// GetShareLink loads link information.
func (h *SharesHandler) GetShareLink(req *restful.Request, rsp *restful.Response) {
ctx := req.Request.Context()
id := req.PathParameter("Uuid")
workspace, _, err := h.GetOrCreateWorkspace(ctx, id, idm.WorkspaceScope_LINK, "", "", false)
if err != nil {
if errors.Parse(err.Error()).Code == 404 {
service.RestError404(req, rsp, err)
} else {
service.RestError500(req, rsp, err)
}
return
}
if output, err := h.WorkspaceToShareLinkObject(ctx, workspace); err == nil {
rsp.WriteEntity(output)
} else {
service.RestError500(req, rsp, err)
}
}
// DeleteShareLink deletes a link information.
func (h *SharesHandler) DeleteShareLink(req *restful.Request, rsp *restful.Response) {
ctx := req.Request.Context()
id := req.PathParameter("Uuid")
if ws, _, e := h.GetOrCreateWorkspace(ctx, id, idm.WorkspaceScope_LINK, "", "", false); e != nil || ws == nil {
service.RestError404(req, rsp, e)
return
} else if !h.IsContextEditable(ctx, id, ws.Policies) {
service.RestError403(req, rsp, fmt.Errorf("you are not allowed to edit this link"))
return
}
// Will try to load the workspace first, and throw an error if something goes wrong
if err := h.DeleteWorkspace(ctx, idm.WorkspaceScope_LINK, id); err != nil {
service.RestError500(req, rsp, err)
return
}
// Now delete associated Document in Docstore
if err := DeleteHashDocument(ctx, id); err != nil {
service.RestError500(req, rsp, err)
return
}
log.Auditer(ctx).Info(
fmt.Sprintf("Removed share link [%s]", id),
log.GetAuditId(common.AUDIT_LINK_UPDATE),
zap.String(common.KEY_LINK_UUID, id),
)
rsp.WriteEntity(&rest.DeleteShareLinkResponse{
Success: true,
})
}
// *********************************************************************************
// WorkspaceToCellObject rewrites a workspace to a Cell object by reloading its ACLs.
func (h *SharesHandler) WorkspaceToCellObject(ctx context.Context, workspace *idm.Workspace) (*rest.Cell, error) {
acls, detectedRoots, err := h.CommonAclsForWorkspace(ctx, workspace.UUID)
if err != nil {
log.Logger(ctx).Error("Error while loading common acls for workspace", zap.Error(err))
return nil, err
}
log.Logger(ctx).Debug("Detected Roots for object", zap.Any("roots", detectedRoots))
roomAcls := h.AclsToCellAcls(ctx, acls)
log.Logger(ctx).Debug("Computed roomAcls before load", zap.Any("roomAcls", roomAcls))
if err := h.LoadCellAclsObjects(ctx, roomAcls); err != nil {
log.Logger(ctx).Error("Error on loadRomAclsObjects", zap.Error(err))
return nil, err
}
rootNodes := h.LoadDetectedRootNodes(ctx, detectedRoots)
var nodesSlices []*tree.Node
for _, node := range rootNodes {
nodesSlices = append(nodesSlices, node)
}
return &rest.Cell{
Uuid: workspace.UUID,
Label: workspace.Label,
Description: workspace.Description,
RootNodes: nodesSlices,
ACLs: roomAcls,
Policies: workspace.Policies,
PoliciesContextEditable: h.IsContextEditable(ctx, workspace.UUID, workspace.Policies),
}, nil
}
func (h *SharesHandler) WorkspaceToShareLinkObject(ctx context.Context, workspace *idm.Workspace) (*rest.ShareLink, error) {
acls, detectedRoots, err := h.CommonAclsForWorkspace(ctx, workspace.UUID)
if err != nil {
return nil, err
}
shareLink := &rest.ShareLink{
Uuid: workspace.UUID,
Label: workspace.Label,
Description: workspace.Description,
Policies: workspace.Policies,
PoliciesContextEditable: h.IsContextEditable(ctx, workspace.UUID, workspace.Policies),
}
for _, rootId := range detectedRoots {
shareLink.RootNodes = append(shareLink.RootNodes, &tree.Node{Uuid: rootId})
}
if err := LoadHashDocumentData(ctx, shareLink, acls); err != nil {
return nil, err
}
shareLink.PoliciesContextEditable = h.IsContextEditable(ctx, workspace.UUID, workspace.Policies)
return shareLink, nil
}
// LoadDetectedRootNodes find actual nodes in the tree, and enrich their metadata if they appear
// in many workspaces for the current user.
func (h *SharesHandler) LoadDetectedRootNodes(ctx context.Context, detectedRoots []string) (rootNodes map[string]*tree.Node) {
rootNodes = make(map[string]*tree.Node)
router := views.NewUuidRouter(views.RouterOptions{})
metaClient := tree.NewNodeProviderClient(common.SERVICE_GRPC_NAMESPACE_+common.SERVICE_META, defaults.NewClient())
eventFilter := views.NewRouterEventFilter(views.RouterOptions{AdminView: false})
accessList, _ := utils.AccessListFromContextClaims(ctx)
for _, rootId := range detectedRoots {
request := &tree.ReadNodeRequest{Node: &tree.Node{Uuid: rootId}}
if resp, err := router.ReadNode(ctx, request); err == nil {
node := resp.Node
var multipleMeta []*tree.WorkspaceRelativePath
for _, ws := range accessList.Workspaces {
if filtered, ok := eventFilter.WorkspaceCanSeeNode(ctx, ws, resp.Node); ok {
multipleMeta = append(multipleMeta, &tree.WorkspaceRelativePath{
WsLabel: ws.Label,
WsUuid: ws.UUID,
Path: filtered.Path,
})
node = filtered
}
}
if len(multipleMeta) > 0 {
node.AppearsIn = multipleMeta
}
if metaResp, e := metaClient.ReadNode(ctx, request); e == nil {
var isRoomNode bool
if metaResp.GetNode().GetMeta("CellNode", &isRoomNode); err == nil && isRoomNode {
node.SetMeta("CellNode", true)
}
}
rootNodes[node.GetUuid()] = node.WithoutReservedMetas()
} else {
log.Logger(ctx).Debug("Share Load - Ignoring Root Node, probably not synced yet", zap.String("nodeId", rootId), zap.Error(err))
}
}
return
}
// AclsToCellAcls Rewrites a flat list of ACLs to a structured map of CellAcls (more easily usable by clients).
func (h *SharesHandler) AclsToCellAcls(ctx context.Context, acls []*idm.ACL) map[string]*rest.CellAcl {
roomAcls := make(map[string]*rest.CellAcl)
registeredRolesAcls := make(map[string]bool)
for _, acl := range acls {
id := acl.RoleID + "-" + acl.Action.Name
if _, has := registeredRolesAcls[id]; !has {
var roomAcl *rest.CellAcl
if roomAcl, has = roomAcls[acl.RoleID]; !has {
roomAcl = &rest.CellAcl{RoleId: acl.RoleID, Actions: []*idm.ACLAction{}}
roomAcls[acl.RoleID] = roomAcl
}
roomAcl.Actions = append(roomAcl.Actions, acl.Action)
registeredRolesAcls[id] = true
}
}
return roomAcls
}
// LoadCellAclsObjects loads associated users / groups / roles based on the role Ids of the acls.
func (h *SharesHandler) LoadCellAclsObjects(ctx context.Context, roomAcls map[string]*rest.CellAcl) error {
log.Logger(ctx).Debug("LoadCellAclsObjects", zap.Any("acls", roomAcls))
roleClient := idm.NewRoleServiceClient(common.SERVICE_GRPC_NAMESPACE_+common.SERVICE_ROLE, defaults.NewClient())
var roleIds []string
for _, acl := range roomAcls {
roleIds = append(roleIds, acl.RoleId)
}
roleQ, _ := ptypes.MarshalAny(&idm.RoleSingleQuery{Uuid: roleIds})
streamer, err := roleClient.SearchRole(ctx, &idm.SearchRoleRequest{Query: &service2.Query{SubQueries: []*any.Any{roleQ}}})
if err != nil {
return err
}
loadUsers := make(map[string]*idm.Role)
defer streamer.Close()
for {
resp, e := streamer.Recv()
if e != nil {
break
}
if resp == nil {
continue
}
role := resp.Role
if role.UserRole || role.GroupRole {
loadUsers[role.Uuid] = role
} else {
roomAcls[role.Uuid].Role = role
}
}
log.Logger(ctx).Debug("LoadCellAclsObjects, will search for users ?", zap.Any("acls", roomAcls), zap.Any("users", loadUsers))
if len(loadUsers) > 0 {
var subQueries []*any.Any
for roleId, _ := range loadUsers {
userQ, _ := ptypes.MarshalAny(&idm.UserSingleQuery{Uuid: roleId})
subQueries = append(subQueries, userQ)
}
userClient := idm.NewUserServiceClient(common.SERVICE_GRPC_NAMESPACE_+common.SERVICE_USER, defaults.NewClient())
stream, err := userClient.SearchUser(ctx, &idm.SearchUserRequest{Query: &service2.Query{SubQueries: subQueries}})
if err != nil {
return err
}
defer stream.Close()
for {
resp, e := stream.Recv()
if e != nil {
break
}
if resp == nil {
continue
}
object := resp.User
if object.IsGroup {
roomAcls[object.Uuid].Group = object
} else {
// Remove some unnecessary fields
object.Roles = []*idm.Role{}
if _, has := object.Attributes["preferences"]; has {
delete(object.Attributes, "preferences")
}
roomAcls[object.Uuid].User = object.WithPublicData(ctx, h.IsContextEditable(ctx, object.Uuid, object.Policies))
}
}
}
log.Logger(ctx).Debug("LoadCellAclsObjects, updated acls: ", zap.Any("acls", roomAcls))
return nil
}
// CommonAclsForWorkspace makes successive calls to ACL service to get all ACLs for a given workspace.
func (h *SharesHandler) CommonAclsForWorkspace(ctx context.Context, workspaceId string) (result []*idm.ACL, detectedRoots []string, err error) {
result, err = utils.GetACLsForWorkspace(ctx, []string{workspaceId}, utils.ACL_READ, utils.ACL_WRITE, utils.ACL_POLICY)
if err != nil {
return
}
roots := make(map[string]string)
for _, acl := range result {
if acl.NodeID == "" {
continue
}
if _, has := roots[acl.NodeID]; !has {
roots[acl.NodeID] = acl.NodeID
detectedRoots = append(detectedRoots, acl.NodeID)
}
}
return
}
// DiffAcls compares to slices of ACLs on their RoleID and Action and
// returns slices of Acls to add and to remove.
func (h *SharesHandler) DiffAcls(ctx context.Context, initial []*idm.ACL, newOnes []*idm.ACL) (add []*idm.ACL, remove []*idm.ACL) {
equals := func(a *idm.ACL, b *idm.ACL) bool {
return a.NodeID == b.NodeID && a.RoleID == b.RoleID && a.Action.Name == b.Action.Name && a.Action.Value == b.Action.Value
}
diff := func(lefts []*idm.ACL, rights []*idm.ACL) (result []*idm.ACL) {
for _, left := range lefts {
has := false
for _, right := range rights {
if equals(left, right) {
has = true
break
}
}
if !has {
result = append(result, left)
}
}
return
}
remove = diff(initial, newOnes)
add = diff(newOnes, initial)
return
}
// DiffReadRoles detects the roles that have been globally added or removed, whatever the node.
func (h *SharesHandler) DiffReadRoles(ctx context.Context, initial []*idm.ACL, newOnes []*idm.ACL) (add []string, remove []string) {
filter := func(acls []*idm.ACL) (roles map[string]bool) {
roles = make(map[string]bool)
for _, acl := range acls {
if acl.Action.Name == utils.ACL_READ.Name {
roles[acl.RoleID] = true
}
}
return
}
diff := func(lefts map[string]bool, rights map[string]bool) (result []string) {
for left, _ := range lefts {
if _, has := rights[left]; !has {
result = append(result, left)
}
}
return
}
initialRoles := filter(initial)
newRoles := filter(newOnes)
remove = diff(initialRoles, newRoles)
add = diff(newRoles, initialRoles)
return
}
// ComputeTargetAcls create ACL objects that should be applied for this cell.
func (h *SharesHandler) ComputeTargetAcls(ctx context.Context, shareRequest *rest.PutCellRequest, workspaceId string, readonly bool) []*idm.ACL {
claims := ctx.Value(claim.ContextKey).(claim.Claims)
userId, _ := claims.DecodeUserUuid()
var targetAcls []*idm.ACL
for _, node := range shareRequest.Room.RootNodes {
userInAcls := false
for _, acl := range shareRequest.Room.ACLs {
for _, action := range acl.Actions {
// Recheck just in case
if readonly && action.Name == utils.ACL_WRITE.Name {
continue
}
targetAcls = append(targetAcls, &idm.ACL{
NodeID: node.Uuid,
RoleID: acl.RoleId,
WorkspaceID: workspaceId,
Action: action,
})
}
if acl.RoleId == userId {
userInAcls = true
}
}
// Make sure that the current user has at least READ permissions
if !userInAcls {
targetAcls = append(targetAcls, &idm.ACL{
NodeID: node.Uuid,
RoleID: userId,
WorkspaceID: workspaceId,
Action: utils.ACL_READ,
})
if !readonly {
targetAcls = append(targetAcls, &idm.ACL{
NodeID: node.Uuid,
RoleID: userId,
WorkspaceID: workspaceId,
Action: utils.ACL_WRITE,
})
}
}
}
return targetAcls
}
// UpdatePoliciesFromAcls recomputes the required policies from acl changes.
func (h *SharesHandler) UpdatePoliciesFromAcls(ctx context.Context, workspace *idm.Workspace, initial []*idm.ACL, target []*idm.ACL) bool {
var output []*service2.ResourcePolicy
initialPolicies := workspace.Policies
resourceId := workspace.UUID
addReads, removeReads := h.DiffReadRoles(ctx, initial, target)
ignoreAdds := make(map[string]bool)
for _, p := range initialPolicies {
toRemove := false
for _, roleId := range removeReads {
if p.Subject == "role:"+roleId && p.Action == service2.ResourcePolicyAction_READ {
toRemove = true
break
}
}
if p.Action == service2.ResourcePolicyAction_READ && strings.HasPrefix(p.Subject, "role:") {
ignoreAdds[strings.TrimPrefix(p.Subject, "role:")] = true
}
if !toRemove {
output = append(output, p)
}
}
for _, roleAdd := range addReads {
if _, has := ignoreAdds[roleAdd]; has { // Already in the list
continue
}
output = append(output, &service2.ResourcePolicy{
Subject: "role:" + roleAdd,
Resource: resourceId,
Action: service2.ResourcePolicyAction_READ,
Effect: service2.ResourcePolicy_allow,
})
}
workspace.Policies = output
return true
}
// ParseRootNodes reads the request property to either create a new node using the "rooms" Virtual node,
// or just verify that the root nodes are not empty.
func (h *SharesHandler) ParseRootNodes(ctx context.Context, shareRequest *rest.PutCellRequest) (error, *tree.Node, bool) {
var createdNode *tree.Node
router := views.NewStandardRouter(views.RouterOptions{})
for i, n := range shareRequest.Room.RootNodes {
r, e := router.ReadNode(ctx, &tree.ReadNodeRequest{Node: n})
if e != nil {
return e, nil, false
}
// If the virtual root is responded, it may miss the UUID ! Set up manually here
if r.Node.Uuid == "" {
r.Node.Uuid = n.Uuid
}
shareRequest.Room.RootNodes[i] = r.Node
}
if shareRequest.CreateEmptyRoot {
manager := views.GetVirtualNodesManager()
internalRouter := views.NewStandardRouter(views.RouterOptions{WatchRegistry: false, AdminView: true})
if root, exists := manager.ByUuid("cells"); exists {
parentNode, err := manager.ResolveInContext(ctx, root, internalRouter.GetClientsPool(), true)
if err != nil {
return err, nil, false
}
index := 0
labelSlug := slug.Make(shareRequest.Room.Label)
baseSlug := labelSlug
for {
if existingResp, err := internalRouter.ReadNode(ctx, &tree.ReadNodeRequest{Node: &tree.Node{Path: parentNode.Path + "/" + labelSlug}}); err == nil && existingResp.Node != nil {
index++
labelSlug = fmt.Sprintf("%s-%v", baseSlug, index)
} else {
break
}
}
createResp, err := internalRouter.CreateNode(ctx, &tree.CreateNodeRequest{
Node: &tree.Node{Path: parentNode.Path + "/" + labelSlug},
})
if err != nil {
log.Logger(ctx).Error("share/cells : create empty root", zap.Error(err))
return err, nil, false
}
// Update node meta
createResp.Node.SetMeta("CellNode", true)
metaClient := tree.NewNodeReceiverClient(common.SERVICE_GRPC_NAMESPACE_+common.SERVICE_META, defaults.NewClient())
metaClient.CreateNode(ctx, &tree.CreateNodeRequest{Node: createResp.Node})
shareRequest.Room.RootNodes = append(shareRequest.Room.RootNodes, createResp.Node)
createdNode = createResp.Node
} else {
return errors.InternalServerError(common.SERVICE_SHARE, "Wrong configuration, missing rooms virtual node"), nil, false
}
}
if len(shareRequest.Room.RootNodes) == 0 {
return errors.BadRequest(common.SERVICE_SHARE, "Wrong configuration, missing RootNodes in CellRequest"), nil, false
}
// First check of incoming ACLs
var hasReadonly bool
for _, root := range shareRequest.Room.RootNodes {
if root.GetStringMeta(common.META_FLAG_READONLY) != "" {
hasReadonly = true
}
}
if hasReadonly {
for _, a := range shareRequest.Room.GetACLs() {
for _, action := range a.GetActions() {
if action.Name == utils.ACL_WRITE.Name {
return errors.Forbidden(common.SERVICE_SHARE, "One of the resource you are sharing is readonly. You cannot assign write permission on this Cell."), nil, true
}
}
}
}
log.Logger(ctx).Debug("ParseRootNodes", zap.Any("r", shareRequest.Room.RootNodes), zap.Bool("readonly", hasReadonly))
return nil, createdNode, hasReadonly
}
// DeleteRootNodeRecursively loads all children of a root node and delete them, including the
// .pydio hidden files when they are folders.
func (h *SharesHandler) DeleteRootNodeRecursively(ctx context.Context, roomNode *tree.Node) error {
manager := views.GetVirtualNodesManager()
router := views.NewStandardRouter(views.RouterOptions{WatchRegistry: false, AdminView: true})
if root, exists := manager.ByUuid("cells"); exists {
parentNode, err := manager.ResolveInContext(ctx, root, router.GetClientsPool(), true)
if err != nil {
return err
}
realNode := &tree.Node{Path: parentNode.Path + "/" + strings.TrimRight(roomNode.Path, "/")}
// Now list all children and delete them all
stream, err := router.ListNodes(ctx, &tree.ListNodesRequest{Node: realNode, Recursive: true})
if err != nil {
return err
}
defer stream.Close()
for {
resp, e := stream.Recv()
if e != nil {
break
}
if resp == nil {
continue
}
if !resp.Node.IsLeaf() {
resp.Node.Path += "/" + common.PYDIO_SYNC_HIDDEN_FILE_META
}
log.Logger(ctx).Debug("Deleting room node associated to workspace", realNode.Zap())
if _, err := router.DeleteNode(ctx, &tree.DeleteNodeRequest{Node: resp.Node}); err != nil {
log.Logger(ctx).Error("Error while deleting Room Node children", zap.Error(err))
//return err // Continue anyway?
}
}
if _, err := router.DeleteNode(ctx, &tree.DeleteNodeRequest{Node: &tree.Node{Path: realNode.Path + "/" + common.PYDIO_SYNC_HIDDEN_FILE_META}}); err != nil {
return err
}
}
return nil
}
// GetOrCreateWorkspace finds a workspace by its Uuid or creates it with the current user ResourcePolicies
// if it does not already exist.
func (h *SharesHandler) GetOrCreateWorkspace(ctx context.Context, wsUuid string, scope idm.WorkspaceScope, label string, description string, updateIfNeeded bool) (*idm.Workspace, bool, error) {
var workspace *idm.Workspace
log.Logger(ctx).Debug("GetOrCreateWorkspace", zap.String("wsUuid", wsUuid), zap.Any("scope", scope.String()), zap.Bool("updateIfNeeded", updateIfNeeded))
wsClient := idm.NewWorkspaceServiceClient(common.SERVICE_GRPC_NAMESPACE_+common.SERVICE_WORKSPACE, defaults.NewClient())
var create bool
if wsUuid == "" {
if label == "" {
return nil, false, errors.BadRequest(common.SERVICE_SHARE, "please provide a non-empty label for this workspace")
}
// Create Workspace
wsUuid = uuid.NewUUID().String()
wsResp, err := wsClient.CreateWorkspace(ctx, &idm.CreateWorkspaceRequest{Workspace: &idm.Workspace{
UUID: wsUuid,
Label: label,
Description: description,
Scope: scope,
Slug: slug.Make(label),
Policies: h.OwnerResourcePolicies(ctx, wsUuid),
}})
if err != nil {
return workspace, false, err
}
workspace = wsResp.Workspace
create = true
} else {
q, _ := ptypes.MarshalAny(&idm.WorkspaceSingleQuery{
Uuid: wsUuid,
Scope: scope,
})
wsStream, err := wsClient.SearchWorkspace(ctx, &idm.SearchWorkspaceRequest{
Query: &service2.Query{
SubQueries: []*any.Any{q},
},
})
if err != nil {
return workspace, false, err
}
defer wsStream.Close()
for {
wsResp, er := wsStream.Recv()
if er != nil {
break
}
workspace = wsResp.Workspace
}
if workspace == nil {
return workspace, false, errors.NotFound(common.SERVICE_SHARE, "Cannot find workspace with Uuid "+wsUuid)
}