build: bump reva to the first part of the audit log (#4134)

Assisted-by: Claude Code:claude-opus-5-5
This commit is contained in:
Michael Barz authored and GitHub committed 2026-11-26 13:28:08 +00:00
1 parent 335e482a96
commit 8a88976436
60 files changed
+3091 -176

No files matched your search

+1 -1
View File
@@ -69,7 +69,7 @@ require (
github.com/open-policy-agent/opa v1.21.1
github.com/opencloud-eu/icap-client v0.0.0-20250930132611-28a2afe62d89
github.com/opencloud-eu/libre-graph-api-go v1.0.9-0.20261119152805-1a7a500a264e
github.com/opencloud-eu/reva/v3 v3.0.2-0.20261123180324-2b2b8732790b
github.com/opencloud-eu/reva/v3 v3.0.2-0.20261126092628-02d5d9ba9a18
github.com/opensearch-project/opensearch-go/v4 v4.7.3
github.com/orcaman/concurrent-map v1.0.0
github.com/pkg/errors v0.9.1
+2 -2
View File
@@ -761,8 +761,8 @@ github.com/opencloud-eu/icap-client v0.0.0-20250930132611-28a2afe62d89 h1:W1ms+l
github.com/opencloud-eu/icap-client v0.0.0-20250930132611-28a2afe62d89/go.mod h1:vigJkNss1N2QEceCuNw/ullDehncuJNFB6mEnzfq9UI=
github.com/opencloud-eu/libre-graph-api-go v1.0.9-0.20261119152805-1a7a500a264e h1:5sf3dNw/eYuuvDL8+3c4pbPSX+Pblw6lsylGtq+cw30=
github.com/opencloud-eu/libre-graph-api-go v1.0.9-0.20261119152805-1a7a500a264e/go.mod h1:lTM8JeGblNpoMySTW7Lui2+c5TTLI95mwxtdUIHHrhU=
github.com/opencloud-eu/reva/v3 v3.0.2-0.20261123180324-2b2b8732790b h1:4ltltng9ieAVaoIRa+VgKoZp1L0Ta6vj6B5noh+UktE=
github.com/opencloud-eu/reva/v3 v3.0.2-0.20261123180324-2b2b8732790b/go.mod h1:oqi8rN/Nt2v+Gn/dmY9p2Zct3VHrdvnYtqZWHrjij7M=
github.com/opencloud-eu/reva/v3 v3.0.2-0.20261126092628-02d5d9ba9a18 h1:yXO3rKf82pb8oaRhokDLTjZWSqZpAHpdWtnT35y+Q5Q=
github.com/opencloud-eu/reva/v3 v3.0.2-0.20261126092628-02d5d9ba9a18/go.mod h1:oqi8rN/Nt2v+Gn/dmY9p2Zct3VHrdvnYtqZWHrjij7M=
github.com/opencloud-eu/secure v0.0.0-20260312082735-b6f5cb2244e4 h1:l2oB/RctH+t8r7QBj5p8thfEHCM/jF35aAY3WQ3hADI=
github.com/opencloud-eu/secure v0.0.0-20260312082735-b6f5cb2244e4/go.mod h1:BmF5hyM6tXczk3MpQkFf1hpKSRqCyhqcbiQtiAF7+40=
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
@@ -0,0 +1,48 @@
// Package auditctx passes the audit request context on to the next service,
// like the useragent interceptor does with the user agent.
package auditctx
import (
"context"
"github.com/opencloud-eu/reva/v3/pkg/audit"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
// NewUnary returns a unary interceptor that keeps the audit request context
// for this service and its outgoing calls.
func NewUnary() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
return handler(withRequestContext(ctx), req)
}
}
// NewStream returns a stream interceptor that keeps the audit request context
// for this service and its outgoing calls.
func NewStream() grpc.StreamServerInterceptor {
return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
return handler(srv, &wrappedServerStream{ServerStream: ss, ctx: withRequestContext(ss.Context())})
}
}
func withRequestContext(ctx context.Context) context.Context {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return ctx
}
lst := md.Get(audit.Header)
if len(lst) == 0 {
return ctx
}
return audit.ContextSetRequest(ctx, audit.ParseRequestContext(lst[0]))
}
type wrappedServerStream struct {
grpc.ServerStream
ctx context.Context
}
func (ss *wrappedServerStream) Context() context.Context {
return ss.ctx
}
@@ -0,0 +1,86 @@
package eventsmiddleware
import (
"context"
"strings"
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
"github.com/go-viper/mapstructure/v2"
"github.com/opencloud-eu/reva/v3/pkg/audit"
"github.com/opencloud-eu/reva/v3/pkg/events/raw"
"github.com/opencloud-eu/reva/v3/pkg/storagespace"
)
// The audit events of the CS3 calls, one file per area: files, folders, trash
// bin and versions in audit_files.go, shares and space members in
// audit_share.go, public links in audit_link.go and spaces in audit_space.go.
// auditConfig is the audit part of the middleware config.
type auditConfig struct {
Enabled bool `mapstructure:"audit_enabled"`
Mode string `mapstructure:"audit_mode"`
Service string `mapstructure:"audit_service"`
Version string `mapstructure:"audit_service_version"`
}
// emitterFromConfig returns the audit emitter, a discarding one when audit is off.
func emitterFromConfig(m map[string]interface{}) (audit.Emitter, error) {
var ac auditConfig
if err := mapstructure.Decode(m, &ac); err != nil {
return nil, err
}
var nc raw.Config
if err := mapstructure.Decode(m, &nc); err != nil {
return nil, err
}
name, _ := m["name"].(string)
return audit.EmitterFromConfig(context.Background(), name+"-audit", audit.EmitterConfig{
Enabled: ac.Enabled,
Mode: ac.Mode,
Service: ac.Service,
ServiceVersion: ac.Version,
Nats: nc,
}, audit.Options{})
}
// outcome maps a CS3 status to the audit outcome and reason.
func outcome(s *rpc.Status) (audit.Outcome, string) {
switch s.GetCode() {
case rpc.Code_CODE_OK:
return audit.OutcomeSuccess, ""
case rpc.Code_CODE_PERMISSION_DENIED:
return audit.OutcomeDenied, "permission_denied"
case rpc.Code_CODE_UNAUTHENTICATED:
return audit.OutcomeDenied, "unauthenticated"
default:
return audit.OutcomeFailure, strings.ToLower(strings.TrimPrefix(s.GetCode().String(), "CODE_"))
}
}
// auditEvent turns a CS3 call into an audit event. item is filled by the
// storage driver with the type, ID and name of the item the call acts on. The
// type is needed for move, delete, restore and purge; when it is unknown,
// e.g. because the item doesn't exist, no event is emitted for these calls.
func auditEvent(req, res interface{}, item *storagespace.ItemSlot) (audit.Event, bool) {
if item == nil {
item = &storagespace.ItemSlot{}
}
// every area knows its own calls and returns false for all others
for _, area := range []func(req, res interface{}, item *storagespace.ItemSlot) (audit.Event, bool){
fileEvent, shareEvent, linkEvent, spaceEvent,
} {
ev, ok := area(req, res, item)
if !ok {
continue
}
if s, ok := res.(su); ok && ev.Outcome == "" {
ev.Outcome, ev.Reason = outcome(s.GetStatus())
}
if ev.Target.ID == "" {
// a failed call may not tell us more than this
ev.Target.ID = "unknown"
}
return ev, true
}
return audit.Event{}, false
}
@@ -0,0 +1,183 @@
package eventsmiddleware
import (
"path"
"strings"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/opencloud-eu/reva/v3/pkg/audit"
"github.com/opencloud-eu/reva/v3/pkg/storagespace"
"github.com/opencloud-eu/reva/v3/pkg/utils"
)
// fileEvent audits the calls on files and folders, the trash bin and versions.
func fileEvent(req, res interface{}, item *storagespace.ItemSlot) (audit.Event, bool) {
itemType := item.Type
var ev audit.Event
switch res.(type) {
case *provider.MoveResponse:
r := req.(*provider.MoveRequest)
src, dst := r.GetSource(), r.GetDestination()
d := pick(itemType, audit.FileMove, audit.FolderMove)
if sameParent(src, dst) {
d = pick(itemType, audit.FileRename, audit.FolderRename)
}
if d == nil {
return ev, false
}
ev = audit.Event{Definition: d, Target: refTarget(src, item)}
before, after := movePaths(src, dst, item)
if before != "" {
ev.Change = &audit.Change{Before: map[string]any{"path": before}}
}
if after != "" {
if ev.Change == nil {
ev.Change = &audit.Change{}
}
ev.Change.After = map[string]any{"path": after}
}
case *provider.DeleteResponse:
d := pick(itemType, audit.FileDelete, audit.FolderDelete)
if d == nil {
return ev, false
}
ev = audit.Event{Definition: d, Target: refTarget(req.(*provider.DeleteRequest).GetRef(), item)}
case *provider.RestoreRecycleItemResponse:
d := pick(itemType, audit.FileRestore, audit.FolderRestore)
if d == nil {
return ev, false
}
r := req.(*provider.RestoreRecycleItemRequest)
ev = audit.Event{Definition: d, Target: trashTarget(r.GetRef(), r.GetKey(), item)}
case *provider.CreateContainerResponse:
r := req.(*provider.CreateContainerRequest)
ev = audit.Event{Definition: audit.FolderCreate, Target: refTarget(r.GetRef(), item)}
case *provider.SetLockResponse:
ev = audit.Event{Definition: audit.FileLock, Target: refTarget(req.(*provider.SetLockRequest).GetRef(), item)}
case *provider.UnlockResponse:
ev = audit.Event{Definition: audit.FileUnlock, Target: refTarget(req.(*provider.UnlockRequest).GetRef(), item)}
case *provider.RestoreFileVersionResponse:
ev = audit.Event{Definition: audit.FileVersionRestore, Target: refTarget(req.(*provider.RestoreFileVersionRequest).GetRef(), item)}
case *provider.PurgeRecycleResponse:
r := req.(*provider.PurgeRecycleRequest)
id := r.GetRef().GetResourceId()
if id != nil && id.GetOpaqueId() == id.GetSpaceId() && r.GetKey() == "" {
ev = audit.Event{Definition: audit.TrashPurgeAll, Target: spaceTarget(id)}
break
}
d := pick(itemType, audit.FilePurge, audit.FolderPurge)
if d == nil {
return ev, false
}
ev = audit.Event{Definition: d, Target: trashTarget(r.GetRef(), r.GetKey(), item)}
default:
return ev, false
}
return ev, true
}
// pick returns the file or the folder definition, nil when the type is unknown.
func pick(t provider.ResourceType, file, folder *audit.Definition) *audit.Definition {
switch t {
case provider.ResourceType_RESOURCE_TYPE_CONTAINER:
return folder
case provider.ResourceType_RESOURCE_TYPE_FILE, provider.ResourceType_RESOURCE_TYPE_SYMLINK, provider.ResourceType_RESOURCE_TYPE_REFERENCE:
return file
default:
return nil
}
}
// sameParent reports whether a move only changes the name.
func sameParent(src, dst *provider.Reference) bool {
if src.GetPath() == "" || dst.GetPath() == "" {
return false
}
return storagespace.FormatResourceID(src.GetResourceId()) == storagespace.FormatResourceID(dst.GetResourceId()) &&
path.Dir(src.GetPath()) == path.Dir(dst.GetPath())
}
// trashTarget identifies a trash bin item in the space of ref: by the ID the
// item had before it was deleted, when the driver reported it, else by its
// trash key.
func trashTarget(ref *provider.Reference, key string, item *storagespace.ItemSlot) audit.Target {
t := audit.Target{ID: key, Name: item.Name, Path: itemPath(item)}
if rid := ref.GetResourceId(); rid != nil {
t.SpaceID = storagespace.FormatStorageID(rid.GetStorageId(), rid.GetSpaceId())
}
if id := itemID(ref, item); id != "" {
t.ID = id
}
return t
}
// refTarget identifies the item of ref by its ID, when the driver reported
// it. A call that failed before the item was found only has the reference.
func refTarget(ref *provider.Reference, item *storagespace.ItemSlot) audit.Target {
t := audit.Target{ID: itemID(ref, item), Path: refPath(ref, item), Name: item.Name}
if t.ID == "" {
t.ID, _ = storagespace.FormatReference(ref)
}
if rid := ref.GetResourceId(); rid != nil {
t.SpaceID = storagespace.FormatStorageID(rid.GetStorageId(), rid.GetSpaceId())
}
if p := ref.GetPath(); p != "" && p != "." {
t.Name = path.Base(p)
}
return t
}
// refPath is the path of the item in its space. The path of a request is
// only that when the request starts at the space root; a request through a
// share, a link or by ID gets the path from the driver.
func refPath(ref *provider.Reference, item *storagespace.ItemSlot) string {
if p := itemPath(item); p != "" {
return p
}
if utils.IsSpaceRootedReference(ref) {
return ref.GetPath()
}
return ""
}
// movePaths returns the paths in the space before and after a move. The
// driver knows the path of the source; a destination relative to the same
// node as the source is put under the same prefix.
func movePaths(src, dst *provider.Reference, item *storagespace.ItemSlot) (before, after string) {
before = refPath(src, item)
switch {
case utils.IsSpaceRootedReference(dst):
after = dst.GetPath()
case before != "" && utils.IsRelativeReference(dst) && utils.ResourceIDEqual(src.GetResourceId(), dst.GetResourceId()):
rel := path.Clean(src.GetPath())
if rel == "." {
break
}
if prefix, ok := strings.CutSuffix(before, rel); ok {
after = utils.MakeRelativePath(path.Join(prefix, dst.GetPath()))
}
}
return before, after
}
// itemPath is the path in the space the driver reported, like the paths of
// requests: "./folder/file".
func itemPath(item *storagespace.ItemSlot) string {
if item.Path == "" || item.Path == "/" {
return ""
}
return utils.MakeRelativePath(item.Path)
}
// itemID formats the ID the driver reported, with the storage ID of ref,
// which the driver doesn't know.
func itemID(ref *provider.Reference, item *storagespace.ItemSlot) string {
if item.ID.GetOpaqueId() == "" {
return ""
}
return storagespace.FormatResourceID(&provider.ResourceId{
StorageId: ref.GetResourceId().GetStorageId(),
SpaceId: item.ID.GetSpaceId(),
OpaqueId: item.ID.GetOpaqueId(),
})
}
@@ -0,0 +1,164 @@
package eventsmiddleware
import (
"context"
"crypto/sha256"
"encoding/hex"
"sync"
"time"
link "github.com/cs3org/go-cs3apis/cs3/sharing/link/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/opencloud-eu/reva/v3/pkg/audit"
"github.com/opencloud-eu/reva/v3/pkg/storagespace"
"github.com/opencloud-eu/reva/v3/pkg/utils"
"go.opentelemetry.io/otel/trace"
)
// linkEvent audits the calls on public links, also the token lookups that
// open a link.
func linkEvent(req, res interface{}, _ *storagespace.ItemSlot) (audit.Event, bool) {
var ev audit.Event
switch v := res.(type) {
case *link.CreatePublicShareResponse:
r := req.(*link.CreatePublicShareRequest)
ev = audit.Event{Definition: audit.PublicLinkCreate, Target: shareTarget(v.GetShare().GetId().GetOpaqueId(), r.GetResourceInfo().GetId(), r.GetResourceInfo().GetName())}
ev.Target.Type = "public_link"
ev.Change = linkCreated(r, v)
case *link.UpdatePublicShareResponse:
r := req.(*link.UpdatePublicShareRequest)
ev = audit.Event{Definition: audit.PublicLinkUpdate, Target: shareTarget(r.GetRef().GetId().GetOpaqueId(), v.GetShare().GetResourceId(), utils.ReadPlainFromOpaque(v.GetOpaque(), "resourcename"))}
ev.Change = linkUpdated(r, v)
case *link.GetPublicShareByTokenResponse:
return publicLinkAccess(req.(*link.GetPublicShareByTokenRequest), v)
case *link.RemovePublicShareResponse:
r := req.(*link.RemovePublicShareRequest)
var rid *provider.ResourceId
_ = utils.ReadJSONFromOpaque(v.GetOpaque(), "resourceid", &rid)
ev = audit.Event{Definition: audit.PublicLinkDelete, Target: shareTarget(r.GetRef().GetId().GetOpaqueId(), rid, utils.ReadPlainFromOpaque(v.GetOpaque(), "resourcename"))}
ev.Change = linkRemoved(v.GetOpaque())
default:
return ev, false
}
return ev, true
}
// publicLinkAccess audits a token lookup. The share ID identifies the link;
// when the lookup failed there is none and a hash of the token is used, never
// the token itself. A denial without any credentials is the web client asking
// whether a link needs a password, not an attempt, and is left out.
func publicLinkAccess(r *link.GetPublicShareByTokenRequest, res *link.GetPublicShareByTokenResponse) (audit.Event, bool) {
ev := audit.Event{Definition: audit.PublicLinkAccess}
ev.Outcome, ev.Reason = outcome(res.GetStatus())
if s := res.GetShare(); s.GetId().GetOpaqueId() != "" {
ev.Target = shareTarget(s.GetId().GetOpaqueId(), s.GetResourceId(), "")
} else {
ev.Target = audit.Target{ID: "token:" + tokenHash(r.GetToken())}
}
ev.Target.Type = "public_link"
ev.Actor = &audit.Actor{Type: audit.ActorPublicLink, ID: ev.Target.ID}
if ev.Outcome == audit.OutcomeDenied {
switch {
case r.GetAuthentication().GetPassword() != "":
ev.Reason = "invalid_password"
// ocdav sends an empty signature when the request has no credentials
case r.GetAuthentication().GetSignature().GetSignature() != "":
ev.Reason = "invalid_signature"
default:
return ev, false
}
}
return ev, true
}
func tokenHash(token string) string {
sum := sha256.Sum256([]byte(token))
return hex.EncodeToString(sum[:8])
}
// accessWindow is how long repeated successful accesses of a link by the same
// client count as one access. Opening a link makes many requests, and every
// one of them looks the token up again.
const accessWindow = 30 * time.Minute
// failureWindow is how long a failed access is remembered. The proxy and ocdav
// check the credentials of the same request one after the other.
const failureWindow = 10 * time.Second
// maxRemembered limits the keys of one onceWithin. When it is full, an access
// is reported each time instead of growing the map.
const maxRemembered = 10000
// onceWithin remembers keys for a while, to report each access only once.
type onceWithin struct {
mu sync.Mutex
window time.Duration
max int
seen map[string]time.Time
nextSweep time.Time
}
func newOnceWithin(window time.Duration, max int) *onceWithin {
return &onceWithin{window: window, max: max, seen: map[string]time.Time{}}
}
// first reports whether key was not seen within the window, and remembers it.
// Expired keys are removed once per window, not on every call.
func (o *onceWithin) first(key string, now time.Time) bool {
o.mu.Lock()
defer o.mu.Unlock()
if t, ok := o.seen[key]; ok && now.Sub(t) < o.window {
return false
}
if !now.Before(o.nextSweep) {
for k, t := range o.seen {
if now.Sub(t) >= o.window {
delete(o.seen, k)
}
}
o.nextSweep = now.Add(o.window)
}
if len(o.seen) < o.max {
o.seen[key] = now
}
return true
}
// linkAccesses remembers successful and failed link accesses apart, failures
// only for a few seconds: someone trying passwords makes a new one each time.
type linkAccesses struct {
successes *onceWithin
failures *onceWithin
}
func newLinkAccesses() *linkAccesses {
return &linkAccesses{
successes: newOnceWithin(accessWindow, maxRemembered),
failures: newOnceWithin(failureWindow, maxRemembered),
}
}
// firstLinkAccess drops repeated successful accesses of a link by the same
// client, and successful ones without a client request. A failed one counts
// once per request: the proxy and ocdav both check the credentials of a
// request to public-files.
func firstLinkAccess(ctx context.Context, a *linkAccesses, ev audit.Event) bool {
if ev.Definition != audit.PublicLinkAccess {
return true
}
if ev.Outcome != audit.OutcomeSuccess {
tid := trace.SpanContextFromContext(ctx).TraceID()
if !tid.IsValid() {
return true
}
return a.failures.first(ev.Target.ID+"|"+ev.Reason+"|"+tid.String(), time.Now())
}
rc, ok := audit.ContextGetRequest(ctx)
if !ok || rc.IsZero() {
// a service resolving the link, e.g. after an upload, is no client
return false
}
return a.successes.first(ev.Target.ID+"|"+rc.ClientAddress+"|"+rc.SessionID, time.Now())
}
@@ -0,0 +1,352 @@
package eventsmiddleware
import (
"context"
"path"
"slices"
"time"
groupv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/group/v1beta1"
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/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"
typesv1beta1 "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
"google.golang.org/protobuf/reflect/protoreflect"
"github.com/opencloud-eu/reva/v3/pkg/audit"
"github.com/opencloud-eu/reva/v3/pkg/conversions"
ctxpkg "github.com/opencloud-eu/reva/v3/pkg/ctx"
"github.com/opencloud-eu/reva/v3/pkg/storage/utils/grants"
"github.com/opencloud-eu/reva/v3/pkg/storagespace"
"github.com/opencloud-eu/reva/v3/pkg/utils"
)
// The keys of share, space member and public link changes. A share or member
// change always names the recipient, a role change the new role.
const (
keyRecipientType = "recipient_type"
keyRecipient = "recipient"
keyRole = "role"
keyPermissions = "permissions"
keyExpiration = "expiration"
keyPassword = "password"
)
// roleCustom is the role of permissions that match no known role.
const roleCustom = "custom"
// recipient adds the grantee to m.
func recipient(m map[string]any, g *provider.Grantee) {
switch {
case g.GetUserId() != nil:
m[keyRecipientType], m[keyRecipient] = "user", g.GetUserId().GetOpaqueId()
case g.GetGroupId() != nil:
m[keyRecipientType], m[keyRecipient] = "group", g.GetGroupId().GetOpaqueId()
}
}
// knownRole is a reva role a unified role is built from. The names are set
// here, some constructors share a name, e.g. the file editor is "editor".
type knownRole struct {
name string
perms func() *conversions.Role
space bool
}
// roles are matched in this order. viewer-list-grants and spaceviewer,
// editor-list-grants and spaceeditor-without-versions have the same
// permissions; on a space root the space roles win, everywhere else the others.
var roles = []knownRole{
{conversions.RoleViewer, conversions.NewViewerRole, false},
{conversions.RoleViewerWithVersions, conversions.NewViewerWithVersionsRole, false},
{conversions.RoleViewerListGrants, conversions.NewViewerListGrantsRole, false},
{conversions.RoleEditor, conversions.NewEditorRole, false},
{conversions.RoleEditorWithVersions, conversions.NewEditorWithVersionsRole, false},
{conversions.RoleEditorListGrants, conversions.NewEditorListGrantsRole, false},
{conversions.RoleEditorListGrantsWithVersions, conversions.NewEditorListGrantsWithVersionsRole, false},
{conversions.RoleFileEditor, conversions.NewFileEditorRole, false},
{conversions.RoleFileEditorWithVersions, conversions.NewFileEditorWithVersionsRole, false},
{conversions.RoleFileEditorListGrants, conversions.NewFileEditorListGrantsRole, false},
{conversions.RoleFileEditorListGrantsWithVersions, conversions.NewFileEditorListGrantsWithVersionsRole, false},
{conversions.RoleEditorLite, conversions.NewEditorLiteRole, false},
{conversions.RoleUploader, conversions.NewUploaderRole, false},
{conversions.RoleSecureViewer, conversions.NewSecureViewerRole, false},
{conversions.RoleCoowner, conversions.NewCoownerRole, false},
{conversions.RoleSpaceViewer, conversions.NewSpaceViewerRole, true},
{conversions.RoleSpaceViewerWithVersions, conversions.NewSpaceViewerWithVersionsRole, true},
{conversions.RoleSpaceEditor, conversions.NewSpaceEditorRole, true},
{conversions.RoleSpaceEditorWithoutVersions, conversions.NewSpaceEditorWithoutVersionsRole, true},
{conversions.RoleSpaceEditorWithoutTrashbin, conversions.NewSpaceEditorWithoutTrashbinRole, true},
{conversions.RoleSpaceEditorWithoutVersionsWithoutTrashbin, conversions.NewSpaceEditorWithoutVersionsWithoutTrashbinRole, true},
{conversions.RoleManager, conversions.NewManagerRole, true},
}
// role adds the role of the permissions to m: the reva role with exactly
// these permissions, the one a unified role is built from, or "custom" with
// the permission names. space tells a space member from a share.
func role(m map[string]any, p *provider.ResourcePermissions, isLink, space bool) {
if p == nil {
return
}
if grants.PermissionsEqual(p, &provider.ResourcePermissions{}) {
// empty permissions deny access, on a link they make an internal link
m[keyRole] = conversions.RoleDenied
if isLink {
m[keyRole] = "internal"
}
return
}
for _, preferred := range []bool{true, false} {
for _, r := range roles {
if (r.space == space) == preferred && grants.PermissionsEqual(p, r.perms().CS3ResourcePermissions()) {
m[keyRole] = r.name
return
}
}
}
m[keyRole] = roleCustom
m[keyPermissions] = permissionNames(p)
}
// permissionNames lists the granted permissions, e.g. stat, list_container.
func permissionNames(p *provider.ResourcePermissions) []string {
names := []string{}
p.ProtoReflect().Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool {
if fd.Kind() == protoreflect.BoolKind && v.Bool() {
names = append(names, string(fd.Name()))
}
return true
})
return names
}
// expiration adds the expiration date to m, an empty string when it was removed.
func expiration(m map[string]any, ts *typesv1beta1.Timestamp) {
if ts == nil {
m[keyExpiration] = ""
return
}
m[keyExpiration] = time.Unix(int64(ts.GetSeconds()), int64(ts.GetNanos())).UTC().Format(time.RFC3339)
}
// shareCreated describes a new share or space member. The response carries the
// share; a failed request only has the grant that was asked for.
func shareCreated(r *collaboration.CreateShareRequest, res *collaboration.CreateShareResponse) *audit.Change {
g, p, exp := r.GetGrant().GetGrantee(), r.GetGrant().GetPermissions().GetPermissions(), r.GetGrant().GetExpiration()
if s := res.GetShare(); s != nil {
g, p, exp = s.GetGrantee(), s.GetPermissions().GetPermissions(), s.GetExpiration()
}
after := map[string]any{}
recipient(after, g)
role(after, p, false, utils.ExistsInOpaque(res.GetOpaque(), "spacegrant"))
if exp != nil {
expiration(after, exp)
}
return &audit.Change{After: after}
}
// shareUpdated describes what an update changed: the fields of the update
// mask, or of the deprecated field.
func shareUpdated(r *collaboration.UpdateShareRequest, res *collaboration.UpdateShareResponse) *audit.Change {
s := res.GetShare()
if s == nil {
s = r.GetShare()
}
space := utils.ExistsInOpaque(res.GetOpaque(), "spacegrant")
after := map[string]any{}
recipient(after, s.GetGrantee())
for _, p := range r.GetUpdateMask().GetPaths() {
switch p {
case "permissions":
role(after, s.GetPermissions().GetPermissions(), false, space)
case "expiration":
expiration(after, s.GetExpiration())
}
}
if p := r.GetField().GetPermissions(); p != nil {
role(after, p.GetPermissions(), false, space)
}
return &audit.Change{After: after}
}
// shareRemoved describes the removed share from what the share provider put
// into the response.
func shareRemoved(o *typesv1beta1.Opaque) *audit.Change {
before := map[string]any{}
var u *userpb.UserId
var g *groupv1beta1.GroupId
switch {
case utils.ReadJSONFromOpaque(o, "granteeuserid", &u) == nil && u != nil:
recipient(before, &provider.Grantee{Type: provider.GranteeType_GRANTEE_TYPE_USER, Id: &provider.Grantee_UserId{UserId: u}})
case utils.ReadJSONFromOpaque(o, "granteegroupid", &g) == nil && g != nil:
recipient(before, &provider.Grantee{Type: provider.GranteeType_GRANTEE_TYPE_GROUP, Id: &provider.Grantee_GroupId{GroupId: g}})
}
var p *provider.ResourcePermissions
if utils.ReadJSONFromOpaque(o, "permissions", &p) == nil {
role(before, p, false, utils.ExistsInOpaque(o, "spacegrant"))
}
if len(before) == 0 {
return nil
}
return &audit.Change{Before: before}
}
// linkCreated describes a new public link: role, expiration and whether it
// has a password, never the password itself.
func linkCreated(r *link.CreatePublicShareRequest, res *link.CreatePublicShareResponse) *audit.Change {
after := map[string]any{}
if s := res.GetShare(); s != nil {
role(after, s.GetPermissions().GetPermissions(), true, false)
after[keyPassword] = s.GetPasswordProtected()
if s.GetExpiration() != nil {
expiration(after, s.GetExpiration())
}
return &audit.Change{After: after}
}
role(after, r.GetGrant().GetPermissions().GetPermissions(), true, false)
after[keyPassword] = r.GetGrant().GetPassword() != ""
if r.GetGrant().GetExpiration() != nil {
expiration(after, r.GetGrant().GetExpiration())
}
return &audit.Change{After: after}
}
// linkUpdated describes the one attribute a public link update changes.
func linkUpdated(r *link.UpdatePublicShareRequest, res *link.UpdatePublicShareResponse) *audit.Change {
u := r.GetUpdate()
s := res.GetShare()
after := map[string]any{}
switch u.GetType() {
case link.UpdatePublicShareRequest_Update_TYPE_PERMISSIONS:
p := u.GetGrant().GetPermissions().GetPermissions()
if s != nil {
p = s.GetPermissions().GetPermissions()
}
role(after, p, true, false)
case link.UpdatePublicShareRequest_Update_TYPE_PASSWORD:
// true: set or changed, false: removed
after[keyPassword] = u.GetGrant().GetPassword() != ""
if s != nil {
after[keyPassword] = s.GetPasswordProtected()
}
case link.UpdatePublicShareRequest_Update_TYPE_EXPIRATION:
expiration(after, u.GetGrant().GetExpiration())
case link.UpdatePublicShareRequest_Update_TYPE_DISPLAYNAME:
after["display_name"] = u.GetDisplayName()
case link.UpdatePublicShareRequest_Update_TYPE_DESCRIPTION:
after["description"] = u.GetDescription()
case link.UpdatePublicShareRequest_Update_TYPE_NOTIFYUPLOADS:
after["notify_uploads"] = u.GetNotifyUploads()
case link.UpdatePublicShareRequest_Update_TYPE_NOTIFYUPLOADSEXTRARECIPIENTS:
// email addresses, only whether there are any
after["notify_uploads_extra_recipients"] = u.GetNotifyUploadsExtraRecipients() != ""
default:
return nil
}
return &audit.Change{After: after}
}
// linkRemoved describes the removed public link.
func linkRemoved(o *typesv1beta1.Opaque) *audit.Change {
var p *provider.ResourcePermissions
if utils.ReadJSONFromOpaque(o, "permissions", &p) != nil || p == nil {
return nil
}
before := map[string]any{}
role(before, p, true, false)
return &audit.Change{Before: before}
}
// shareEvent audits the calls on shares and space members. The sharing
// service marks space grants in its responses, they are space member events.
func shareEvent(req, res interface{}, _ *storagespace.ItemSlot) (audit.Event, bool) {
var ev audit.Event
switch v := res.(type) {
case *collaboration.CreateShareResponse:
if utils.ExistsInOpaque(v.GetOpaque(), "noevent") {
return ev, false
}
r := req.(*collaboration.CreateShareRequest)
rid := r.GetResourceInfo().GetId()
// a failed space grant therefore shows up as a failed share.create
if utils.ExistsInOpaque(v.GetOpaque(), "spacegrant") {
ev = audit.Event{Definition: audit.SpaceMemberAdd, Target: spaceTarget(rid)}
ev.Target.Name = utils.ReadPlainFromOpaque(v.GetOpaque(), "resourcename")
} else {
ev = audit.Event{Definition: audit.ShareCreate, Target: shareTarget(v.GetShare().GetId().GetOpaqueId(), rid, r.GetResourceInfo().GetName())}
}
ev.Change = shareCreated(r, v)
case *collaboration.UpdateShareResponse:
r := req.(*collaboration.UpdateShareRequest)
if utils.ExistsInOpaque(v.GetOpaque(), "spacegrant") {
ev = audit.Event{Definition: audit.SpaceMemberUpdate, Target: spaceTarget(v.GetShare().GetResourceId())}
ev.Target.Name = utils.ReadPlainFromOpaque(v.GetOpaque(), "resourcename")
} else {
ev = audit.Event{Definition: audit.ShareUpdate, Target: shareTarget(shareID(r.GetShare().GetId(), r.GetRef()), v.GetShare().GetResourceId(), utils.ReadPlainFromOpaque(v.GetOpaque(), "resourcename"))}
}
ev.Change = shareUpdated(r, v)
case *collaboration.RemoveShareResponse:
r := req.(*collaboration.RemoveShareRequest)
var rid *provider.ResourceId
_ = utils.ReadJSONFromOpaque(v.GetOpaque(), "resourceid", &rid)
if utils.ExistsInOpaque(v.GetOpaque(), "spacegrant") {
ev = audit.Event{Definition: audit.SpaceMemberRemove, Target: spaceTarget(rid)}
ev.Target.Name = utils.ReadPlainFromOpaque(v.GetOpaque(), "resourcename")
} else {
ev = audit.Event{Definition: audit.ShareDelete, Target: shareTarget(shareID(nil, r.GetRef()), rid, utils.ReadPlainFromOpaque(v.GetOpaque(), "resourcename"))}
}
ev.Change = shareRemoved(v.GetOpaque())
case *collaboration.UpdateReceivedShareResponse:
// hiding a share or moving its mount point leaves the state as it is,
// some clients send the state along, the provider adds the one before
if r, ok := req.(*collaboration.UpdateReceivedShareRequest); !ok || !slices.Contains(r.GetUpdateMask().GetPaths(), "state") {
return ev, false
}
rs := v.GetShare()
if utils.ReadPlainFromOpaque(v.GetOpaque(), "previousstate") == rs.GetState().String() {
return ev, false
}
switch rs.GetState() {
case collaboration.ShareState_SHARE_STATE_ACCEPTED:
ev = audit.Event{Definition: audit.ShareAccept}
case collaboration.ShareState_SHARE_STATE_REJECTED:
ev = audit.Event{Definition: audit.ShareDecline}
default:
return ev, false
}
ev.Target = shareTarget(rs.GetShare().GetId().GetOpaqueId(), rs.GetShare().GetResourceId(), path.Base(rs.GetMountPoint().GetPath()))
if ev.Target.Name == "." || ev.Target.Name == "/" {
ev.Target.Name = ""
}
default:
return ev, false
}
return ev, true
}
// autoAccepted reports a share accepted by a service account, e.g. the
// sharing service accepting new shares automatically. Nobody decided anything,
// the share.create of the sharer is the record that counts.
func autoAccepted(ctx context.Context, res interface{}) bool {
if _, ok := res.(*collaboration.UpdateReceivedShareResponse); !ok {
return false
}
u, ok := ctxpkg.ContextGetUser(ctx)
return ok && u.GetId().GetType() == userpb.UserType_USER_TYPE_SERVICE
}
func shareTarget(id string, rid *provider.ResourceId, name string) audit.Target {
t := audit.Target{ID: id, Name: name}
if rid != nil {
t.SpaceID = storagespace.FormatStorageID(rid.GetStorageId(), rid.GetSpaceId())
}
return t
}
func shareID(id *collaboration.ShareId, ref *collaboration.ShareReference) string {
if id != nil {
return id.GetOpaqueId()
}
return ref.GetId().GetOpaqueId()
}
@@ -0,0 +1,100 @@
package eventsmiddleware
import (
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/opencloud-eu/reva/v3/pkg/audit"
"github.com/opencloud-eu/reva/v3/pkg/storagespace"
"github.com/opencloud-eu/reva/v3/pkg/utils"
)
// spaceEvent audits the calls on spaces. item has the name of the space
// before the call changed it.
func spaceEvent(req, res interface{}, item *storagespace.ItemSlot) (audit.Event, bool) {
var ev audit.Event
switch v := res.(type) {
case *provider.CreateStorageSpaceResponse:
r := req.(*provider.CreateStorageSpaceRequest)
// the proxy calls CreateHome on every request, for an existing
// personal space nothing was created
if r.GetType() == "personal" && v.GetStatus().GetCode() == rpc.Code_CODE_ALREADY_EXISTS {
return ev, false
}
ev = audit.Event{Definition: audit.SpaceCreate, Target: spaceTarget(v.GetStorageSpace().GetRoot())}
ev.Target.Name = r.GetName()
if ev.Target.ID == "" {
ev.Target.ID = r.GetName()
}
case *provider.UpdateStorageSpaceResponse:
r := req.(*provider.UpdateStorageSpaceRequest)
ev.Target = spaceTarget(r.GetStorageSpace().GetRoot())
if ev.Target.ID == "" {
ev.Target.ID = r.GetStorageSpace().GetId().GetOpaqueId()
}
ev.Target.Name = item.Name
if utils.ExistsInOpaque(r.GetOpaque(), "restore") {
ev.Definition = audit.SpaceEnable
break
}
// graph sends all changes of a drive PATCH in one request, a quota
// change is only its own event when nothing else changed
ev.Change = spaceChange(r.GetStorageSpace())
ev.Definition = audit.SpaceUpdate
if c := ev.Change; c != nil && len(c.After) == 1 {
if _, quota := c.After["quota"]; quota {
ev.Definition = audit.SpaceQuotaChange
}
}
case *provider.DeleteStorageSpaceResponse:
r := req.(*provider.DeleteStorageSpaceRequest)
ev = audit.Event{Definition: audit.SpaceDisable, Target: audit.Target{ID: r.GetId().GetOpaqueId(), Name: item.Name}}
if rid, err := storagespace.ParseID(r.GetId().GetOpaqueId()); err == nil {
ev.Target.SpaceID = storagespace.FormatStorageID(rid.GetStorageId(), rid.GetSpaceId())
}
if utils.ExistsInOpaque(r.GetOpaque(), "purge") {
ev.Definition = audit.SpaceDelete
}
default:
return ev, false
}
return ev, true
}
func spaceTarget(rid *provider.ResourceId) audit.Target {
if rid == nil {
return audit.Target{}
}
id := storagespace.FormatStorageID(rid.GetStorageId(), rid.GetSpaceId())
return audit.Target{ID: id, SpaceID: id}
}
// spaceAttributes are the space attributes graph puts into the opaque of an
// update, with their keys in the record. image and readme are the IDs of the
// files.
var spaceAttributes = []struct{ opaque, key string }{
{"description", "description"},
{"spaceAlias", "alias"},
{"image", "image"},
{"readme", "readme"},
}
// spaceChange lists what a space update changes. An attribute set to an
// empty value was removed.
func spaceChange(s *provider.StorageSpace) *audit.Change {
after := map[string]any{}
if n := s.GetName(); n != "" {
after["name"] = n
}
if q := s.GetQuota(); q != nil {
after["quota"] = q.GetQuotaMaxBytes()
}
for _, a := range spaceAttributes {
if utils.ExistsInOpaque(s.GetOpaque(), a.opaque) {
after[a.key] = utils.ReadPlainFromOpaque(s.GetOpaque(), a.opaque)
}
}
if len(after) == 0 {
return nil
}
return &audit.Change{After: after}
}
@@ -29,6 +29,7 @@ import (
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/go-viper/mapstructure/v2"
"github.com/opencloud-eu/reva/v3/pkg/appctx"
"github.com/opencloud-eu/reva/v3/pkg/audit"
revactx "github.com/opencloud-eu/reva/v3/pkg/ctx"
"github.com/opencloud-eu/reva/v3/pkg/events"
"github.com/opencloud-eu/reva/v3/pkg/events/stream"
@@ -55,6 +56,13 @@ func NewUnary(m map[string]interface{}) (grpc.UnaryServerInterceptor, int, error
if err != nil {
return nil, 0, err
}
emitter, err := emitterFromConfig(m)
if err != nil {
return nil, 0, err
}
linkAccesses := newLinkAccesses()
_, auditOff := emitter.(audit.Discard)
auditOn := !auditOff
interceptor := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
// Register slots so the storage driver can pass data back up through
@@ -67,11 +75,26 @@ func NewUnary(m map[string]interface{}) (grpc.UnaryServerInterceptor, int, error
// Register a slot for typed DeleteStorageSpace results
ctx = storagespace.ContextRegisterDeleteStorageSpaceResultSlot(ctx)
// only with audit on, the drivers look up more for the slot
itemSlot := &storagespace.ItemSlot{}
if auditOn {
ctx = storagespace.ContextRegisterItemSlot(ctx, itemSlot)
}
res, err := handler(ctx, req)
if err != nil {
return res, err
}
if auditOn {
if aev, ok := auditEvent(req, res, itemSlot); ok && !autoAccepted(ctx, res) && firstLinkAccess(ctx, linkAccesses, aev) {
if err := emitter.Emit(ctx, aev); err != nil {
// the call is done already, failing it now would hide that it happened
appctx.GetLogger(ctx).Error().Err(err).Str("event", aev.Definition.Name).Msg("audit event not emitted")
}
}
}
spaceOwnerID := storagespace.ContextGetSpaceOwner(ctx) // nil if not set by handler
executant, _ := revactx.ContextGetUser(ctx)
@@ -394,8 +394,8 @@ func (s *svc) updateGrant(ctx context.Context, id *provider.ResourceId, grant *p
return nil, errors.Wrap(err, "gateway: error calling UpdateGrant")
}
if grantRes.Status.Code != rpc.Code_CODE_OK {
return status.NewInternal(ctx,
"error committing share to storage grant"), nil
grantRes.Status.Message = "error committing share to storage grant"
return grantRes.GetStatus(), nil
}
return status.NewOK(ctx), nil
@@ -393,6 +393,7 @@ func (s *service) RemovePublicShare(ctx context.Context, req *link.RemovePublicS
}
o := utils.AppendJSONToOpaque(nil, "resourceid", ps.GetResourceId())
o = utils.AppendPlainToOpaque(o, "resourcename", sRes.GetInfo().GetName())
o = utils.AppendJSONToOpaque(o, "permissions", ps.GetPermissions().GetPermissions())
return &link.RemovePublicShareResponse{
Opaque: o,
Status: status.NewOK(ctx),
@@ -49,6 +49,7 @@ import (
"github.com/opencloud-eu/reva/v3/pkg/share"
"github.com/opencloud-eu/reva/v3/pkg/share/manager/registry"
"github.com/opencloud-eu/reva/v3/pkg/sharedconf"
"github.com/opencloud-eu/reva/v3/pkg/storagespace"
"github.com/opencloud-eu/reva/v3/pkg/utils"
)
@@ -506,6 +507,7 @@ func (s *service) RemoveShare(ctx context.Context, req *collaboration.RemoveShar
opaque = utils.AppendJSONToOpaque(opaque, "granteegroupid", share.GetGrantee().GetGroupId())
}
opaque = utils.AppendJSONToOpaque(opaque, "shareid", share.GetId())
opaque = utils.AppendJSONToOpaque(opaque, "permissions", share.GetPermissions().GetPermissions())
return &collaboration.RemoveShareResponse{
Opaque: opaque,
@@ -563,7 +565,7 @@ func (s *service) UpdateShare(ctx context.Context, req *collaboration.UpdateShar
if err != nil {
return &collaboration.UpdateShareResponse{
Status: status.NewInternal(ctx, "failed check user permission to write share"),
}, err
}, nil
}
if !ok {
return &collaboration.UpdateShareResponse{
@@ -613,7 +615,7 @@ func (s *service) UpdateShare(ctx context.Context, req *collaboration.UpdateShar
log.Err(err).Interface("resource_id", req.GetShare().GetResourceId()).Msg("failed to stat resource to share")
return &collaboration.UpdateShareResponse{
Status: status.NewInternal(ctx, "failed to stat shared resource"),
}, err
}, nil
}
// the requesting user needs to be either the Owner/Creator of the share or have the UpdateGrant permissions on the Resource
switch {
@@ -624,7 +626,7 @@ func (s *service) UpdateShare(ctx context.Context, req *collaboration.UpdateShar
default:
return &collaboration.UpdateShareResponse{
Status: status.NewPermissionDenied(ctx, nil, "no permission to remove grants on shared resource"),
}, err
}, nil
}
// resharing is forbidden for not space roots
@@ -774,6 +776,15 @@ func (s *service) UpdateReceivedShare(ctx context.Context, req *collaboration.Up
}
}
// the audit tells an accept from a hide or a rename, which send the state
// the share already has
var opaque *typesv1beta1.Opaque
if storagespace.ContextWantsItem(ctx) && slices.Contains(req.GetUpdateMask().GetPaths(), _fieldMaskPathState) {
if prev, err := s.sm.GetReceivedShare(ctx, &collaboration.ShareReference{Spec: &collaboration.ShareReference_Id{Id: req.GetShare().GetShare().GetId()}}); err == nil {
opaque = utils.AppendPlainToOpaque(opaque, "previousstate", prev.GetState().String())
}
}
var uid userpb.UserId
_ = utils.ReadJSONFromOpaque(req.Opaque, "userid", &uid)
updatedShare, err := s.sm.UpdateReceivedShare(ctx, req.Share, req.UpdateMask, &uid)
@@ -782,6 +793,7 @@ func (s *service) UpdateReceivedShare(ctx context.Context, req *collaboration.Up
return &collaboration.UpdateReceivedShareResponse{
Status: status.NewOK(ctx),
Share: updatedShare,
Opaque: opaque,
}, nil
case errtypes.NotFound:
return &collaboration.UpdateReceivedShareResponse{
@@ -36,6 +36,7 @@ import (
tokenregistry "github.com/opencloud-eu/reva/v3/internal/http/interceptors/auth/token/registry"
tokenwriterregistry "github.com/opencloud-eu/reva/v3/internal/http/interceptors/auth/tokenwriter/registry"
"github.com/opencloud-eu/reva/v3/pkg/appctx"
"github.com/opencloud-eu/reva/v3/pkg/audit"
"github.com/opencloud-eu/reva/v3/pkg/auth"
"github.com/opencloud-eu/reva/v3/pkg/auth/scope"
ctxpkg "github.com/opencloud-eu/reva/v3/pkg/ctx"
@@ -196,6 +197,12 @@ func New(m map[string]interface{}, unprotected []string, tp trace.TracerProvider
isUnprotectedEndpoint = true
}
// unprotected endpoints need the audit context as well, e.g.
// public-files authenticates the public link itself
if v := r.Header.Get(audit.Header); v != "" {
r = r.WithContext(audit.ContextSetRequest(r.Context(), audit.ParseRequestContext(v)))
}
ctx, err := authenticateUser(w, r, conf, tokenStrategyChain, tokenManager, tokenWriter, credChain, isUnprotectedEndpoint)
if err != nil {
if !isUnprotectedEndpoint {
@@ -37,6 +37,7 @@ import (
"github.com/go-viper/mapstructure/v2"
"github.com/opencloud-eu/reva/v3/internal/http/services/archiver/manager"
"github.com/opencloud-eu/reva/v3/internal/http/services/owncloud/ocdav/net"
"github.com/opencloud-eu/reva/v3/pkg/audit"
"github.com/opencloud-eu/reva/v3/pkg/errtypes"
"github.com/opencloud-eu/reva/v3/pkg/rgrpc/todo/pool"
"github.com/opencloud-eu/reva/v3/pkg/rhttp"
@@ -45,6 +46,7 @@ import (
"github.com/opencloud-eu/reva/v3/pkg/storage/utils/downloader"
"github.com/opencloud-eu/reva/v3/pkg/storage/utils/walker"
"github.com/opencloud-eu/reva/v3/pkg/storagespace"
"github.com/opencloud-eu/reva/v3/pkg/utils"
"github.com/rs/zerolog"
)
@@ -56,18 +58,20 @@ type svc struct {
downloader downloader.Downloader
allowedFolders []*regexp.Regexp
emitter audit.Emitter
}
// Config holds the config options that need to be passed down to all ocdav handlers
type Config struct {
Prefix string `mapstructure:"prefix"`
GatewaySvc string `mapstructure:"gatewaysvc"`
Timeout int64 `mapstructure:"timeout"`
Insecure bool `mapstructure:"insecure"`
Name string `mapstructure:"name"`
MaxNumFiles int64 `mapstructure:"max_num_files"`
MaxSize int64 `mapstructure:"max_size"`
AllowedFolders []string `mapstructure:"allowed_folders"`
Prefix string `mapstructure:"prefix"`
GatewaySvc string `mapstructure:"gatewaysvc"`
Timeout int64 `mapstructure:"timeout"`
Insecure bool `mapstructure:"insecure"`
Name string `mapstructure:"name"`
MaxNumFiles int64 `mapstructure:"max_num_files"`
MaxSize int64 `mapstructure:"max_size"`
AllowedFolders []string `mapstructure:"allowed_folders"`
Audit audit.EmitterConfig `mapstructure:"audit"`
}
func init() {
@@ -99,7 +103,13 @@ func New(conf map[string]interface{}, log *zerolog.Logger) (global.Service, erro
allowedFolderRegex = append(allowedFolderRegex, regex)
}
emitter, err := audit.EmitterFromConfig(context.Background(), "archiver-audit", c.Audit, audit.Options{Logger: log})
if err != nil {
return nil, err
}
return &svc{
emitter: emitter,
config: c,
gatewaySelector: gatewaySelector,
downloader: downloader.NewDownloader(gatewaySelector, rhttp.Insecure(c.Insecure), rhttp.Timeout(time.Duration(c.Timeout*int64(time.Second)))),
@@ -339,9 +349,11 @@ func (s *svc) Handler() http.Handler {
defer closeArchive()
if err != nil {
s.auditArchive(ctx, resources, audit.OutcomeFailure, "incomplete")
s.writeHTTPError(rw, err)
return
}
s.auditArchive(ctx, resources, audit.OutcomeSuccess, "")
})
}
@@ -351,9 +363,48 @@ func (s *svc) Prefix() string {
}
func (s *svc) Close() error {
audit.CloseEmitter(s.emitter)
return nil
}
func (s *svc) Unprotected() []string {
return nil
}
// auditArchive reports the download of every resource in the archive, when
// the archive is written. The files read for it are internal reads and not
// audited on their own.
func (s *svc) auditArchive(ctx context.Context, resources []*provider.ResourceId, outcome audit.Outcome, reason string) {
if !audit.Enabled(s.emitter) {
return
}
gatewayClient, err := s.gatewaySelector.Next()
if err != nil {
s.log.Error().Err(err).Msg("archiver: could not select gateway for the audit event")
return
}
// a client that aborts the download cancels ctx, the lookup of type and
// name must still work for the incomplete record
statCtx := context.WithoutCancel(ctx)
for _, id := range resources {
d := audit.FolderDownload
target := audit.Target{
ID: storagespace.FormatResourceID(id),
SpaceID: storagespace.FormatStorageID(id.GetStorageId(), id.GetSpaceId()),
}
if res, err := gatewayClient.Stat(statCtx, &provider.StatRequest{Ref: &provider.Reference{ResourceId: id}}); err == nil && res.GetStatus().GetCode() == rpc.Code_CODE_OK {
target.Name = res.GetInfo().GetName()
if res.GetInfo().GetType() != provider.ResourceType_RESOURCE_TYPE_CONTAINER {
d = audit.FileDownload
}
// a stat by ID returns the path in the space, like the other
// file events have it; a space root has none
if p := res.GetInfo().GetPath(); p != "" && p != "." {
target.Path = utils.MakeRelativePath(p)
}
}
if err := s.emitter.Emit(ctx, audit.Event{Definition: d, Outcome: outcome, Reason: reason, Target: target}); err != nil {
s.log.Error().Err(err).Msg("archiver: audit event not emitted")
}
}
}
@@ -19,6 +19,7 @@
package dataprovider
import (
"context"
"fmt"
"net/http"
@@ -26,7 +27,9 @@ import (
"github.com/rs/zerolog"
"github.com/opencloud-eu/reva/v3/pkg/appctx"
"github.com/opencloud-eu/reva/v3/pkg/audit"
"github.com/opencloud-eu/reva/v3/pkg/events"
"github.com/opencloud-eu/reva/v3/pkg/events/raw"
"github.com/opencloud-eu/reva/v3/pkg/events/stream"
datatxregistry "github.com/opencloud-eu/reva/v3/pkg/rhttp/datatx/manager/registry"
"github.com/opencloud-eu/reva/v3/pkg/rhttp/global"
@@ -41,18 +44,22 @@ func init() {
}
type config struct {
Prefix string `mapstructure:"prefix" docs:"data;The prefix to be used for this HTTP service"`
Driver string `mapstructure:"driver" docs:"localhome;The storage driver to be used."`
Drivers map[string]map[string]interface{} `mapstructure:"drivers" docs:"url:pkg/storage/fs/localhome/localhome.go;The configuration for the storage driver"`
DataTXs map[string]map[string]interface{} `mapstructure:"data_txs" docs:"url:pkg/rhttp/datatx/manager/simple/simple.go;The configuration for the data tx protocols"`
NatsAddress string `mapstructure:"nats_address"`
NatsClusterID string `mapstructure:"nats_clusterID"`
NatsTLSInsecure bool `mapstructure:"nats_tls_insecure"`
NatsRootCACertPath string `mapstructure:"nats_root_ca_cert_path"`
NatsEnableTLS bool `mapstructure:"nats_enable_tls"`
NatsUsername string `mapstructure:"nats_username"`
NatsPassword string `mapstructure:"nats_password"`
UploadDirectory string `mapstructure:"upload_directory" docs:";Local directory for staging upload sessions. Overrides the driver's root. Required for drivers that have no local filesystem root."`
Prefix string `mapstructure:"prefix" docs:"data;The prefix to be used for this HTTP service"`
Driver string `mapstructure:"driver" docs:"localhome;The storage driver to be used."`
Drivers map[string]map[string]interface{} `mapstructure:"drivers" docs:"url:pkg/storage/fs/localhome/localhome.go;The configuration for the storage driver"`
DataTXs map[string]map[string]interface{} `mapstructure:"data_txs" docs:"url:pkg/rhttp/datatx/manager/simple/simple.go;The configuration for the data tx protocols"`
NatsAddress string `mapstructure:"nats_address"`
NatsClusterID string `mapstructure:"nats_clusterID"`
NatsTLSInsecure bool `mapstructure:"nats_tls_insecure"`
NatsRootCACertPath string `mapstructure:"nats_root_ca_cert_path"`
NatsEnableTLS bool `mapstructure:"nats_enable_tls"`
NatsUsername string `mapstructure:"nats_username"`
NatsPassword string `mapstructure:"nats_password"`
UploadDirectory string `mapstructure:"upload_directory" docs:";Local directory for staging upload sessions. Overrides the driver's root. Required for drivers that have no local filesystem root."`
AuditEnabled bool `mapstructure:"audit_enabled"`
AuditMode string `mapstructure:"audit_mode"`
AuditService string `mapstructure:"audit_service"`
AuditServiceVersion string `mapstructure:"audit_service_version"`
}
func (c *config) init() {
@@ -69,6 +76,7 @@ type svc struct {
handler http.Handler
storage storage.FS
dataTXs map[string]http.Handler
emitter audit.Emitter
}
// New returns a new datasvc
@@ -82,9 +90,14 @@ func New(m map[string]interface{}, log *zerolog.Logger) (global.Service, error)
var evstream events.Stream
if conf.NatsAddress == "" || conf.NatsClusterID == "" {
log.Warn().Msg("missing or incomplete nats configuration. Events will not be published.")
} else {
switch {
case conf.NatsAddress == "" && conf.NatsClusterID == "":
// services like the system storage run a dataprovider without events on purpose
log.Debug().Msg("no nats configuration. Events will not be published.")
case conf.NatsAddress == "" || conf.NatsClusterID == "":
log.Warn().Str("nats_address", conf.NatsAddress).Str("nats_clusterID", conf.NatsClusterID).
Msg("incomplete nats configuration. Events will not be published.")
default:
s, err := stream.NatsFromConfig("dataprovider", false, stream.NatsConfig{
Endpoint: conf.NatsAddress,
Cluster: conf.NatsClusterID,
@@ -101,6 +114,25 @@ func New(m map[string]interface{}, log *zerolog.Logger) (global.Service, error)
evstream = s
}
emitter, err := audit.EmitterFromConfig(context.Background(), "dataprovider-audit", audit.EmitterConfig{
Enabled: conf.AuditEnabled,
Mode: conf.AuditMode,
Service: conf.AuditService,
ServiceVersion: conf.AuditServiceVersion,
Nats: raw.Config{
Endpoint: conf.NatsAddress,
Cluster: conf.NatsClusterID,
EnableTLS: conf.NatsEnableTLS,
TLSInsecure: conf.NatsTLSInsecure,
TLSRootCACertificate: conf.NatsRootCACertPath,
AuthUsername: conf.NatsUsername,
AuthPassword: conf.NatsPassword,
},
}, audit.Options{Logger: log})
if err != nil {
return nil, fmt.Errorf("dataprovider: %w", err)
}
fs, err := getFS(conf, evstream, log)
if err != nil {
return nil, err
@@ -120,7 +152,7 @@ func New(m map[string]interface{}, log *zerolog.Logger) (global.Service, error)
}
}
dataTXs, err := getDataTXs(conf, coord, fs, evstream, log)
dataTXs, err := getDataTXs(conf, coord, fs, evstream, emitter, log)
if err != nil {
return nil, err
}
@@ -129,6 +161,7 @@ func New(m map[string]interface{}, log *zerolog.Logger) (global.Service, error)
storage: fs,
conf: conf,
dataTXs: dataTXs,
emitter: emitter,
}
err = s.setHandler()
@@ -142,7 +175,7 @@ func getFS(c *config, stream events.Stream, log *zerolog.Logger) (storage.FS, er
return nil, fmt.Errorf("driver not found: %s", c.Driver)
}
func getDataTXs(c *config, coord upload.Coordinator, fs storage.FS, publisher events.Publisher, log *zerolog.Logger) (map[string]http.Handler, error) {
func getDataTXs(c *config, coord upload.Coordinator, fs storage.FS, publisher events.Publisher, emitter audit.Emitter, log *zerolog.Logger) (map[string]http.Handler, error) {
if c.DataTXs == nil {
c.DataTXs = make(map[string]map[string]interface{})
}
@@ -161,7 +194,7 @@ func getDataTXs(c *config, coord upload.Coordinator, fs storage.FS, publisher ev
txs := make(map[string]http.Handler)
for t := range c.DataTXs {
if f, ok := datatxregistry.NewFuncs[t]; ok {
if tx, err := f(c.DataTXs[t], publisher, log); err == nil {
if tx, err := f(c.DataTXs[t], publisher, emitter, log); err == nil {
if handler, err := tx.Handler(coord, fs); err == nil {
txs[t] = handler
}
@@ -172,6 +205,7 @@ func getDataTXs(c *config, coord upload.Coordinator, fs storage.FS, publisher ev
}
func (s *svc) Close() error {
audit.CloseEmitter(s.emitter)
return nil
}
@@ -32,6 +32,7 @@ import (
"github.com/opencloud-eu/reva/v3/internal/http/services/owncloud/ocdav/net"
"github.com/opencloud-eu/reva/v3/internal/http/services/owncloud/ocdav/spacelookup"
"github.com/opencloud-eu/reva/v3/pkg/appctx"
"github.com/opencloud-eu/reva/v3/pkg/audit"
"github.com/opencloud-eu/reva/v3/pkg/rhttp"
"github.com/opencloud-eu/reva/v3/pkg/utils"
"github.com/rs/zerolog"
@@ -116,6 +117,10 @@ func (s *svc) handleGet(ctx context.Context, w http.ResponseWriter, r *http.Requ
return
}
httpReq.Header.Set(datagateway.TokenTransportHeader, token)
// marks the transfer as a download the client asked for, the data provider audits it
if v := r.Header.Get(audit.Header); v != "" {
httpReq.Header.Set(audit.Header, v)
}
if r.Header.Get(net.HeaderRange) != "" {
httpReq.Header.Set(net.HeaderRange, r.Header.Get(net.HeaderRange))
@@ -1415,12 +1415,16 @@ func mdToPropResponse(ctx context.Context, pf *XML, md *provider.ResourceInfo, p
}
case "public-link-item-type": // only on a share root node
if ls != nil {
itemType := "file"
if md.Type == provider.ResourceType_RESOURCE_TYPE_CONTAINER {
appendToOK(prop.Raw("oc:public-link-item-type", "folder"))
} else {
appendToOK(prop.Raw("oc:public-link-item-type", "file"))
// redirectref is another option
itemType = "folder"
}
// the synthetic collection of a single file link carries the type of the shared resource
if t := utils.ReadPlainFromOpaque(md.Opaque, "public-link-item-type"); t != "" {
itemType = t
}
appendToOK(prop.Raw("oc:public-link-item-type", itemType))
// redirectref is another option
} else {
appendToNotFound(prop.NotFound("oc:public-link-item-type"))
}
@@ -31,6 +31,7 @@ import (
"github.com/opencloud-eu/reva/v3/internal/http/services/owncloud/ocdav/propfind"
"github.com/opencloud-eu/reva/v3/pkg/appctx"
"github.com/opencloud-eu/reva/v3/pkg/rhttp/router"
"github.com/opencloud-eu/reva/v3/pkg/utils"
"go.opentelemetry.io/otel/codes"
semconv "go.opentelemetry.io/otel/semconv/v1.37.0"
)
@@ -176,11 +177,12 @@ func (s *svc) getPublicFileInfos(onContainer, onlyRoot bool, i *provider.Resourc
// we don't copy everything because the checksum should not be present
var o *typesv1beta1.Opaque
if i.Opaque != nil && i.Opaque.Map != nil && i.Opaque.Map["link-share"] != nil {
o = &typesv1beta1.Opaque{
// the collection is synthetic and the shared resource is a file
o = utils.AppendPlainToOpaque(&typesv1beta1.Opaque{
Map: map[string]*typesv1beta1.OpaqueEntry{
"link-share": i.Opaque.Map["link-share"],
},
}
}, "public-link-item-type", "file")
}
// always add collection
infos = append(infos, &provider.ResourceInfo{
@@ -35,6 +35,7 @@ import (
"github.com/opencloud-eu/reva/v3/internal/http/services/owncloud/ocdav/net"
"github.com/opencloud-eu/reva/v3/internal/http/services/owncloud/ocdav/spacelookup"
"github.com/opencloud-eu/reva/v3/pkg/appctx"
"github.com/opencloud-eu/reva/v3/pkg/audit"
"github.com/opencloud-eu/reva/v3/pkg/errtypes"
"github.com/opencloud-eu/reva/v3/pkg/rhttp"
"github.com/opencloud-eu/reva/v3/pkg/storagespace"
@@ -349,6 +350,10 @@ func (s *svc) handlePut(ctx context.Context, w http.ResponseWriter, r *http.Requ
Propagator.Inject(ctx, propagation.HeaderCarrier(httpReq.Header))
httpReq.Header.Set(datagateway.TokenTransportHeader, token)
httpReq.ContentLength = length
// marks the transfer as an upload the client sent, the data provider audits it
if v := r.Header.Get(audit.Header); v != "" {
httpReq.Header.Set(audit.Header, v)
}
httpRes, err := s.client.Do(httpReq)
if err != nil {
@@ -35,6 +35,7 @@ import (
"github.com/opencloud-eu/reva/v3/internal/http/services/owncloud/ocdav/net"
"github.com/opencloud-eu/reva/v3/internal/http/services/owncloud/ocdav/spacelookup"
"github.com/opencloud-eu/reva/v3/pkg/appctx"
"github.com/opencloud-eu/reva/v3/pkg/audit"
"github.com/opencloud-eu/reva/v3/pkg/rhttp"
"github.com/opencloud-eu/reva/v3/pkg/storagespace"
"github.com/opencloud-eu/reva/v3/pkg/utils"
@@ -304,6 +305,10 @@ func (s *svc) handleTusPost(ctx context.Context, w http.ResponseWriter, r *http.
Propagator.Inject(ctx, propagation.HeaderCarrier(httpReq.Header))
httpReq.Header.Set(net.HeaderContentType, r.Header.Get(net.HeaderContentType))
// marks the transfer as an upload the client sent, the data provider audits it
if v := r.Header.Get(audit.Header); v != "" {
httpReq.Header.Set(audit.Header, v)
}
httpReq.Header.Set(net.HeaderContentLength, r.Header.Get(net.HeaderContentLength))
if r.Header.Get(net.HeaderUploadOffset) != "" {
httpReq.Header.Set(net.HeaderUploadOffset, r.Header.Get(net.HeaderUploadOffset))
+235
View File
@@ -0,0 +1,235 @@
package audit
import (
"fmt"
"sort"
)
// OCSF 1.9.0 class UIDs used by the catalog.
const (
OCSFDetectionFinding = 2004
OCSFAuthentication = 3002
OCSFEntityManagement = 3004
OCSFGroupManagement = 3006
OCSFUserManagement = 3007
OCSFRoleManagement = 3008
OCSFAPIActivity = 6003
OCSFWebResourceAccessActivity = 6004
OCSFFileHostingActivity = 6006
)
// ocsfOther is the OCSF activity "Other", used when a class has no matching activity.
const ocsfOther = 99
// Definition describes one event of the catalog. Every event is defined once
// here; the emitter validates against it and the catalog docs are generated
// from it.
type Definition struct {
// Name is the stable event name, opencloud.<object>.<action>.
Name string
// Category groups events for the docs and the stream subject.
Category string
// TargetType is the type of object the event acts on.
TargetType string
// code is the stable base code, e.g. F012. Never change or reuse it.
code string
// Severity on success. Failures and denials raise it to at least warning.
Severity Severity
// OCSFClass and OCSFActivity map the event to OCSF 1.9.0.
OCSFClass int
OCSFActivity int
// OCSFDeniedActivity, when set, replaces OCSFActivity for failures and denials.
OCSFDeniedActivity int
}
// Code returns the event code for the given outcome: the base code plus
// S (success), F (failure) or D (denied), e.g. F012S.
func (d *Definition) Code(o Outcome) string {
switch o {
case OutcomeFailure:
return d.code + "F"
case OutcomeDenied:
return d.code + "D"
default:
return d.code + "S"
}
}
func (d *Definition) activity(o Outcome) int {
if o != OutcomeSuccess && d.OCSFDeniedActivity != 0 {
return d.OCSFDeniedActivity
}
return d.OCSFActivity
}
func (d *Definition) severity(o Outcome) Severity {
if o != OutcomeSuccess && d.Severity.rank() < SeverityWarning.rank() {
return SeverityWarning
}
return d.Severity
}
// Categories
const (
CategoryAuthentication = "authentication"
CategoryCredentials = "credentials"
CategoryFiles = "files"
CategorySharing = "sharing"
CategorySpaces = "spaces"
CategoryIdentity = "identity"
CategoryAdministration = "administration"
CategorySecurity = "security"
)
var registry = map[string]*Definition{}
func define(name, category, targetType, code string, sev Severity, class, activity int) *Definition {
d := &Definition{
Name: "opencloud." + name,
Category: category,
TargetType: targetType,
code: code,
Severity: sev,
OCSFClass: class,
OCSFActivity: activity,
}
if _, ok := registry[d.Name]; ok {
panic(fmt.Sprintf("audit: event %s defined twice", d.Name))
}
for _, other := range registry {
if other.code == code {
panic(fmt.Sprintf("audit: code %s used by %s and %s", code, other.Name, d.Name))
}
}
registry[d.Name] = d
return d
}
func deniedActivity(d *Definition, activity int) *Definition {
d.OCSFDeniedActivity = activity
return d
}
// Authentication
var (
AuthLogin = define("auth.login", CategoryAuthentication, "user", "A001", SeverityInfo, OCSFAuthentication, 1)
AuthBackchannelLogout = define("auth.backchannel_logout", CategoryAuthentication, "user", "A002", SeverityInfo, OCSFAuthentication, 2)
)
// Credentials
var (
AppTokenCreate = define("app_token.create", CategoryCredentials, "app_token", "C001", SeverityNotice, OCSFUserManagement, 18)
AppTokenDelete = define("app_token.delete", CategoryCredentials, "app_token", "C002", SeverityNotice, OCSFUserManagement, 19)
GuestTokenCreate = define("guest_token.create", CategoryCredentials, "guest_token", "C003", SeverityNotice, OCSFUserManagement, 18)
GuestTokenRenew = define("guest_token.renew", CategoryCredentials, "guest_token", "C004", SeverityNotice, OCSFUserManagement, 18)
UserPasswordChange = define("user.password.change", CategoryCredentials, "user", "C005", SeverityNotice, OCSFUserManagement, 8)
UserPasswordReset = define("user.password.reset", CategoryCredentials, "user", "C006", SeverityNotice, OCSFUserManagement, 9)
)
// Files
var (
FileUpload = define("file.upload", CategoryFiles, "file", "F001", SeverityInfo, OCSFFileHostingActivity, 1)
FileDownload = define("file.download", CategoryFiles, "file", "F002", SeverityInfo, OCSFFileHostingActivity, 2)
FilePreview = define("file.preview", CategoryFiles, "file", "F003", SeverityInfo, OCSFFileHostingActivity, 9)
FileOpenInApp = define("file.open_in_app", CategoryFiles, "file", "F004", SeverityInfo, OCSFFileHostingActivity, 14)
FileRename = define("file.rename", CategoryFiles, "file", "F005", SeverityInfo, OCSFFileHostingActivity, 5)
FileMove = define("file.move", CategoryFiles, "file", "F006", SeverityInfo, OCSFFileHostingActivity, 7)
FileCopy = define("file.copy", CategoryFiles, "file", "F007", SeverityInfo, OCSFFileHostingActivity, 6)
FileDelete = define("file.delete", CategoryFiles, "file", "F008", SeverityInfo, OCSFFileHostingActivity, 4)
FileRestore = define("file.restore", CategoryFiles, "file", "F009", SeverityInfo, OCSFFileHostingActivity, 8)
FilePurge = define("file.purge", CategoryFiles, "file", "F010", SeverityNotice, OCSFFileHostingActivity, 4)
FileLock = define("file.lock", CategoryFiles, "file", "F011", SeverityInfo, OCSFFileHostingActivity, 10)
FileUnlock = define("file.unlock", CategoryFiles, "file", "F012", SeverityInfo, OCSFFileHostingActivity, 11)
FileVersionRestore = define("file.version.restore", CategoryFiles, "file", "F013", SeverityInfo, OCSFFileHostingActivity, 8)
FileVersionDelete = define("file.version.delete", CategoryFiles, "file", "F014", SeverityNotice, OCSFFileHostingActivity, 4)
FileMalwareDetect = define("file.malware.detected", CategoryFiles, "file", "F015", SeverityAlert, OCSFDetectionFinding, 1)
FolderCreate = define("folder.create", CategoryFiles, "folder", "F016", SeverityInfo, OCSFFileHostingActivity, ocsfOther)
FolderDownload = define("folder.download", CategoryFiles, "folder", "F017", SeverityInfo, OCSFFileHostingActivity, 2)
FolderRename = define("folder.rename", CategoryFiles, "folder", "F018", SeverityInfo, OCSFFileHostingActivity, 5)
FolderMove = define("folder.move", CategoryFiles, "folder", "F019", SeverityInfo, OCSFFileHostingActivity, 7)
FolderCopy = define("folder.copy", CategoryFiles, "folder", "F020", SeverityInfo, OCSFFileHostingActivity, 6)
FolderDelete = define("folder.delete", CategoryFiles, "folder", "F021", SeverityInfo, OCSFFileHostingActivity, 4)
FolderRestore = define("folder.restore", CategoryFiles, "folder", "F022", SeverityInfo, OCSFFileHostingActivity, 8)
FolderPurge = define("folder.purge", CategoryFiles, "folder", "F023", SeverityNotice, OCSFFileHostingActivity, 4)
TrashPurgeAll = define("trash.purge_all", CategoryFiles, "space", "F024", SeverityNotice, OCSFFileHostingActivity, 4)
)
// Sharing
var (
ShareCreate = define("share.create", CategorySharing, "share", "S001", SeverityInfo, OCSFFileHostingActivity, 12)
ShareUpdate = define("share.update", CategorySharing, "share", "S002", SeverityInfo, OCSFFileHostingActivity, 12)
ShareDelete = define("share.delete", CategorySharing, "share", "S003", SeverityInfo, OCSFFileHostingActivity, 13)
ShareAccept = define("share.accept", CategorySharing, "share", "S004", SeverityInfo, OCSFFileHostingActivity, ocsfOther)
ShareDecline = define("share.decline", CategorySharing, "share", "S005", SeverityInfo, OCSFFileHostingActivity, ocsfOther)
PublicLinkCreate = define("public_link.create", CategorySharing, "public_link", "S006", SeverityNotice, OCSFFileHostingActivity, 12)
PublicLinkUpdate = define("public_link.update", CategorySharing, "public_link", "S007", SeverityNotice, OCSFFileHostingActivity, 12)
PublicLinkDelete = define("public_link.delete", CategorySharing, "public_link", "S008", SeverityNotice, OCSFFileHostingActivity, 13)
PublicLinkAccess = deniedActivity(define("public_link.access", CategorySharing, "public_link", "S009", SeverityInfo, OCSFWebResourceAccessActivity, 1), 2)
OCMShareCreate = define("ocm.share.create", CategorySharing, "ocm_share", "S010", SeverityNotice, OCSFFileHostingActivity, 12)
OCMShareUpdate = define("ocm.share.update", CategorySharing, "ocm_share", "S011", SeverityNotice, OCSFFileHostingActivity, 12)
OCMShareDelete = define("ocm.share.delete", CategorySharing, "ocm_share", "S012", SeverityNotice, OCSFFileHostingActivity, 13)
OCMInviteCreate = define("ocm.invite.create", CategorySharing, "ocm_invite", "S013", SeverityNotice, OCSFFileHostingActivity, ocsfOther)
OCMInviteAccept = define("ocm.invite.accept", CategorySharing, "ocm_invite", "S014", SeverityNotice, OCSFFileHostingActivity, ocsfOther)
)
// Spaces
var (
SpaceCreate = define("space.create", CategorySpaces, "space", "P001", SeverityNotice, OCSFEntityManagement, 1)
SpaceUpdate = define("space.update", CategorySpaces, "space", "P002", SeverityInfo, OCSFEntityManagement, 3)
SpaceEnable = define("space.enable", CategorySpaces, "space", "P003", SeverityNotice, OCSFEntityManagement, 8)
SpaceDisable = define("space.disable", CategorySpaces, "space", "P004", SeverityNotice, OCSFEntityManagement, 9)
SpaceDelete = define("space.delete", CategorySpaces, "space", "P005", SeverityNotice, OCSFEntityManagement, 4)
SpaceMemberAdd = define("space.member.add", CategorySpaces, "space", "P006", SeverityNotice, OCSFFileHostingActivity, 12)
SpaceMemberUpdate = define("space.member.update", CategorySpaces, "space", "P007", SeverityNotice, OCSFFileHostingActivity, 12)
SpaceMemberRemove = define("space.member.remove", CategorySpaces, "space", "P008", SeverityNotice, OCSFFileHostingActivity, 13)
SpaceQuotaChange = define("space.quota.change", CategorySpaces, "space", "P009", SeverityNotice, OCSFEntityManagement, 3)
)
// Identity
var (
UserCreate = define("user.create", CategoryIdentity, "user", "I001", SeverityNotice, OCSFUserManagement, 1)
UserUpdate = define("user.update", CategoryIdentity, "user", "I002", SeverityNotice, OCSFUserManagement, 2)
UserEnable = define("user.enable", CategoryIdentity, "user", "I003", SeverityNotice, OCSFUserManagement, 4)
UserDisable = define("user.disable", CategoryIdentity, "user", "I004", SeverityNotice, OCSFUserManagement, 5)
UserSoftDelete = define("user.soft_delete", CategoryIdentity, "user", "I005", SeverityNotice, OCSFUserManagement, 5)
UserDelete = define("user.delete", CategoryIdentity, "user", "I006", SeverityNotice, OCSFUserManagement, 3)
GroupCreate = define("group.create", CategoryIdentity, "group", "I007", SeverityNotice, OCSFGroupManagement, 6)
GroupUpdate = define("group.update", CategoryIdentity, "group", "I008", SeverityNotice, OCSFGroupManagement, 9)
GroupDelete = define("group.delete", CategoryIdentity, "group", "I009", SeverityNotice, OCSFGroupManagement, 5)
GroupMemberAdd = define("group.member.add", CategoryIdentity, "group", "I010", SeverityNotice, OCSFGroupManagement, 3)
GroupMemberRemove = define("group.member.remove", CategoryIdentity, "group", "I011", SeverityNotice, OCSFGroupManagement, 4)
AppRoleAssign = define("app_role.assign", CategoryIdentity, "user", "I012", SeverityNotice, OCSFUserManagement, 16)
AppRoleUnassign = define("app_role.unassign", CategoryIdentity, "user", "I013", SeverityNotice, OCSFUserManagement, 17)
)
// Administration
var (
AppRoleDefinitionChange = define("app_role.definition.change", CategoryAdministration, "app_role", "M001", SeverityNotice, OCSFRoleManagement, 2)
SharingRoleEnable = define("sharing_role.enable", CategoryAdministration, "sharing_role", "M002", SeverityNotice, OCSFRoleManagement, 2)
SharingRoleDisable = define("sharing_role.disable", CategoryAdministration, "sharing_role", "M003", SeverityNotice, OCSFRoleManagement, 2)
SettingsChange = define("settings.change", CategoryAdministration, "settings", "M004", SeverityInfo, OCSFAPIActivity, 3)
ConfigChange = define("config.change", CategoryAdministration, "config", "M005", SeverityNotice, OCSFAPIActivity, 3)
CLICommand = define("cli.command", CategoryAdministration, "cli", "M006", SeverityNotice, OCSFAPIActivity, ocsfOther)
PersonalDataExport = define("personal_data.export", CategoryAdministration, "user", "M007", SeverityNotice, OCSFAPIActivity, 2)
)
// Security
var (
AccessDenied = define("access.denied", CategorySecurity, "resource", "X001", SeverityWarning, OCSFWebResourceAccessActivity, 2)
)
// Lookup returns the definition of the event with the given name.
func Lookup(name string) (*Definition, bool) {
d, ok := registry[name]
return d, ok
}
// Catalog returns all definitions, sorted by name.
func Catalog() []*Definition {
defs := make([]*Definition, 0, len(registry))
for _, d := range registry {
defs = append(defs, d)
}
sort.Slice(defs, func(i, j int) bool { return defs[i].Name < defs[j].Name })
return defs
}
+136
View File
@@ -0,0 +1,136 @@
package audit
import (
"context"
"net/url"
"strings"
ctxpkg "github.com/opencloud-eu/reva/v3/pkg/ctx"
"google.golang.org/grpc/metadata"
)
// Header carries the request context between services, as HTTP header and as
// gRPC metadata. Everything else the audit record needs (user, tenant,
// initiator, trace) already travels in its own header.
const Header = "x-audit-context"
// Short keys keep the header small, it is sent with every call.
const (
keyClientAddress = "ip"
keySessionID = "sid"
keyAuthMethod = "am"
keyClientID = "cid"
keyUserAgent = "ua"
)
// RequestContext is what the proxy knows about a request and the audit
// record needs, but no other header carries.
type RequestContext struct {
// ClientAddress is the real client address, resolved behind trusted proxies.
ClientAddress string
// SessionID identifies the login session.
SessionID string
// AuthMethod is how the actor authenticated, e.g. oidc, app_token, public_link, basic.
AuthMethod string
// ClientID is the OIDC client.
ClientID string
// UserAgent is the user agent of the client. The x-user-agent metadata
// is not set by every service, and the gRPC user-agent is the one of
// the calling service, not of the client.
UserAgent string
}
// IsZero reports whether no field is set.
func (rc RequestContext) IsZero() bool {
return rc == RequestContext{}
}
// Merge fills the identity fields rc lacks from initial, the request context
// of an earlier request of the same operation. A tus upload is created by an
// authenticated request, its data is sent with a transfer token, which has no
// login session or auth method. Address and user agent stay the ones of rc.
func (rc RequestContext) Merge(initial RequestContext) RequestContext {
fill := func(v *string, from string) {
if *v == "" {
*v = from
}
}
fill(&rc.SessionID, initial.SessionID)
fill(&rc.AuthMethod, initial.AuthMethod)
fill(&rc.ClientID, initial.ClientID)
return rc
}
// PublicShareID returns the public link a request is authorized by, if any.
func PublicShareID(ctx context.Context) string {
scopes, ok := ctxpkg.ContextGetScopes(ctx)
if !ok {
return ""
}
for k := range scopes {
if id, found := strings.CutPrefix(k, "publicshare:"); found {
return id
}
}
return ""
}
// Encode returns the header value.
func (rc RequestContext) Encode() string {
v := url.Values{}
set := func(k, val string) {
if val != "" {
v.Set(k, val)
}
}
set(keyClientAddress, rc.ClientAddress)
set(keySessionID, rc.SessionID)
set(keyAuthMethod, rc.AuthMethod)
set(keyClientID, rc.ClientID)
set(keyUserAgent, rc.UserAgent)
return v.Encode()
}
// ParseRequestContext reads a header value. Unknown keys are ignored, a
// broken value returns an empty context.
func ParseRequestContext(s string) RequestContext {
v, err := url.ParseQuery(s)
if err != nil {
return RequestContext{}
}
return RequestContext{
ClientAddress: v.Get(keyClientAddress),
SessionID: v.Get(keySessionID),
AuthMethod: v.Get(keyAuthMethod),
ClientID: v.Get(keyClientID),
UserAgent: v.Get(keyUserAgent),
}
}
type requestContextKey struct{}
// ContextSetRequest stores the request context in ctx and adds it to the
// outgoing gRPC metadata, so it reaches the next service.
func ContextSetRequest(ctx context.Context, rc RequestContext) context.Context {
if rc.IsZero() {
return ctx
}
ctx = context.WithValue(ctx, requestContextKey{}, rc)
return metadata.AppendToOutgoingContext(ctx, Header, rc.Encode())
}
// ContextGetRequest returns the request context from ctx, falling back to the
// incoming gRPC metadata.
func ContextGetRequest(ctx context.Context) (RequestContext, bool) {
if rc, ok := ctx.Value(requestContextKey{}).(RequestContext); ok {
return rc, true
}
if md, ok := metadata.FromIncomingContext(ctx); ok {
if lst := md.Get(Header); len(lst) > 0 {
rc := ParseRequestContext(lst[0])
return rc, !rc.IsZero()
}
}
return RequestContext{}, false
}
+389
View File
@@ -0,0 +1,389 @@
package audit
import (
"context"
"encoding/json"
"errors"
"fmt"
"sync"
"time"
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
"github.com/google/uuid"
"github.com/nats-io/nats.go"
ctxpkg "github.com/opencloud-eu/reva/v3/pkg/ctx"
"github.com/rs/zerolog"
"go.opentelemetry.io/otel/trace"
"google.golang.org/grpc/metadata"
)
// Mode decides what happens when an event can't be stored.
type Mode string
// ModeBestEffort publishes asynchronously through a bounded buffer and never
// blocks a request. Events that don't fit or fail are dropped and counted. It
// is the only mode for now: a strict mode has to refuse a request before it
// acts, the events middleware only sees a call after it happened.
const ModeBestEffort Mode = "best_effort"
// ErrUnknownMode is returned for a mode other than best_effort.
var ErrUnknownMode = errors.New("audit: unknown mode, only best_effort is supported")
// ErrInvalidEvent is returned when an event misses required fields.
var ErrInvalidEvent = errors.New("audit: invalid event")
// Target is the object an event acts on.
type Target struct {
ID string
SpaceID string
Name string
Path string
// Type overrides the target type of the definition.
Type string
}
// Change holds the changed attributes of an update. Never put secrets in it.
type Change struct {
Before map[string]any
After map[string]any
}
// Actor overrides the actor taken from the context, e.g. for the CLI, the
// system or a public link.
type Actor struct {
Type ActorType
ID string
Name string
}
// Event is what a service reports.
type Event struct {
Definition *Definition
Outcome Outcome
// Reason is a machine readable reason for failures and denials, e.g. permission_denied.
Reason string
Target Target
Change *Change
// Actor, when set, replaces the actor from the context.
Actor *Actor
// Tenant, when set, replaces the tenant of the actor, e.g. the tenant of the resource.
Tenant string
// Time defaults to now.
Time time.Time
}
// Emitter reports audit events.
type Emitter interface {
Emit(ctx context.Context, ev Event) error
}
// Publisher stores a message, in production a JetStream publish that waits for the ack.
type Publisher interface {
Publish(ctx context.Context, msg *nats.Msg) error
}
// Service describes the emitting service.
type Service struct {
Name string
Version string
InstanceID string
}
// Options configure an emitter.
type Options struct {
Service Service
// BufferSize is the size of the buffer, default 1000.
BufferSize int
// PublishTimeout limits one publish, default 5s.
PublishTimeout time.Duration
Logger *zerolog.Logger
}
// NatsEmitter builds records and publishes them.
type NatsEmitter struct {
pub Publisher
opts Options
log zerolog.Logger
queue chan *nats.Msg
// mu guards closed: Emit holds it for reading while it queues, Close for
// writing while it closes the queue, so no send hits a closed channel.
mu sync.RWMutex
closed bool
wg sync.WaitGroup
once sync.Once
now func() time.Time
}
// NewEmitter returns an emitter and starts its worker; call Close to flush the
// buffer on shutdown.
func NewEmitter(pub Publisher, opts Options) *NatsEmitter {
if opts.BufferSize <= 0 {
opts.BufferSize = 1000
}
if opts.PublishTimeout <= 0 {
opts.PublishTimeout = 5 * time.Second
}
log := zerolog.Nop()
if opts.Logger != nil {
log = *opts.Logger
}
e := &NatsEmitter{pub: pub, opts: opts, log: log, now: time.Now}
registerMetrics()
e.queue = make(chan *nats.Msg, opts.BufferSize)
e.wg.Add(1)
go e.work()
return e
}
// Emit builds the record and queues it for publishing. It never blocks: when
// the buffer is full, the record is dropped and counted.
func (e *NatsEmitter) Emit(ctx context.Context, ev Event) error {
rec, err := e.Record(ctx, ev)
if err != nil {
name := "unknown"
if ev.Definition != nil {
name = ev.Definition.Name
}
e.dropped(name, "invalid")
e.log.Error().Err(err).Msg("audit event not emitted")
return err
}
msg, err := message(rec, trace.SpanContextFromContext(ctx))
if err != nil {
e.dropped(rec.EventName, "marshal")
e.log.Error().Err(err).Str("event", rec.EventName).Msg("audit event not emitted")
return err
}
emittedTotal.WithLabelValues(e.opts.Service.Name, rec.EventName, string(rec.Outcome)).Inc()
e.mu.RLock()
defer e.mu.RUnlock()
if e.closed {
e.dropped(rec.EventName, "closed")
e.log.Error().Str("event", rec.EventName).Str("event_id", rec.EventID).Msg("audit emitter closed, event dropped")
return nil
}
select {
case e.queue <- msg:
default:
e.dropped(rec.EventName, "buffer_full")
e.log.Error().Str("event", rec.EventName).Str("event_id", rec.EventID).Msg("audit buffer full, event dropped")
}
return nil
}
// Record builds and validates the record for an event without publishing it.
func (e *NatsEmitter) Record(ctx context.Context, ev Event) (*Record, error) {
d := ev.Definition
if d == nil {
return nil, fmt.Errorf("%w: no definition", ErrInvalidEvent)
}
outcome := ev.Outcome
if outcome == "" {
outcome = OutcomeSuccess
}
if outcome != OutcomeSuccess && ev.Reason == "" {
return nil, fmt.Errorf("%w: %s %s without reason", ErrInvalidEvent, d.Name, outcome)
}
if ev.Target.ID == "" {
return nil, fmt.Errorf("%w: %s without target id", ErrInvalidEvent, d.Name)
}
t := ev.Time
if t.IsZero() {
t = e.now()
}
id, err := uuid.NewV7()
if err != nil {
return nil, err
}
rec := &Record{
EventID: id.String(),
EventName: d.Name,
EventCode: d.Code(outcome),
SchemaVersion: SchemaVersion,
Time: formatTime(t),
Outcome: outcome,
OutcomeReason: ev.Reason,
Severity: d.severity(outcome),
TargetType: d.TargetType,
TargetID: ev.Target.ID,
TargetSpaceID: ev.Target.SpaceID,
TargetName: ev.Target.Name,
TargetPath: ev.Target.Path,
ServiceName: e.opts.Service.Name,
ServiceVersion: e.opts.Service.Version,
ServiceInstanceID: e.opts.Service.InstanceID,
OCSFClassUID: d.OCSFClass,
OCSFActivityID: d.activity(outcome),
}
if ev.Target.Type != "" {
rec.TargetType = ev.Target.Type
}
if ev.Change != nil {
rec.ChangeBefore = ev.Change.Before
rec.ChangeAfter = ev.Change.After
}
setActor(ctx, rec, ev.Actor)
if ev.Tenant != "" {
rec.TenantID = ev.Tenant
}
if rc, ok := ContextGetRequest(ctx); ok {
rec.ClientAddress = rc.ClientAddress
rec.SessionID = rc.SessionID
rec.AuthMethod = rc.AuthMethod
rec.AuthClientID = rc.ClientID
rec.UserAgent = rc.UserAgent
}
if rec.UserAgent == "" {
rec.UserAgent = clientUserAgent(ctx)
}
if sc := trace.SpanContextFromContext(ctx); sc.IsValid() {
rec.TraceID = sc.TraceID().String()
rec.SpanID = sc.SpanID().String()
}
return rec, nil
}
// clientUserAgent reads the x-user-agent metadata the reva HTTP services set.
// Unlike ctxpkg.ContextGetUserAgentString it never falls back to the gRPC
// user-agent, that is the one of the calling service, e.g. grpc-go/1.84.0.
func clientUserAgent(ctx context.Context) string {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return ""
}
if lst := md.Get(ctxpkg.UserAgentHeader); len(lst) > 0 {
return lst[0]
}
return ""
}
func setActor(ctx context.Context, rec *Record, override *Actor) {
if override != nil {
rec.ActorType, rec.ActorID, rec.ActorName = override.Type, override.ID, override.Name
}
u, ok := ctxpkg.ContextGetUser(ctx)
if !ok || u == nil {
if override == nil {
rec.ActorType = ActorAnonymous
}
return
}
rec.TenantID = u.GetId().GetTenantId()
if override != nil {
return
}
// a public link acts with the user of its owner, the scope names the link
if id := PublicShareID(ctx); id != "" {
rec.ActorType, rec.ActorID = ActorPublicLink, id
return
}
rec.ActorID = u.GetId().GetOpaqueId()
rec.ActorName = u.GetDisplayName()
if rec.ActorName == "" {
rec.ActorName = u.GetUsername()
}
switch u.GetId().GetType() {
case userpb.UserType_USER_TYPE_GUEST, userpb.UserType_USER_TYPE_LIGHTWEIGHT:
rec.ActorType = ActorGuest
case userpb.UserType_USER_TYPE_SERVICE, userpb.UserType_USER_TYPE_APPLICATION:
rec.ActorType = ActorService
default:
rec.ActorType = ActorUser
}
}
func (e *NatsEmitter) publish(ctx context.Context, msg *nats.Msg) error {
ctx, cancel := context.WithTimeout(ctx, e.opts.PublishTimeout)
defer cancel()
start := time.Now()
err := e.pub.Publish(ctx, msg)
publishDuration.WithLabelValues(e.opts.Service.Name).Observe(time.Since(start).Seconds())
if err != nil {
e.dropped(msg.Header.Get("ce-type"), "publish")
e.log.Error().Err(err).Str("event_id", msg.Header.Get(nats.MsgIdHdr)).Msg("audit event not stored")
}
return err
}
// dropped counts an event that is not stored. The event names come from the
// catalog, so the label stays bounded.
func (e *NatsEmitter) dropped(event, reason string) {
droppedTotal.WithLabelValues(e.opts.Service.Name, event, reason).Inc()
}
func (e *NatsEmitter) work() {
defer e.wg.Done()
for msg := range e.queue {
// the request is gone, the publish must not be cancelled with it
_ = e.publish(context.Background(), msg)
}
}
// Close flushes the buffer. Events emitted afterwards are dropped and counted.
func (e *NatsEmitter) Close() {
e.once.Do(func() {
e.mu.Lock()
e.closed = true
close(e.queue)
e.mu.Unlock()
e.wg.Wait()
})
}
func message(rec *Record, sc trace.SpanContext) (*nats.Msg, error) {
data, err := json.Marshal(rec)
if err != nil {
return nil, err
}
msg := nats.NewMsg(Subject(rec.TenantID, categoryOf(rec.EventName)))
msg.Data = data
// CloudEvents NATS binding, binary mode
msg.Header.Set(nats.MsgIdHdr, rec.EventID)
msg.Header.Set("ce-specversion", "1.0")
msg.Header.Set("ce-id", rec.EventID)
msg.Header.Set("ce-type", rec.EventName)
msg.Header.Set("ce-source", "/opencloud/"+rec.ServiceName)
msg.Header.Set("ce-time", rec.Time)
msg.Header.Set("ce-partitionkey", rec.TenantID)
msg.Header.Set("content-type", "application/json")
if sc.IsValid() {
msg.Header.Set("traceparent", fmt.Sprintf("00-%s-%s-%s", sc.TraceID(), sc.SpanID(), sc.TraceFlags()))
}
return msg, nil
}
func categoryOf(name string) string {
if d, ok := Lookup(name); ok {
return d.Category
}
return "unknown"
}
// Enabled reports whether e stores events, false for nil and Discard. Code
// that has to look something up for an event checks it first.
func Enabled(e Emitter) bool {
if e == nil {
return false
}
_, off := e.(Discard)
return !off
}
// CloseEmitter flushes and closes e if it has a buffer, e.g. on shutdown.
func CloseEmitter(e Emitter) {
if c, ok := e.(interface{ Close() }); ok {
c.Close()
}
}
// Discard is an emitter that drops everything, for tests and disabled audit.
type Discard struct{}
// Emit does nothing.
func (Discard) Emit(context.Context, Event) error { return nil }
+49
View File
@@ -0,0 +1,49 @@
package audit
import (
"errors"
"sync"
"github.com/prometheus/client_golang/prometheus"
)
// All services run in one binary, so the metrics are registered once and
// labelled by service.
var (
emittedTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: "opencloud",
Subsystem: "audit",
Name: "events_emitted_total",
Help: "Audit events handed to the emitter, including the ones dropped later.",
}, []string{"service", "event", "outcome"})
droppedTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: "opencloud",
Subsystem: "audit",
Name: "events_dropped_total",
Help: "Audit events that were not stored, by event and reason.",
}, []string{"service", "event", "reason"})
publishDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Namespace: "opencloud",
Subsystem: "audit",
Name: "publish_duration_seconds",
Help: "Time to store an audit event in JetStream.",
Buckets: []float64{.001, .0025, .005, .01, .025, .05, .1, .25, .5, 1, 5},
}, []string{"service"})
metricsOnce sync.Once
)
func registerMetrics() {
metricsOnce.Do(func() {
for _, c := range []prometheus.Collector{emittedTotal, droppedTotal, publishDuration} {
if err := prometheus.Register(c); err != nil {
var are prometheus.AlreadyRegisteredError
if !errors.As(err, &are) {
panic(err)
}
}
}
})
}
+71
View File
@@ -0,0 +1,71 @@
package audit
import (
"context"
"errors"
"fmt"
"github.com/nats-io/nats.go/jetstream"
"github.com/opencloud-eu/reva/v3/pkg/events/raw"
)
// NewNatsEmitter connects to NATS and returns an emitter that publishes to
// the audit stream. It creates the stream with defaults when it is missing,
// so events published before the audit service started are kept. It never
// changes an existing stream, that is the job of the audit service.
func NewNatsEmitter(ctx context.Context, connName string, cfg raw.Config, opts Options) (*NatsEmitter, error) {
js, err := raw.JetStream(ctx, connName, cfg)
if err != nil {
return nil, err
}
if err := createStreamIfMissing(ctx, js); err != nil {
return nil, err
}
return NewEmitter(JetStreamPublisher{JS: js}, opts), nil
}
func createStreamIfMissing(ctx context.Context, js jetstream.JetStream) error {
if _, err := js.Stream(ctx, StreamName); err == nil {
return nil
} else if !errors.Is(err, jetstream.ErrStreamNotFound) {
return err
}
// another service may create it at the same time, that is fine
_, err := js.CreateStream(ctx, streamConfig(StreamConfig{}))
if errors.Is(err, jetstream.ErrStreamNameAlreadyInUse) {
return nil
}
return err
}
// EmitterConfig is the audit part of a reva service config.
type EmitterConfig struct {
Enabled bool `mapstructure:"enabled"`
Mode string `mapstructure:"mode"`
Service string `mapstructure:"service"`
// ServiceVersion is the version of the service, e.g. of OpenCloud.
ServiceVersion string `mapstructure:"service_version"`
// NATS connection, same keys as the events config: address, clusterID, ...
Nats raw.Config `mapstructure:",squash"`
}
// ErrNoEndpoint is returned when audit is enabled without a NATS endpoint.
var ErrNoEndpoint = errors.New("audit is enabled but no events endpoint is configured")
// EmitterFromConfig returns an emitter for the config, one that drops
// everything when audit is off. Audit without an endpoint or with an unknown
// mode is an error, not a silent discard.
func EmitterFromConfig(ctx context.Context, connName string, cfg EmitterConfig, opts Options) (Emitter, error) {
if !cfg.Enabled {
return Discard{}, nil
}
if cfg.Nats.Endpoint == "" {
return nil, ErrNoEndpoint
}
if m := Mode(cfg.Mode); m != "" && m != ModeBestEffort {
return nil, fmt.Errorf("%w: %q", ErrUnknownMode, cfg.Mode)
}
opts.Service.Name = cfg.Service
opts.Service.Version = cfg.ServiceVersion
return NewNatsEmitter(ctx, connName, cfg.Nats, opts)
}
+111
View File
@@ -0,0 +1,111 @@
// Package audit emits audit events as described in OpenCloud ADR 0006.
//
// Services describe what happened with an Event and hand it to an Emitter.
// The emitter fills in the actor, the request context, the trace and the
// service, validates the event against its Definition and publishes the
// resulting Record to the JetStream stream "audit".
package audit
import "time"
// SchemaVersion is the version of the Record schema. Changes are additive only.
const SchemaVersion = "1.0"
// TimeFormat is RFC 3339 in UTC with millisecond precision.
const TimeFormat = "2006-01-02T15:04:05.000Z07:00"
// Outcome is the result of the audited action.
type Outcome string
const (
OutcomeSuccess Outcome = "success"
OutcomeFailure Outcome = "failure"
OutcomeDenied Outcome = "denied"
)
// Severity of a record.
type Severity string
const (
SeverityInfo Severity = "info"
SeverityNotice Severity = "notice"
SeverityWarning Severity = "warning"
SeverityAlert Severity = "alert"
)
// rank orders severities, so an outcome can raise but never lower it.
func (s Severity) rank() int {
switch s {
case SeverityNotice:
return 1
case SeverityWarning:
return 2
case SeverityAlert:
return 3
default:
return 0
}
}
// ActorType says who acted.
type ActorType string
const (
ActorUser ActorType = "user"
ActorService ActorType = "service"
ActorPublicLink ActorType = "public_link"
ActorGuest ActorType = "guest"
ActorAnonymous ActorType = "anonymous"
ActorSystem ActorType = "system"
ActorCLI ActorType = "cli"
)
// Record is one audit event as it is written to the stream and the sinks:
// one line of JSON with OpenTelemetry attribute names where they exist.
type Record struct {
EventID string `json:"event.id"`
EventName string `json:"event.name"`
EventCode string `json:"event.code"`
SchemaVersion string `json:"schema_version"`
Time string `json:"time"`
Outcome Outcome `json:"outcome"`
OutcomeReason string `json:"outcome.reason,omitempty"`
Severity Severity `json:"severity"`
TenantID string `json:"tenant.id"`
ActorType ActorType `json:"actor.type"`
ActorID string `json:"actor.id,omitempty"`
ActorName string `json:"actor.name,omitempty"`
AuthMethod string `json:"auth.method,omitempty"`
AuthClientID string `json:"auth.client_id,omitempty"`
SessionID string `json:"session.id,omitempty"`
ClientAddress string `json:"client.address,omitempty"`
UserAgent string `json:"user_agent.original,omitempty"`
TargetType string `json:"target.type"`
TargetID string `json:"target.id"`
TargetSpaceID string `json:"target.space.id,omitempty"`
TargetName string `json:"target.name,omitempty"`
TargetPath string `json:"target.path,omitempty"`
ChangeBefore map[string]any `json:"change.before,omitempty"`
ChangeAfter map[string]any `json:"change.after,omitempty"`
TraceID string `json:"trace_id,omitempty"`
SpanID string `json:"span_id,omitempty"`
ServiceName string `json:"service.name"`
ServiceVersion string `json:"service.version,omitempty"`
ServiceInstanceID string `json:"service.instance.id,omitempty"`
OCSFClassUID int `json:"ocsf.class_uid"`
OCSFActivityID int `json:"ocsf.activity_id"`
}
func formatTime(t time.Time) string {
return t.UTC().Format(TimeFormat)
}
+93
View File
@@ -0,0 +1,93 @@
package audit
import (
"context"
"errors"
"strings"
"time"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
)
// StreamName is the JetStream stream that buffers audit events.
const StreamName = "audit"
// SubjectPrefix of all audit subjects: audit.<tenant>.<category>.
const SubjectPrefix = "audit"
// noTenant replaces an empty tenant in the subject.
const noTenant = "_"
// Subject returns the subject for a tenant and a category.
func Subject(tenant, category string) string {
return SubjectPrefix + "." + token(tenant) + "." + token(category)
}
// token makes a value safe as one subject token: no dots, wildcards or spaces.
func token(s string) string {
if s == "" {
return noTenant
}
return strings.Map(func(r rune) rune {
switch {
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '-', r == '_':
return r
default:
return '_'
}
}, s)
}
// StreamConfig configures the audit stream.
type StreamConfig struct {
// Replicas in clustered NATS, default 1.
Replicas int
// MaxAge is how long events stay in the buffer, default 7 days.
MaxAge time.Duration
// DuplicateWindow for Nats-Msg-Id deduplication, default 2 minutes.
DuplicateWindow time.Duration
}
// EnsureStream creates the audit stream or updates its configuration.
func EnsureStream(ctx context.Context, js jetstream.JetStream, cfg StreamConfig) (jetstream.Stream, error) {
sc := streamConfig(cfg)
s, err := js.CreateStream(ctx, sc)
if errors.Is(err, jetstream.ErrStreamNameAlreadyInUse) {
return js.UpdateStream(ctx, sc)
}
return s, err
}
func streamConfig(cfg StreamConfig) jetstream.StreamConfig {
if cfg.Replicas <= 0 {
cfg.Replicas = 1
}
if cfg.MaxAge <= 0 {
cfg.MaxAge = 7 * 24 * time.Hour
}
if cfg.DuplicateWindow <= 0 {
cfg.DuplicateWindow = 2 * time.Minute
}
return jetstream.StreamConfig{
Name: StreamName,
Description: "OpenCloud audit events, a buffer between the services and the audit service",
Subjects: []string{SubjectPrefix + ".>"},
Storage: jetstream.FileStorage,
Retention: jetstream.LimitsPolicy,
Replicas: cfg.Replicas,
MaxAge: cfg.MaxAge,
Duplicates: cfg.DuplicateWindow,
}
}
// JetStreamPublisher publishes to JetStream and waits for the ack.
type JetStreamPublisher struct {
JS jetstream.JetStream
}
// Publish stores the message in the audit stream.
func (p JetStreamPublisher) Publish(ctx context.Context, msg *nats.Msg) error {
_, err := p.JS.PublishMsg(ctx, msg)
return err
}
+45 -18
View File
@@ -21,6 +21,7 @@ package scope
import (
"context"
"fmt"
"path"
"strings"
appprovider "github.com/cs3org/go-cs3apis/cs3/app/provider/v1beta1"
@@ -55,6 +56,12 @@ func resourceinfoScope(_ context.Context, scope *authpb.Scope, resource interfac
StorageId: string(e.Value),
}
}
if e, ok := v.Opaque.Map["space_id"]; ok {
if ref.ResourceId == nil {
ref.ResourceId = &provider.ResourceId{}
}
ref.ResourceId.SpaceId = string(e.Value)
}
if e, ok := v.Opaque.Map["opaque_id"]; ok {
if ref.ResourceId == nil {
ref.ResourceId = &provider.ResourceId{}
@@ -106,24 +113,38 @@ func resourceinfoScope(_ context.Context, scope *authpb.Scope, resource interfac
return false, errtypes.InternalError(msg)
}
// checkResourceInfo checks whether ref references the resource of the scope,
// or a resource below it.
//
// Only references with the id of the resource are accepted, with an optional
// relative path that doesn't leave the resource. References with a path only
// are rejected: the path of the resource in the scope is whatever the storage
// provider returned for it (e.g. only its name for a relative reference), while
// the path of a path only reference is in the namespace of the gateway, so the
// two can't be compared.
func checkResourceInfo(inf *provider.ResourceInfo, ref *provider.Reference) bool {
// ref: <resource_id:<storage_id:$storageID opaque_id:$opaqueID path:$path> >
if ref.ResourceId != nil { // path can be empty or a relative path
if inf.Id.SpaceId == ref.ResourceId.SpaceId && inf.Id.OpaqueId == ref.ResourceId.OpaqueId {
if ref.Path == "" {
// id only reference
return true
}
// check path has same prefix below
} else {
return false
}
id := ref.GetResourceId()
if id == nil || inf.GetId().GetSpaceId() == "" || inf.GetId().GetOpaqueId() == "" {
return false
}
// ref: <path:$path >
if strings.HasPrefix(ref.GetPath(), inf.Path) {
if id.GetSpaceId() != inf.GetId().GetSpaceId() || id.GetOpaqueId() != inf.GetId().GetOpaqueId() {
return false
}
return isPathInsideResource(ref.GetPath())
}
// isPathInsideResource checks whether p, the path of an id based reference, is
// the resource itself ("" or ".") or a path below it ("./a", "a/b"). Absolute
// paths and paths leaving the resource ("..", "./a/../../b") are rejected.
func isPathInsideResource(p string) bool {
if p == "" {
return true
}
return false
if strings.HasPrefix(p, "/") {
return false
}
p = path.Clean(p)
return p != ".." && !strings.HasPrefix(p, "../")
}
func checkResourcePath(path string) bool {
@@ -144,10 +165,16 @@ func checkResourcePath(path string) bool {
return false
}
// AddResourceInfoScope adds the scope to allow access to a resource info object.
// AddResourceInfoScope adds the scope to allow access to the resource with the
// id of r, and to the resources below it. r must have a complete id.
//
// Only the id is stored in the scope: the path of a resource info is no stable
// address of the resource, and its form depends on how it was looked up.
func AddResourceInfoScope(r *provider.ResourceInfo, role authpb.Role, scopes map[string]*authpb.Scope) (map[string]*authpb.Scope, error) {
// Create a new "scope info" to only expose the required fields `Id` and `Path` to the scope.
scopeInfo := &provider.ResourceInfo{Id: r.Id, Path: r.Path}
if r.GetId().GetSpaceId() == "" || r.GetId().GetOpaqueId() == "" {
return nil, errtypes.BadRequest("resourceinfo scope: resource info without a complete id")
}
scopeInfo := &provider.ResourceInfo{Id: r.GetId()}
val, err := utils.MarshalProtoV1ToJSON(scopeInfo)
if err != nil {
return nil, err
@@ -155,7 +182,7 @@ func AddResourceInfoScope(r *provider.ResourceInfo, role authpb.Role, scopes map
if scopes == nil {
scopes = make(map[string]*authpb.Scope)
}
scopes["resourceinfo:"+r.Id.String()] = &authpb.Scope{
scopes["resourceinfo:"+r.GetId().String()] = &authpb.Scope{
Resource: &types.OpaqueEntry{
Decoder: "json",
Value: val,
+3
View File
@@ -28,6 +28,7 @@ import (
"github.com/go-viper/mapstructure/v2"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
"github.com/opencloud-eu/reva/v3/internal/grpc/interceptors/appctx"
"github.com/opencloud-eu/reva/v3/internal/grpc/interceptors/auditctx"
"github.com/opencloud-eu/reva/v3/internal/grpc/interceptors/auth"
"github.com/opencloud-eu/reva/v3/internal/grpc/interceptors/log"
"github.com/opencloud-eu/reva/v3/internal/grpc/interceptors/recovery"
@@ -333,6 +334,7 @@ func (s *Server) getInterceptors(unprotected []string) ([]grpc.ServerOption, err
appctx.NewUnary(s.log, s.tracerProvider),
token.NewUnary(),
useragent.NewUnary(),
auditctx.NewUnary(),
log.NewUnary(),
recovery.NewUnary(),
authUnary,
@@ -375,6 +377,7 @@ func (s *Server) getInterceptors(unprotected []string) ([]grpc.ServerOption, err
appctx.NewStream(s.log, s.tracerProvider),
token.NewStream(),
useragent.NewStream(),
auditctx.NewStream(),
log.NewStream(),
recovery.NewStream(),
authStream,
+97
View File
@@ -0,0 +1,97 @@
package datatx
import (
"context"
"path"
userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/opencloud-eu/reva/v3/pkg/appctx"
"github.com/opencloud-eu/reva/v3/pkg/audit"
ctxpkg "github.com/opencloud-eu/reva/v3/pkg/ctx"
"github.com/opencloud-eu/reva/v3/pkg/storage"
"github.com/opencloud-eu/reva/v3/pkg/storagespace"
"github.com/opencloud-eu/reva/v3/pkg/utils"
)
// UploadAudit describes a finished upload for the audit log.
type UploadAudit struct {
// Header is the X-Audit-Context of the request that finished the upload.
// Without it the upload was not sent by a client and is not reported.
Header string
// Initial is the request context of the request that created the upload,
// for what the finishing request lacks, e.g. the auth method of a tus
// upload whose data is sent with a transfer token.
Initial audit.RequestContext
// Executant is the user of the upload session, the actor when the
// context has no user, as for tus uploads.
Executant *userv1beta1.User
// PublicShareID is the public link the upload was created through, when
// the context doesn't tell.
PublicShareID string
// Ref is where the file was uploaded to, ID the node.
Ref *provider.Reference
ID *provider.ResourceId
Name string
// FS looks up the path of the node in its space. The path of the upload
// session is cut off above what the uploader may see, e.g. in a share.
FS storage.FS
}
// EmitUploadAudit reports a finished upload. Only uploads a client sent are
// reported: the proxy marks them with the audit header, writes by OpenCloud
// itself, e.g. for a copy, don't carry it. With audit off nothing is looked up.
func EmitUploadAudit(ctx context.Context, e audit.Emitter, u UploadAudit) {
if !audit.Enabled(e) || u.Header == "" {
return
}
ctx = audit.ContextSetRequest(ctx, audit.ParseRequestContext(u.Header).Merge(u.Initial))
target := storagespace.FormatResourceID(u.ID)
if u.ID.GetOpaqueId() == "" {
target, _ = storagespace.FormatReference(u.Ref)
}
ev := audit.Event{
Definition: audit.FileUpload,
Target: audit.Target{ID: target, Path: u.Ref.GetPath(), Name: u.Name},
}
if rid := u.Ref.GetResourceId(); rid != nil {
ev.Target.SpaceID = storagespace.FormatStorageID(rid.GetStorageId(), rid.GetSpaceId())
}
if ev.Target.Name == "" && u.Ref.GetPath() != "" && u.Ref.GetPath() != "." {
ev.Target.Name = path.Base(u.Ref.GetPath())
}
if _, ok := ctxpkg.ContextGetUser(ctx); !ok && u.Executant != nil {
// the emitter takes name, type and tenant from the user
ctx = ctxpkg.ContextSetUser(ctx, u.Executant)
}
if p := pathInSpace(ctx, u.FS, u.ID); p != "" {
ev.Target.Path = p
}
shareID := audit.PublicShareID(ctx)
if shareID == "" {
shareID = u.PublicShareID
}
if shareID != "" {
// through a public link the user is the owner of the link
ev.Actor = &audit.Actor{Type: audit.ActorPublicLink, ID: shareID}
}
if err := e.Emit(ctx, ev); err != nil {
appctx.GetLogger(ctx).Error().Err(err).Msg("audit event not emitted")
}
}
// pathInSpace returns the path of the node in its space. A stat by ID has the
// whole path, a stat by path only what the user may see.
func pathInSpace(ctx context.Context, fs storage.FS, id *provider.ResourceId) string {
if fs == nil || id.GetOpaqueId() == "" {
return ""
}
info, err := fs.GetMD(ctx, &provider.Reference{ResourceId: id}, nil, []string{"path"})
if err != nil || info.GetPath() == "" || info.GetPath() == "." {
return ""
}
return utils.MakeRelativePath(info.GetPath())
}
@@ -21,13 +21,15 @@ package registry
import (
"github.com/rs/zerolog"
"github.com/opencloud-eu/reva/v3/pkg/audit"
"github.com/opencloud-eu/reva/v3/pkg/events"
"github.com/opencloud-eu/reva/v3/pkg/rhttp/datatx"
)
// NewFunc is the function that data transfer implementations
// should register at init time.
type NewFunc func(map[string]interface{}, events.Publisher, *zerolog.Logger) (datatx.DataTX, error)
// The emitter receives the audit events of uploads and downloads.
type NewFunc func(map[string]interface{}, events.Publisher, audit.Emitter, *zerolog.Logger) (datatx.DataTX, error)
// NewFuncs is a map containing all the registered data transfers.
var NewFuncs = map[string]NewFunc{}
@@ -25,6 +25,7 @@ import (
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/go-viper/mapstructure/v2"
"github.com/opencloud-eu/reva/v3/pkg/audit"
ctxpkg "github.com/opencloud-eu/reva/v3/pkg/ctx"
"github.com/pkg/errors"
"github.com/rs/zerolog"
@@ -51,6 +52,7 @@ func init() {
type manager struct {
conf *cache.Config
publisher events.Publisher
emitter audit.Emitter
log *zerolog.Logger
}
@@ -64,7 +66,7 @@ func parseConfig(m map[string]interface{}) (*cache.Config, error) {
}
// New returns a datatx manager implementation that relies on HTTP PUT/GET.
func New(m map[string]interface{}, publisher events.Publisher, log *zerolog.Logger) (datatx.DataTX, error) {
func New(m map[string]interface{}, publisher events.Publisher, emitter audit.Emitter, log *zerolog.Logger) (datatx.DataTX, error) {
c, err := parseConfig(m)
if err != nil {
return nil, err
@@ -75,6 +77,7 @@ func New(m map[string]interface{}, publisher events.Publisher, log *zerolog.Logg
return &manager{
conf: c,
publisher: publisher,
emitter: emitter,
log: &l,
}, nil
}
@@ -93,7 +96,7 @@ func (m *manager) Handler(coord upload.Coordinator, driver storage.FS) (http.Han
metrics.DownloadsActive.Sub(1)
}()
}
download.GetOrHeadFile(w, r, driver, "")
download.GetOrHeadFile(w, r, driver, "", m.emitter)
case "PUT":
metrics.UploadsActive.Add(1)
defer func() {
@@ -115,6 +118,8 @@ func (m *manager) Handler(coord upload.Coordinator, driver storage.FS) (http.Han
ctx = ctxpkg.ContextSetLockID(ctx, lockID)
}
var auditOwner *userpb.UserId
var auditRef *provider.Reference
info, err := coord.Upload(ctx, upload.Request{
Ref: ref,
Body: r.Body,
@@ -123,9 +128,14 @@ func (m *manager) Handler(coord upload.Coordinator, driver storage.FS) (http.Han
if err := datatx.EmitFileUploadedEvent(spaceOwner, owner, ref, m.publisher); err != nil {
sublog.Error().Err(err).Msg("failed to publish FileUploaded event")
}
auditOwner, auditRef = owner, ref
})
switch v := err.(type) {
case nil:
// audited here, the node ID is only known now
if auditRef != nil {
datatx.EmitUploadAudit(ctx, m.emitter, datatx.UploadAudit{Header: r.Header.Get(audit.Header), Executant: &userpb.User{Id: auditOwner}, Ref: auditRef, ID: info.GetId(), FS: driver})
}
// set etag, mtime and file id
w.Header().Set(net.HeaderETag, info.Etag)
w.Header().Set(net.HeaderOCETag, info.Etag)
@@ -32,6 +32,7 @@ import (
"github.com/opencloud-eu/reva/v3/internal/http/services/owncloud/ocdav/net"
"github.com/opencloud-eu/reva/v3/pkg/appctx"
"github.com/opencloud-eu/reva/v3/pkg/audit"
"github.com/opencloud-eu/reva/v3/pkg/errtypes"
"github.com/opencloud-eu/reva/v3/pkg/events"
"github.com/opencloud-eu/reva/v3/pkg/rhttp/datatx"
@@ -53,6 +54,7 @@ func init() {
type manager struct {
conf *cache.Config
publisher events.Publisher
emitter audit.Emitter
log *zerolog.Logger
}
@@ -66,7 +68,7 @@ func parseConfig(m map[string]interface{}) (*cache.Config, error) {
}
// New returns a datatx manager implementation that relies on HTTP PUT/GET.
func New(m map[string]interface{}, publisher events.Publisher, log *zerolog.Logger) (datatx.DataTX, error) {
func New(m map[string]interface{}, publisher events.Publisher, emitter audit.Emitter, log *zerolog.Logger) (datatx.DataTX, error) {
c, err := parseConfig(m)
if err != nil {
return nil, err
@@ -77,6 +79,7 @@ func New(m map[string]interface{}, publisher events.Publisher, log *zerolog.Logg
return &manager{
conf: c,
publisher: publisher,
emitter: emitter,
log: &l,
}, nil
}
@@ -98,7 +101,7 @@ func (m *manager) Handler(coord upload.Coordinator, driver storage.FS) (http.Han
metrics.DownloadsActive.Sub(1)
}()
}
download.GetOrHeadFile(w, r, driver, spaceID)
download.GetOrHeadFile(w, r, driver, spaceID, m.emitter)
case "PUT":
metrics.UploadsActive.Add(1)
defer func() {
@@ -118,6 +121,8 @@ func (m *manager) Handler(coord upload.Coordinator, driver storage.FS) (http.Han
Path: fn,
}
var info *provider.ResourceInfo
var auditOwner *userpb.UserId
var auditRef *provider.Reference
info, err = coord.Upload(ctx, upload.Request{
Ref: ref,
Body: r.Body,
@@ -126,9 +131,14 @@ func (m *manager) Handler(coord upload.Coordinator, driver storage.FS) (http.Han
if err := datatx.EmitFileUploadedEvent(spaceOwner, owner, ref, m.publisher); err != nil {
sublog.Error().Err(err).Msg("failed to publish FileUploaded event")
}
auditOwner, auditRef = owner, ref
})
switch v := err.(type) {
case nil:
// audited here, the node ID is only known now
if auditRef != nil {
datatx.EmitUploadAudit(ctx, m.emitter, datatx.UploadAudit{Header: r.Header.Get(audit.Header), Executant: &userpb.User{Id: auditOwner}, Ref: auditRef, ID: info.GetId(), FS: driver})
}
// set etag, mtime and file id
w.Header().Set(net.HeaderETag, info.Etag)
w.Header().Set(net.HeaderOCETag, info.Etag)
+29 -1
View File
@@ -26,6 +26,7 @@ import (
"regexp"
"runtime"
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/go-viper/mapstructure/v2"
"github.com/pkg/errors"
@@ -35,6 +36,7 @@ import (
"github.com/opencloud-eu/reva/v3/internal/http/services/owncloud/ocdav/net"
"github.com/opencloud-eu/reva/v3/pkg/appctx"
"github.com/opencloud-eu/reva/v3/pkg/audit"
"github.com/opencloud-eu/reva/v3/pkg/events"
"github.com/opencloud-eu/reva/v3/pkg/rhttp/datatx"
"github.com/opencloud-eu/reva/v3/pkg/rhttp/datatx/manager/registry"
@@ -42,6 +44,7 @@ import (
"github.com/opencloud-eu/reva/v3/pkg/storage"
"github.com/opencloud-eu/reva/v3/pkg/storagespace"
"github.com/opencloud-eu/reva/v3/pkg/upload"
"github.com/opencloud-eu/reva/v3/pkg/utils"
)
func init() {
@@ -61,6 +64,7 @@ type TusConfig struct {
type manager struct {
conf *TusConfig
publisher events.Publisher
emitter audit.Emitter
log *zerolog.Logger
}
@@ -74,7 +78,7 @@ func parseConfig(m map[string]interface{}) (*TusConfig, error) {
}
// New returns a datatx manager implementation that relies on HTTP PUT/GET.
func New(m map[string]interface{}, publisher events.Publisher, log *zerolog.Logger) (datatx.DataTX, error) {
func New(m map[string]interface{}, publisher events.Publisher, emitter audit.Emitter, log *zerolog.Logger) (datatx.DataTX, error) {
c, err := parseConfig(m)
if err != nil {
return nil, err
@@ -85,6 +89,7 @@ func New(m map[string]interface{}, publisher events.Publisher, log *zerolog.Logg
return &manager{
conf: c,
publisher: publisher,
emitter: emitter,
log: &l,
}, nil
}
@@ -155,6 +160,9 @@ func (m *manager) Handler(coord upload.Coordinator, fs storage.FS) (http.Handler
appctx.GetLogger(context.Background()).Error().Err(err).Msg("failed to publish FileUploaded event")
}
}
ua := tusUploadAudit(up, ev.HTTPRequest.Header.Get(audit.Header), ev.Upload.MetaData["filename"])
ua.FS = fs
datatx.EmitUploadAudit(ev.Context, m.emitter, ua)
}
}()
@@ -350,3 +358,23 @@ func (l tusdLogger) WithAttrs(attr []slog.Attr) slog.Handler {
// WithGroup is not implemented
func (l tusdLogger) WithGroup(name string) slog.Handler { return l }
// tusUploadAudit describes a finished tus upload. The data requests carry a
// transfer token, so the user, the public link, the auth method and the path
// come from the upload session.
func tusUploadAudit(up storage.UploadSession, header, filename string) datatx.UploadAudit {
ref := up.Reference()
ua := datatx.UploadAudit{Header: header, Ref: &ref, ID: ref.GetResourceId(), Name: filename}
executant := up.Executant()
ua.Executant = &userpb.User{Id: &executant}
if s, ok := up.(upload.Session); ok {
ua.Executant = s.ExecutantUser()
ua.Initial, ua.PublicShareID = s.AuditOrigin()
// the path in the space, like the other file events
ua.Ref = &provider.Reference{
ResourceId: &provider.ResourceId{StorageId: s.ProviderID(), SpaceId: s.SpaceID(), OpaqueId: s.SpaceID()},
Path: utils.MakeRelativePath(path.Join(s.Dir(), s.Filename())),
}
}
return ua
}
@@ -35,6 +35,7 @@ import (
"github.com/opencloud-eu/reva/v3/internal/grpc/services/storageprovider"
"github.com/opencloud-eu/reva/v3/internal/http/services/owncloud/ocdav/net"
"github.com/opencloud-eu/reva/v3/pkg/appctx"
"github.com/opencloud-eu/reva/v3/pkg/audit"
"github.com/opencloud-eu/reva/v3/pkg/errtypes"
"github.com/opencloud-eu/reva/v3/pkg/storage"
"github.com/opencloud-eu/reva/v3/pkg/storagespace"
@@ -60,9 +61,18 @@ func EtagFromContext(ctx context.Context) string {
return ""
}
// GetOrHeadFile returns the requested file content
func GetOrHeadFile(w http.ResponseWriter, r *http.Request, fs storage.FS, spaceID string) {
// GetOrHeadFile returns the requested file content. Downloads are reported to
// the emitter.
func GetOrHeadFile(w http.ResponseWriter, r *http.Request, fs storage.FS, spaceID string, emitter audit.Emitter) {
ctx := r.Context()
// Only downloads a client asked for are audited. The proxy marks them with
// the audit header; internal reads (copy, thumbnails, search, the
// archiver) build their own requests without it.
auditHeader := r.Header.Get(audit.Header)
audited := r.Method == http.MethodGet && auditHeader != "" && audit.Enabled(emitter)
if audited {
ctx = audit.ContextSetRequest(ctx, audit.ParseRequestContext(auditHeader))
}
sublog := appctx.GetLogger(ctx).With().Str("svc", "datatx").Str("handler", "download").Logger()
var fn string
@@ -82,6 +92,7 @@ func GetOrHeadFile(w http.ResponseWriter, r *http.Request, fs storage.FS, spaceI
rid, err := storagespace.ParseID(spaceID)
if err != nil {
handleError(w, &sublog, err, "parse ID")
return
}
ref = &provider.Reference{
ResourceId: &rid,
@@ -123,6 +134,10 @@ func GetOrHeadFile(w http.ResponseWriter, r *http.Request, fs storage.FS, spaceI
return true
})
if err != nil {
if _, denied := err.(errtypes.IsPermissionDenied); denied && audited {
id, _ := storagespace.FormatReference(ref)
emitDownload(ctx, emitter, audit.Target{ID: id, Path: ref.GetPath()}, audit.OutcomeDenied, "permission_denied")
}
handleError(w, &sublog, err, "download")
return
}
@@ -252,15 +267,58 @@ func GetOrHeadFile(w http.ResponseWriter, r *http.Request, fs storage.FS, spaceI
w.WriteHeader(code)
if r.Method != "HEAD" {
// a resumed download or a video that is seeked makes many range
// requests, only the one from the start counts
audited = audited && (len(ranges) == 0 || len(ranges) == 1 && ranges[0].Start == 0)
target := audit.Target{
ID: storagespace.FormatResourceID(md.GetId()),
SpaceID: storagespace.FormatStorageID(md.GetId().GetStorageId(), md.GetId().GetSpaceId()),
Name: path.Base(md.GetPath()),
Path: md.GetPath(),
}
if audited {
// the resource info only has the name; a stat by ID has the
// path in the space, like the other file events and the archiver
if info, err := fs.GetMD(ctx, &provider.Reference{ResourceId: md.GetId()}, nil, []string{"path"}); err == nil && info.GetPath() != "" && info.GetPath() != "." {
target.Path = utils.MakeRelativePath(info.GetPath())
}
}
var c int64
c, err = io.CopyN(w, sendContent, sendSize)
if err != nil {
sublog.Error().Err(err).Interface("resourceid", md.Id).Msg("error copying data to response")
if audited {
emitDownload(ctx, emitter, target, audit.OutcomeFailure, "incomplete")
}
return
}
if c != sendSize {
sublog.Error().Int64("copied", c).Int64("size", sendSize).Msg("copied vs size mismatch")
}
if audited {
emitDownload(ctx, emitter, target, audit.OutcomeSuccess, "")
}
}
}
// emitDownload reports a download. It is emitted when the transfer is done,
// not when it is initiated.
func emitDownload(ctx context.Context, emitter audit.Emitter, target audit.Target, outcome audit.Outcome, reason string) {
ev := audit.Event{
Definition: audit.FileDownload,
Outcome: outcome,
Reason: reason,
Target: target,
}
// through a public link the user in the context is the owner of the link,
// the one who downloads is the link
if shareID := audit.PublicShareID(ctx); shareID != "" {
ev.Actor = &audit.Actor{Type: audit.ActorPublicLink, ID: shareID}
}
err := emitter.Emit(ctx, ev)
if err != nil {
appctx.GetLogger(ctx).Error().Err(err).Msg("audit event not emitted")
}
}
+12 -2
View File
@@ -29,6 +29,7 @@ import (
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/opencloud-eu/reva/v3/pkg/store"
"github.com/vmihailenco/msgpack/v5"
"github.com/vmihailenco/msgpack/v5/msgpcode"
microstore "go-micro.dev/v4/store"
)
@@ -135,7 +136,8 @@ type cacheStore struct {
ttl time.Duration
}
// PullFromCache pulls a value from the configured database and table of the underlying store using the given key
// PullFromCache pulls a value from the configured database and table of the underlying store using the given key.
// dest must be a pointer. A nil value (e.g. a nil map that was pushed) counts as not found.
func (cache cacheStore) PullFromCache(key string, dest interface{}) error {
r, err := cache.s.Read(key, microstore.ReadFrom(cache.database, cache.table), microstore.ReadLimit(1))
if err != nil {
@@ -144,8 +146,16 @@ func (cache cacheStore) PullFromCache(key string, dest interface{}) error {
if len(r) == 0 {
return fmt.Errorf("not found")
}
// A nil map or pointer is stored as the msgpack nil. Decoded, it would make the caller's
// value nil, which callers don't expect (a nil map from the file metadata cache, see
// https://github.com/opencloud-eu/reva/issues/1073): read it again from where it comes from.
if len(r[0].Value) == 1 && r[0].Value[0] == msgpcode.Nil {
return fmt.Errorf("not found")
}
return msgpack.Unmarshal(r[0].Value, &dest)
// dest, not &dest: decoding a nil into the pointer wrapped in the interface panics
// ("reflect.Value.Set using unaddressable value")
return msgpack.Unmarshal(r[0].Value, dest)
}
// PushToCache pushes a key and value to the configured database and table of the underlying store
@@ -44,6 +44,7 @@ import (
"github.com/opencloud-eu/reva/v3/pkg/storage/internal/goroutinelock"
"github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/prefixes"
"github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/node"
"github.com/opencloud-eu/reva/v3/pkg/storagespace"
"github.com/opencloud-eu/reva/v3/pkg/utils"
)
@@ -321,6 +322,7 @@ func (tb *Trashbin) RestoreRecycleItem(ctx context.Context, spaceID string, key,
trashRoot := filepath.Join(tb.lu.InternalPath(spaceID, spaceID), lookup.TrashDir)
trashPath := filepath.Clean(filepath.Join(trashRoot, "files", key+".trashitem", relativePath))
tb.setAuditItem(ctx, spaceID, trashRoot, key, relativePath, trashPath)
restorePath := ""
// TODO why can we not use NodeFromResource here? It will use walk path. Do trashed items have a problem with that?
@@ -397,6 +399,7 @@ func (tb *Trashbin) PurgeRecycleItem(ctx context.Context, spaceID, key, relative
trashRoot := filepath.Join(tb.lu.InternalPath(spaceID, spaceID), lookup.TrashDir)
trashPath := filepath.Clean(filepath.Join(trashRoot, "files", key+".trashitem", relativePath))
tb.setAuditItem(ctx, spaceID, trashRoot, key, relativePath, trashPath)
type item struct {
path string
@@ -623,3 +626,39 @@ func (tb *Trashbin) IsEmpty(ctx context.Context, spaceID string) bool {
// if we cannot read the trash, we assume there are no trashed items
return true
}
// setAuditItem tells the events middleware which trashed item a call acts
// on: file or folder, its ID and its name.
func (tb *Trashbin) setAuditItem(ctx context.Context, spaceID, trashRoot, key, relativePath, trashPath string) {
if !storagespace.ContextWantsItem(ctx) {
return
}
fi, err := os.Lstat(trashPath)
if err != nil {
return
}
t := provider.ResourceType_RESOURCE_TYPE_FILE
if fi.IsDir() {
t = provider.ResourceType_RESOURCE_TYPE_CONTAINER
}
var id *provider.ResourceId
if _, nodeID, _, _, err := tb.lu.MetadataBackend().IdentifyPath(ctx, trashPath); err == nil && nodeID != "" {
id = &provider.ResourceId{SpaceId: spaceID, OpaqueId: nodeID}
}
// the info file has the path in the space, without a leading slash
origin, _, err := tb.readInfoFile(trashRoot, key)
if err == nil {
origin = filepath.Join("/", origin, relativePath)
}
name := filepath.Base(relativePath)
if relativePath == "" || relativePath == "." || relativePath == "/" {
name = ""
if origin != "" {
name = filepath.Base(origin)
}
}
storagespace.ContextSetItem(ctx, t, id, name)
if origin != "" {
storagespace.ContextSetItemPath(ctx, origin)
}
}
+12 -1
View File
@@ -26,6 +26,7 @@ import (
"io/fs"
"os"
"path/filepath"
"runtime/debug"
"strings"
"syscall"
"time"
@@ -649,7 +650,17 @@ func (t *Tree) listFolder(ctx context.Context, n *node.Node, forUser bool) ([]*n
// Spawn workers that'll concurrently work the queue
for i := 0; i < numWorkers; i++ {
g.Go(func() error {
g.Go(func() (err error) {
// The workers run in goroutines of their own, out of reach of the recovery of the
// gRPC interceptors: a panic here would end the whole process, as it did in
// https://github.com/opencloud-eu/reva/issues/1073. Fail the listing instead.
defer func() {
if r := recover(); r != nil {
t.log.Error().Str("dir", dir).Interface("panic", r).Str("stack", string(debug.Stack())).Msg("panic while listing a directory")
err = fmt.Errorf("tree: panic while listing %s: %v", dir, r)
}
}()
// switch user if necessary
spaceGID, ok := ctx.Value(decomposedfs.CtxKeySpaceGID).(uint32)
if ok {
@@ -551,6 +551,8 @@ func (fs *Decomposedfs) CreateDir(ctx context.Context, ref *provider.Reference)
if err = fs.tp.CreateDir(ctx, n); err != nil {
return nil, err
}
setAuditItem(ctx, n)
fs.setAuditPath(ctx, n, ref)
return &storage.CreateDirResult{SpaceOwner: spaceOwner, SpaceID: n.SpaceID, ResourceID: &provider.ResourceId{OpaqueId: n.ID, SpaceId: n.SpaceID}}, nil
}
@@ -629,6 +631,8 @@ func (fs *Decomposedfs) Move(ctx context.Context, oldRef, newRef *provider.Refer
if !oldNode.Exists {
return nil, errtypes.NotFound(filepath.Join(oldNode.ParentID, oldNode.Name))
}
setAuditItem(ctx, oldNode)
fs.setAuditPath(ctx, oldNode, oldRef)
orp, err := fs.p.AssemblePermissions(ctx, oldNode)
switch {
@@ -916,6 +920,8 @@ func (fs *Decomposedfs) Delete(ctx context.Context, ref *provider.Reference) (dr
if node.IsProcessing(ctx) {
return nil, errtypes.TooEarly("file is processing")
}
setAuditItem(ctx, node)
fs.setAuditPath(ctx, node, ref)
rp, err := fs.p.AssemblePermissions(ctx, node)
switch {
@@ -1086,6 +1092,9 @@ func (fs *Decomposedfs) SetLock(ctx context.Context, ref *provider.Reference, lo
return nil, errtypes.NotFound(filepath.Join(node.ParentID, node.Name))
}
setAuditItem(ctx, node)
fs.setAuditPath(ctx, node, ref)
rp, err := fs.p.AssemblePermissions(ctx, node)
switch {
case err != nil:
@@ -1155,6 +1164,9 @@ func (fs *Decomposedfs) Unlock(ctx context.Context, ref *provider.Reference, loc
return nil, errtypes.NotFound(filepath.Join(node.ParentID, node.Name))
}
setAuditItem(ctx, node)
fs.setAuditPath(ctx, node, ref)
rp, err := fs.p.AssemblePermissions(ctx, node)
switch {
case err != nil:
@@ -1390,3 +1402,26 @@ func (fs *Decomposedfs) refFromNode(ctx context.Context, n *node.Node, storageId
Path: path,
}, nil
}
// setAuditPath tells the events middleware the path of n in its space when
// the request does not start at the space root, e.g. a request through a
// share, a link or by ID: its path is relative to another node. The permission
// check walks the same parents, so their metadata is cached.
func (fs *Decomposedfs) setAuditPath(ctx context.Context, n *node.Node, ref *provider.Reference) {
if !storagespace.ContextWantsItem(ctx) || utils.IsSpaceRootedReference(ref) {
return
}
if p, err := fs.lu.Path(ctx, n, node.NoCheck); err == nil {
storagespace.ContextSetItemPath(ctx, p)
}
}
// setAuditItem tells the events middleware which item a call acts on. A
// trashed node keeps the ID it had before it was deleted.
func setAuditItem(ctx context.Context, n *node.Node) {
if !storagespace.ContextWantsItem(ctx) {
return
}
id, _, _ := strings.Cut(n.ID, node.TrashIDDelimiter)
storagespace.ContextSetItem(ctx, n.Type(ctx), &provider.ResourceId{SpaceId: n.SpaceID, OpaqueId: id}, n.Name)
}
@@ -170,9 +170,15 @@ func (b HybridBackend) Reload(ctx context.Context, n MetadataNode) (map[string][
}
// getAll reads all attributes of n from storage, like readAll, and caches them.
// If the read fails, it drops the cached attributes of n, so that the next read goes to storage.
func (b HybridBackend) getAll(ctx context.Context, n MetadataNode, skipOffloaded bool) (map[string][]byte, error) {
attribs, err := b.readAll(ctx, n, skipOffloaded)
if err != nil {
// SetMultiple and Remove refresh the cache with getAll after they changed the
// attributes on storage: if that read fails, the cached attributes are outdated
// and would be served until their TTL runs out. The read error is what matters to
// the caller, a failure to drop the entry is left out.
_ = b.metaCache.RemoveMetadata(b.cacheKey(n))
return nil, err
}
if err := b.metaCache.PushToCache(b.cacheKey(n), attribs); err != nil {
@@ -194,25 +200,10 @@ func (b HybridBackend) readAll(ctx context.Context, n MetadataNode, skipOffloade
return attribs, nil
}
var (
xerrs = 0
xerr error
)
// error handling: Count if there are errors while reading all attribs.
// if there were any, return an error.
attribs = make(map[string][]byte, len(attrNames))
path := n.InternalPath()
for _, name := range attrNames {
var val []byte
if val, xerr = xattr.Get(path, name); xerr != nil && !IsAttrUnset(xerr) {
xerrs++
} else {
attribs[name] = val
}
}
if xerrs > 0 {
return nil, errors.Wrap(xerr, "Failed to read all xattrs")
attribs, err = readXattrs(path, attrNames, xattr.Get)
if err != nil {
return nil, err
}
// merge the attributes from the offload file
@@ -238,6 +229,32 @@ func (b HybridBackend) readAll(ctx context.Context, n MetadataNode, skipOffloade
return attribs, nil
}
// readXattrs reads the named attributes of path with get. If any of them can't be read, it
// fails as a whole: its result gets cached, and must not miss attributes, or be nil.
// It used to keep only the error of the last attribute, so a failure followed by a successful
// read returned no error and a nil map, which then got cached,
// https://github.com/opencloud-eu/reva/issues/1073.
func readXattrs(path string, names []string, get func(path, name string) ([]byte, error)) (map[string][]byte, error) {
attribs := make(map[string][]byte, len(names))
failed := 0
var firstErr error
for _, name := range names {
val, err := get(path, name)
if err != nil && !IsAttrUnset(err) {
if failed == 0 {
firstErr = err
}
failed++
continue
}
attribs[name] = val
}
if failed > 0 {
return nil, fmt.Errorf("failed to read %d of %d xattrs, the first: %w", failed, len(names), firstErr)
}
return attribs, nil
}
// Set sets one attribute for the given path
func (b HybridBackend) Set(ctx context.Context, n MetadataNode, key string, val []byte) (err error) {
return b.SetMultiple(ctx, n, map[string][]byte{key: val})
@@ -393,13 +410,17 @@ func (b HybridBackend) offloadMetadata(ctx context.Context, n MetadataNode) erro
}
// remove offloaded attributes from xattrs
for key := range msgpackAttribs {
xerr = xattr.Remove(path, key)
if xerr != nil {
if err := xattr.Remove(path, key); err != nil {
if xerrs == 0 {
// the first one: the last one may have been removed fine, so its nil error
// would have reported success (errors.Wrap(nil, ...) is nil)
xerr = err
}
xerrs++
}
}
if xerrs > 0 {
return errors.Wrap(xerr, "Failed to remove xattrs while offloading")
return fmt.Errorf("failed to remove %d of %d xattrs while offloading, the first: %w", xerrs, len(msgpackAttribs), xerr)
}
return nil
@@ -118,11 +118,11 @@ type Options struct {
// A number of revisions to keep counts the ones within X1 too: "7d, 10" keeps at
// most 10 revisions, unless more than 10 are younger than 7 days.
//
// The age of a revision is the time its content was written, i.e. the modification time
// the file had before it was changed, not the time of that change, which turned the
// content into a revision. A revision created today from content that was unchanged for
// two months is two months old, so e.g. "30d" deletes it right away; combine
// durations with a number of revisions, e.g. "5, 30d", to always keep the newest ones.
// The age of a revision is the time it was created, i.e. when the file was changed and its
// previous content became the revision, not the modification time of that content, which
// the version list shows. A revision created today from content that was unchanged for two
// months is new, so e.g. "30d" keeps it for 30 days. Combine durations with a number of
// revisions, e.g. "5, 30d", to always keep the newest ones.
//
// A duration in days or weeks with an uppercase unit (D, W) is aligned to midnight in the
// server's local time zone: "1d" means the last 24 hours, "1D" since yesterday 00:00,
@@ -134,6 +134,13 @@ type Options struct {
// to revisions posix creates from changes on disk (enable_fs_revisions).
// An invalid value makes the driver fail at startup.
RevisionsCleanupStrategy string `mapstructure:"revisions_cleanup_strategy"`
// RevisionsCleanupStrategyPersonal is the strategy for the personal spaces, in the same
// form as RevisionsCleanupStrategy. Leaving it empty applies RevisionsCleanupStrategy to
// them, "disabled" keeps all their revisions, whatever RevisionsCleanupStrategy says.
RevisionsCleanupStrategyPersonal string `mapstructure:"revisions_cleanup_strategy_personal"`
// RevisionsCleanupStrategyProject is the strategy for the project spaces, like
// RevisionsCleanupStrategyPersonal for the personal spaces.
RevisionsCleanupStrategyProject string `mapstructure:"revisions_cleanup_strategy_project"`
// RevisionsCleanupAsync runs the revision cleanup in the background instead of as part of
// the upload, restore or change on disk that created the new revision, so that those are not
@@ -38,6 +38,7 @@ import (
"github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/prefixes"
"github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/node"
"github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/tree"
"github.com/opencloud-eu/reva/v3/pkg/storagespace"
)
type DecomposedfsTrashbin struct {
@@ -365,6 +366,8 @@ func (tb *DecomposedfsTrashbin) RestoreRecycleItem(ctx context.Context, spaceID
}
return nil, err
}
setAuditItem(ctx, rn)
tb.setAuditOrigin(ctx, spaceID, key, relativePath)
// check permissions of deleted node
rp, err := tb.fs.p.AssembleTrashPermissions(ctx, rn)
@@ -407,6 +410,8 @@ func (tb *DecomposedfsTrashbin) PurgeRecycleItem(ctx context.Context, spaceID, k
}
return err
}
setAuditItem(ctx, rn)
tb.setAuditOrigin(ctx, spaceID, key, relativePath)
// check permissions of deleted node
rp, err := tb.fs.p.AssembleTrashPermissions(ctx, rn)
@@ -472,3 +477,14 @@ func (fs *DecomposedfsTrashbin) IsEmpty(ctx context.Context, spaceID string) boo
// if we cannot read the trash, we assume there are no trashed items
return true
}
// setAuditOrigin tells the events middleware where a trashed item was
// before it was deleted.
func (tb *DecomposedfsTrashbin) setAuditOrigin(ctx context.Context, spaceID, key, relativePath string) {
if !storagespace.ContextWantsItem(ctx) {
return
}
if origin, err := tb.fs.tp.(*tree.Tree).RecycleItemOrigin(ctx, spaceID, key, relativePath); err == nil {
storagespace.ContextSetItemPath(ctx, origin)
}
}
@@ -21,6 +21,7 @@ import (
"github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata"
"github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/node"
"github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup"
"github.com/opencloud-eu/reva/v3/pkg/storagespace"
)
var _ revisioncleanup.OnDemand = (*Decomposedfs)(nil)
@@ -87,15 +88,18 @@ func (fs *Decomposedfs) CleanupRevisionsUnchecked(ctx context.Context, req revis
report = func(revisioncleanup.Result) {}
}
strategy := req.Strategy
if strategy == "" {
strategy = fs.o.RevisionsCleanupStrategy
config := revisioncleanup.PolicyConfigFromOptions(fs.o)
for typ, strategy := range map[string]string{storagespace.TypePersonal: req.StrategyPersonal, storagespace.TypeProject: req.StrategyProject} {
if strings.TrimSpace(strategy) != "" {
config.SpaceTypes[typ] = strategy
}
}
cleaner, err := revisioncleanup.New(strategy)
config.Forced = req.Strategy
policy, err := revisioncleanup.NewPolicy(config)
if err != nil {
return errors.Wrap(err, "invalid revisions cleanup strategy")
}
if !cleaner.Enabled() {
if !policy.Enabled() {
return errors.New("no revisions cleanup strategy configured or given")
}
o := revisioncleanup.RunOptions{Async: revisioncleanup.AsyncOptionsFromOptions(fs.o), DryRun: req.DryRun, Shuffle: req.Shuffle}
@@ -110,7 +114,7 @@ func (fs *Decomposedfs) CleanupRevisionsUnchecked(ctx context.Context, req revis
if err != nil {
return err
}
return revisioncleanup.Run(ctx, fs.lu, w, roots, cleaner, o, report, fs.log)
return revisioncleanup.Run(ctx, fs.lu, w, roots, policy, o, report, fs.log)
}
// errSpaceDisabled is the error for a space that is disabled, i.e. in the trash
@@ -15,6 +15,8 @@ The options are part of the decomposedfs options and therefore apply to all thre
| Option | Default | Meaning |
|---|---|---|
| `revisions_cleanup_strategy` | `""` (disabled) | Which revisions to delete, see below. Empty or `disabled` keeps all revisions. |
| `revisions_cleanup_strategy_personal` | `""` (the default applies) | The strategy for personal spaces. Empty applies `revisions_cleanup_strategy` to them, `disabled` keeps all their revisions, whatever `revisions_cleanup_strategy` says. |
| `revisions_cleanup_strategy_project` | `""` (the default applies) | The strategy for project spaces, like `revisions_cleanup_strategy_personal`. |
| `revisions_cleanup_async` | `true` | Run the cleanup in background workers, so that it doesn't slow down the upload, restore or change that created the new revision. `false` runs it right away. |
| `revisions_cleanup_async_workers` | `0` (automatic) | Number of background workers. Automatic: half the available CPUs (respecting container CPU limits), at least 2. |
| `revisions_cleanup_async_queue_size` | `0` (automatic) | Number of files that can wait for a background cleanup. Automatic: 64 per worker. |
@@ -23,6 +25,10 @@ The options are part of the decomposedfs options and therefore apply to all thre
An invalid value in any of these options makes the storage driver fail at startup.
Which strategy applies to a file depends on its space (see `Policy` in `policy.go`): the strategy of the space's type if it has one, otherwise `revisions_cleanup_strategy`.
Spaces of any other type than `personal` and `project` always get `revisions_cleanup_strategy`.
A cleanup on demand can replace the strategy of a type for its run, or force one strategy on all spaces instead (see `Request` in `ondemand.go`).
## Strategies
A strategy is a comma separated list of up to three parts.
@@ -103,9 +109,9 @@ The cleanup exports Prometheus metrics, all named `reva_revision_cleanup_*`.
| Metric | Type | Meaning |
|---|---|---|
| `reva_revision_cleanup_enabled` | gauge | 1 if a strategy is configured, 0 otherwise |
| `reva_revision_cleanup_revisions_deleted_total` | counter | Deleted revisions |
| `reva_revision_cleanup_bytes_deleted_total` | counter | Total size of the deleted revisions |
| `reva_revision_cleanup_purge_failures_total` | counter | Revisions that could not be deleted, which are retried with the file's next revision, and revisions whose blob could not be deleted afterwards, which is left behind (logged with its blob id) |
| `reva_revision_cleanup_revisions_deleted_total{space_type}` | counter | Deleted revisions |
| `reva_revision_cleanup_bytes_deleted_total{space_type}` | counter | Total size of the deleted revisions |
| `reva_revision_cleanup_purge_failures_total{space_type}` | counter | Revisions that could not be deleted, which are retried with the file's next revision, and revisions whose blob could not be deleted afterwards, which is left behind (logged with its blob id) |
| `reva_revision_cleanup_queue_full_total{outcome}` | counter | Requests that found the queue full, by `outcome`: `blocked` (the writer waited) or `dropped` (cleanup skipped); a writer that waited until the timeout of `block` counts as both |
| `reva_revision_cleanup_queue_length` | gauge | Files waiting for a background cleanup, including writers waiting for room in a full queue |
| `reva_revision_cleanup_queue_capacity` | gauge | Size of the queue |
@@ -114,6 +120,7 @@ The cleanup exports Prometheus metrics, all named `reva_revision_cleanup_*`.
Things to keep in mind:
- **The counters of deleted revisions are by `space_type`**: `personal`, `project`, or `other` for any other type of space (and when the type can't be read), so that the strategies of the space types can be compared, with at most three series each.
- **The queue holds files, not revisions.** A file waits at most once, however many revisions it got in the meantime, and how many of its revisions get deleted is only decided when a worker processes it.
- **One process can have several queues.** The storageprovider and the dataprovider each create their own storage driver, and with it their own cleanup. The queue and worker gauges are the sum over all of them.
Because a sum can hide one queue being full while another one is empty, `queue_full_total` counts every request that found its queue full.
@@ -123,9 +130,9 @@ Things to keep in mind:
Example queries:
```promql
# revisions deleted per second, and storage freed per second
rate(reva_revision_cleanup_revisions_deleted_total[5m])
rate(reva_revision_cleanup_bytes_deleted_total[5m])
# revisions deleted per second, and storage freed per second, by space type
sum by (space_type) (rate(reva_revision_cleanup_revisions_deleted_total[5m]))
sum by (space_type) (rate(reva_revision_cleanup_bytes_deleted_total[5m]))
# how full the queues are (0..1, can exceed 1 while writers wait for room)
reva_revision_cleanup_queue_length / reva_revision_cleanup_queue_capacity
@@ -137,7 +144,7 @@ sum by (outcome) (rate(reva_revision_cleanup_queue_full_total[5m]))
reva_revision_cleanup_running / reva_revision_cleanup_workers
# failed deletions, worth an alert
increase(reva_revision_cleanup_purge_failures_total[1h]) > 0
sum(increase(reva_revision_cleanup_purge_failures_total[1h])) > 0
```
## Logging
@@ -322,6 +322,8 @@ func (c *Cleaner) run(ctx context.Context, lu node.PathLookup, rs RevisionStore,
return result
}
defer func() { _ = unscope() }()
// for the counters of the deleted revisions, read in the group of the space like everything else
spaceType := spaceTypeLabel(ctx, n)
// The blobs of the purged revisions are deleted once the node lock is released (this defer
// runs after the one releasing it): their revisions are gone by then, so nothing refers to
@@ -343,12 +345,12 @@ func (c *Cleaner) run(ctx context.Context, lu node.PathLookup, rs RevisionStore,
// left alone (as CommitUpload does for the revisions it removes).
log.Warn().Str("revision", b.key).Str("blobid", b.blobID).Msg("revision cleanup: not deleting the blob of a purged revision, the file still uses it")
// the revision is deleted all the same, but it freed no space
RevisionsDeleted.Inc()
RevisionsDeleted.WithLabelValues(spaceType).Inc()
continue
}
if err := deleteBlob(rs, n.SpaceID, b.blobID); err != nil {
// the revision is gone, but not its blob: that's a failure, not a deletion
PurgeFailures.Inc()
PurgeFailures.WithLabelValues(spaceType).Inc()
log.Error().Err(err).Str("revision", b.key).Str("blobid", b.blobID).Msg("revision cleanup: could not delete the blob of a purged revision")
for i := range result.Revisions {
if result.Revisions[i].Key == b.key {
@@ -357,8 +359,8 @@ func (c *Cleaner) run(ctx context.Context, lu node.PathLookup, rs RevisionStore,
}
continue
}
RevisionsDeleted.Inc()
BytesDeleted.Add(float64(b.size))
RevisionsDeleted.WithLabelValues(spaceType).Inc()
BytesDeleted.WithLabelValues(spaceType).Add(float64(b.size))
}
}()
@@ -449,7 +451,7 @@ func (c *Cleaner) run(ctx context.Context, lu node.PathLookup, rs RevisionStore,
}
blobID, err := removeRevisionUnchecked(ctx, n, rev.Key())
if err != nil {
PurgeFailures.Inc()
PurgeFailures.WithLabelValues(spaceType).Inc()
purgeErrs[rev.Key()] = err
return fmt.Errorf("could not purge revision %q: %w", rev.Key(), err)
}
@@ -4,8 +4,14 @@
package revisioncleanup
import (
"context"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/prefixes"
"github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/node"
"github.com/opencloud-eu/reva/v3/pkg/storagespace"
)
// Prometheus metrics of the revision cleanup, e.g. for Grafana dashboards.
@@ -19,24 +25,27 @@ import (
// request that found its queue full, which is the most direct sign that the number of workers
// or the queue size is too small.
var (
// RevisionsDeleted counts the revisions deleted by the cleanup.
RevisionsDeleted = promauto.NewCounter(prometheus.CounterOpts{
// RevisionsDeleted counts the revisions deleted by the cleanup, by the type of their space,
// see spaceTypeLabel.
RevisionsDeleted = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "reva_revision_cleanup_revisions_deleted_total",
Help: "Number of old file revisions deleted by the revision cleanup",
})
Help: "Number of old file revisions deleted by the revision cleanup, by space type (personal, project or other)",
}, []string{spaceTypeLabelName})
// BytesDeleted counts the size of the revisions deleted by the cleanup.
BytesDeleted = promauto.NewCounter(prometheus.CounterOpts{
// BytesDeleted counts the size of the revisions deleted by the cleanup, by the type of their
// space, see spaceTypeLabel.
BytesDeleted = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "reva_revision_cleanup_bytes_deleted_total",
Help: "Total size in bytes of the old file revisions deleted by the revision cleanup",
})
Help: "Total size in bytes of the old file revisions deleted by the revision cleanup, by space type (personal, project or other)",
}, []string{spaceTypeLabelName})
// PurgeFailures counts the revisions that could not be deleted. They are retried by the
// next cleanup of their node, i.e. when the node gets its next revision.
PurgeFailures = promauto.NewCounter(prometheus.CounterOpts{
// PurgeFailures counts the revisions that could not be deleted, by the type of their space,
// see spaceTypeLabel. They are retried by the next cleanup of their node, i.e. when the
// node gets its next revision.
PurgeFailures = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "reva_revision_cleanup_purge_failures_total",
Help: "Number of old file revisions the revision cleanup failed to delete, completely or only their blob",
})
Help: "Number of old file revisions the revision cleanup failed to delete, completely or only their blob, by space type (personal, project or other)",
}, []string{spaceTypeLabelName})
// QueueFull counts the cleanup requests that found the queue full, by outcome: "blocked"
// (the caller waited for room, queue full policy "block") or "dropped" (the cleanup was
@@ -88,6 +97,32 @@ const (
queueFullDropped = "dropped"
)
const (
// the label of the counters of deleted revisions, see spaceTypeLabel
spaceTypeLabelName = "space_type"
// the value of that label for the spaces of any other type than personal and project
spaceTypeOther = "other"
)
// spaceTypeLabel returns the value of the space_type label for the revisions of n: the type of
// its space if that is personal or project, otherwise "other", also when the type can't be
// read. So the counters have at most three series each, whatever types of spaces there are.
func spaceTypeLabel(ctx context.Context, n *node.Node) string {
if n.SpaceRoot == nil {
return spaceTypeOther
}
// It is called once per cleanup of a file, and reads nothing from disk then: the space root
// of a node read with node.ReadNode has all its attributes cached already, as ReadNode reads
// its name.
switch typ, err := n.SpaceRoot.XattrString(ctx, prefixes.SpaceTypeAttr); {
case err != nil:
return spaceTypeOther
case typ == storagespace.TypePersonal, typ == storagespace.TypeProject:
return typ
}
return spaceTypeOther
}
// serviceMetrics are the metrics a Service updates about itself: its configuration, its queue
// and its workers.
type serviceMetrics struct {
@@ -9,6 +9,7 @@ import (
"fmt"
"math/rand/v2"
"path"
"strings"
"sync"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
@@ -20,7 +21,7 @@ import (
// Request describes an on-demand cleanup of revisions, e.g. by a command line tool, as opposed
// to the cleanup that runs whenever a file gets a new revision.
//
// The strategy and the AsyncOptions default to the configuration of the storage driver, and
// The strategies and the AsyncOptions default to the configuration of the storage driver, and
// can be overridden for this run. Without AsyncOptions of its own, though, a run waits for
// room in a full queue for as long as it takes (QueueFullBlock without a timeout), whatever
// the queue full policy of the storage driver: a run queues the files as fast as it finds
@@ -38,9 +39,14 @@ type Request struct {
// resolves it to the space and the path within it.
FSPath string
// Strategy overrides the configured revisions cleanup strategy for this run, see
// revisions.NewRevisionCleanupStrategy.
// Strategy is forced on all spaces of this run, instead of the configured strategies, see
// PolicyConfig.Forced and revisions.NewRevisionCleanupStrategy.
Strategy string
// StrategyPersonal and StrategyProject replace the configured strategy of the personal
// and the project spaces for this run, see PolicyConfig.SpaceTypes. Empty keeps the
// configured one. They can't be combined with Strategy, which would override them.
StrategyPersonal string
StrategyProject string
// Async overrides the configured AsyncOptions for this run. Without it, the configured
// ones are used, but with QueueFullBlock and no timeout.
Async *AsyncOptions
@@ -54,9 +60,12 @@ type Request struct {
Shuffle bool
}
// Validate checks the scope of the request.
// Validate checks the scope of the request, and that it doesn't combine a forced strategy with
// strategies per space type.
func (r Request) Validate() error {
switch {
case strings.TrimSpace(r.Strategy) != "" && (strings.TrimSpace(r.StrategyPersonal) != "" || strings.TrimSpace(r.StrategyProject) != ""):
return errors.New("a strategy for all spaces can't be combined with strategies per space type")
case r.FSPath != "" && (r.All || len(r.SpaceIDs) > 0 || r.Path != ""):
return errors.New("a path on disk can't be combined with spaces or a path within a space")
case r.FSPath != "":
@@ -114,11 +123,11 @@ type RunOptions struct {
}
// Run cleans up the revisions of the given roots, files or folders (recursively, e.g. space roots),
// with the given Cleaner and RunOptions, and hands the Result of every file to report, one at a
// with the given strategies and RunOptions, and hands the Result of every file to report, one at a
// time. It is the common implementation of OnDemand.CleanupRevisionsUnchecked for the storage
// drivers.
//
// It uses a Service of its own, independent of the storage driver's, so that the Cleaner and
// It uses a Service of its own, independent of the storage driver's, so that the Policy and
// the AsyncOptions of the run apply: files are queued as they are found, while the workers
// already clean up, and Run waits for all cleanups before it returns. Files dropped by a full
// queue (queue full policy "drop") are reported as skipped. That Service leaves the metrics
@@ -131,8 +140,8 @@ type RunOptions struct {
//
// It checks no permissions: the Walker lists folders without them, and neither do the
// cleanups.
func Run(ctx context.Context, lu node.PathLookup, w Walker, roots []*node.Node, cleaner *Cleaner, o RunOptions, report func(Result), log *zerolog.Logger) error {
if !cleaner.Enabled() {
func Run(ctx context.Context, lu node.PathLookup, w Walker, roots []*node.Node, strategies *Policy, o RunOptions, report func(Result), log *zerolog.Logger) error {
if !strategies.Enabled() {
return errors.New("no revisions cleanup strategy configured or given")
}
if report == nil {
@@ -168,7 +177,7 @@ func Run(ctx context.Context, lu node.PathLookup, w Walker, roots []*node.Node,
paths[key] = &queuedPath{path: path, count: 1}
}
s, err := newService(cleaner, lu, w, o.Async, log, true, o.DryRun, serialized)
s, err := newService(strategies, lu, w, o.Async, log, true, o.DryRun, serialized)
if err != nil {
return err
}
@@ -0,0 +1,184 @@
// Copyright 2026 OpenCloud GmbH <mail@opencloud.eu>
// SPDX-License-Identifier: Apache-2.0
package revisioncleanup
import (
"context"
"errors"
"fmt"
"maps"
"slices"
"strings"
"github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/prefixes"
"github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/node"
"github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/options"
"github.com/opencloud-eu/reva/v3/pkg/storagespace"
)
// PolicyConfig holds the strategy specifications a Policy is made of, each as understood by New:
// empty means that the next, less specific one applies, "disabled" that no revisions are deleted.
type PolicyConfig struct {
// Default is the strategy of the spaces that nothing more specific applies to.
Default string
// SpaceTypes are the strategies of the spaces of a type, by type, e.g.
// storagespace.TypePersonal. An empty strategy, like a missing type, leaves the spaces of
// that type to Default; "disabled" keeps all their revisions, whatever Default says.
SpaceTypes map[string]string
// Forced applies to all spaces, whatever the other settings say, e.g. the strategy given
// to a command for a single run.
Forced string
}
// PolicyConfigFromOptions returns the PolicyConfig configured in the driver options: the
// RevisionsCleanupStrategy* settings. It never has a Forced strategy.
func PolicyConfigFromOptions(o *options.Options) PolicyConfig {
return PolicyConfig{
Default: o.RevisionsCleanupStrategy,
SpaceTypes: map[string]string{
storagespace.TypePersonal: o.RevisionsCleanupStrategyPersonal,
storagespace.TypeProject: o.RevisionsCleanupStrategyProject,
},
}
}
// StrategySource tells which setting of a Policy the strategy of a file came from.
type StrategySource string
const (
// SourceForced is the forced strategy, see PolicyConfig.Forced.
SourceForced StrategySource = "forced"
// SourceSpaceType is the strategy of the type of the file's space, see
// PolicyConfig.SpaceTypes.
SourceSpaceType StrategySource = "space type"
// SourceDefault is the default strategy, see PolicyConfig.Default.
SourceDefault StrategySource = "default"
)
// Policy decides which strategy, as a Cleaner, applies to a file. Its settings are layered, the
// most specific first, and the first one that is set applies:
//
// 1. the forced strategy (PolicyConfig.Forced)
// 2. the strategy of the space's type (PolicyConfig.SpaceTypes)
// 3. the default (PolicyConfig.Default)
//
// It decides by the file, which knows its space root, so that more layers can be added: for the
// settings of a space itself, from an attribute of its root, between 1 and 2, and for rules by
// the type or the size of the file.
//
// A Policy is created once, with all its strategies parsed, and can be used by many goroutines
// at the same time. A nil *Policy behaves like one without any strategy, as a safeguard.
type Policy struct {
forced *Cleaner // nil without a forced strategy
def *Cleaner
// only the types with a strategy of their own
spaceTypes map[string]*Cleaner
// the settings, without the empty ones, see String
config PolicyConfig
}
// NewPolicy creates a Policy from its settings. It returns an error for an invalid strategy,
// naming the setting it belongs to.
func NewPolicy(c PolicyConfig) (*Policy, error) {
p := &Policy{spaceTypes: map[string]*Cleaner{}}
var err error
if p.def, err = New(c.Default); err != nil {
return nil, fmt.Errorf("invalid default strategy: %w", err)
}
p.config.Default = p.def.config
for typ, spec := range c.SpaceTypes {
if strings.TrimSpace(spec) == "" {
continue
}
if p.spaceTypes[typ], err = New(spec); err != nil {
return nil, fmt.Errorf("invalid strategy for %s spaces: %w", typ, err)
}
if p.config.SpaceTypes == nil {
p.config.SpaceTypes = map[string]string{}
}
p.config.SpaceTypes[typ] = p.spaceTypes[typ].config
}
if strings.TrimSpace(c.Forced) != "" {
if p.forced, err = New(c.Forced); err != nil {
return nil, fmt.Errorf("invalid forced strategy: %w", err)
}
p.config.Forced = p.forced.config
}
return p, nil
}
// Enabled tells whether p may delete revisions in any space, i.e. whether any of its strategies
// is enabled; with a forced strategy, only that one counts. It is false for a nil Policy.
func (p *Policy) Enabled() bool {
if p == nil {
return false
}
if p.forced != nil {
return p.forced.Enabled()
}
if p.def.Enabled() {
return true
}
for _, c := range p.spaceTypes {
if c.Enabled() {
return true
}
}
return false
}
// CleanerFor returns the Cleaner for the file n, and which setting its strategy came from. The
// Cleaner may be disabled, e.g. for a file in a space whose type has the strategy "disabled":
// none of its revisions are deleted then.
//
// It reads the type of the space from the space root of n only when there are strategies per
// type. It returns an error if that fails, or if n or its space root is unknown; the caller must
// not delete anything then, as it doesn't know the strategy that applies.
func (p *Policy) CleanerFor(ctx context.Context, n *node.Node) (*Cleaner, StrategySource, error) {
if p == nil {
return nil, SourceDefault, nil
}
if p.forced != nil {
return p.forced, SourceForced, nil
}
if len(p.spaceTypes) == 0 {
return p.def, SourceDefault, nil
}
if n == nil || n.SpaceRoot == nil {
return nil, "", errors.New("the space root of the file is unknown")
}
// This reads nothing from disk for a node read with node.ReadNode: its space root has all
// its attributes cached already, as ReadNode reads its name.
typ, err := n.SpaceRoot.XattrString(ctx, prefixes.SpaceTypeAttr)
if err != nil {
return nil, "", fmt.Errorf("could not read the type of the space: %w", err)
}
c, source := p.cleanerForSpaceType(typ)
return c, source, nil
}
// cleanerForSpaceType is CleanerFor without the forced strategy, for a space of the given type.
func (p *Policy) cleanerForSpaceType(typ string) (*Cleaner, StrategySource) {
if c, ok := p.spaceTypes[typ]; ok {
return c, SourceSpaceType
}
return p.def, SourceDefault
}
// String describes the settings of p for the log, with the types in a fixed order, e.g.
// "default: 30d; personal: 7d, 5; project: disabled". Two Policies with the same settings
// have the same String.
func (p *Policy) String() string {
if p == nil {
return "disabled"
}
parts := []string{"default: " + p.config.Default}
for _, typ := range slices.Sorted(maps.Keys(p.config.SpaceTypes)) {
parts = append(parts, typ+": "+p.config.SpaceTypes[typ])
}
if p.config.Forced != "" {
parts = append(parts, "forced: "+p.config.Forced)
}
return strings.Join(parts, "; ")
}
@@ -44,6 +44,11 @@ type Result struct {
Path string
// DryRun is set when nothing was deleted, only decided.
DryRun bool
// Strategy is the strategy the node was cleaned up with, and StrategySource the setting of
// the Policy it came from. Both are empty when the cleanup failed before the strategy was
// chosen, or when it didn't run because of the node, e.g. as it no longer exists.
Strategy string
StrategySource StrategySource
// Skipped explains why the node was not cleaned up, e.g. because an upload to it is still
// being processed. Revisions is empty then.
Skipped string
@@ -101,9 +101,10 @@ func (o AsyncOptions) resolve() (workers int, queueSize int, policy QueueFullPol
// Service is the revision cleanup of a storage driver. Callers report that a new revision
// was created (HandleRevisionCreated), and the Service decides whether, when and how the
// old revisions are cleaned up; callers don't need to know whether that happens right away
// or in background workers (see AsyncOptions). It binds a Cleaner to the driver's lookup
// and tree, so that callers only need to name the node.
// A disabled Service, created without a strategy, never cleans up anything; see Enabled.
// or in background workers (see AsyncOptions). It binds a Policy to the driver's lookup
// and tree, so that callers only need to name the node; the Policy chooses the strategy of
// each node by its space.
// A disabled Service, created without any strategy, never cleans up anything; see Enabled.
// A nil *Service behaves the same, as a safeguard, but NewService never returns one.
//
// In asynchronous mode, the cleanup runs in background workers fed by a bounded queue, so
@@ -119,10 +120,11 @@ func (o AsyncOptions) resolve() (workers int, queueSize int, policy QueueFullPol
// A node therefore never occupies more than
// one worker, and a single busy file can't keep the workers from the others.
type Service struct {
cleaner *Cleaner
lu node.PathLookup
rs RevisionStore
log *zerolog.Logger
// the strategies, see Policy; not to be confused with policy, the QueueFullPolicy
strategies *Policy
lu node.PathLookup
rs RevisionStore
log *zerolog.Logger
// set for the Service of an on-demand Run: only decide, don't delete, and hand the Result
// of every cleanup to report
@@ -179,7 +181,8 @@ func (r *request) key() string {
}
// NewServiceFromOptions returns the Service of a storage driver from its options: the cleanup
// strategy (RevisionsCleanupStrategy) and the RevisionsCleanupAsync* settings.
// strategies (RevisionsCleanupStrategy*, see PolicyConfigFromOptions) and the
// RevisionsCleanupAsync* settings.
// It returns a disabled Service when no strategy is configured, and an error for invalid
// settings.
//
@@ -188,12 +191,12 @@ func (r *request) key() string {
// see Service.Shutdown.
func NewServiceFromOptions(o *options.Options, lu node.PathLookup, rs RevisionStore, log *zerolog.Logger) (*Service, error) {
async := AsyncOptionsFromOptions(o)
return sharedService(o.Root, o.RevisionsCleanupStrategy, async, func() (*Service, error) {
cleaner, err := New(o.RevisionsCleanupStrategy)
if err != nil {
return nil, err
}
return NewService(cleaner, lu, rs, async, log)
policy, err := NewPolicy(PolicyConfigFromOptions(o))
if err != nil {
return nil, err
}
return sharedService(o.Root, policy.String(), async, func() (*Service, error) {
return NewService(policy, lu, rs, async, log)
})
}
@@ -209,19 +212,19 @@ func AsyncOptionsFromOptions(o *options.Options) AsyncOptions {
}
}
// NewService creates a Service that cleans up with the given Cleaner, and starts its
// workers if opts.Enabled. With a disabled (or nil) Cleaner, it returns a disabled Service,
// which starts no workers and never cleans up anything.
// NewService creates a Service that cleans up with the given strategies, and
// starts its workers if opts.Enabled. With a Policy that has no enabled strategy (or a nil
// one), it returns a disabled Service, which starts no workers and never cleans up anything.
// The options are validated in any case, so that invalid settings are reported even while
// the cleanup is disabled.
func NewService(cleaner *Cleaner, lu node.PathLookup, rs RevisionStore, opts AsyncOptions, log *zerolog.Logger) (*Service, error) {
return newService(cleaner, lu, rs, opts, log, false, false, nil)
func NewService(strategies *Policy, lu node.PathLookup, rs RevisionStore, opts AsyncOptions, log *zerolog.Logger) (*Service, error) {
return newService(strategies, lu, rs, opts, log, false, false, nil)
}
// newService creates a Service, see NewService; onDemand creates the Service of an on-demand
// Run, with dryRun it only decides without deleting, and report, if not nil, gets the Result
// of every cleanup.
func newService(cleaner *Cleaner, lu node.PathLookup, rs RevisionStore, opts AsyncOptions, log *zerolog.Logger, onDemand, dryRun bool, report func(Result)) (*Service, error) {
func newService(strategies *Policy, lu node.PathLookup, rs RevisionStore, opts AsyncOptions, log *zerolog.Logger, onDemand, dryRun bool, report func(Result)) (*Service, error) {
workers, queueSize, policy, err := opts.resolve()
if err != nil {
return nil, err
@@ -229,10 +232,10 @@ func newService(cleaner *Cleaner, lu node.PathLookup, rs RevisionStore, opts Asy
if log == nil {
log = &zerolog.Logger{}
}
if !cleaner.Enabled() {
return &Service{cleaner: cleaner, log: log}, nil
if !strategies.Enabled() {
return &Service{strategies: strategies, log: log}, nil
}
s := &Service{cleaner: cleaner, lu: lu, rs: rs, log: log, onDemand: onDemand, dryRun: dryRun, report: report}
s := &Service{strategies: strategies, lu: lu, rs: rs, log: log, onDemand: onDemand, dryRun: dryRun, report: report}
if onDemand {
s.metrics = unregisteredMetrics()
}
@@ -240,17 +243,20 @@ func newService(cleaner *Cleaner, lu node.PathLookup, rs RevisionStore, opts Asy
if opts.Enabled {
s.queueFullTimeout = opts.QueueFullTimeout
s.startWorkers(workers, queueSize, policy, s.cleanupNode)
log.Info().Str("config", cleaner.config).Int("workers", workers).Int("queuesize", queueSize).
log.Info().Str("config", strategies.String()).Int("workers", workers).Int("queuesize", queueSize).
Str("queuefull", string(policy)).Dur("queuefulltimeout", opts.QueueFullTimeout).
Msg("revision cleanup: running in the background")
}
return s, nil
}
// Enabled tells whether s cleans up anything, i.e. whether its Cleaner has a strategy.
// Enabled tells whether s cleans up anything, i.e. whether its Policy has an enabled strategy.
// It may still clean up nothing in some spaces, e.g. in those whose type has the strategy
// "disabled": their nodes are queued all the same, the strategy of a node is only chosen when
// it is cleaned up, as that reads the node anyway.
// It is false for a disabled Service, and for a nil one.
func (s *Service) Enabled() bool {
return s != nil && s.cleaner.Enabled()
return s != nil && s.strategies.Enabled()
}
// startWorkers switches the Service to asynchronous mode. process does the work for one
@@ -566,10 +572,24 @@ func (s *Service) cleanupNode(ctx context.Context, spaceID, nodeID string) {
s.clean(ctx, n)
}
// clean runs the cleanup of n, or only decides about it in a dry run, and reports the Result.
// clean runs the cleanup of n with the strategy the Policy chooses for its space, or only
// decides about it in a dry run, and reports the Result.
func (s *Service) clean(ctx context.Context, n *node.Node) {
cleaner, source, err := s.strategies.CleanerFor(ctx, n)
if err != nil {
// without knowing the strategy, nothing may be deleted
appctx.GetLogger(ctx).Error().Err(err).Str("spaceid", n.SpaceID).Str("nodeid", n.ID).Msg("revision cleanup: could not choose the strategy")
s.reportResult(Result{SpaceID: n.SpaceID, NodeID: n.ID, DryRun: s.dryRun, Err: fmt.Errorf("could not choose the strategy: %w", err)})
return
}
if !cleaner.Enabled() {
s.reportResult(Result{SpaceID: n.SpaceID, NodeID: n.ID, DryRun: s.dryRun, Strategy: "disabled", StrategySource: source,
Skipped: "the revision cleanup is disabled for this space"})
return
}
// the details of the revisions only for someone who reads them
result := s.cleaner.run(ctx, s.lu, s.rs, n, s.dryRun, s.report != nil)
result := cleaner.run(ctx, s.lu, s.rs, n, s.dryRun, s.report != nil)
result.Strategy, result.StrategySource = cleaner.config, source
s.reportResult(result)
}
@@ -27,24 +27,24 @@ var shared = struct {
// share is the bookkeeping of a Service shared by the instances of a storage, see shared.
type share struct {
root string
refs int // the instances that haven't shut the Service down yet
strategy string
async AsyncOptions
root string
refs int // the instances that haven't shut the Service down yet
policy string // the settings of the Policy, see Policy.String
async AsyncOptions
}
// sharedService returns the Service shared by the instances of the storage at root, creating it
// with create for the first one. The instances must agree on the strategy and the AsyncOptions:
// a storage set up twice with different settings would otherwise be cleaned up with the
// settings of whichever instance happened to come first.
func sharedService(root, strategy string, async AsyncOptions, create func() (*Service, error)) (*Service, error) {
// with create for the first one. The instances must agree on the strategies (policy, see
// Policy.String) and the AsyncOptions: a storage set up twice with different settings would
// otherwise be cleaned up with the settings of whichever instance happened to come first.
func sharedService(root, policy string, async AsyncOptions, create func() (*Service, error)) (*Service, error) {
root = filepath.Clean(root)
shared.Lock()
defer shared.Unlock()
if s, ok := shared.byRoot[root]; ok {
if s.share.strategy != strategy || s.share.async != async {
return nil, fmt.Errorf("the storage at %q is set up more than once in this process with different revision cleanup settings: strategy %q and %+v, then strategy %q and %+v",
root, s.share.strategy, s.share.async, strategy, async)
if s.share.policy != policy || s.share.async != async {
return nil, fmt.Errorf("the storage at %q is set up more than once in this process with different revision cleanup settings: strategies %q and %+v, then strategies %q and %+v",
root, s.share.policy, s.share.async, policy, async)
}
s.share.refs++
return s, nil
@@ -53,7 +53,7 @@ func sharedService(root, strategy string, async AsyncOptions, create func() (*Se
if err != nil {
return nil, err
}
s.share = &share{root: root, refs: 1, strategy: strategy, async: async}
s.share = &share{root: root, refs: 1, policy: policy, async: async}
shared.byRoot[root] = s
return s, nil
}
@@ -133,6 +133,8 @@ func (fs *Decomposedfs) RestoreRevision(ctx context.Context, ref *provider.Refer
err = errtypes.NotFound(filepath.Join(n.ParentID, n.Name))
return nil, err
}
setAuditItem(ctx, n)
fs.setAuditPath(ctx, n, ref)
rp, err := fs.p.AssemblePermissions(ctx, n)
switch {
@@ -698,6 +698,7 @@ func (fs *Decomposedfs) UpdateStorageSpace(ctx context.Context, req *provider.Up
Status: &v1beta11.Status{Code: v1beta11.Code_CODE_NOT_FOUND},
}, nil
}
setAuditSpace(ctx, spaceNode)
spaceType, err := spaceNode.SpaceRoot.XattrString(ctx, prefixes.SpaceTypeAttr)
if err != nil {
@@ -820,6 +821,7 @@ func (fs *Decomposedfs) DeleteStorageSpace(ctx context.Context, req *provider.De
if !n.Exists {
return nil, errtypes.NotFound(spaceID)
}
setAuditSpace(ctx, n)
st, err := n.SpaceRoot.XattrString(ctx, prefixes.SpaceTypeAttr)
if err != nil {
@@ -1390,3 +1392,13 @@ func canDeleteSpace(ctx context.Context, spaceID string, typ string, purge bool,
return errtypes.PermissionDenied(fmt.Sprintf("user is not allowed to delete space %s", n.GetID()))
}
// setAuditSpace tells the events middleware the name of the space a call acts
// on, before it is changed.
func setAuditSpace(ctx context.Context, n *node.Node) {
if !storagespace.ContextWantsItem(ctx) {
return
}
name, _ := n.SpaceRoot.XattrString(ctx, prefixes.SpaceNameAttr)
storagespace.ContextSetItem(ctx, provider.ResourceType_RESOURCE_TYPE_CONTAINER, &provider.ResourceId{SpaceId: n.SpaceID, OpaqueId: n.SpaceID}, name)
}
@@ -913,6 +913,13 @@ var nodeIDRegep = regexp.MustCompile(`.*/nodes/([^.]*).*`)
var nodeFullIDRegep = regexp.MustCompile(`.*/nodes/(.*)`)
// TODO refactor the returned params into Node properties? would make all the path transformations go away...
// RecycleItemOrigin returns the path in the space a trashed item had before
// it was deleted.
func (t *Tree) RecycleItemOrigin(ctx context.Context, spaceID, key, path string) (string, error) {
_, _, origin, err := t.readRecycleItem(ctx, spaceID, key, path)
return origin, err
}
func (t *Tree) readRecycleItem(ctx context.Context, spaceID, key, path string) (recycleNode *node.Node, trashItem string, origin string, err error) {
_, span := tracer.Start(ctx, "readRecycleItem")
defer span.End()
@@ -953,6 +960,8 @@ func (t *Tree) readRecycleItem(ctx context.Context, spaceID, key, path string) (
var attrBytes []byte
typeInt, err := attrs.Int64(prefixes.TypeAttr)
// the node is not at its usual path, so Type() can't read it later
recycleNode.SetType(provider.ResourceType(typeInt))
if provider.ResourceType(typeInt) == provider.ResourceType_RESOURCE_TYPE_FILE {
// lookup blobID in extended attributes
recycleNode.BlobID = attrs.String(prefixes.BlobIDAttr)
+43
View File
@@ -22,6 +22,8 @@ import (
"context"
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/opencloud-eu/reva/v3/pkg/storage"
)
@@ -32,6 +34,7 @@ const (
moveResultSlotKey
deleteResultSlotKey
deleteStorageSpaceResultSlotKey
itemSlotKey
)
// --- space owner ---
@@ -170,3 +173,43 @@ func ContextGetDeleteStorageSpaceResult(ctx context.Context) *storage.DeleteStor
}
return nil
}
// --- item ---
// ItemSlot receives the item a storage call acts on, so the audit events can
// tell files and folders apart. ID and Name identify the item when the driver
// knows them; ID may lack the storage ID. Path is the path in the space, set
// where the request has no path, e.g. for trashed items.
type ItemSlot struct {
Type provider.ResourceType
ID *provider.ResourceId
Name string
Path string
}
// ContextRegisterItemSlot stores an empty slot in ctx so the storage driver can fill it.
func ContextRegisterItemSlot(ctx context.Context, slot *ItemSlot) context.Context {
return context.WithValue(ctx, itemSlotKey, slot)
}
// ContextWantsItem reports whether a slot is registered in ctx, so a driver
// only looks up what the slot needs when someone reads it.
func ContextWantsItem(ctx context.Context) bool {
_, ok := ctx.Value(itemSlotKey).(*ItemSlot)
return ok
}
// ContextSetItemPath sets the path of the item in the space.
func ContextSetItemPath(ctx context.Context, p string) {
if slot, ok := ctx.Value(itemSlotKey).(*ItemSlot); ok {
slot.Path = p
}
}
// ContextSetItem fills the slot registered in ctx with the type, ID and name
// of the item.
func ContextSetItem(ctx context.Context, t provider.ResourceType, id *provider.ResourceId, name string) {
if slot, ok := ctx.Value(itemSlotKey).(*ItemSlot); ok {
slot.Type, slot.ID, slot.Name = t, id, name
}
}
@@ -32,6 +32,17 @@ const (
_storageIDDelimiter string = "$"
)
// The types of the spaces that hold files, see provider.StorageSpace.SpaceType. Other types, e.g.
// "mountpoint" or "virtual", are views onto files in such spaces, which the providers of shares
// and public links make up.
const (
// TypePersonal is the type of the personal space of a user.
TypePersonal = "personal"
// TypeProject is the type of a space that space managers create, e.g. for a team or a
// project, and share with its members.
TypeProject = "project"
)
var (
// ErrInvalidSpaceReference signals that the space reference is invalid.
ErrInvalidSpaceReference = errors.New("invalid storage space reference")
+3
View File
@@ -17,6 +17,7 @@ import (
tusd "github.com/tus/tusd/v2/pkg/handler"
"github.com/opencloud-eu/reva/v3/pkg/appctx"
"github.com/opencloud-eu/reva/v3/pkg/audit"
ctxpkg "github.com/opencloud-eu/reva/v3/pkg/ctx"
"github.com/opencloud-eu/reva/v3/pkg/errtypes"
"github.com/opencloud-eu/reva/v3/pkg/events"
@@ -179,6 +180,8 @@ func (c *coordinator) populateSession(ctx context.Context, session Session, t *u
// The ctx is gone by the time the bytes arrive, so record the actor now.
session.SetExecutant(ctxpkg.ContextMustGetUser(ctx))
rc, _ := audit.ContextGetRequest(ctx)
session.SetAuditOrigin(rc, audit.PublicShareID(ctx))
lockID, _ := ctxpkg.ContextGetLockID(ctx)
session.SetMetadata("lockid", lockID)
initiatorID, _ := ctxpkg.ContextGetInitiator(ctx)
+20
View File
@@ -25,6 +25,7 @@ import (
tusd "github.com/tus/tusd/v2/pkg/handler"
"github.com/opencloud-eu/reva/v3/pkg/appctx"
"github.com/opencloud-eu/reva/v3/pkg/audit"
ctxpkg "github.com/opencloud-eu/reva/v3/pkg/ctx"
"github.com/opencloud-eu/reva/v3/pkg/errtypes"
"github.com/opencloud-eu/reva/v3/pkg/storage"
@@ -68,6 +69,7 @@ type Session interface {
Chunk() string
BinPath() string
ExecutantUser() *userpb.User
AuditOrigin() (audit.RequestContext, string)
ProviderID() string
SpaceID() string
NodeID() string
@@ -97,6 +99,7 @@ type Session interface {
SetSize(size int64)
SetSizeIsDeferred(value bool)
SetExecutant(u *userpb.User)
SetAuditOrigin(rc audit.RequestContext, publicShareID string)
TouchBin() error
}
@@ -381,6 +384,23 @@ func (s *FileSession) SetExecutant(u *userpb.User) {
s.info.Storage["UserGroups"] = string(g)
}
// SetAuditOrigin stores the audit request context of the request that created
// the upload and the public link it came through, if any. The requests that
// send the data later carry a transfer token, which tells neither.
func (s *FileSession) SetAuditOrigin(rc audit.RequestContext, publicShareID string) {
if !rc.IsZero() {
s.info.Storage["AuditRequest"] = rc.Encode()
}
if publicShareID != "" {
s.info.Storage["AuditPublicShareID"] = publicShareID
}
}
// AuditOrigin returns what SetAuditOrigin stored.
func (s *FileSession) AuditOrigin() (audit.RequestContext, string) {
return audit.ParseRequestContext(s.info.Storage["AuditRequest"]), s.info.Storage["AuditPublicShareID"]
}
// TouchBin creates the empty staging file.
func (s *FileSession) TouchBin() error {
f, err := os.OpenFile(s.binPath(), os.O_CREATE|os.O_WRONLY, defaultFilePerm)
+7
View File
@@ -321,6 +321,13 @@ func IsRelativeReference(ref *provider.Reference) bool {
return ref.ResourceId != nil && strings.HasPrefix(ref.Path, ".")
}
// IsSpaceRootedReference returns true if the given reference is a path relative
// to the root of its space, so its path is the path in the space.
func IsSpaceRootedReference(ref *provider.Reference) bool {
rid := ref.GetResourceId()
return IsRelativeReference(ref) && rid.GetSpaceId() != "" && rid.GetOpaqueId() == rid.GetSpaceId()
}
// IsAbsoluteReference returns true if the given reference qualifies as absolute
// when either only the resource id is set or only the path is set and starts with /
//
+3 -1
View File
@@ -1360,11 +1360,12 @@ github.com/opencloud-eu/icap-client
# github.com/opencloud-eu/libre-graph-api-go v1.0.9-0.20261119152805-1a7a500a264e
## explicit; go 1.23
github.com/opencloud-eu/libre-graph-api-go
# github.com/opencloud-eu/reva/v3 v3.0.2-0.20261123180324-2b2b8732790b
# github.com/opencloud-eu/reva/v3 v3.0.2-0.20261126092628-02d5d9ba9a18
## explicit; go 1.26.0
github.com/opencloud-eu/reva/v3/cmd/revad/internal/grace
github.com/opencloud-eu/reva/v3/cmd/revad/runtime
github.com/opencloud-eu/reva/v3/internal/grpc/interceptors/appctx
github.com/opencloud-eu/reva/v3/internal/grpc/interceptors/auditctx
github.com/opencloud-eu/reva/v3/internal/grpc/interceptors/auth
github.com/opencloud-eu/reva/v3/internal/grpc/interceptors/eventsmiddleware
github.com/opencloud-eu/reva/v3/internal/grpc/interceptors/loader
@@ -1467,6 +1468,7 @@ github.com/opencloud-eu/reva/v3/pkg/appauth/manager/jsoncs3
github.com/opencloud-eu/reva/v3/pkg/appauth/manager/loader
github.com/opencloud-eu/reva/v3/pkg/appauth/manager/registry
github.com/opencloud-eu/reva/v3/pkg/appctx
github.com/opencloud-eu/reva/v3/pkg/audit
github.com/opencloud-eu/reva/v3/pkg/auth
github.com/opencloud-eu/reva/v3/pkg/auth/manager/appauth
github.com/opencloud-eu/reva/v3/pkg/auth/manager/demo