feat: [stable-8.2][OCISDEV-855] receivedsharecache: retry on transient storage errors in CAS loop (#12789)

feat: [OCISDEV-855] receivedsharecache: retry on transient storage errors in CAS loop (#12621)
This commit is contained in:
Michal Klos authored and GitHub committed 2026-08-14 09:41:31 +02:00
1 parent 544ebe5cad
commit 895d09db3f
18 files changed
+207 -122

No files matched your search

@@ -0,0 +1,9 @@
Bugfix: Fix share metadata corruption during concurrent share operations
When multiple sharing service replicas processed share operations concurrently
for the same user, the share metadata could become corrupted with references to
missing data, making all shares inaccessible to that user. The received share
cache now uses compare-and-swap (etag) validation to detect concurrent writes
and retries gracefully, preventing metadata corruption.
https://github.com/owncloud/ocis/pull/12621
+1 -1
View File
@@ -67,7 +67,7 @@ require (
github.com/open-policy-agent/opa v1.19.0
github.com/orcaman/concurrent-map v1.0.0
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245
github.com/owncloud/reva/v2 v2.0.0-20260807092659-5e5d7767ea70
github.com/owncloud/reva/v2 v2.0.0-20260813081456-8ed15f4851e1
github.com/pkg/errors v0.9.1
github.com/pkg/xattr v0.4.12
github.com/prometheus/client_golang v1.24.1
+2 -2
View File
@@ -737,8 +737,8 @@ github.com/orcaman/concurrent-map v1.0.0 h1:I/2A2XPCb4IuQWcQhBhSwGfiuybl/J0ev9HD
github.com/orcaman/concurrent-map v1.0.0/go.mod h1:Lu3tH6HLW3feq74c2GC+jIMS/K2CFcDWnWD9XkenwhI=
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245 h1:JRidLTAKhnvyLMRtVtSF4lhBa0NSAOs6fof+d6JnKII=
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245/go.mod h1:z61VMGAJRtR1nbgXWiNoCkxUXP1B3Je9rMuJbnGd+Og=
github.com/owncloud/reva/v2 v2.0.0-20260807092659-5e5d7767ea70 h1:CmCVRdKEOJipgY1zPsgTUU8dk3ExbMPg9xUgDUjycXM=
github.com/owncloud/reva/v2 v2.0.0-20260807092659-5e5d7767ea70/go.mod h1:zJV1uSPyjLXGhb3JwI0EuUx8GJaq1d/NCmpuqN0U4IE=
github.com/owncloud/reva/v2 v2.0.0-20260813081456-8ed15f4851e1 h1:4Qgzuphg6OERnBYyqmYy4cdyBBRzri4/yAy5UjpFQmg=
github.com/owncloud/reva/v2 v2.0.0-20260813081456-8ed15f4851e1/go.mod h1:zJV1uSPyjLXGhb3JwI0EuUx8GJaq1d/NCmpuqN0U4IE=
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c h1:rp5dCmg/yLR3mgFuSOe4oEnDDmGLROTvMragMUXpTQw=
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0=
github.com/pablodz/inotifywaitgo v0.0.12 h1:DVJJTFMDlSAdO46yisPF2vzozs/r+4k6ih8MVghq78M=
@@ -452,6 +452,8 @@ func (s *Service) InitiateFileUpload(ctx context.Context, req *provider.Initiate
st = status.NewFailedPrecondition(ctx, err, "failed precondition")
case errtypes.Locked:
st = status.NewLocked(ctx, "locked")
case errtypes.IsTooEarly:
st = status.NewTooEarly(ctx, err.Error())
default:
st = status.NewInternal(ctx, "error getting upload id: "+err.Error())
}
@@ -61,6 +61,9 @@ type config struct {
StoreTable string `mapstructure:"store_table"`
StoreUsername string `mapstructure:"store_username"`
StorePassword string `mapstructure:"store_password"`
StoreEnableTLS bool `mapstructure:"store_enable_tls"`
StoreTLSInsecure bool `mapstructure:"store_tls_insecure"`
StoreTLSRootCACert string `mapstructure:"store_tls_root_ca_certificate"`
}
func parseConfig(m map[string]interface{}) (*config, error) {
@@ -86,6 +89,7 @@ func New(m map[string]interface{}) (auth.Manager, error) {
microstore.Database(mgr.c.StoreDatabase),
microstore.Table(mgr.c.StoreTable),
store.Authentication(mgr.c.StoreUsername, mgr.c.StorePassword),
store.TLS(mgr.c.StoreEnableTLS, mgr.c.StoreTLSInsecure, mgr.c.StoreTLSRootCACert),
)
mgr.bfp = NewBruteForceProtection(revaStore, mgr.c.BruteForceTimeGap, mgr.c.BruteForceMaxAttempts)
return mgr, nil
@@ -275,6 +275,9 @@ func handleError(w http.ResponseWriter, log *zerolog.Logger, err error, action s
case errtypes.Aborted:
log.Debug().Err(err).Str("action", action).Msg("etags do not match")
w.WriteHeader(http.StatusPreconditionFailed)
case errtypes.IsResourceProcessing, errtypes.IsTooEarly:
log.Debug().Err(err).Str("action", action).Msg("resource is processing")
w.WriteHeader(http.StatusTooEarly)
default:
log.Error().Err(err).Str("action", action).Msg("unexpected error")
w.WriteHeader(http.StatusInternalServerError)
@@ -100,7 +100,7 @@ func (c *Cache) Add(ctx context.Context, userID, spaceID string, rs *collaborati
defer unlock()
if _, ok := c.ReceivedSpaces.Load(userID); !ok {
err := c.syncWithLock(ctx, userID)
err := c.syncIfStale(ctx, userID)
if err != nil {
return err
}
@@ -110,7 +110,7 @@ func (c *Cache) Add(ctx context.Context, userID, spaceID string, rs *collaborati
defer span.End()
span.SetAttributes(attribute.String("cs3.userid", userID), attribute.String("cs3.spaceid", spaceID))
persistFunc := func() error {
err := c.retryPersist(ctx, userID, spaceID, func() error {
c.initializeIfNeeded(userID, spaceID)
rss, _ := c.ReceivedSpaces.Load(userID)
@@ -125,56 +125,12 @@ func (c *Cache) Add(ctx context.Context, userID, spaceID string, rs *collaborati
}
return c.persist(ctx, userID)
}
log := appctx.GetLogger(ctx).With().
Str("hostname", os.Getenv("HOSTNAME")).
Str("userID", userID).
Str("spaceID", spaceID).Logger()
var err error
for attempt := 0; attempt < 20; attempt++ {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
err = persistFunc()
switch err.(type) {
case nil:
span.SetStatus(codes.Ok, "")
return nil
case errtypes.Aborted:
log.Debug().Msg("aborted when persisting added received share: etag changed. retrying...")
// this is the expected status code from the server when the if-match etag check fails
// continue with sync below
case errtypes.PreconditionFailed:
log.Debug().Msg("precondition failed when persisting added received share: etag changed. retrying...")
// actually, this is the wrong status code and we treat it like errtypes.Aborted because of inconsistencies on the server side
// continue with sync below
case errtypes.AlreadyExists:
log.Debug().Msg("already exists when persisting added received share. retrying...")
// CS3 uses an already exists error instead of precondition failed when using an If-None-Match=* header / IfExists flag in the InitiateFileUpload call.
// Thas happens when the cache thinks there is no file.
// continue with sync below
default:
span.SetStatus(codes.Error, fmt.Sprintf("persisting added received share failed. giving up: %s", err.Error()))
log.Error().Err(err).Msg("persisting added received share failed")
return err
}
timer := time.NewTimer(expBackoff(attempt))
select {
case <-timer.C:
case <-ctx.Done():
timer.Stop()
return ctx.Err()
}
if err := c.syncWithLock(ctx, userID); err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
log.Error().Err(err).Msg("persisting added received share failed. giving up.")
return err
}
})
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
} else {
span.SetStatus(codes.Ok, "")
}
return err
}
@@ -187,7 +143,7 @@ func (c *Cache) Get(ctx context.Context, userID, spaceID, shareID string) (*Stat
span.SetAttributes(attribute.String("cs3.userid", userID))
defer unlock()
err := c.syncWithLock(ctx, userID)
err := c.syncIfStale(ctx, userID)
if err != nil {
return nil, err
}
@@ -206,11 +162,11 @@ func (c *Cache) Remove(ctx context.Context, userID, spaceID, shareID string) err
span.SetAttributes(attribute.String("cs3.userid", userID))
defer unlock()
ctx, span = appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "Add")
ctx, span = appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "Remove")
defer span.End()
span.SetAttributes(attribute.String("cs3.userid", userID), attribute.String("cs3.spaceid", spaceID))
persistFunc := func() error {
err := c.retryPersist(ctx, userID, spaceID, func() error {
c.initializeIfNeeded(userID, spaceID)
rss, _ := c.ReceivedSpaces.Load(userID)
@@ -224,56 +180,12 @@ func (c *Cache) Remove(ctx context.Context, userID, spaceID, shareID string) err
}
return c.persist(ctx, userID)
}
log := appctx.GetLogger(ctx).With().
Str("hostname", os.Getenv("HOSTNAME")).
Str("userID", userID).
Str("spaceID", spaceID).Logger()
var err error
for attempt := 0; attempt < 20; attempt++ {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
err = persistFunc()
switch err.(type) {
case nil:
span.SetStatus(codes.Ok, "")
return nil
case errtypes.Aborted:
log.Debug().Msg("aborted when persisting added received share: etag changed. retrying...")
// this is the expected status code from the server when the if-match etag check fails
// continue with sync below
case errtypes.PreconditionFailed:
log.Debug().Msg("precondition failed when persisting added received share: etag changed. retrying...")
// actually, this is the wrong status code and we treat it like errtypes.Aborted because of inconsistencies on the server side
// continue with sync below
case errtypes.AlreadyExists:
log.Debug().Msg("already exists when persisting added received share. retrying...")
// CS3 uses an already exists error instead of precondition failed when using an If-None-Match=* header / IfExists flag in the InitiateFileUpload call.
// Thas happens when the cache thinks there is no file.
// continue with sync below
default:
span.SetStatus(codes.Error, fmt.Sprintf("persisting added received share failed. giving up: %s", err.Error()))
log.Error().Err(err).Msg("persisting added received share failed")
return err
}
timer := time.NewTimer(expBackoff(attempt))
select {
case <-timer.C:
case <-ctx.Done():
timer.Stop()
return ctx.Err()
}
if err := c.syncWithLock(ctx, userID); err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
log.Error().Err(err).Msg("persisting added received share failed. giving up.")
return err
}
})
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
} else {
span.SetStatus(codes.Ok, "")
}
return err
}
@@ -281,13 +193,14 @@ func (c *Cache) Remove(ctx context.Context, userID, spaceID, shareID string) err
// List returns a list of received shares for a given user
// The return list is guaranteed to be thread-safe
func (c *Cache) List(ctx context.Context, userID string) (map[string]*Space, error) {
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "Grab lock")
unlock := c.lockUser(userID)
span.End()
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "List")
defer span.End()
span.SetAttributes(attribute.String("cs3.userid", userID))
unlock := c.lockUser(userID)
defer unlock()
err := c.syncWithLock(ctx, userID)
err := c.syncIfStale(ctx, userID)
if err != nil {
return nil, err
}
@@ -310,8 +223,71 @@ func (c *Cache) List(ctx context.Context, userID string) (map[string]*Space, err
return spaces, nil
}
func (c *Cache) syncWithLock(ctx context.Context, userID string) error {
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "Sync")
func isSyncTransient(err error) bool {
_, isTooEarly := err.(errtypes.IsTooEarly)
_, isInternal := err.(errtypes.IsInternalError)
return isTooEarly || isInternal
}
func (c *Cache) retryPersist(ctx context.Context, userID, spaceID string, persistFunc func() error) error {
log := appctx.GetLogger(ctx).With().
Str("hostname", os.Getenv("HOSTNAME")).
Str("userID", userID).
Str("spaceID", spaceID).Logger()
var err error
for attempt := 0; attempt < 20; attempt++ {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
err = persistFunc()
switch err.(type) {
case nil:
return nil
case errtypes.Aborted:
// this is the expected status code from the server when the if-match etag check fails
// continue with sync below
log.Debug().Int("attempt", attempt).Msg("CAS failed: Aborted (etag changed), retrying")
case errtypes.PreconditionFailed:
// actually, this is the wrong status code and we treat it like errtypes.Aborted because of inconsistencies on the server side
// continue with sync below
log.Debug().Int("attempt", attempt).Msg("CAS failed: PreconditionFailed (etag changed), retrying")
case errtypes.AlreadyExists:
// CS3 uses an already exists error instead of precondition failed when using an If-None-Match=* header / IfExists flag in the InitiateFileUpload call.
// Thas happens when the cache thinks there is no file.
// continue with sync below
log.Debug().Int("attempt", attempt).Msg("CAS failed: AlreadyExists (file created concurrently), retrying")
case errtypes.TooEarly:
// storage-system has an upload in progress for this node; wait for it to finish
// continue with sync below
log.Debug().Int("attempt", attempt).Msg("CAS failed: TooEarly (upload in progress), retrying")
default:
log.Error().Int("attempt", attempt).Err(err).Msg("persisting received share failed, giving up")
return err
}
timer := time.NewTimer(expBackoff(attempt))
select {
case <-timer.C:
case <-ctx.Done():
timer.Stop()
return ctx.Err()
}
if serr := c.syncIfStale(ctx, userID); serr != nil {
if !isSyncTransient(serr) {
log.Error().Int("attempt", attempt).Err(serr).Msg("lost update: re-read failed, aborting")
return serr
}
log.Warn().Int("attempt", attempt).Err(serr).Msg("lost update: re-read before retry")
}
}
return err
}
// syncIfStale pulls the authoritative state from storage when the local replica is stale; caller must hold the user lock.
func (c *Cache) syncIfStale(ctx context.Context, userID string) error {
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "SyncIfStale")
defer span.End()
span.SetAttributes(attribute.String("cs3.userid", userID))
@@ -340,8 +316,12 @@ func (c *Cache) syncWithLock(ctx context.Context, userID string) error {
span.SetStatus(codes.Ok, "")
return nil
default:
span.SetStatus(codes.Error, fmt.Sprintf("Failed to download the received share: %s", err.Error()))
log.Error().Err(err).Msg("Failed to download the received share")
span.SetStatus(codes.Error, err.Error())
if isSyncTransient(err) {
log.Warn().Err(err).Msg("lost update: re-read transient error")
} else {
log.Error().Err(err).Msg("lost update: re-read failed")
}
return err
}
@@ -402,7 +382,6 @@ func (c *Cache) persist(ctx context.Context, userID string) error {
return err
}
rss.etag = res.Etag
span.SetStatus(codes.Ok, "")
return nil
}
+14 -3
View File
@@ -21,6 +21,7 @@ package cache
import (
"context"
"fmt"
"strconv"
"strings"
"sync"
"time"
@@ -51,6 +52,9 @@ type Config struct {
DisablePersistence bool `mapstructure:"cache_disable_persistence"`
AuthUsername string `mapstructure:"cache_auth_username"`
AuthPassword string `mapstructure:"cache_auth_password"`
EnableTLS bool `mapstructure:"cache_enable_tls"`
TLSInsecure bool `mapstructure:"cache_tls_insecure"`
TLSRootCACert string `mapstructure:"cache_tls_root_ca_certificate"`
}
// Cache handles key value operations on caches
@@ -86,13 +90,19 @@ type FileMetadataCache interface {
RemoveMetadata(path string) error
}
func cacheKey(cfg Config) string {
return strings.Join(append(append([]string{cfg.Store}, cfg.Nodes...),
cfg.Database, cfg.Table,
strconv.FormatBool(cfg.EnableTLS)+":"+strconv.FormatBool(cfg.TLSInsecure)+":"+cfg.TLSRootCACert), ":")
}
// GetStatCache will return an existing StatCache for the given store, nodes, database and table
// If it does not exist yet it will be created, different TTLs are ignored
func GetStatCache(cfg Config) StatCache {
mutex.Lock()
defer mutex.Unlock()
key := strings.Join(append(append([]string{cfg.Store}, cfg.Nodes...), cfg.Database, cfg.Table), ":")
key := cacheKey(cfg)
if statCaches[key] == nil {
statCaches[key] = NewStatCache(cfg)
}
@@ -105,7 +115,7 @@ func GetProviderCache(cfg Config) ProviderCache {
mutex.Lock()
defer mutex.Unlock()
key := strings.Join(append(append([]string{cfg.Store}, cfg.Nodes...), cfg.Database, cfg.Table), ":")
key := cacheKey(cfg)
if providerCaches[key] == nil {
providerCaches[key] = NewProviderCache(cfg)
}
@@ -118,7 +128,7 @@ func GetFileMetadataCache(cfg Config) FileMetadataCache {
mutex.Lock()
defer mutex.Unlock()
key := strings.Join(append(append([]string{cfg.Store}, cfg.Nodes...), cfg.Database, cfg.Table), ":")
key := cacheKey(cfg)
if fileMetadataCaches[key] == nil {
fileMetadataCaches[key] = NewFileMetadataCache(cfg)
}
@@ -202,5 +212,6 @@ func getStore(cfg Config) microstore.Store {
store.Size(cfg.Size),
store.DisablePersistence(cfg.DisablePersistence),
store.Authentication(cfg.AuthUsername, cfg.AuthPassword),
store.TLS(cfg.EnableTLS, cfg.TLSInsecure, cfg.TLSRootCACert),
)
}
@@ -44,6 +44,7 @@ func NewStoreIDCache(o *options.Options) *StoreIDCache {
microstore.Table(o.IDCache.Table),
store.DisablePersistence(o.IDCache.DisablePersistence),
store.Authentication(o.IDCache.AuthUsername, o.IDCache.AuthPassword),
store.TLS(o.IDCache.EnableTLS, o.IDCache.TLSInsecure, o.IDCache.TLSRootCACert),
),
}
}
+1
View File
@@ -112,6 +112,7 @@ func New(m map[string]interface{}, stream events.Stream, log *zerolog.Logger) (s
microstore.Table(o.IDCache.Table),
store.DisablePersistence(o.IDCache.DisablePersistence),
store.Authentication(o.IDCache.AuthUsername, o.IDCache.AuthPassword),
store.TLS(o.IDCache.EnableTLS, o.IDCache.TLSInsecure, o.IDCache.TLSRootCACert),
), log)
if err != nil {
return nil, err
@@ -163,6 +163,7 @@ func NewDefault(m map[string]interface{}, bs tree.Blobstore, es events.Stream, l
microstore.Table(o.IDCache.Table),
store.DisablePersistence(o.IDCache.DisablePersistence),
store.Authentication(o.IDCache.AuthUsername, o.IDCache.AuthPassword),
store.TLS(o.IDCache.EnableTLS, o.IDCache.TLSInsecure, o.IDCache.TLSRootCACert),
), log)
permissionsSelector, err := pool.PermissionsSelector(o.PermissionsSVC, pool.WithTLSMode(o.PermTLSMode))
@@ -706,6 +706,9 @@ func (t *Tree) InitNewNode(ctx context.Context, n *node.Node, fsize uint64) (met
h, err := os.OpenFile(n.InternalPath(), os.O_CREATE|os.O_EXCL, 0600)
subspan.End()
if err != nil {
if errors.Is(err, fs.ErrExist) {
return unlock, errtypes.AlreadyExists(n.Name)
}
return unlock, err
}
h.Close()
@@ -136,6 +136,7 @@ func (fs *Decomposedfs) InitiateUpload(ctx context.Context, ref *provider.Refere
_, span := tracer.Start(ctx, "InitiateUpload")
defer span.End()
log := appctx.GetLogger(ctx)
log.Debug().Interface("ref", ref).Msg("decomposedfs:InitiateUpload:start")
// remember the path from the reference
refpath := ref.GetPath()
@@ -336,6 +337,7 @@ func (fs *Decomposedfs) InitiateUpload(ctx context.Context, ref *provider.Refere
}
}
log.Debug().Str("uploadid", session.ID()).Msg("decomposedfs:InitiateUpload:complete")
return map[string]string{
"simple": session.ID(),
"tus": session.ID(),
@@ -114,12 +114,13 @@ func (session *OcisSession) GetReader(ctx context.Context) (io.ReadCloser, error
// implements tusd.DataStore interface
// returns tusd errors
func (session *OcisSession) FinishUpload(ctx context.Context) error {
log := appctx.GetLogger(ctx)
log.Debug().Msg("decomposedfs:FinishUpload:start")
err := session.FinishUploadDecomposed(ctx)
if err != nil {
// this is part of the tusd integration and we might be able to
// log the error in another place
log := appctx.GetLogger(ctx)
log.Error().Err(err).Msg("failed to finish upload")
}
@@ -140,6 +141,7 @@ func (session *OcisSession) FinishUploadDecomposed(ctx context.Context) error {
ctx, span := tracer.Start(session.Context(ctx), "FinishUpload")
defer span.End()
log := appctx.GetLogger(ctx)
log.Debug().Str("session", session.ID()).Msg("decomposedfs:FinishUploadDecomposed:start")
ctx = ctxpkg.ContextSetInitiator(ctx, session.InitiatorID())
@@ -246,6 +248,7 @@ func (session *OcisSession) FinishUploadDecomposed(ctx context.Context) error {
metrics.UploadSessionsFinalized.Inc()
}
log.Debug().Str("session", session.ID()).Msg("decomposedfs:FinishUploadDecomposed:complete")
return session.store.tp.Propagate(ctx, n, session.SizeDiff())
}
+11
View File
@@ -39,6 +39,7 @@ import (
"google.golang.org/grpc/metadata"
"github.com/owncloud/reva/v2/internal/http/services/owncloud/ocdav/net"
"github.com/owncloud/reva/v2/pkg/appctx"
ctxpkg "github.com/owncloud/reva/v2/pkg/ctx"
"github.com/owncloud/reva/v2/pkg/errtypes"
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
@@ -64,6 +65,7 @@ type CS3 struct {
dataGatewayClient *http.Client
}
// NewCS3 returns a new CS3 instance. Use an authenticated context and be sure to define SpaceRoot manually.
func NewCS3(gwAddr, providerAddr string) (s *CS3) {
return &CS3{
@@ -162,6 +164,8 @@ func (cs3 *CS3) SimpleUpload(ctx context.Context, uploadpath string, content []b
ctx, span := tracer.Start(ctx, "SimpleUpload")
defer span.End()
log := appctx.GetLogger(ctx)
log.Debug().Str("path", uploadpath).Msg("cs3.SimpleUpload.start")
_, err := cs3.Upload(ctx, UploadRequest{
Path: uploadpath,
Content: content,
@@ -174,6 +178,9 @@ func (cs3 *CS3) Upload(ctx context.Context, req UploadRequest) (*UploadResponse,
ctx, span := tracer.Start(ctx, "Upload")
defer span.End()
log := appctx.GetLogger(ctx)
log.Debug().Str("path", req.Path).Msg("cs3.Upload.start")
client, err := cs3.providerClient()
if err != nil {
return nil, err
@@ -238,6 +245,8 @@ func (cs3 *CS3) Upload(ctx context.Context, req UploadRequest) (*UploadResponse,
return nil, errors.New("metadata storage doesn't support the simple upload protocol")
}
log.Debug().Str("path", req.Path).Str("endpoint", endpoint).Msg("cs3.Upload.initiate_done")
httpReq, err := http.NewRequest(http.MethodPut, endpoint, bytes.NewReader(req.Content))
if err != nil {
return nil, err
@@ -253,6 +262,7 @@ func (cs3 *CS3) Upload(ctx context.Context, req UploadRequest) (*UploadResponse,
return nil, err
}
defer resp.Body.Close()
log.Debug().Str("path", req.Path).Int("status", resp.StatusCode).Msg("cs3.Upload.put_done")
if err := errtypes.NewErrtypeFromHTTPStatusCode(resp.StatusCode, httpReq.URL.Path); err != nil {
return nil, err
}
@@ -260,6 +270,7 @@ func (cs3 *CS3) Upload(ctx context.Context, req UploadRequest) (*UploadResponse,
if ocEtag := resp.Header.Get("OC-ETag"); ocEtag != "" {
etag = ocEtag
}
log.Debug().Str("path", req.Path).Str("etag", etag).Msg("cs3.Upload.complete")
return &UploadResponse{
Etag: etag,
FileID: resp.Header.Get("OC-Fileid"),
+20
View File
@@ -25,6 +25,8 @@ import (
"go-micro.dev/v4/store"
)
type tlsContextKey struct{}
type typeContextKey struct{}
// Store determines the implementation:
@@ -103,3 +105,21 @@ func Authentication(username, password string) store.Option {
o.Context = context.WithValue(o.Context, authenticationContextKey{}, []string{username, password})
}
}
type tlsOptions struct {
enable bool
insecure bool
rootCACert string
}
// TLS configures TLS for the nats-js and nats-js-kv store backends.
// enable activates TLS; insecure skips certificate verification (for self-signed certs);
// rootCACert is an optional path to a PEM file used to validate the server certificate.
func TLS(enable bool, insecure bool, rootCACert string) store.Option {
return func(o *store.Options) {
if o.Context == nil {
o.Context = context.Background()
}
o.Context = context.WithValue(o.Context, tlsContextKey{}, tlsOptions{enable, insecure, rootCACert})
}
}
+35
View File
@@ -20,6 +20,9 @@ package store
import (
"context"
"crypto/tls"
"crypto/x509"
"os"
"strings"
"time"
@@ -66,6 +69,12 @@ func Create(opts ...microstore.Option) microstore.Store {
storeType, _ := options.Context.Value(typeContextKey{}).(string)
if tlsOpts, ok := options.Context.Value(tlsContextKey{}).(tlsOptions); ok && tlsOpts.enable &&
storeType != TypeNatsJS && storeType != TypeNatsJSKV {
logger.Logf(logger.WarnLevel,
"reva-store: TLS requested but store type %q does not support TLS — settings ignored", storeType)
}
switch storeType {
case TypeNoop:
return microstore.NewNoopStore(opts...)
@@ -174,6 +183,10 @@ func defaultNatsOptions(options *microstore.Options) nats.Options {
natsOptions.User = auth[0]
natsOptions.Password = auth[1]
}
if tlsOpts, ok := options.Context.Value(tlsContextKey{}).(tlsOptions); ok && tlsOpts.enable {
natsOptions.TLSConfig = BuildNatsTLSConfig(tlsOpts.insecure, tlsOpts.rootCACert)
natsOptions.Secure = true
}
natsOptions.DisconnectedErrCB = func(_ *nats.Conn, err error) {
logger.Logf(logger.WarnLevel, "reva-store: nats connection disconnected: %v", err)
}
@@ -185,3 +198,25 @@ func defaultNatsOptions(options *microstore.Options) nats.Options {
}
return natsOptions
}
// BuildNatsTLSConfig constructs a tls.Config for NATS client connections.
// insecure skips certificate verification; rootCACert is an optional path to a
// PEM file whose CA is used to validate the server certificate.
func BuildNatsTLSConfig(insecure bool, rootCACert string) *tls.Config {
tlsConf := &tls.Config{MinVersion: tls.VersionTLS12, InsecureSkipVerify: insecure} //nolint:gosec
if rootCACert != "" {
b, err := os.ReadFile(rootCACert)
if err != nil {
logger.Logf(logger.WarnLevel, "reva-store: failed to read TLS root CA cert %q: %v", rootCACert, err)
} else {
pool := x509.NewCertPool()
if pool.AppendCertsFromPEM(b) {
tlsConf.RootCAs = pool
tlsConf.InsecureSkipVerify = false
} else {
logger.Logf(logger.WarnLevel, "reva-store: no valid PEM certificates found in %q", rootCACert)
}
}
}
return tlsConf
}
+1 -1
View File
@@ -1328,7 +1328,7 @@ github.com/orcaman/concurrent-map
# github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245
## explicit; go 1.18
github.com/owncloud/libre-graph-api-go
# github.com/owncloud/reva/v2 v2.0.0-20260807092659-5e5d7767ea70
# github.com/owncloud/reva/v2 v2.0.0-20260813081456-8ed15f4851e1
## explicit; go 1.25.8
github.com/owncloud/reva/v2/cmd/revad/internal/grace
github.com/owncloud/reva/v2/cmd/revad/runtime