-
Notifications
You must be signed in to change notification settings - Fork 113
/
shares.go
1548 lines (1369 loc) · 52.4 KB
/
shares.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 2018-2021 CERN
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// In applying this license, CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
package shares
import (
"bytes"
"context"
"encoding/json"
"fmt"
"mime"
"net/http"
"path"
"strconv"
"strings"
"text/template"
"time"
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
grouppb "github.com/cs3org/go-cs3apis/cs3/identity/group/v1beta1"
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
collaboration "github.com/cs3org/go-cs3apis/cs3/sharing/collaboration/v1beta1"
link "github.com/cs3org/go-cs3apis/cs3/sharing/link/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
"github.com/go-chi/chi/v5"
"github.com/rs/zerolog"
"google.golang.org/grpc/metadata"
"google.golang.org/protobuf/types/known/fieldmaskpb"
"github.com/cs3org/reva/v2/internal/http/services/owncloud/ocs/config"
"github.com/cs3org/reva/v2/internal/http/services/owncloud/ocs/conversions"
"github.com/cs3org/reva/v2/internal/http/services/owncloud/ocs/response"
"github.com/cs3org/reva/v2/pkg/appctx"
ctxpkg "github.com/cs3org/reva/v2/pkg/ctx"
"github.com/cs3org/reva/v2/pkg/publicshare"
"github.com/cs3org/reva/v2/pkg/rgrpc/todo/pool"
"github.com/cs3org/reva/v2/pkg/share"
sharecache "github.com/cs3org/reva/v2/pkg/share/cache"
warmupreg "github.com/cs3org/reva/v2/pkg/share/cache/warmup/registry"
"github.com/cs3org/reva/v2/pkg/storage/cache"
"github.com/cs3org/reva/v2/pkg/storage/utils/templates"
"github.com/cs3org/reva/v2/pkg/storagespace"
"github.com/cs3org/reva/v2/pkg/utils"
"github.com/jellydator/ttlcache/v2"
"github.com/pkg/errors"
)
const (
storageIDPrefix string = "shared::"
_resharingDefault bool = false
)
var (
errParsingSpaceReference = errors.New("could not parse space reference")
)
// Handler implements the shares part of the ownCloud sharing API
type Handler struct {
gatewayAddr string
machineAuthAPIKey string
storageRegistryAddr string
publicURL string
sharePrefix string
homeNamespace string
skipUpdatingExistingSharesMountpoints bool
additionalInfoTemplate *template.Template
userIdentifierCache *ttlcache.Cache
statCache cache.StatCache
deniable bool
resharing bool
getClient GatewayClientGetter
}
// we only cache the minimal set of data instead of the full user metadata
type userIdentifiers struct {
DisplayName string
Username string
Mail string
}
type ocsError struct {
Error error
Code int
Message string
}
func getCacheWarmupManager(c *config.Config) (sharecache.Warmup, error) {
if f, ok := warmupreg.NewFuncs[c.CacheWarmupDriver]; ok {
return f(c.CacheWarmupDrivers[c.CacheWarmupDriver])
}
return nil, fmt.Errorf("driver not found: %s", c.CacheWarmupDriver)
}
// GatewayClientGetter is the function being used to retrieve a gateway client instance
type GatewayClientGetter func() (gateway.GatewayAPIClient, error)
// Init initializes this and any contained handlers
func (h *Handler) Init(c *config.Config) {
h.gatewayAddr = c.GatewaySvc
h.machineAuthAPIKey = c.MachineAuthAPIKey
h.storageRegistryAddr = c.StorageregistrySvc
h.publicURL = c.Config.Host
h.sharePrefix = c.SharePrefix
h.homeNamespace = c.HomeNamespace
h.skipUpdatingExistingSharesMountpoints = c.SkipUpdatingExistingSharesMountpoints
h.additionalInfoTemplate, _ = template.New("additionalInfo").Parse(c.AdditionalInfoAttribute)
h.userIdentifierCache = ttlcache.NewCache()
_ = h.userIdentifierCache.SetTTL(time.Second * time.Duration(c.UserIdentifierCacheTTL))
h.deniable = c.EnableDenials
h.resharing = resharing(c)
h.statCache = cache.GetStatCache(c.StatCacheStore, c.StatCacheNodes, c.StatCacheDatabase, "stat", time.Duration(c.StatCacheTTL)*time.Second, c.StatCacheSize)
if c.CacheWarmupDriver != "" {
cwm, err := getCacheWarmupManager(c)
if err == nil {
go h.startCacheWarmup(cwm)
}
}
h.getClient = h.getPoolClient
}
// InitWithGetter initializes the handler and adds the clientGetter
func (h *Handler) InitWithGetter(c *config.Config, clientGetter GatewayClientGetter) {
h.Init(c)
h.getClient = clientGetter
}
func (h *Handler) startCacheWarmup(c sharecache.Warmup) {
time.Sleep(2 * time.Second)
infos, err := c.GetResourceInfos()
if err != nil {
return
}
for _, r := range infos {
key := h.statCache.GetKey(r.Owner, &provider.Reference{ResourceId: r.Id}, []string{}, []string{})
_ = h.statCache.PushToCache(key, r)
}
}
func (h *Handler) extractReference(r *http.Request) (provider.Reference, error) {
var ref provider.Reference
// NOTE: space_ref is deprecated and will be removed in ~2 weeks (1.6.22)
sr := r.FormValue("space_ref")
if sr != "" {
return storagespace.ParseReference(sr)
}
p, id := r.FormValue("path"), r.FormValue("space")
if p == "" && id == "" {
return ref, errors.New("need path or space to extract reference")
}
if p != "" {
u := ctxpkg.ContextMustGetUser(r.Context())
ref.Path = path.Join(h.getHomeNamespace(u), p)
}
if id != "" {
rid, err := storagespace.ParseID(id)
if err != nil {
return ref, err
}
ref.ResourceId = &rid
}
return ref, nil
}
// CreateShare handles POST requests on /apps/files_sharing/api/v1/shares
func (h *Handler) CreateShare(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
shareType, err := strconv.Atoi(r.FormValue("shareType"))
if err != nil {
response.WriteOCSError(w, r, response.MetaBadRequest.StatusCode, "shareType must be an integer", nil)
return
}
// get user permissions on the shared file
client, err := h.getClient()
if err != nil {
response.WriteOCSError(w, r, response.MetaServerError.StatusCode, "error getting grpc gateway client", err)
return
}
ref, err := h.extractReference(r)
if err != nil {
response.WriteOCSError(w, r, response.MetaBadRequest.StatusCode, errParsingSpaceReference.Error(), errParsingSpaceReference)
return
}
sublog := appctx.GetLogger(ctx).With().Interface("ref", ref).Logger()
statReq := provider.StatRequest{Ref: &ref, FieldMask: &fieldmaskpb.FieldMask{Paths: []string{"space"}}}
statRes, err := client.Stat(ctx, &statReq)
if err != nil {
sublog.Debug().Err(err).Msg("CreateShare: error on stat call")
response.WriteOCSError(w, r, response.MetaServerError.StatusCode, "missing resource information", fmt.Errorf("error getting resource information"))
return
}
if statRes.Status.Code != rpc.Code_CODE_OK {
switch statRes.Status.Code {
case rpc.Code_CODE_NOT_FOUND:
response.WriteOCSData(w, r, response.MetaPathNotFound, nil, nil)
case rpc.Code_CODE_PERMISSION_DENIED:
response.WriteOCSError(w, r, http.StatusNotFound, "No share permission", nil)
default:
sublog.Error().Interface("status", statRes.Status).Msg("CreateShare: stat failed")
w.WriteHeader(http.StatusInternalServerError)
}
return
}
// check that this is a valid share
if statRes.Info.Id.OpaqueId == statRes.Info.Id.SpaceId &&
statRes.GetInfo().GetSpace().GetSpaceType() == "personal" &&
(shareType != int(conversions.ShareTypeSpaceMembershipUser) && shareType != int(conversions.ShareTypeSpaceMembershipGroup)) {
response.WriteOCSError(w, r, http.StatusBadRequest, "Can not share space root", nil)
return
}
// check user has share permissions
if !conversions.RoleFromResourcePermissions(statRes.Info.PermissionSet, false).OCSPermissions().Contain(conversions.PermissionShare) {
response.WriteOCSError(w, r, http.StatusNotFound, "No share permission", nil)
return
}
reqRole, reqPermissions := r.FormValue("role"), r.FormValue("permissions")
switch shareType {
case int(conversions.ShareTypeUser), int(conversions.ShareTypeGroup):
// user collaborations default to Manager (=all permissions)
role, val, ocsErr := h.extractPermissions(reqRole, reqPermissions, statRes.Info, conversions.NewManagerRole())
if ocsErr != nil {
response.WriteOCSError(w, r, ocsErr.Code, ocsErr.Message, ocsErr.Error)
return
}
var share *collaboration.Share
if shareType == int(conversions.ShareTypeUser) {
share, ocsErr = h.createUserShare(w, r, statRes.Info, role, val)
} else {
share, ocsErr = h.createGroupShare(w, r, statRes.Info, role, val)
}
if ocsErr != nil {
response.WriteOCSError(w, r, ocsErr.Code, ocsErr.Message, ocsErr.Error)
return
}
s, err := conversions.CS3Share2ShareData(ctx, share)
if err != nil {
response.WriteOCSError(w, r, response.MetaServerError.StatusCode, "error mapping share data", err)
return
}
h.addFileInfo(ctx, s, statRes.Info)
h.mapUserIds(ctx, client, s)
if !h.skipUpdatingExistingSharesMountpoints {
status, msg, err := h.updateExistingShareMountpoints(ctx, shareType, share, statRes.Info, client)
if status != response.MetaOK.StatusCode {
response.WriteOCSError(w, r, status, msg, err)
return
}
}
response.WriteOCSSuccess(w, r, s)
case int(conversions.ShareTypePublicLink):
// public links default to read only
_, _, ocsErr := h.extractPermissions(reqRole, reqPermissions, statRes.Info, conversions.NewViewerRole(h.resharing))
if ocsErr != nil && ocsErr.Error != conversions.ErrZeroPermission {
response.WriteOCSError(w, r, http.StatusNotFound, "No share permission", nil)
return
}
share, ocsErr := h.createPublicLinkShare(w, r, statRes.Info)
if ocsErr != nil {
response.WriteOCSError(w, r, ocsErr.Code, ocsErr.Message, ocsErr.Error)
return
}
s := conversions.PublicShare2ShareData(share, r, h.publicURL)
h.addFileInfo(ctx, s, statRes.Info)
h.mapUserIds(ctx, client, s)
response.WriteOCSSuccess(w, r, s)
case int(conversions.ShareTypeFederatedCloudShare):
// federated shares default to read only
if role, val, err := h.extractPermissions(reqRole, reqPermissions, statRes.Info, conversions.NewViewerRole(h.resharing)); err == nil {
h.createFederatedCloudShare(w, r, statRes.Info, role, val)
}
case int(conversions.ShareTypeSpaceMembershipUser), int(conversions.ShareTypeSpaceMembershipGroup):
switch reqRole {
// Note: we convert viewer and editor roles to spaceviewer and spaceditor to keep backwards compatibility
// we can remove this switch when this behaviour is no longer wanted.
case conversions.RoleViewer:
reqRole = conversions.RoleSpaceViewer
case conversions.RoleEditor:
reqRole = conversions.RoleSpaceEditor
}
if role, val, err := h.extractPermissions(reqRole, reqPermissions, statRes.Info, conversions.NewSpaceViewerRole()); err == nil {
switch role.Name {
case conversions.RoleManager, conversions.RoleSpaceEditor, conversions.RoleSpaceViewer:
h.addSpaceMember(w, r, statRes.Info, role, val)
default:
response.WriteOCSError(w, r, response.MetaBadRequest.StatusCode, "invalid role for space member", nil)
return
}
}
default:
response.WriteOCSError(w, r, response.MetaBadRequest.StatusCode, "unknown share type", nil)
}
}
func (h *Handler) updateExistingShareMountpoints(ctx context.Context, shareType int, share *collaboration.Share, info *provider.ResourceInfo, client gateway.GatewayAPIClient) (int, string, error) {
if shareType == int(conversions.ShareTypeUser) {
res, err := client.GetUser(ctx, &userpb.GetUserRequest{
UserId: &userpb.UserId{
OpaqueId: share.Grantee.GetUserId().GetOpaqueId(),
},
})
if err != nil {
return response.MetaServerError.StatusCode, "could not look up user", err
}
if res.GetStatus().GetCode() != rpc.Code_CODE_OK {
return response.MetaServerError.StatusCode, "get user call failed", nil
}
if res.User == nil {
return response.MetaServerError.StatusCode, "grantee not found", nil
}
// Get auth
granteeCtx := ctxpkg.ContextSetUser(context.Background(), res.User)
authRes, err := client.Authenticate(granteeCtx, &gateway.AuthenticateRequest{
Type: "machine",
ClientId: res.User.Username,
ClientSecret: h.machineAuthAPIKey,
})
if err != nil {
return response.MetaServerError.StatusCode, "could not do machine authentication", err
}
if authRes.GetStatus().GetCode() != rpc.Code_CODE_OK {
return response.MetaServerError.StatusCode, "machine authentication failed", nil
}
granteeCtx = metadata.AppendToOutgoingContext(granteeCtx, ctxpkg.TokenHeader, authRes.Token)
lrs, ocsResponse := getSharesList(granteeCtx, client)
if ocsResponse != nil {
return ocsResponse.OCS.Meta.StatusCode, ocsResponse.OCS.Meta.Message, nil
}
for _, s := range lrs.Shares {
if s.GetShare().GetId() != share.Id && s.State == collaboration.ShareState_SHARE_STATE_ACCEPTED && utils.ResourceIDEqual(s.Share.ResourceId, info.GetId()) {
updateRequest := &collaboration.UpdateReceivedShareRequest{
Share: &collaboration.ReceivedShare{
Share: share,
MountPoint: s.MountPoint,
State: collaboration.ShareState_SHARE_STATE_ACCEPTED,
},
UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"state", "mount_point"}},
}
shareRes, err := client.UpdateReceivedShare(granteeCtx, updateRequest)
if err != nil || shareRes.Status.Code != rpc.Code_CODE_OK {
return response.MetaServerError.StatusCode, "grpc update received share request failed", err
}
}
}
}
return response.MetaOK.StatusCode, "", nil
}
func (h *Handler) extractPermissions(reqRole string, reqPermissions string, ri *provider.ResourceInfo, defaultPermissions *conversions.Role) (*conversions.Role, []byte, *ocsError) {
var role *conversions.Role
// the share role overrides the requested permissions
if reqRole != "" {
role = conversions.RoleFromName(reqRole, h.resharing)
}
// if the role is unknown - fall back to reqPermissions or defaultPermissions
if role == nil || role.Name == conversions.RoleUnknown {
// map requested permissions
if reqPermissions == "" {
// TODO default link vs user share
role = defaultPermissions
} else {
pint, err := strconv.Atoi(reqPermissions)
if err != nil {
return nil, nil, &ocsError{
Code: response.MetaBadRequest.StatusCode,
Message: "permissions must be an integer",
Error: err,
}
}
perm, err := conversions.NewPermissions(pint)
if err != nil {
if err == conversions.ErrPermissionNotInRange {
return nil, nil, &ocsError{
Code: http.StatusNotFound,
Message: err.Error(),
Error: err,
}
}
return nil, nil, &ocsError{
Code: response.MetaBadRequest.StatusCode,
Message: err.Error(),
Error: err,
}
}
role = conversions.RoleFromOCSPermissions(perm)
}
}
permissions := role.OCSPermissions()
if ri != nil && ri.Type == provider.ResourceType_RESOURCE_TYPE_FILE && permissions != conversions.PermissionInvalid {
// Single file shares should never have delete or create permissions
permissions &^= conversions.PermissionCreate
permissions &^= conversions.PermissionDelete
if permissions == conversions.PermissionInvalid {
return nil, nil, &ocsError{
Code: response.MetaBadRequest.StatusCode,
Message: "Cannot set the requested share permissions",
Error: errors.New("cannot set the requested share permissions"),
}
}
role = conversions.RoleFromOCSPermissions(permissions)
}
if !sufficientPermissions(ri.PermissionSet, role.CS3ResourcePermissions(), false) && role.Name != conversions.RoleDenied {
return nil, nil, &ocsError{
Code: http.StatusNotFound,
Message: "Cannot set the requested share permissions",
Error: errors.New("cannot set the requested share permissions"),
}
}
if role.Name == conversions.RoleDenied {
switch {
case !h.deniable:
return nil, nil, &ocsError{
Code: http.StatusBadRequest,
Message: "Cannot set the requested share permissions: denials are not enabled on this api",
Error: errors.New("Cannot set the requested share permissions: denials are not enabled on this api"),
}
case ri.Type != provider.ResourceType_RESOURCE_TYPE_CONTAINER:
return nil, nil, &ocsError{
Code: http.StatusBadRequest,
Message: "Cannot set the requested share permissions: deny access only works on folders",
Error: errors.New("Cannot set the requested share permissions: deny access only works on folders"),
}
case !ri.PermissionSet.DenyGrant:
// add a deny permission only if the user has the grant to deny (ResourcePermissions.DenyGrant == true)
return nil, nil, &ocsError{
Code: http.StatusForbidden,
Message: "Cannot set the requested share permissions: no deny grant on resource",
Error: errors.New("Cannot set the requested share permissions: no deny grant on resource"),
}
}
}
roleMap := map[string]string{"name": role.Name}
val, err := json.Marshal(roleMap)
if err != nil {
return nil, nil, &ocsError{
Code: response.MetaServerError.StatusCode,
Message: "could not encode role",
Error: err,
}
}
return role, val, nil
}
// PublicShareContextName represent cross boundaries context for the name of the public share
type PublicShareContextName string
// GetShare handles GET requests on /apps/files_sharing/api/v1/shares/(shareid)
func (h *Handler) GetShare(w http.ResponseWriter, r *http.Request) {
var share *conversions.ShareData
var resourceID *provider.ResourceId
shareID := chi.URLParam(r, "shareid")
ctx := r.Context()
sublog := appctx.GetLogger(ctx).With().Str("shareID", shareID).Logger()
client, err := pool.GetGatewayServiceClient(h.gatewayAddr)
if err != nil {
response.WriteOCSError(w, r, response.MetaServerError.StatusCode, "error getting grpc gateway client", err)
return
}
sublog.Debug().Msg("get public share by id")
psRes, err := client.GetPublicShare(r.Context(), &link.GetPublicShareRequest{
Ref: &link.PublicShareReference{
Spec: &link.PublicShareReference_Id{
Id: &link.PublicShareId{
OpaqueId: shareID,
},
},
},
})
// FIXME: the backend is returning an err when the public share is not found
// the below code can be uncommented once error handling is normalized
// to return Code_CODE_NOT_FOUND when a public share was not found
/*
if err != nil {
response.WriteOCSError(w, r, response.MetaServerError.StatusCode, "error making GetPublicShare grpc request", err)
return
}
if psRes.Status.Code != rpc.Code_CODE_OK && psRes.Status.Code != rpc.Code_CODE_NOT_FOUND {
logger.Error().Err(err).Msgf("grpc get public share request failed, code: %v", psRes.Status.Code.String)
response.WriteOCSError(w, r, response.MetaServerError.StatusCode, "grpc get public share request failed", err)
return
}
*/
if err == nil && psRes.GetShare() != nil {
share = conversions.PublicShare2ShareData(psRes.Share, r, h.publicURL)
resourceID = psRes.Share.ResourceId
}
var receivedshare *collaboration.ReceivedShare
if share == nil {
// check if we have a user share
sublog.Debug().Msg("get received user share by id")
uRes, err := client.GetReceivedShare(r.Context(), &collaboration.GetReceivedShareRequest{
Ref: &collaboration.ShareReference{
Spec: &collaboration.ShareReference_Id{
Id: &collaboration.ShareId{
OpaqueId: shareID,
},
},
},
})
if err == nil && uRes.GetShare() != nil {
receivedshare = uRes.Share
resourceID = uRes.Share.Share.ResourceId
share, err = conversions.CS3Share2ShareData(ctx, uRes.Share.Share)
if err != nil {
response.WriteOCSError(w, r, response.MetaServerError.StatusCode, "error mapping share data", err)
return
}
}
}
if share == nil {
// check if we have a user share
sublog.Debug().Msg("get user share by id")
uRes, err := client.GetShare(r.Context(), &collaboration.GetShareRequest{
Ref: &collaboration.ShareReference{
Spec: &collaboration.ShareReference_Id{
Id: &collaboration.ShareId{
OpaqueId: shareID,
},
},
},
})
// FIXME: the backend is returning an err when the public share is not found
// the below code can be uncommented once error handling is normalized
// to return Code_CODE_NOT_FOUND when a public share was not found
/*
if err != nil {
response.WriteOCSError(w, r, response.MetaServerError.StatusCode, "error making GetShare grpc request", err)
return
}
if uRes.Status.Code != rpc.Code_CODE_OK && uRes.Status.Code != rpc.Code_CODE_NOT_FOUND {
logger.Error().Err(err).Msgf("grpc get user share request failed, code: %v", uRes.Status.Code)
response.WriteOCSError(w, r, response.MetaServerError.StatusCode, "grpc get user share request failed", err)
return
}
*/
if err == nil && uRes.GetShare() != nil {
resourceID = uRes.Share.ResourceId
share, err = conversions.CS3Share2ShareData(ctx, uRes.Share)
if err != nil {
response.WriteOCSError(w, r, response.MetaServerError.StatusCode, "error mapping share data", err)
return
}
}
}
if share == nil {
sublog.Debug().Msg("no share found with this id")
response.WriteOCSError(w, r, response.MetaNotFound.StatusCode, "share not found", nil)
return
}
info, status, err := h.getResourceInfoByID(ctx, client, resourceID)
if err != nil {
sublog.Error().Err(err).Msg("error mapping share data")
response.WriteOCSError(w, r, response.MetaServerError.StatusCode, "error mapping share data", err)
return
}
if status.Code != rpc.Code_CODE_OK {
sublog.Error().Err(err).Str("status", status.Code.String()).Msg("error mapping share data")
response.WriteOCSError(w, r, response.MetaServerError.StatusCode, "error mapping share data", err)
return
}
h.addFileInfo(ctx, share, info)
h.mapUserIds(ctx, client, share)
if receivedshare != nil && receivedshare.State == collaboration.ShareState_SHARE_STATE_ACCEPTED {
// only accepted shares can be accessed when jailing users into their home.
// in this case we cannot stat shared resources that are outside the users home (/home),
// the path (/users/u-u-i-d/foo) will not be accessible
// in a global namespace we can access the share using the full path
// in a jailed namespace we have to point to the mount point in the users /Shares Jail
// - needed for oc10 hot migration
// or use the /dav/spaces/<space id> endpoint?
// list /Shares and match fileids with list of received shares
// - only works for a /Shares folder jail
// - does not work for freely mountable shares as in oc10 because we would need to iterate over the whole tree, there is no listing of mountpoints, yet
// can we return the mountpoint when the gateway resolves the listing of shares?
// - no, the gateway only sees the same list any has the same options as the ocs service
// - we would need to have a list of mountpoints for the shares -> owncloudstorageprovider for hot migration migration
// best we can do for now is stat the /Shares Jail if it is set and return those paths
// if we are in a jail and the current share has been accepted use the stat from the share jail
// Needed because received shares can be jailed in a folder in the users home
if h.sharePrefix != "/" {
// if we have a mount point use it to build the path
if receivedshare.MountPoint != nil && receivedshare.MountPoint.Path != "" {
// override path with info from share jail
share.FileTarget = path.Join(h.sharePrefix, receivedshare.MountPoint.Path)
share.Path = path.Join(h.sharePrefix, receivedshare.MountPoint.Path)
} else {
share.FileTarget = path.Join(h.sharePrefix, path.Base(info.Path))
share.Path = path.Join(h.sharePrefix, path.Base(info.Path))
}
} else {
share.FileTarget = info.Path
share.Path = info.Path
}
} else {
// not accepted shares need their Path jailed to make the testsuite happy
if h.sharePrefix != "/" {
share.Path = path.Join("/", path.Base(info.Path))
}
}
response.WriteOCSSuccess(w, r, []*conversions.ShareData{share})
}
// UpdateShare handles PUT requests on /apps/files_sharing/api/v1/shares/(shareid)
func (h *Handler) UpdateShare(w http.ResponseWriter, r *http.Request) {
shareID := chi.URLParam(r, "shareid")
// FIXME: isPublicShare is already doing a GetShare and GetPublicShare,
// we should just reuse that object when doing updates
if share, ok := h.isPublicShare(r, shareID); ok {
h.updatePublicShare(w, r, share)
return
}
if share, ok := h.isUserShare(r, shareID); ok {
h.updateShare(w, r, share) // TODO PUT is used with incomplete data to update a share}
return
}
response.WriteOCSError(w, r, response.MetaNotFound.StatusCode, "cannot find share", nil)
}
func (h *Handler) updateShare(w http.ResponseWriter, r *http.Request, share *collaboration.Share) {
ctx := r.Context()
sublog := appctx.GetLogger(ctx).With().Str("shareID", share.GetId().GetOpaqueId()).Logger()
client, err := pool.GetGatewayServiceClient(h.gatewayAddr)
if err != nil {
response.WriteOCSError(w, r, response.MetaServerError.StatusCode, "error getting grpc gateway client", err)
return
}
info, status, err := h.getResourceInfoByID(ctx, client, share.ResourceId)
if err != nil || status.Code != rpc.Code_CODE_OK {
response.WriteOCSError(w, r, response.MetaServerError.StatusCode, "error mapping share data", err)
return
}
role, _, ocsErr := h.extractPermissions(r.FormValue("role"), r.FormValue("permissions"), info, conversions.NewManagerRole())
if ocsErr != nil {
response.WriteOCSError(w, r, ocsErr.Code, ocsErr.Message, ocsErr.Error)
return
}
share.Permissions = &collaboration.SharePermissions{Permissions: role.CS3ResourcePermissions()}
var fieldMaskPaths = []string{"permissions"}
expireDate := r.PostFormValue("expireDate")
var expirationTs *types.Timestamp
if expireDate != "" {
expiration, err := time.Parse(time.RFC3339, expireDate)
if err != nil {
response.WriteOCSError(w, r, response.MetaBadRequest.StatusCode, "could not parse expireDate", err)
return
}
expirationTs = &types.Timestamp{
Seconds: uint64(expiration.UnixNano() / int64(time.Second)),
Nanos: uint32(expiration.UnixNano() % int64(time.Second)),
}
share.Expiration = expirationTs
fieldMaskPaths = append(fieldMaskPaths, "expiration")
} else if r.Form.Has("expireDate") {
// If the expiration parameter was sent but is empty, then the expiration should be removed.
share.Expiration = nil
fieldMaskPaths = append(fieldMaskPaths, "expiration")
}
uReq := &collaboration.UpdateShareRequest{
Share: share,
UpdateMask: &fieldmaskpb.FieldMask{
Paths: fieldMaskPaths,
},
}
uRes, err := client.UpdateShare(ctx, uReq)
if err != nil {
response.WriteOCSError(w, r, response.MetaServerError.StatusCode, "error sending a grpc update share request", err)
return
}
if uRes.Status.Code != rpc.Code_CODE_OK {
if uRes.Status.Code == rpc.Code_CODE_NOT_FOUND {
response.WriteOCSError(w, r, response.MetaNotFound.StatusCode, "not found", nil)
return
}
response.WriteOCSError(w, r, response.MetaServerError.StatusCode, "grpc update share request failed", err)
return
}
if currentUser, ok := ctxpkg.ContextGetUser(ctx); ok {
h.statCache.RemoveStat(currentUser.Id, share.ResourceId)
}
resultshare, err := conversions.CS3Share2ShareData(ctx, uRes.Share)
if err != nil {
response.WriteOCSError(w, r, response.MetaServerError.StatusCode, "error mapping share data", err)
return
}
statReq := provider.StatRequest{Ref: &provider.Reference{
ResourceId: uRes.Share.ResourceId,
}}
statRes, err := client.Stat(r.Context(), &statReq)
if err != nil {
sublog.Debug().Err(err).Str("shares", "update user share").Msg("error during stat")
response.WriteOCSError(w, r, response.MetaServerError.StatusCode, "missing resource information", fmt.Errorf("error getting resource information"))
return
}
if statRes.Status.Code != rpc.Code_CODE_OK {
if statRes.Status.Code == rpc.Code_CODE_NOT_FOUND {
response.WriteOCSError(w, r, response.MetaNotFound.StatusCode, "update user share: resource not found", err)
return
}
response.WriteOCSError(w, r, response.MetaServerError.StatusCode, "grpc stat request failed for stat after updating user share", err)
return
}
h.addFileInfo(r.Context(), resultshare, statRes.Info)
h.mapUserIds(ctx, client, resultshare)
response.WriteOCSSuccess(w, r, resultshare)
}
// RemoveShare handles DELETE requests on /apps/files_sharing/api/v1/shares/(shareid)
func (h *Handler) RemoveShare(w http.ResponseWriter, r *http.Request) {
shareID := chi.URLParam(r, "shareid")
if share, ok := h.isPublicShare(r, shareID); ok {
h.removePublicShare(w, r, share)
return
}
if share, ok := h.isUserShare(r, shareID); ok {
h.removeUserShare(w, r, share)
return
}
if prov, ok := h.isSpaceShare(r, shareID); ok {
// The request is a remove space member request.
h.removeSpaceMember(w, r, shareID, prov)
return
}
response.WriteOCSError(w, r, response.MetaNotFound.StatusCode, "cannot find share", nil)
}
// ListShares handles GET requests on /apps/files_sharing/api/v1/shares
func (h *Handler) ListShares(w http.ResponseWriter, r *http.Request) {
if r.FormValue("shared_with_me") != "" {
var err error
listSharedWithMe, err := strconv.ParseBool(r.FormValue("shared_with_me"))
if err != nil {
response.WriteOCSError(w, r, response.MetaServerError.StatusCode, "error mapping share data", err)
}
if listSharedWithMe {
h.listSharesWithMe(w, r)
return
}
}
h.listSharesWithOthers(w, r)
}
const (
ocsStateUnknown = -1
ocsStateAccepted = 0
ocsStatePending = 1
ocsStateRejected = 2
)
func (h *Handler) listSharesWithMe(w http.ResponseWriter, r *http.Request) {
// which pending state to list
stateFilter := getStateFilter(r.FormValue("state"))
ctx := r.Context()
p := r.URL.Query().Get("path")
shareRef := r.URL.Query().Get("share_ref")
shareTypesParam := r.URL.Query().Get("share_types")
sublog := appctx.GetLogger(ctx).With().Str("path", p).Str("share_ref", shareRef).Str("share_types", shareTypesParam).Logger()
client, err := h.getClient()
if err != nil {
response.WriteOCSError(w, r, response.MetaServerError.StatusCode, "error getting grpc gateway client", err)
return
}
var pinfo *provider.ResourceInfo
// we need to lookup the resource id so we can filter the list of shares later
if p != "" || shareRef != "" {
ref, err := h.extractReference(r)
if err != nil {
response.WriteOCSError(w, r, response.MetaBadRequest.StatusCode, errParsingSpaceReference.Error(), errParsingSpaceReference)
return
}
var status *rpc.Status
pinfo, status, err = h.getResourceInfoByReference(ctx, client, &ref)
if err != nil {
response.WriteOCSError(w, r, response.MetaServerError.StatusCode, "error sending a grpc stat request", err)
return
}
if status.Code != rpc.Code_CODE_OK {
switch status.Code {
case rpc.Code_CODE_NOT_FOUND:
response.WriteOCSError(w, r, response.MetaNotFound.StatusCode, "path not found", nil)
case rpc.Code_CODE_PERMISSION_DENIED:
response.WriteOCSError(w, r, response.MetaUnauthorized.StatusCode, "permission denied", nil)
default:
response.WriteOCSError(w, r, response.MetaServerError.StatusCode, "grpc stat request failed", nil)
}
return
}
}
filters := []*collaboration.Filter{}
var shareTypes []string
if shareTypesParam != "" {
shareTypes = strings.Split(shareTypesParam, ",")
}
for _, s := range shareTypes {
if s == "" {
continue
}
shareType, err := strconv.Atoi(strings.TrimSpace(s))
if err != nil {
response.WriteOCSError(w, r, response.MetaBadRequest.StatusCode, "invalid share type", err)
return
}
switch shareType {
case int(conversions.ShareTypeUser):
filters = append(filters, share.UserGranteeFilter())
case int(conversions.ShareTypeGroup):
filters = append(filters, share.GroupGranteeFilter())
}
}
if len(shareTypes) != 0 && len(filters) == 0 {
// If a share_types filter was set for anything other than user or group shares just return an empty response
response.WriteOCSSuccess(w, r, []*conversions.ShareData{})
return
}
lrsRes, err := client.ListReceivedShares(ctx, &collaboration.ListReceivedSharesRequest{Filters: filters})
if err != nil {
response.WriteOCSError(w, r, response.MetaServerError.StatusCode, "error sending a grpc ListReceivedShares request", err)
return
}
if lrsRes.Status.Code != rpc.Code_CODE_OK {
if lrsRes.Status.Code == rpc.Code_CODE_NOT_FOUND {
response.WriteOCSError(w, r, response.MetaNotFound.StatusCode, "not found", nil)
return
}
response.WriteOCSError(w, r, response.MetaServerError.StatusCode, "grpc ListReceivedShares request failed", err)
return
}
shares := make([]*conversions.ShareData, 0, len(lrsRes.GetShares()))
// TODO(refs) filter out "invalid" shares
for _, rs := range lrsRes.GetShares() {
if stateFilter != ocsStateUnknown && rs.GetState() != stateFilter {
continue
}
var info *provider.ResourceInfo
if pinfo != nil {
// check if the shared resource matches the path resource
if !utils.ResourceIDEqual(rs.Share.ResourceId, pinfo.Id) {
// try next share
continue
}
// we can reuse the stat info
info = pinfo
} else {
var status *rpc.Status
info, status, err = h.getResourceInfoByID(ctx, client, rs.Share.ResourceId)
if err != nil || status.Code != rpc.Code_CODE_OK {
h.logProblems(&sublog, status, err, "could not stat, skipping")
continue
}
}
data, err := conversions.CS3Share2ShareData(r.Context(), rs.Share)
if err != nil {
sublog.Debug().Interface("share", rs.Share).Interface("shareData", data).Err(err).Msg("could not CS3Share2ShareData, skipping")
continue
}
data.State = mapState(rs.GetState())
h.addFileInfo(ctx, data, info)
h.mapUserIds(r.Context(), client, data)
if data.State == ocsStateAccepted {
// only accepted shares can be accessed when jailing users into their home.
// in this case we cannot stat shared resources that are outside the users home (/home),
// the path (/users/u-u-i-d/foo) will not be accessible
// in a global namespace we can access the share using the full path
// in a jailed namespace we have to point to the mount point in the users /Shares Jail
// - needed for oc10 hot migration
// or use the /dav/spaces/<space id> endpoint?
// list /Shares and match fileids with list of received shares
// - only works for a /Shares folder jail
// - does not work for freely mountable shares as in oc10 because we would need to iterate over the whole tree, there is no listing of mountpoints, yet
// can we return the mountpoint when the gateway resolves the listing of shares?
// - no, the gateway only sees the same list any has the same options as the ocs service
// - we would need to have a list of mountpoints for the shares -> owncloudstorageprovider for hot migration migration
// best we can do for now is stat the /Shares Jail if it is set and return those paths
// if we are in a jail and the current share has been accepted use the stat from the share jail
// Needed because received shares can be jailed in a folder in the users home
if h.sharePrefix != "/" {
// if we have a mount point use it to build the path
if rs.MountPoint != nil && rs.MountPoint.Path != "" {
// override path with info from share jail
data.FileTarget = path.Join(h.sharePrefix, rs.MountPoint.Path)
data.Path = path.Join(h.sharePrefix, rs.MountPoint.Path)
} else {
data.FileTarget = path.Join(h.sharePrefix, path.Base(info.Path))
data.Path = path.Join(h.sharePrefix, path.Base(info.Path))
}
} else {
data.FileTarget = info.Path