-
Notifications
You must be signed in to change notification settings - Fork 113
/
eosfs.go
2207 lines (1899 loc) · 63.2 KB
/
eosfs.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-2024 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 eosfs
import (
"context"
b64 "encoding/base64"
"encoding/json"
"fmt"
"io"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/ReneKroon/ttlcache/v2"
"github.com/bluele/gcache"
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"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
"github.com/cs3org/reva/internal/http/services/owncloud/ocs/conversions"
"github.com/cs3org/reva/pkg/appctx"
"github.com/cs3org/reva/pkg/eosclient"
"github.com/cs3org/reva/pkg/eosclient/eosbinary"
"github.com/cs3org/reva/pkg/eosclient/eosgrpc"
"github.com/cs3org/reva/pkg/errtypes"
"github.com/cs3org/reva/pkg/mime"
"github.com/cs3org/reva/pkg/rgrpc/status"
"github.com/cs3org/reva/pkg/rgrpc/todo/pool"
"github.com/cs3org/reva/pkg/sharedconf"
"github.com/cs3org/reva/pkg/storage"
"github.com/cs3org/reva/pkg/storage/utils/acl"
"github.com/cs3org/reva/pkg/storage/utils/chunking"
"github.com/cs3org/reva/pkg/storage/utils/grants"
"github.com/cs3org/reva/pkg/storage/utils/templates"
"github.com/cs3org/reva/pkg/utils"
"github.com/pkg/errors"
)
const (
refTargetAttrKey = "reva.target" // used as user attr to store a reference
lwShareAttrKey = "reva.lwshare" // used to store grants to lightweight accounts
lockPayloadKey = "reva.lockpayload" // used to store lock payloads
eosLockKey = "app.lock" // this is the key known by EOS to enforce a lock.
FavoritesKey = "http://owncloud.org/ns/favorite"
)
const (
// SystemAttr is the system extended attribute.
SystemAttr eosclient.AttrType = iota
// UserAttr is the user extended attribute.
UserAttr
)
var hiddenReg = regexp.MustCompile(`\.sys\..#.`)
var eosLockReg = regexp.MustCompile(`expires:\d+,type:[a-z]+,owner:.+:.+`)
func (c *Config) ApplyDefaults() {
c.Namespace = path.Clean(c.Namespace)
if !strings.HasPrefix(c.Namespace, "/") {
c.Namespace = "/"
}
// Quota node defaults to namespace if empty
if c.QuotaNode == "" {
c.QuotaNode = c.Namespace
}
if c.EosBinary == "" {
c.EosBinary = "/usr/bin/eos"
}
if c.XrdcopyBinary == "" {
c.XrdcopyBinary = "/opt/eos/xrootd/bin/xrdcopy"
}
if c.MasterURL == "" {
c.MasterURL = "root://eos-example.org"
}
if c.SlaveURL == "" {
c.SlaveURL = c.MasterURL
}
if c.CacheDirectory == "" {
c.CacheDirectory = os.TempDir()
}
if c.UserLayout == "" {
c.UserLayout = "{{.Username}}" // TODO set better layout
}
if c.UserIDCacheSize == 0 {
c.UserIDCacheSize = 1000000
}
if c.UserIDCacheWarmupDepth == 0 {
c.UserIDCacheWarmupDepth = 2
}
if c.TokenExpiry == 0 {
c.TokenExpiry = 3600
}
if c.MaxRecycleEntries == 0 {
c.MaxRecycleEntries = 2000
}
if c.MaxDaysInRecycleList == 0 {
c.MaxDaysInRecycleList = 14
}
c.GatewaySvc = sharedconf.GetGatewaySVC(c.GatewaySvc)
}
type eosfs struct {
c eosclient.EOSClient
conf *Config
chunkHandler *chunking.ChunkHandler
singleUserAuth eosclient.Authorization
userIDCache *ttlcache.Cache
tokenCache gcache.Cache
}
// NewEOSFS returns a storage.FS interface implementation that connects to an EOS instance.
func NewEOSFS(ctx context.Context, c *Config) (storage.FS, error) {
c.ApplyDefaults()
// bail out if keytab is not found.
if c.UseKeytab {
if _, err := os.Stat(c.Keytab); err != nil {
err = errors.Wrapf(err, "eosfs: keytab not accessible at location: %s", err)
return nil, err
}
}
var eosClient eosclient.EOSClient
var err error
if c.UseGRPC {
eosClientOpts := &eosgrpc.Options{
XrdcopyBinary: c.XrdcopyBinary,
URL: c.MasterURL,
GrpcURI: c.GrpcURI,
CacheDirectory: c.CacheDirectory,
UseKeytab: c.UseKeytab,
Keytab: c.Keytab,
Authkey: c.GRPCAuthkey,
SecProtocol: c.SecProtocol,
VersionInvariant: c.VersionInvariant,
ReadUsesLocalTemp: c.ReadUsesLocalTemp,
WriteUsesLocalTemp: c.WriteUsesLocalTemp,
TokenExpiry: c.TokenExpiry,
}
eosHTTPOpts := &eosgrpc.HTTPOptions{
BaseURL: c.MasterURL,
MaxIdleConns: c.MaxIdleConns,
MaxConnsPerHost: c.MaxConnsPerHost,
MaxIdleConnsPerHost: c.MaxIdleConnsPerHost,
IdleConnTimeout: c.IdleConnTimeout,
ClientCertFile: c.ClientCertFile,
ClientKeyFile: c.ClientKeyFile,
ClientCADirs: c.ClientCADirs,
ClientCAFiles: c.ClientCAFiles,
Authkey: c.HTTPSAuthkey,
}
eosClient, err = eosgrpc.New(ctx, eosClientOpts, eosHTTPOpts)
} else {
eosClientOpts := &eosbinary.Options{
XrdcopyBinary: c.XrdcopyBinary,
URL: c.MasterURL,
EosBinary: c.EosBinary,
CacheDirectory: c.CacheDirectory,
ForceSingleUserMode: c.ForceSingleUserMode,
SingleUsername: c.SingleUsername,
UseKeytab: c.UseKeytab,
Keytab: c.Keytab,
SecProtocol: c.SecProtocol,
VersionInvariant: c.VersionInvariant,
TokenExpiry: c.TokenExpiry,
}
eosClient, err = eosbinary.New(eosClientOpts)
}
if err != nil {
return nil, errors.Wrap(err, "error initializing eosclient")
}
eosfs := &eosfs{
c: eosClient,
conf: c,
chunkHandler: chunking.NewChunkHandler(c.CacheDirectory),
userIDCache: ttlcache.NewCache(),
tokenCache: gcache.New(c.UserIDCacheSize).LFU().Build(),
}
eosfs.userIDCache.SetCacheSizeLimit(c.UserIDCacheSize)
eosfs.userIDCache.SetExpirationReasonCallback(func(key string, reason ttlcache.EvictionReason, value interface{}) {
// We only set those keys with TTL which we weren't able to retrieve the last time
// For those keys, try to contact the userprovider service again when they expire
if reason == ttlcache.Expired {
_, _ = eosfs.getUserIDGateway(context.Background(), key)
}
})
go eosfs.userIDcacheWarmup()
return eosfs, nil
}
func (fs *eosfs) userIDcacheWarmup() {
if !fs.conf.EnableHome {
time.Sleep(2 * time.Second)
ctx := context.Background()
paths := []string{fs.wrap(ctx, "/")}
for i := 0; i < fs.conf.UserIDCacheWarmupDepth; i++ {
var newPaths []string
for _, fn := range paths {
if eosFileInfos, err := fs.c.List(ctx, utils.GetEmptyAuth(), fn); err == nil {
for _, f := range eosFileInfos {
_, _ = fs.getUserIDGateway(ctx, strconv.FormatUint(f.UID, 10))
newPaths = append(newPaths, f.File)
}
}
}
paths = newPaths
}
}
}
func (fs *eosfs) Shutdown(ctx context.Context) error {
// TODO(labkode): in a grpc implementation we can close connections.
return nil
}
func (fs *eosfs) getLayout(ctx context.Context) (layout string) {
if fs.conf.EnableHome {
u := appctx.ContextMustGetUser(ctx)
layout = templates.WithUser(u, fs.conf.UserLayout)
}
return
}
func (fs *eosfs) getInternalHome(ctx context.Context) string {
if !fs.conf.EnableHome {
// TODO(lopresti): this is to be removed as we always want to support home,
// cf. https://github.com/cs3org/reva/pull/4940
return "/"
}
u := appctx.ContextMustGetUser(ctx)
relativeHome := templates.WithUser(u, fs.conf.UserLayout)
return relativeHome
}
func (fs *eosfs) wrap(ctx context.Context, fn string) (internal string) {
if fs.conf.EnableHome {
internal = path.Join(fs.conf.Namespace, fs.getInternalHome(ctx), fn)
} else {
internal = path.Join(fs.conf.Namespace, fn)
}
log := appctx.GetLogger(ctx)
log.Debug().Msg("eosfs: wrap external=" + fn + " internal=" + internal)
return
}
func (fs *eosfs) unwrap(ctx context.Context, internal string) (string, error) {
log := appctx.GetLogger(ctx)
layout := fs.getLayout(ctx)
ns, err := fs.getNsMatch(internal, []string{fs.conf.Namespace})
if err != nil {
return "", err
}
external, err := fs.unwrapInternal(ctx, ns, internal, layout)
if err != nil {
return "", err
}
log.Debug().Msgf("eosfs: unwrap: internal=%s external=%s", internal, external)
return external, nil
}
func (fs *eosfs) getNsMatch(internal string, nss []string) (string, error) {
var match string
for _, ns := range nss {
if strings.HasPrefix(internal, ns) && len(ns) > len(match) {
match = ns
}
}
if match == "" {
return "", errtypes.NotFound(fmt.Sprintf("eosfs: path is outside namespaces: path=%s namespaces=%+v", internal, nss))
}
return match, nil
}
func (fs *eosfs) unwrapInternal(ctx context.Context, ns, np, layout string) (string, error) {
trim := path.Join(ns, layout)
if !strings.HasPrefix(np, trim) {
return "", errtypes.NotFound(fmt.Sprintf("eosfs: path is outside the directory of the logged-in user: internal=%s trim=%s namespace=%+v", np, trim, ns))
}
external := strings.TrimPrefix(np, trim)
if external == "" {
external = "/"
}
return external, nil
}
func (fs *eosfs) resolveRefAndGetAuth(ctx context.Context, ref *provider.Reference) (string, eosclient.Authorization, error) {
p, err := fs.resolve(ctx, ref)
if err != nil {
return "", eosclient.Authorization{}, errors.Wrap(err, "eosfs: error resolving reference")
}
u, err := utils.GetUser(ctx)
if err != nil {
return "", eosclient.Authorization{}, errors.Wrap(err, "eosfs: no user in ctx")
}
fn := fs.wrap(ctx, p)
auth, err := fs.getUserAuth(ctx, u, fn)
if err != nil {
return "", eosclient.Authorization{}, err
}
return fn, auth, nil
}
// resolve takes in a request path or request id and returns the unwrapped path.
func (fs *eosfs) resolve(ctx context.Context, ref *provider.Reference) (string, error) {
if ref.ResourceId != nil {
p, err := fs.getPath(ctx, ref.ResourceId)
if err != nil {
return "", err
}
p = path.Join(p, ref.Path)
return p, nil
}
if ref.Path != "" {
return ref.Path, nil
}
// reference is invalid
return "", fmt.Errorf("invalid reference %+v. at least resource_id or path must be set", ref)
}
func (fs *eosfs) getPath(ctx context.Context, id *provider.ResourceId) (string, error) {
fid, err := strconv.ParseUint(id.OpaqueId, 10, 64)
if err != nil {
return "", fmt.Errorf("error converting string to int for eos fileid: %s", id.OpaqueId)
}
auth, err := fs.getDaemonAuth(ctx)
if err != nil {
return "", err
}
eosFileInfo, err := fs.c.GetFileInfoByInode(ctx, auth, fid)
if err != nil {
return "", errors.Wrap(err, "eosfs: error getting file info by inode")
}
return fs.unwrap(ctx, eosFileInfo.File)
}
func (fs *eosfs) GetPathByID(ctx context.Context, id *provider.ResourceId) (string, error) {
fid, err := strconv.ParseUint(id.OpaqueId, 10, 64)
if err != nil {
return "", errors.Wrap(err, "eosfs: error parsing fileid string")
}
u, err := utils.GetUser(ctx)
if err != nil {
return "", errors.Wrap(err, "eosfs: no user in ctx")
}
var auth eosclient.Authorization
if utils.IsLightweightUser(u) {
auth, err = fs.getDaemonAuth(ctx)
} else {
auth, err = fs.getUserAuth(ctx, u, "")
}
if err != nil {
return "", err
}
eosFileInfo, err := fs.c.GetFileInfoByInode(ctx, auth, fid)
if err != nil {
return "", errors.Wrap(err, "eosfs: error getting file info by inode")
}
if perm := fs.permissionSet(ctx, eosFileInfo, nil); !perm.GetPath {
return "", errtypes.PermissionDenied("eosfs: getting path for id not allowed")
}
return fs.unwrap(ctx, eosFileInfo.File)
}
func (fs *eosfs) SetArbitraryMetadata(ctx context.Context, ref *provider.Reference, md *provider.ArbitraryMetadata) error {
if len(md.Metadata) == 0 {
return errtypes.BadRequest("eosfs: no metadata set")
}
fn, _, err := fs.resolveRefAndGetAuth(ctx, ref)
if err != nil {
return err
}
cboxAuth := utils.GetEmptyAuth()
for k, v := range md.Metadata {
if k == "" || v == "" {
return errtypes.BadRequest(fmt.Sprintf("eosfs: key or value is empty: key:%s, value:%s", k, v))
}
// do not allow to override system-reserved keys
if k == lockPayloadKey || k == eosLockKey || k == lwShareAttrKey || k == refTargetAttrKey {
return errtypes.BadRequest(fmt.Sprintf("eosfs: key %s is reserved", k))
}
attr := &eosclient.Attribute{
Type: UserAttr,
Key: k,
Val: v,
}
// TODO(labkode): SetArbitraryMetadata does not have semantics for recursivity.
// We set it to false
err := fs.c.SetAttr(ctx, cboxAuth, attr, false, false, fn, "")
if err != nil {
return errors.Wrap(err, "eosfs: error setting xattr in eos driver")
}
}
return nil
}
func (fs *eosfs) UnsetArbitraryMetadata(ctx context.Context, ref *provider.Reference, keys []string) error {
if len(keys) == 0 {
return errtypes.BadRequest("eosfs: no keys set")
}
fn, _, err := fs.resolveRefAndGetAuth(ctx, ref)
if err != nil {
return err
}
cboxAuth := utils.GetEmptyAuth()
for _, k := range keys {
if k == "" {
return errtypes.BadRequest("eosfs: key is empty")
}
attr := &eosclient.Attribute{
Type: UserAttr,
Key: k,
}
err := fs.c.UnsetAttr(ctx, cboxAuth, attr, false, fn, "")
if err != nil {
if errors.Is(err, eosclient.AttrNotExistsError) {
continue
}
return errors.Wrap(err, "eosfs: error unsetting xattr in eos driver")
}
}
return nil
}
func (fs *eosfs) EncodeAppName(a string) string {
// this function returns the string to be used as EOS "app" tag, both in uploads and when handling locks;
// note that the GET (and PUT) operations in eosbinary.go and eoshttp.go use a `reva_eosclient::read`
// (resp. `write`) tag when no locks are involved.
r := strings.NewReplacer(" ", "_")
return "reva_eosclient::app_" + strings.ToLower(r.Replace(a))
}
func (fs *eosfs) getLockPayloads(ctx context.Context, path string) (string, string, error) {
// sys attributes want root auth, buddy
cboxAuth := utils.GetEmptyAuth()
data, err := fs.c.GetAttr(ctx, cboxAuth, "sys."+lockPayloadKey, path)
if err != nil {
return "", "", err
}
eoslock, err := fs.c.GetAttr(ctx, cboxAuth, "sys."+eosLockKey, path)
if err != nil {
return "", "", err
}
return data.Val, eoslock.Val, nil
}
func (fs *eosfs) removeLockAttrs(ctx context.Context, path, app string) error {
cboxAuth := utils.GetEmptyAuth()
err := fs.c.UnsetAttr(ctx, cboxAuth, &eosclient.Attribute{
Type: SystemAttr,
Key: eosLockKey,
}, false, path, app)
if err != nil {
return errors.Wrap(err, "eosfs: error unsetting the eos lock")
}
err = fs.c.UnsetAttr(ctx, cboxAuth, &eosclient.Attribute{
Type: SystemAttr,
Key: lockPayloadKey,
}, false, path, app)
if err != nil {
return errors.Wrap(err, "eosfs: error unsetting the lock payload")
}
return nil
}
func (fs *eosfs) getLock(ctx context.Context, user *userpb.User, path string, ref *provider.Reference) (*provider.Lock, error) {
// the cs3apis require to have the read permission on the resource
// to get the eventual lock.
has, err := fs.userHasReadAccess(ctx, user, ref)
if err != nil {
return nil, errors.Wrap(err, "eosfs: error checking read access to resource")
}
if !has {
return nil, errtypes.BadRequest("user has not read access on resource")
}
d, eosl, err := fs.getLockPayloads(ctx, path)
if err != nil {
if !errors.Is(err, eosclient.AttrNotExistsError) {
return nil, errtypes.NotFound("lock not found for ref")
}
}
l, err := decodeLock(d, eosl)
if err != nil {
return nil, errors.Wrap(err, "eosfs: malformed lock payload")
}
if time.Unix(int64(l.Expiration.Seconds), 0).Before(time.Now()) {
// the lock expired
if err := fs.removeLockAttrs(ctx, path, fs.EncodeAppName(l.AppName)); err != nil {
return nil, err
}
return nil, errtypes.NotFound("lock not found for ref")
}
return l, nil
}
// GetLock returns an existing lock on the given reference.
func (fs *eosfs) GetLock(ctx context.Context, ref *provider.Reference) (*provider.Lock, error) {
path, err := fs.resolve(ctx, ref)
if err != nil {
return nil, errors.Wrap(err, "eosfs: error resolving reference")
}
user, err := utils.GetUser(ctx)
if err != nil {
return nil, errors.Wrap(err, "eosfs: no user in ctx")
}
// the cs3apis require to have the read permission on the resource
// to get the eventual lock.
has, err := fs.userHasReadAccess(ctx, user, ref)
if err != nil {
return nil, errors.Wrap(err, "eosfs: error checking read access to resource")
}
if !has {
return nil, errtypes.BadRequest("user has no read access on resource")
}
path = fs.wrap(ctx, path)
return fs.getLock(ctx, user, path, ref)
}
func (fs *eosfs) setLock(ctx context.Context, lock *provider.Lock, path string) error {
cboxAuth := utils.GetEmptyAuth()
encodedLock, eosLock, err := fs.encodeLock(lock)
if err != nil {
return errors.Wrap(err, "eosfs: error encoding lock")
}
// set eos lock
err = fs.c.SetAttr(ctx, cboxAuth, &eosclient.Attribute{
Type: SystemAttr,
Key: eosLockKey,
Val: eosLock,
}, false, false, path, fs.EncodeAppName(lock.AppName))
switch {
case errors.Is(err, eosclient.FileIsLockedError):
return errtypes.Conflict("resource already locked")
case err != nil:
return errors.Wrap(err, "eosfs: error setting eos lock")
}
// set payload
err = fs.c.SetAttr(ctx, cboxAuth, &eosclient.Attribute{
Type: SystemAttr,
Key: lockPayloadKey,
Val: encodedLock,
}, false, false, path, fs.EncodeAppName(lock.AppName))
if err != nil {
return errors.Wrap(err, "eosfs: error setting lock payload")
}
return nil
}
// SetLock puts a lock on the given reference.
func (fs *eosfs) SetLock(ctx context.Context, ref *provider.Reference, l *provider.Lock) error {
if l.Type == provider.LockType_LOCK_TYPE_SHARED {
return errtypes.NotSupported("shared lock not yet implemented")
}
path, err := fs.resolve(ctx, ref)
if err != nil {
return errors.Wrap(err, "eosfs: error resolving reference")
}
user, err := utils.GetUser(ctx)
if err != nil {
return errors.Wrap(err, "eosfs: no user in ctx")
}
// the cs3apis require to have the write permission on the resource
// to set a lock. because in eos we can set attrs even if the user does
// not have the write permission, we need to check if the user that made
// the request has it
has, err := fs.userHasWriteAccess(ctx, user, ref)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("eosfs: cannot check if user %s has write access on resource", user.Username))
}
if !has {
return errtypes.PermissionDenied(fmt.Sprintf("user %s has no write access on resource", user.Username))
}
// the user in the lock could differ from the user in the context
// in that case, also the user in the lock MUST have the write permission
if l.User != nil && !utils.UserEqual(user.Id, l.User) {
has, err := fs.userIDHasWriteAccess(ctx, l.User, ref)
if err != nil {
return errors.Wrap(err, "eosfs: cannot check if user has write access on resource")
}
if !has {
return errtypes.PermissionDenied(fmt.Sprintf("user %s has no write access on resource", user.Username))
}
}
path = fs.wrap(ctx, path)
return fs.setLock(ctx, l, path)
}
func (fs *eosfs) getUserFromID(ctx context.Context, userID *userpb.UserId) (*userpb.User, error) {
client, err := pool.GetGatewayServiceClient(pool.Endpoint(fs.conf.GatewaySvc))
if err != nil {
return nil, err
}
res, err := client.GetUser(ctx, &userpb.GetUserRequest{
UserId: userID,
})
if err != nil {
return nil, err
}
if res.Status.Code != rpc.Code_CODE_OK {
return nil, errtypes.InternalError(res.Status.Message)
}
return res.User, nil
}
func (fs *eosfs) userHasWriteAccess(ctx context.Context, user *userpb.User, ref *provider.Reference) (bool, error) {
ctx = appctx.ContextSetUser(ctx, user)
resInfo, err := fs.GetMD(ctx, ref, nil)
if err != nil {
return false, err
}
return resInfo.PermissionSet.InitiateFileUpload, nil
}
func (fs *eosfs) userIDHasWriteAccess(ctx context.Context, userID *userpb.UserId, ref *provider.Reference) (bool, error) {
user, err := fs.getUserFromID(ctx, userID)
if err != nil {
return false, nil
}
return fs.userHasWriteAccess(ctx, user, ref)
}
func (fs *eosfs) userHasReadAccess(ctx context.Context, user *userpb.User, ref *provider.Reference) (bool, error) {
ctx = appctx.ContextSetUser(ctx, user)
resInfo, err := fs.GetMD(ctx, ref, nil)
if err != nil {
return false, err
}
return resInfo.PermissionSet.InitiateFileDownload, nil
}
func (fs *eosfs) encodeLock(l *provider.Lock) (string, string, error) {
data, err := json.Marshal(l)
if err != nil {
return "", "", err
}
var a string
if l.AppName != "" {
// cf. upload implementation
a = fs.EncodeAppName(l.AppName)
} else {
a = "*"
}
var u string
if l.User != nil {
u = l.User.OpaqueId
} else {
u = "*"
}
// the eos lock has hardcoded type "shared" because that's what eos supports. This is good enough
// for apps via WOPI and for checkout/checkin behavior, not for "exclusive" (no read access unless holding the lock).
return b64.StdEncoding.EncodeToString(data),
fmt.Sprintf("expires:%d,type:shared,owner:%s:%s", l.Expiration.Seconds, u, a),
nil
}
func decodeLock(content string, eosLock string) (*provider.Lock, error) {
d, err := b64.StdEncoding.DecodeString(content)
if err != nil {
return nil, err
}
l := new(provider.Lock)
err = json.Unmarshal(d, l)
if err != nil {
return nil, err
}
// validate that the eosLock respect the format, otherwise raise error
if !eosLockReg.MatchString(eosLock) {
return nil, errtypes.BadRequest("eos lock payload does not match expected format: " + eosLock)
}
return l, nil
}
// RefreshLock refreshes an existing lock on the given reference.
func (fs *eosfs) RefreshLock(ctx context.Context, ref *provider.Reference, newLock *provider.Lock, existingLockID string) error {
if newLock.Type == provider.LockType_LOCK_TYPE_SHARED {
return errtypes.NotSupported("shared lock not yet implemented")
}
oldLock, err := fs.GetLock(ctx, ref)
if err != nil {
switch err.(type) {
case errtypes.NotFound:
// the lock does not exist
return errtypes.BadRequest("file was not locked")
default:
return err
}
}
user, err := utils.GetUser(ctx)
if err != nil {
return errors.Wrap(err, "eosfs: error getting user")
}
// check if the holder is the same of the new lock
if !sameHolder(oldLock, newLock) {
return errtypes.BadRequest("caller does not hold the lock")
}
if existingLockID != "" && oldLock.LockId != existingLockID {
return errtypes.BadRequest("lock id does not match")
}
path, err := fs.resolve(ctx, ref)
if err != nil {
return errors.Wrap(err, "eosfs: error resolving reference")
}
path = fs.wrap(ctx, path)
// the cs3apis require to have the write permission on the resource
// to set a lock
has, err := fs.userHasWriteAccess(ctx, user, ref)
if err != nil {
return errors.Wrap(err, "eosfs: cannot check if user has write access on resource")
}
if !has {
return errtypes.PermissionDenied(fmt.Sprintf("user %s has no write access on resource", user.Username))
}
return fs.setLock(ctx, newLock, path)
}
func sameHolder(l1, l2 *provider.Lock) bool {
same := true
if l1.User != nil || l2.User != nil {
same = utils.UserEqual(l1.User, l2.User)
}
if l1.AppName != "" || l2.AppName != "" {
same = l1.AppName == l2.AppName
}
return same
}
// Unlock removes an existing lock from the given reference.
func (fs *eosfs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error {
oldLock, err := fs.GetLock(ctx, ref)
if err != nil {
switch err.(type) {
case errtypes.NotFound:
// the lock does not exist
return errtypes.BadRequest("file was not locked")
default:
return err
}
}
// check if the lock id of the lock corresponds to the stored lock
if oldLock.LockId != lock.LockId {
return errtypes.BadRequest("lock id does not match")
}
if !sameHolder(oldLock, lock) {
return errtypes.BadRequest("caller does not hold the lock")
}
user, err := utils.GetUser(ctx)
if err != nil {
return errors.Wrap(err, "eosfs: error getting user")
}
// the cs3apis require to have the write permission on the resource
// to remove the lock
has, err := fs.userHasWriteAccess(ctx, user, ref)
if err != nil {
return errors.Wrap(err, "eosfs: cannot check if user has write access on resource")
}
if !has {
return errtypes.PermissionDenied(fmt.Sprintf("user %s has no write access on resource", user.Username))
}
path, err := fs.resolve(ctx, ref)
if err != nil {
return errors.Wrap(err, "eosfs: error resolving reference")
}
path = fs.wrap(ctx, path)
return fs.removeLockAttrs(ctx, path, fs.EncodeAppName(lock.AppName))
}
func (fs *eosfs) AddGrant(ctx context.Context, ref *provider.Reference, g *provider.Grant) error {
fn, auth, err := fs.resolveRefAndGetAuth(ctx, ref)
if err != nil {
return err
}
cboxAuth := utils.GetEmptyAuth()
eosACL, err := fs.getEosACL(ctx, g)
if err != nil {
return err
}
if eosACL.Type == acl.TypeLightweight {
// The ACLs for a lightweight are not understandable by EOS
// directly, but only from reva. So we have to store them
// in an xattr named sys.reva.lwshare.<lw_account>, with value
// the permissions.
attr := &eosclient.Attribute{
Type: SystemAttr,
Key: fmt.Sprintf("%s.%s", lwShareAttrKey, eosACL.Qualifier),
Val: eosACL.Permissions,
}
if err := fs.c.SetAttr(ctx, cboxAuth, attr, false, true, fn, ""); err != nil {
return errors.Wrap(err, "eosfs: error adding acl for lightweight account")
}
return nil
}
err = fs.c.AddACL(ctx, auth, cboxAuth, fn, eosclient.StartPosition, eosACL)
if err != nil {
return errors.Wrap(err, "eosfs: error adding acl")
}
return nil
}
func (fs *eosfs) DenyGrant(ctx context.Context, ref *provider.Reference, g *provider.Grantee) error {
fn, auth, err := fs.resolveRefAndGetAuth(ctx, ref)
if err != nil {
return err
}
position := eosclient.EndPosition
cboxAuth := utils.GetEmptyAuth()
// empty permissions => deny
grant := &provider.Grant{
Grantee: g,
Permissions: &provider.ResourcePermissions{},
}
eosACL, err := fs.getEosACL(ctx, grant)
if err != nil {
return err
}
err = fs.c.AddACL(ctx, auth, cboxAuth, fn, position, eosACL)
if err != nil {
return errors.Wrap(err, "eosfs: error adding acl")
}
return nil
}
func (fs *eosfs) getEosACL(ctx context.Context, g *provider.Grant) (*acl.Entry, error) {
permissions, err := grants.GetACLPerm(g.Permissions)
if err != nil {
return nil, err
}
t, err := grants.GetACLType(g.Grantee.Type)
if err != nil {
return nil, err
}
var qualifier string
if t == acl.TypeUser {
// if the grantee is a lightweight account, we need to set it accordingly
if g.Grantee.GetUserId().Type == userpb.UserType_USER_TYPE_LIGHTWEIGHT ||
g.Grantee.GetUserId().Type == userpb.UserType_USER_TYPE_FEDERATED {
t = acl.TypeLightweight
qualifier = g.Grantee.GetUserId().OpaqueId
} else {
// since EOS Citrine ACLs are stored with uid, we need to convert username to
// uid only for users.
auth, err := fs.getUIDGateway(ctx, g.Grantee.GetUserId())
if err != nil {
return nil, err
}
qualifier = auth.Role.UID
}
} else {
qualifier = g.Grantee.GetGroupId().OpaqueId
}
eosACL := &acl.Entry{
Qualifier: qualifier,
Permissions: permissions,
Type: t,
}
return eosACL, nil
}
func (fs *eosfs) RemoveGrant(ctx context.Context, ref *provider.Reference, g *provider.Grant) error {
fn, auth, err := fs.resolveRefAndGetAuth(ctx, ref)
if err != nil {
return err
}
cboxAuth := utils.GetEmptyAuth()
eosACL, err := fs.getEosACL(ctx, g)
if err != nil {
return err
}
if eosACL.Type == acl.TypeLightweight {
attr := &eosclient.Attribute{
Type: SystemAttr,
Key: fmt.Sprintf("%s.%s", lwShareAttrKey, eosACL.Qualifier),
}
if err := fs.c.UnsetAttr(ctx, cboxAuth, attr, true, fn, ""); err != nil {
return errors.Wrap(err, "eosfs: error removing acl for lightweight account")
}