diff --git a/services/graph/mocks/drives_drive_item_provider.go b/services/graph/mocks/drives_drive_item_provider.go index a3222cb187..d7c0e590a2 100644 --- a/services/graph/mocks/drives_drive_item_provider.go +++ b/services/graph/mocks/drives_drive_item_provider.go @@ -127,48 +127,49 @@ func (_c *DrivesDriveItemProvider_CreateChild_Call) RunAndReturn(run func(ctx co return _c } -// CreatePath provides a mock function for the type DrivesDriveItemProvider -func (_mock *DrivesDriveItemProvider) CreatePath(ctx context.Context, parentID *providerv1beta1.ResourceId, relPath string) (*providerv1beta1.ResourceId, error) { - ret := _mock.Called(ctx, parentID, relPath) +// ResolvePath provides a mock function for the type DrivesDriveItemProvider +func (_mock *DrivesDriveItemProvider) ResolvePath(ctx context.Context, parentID *providerv1beta1.ResourceId, relPath string, createMissing bool) (*providerv1beta1.ResourceId, error) { + ret := _mock.Called(ctx, parentID, relPath, createMissing) if len(ret) == 0 { - panic("no return value specified for CreatePath") + panic("no return value specified for ResolvePath") } var r0 *providerv1beta1.ResourceId var r1 error - if returnFunc, ok := ret.Get(0).(func(context.Context, *providerv1beta1.ResourceId, string) (*providerv1beta1.ResourceId, error)); ok { - return returnFunc(ctx, parentID, relPath) + if returnFunc, ok := ret.Get(0).(func(context.Context, *providerv1beta1.ResourceId, string, bool) (*providerv1beta1.ResourceId, error)); ok { + return returnFunc(ctx, parentID, relPath, createMissing) } - if returnFunc, ok := ret.Get(0).(func(context.Context, *providerv1beta1.ResourceId, string) *providerv1beta1.ResourceId); ok { - r0 = returnFunc(ctx, parentID, relPath) + if returnFunc, ok := ret.Get(0).(func(context.Context, *providerv1beta1.ResourceId, string, bool) *providerv1beta1.ResourceId); ok { + r0 = returnFunc(ctx, parentID, relPath, createMissing) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*providerv1beta1.ResourceId) } } - if returnFunc, ok := ret.Get(1).(func(context.Context, *providerv1beta1.ResourceId, string) error); ok { - r1 = returnFunc(ctx, parentID, relPath) + if returnFunc, ok := ret.Get(1).(func(context.Context, *providerv1beta1.ResourceId, string, bool) error); ok { + r1 = returnFunc(ctx, parentID, relPath, createMissing) } else { r1 = ret.Error(1) } return r0, r1 } -// DrivesDriveItemProvider_CreatePath_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreatePath' -type DrivesDriveItemProvider_CreatePath_Call struct { +// DrivesDriveItemProvider_ResolvePath_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ResolvePath' +type DrivesDriveItemProvider_ResolvePath_Call struct { *mock.Call } -// CreatePath is a helper method to define mock.On call +// ResolvePath is a helper method to define mock.On call // - ctx context.Context // - parentID *providerv1beta1.ResourceId // - relPath string -func (_e *DrivesDriveItemProvider_Expecter) CreatePath(ctx interface{}, parentID interface{}, relPath interface{}) *DrivesDriveItemProvider_CreatePath_Call { - return &DrivesDriveItemProvider_CreatePath_Call{Call: _e.mock.On("CreatePath", ctx, parentID, relPath)} +// - createMissing bool +func (_e *DrivesDriveItemProvider_Expecter) ResolvePath(ctx interface{}, parentID interface{}, relPath interface{}, createMissing interface{}) *DrivesDriveItemProvider_ResolvePath_Call { + return &DrivesDriveItemProvider_ResolvePath_Call{Call: _e.mock.On("ResolvePath", ctx, parentID, relPath, createMissing)} } -func (_c *DrivesDriveItemProvider_CreatePath_Call) Run(run func(ctx context.Context, parentID *providerv1beta1.ResourceId, relPath string)) *DrivesDriveItemProvider_CreatePath_Call { +func (_c *DrivesDriveItemProvider_ResolvePath_Call) Run(run func(ctx context.Context, parentID *providerv1beta1.ResourceId, relPath string, createMissing bool)) *DrivesDriveItemProvider_ResolvePath_Call { _c.Call.Run(func(args mock.Arguments) { var arg0 context.Context if args[0] != nil { @@ -182,21 +183,26 @@ func (_c *DrivesDriveItemProvider_CreatePath_Call) Run(run func(ctx context.Cont if args[2] != nil { arg2 = args[2].(string) } + var arg3 bool + if args[3] != nil { + arg3 = args[3].(bool) + } run( arg0, arg1, arg2, + arg3, ) }) return _c } -func (_c *DrivesDriveItemProvider_CreatePath_Call) Return(resourceId *providerv1beta1.ResourceId, err error) *DrivesDriveItemProvider_CreatePath_Call { +func (_c *DrivesDriveItemProvider_ResolvePath_Call) Return(resourceId *providerv1beta1.ResourceId, err error) *DrivesDriveItemProvider_ResolvePath_Call { _c.Call.Return(resourceId, err) return _c } -func (_c *DrivesDriveItemProvider_CreatePath_Call) RunAndReturn(run func(ctx context.Context, parentID *providerv1beta1.ResourceId, relPath string) (*providerv1beta1.ResourceId, error)) *DrivesDriveItemProvider_CreatePath_Call { +func (_c *DrivesDriveItemProvider_ResolvePath_Call) RunAndReturn(run func(ctx context.Context, parentID *providerv1beta1.ResourceId, relPath string, createMissing bool) (*providerv1beta1.ResourceId, error)) *DrivesDriveItemProvider_ResolvePath_Call { _c.Call.Return(run) return _c } diff --git a/services/graph/pkg/middleware/path_lookup.go b/services/graph/pkg/middleware/path_lookup.go index d642c5ea23..26bff20cee 100644 --- a/services/graph/pkg/middleware/path_lookup.go +++ b/services/graph/pkg/middleware/path_lookup.go @@ -36,18 +36,14 @@ type contextKey string // tracing/logging consumers. const OriginalPathContextKey contextKey = "graph.original_path" -// CreateParentsContextKey holds the unresolved parent path of a POST children -// colon request with @libre.graph.missingParentsBehavior=create. The middleware -// leaves such paths unresolved (the route is rewritten to the anchor item -// instead); the handler resolves the path and creates the missing folders, but -// only after fully validating the request - so an invalid request has no side -// effects. -const CreateParentsContextKey contextKey = "graph.create_parents" +// ParentPathContextKey holds the unresolved parent path of a POST .../children +// colon request; the handler resolves (or creates) it after validation. +const ParentPathContextKey contextKey = "graph.parent_path" -// CreateParentsPath returns the parent path stored by ResolveGraphPath, or "" -// for all other requests. -func CreateParentsPath(ctx context.Context) string { - path, _ := ctx.Value(CreateParentsContextKey).(string) +// ParentPath returns the parent path stored by ResolveGraphPath, or "" for all +// other requests. +func ParentPath(ctx context.Context) string { + path, _ := ctx.Value(ParentPathContextKey).(string) return path } @@ -89,6 +85,10 @@ var ( // failures (gateway selection, RPC transport, unexpected status) surface // as 5xx so outages aren't masked. // +// POST .../children colon requests are never resolved here: the rewrite targets +// the anchor item and the parent path reaches the handler via +// ParentPathContextKey (see createChild). +// // Requests whose RoutePath contains no colon fast-path through untouched. func ResolveGraphPath(gws pool.Selectable[gateway.GatewayAPIClient], logger log.Logger) func(http.Handler) http.Handler { l := logger.With().Str("middleware", "graphPathLookup").Logger() @@ -106,7 +106,7 @@ func ResolveGraphPath(gws pool.Selectable[gateway.GatewayAPIClient], logger log. driveID := chi.URLParam(r, "driveID") original := r.URL.Path - rewritten, createParents, err := rewriteColonPath(r.Context(), gws, l, driveID, rctx.RoutePath, r) + rewritten, parentPath, err := rewriteColonPath(r.Context(), gws, l, driveID, rctx.RoutePath, r.Method) switch { case errors.Is(err, errPathNotFound): l.Debug().Str("original", original).Msg("colon-path resolution: not found") @@ -141,8 +141,8 @@ func ResolveGraphPath(gws pool.Selectable[gateway.GatewayAPIClient], logger log. // tracing/logging. r.URL.Path itself stays untouched; only chi's // internal RoutePath is rewritten. r = r.WithContext(context.WithValue(r.Context(), OriginalPathContextKey, original)) - if createParents != "" { - r = r.WithContext(context.WithValue(r.Context(), CreateParentsContextKey, createParents)) + if parentPath != "" { + r = r.WithContext(context.WithValue(r.Context(), ParentPathContextKey, parentPath)) } rctx.RoutePath = rewritten next.ServeHTTP(w, r) @@ -163,7 +163,7 @@ type colonMatch struct { suffix string // suffix with leading slash (e.g. "/children"); may be empty } -// rewriteColonPath returns (rewritten, createParents, err): +// rewriteColonPath returns (rewritten, parentPath, err): // - "" + nil - no colon-syntax pattern matched (passthrough) // - rewritten + nil - matched and resolved to a canonical RoutePath // - "" + errPathNotFound - path doesn't exist or user lacks permission (404) @@ -171,24 +171,19 @@ type colonMatch struct { // - "" + errUnauthenticated - gateway said caller isn't authenticated (401) // - "" + other error - operational / internal failure (5xx) // -// createParents is non-empty for POST .../children requests with -// @libre.graph.missingParentsBehavior=create: the colon path is then not -// resolved at all - the rewrite targets the anchor item and createParents -// carries the parent path for the handler to resolve/create (see -// CreateParentsContextKey). +// parentPath is non-empty for POST .../children requests: their colon path is +// never resolved here, the rewrite targets the anchor item and the handler +// resolves (or creates) the parent path (see ParentPathContextKey). // // driveIDParam is the {driveID} route param (raw chi.URLParam value); routePath -// is chi.RouteContext().RoutePath (the part below /drives/{driveID}). r is only -// consulted for the method and the @libre.graph.missingParentsBehavior query -// parameter, which is meaningful for POST .../children requests only and -// ignored otherwise. +// is chi.RouteContext().RoutePath (the part below /drives/{driveID}). func rewriteColonPath( ctx context.Context, gws pool.Selectable[gateway.GatewayAPIClient], logger zerolog.Logger, driveIDParam string, routePath string, - r *http.Request, + method string, ) (string, string, error) { match, ok := parseColonPath(routePath) if !ok { @@ -196,19 +191,8 @@ func rewriteColonPath( } // The colon path addresses the parent of the item a POST .../children - // creates. With missingParentsBehavior=create the missing folders along - // that path are created instead of returning 404. - createParents := false - if r.Method == http.MethodPost && match.suffix == "/children" { - switch r.URL.Query().Get("@libre.graph.missingParentsBehavior") { - case "", "fail": - case "create": - createParents = true - default: - logger.Debug().Msg("invalid @libre.graph.missingParentsBehavior in colon path") - return "", "", errInvalidRequest - } - } + // creates; the handler decides how to resolve it. + deferToHandler := method == http.MethodPost && match.suffix == "/children" // RoutePath follows chi's RawPath, i.e. the percent-encoded wire form // (e.g. "/Documents/My%20File"). A single PathUnescape reproduces exactly @@ -261,14 +245,10 @@ func rewriteColonPath( return "", "", errInvalidRequest } - if createParents { - // Leave the path unresolved: rewrite to the anchor item and hand the - // parent path to the handler (via CreateParentsContextKey), which - // creates the missing folders after validating the request. This - // middleware stays free of side effects. + if deferToHandler { + // rewrite to the anchor item, the handler resolves the parent path if anchor.GetOpaqueId() == "" { - // the root-anchored form parses without an opaque part; the space - // root item id is storage$space!space + // the space root item id is storage$space!space anchor.OpaqueId = anchor.GetSpaceId() } return buildCanonicalRoutePath(storagespace.FormatResourceID(&anchor), match.suffix), relPath, nil diff --git a/services/graph/pkg/middleware/path_lookup_test.go b/services/graph/pkg/middleware/path_lookup_test.go index 66e3be1d77..e1581e8074 100644 --- a/services/graph/pkg/middleware/path_lookup_test.go +++ b/services/graph/pkg/middleware/path_lookup_test.go @@ -61,12 +61,12 @@ func statResponse(code cs3rpc.Code, withInfo bool) *storageprovider.StatResponse // the middleware rewrote chi's route path correctly and the request reached the // intended /items/{itemID}... handler with the resolved id bound as a param. type leafCapture struct { - hit string // which leaf was reached ("" = none) - urlPath string // r.URL.Path as seen by the handler (must stay the original) - driveID string // chi.URLParam(driveID) - itemID string // resolved item id, decoded via PathUnescape - original any // OriginalPathContextKey value - createParents string // CreateParentsPath(ctx) as seen by the handler + hit string // which leaf was reached ("" = none) + urlPath string // r.URL.Path as seen by the handler (must stay the original) + driveID string // chi.URLParam(driveID) + itemID string // resolved item id, decoded via PathUnescape + original any // OriginalPathContextKey value + parentPath string // ParentPath(ctx) as seen by the handler } // newGraphTestRouter wires ResolveGraphPath into a chi router that mirrors the @@ -95,7 +95,7 @@ func newGraphTestRouter(t *testing.T, gw *cs3mocks.GatewayAPIClient) (http.Handl // mirror that here so we assert on the recovered id. cap.itemID, _ = url.PathUnescape(raw) cap.original = r.Context().Value(middleware.OriginalPathContextKey) - cap.createParents = middleware.CreateParentsPath(r.Context()) + cap.parentPath = middleware.ParentPath(r.Context()) w.WriteHeader(http.StatusOK) } } @@ -473,88 +473,43 @@ func TestResolveGraphPath_OriginalPathContext(t *testing.T) { assert.Equal(t, original, cap.urlPath, "r.URL.Path must remain the original request path") } -// TestResolveGraphPath_MissingParentsBehavior covers the -// @libre.graph.missingParentsBehavior query parameter on POST .../children -// colon-syntax requests. With behavior=create the middleware does NOT resolve -// (or create) anything: it rewrites to the anchor item and hands the parent -// path to the handler via CreateParentsContextKey. -func TestResolveGraphPath_MissingParentsBehavior(t *testing.T) { - childrenURL := "/graph/v1beta1/drives/" + testDriveID + "/root:/a/b:/children" +// TestResolveGraphPath_DeferredChildrenPost pins that POST .../children colon +// requests are never resolved in the middleware: no CS3 calls, the rewrite +// targets the anchor item and the handler receives the parent path via +// ParentPathContextKey. +func TestResolveGraphPath_DeferredChildrenPost(t *testing.T) { // the root-anchored form rewrites to the space root item id rootItemID := testDriveID + "!f503f6fe-2656-4b0f-8289-fb3184962dfd" - t.Run("create rewrites to the root anchor and passes the path unresolved", func(t *testing.T) { + t.Run("root-anchored rewrites to the root anchor and passes the path unresolved", func(t *testing.T) { gw := cs3mocks.NewGatewayAPIClient(t) // no CS3 calls expected router, cap := newGraphTestRouter(t, gw) rr := httptest.NewRecorder() router.ServeHTTP(rr, httptest.NewRequest( - http.MethodPost, childrenURL+"?%40libre.graph.missingParentsBehavior=create", nil, + http.MethodPost, "/graph/v1beta1/drives/"+testDriveID+"/root:/a/b:/children", nil, )) assert.Equal(t, http.StatusOK, rr.Code) assert.Equal(t, "createChild", cap.hit) assert.Equal(t, rootItemID, cap.itemID) - assert.Equal(t, "/a/b", cap.createParents) + assert.Equal(t, "/a/b", cap.parentPath) }) - t.Run("create rewrites to the item anchor and passes the path unresolved", func(t *testing.T) { + t.Run("item-anchored rewrites to the item anchor and passes the path unresolved", func(t *testing.T) { gw := cs3mocks.NewGatewayAPIClient(t) // no CS3 calls expected router, cap := newGraphTestRouter(t, gw) rr := httptest.NewRecorder() router.ServeHTTP(rr, httptest.NewRequest( http.MethodPost, - "/graph/v1beta1/drives/"+testDriveID+"/items/"+testItemID+":/a/b:/children?%40libre.graph.missingParentsBehavior=create", + "/graph/v1beta1/drives/"+testDriveID+"/items/"+testItemID+":/a/b:/children", nil, )) assert.Equal(t, http.StatusOK, rr.Code) assert.Equal(t, "createChild", cap.hit) assert.Equal(t, testItemID, cap.itemID) - assert.Equal(t, "/a/b", cap.createParents) - }) - - t.Run("default fail resolves and returns 404 for a missing path", func(t *testing.T) { - gw := cs3mocks.NewGatewayAPIClient(t) - gw.EXPECT().Stat(mock.Anything, mock.Anything, mock.Anything). - Return(statResponse(cs3rpc.Code_CODE_NOT_FOUND, false), nil). - Once() - - router, cap := newGraphTestRouter(t, gw) - rr := httptest.NewRecorder() - router.ServeHTTP(rr, httptest.NewRequest(http.MethodPost, childrenURL, nil)) - - assert.Equal(t, http.StatusNotFound, rr.Code) - assert.Equal(t, "", cap.hit) - }) - - t.Run("default fail resolves an existing path without context handoff", func(t *testing.T) { - gw := cs3mocks.NewGatewayAPIClient(t) - gw.EXPECT().Stat(mock.Anything, mock.Anything, mock.Anything). - Return(statResponse(cs3rpc.Code_CODE_OK, true), nil). - Once() - - router, cap := newGraphTestRouter(t, gw) - rr := httptest.NewRecorder() - router.ServeHTTP(rr, httptest.NewRequest(http.MethodPost, childrenURL, nil)) - - assert.Equal(t, http.StatusOK, rr.Code) - assert.Equal(t, "createChild", cap.hit) - assert.Equal(t, testItemID, cap.itemID) - assert.Equal(t, "", cap.createParents) - }) - - t.Run("invalid value returns 400", func(t *testing.T) { - gw := cs3mocks.NewGatewayAPIClient(t) - - router, cap := newGraphTestRouter(t, gw) - rr := httptest.NewRecorder() - router.ServeHTTP(rr, httptest.NewRequest( - http.MethodPost, childrenURL+"?%40libre.graph.missingParentsBehavior=maybe", nil, - )) - - assert.Equal(t, http.StatusBadRequest, rr.Code) - assert.Equal(t, "", cap.hit) + assert.Equal(t, "/a/b", cap.parentPath) }) } diff --git a/services/graph/pkg/service/v0/api_drives_drive_item.go b/services/graph/pkg/service/v0/api_drives_drive_item.go index 4984ea76c8..ca105fbfa1 100644 --- a/services/graph/pkg/service/v0/api_drives_drive_item.go +++ b/services/graph/pkg/service/v0/api_drives_drive_item.go @@ -87,6 +87,12 @@ var ( // ErrInvalidConflictBehavior is returned when the conflictBehavior query parameter is invalid ErrInvalidConflictBehavior = errorcode.New(errorcode.InvalidRequest, "invalid @libre.graph.conflictBehavior") + + // ErrInvalidMissingParentsBehavior is returned when the missingParentsBehavior query parameter is invalid + ErrInvalidMissingParentsBehavior = errorcode.New(errorcode.InvalidRequest, "invalid @libre.graph.missingParentsBehavior") + + // ErrPathNotFound is returned when a parent path cannot be resolved + ErrPathNotFound = errorcode.New(errorcode.ItemNotFound, "path not found") ) type ( @@ -98,8 +104,8 @@ type ( // CreateChild creates a folder or an empty file below the given parent CreateChild(ctx context.Context, parentID *storageprovider.ResourceId, name string, isFolder, replace bool) (*storageprovider.ResourceInfo, error) - // CreatePath ensures the folders along relPath below parentID exist and returns the id of the deepest one - CreatePath(ctx context.Context, parentID *storageprovider.ResourceId, relPath string) (*storageprovider.ResourceId, error) + // ResolvePath resolves relPath below parentID to its id, creating missing folders when createMissing is set + ResolvePath(ctx context.Context, parentID *storageprovider.ResourceId, relPath string, createMissing bool) (*storageprovider.ResourceId, error) // MountShare mounts a share MountShare(ctx context.Context, resourceID *storageprovider.ResourceId, name string) ([]*collaboration.ReceivedShare, error) @@ -403,9 +409,10 @@ func (s DrivesDriveItemService) CreateChild(ctx context.Context, parentID *stora return idRes.GetInfo(), nil } -// CreatePath ensures the folders along relPath below parentID exist, creating the missing -// ones, and returns the id of the deepest one. It backs @libre.graph.missingParentsBehavior=create. -func (s DrivesDriveItemService) CreatePath(ctx context.Context, parentID *storageprovider.ResourceId, relPath string) (*storageprovider.ResourceId, error) { +// ResolvePath resolves relPath below parentID to its id; with createMissing the +// missing folders along the path are created first. It backs colon-path POST +// .../children requests and @libre.graph.missingParentsBehavior. +func (s DrivesDriveItemService) ResolvePath(ctx context.Context, parentID *storageprovider.ResourceId, relPath string, createMissing bool) (*storageprovider.ResourceId, error) { segments := strings.Split(strings.Trim(relPath, "/"), "/") for _, segment := range segments { if segment == "" || segment == "." || segment == ".." { @@ -433,8 +440,15 @@ func (s DrivesDriveItemService) CreatePath(ctx context.Context, parentID *storag // common case: the full path exists already id, err := stat() - if err == nil || !hasErrorCode(err, errorcode.ItemNotFound) { - return id, err + switch { + case err == nil: + return id, nil + case !hasErrorCode(err, errorcode.ItemNotFound) && !hasErrorCode(err, errorcode.AccessDenied): + return nil, err + case !createMissing: + // denied collapses to not-found, matching the middleware's colon + // lookups (no existence disclosure) + return nil, ErrPathNotFound } var walked string @@ -711,14 +725,24 @@ func (api DrivesDriveItemApi) createChild(w http.ResponseWriter, r *http.Request return } - // a colon path with missingParentsBehavior=create arrives unresolved: parentID is - // the anchor item and the parent path below it still needs to be resolved/created. - // This runs after all validation so an invalid request has no side effects. - if parents := graphm.CreateParentsPath(r.Context()); parents != "" { + // colon-path POST children requests arrive unresolved: parentID is the anchor + // item, the parent path below it is resolved (or created) here, after validation + if parentPath := graphm.ParentPath(r.Context()); parentPath != "" { + var createMissing bool + switch r.URL.Query().Get("@libre.graph.missingParentsBehavior") { + case "", "fail": + case "create": + createMissing = true + default: + api.logger.Debug().Msg(ErrInvalidMissingParentsBehavior.Error()) + ErrInvalidMissingParentsBehavior.Render(w, r) + return + } + var err error - parentID, err = api.drivesDriveItemService.CreatePath(r.Context(), parentID, parents) + parentID, err = api.drivesDriveItemService.ResolvePath(r.Context(), parentID, parentPath, createMissing) if err != nil { - api.logger.Debug().Err(err).Msg("creating parent folders failed") + api.logger.Debug().Err(err).Msg("resolving the parent path failed") errorcode.RenderError(w, r, err) return } diff --git a/services/graph/pkg/service/v0/api_drives_drive_item_test.go b/services/graph/pkg/service/v0/api_drives_drive_item_test.go index 373a20c483..3a4b610e03 100644 --- a/services/graph/pkg/service/v0/api_drives_drive_item_test.go +++ b/services/graph/pkg/service/v0/api_drives_drive_item_test.go @@ -583,7 +583,7 @@ var _ = Describe("DrivesDriveItemService", func() { }) }) - var _ = Describe("CreatePath", func() { + var _ = Describe("ResolvePath", func() { parentID := &storageprovider.ResourceId{StorageId: "1", SpaceId: "2", OpaqueId: "2"} pathID := &storageprovider.ResourceId{StorageId: "1", SpaceId: "2", OpaqueId: "3"} @@ -597,7 +597,7 @@ var _ = Describe("DrivesDriveItemService", func() { It("rejects invalid path segments", func() { for _, relPath := range []string{"", ".", "..", "a/../b", "a//b"} { - _, err := drivesDriveItemService.CreatePath(context.Background(), parentID, relPath) + _, err := drivesDriveItemService.ResolvePath(context.Background(), parentID, relPath, false) Expect(err).To(MatchError(svc.ErrInvalidItemName)) } }) @@ -612,11 +612,33 @@ var _ = Describe("DrivesDriveItemService", func() { }). Once() - id, err := drivesDriveItemService.CreatePath(context.Background(), parentID, "/a/b") + id, err := drivesDriveItemService.ResolvePath(context.Background(), parentID, "/a/b", true) Expect(err).ToNot(HaveOccurred()) Expect(id.GetOpaqueId()).To(Equal("3")) }) + It("returns ErrPathNotFound for a missing path without createMissing", func() { + gatewayClient. + EXPECT(). + Stat(mock.Anything, mock.Anything, mock.Anything). + Return(statResponse(status.NewNotFound(context.Background(), "missing")), nil). + Once() + + _, err := drivesDriveItemService.ResolvePath(context.Background(), parentID, "/a/b", false) + Expect(err).To(MatchError(svc.ErrPathNotFound)) + }) + + It("returns ErrPathNotFound for a denied path without createMissing", func() { + gatewayClient. + EXPECT(). + Stat(mock.Anything, mock.Anything, mock.Anything). + Return(statResponse(status.NewPermissionDenied(context.Background(), nil, "denied")), nil). + Once() + + _, err := drivesDriveItemService.ResolvePath(context.Background(), parentID, "/a/b", false) + Expect(err).To(MatchError(svc.ErrPathNotFound)) + }) + It("creates the folders along a missing path, reusing existing ones", func() { gatewayClient. EXPECT(). @@ -645,7 +667,7 @@ var _ = Describe("DrivesDriveItemService", func() { Return(statResponse(status.NewOK(context.Background())), nil). Once() - id, err := drivesDriveItemService.CreatePath(context.Background(), parentID, "/a/b") + id, err := drivesDriveItemService.ResolvePath(context.Background(), parentID, "/a/b", true) Expect(err).ToNot(HaveOccurred()) Expect(id.GetOpaqueId()).To(Equal("3")) }) @@ -662,7 +684,7 @@ var _ = Describe("DrivesDriveItemService", func() { Return(&storageprovider.CreateContainerResponse{Status: status.NewPermissionDenied(context.Background(), nil, "denied")}, nil). Once() - _, err := drivesDriveItemService.CreatePath(context.Background(), parentID, "/a") + _, err := drivesDriveItemService.ResolvePath(context.Background(), parentID, "/a", true) var lgErr errorcode.Error Expect(errors.As(err, &lgErr)).To(BeTrue()) Expect(lgErr.GetCode()).To(Equal(errorcode.AccessDenied)) @@ -1605,7 +1627,7 @@ var _ = Describe("DrivesDriveItemApi", func() { Expect(gjson.Get(w.Body.String(), "file.mimeType").String()).To(Equal("text/plain")) }) - It("creates the unresolved parent path from the context first", func() { + It("resolves the parent path from the context first", func() { rCTX.URLParams.Add("driveID", "1$2") rCTX.URLParams.Add("itemID", "1$2!2") @@ -1620,9 +1642,9 @@ var _ = Describe("DrivesDriveItemApi", func() { parentID := &storageprovider.ResourceId{StorageId: "1", SpaceId: "2", OpaqueId: "3"} drivesDriveItemProvider. EXPECT(). - CreatePath(mock.Anything, mock.MatchedBy(func(id *storageprovider.ResourceId) bool { + ResolvePath(mock.Anything, mock.MatchedBy(func(id *storageprovider.ResourceId) bool { return id.GetOpaqueId() == "2" - }), "/a/b"). + }), "/a/b", true). Return(parentID, nil). Once() drivesDriveItemProvider. @@ -1636,14 +1658,14 @@ var _ = Describe("DrivesDriveItemApi", func() { Once() ctx := context.WithValue(context.Background(), chi.RouteCtxKey, rCTX) - ctx = context.WithValue(ctx, graphm.CreateParentsContextKey, "/a/b") - r := httptest.NewRequest(http.MethodPost, "/", bytes.NewBuffer(driveItemJson)).WithContext(ctx) + ctx = context.WithValue(ctx, graphm.ParentPathContextKey, "/a/b") + r := httptest.NewRequest(http.MethodPost, "/?%40libre.graph.missingParentsBehavior=create", bytes.NewBuffer(driveItemJson)).WithContext(ctx) drivesDriveItemApi.CreateChildDriveItem(w, r) Expect(w.Code).To(Equal(http.StatusCreated)) }) - It("does not create parent folders when the request is invalid", func() { + It("fails on an invalid missingParentsBehavior without calling the provider", func() { rCTX.URLParams.Add("driveID", "1$2") rCTX.URLParams.Add("itemID", "1$2!2") @@ -1656,10 +1678,34 @@ var _ = Describe("DrivesDriveItemApi", func() { Expect(err).ToNot(HaveOccurred()) ctx := context.WithValue(context.Background(), chi.RouteCtxKey, rCTX) - ctx = context.WithValue(ctx, graphm.CreateParentsContextKey, "/a/b") + ctx = context.WithValue(ctx, graphm.ParentPathContextKey, "/a/b") + r := httptest.NewRequest(http.MethodPost, "/?%40libre.graph.missingParentsBehavior=maybe", bytes.NewBuffer(driveItemJson)).WithContext(ctx) + + // no ResolvePath / CreateChild expectations: the provider must not be called + drivesDriveItemApi.CreateChildDriveItem(w, r) + Expect(w.Code).To(Equal(http.StatusBadRequest)) + + jsonData := gjson.Get(w.Body.String(), "error") + Expect(jsonData.Get("code").String() + ": " + jsonData.Get("message").String()).To(Equal(svc.ErrInvalidMissingParentsBehavior.Error())) + }) + + It("does not resolve parent folders when the request is invalid", func() { + rCTX.URLParams.Add("driveID", "1$2") + rCTX.URLParams.Add("itemID", "1$2!2") + + w := httptest.NewRecorder() + + driveItemJson, err := json.Marshal(libregraph.DriveItem{ + Name: conversions.ToPointer("New Folder"), + Folder: &libregraph.Folder{}, + }) + Expect(err).ToNot(HaveOccurred()) + + ctx := context.WithValue(context.Background(), chi.RouteCtxKey, rCTX) + ctx = context.WithValue(ctx, graphm.ParentPathContextKey, "/a/b") r := httptest.NewRequest(http.MethodPost, "/?%40libre.graph.conflictBehavior=rename", bytes.NewBuffer(driveItemJson)).WithContext(ctx) - // no CreatePath / CreateChild expectations: the provider must not be called + // no ResolvePath / CreateChild expectations: the provider must not be called drivesDriveItemApi.CreateChildDriveItem(w, r) Expect(w.Code).To(Equal(http.StatusBadRequest)) })