diff --git a/services/graph/pkg/errorcode/errorcode.go b/services/graph/pkg/errorcode/errorcode.go index 0347d83dbb..79c9bca432 100644 --- a/services/graph/pkg/errorcode/errorcode.go +++ b/services/graph/pkg/errorcode/errorcode.go @@ -76,6 +76,10 @@ const ( PreconditionFailed // ItemIsLocked The item is locked by another process. Try again later. ItemIsLocked + // PublicLinkPasswordRequired the public link is password protected and no password was provided. + PublicLinkPasswordRequired + // PublicLinkPasswordInvalid a password was provided for the public link but it was rejected. + PublicLinkPasswordInvalid ) var errorCodes = [...]string{ @@ -99,6 +103,8 @@ var errorCodes = [...]string{ "unauthenticated", "preconditionFailed", "itemIsLocked", + "publicLinkPasswordRequired", + "publicLinkPasswordInvalid", } // New constructs a new errorcode.Error @@ -151,6 +157,8 @@ func (e Error) Render(w http.ResponseWriter, r *http.Request) { status = http.StatusMethodNotAllowed case ItemIsLocked: status = http.StatusLocked + case PublicLinkPasswordRequired, PublicLinkPasswordInvalid: + status = http.StatusUnauthorized case PreconditionFailed: status = http.StatusPreconditionFailed default: diff --git a/services/graph/pkg/middleware/auth.go b/services/graph/pkg/middleware/auth.go index 3cab200ed1..212f3383d0 100644 --- a/services/graph/pkg/middleware/auth.go +++ b/services/graph/pkg/middleware/auth.go @@ -44,6 +44,17 @@ func Auth(opts ...account.Option) func(http.Handler) http.Handler { ctx := r.Context() t := r.Header.Get(revactx.TokenHeader) if t == "" { + if hint := r.Header.Get(opkgm.PublicLinkAuthHeader); hint != "" && opkgm.HasPublicLinkToken(r) { + // no WWW-Authenticate: a Basic challenge would open the browser's auth dialog + switch hint { + case opkgm.PublicLinkPasswordRequired: + errorcode.PublicLinkPasswordRequired.Render(w, r, http.StatusUnauthorized, "This public link is password protected.") + return + case opkgm.PublicLinkInvalidPassword: + errorcode.PublicLinkPasswordInvalid.Render(w, r, http.StatusUnauthorized, "The password is incorrect.") + return + } + } errorcode.InvalidAuthenticationToken.Render(w, r, http.StatusUnauthorized, "Access token is empty.") /* msgraph error for GET https://graph.microsoft.com/v1.0/me { @@ -67,7 +78,7 @@ func Auth(opts ...account.Option) func(http.Handler) http.Handler { errorcode.InvalidAuthenticationToken.Render(w, r, http.StatusUnauthorized, "invalid token") return } - if ok, err := scope.VerifyScope(ctx, tokenScope, r); err != nil || !ok { + if ok, err := scope.VerifyScope(ctx, tokenScope, r.URL.Path); err != nil || !ok { opt.Logger.Error().Str(log.RequestIDString, r.Header.Get("X-Request-ID")).Err(err).Msg("verifying scope failed") errorcode.InvalidAuthenticationToken.Render(w, r, http.StatusUnauthorized, "verifying scope failed") return diff --git a/services/graph/pkg/middleware/path_lookup.go b/services/graph/pkg/middleware/path_lookup.go index efa1f344d3..34516219a7 100644 --- a/services/graph/pkg/middleware/path_lookup.go +++ b/services/graph/pkg/middleware/path_lookup.go @@ -203,7 +203,7 @@ func rewriteColonPath( logger.Debug().Err(err).Str("driveID", driveID).Msg("invalid drive id in colon path") return "", errInvalidRequest } - if drive.GetStorageId() != anchor.GetStorageId() || drive.GetSpaceId() != anchor.GetSpaceId() { + if !ItemAddressableInDrive(&drive, &anchor) { logger.Debug(). Str("driveID", driveID). Str("itemID", anchorIDStr). @@ -364,3 +364,17 @@ func resolvePath( func buildCanonicalRoutePath(itemID, suffix string) string { return "/items/" + itemID + suffix } + +// ItemAddressableInDrive is always true below the public share drive: its items +// keep their real ids and the token scope checks containment instead. +func ItemAddressableInDrive(driveID, driveItemID *storageprovider.ResourceId) bool { + if IsPublicLinkDrive(driveID) { + return true + } + return driveID.GetStorageId() == driveItemID.GetStorageId() && driveID.GetSpaceId() == driveItemID.GetSpaceId() +} + +// IsPublicLinkDrive reports whether the drive id is the public share mountpoint. +func IsPublicLinkDrive(driveID *storageprovider.ResourceId) bool { + return driveID.GetStorageId() == utils.PublicStorageProviderID && driveID.GetSpaceId() == utils.PublicStorageSpaceID +} diff --git a/services/graph/pkg/service/v0/driveitems.go b/services/graph/pkg/service/v0/driveitems.go index 2f4692488e..513c0ee60b 100644 --- a/services/graph/pkg/service/v0/driveitems.go +++ b/services/graph/pkg/service/v0/driveitems.go @@ -18,6 +18,7 @@ import ( link "github.com/cs3org/go-cs3apis/cs3/sharing/link/v1beta1" storageprovider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" + "github.com/go-chi/chi/v5" "github.com/go-chi/render" libregraph "github.com/opencloud-eu/libre-graph-api-go" "golang.org/x/crypto/sha3" @@ -32,6 +33,7 @@ import ( "github.com/opencloud-eu/opencloud/pkg/log" "github.com/opencloud-eu/opencloud/services/graph/pkg/errorcode" + graphm "github.com/opencloud-eu/opencloud/services/graph/pkg/middleware" "github.com/opencloud-eu/opencloud/services/graph/pkg/unifiedrole" "github.com/opencloud-eu/opencloud/services/search/pkg/mapping" ) @@ -62,6 +64,111 @@ func odataListContains(r *http.Request, parameter, value string) bool { return false } +func publicLinkOf(r *http.Request) (publicLink, bool) { + l, ok := r.Context().Value(publicLinkKey{}).(publicLink) + return l, ok +} + +func publicDriveRequest(r *http.Request) bool { + _, ok := publicLinkOf(r) + return ok +} + +// publicLinkGate lets a link without ListContainer reach only its drive and upload sessions. +func (g Graph) publicLinkGate(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + driveID, err := parseIDParam(r, "driveID") + if err != nil || !graphm.IsPublicLinkDrive(&driveID) { + next.ServeHTTP(w, r) + return + } + l, err := g.resolvePublicLink(r.Context(), &driveID) + if err != nil { + errorcode.RenderError(w, r, err) + return + } + if !l.grant.GetListContainer() && !addressesDriveOrUploadSession(r) { + errorcode.AccessDenied.Render(w, r, http.StatusForbidden, "the public link does not grant listing") + return + } + next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), publicLinkKey{}, l))) + }) +} + +func addressesDriveOrUploadSession(r *http.Request) bool { + p := strings.TrimSuffix(r.URL.EscapedPath(), "/") + if r.Method == http.MethodPost && strings.HasSuffix(p, "/createUploadSession") { + return true + } + return r.Method == http.MethodGet && strings.HasSuffix(p, "/drives/"+chi.URLParam(r, "driveID")) +} + +// sanitizePublicDriveInfos limits infos to what the public link may see. +func sanitizePublicDriveInfos(l publicLink, infos ...*storageprovider.ResourceInfo) { + for _, info := range infos { + if info == nil { + continue + } + publicshare.FilterResourceInfo(info, l.root, l.grant) + delete(info.GetArbitraryMetadata().GetMetadata(), _favoriteMetadataKey) + if utils.ResourceIDEqual(info.GetId(), l.root.GetId()) { + info.ParentId = nil + // graph names items after the path base + info.Path = path.Join("/", info.GetName()) + } + if lock := info.GetLock(); lock != nil { + lock.User = nil + delete(lock.GetOpaque().GetMap(), "lockownername") + } + } +} + +// pointParentsAtPublicDrive keeps a visitor inside the drive the items were reached through. +func pointParentsAtPublicDrive(l publicLink, items ...*libregraph.DriveItem) { + for _, item := range items { + if item.ParentReference != nil { + item.ParentReference.SetDriveId(l.driveID) + } + } +} + +type publicLinkKey struct{} + +type publicLink struct { + driveID string + root *storageprovider.ResourceInfo + grant *storageprovider.ResourcePermissions +} + +// resolvePublicLink looks up the link whose token is the public drive's opaque id. +func (g Graph) resolvePublicLink(ctx context.Context, driveID *storageprovider.ResourceId) (publicLink, error) { + gatewayClient, err := g.gatewaySelector.Next() + if err != nil { + return publicLink{}, err + } + shareResp, err := gatewayClient.GetPublicShare(ctx, &link.GetPublicShareRequest{ + Ref: &link.PublicShareReference{ + Spec: &link.PublicShareReference_Token{Token: driveID.GetOpaqueId()}, + }, + }) + if err := errorcode.FromCS3Status(shareResp.GetStatus(), err); err != nil { + g.logger.Error().Err(err).Msg("could not resolve the public link of the request") + return publicLink{}, err + } + statResp, err := gatewayClient.Stat(ctx, &storageprovider.StatRequest{ + Ref: &storageprovider.Reference{ResourceId: shareResp.GetShare().GetResourceId()}, + }) + if err := errorcode.FromCS3Status(statResp.GetStatus(), err); err != nil { + g.logger.Error().Err(err).Msg("could not stat the public link root") + return publicLink{}, err + } + return publicLink{ + driveID: storagespace.FormatResourceID(driveID), + root: statResp.GetInfo(), + grant: shareResp.GetShare().GetPermissions().GetPermissions(), + }, nil +} + // driveItemPropertySelected reports whether the given opt-in property was requested via $select func driveItemPropertySelected(r *http.Request, property string) bool { return odataListContains(r, "$select", property) @@ -99,7 +206,7 @@ func (g Graph) CreateUploadSession(w http.ResponseWriter, r *http.Request) { errorcode.RenderError(w, r, err) return } - if driveID.GetStorageId() != driveItemID.GetStorageId() || driveID.GetSpaceId() != driveItemID.GetSpaceId() { + if !graphm.ItemAddressableInDrive(&driveID, &driveItemID) { errorcode.ItemNotFound.Render(w, r, http.StatusNotFound, "Item does not exist") return } @@ -110,6 +217,10 @@ func (g Graph) CreateUploadSession(w http.ResponseWriter, r *http.Request) { http.Error(w, err.Error(), http.StatusBadRequest) return } + if publicDriveRequest(r) && !plainName(cusr.Item.Name) { + errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, "the item name must not contain a path") + return + } gatewayClient, err := g.gatewaySelector.Next() if err != nil { @@ -162,6 +273,10 @@ func (g Graph) CreateUploadSession(w http.ResponseWriter, r *http.Request) { render.JSON(w, r, &uploadSession) } +func plainName(name string) bool { + return !strings.Contains(name, "/") && name != "." && name != ".." +} + type createUploadSessionRequest struct { DeferCommit bool `json:"deferCommit"` Item driveItemUploadableProperties `json:"item"` @@ -247,7 +362,7 @@ func (g Graph) GetDriveItem(w http.ResponseWriter, r *http.Request) { errorcode.RenderError(w, r, err) return } - if driveID.GetStorageId() != driveItemID.GetStorageId() || driveID.GetSpaceId() != driveItemID.GetSpaceId() { + if !graphm.ItemAddressableInDrive(&driveID, &driveItemID) { errorcode.ItemNotFound.Render(w, r, http.StatusNotFound, "Item does not exist") return } @@ -272,7 +387,9 @@ func (g Graph) GetDriveItem(w http.ResponseWriter, r *http.Request) { errorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error()) return case res.GetStatus().GetCode() == cs3rpc.Code_CODE_OK: - // ok + if l, ok := publicLinkOf(r); ok { + sanitizePublicDriveInfos(l, res.GetInfo()) + } case res.GetStatus().GetCode() == cs3rpc.Code_CODE_NOT_FOUND: errorcode.ItemNotFound.Render(w, r, http.StatusNotFound, res.GetStatus().GetMessage()) return @@ -291,6 +408,9 @@ func (g Graph) GetDriveItem(w http.ResponseWriter, r *http.Request) { errorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error()) return } + if l, ok := publicLinkOf(r); ok { + pointParentsAtPublicDrive(l, driveItem) + } if driveItemPropertySelected(r, _selectAllowedValues) { setDriveItemAllowedValues(driveItem, res.GetInfo()) @@ -305,7 +425,7 @@ func (g Graph) GetDriveItem(w http.ResponseWriter, r *http.Request) { driveItem.Children = children } - if driveItemPropertySelected(r, _selectShareTypes) { + if driveItemPropertySelected(r, _selectShareTypes) && !publicDriveRequest(r) { infos := []*storageprovider.ResourceInfo{res.GetInfo()} driveItem.LibreGraphShareTypes = shareTypesOf(res.GetInfo(), g.listLinkShares(ctx, infos)) } @@ -332,7 +452,7 @@ func (g Graph) GetDriveItemChildren(w http.ResponseWriter, r *http.Request) { errorcode.RenderError(w, r, err) return } - if driveID.GetStorageId() != driveItemID.GetStorageId() || driveID.GetSpaceId() != driveItemID.GetSpaceId() { + if !graphm.ItemAddressableInDrive(&driveID, &driveItemID) { errorcode.ItemNotFound.Render(w, r, http.StatusNotFound, "Item does not exist") return } @@ -365,7 +485,7 @@ func (g Graph) listDriveItemChildren(w http.ResponseWriter, r *http.Request, dri childrenRequest := &storageprovider.ListContainerRequest{ Ref: &storageprovider.Reference{ResourceId: driveItemID}, } - if driveItemPropertySelected(r, _selectShareTypes) { + if driveItemPropertySelected(r, _selectShareTypes) && !publicDriveRequest(r) { childrenRequest.FieldMask = shareTypesFieldMask } @@ -390,15 +510,25 @@ func (g Graph) listDriveItemChildren(w http.ResponseWriter, r *http.Request, dri return nil, false } + l, public := publicLinkOf(r) + if public { + sanitizePublicDriveInfos(l, res.GetInfos()...) + } + files, err := formatDriveItems(g.logger, g.publicBaseURL, res.GetInfos()) if err != nil { errorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error()) return nil, false } + if public { + for i := range files { + pointParentsAtPublicDrive(l, &files[i]) + } + } setDriveItemsAllowedValues(r, files, res.GetInfos()) - if driveItemPropertySelected(r, _selectShareTypes) { + if driveItemPropertySelected(r, _selectShareTypes) && !publicDriveRequest(r) { g.addShareTypes(r.Context(), files, res.GetInfos()) } diff --git a/services/graph/pkg/service/v0/drives.go b/services/graph/pkg/service/v0/drives.go index 634642cb9f..9feaeba0d5 100644 --- a/services/graph/pkg/service/v0/drives.go +++ b/services/graph/pkg/service/v0/drives.go @@ -37,6 +37,7 @@ import ( v0 "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/messages/settings/v0" settingssvc "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/services/settings/v0" "github.com/opencloud-eu/opencloud/services/graph/pkg/errorcode" + graphm "github.com/opencloud-eu/opencloud/services/graph/pkg/middleware" "github.com/opencloud-eu/opencloud/services/graph/pkg/odata" settingsServiceExt "github.com/opencloud-eu/opencloud/services/settings/pkg/store/defaults" ) @@ -992,6 +993,17 @@ func (g Graph) cs3StorageSpaceToDrive(ctx context.Context, baseURL *url.URL, spa // DisplayName: , TODO read and cache from users provider }, } + } else if graphm.IsPublicLinkDrive(space.GetRoot()) { + // a public share mountpoint has no space owner; the request runs as the sharer + if u, ok := revactx.ContextGetUser(ctx); ok && u.GetId().GetOpaqueId() != "" { + id := u.GetId().GetOpaqueId() + drive.Owner = &libregraph.IdentitySet{ + User: &libregraph.Identity{ + Id: &id, + DisplayName: u.GetDisplayName(), + }, + } + } } if space.Mtime != nil { lastModified := cs3TimestampToTime(space.Mtime) diff --git a/services/graph/pkg/service/v0/service.go b/services/graph/pkg/service/v0/service.go index 09f0700a6b..513cd21ae5 100644 --- a/services/graph/pkg/service/v0/service.go +++ b/services/graph/pkg/service/v0/service.go @@ -271,6 +271,7 @@ func NewService(opts ...Option) (Graph, error) { //nolint:maintidx // matches the leaf route. Must sit here, on the // /drives/{driveID} sub-router, so it can rewrite the // remaining RoutePath. See graphm.ResolveGraphPath. + r.Use(svc.publicLinkGate) r.Use(graphm.ResolveGraphPath(options.GatewaySelector, options.Logger)) r.Get("/", svc.GetSingleDriveV1Beta1) r.Patch("/", svc.UpdateDriveV1Beta1) @@ -395,6 +396,7 @@ func NewService(opts ...Option) (Graph, error) { //nolint:maintidx // matches the leaf route. Must sit here, on the // /drives/{driveID} sub-router, so it can rewrite the // remaining RoutePath. See graphm.ResolveGraphPath. + r.Use(svc.publicLinkGate) r.Use(graphm.ResolveGraphPath(options.GatewaySelector, options.Logger)) r.Patch("/", svc.UpdateDrive) r.Get("/", svc.GetSingleDrive)