Skip to content

Sync-in · Sovereign platform for file storage, sharing, synchronization, and collaboration.

test(backend:webdav): improve coverage

johaven085bb44d5a43
diff --git a/backend/src/applications/webdav/decorators/if-header.decorator.ts b/backend/src/applications/webdav/decorators/if-header.decorator.ts
index ca275c09..cb7a66f7 100644
--- a/backend/src/applications/webdav/decorators/if-header.decorator.ts
+++ b/backend/src/applications/webdav/decorators/if-header.decorator.ts
@@ -13,7 +13,10 @@ export function IfHeaderDecorator() {
descriptor.value = async function (...args: any[]) {
const req: FastifyDAVRequest = args[0]
const res: FastifyReply = args[1]
- if (!(await this.evaluateIfHeaders(req, res))) return
+ if (!(await this.evaluateIfHeaders(req, res))) {
+ // if there is an error the response is generated inside the `evaluateIfHeaders` function
+ return
+ }
return await originalMethod.apply(this, args)
}
}
diff --git a/backend/src/applications/webdav/guards/webdav-protocol.guard.spec.ts b/backend/src/applications/webdav/guards/webdav-protocol.guard.spec.ts
new file mode 100644
index 00000000..ee22d603
--- /dev/null
+++ b/backend/src/applications/webdav/guards/webdav-protocol.guard.spec.ts
@@ -0,0 +1,511 @@
+import { HttpException, HttpStatus } from '@nestjs/common'
+import { Test, TestingModule } from '@nestjs/testing'
+import { FastifyReply } from 'fastify'
+import { urlToPath } from '../../../common/functions'
+import { decodeUrl } from '../../../common/shared'
+import { HTTP_METHOD } from '../../applications.constants'
+import { FilesLockManager } from '../../files/services/files-lock-manager.service'
+import { DEPTH, HEADER, LOCK_SCOPE, OPTIONS_HEADERS, PROPSTAT } from '../constants/webdav'
+import { FastifyDAVRequest } from '../interfaces/webdav.interface'
+import { PROPFIND_ALL_PROP } from '../utils/webdav'
+import { WebDAVProtocolGuard } from './webdav-protocol.guard'
+import * as IfHeaderUtils from '../utils/if-header'
+
+// Keep these mocks to control path transforms in COPY/MOVE tests
+jest.mock('../../../common/shared', () => ({
+ decodeUrl: jest.fn((s: string) => s)
+}))
+jest.mock('../../../common/functions', () => ({
+ urlToPath: jest.fn((s: string) => s)
+}))
+
+describe(WebDAVProtocolGuard.name, () => {
+ let guard: WebDAVProtocolGuard
+
+ const makeUser = (hasPerm = true) => ({
+ havePermission: jest.fn(() => hasPerm),
+ fullName: 'John Doe',
+ })
+
+ const makeRes = (): FastifyReply =>
+ ({
+ headers: jest.fn()
+ }) as unknown as FastifyReply
+
+ const baseReq = (method: string, overrides: Partial<FastifyDAVRequest> = {}): FastifyDAVRequest =>
+ ({
+ method,
+ headers: {},
+ // undefined body allows to hit the "allowed empty body" branch for PROPFIND/LOCK
+ body: undefined as any,
+ originalUrl: '/webdav/base/path',
+ protocol: 'http',
+ raw: { httpVersion: '1.1' } as any,
+ user: makeUser(),
+ ...overrides
+ }) as unknown as FastifyDAVRequest
+
+ const makeCtx = (req: FastifyDAVRequest, res: FastifyReply) =>
+ ({
+ switchToHttp: () => ({
+ getRequest: () => req,
+ getResponse: () => res
+ })
+ }) as any
+
+ const expectIfHeadersParsed = (req: FastifyDAVRequest) => {
+ expect(Array.isArray(req.dav.ifHeaders)).toBe(true)
+ expect(req.dav.ifHeaders.length).toBeGreaterThan(0)
+ }
+
+ beforeEach(async () => {
+ jest.clearAllMocks()
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [WebDAVProtocolGuard]
+ }).compile()
+
+ guard = module.get(WebDAVProtocolGuard)
+ })
+
+ describe('Permissions', () => {
+ it('allows OPTIONS even without WEBDAV permission (responds headers + 200)', async () => {
+ const req = baseReq(HTTP_METHOD.OPTIONS, { user: makeUser(false) as any })
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+
+ await expect(guard.canActivate(ctx)).rejects.toThrow(HttpException)
+ try {
+ await guard.canActivate(ctx)
+ } catch (e) {
+ const ex = e as HttpException
+ expect(res.headers).toHaveBeenCalledWith(OPTIONS_HEADERS)
+ expect(ex.getStatus()).toBe(HttpStatus.OK)
+ }
+ })
+
+ it('forbids non-OPTIONS when the user lacks WEBDAV permission', async () => {
+ const req = baseReq(HTTP_METHOD.GET, { user: makeUser(false) as any })
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+ await expect(guard.canActivate(ctx)).rejects.toMatchObject({ status: HttpStatus.FORBIDDEN })
+ })
+
+ it('falls through for a method not handled by the switch', async () => {
+ const req = baseReq('VIEW', {})
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+ const spy = jest.spyOn(guard as any, 'setDAVContext')
+
+ const result = await guard.canActivate(ctx)
+ expect(result).toBe(true)
+ expect(spy).toHaveBeenCalled()
+ spy.mockRestore()
+ })
+ })
+
+ describe('PROPFIND', () => {
+ it('defaults depth=1 (members) when header is missing, and sets ALLPROP with empty body', async () => {
+ const req = baseReq(HTTP_METHOD.PROPFIND, {
+ headers: {},
+ body: undefined
+ })
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+
+ await expect(guard.canActivate(ctx)).resolves.toBe(true)
+ expect(req.dav.url).toBe(req.originalUrl)
+ expect(req.dav.depth).toBe(DEPTH.MEMBERS)
+ expect(req.dav.body).toBe(PROPFIND_ALL_PROP)
+ expect(req.dav.propfindMode).toBe(PROPSTAT.ALLPROP)
+ expect(req.dav.ifHeaders === undefined || req.dav.ifHeaders.length === 0).toBe(true)
+ })
+
+ it.each([
+ { title: 'depth "infinity" normalized to 1 (members)', depth: DEPTH.INFINITY as any },
+ { title: 'invalid depth normalized to 1 (members)', depth: 'bad' as any }
+ ])('depth normalization: $title', async ({ depth }) => {
+ const req = baseReq(HTTP_METHOD.PROPFIND, {
+ headers: { [HEADER.DEPTH]: depth },
+ body: undefined
+ })
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+ await expect(guard.canActivate(ctx)).resolves.toBe(true)
+ expect(req.dav.depth).toBe(DEPTH.MEMBERS)
+ })
+
+ it('valid XML body with propname and parses If header', async () => {
+ const req = baseReq(HTTP_METHOD.PROPFIND, {
+ headers: { [HEADER.DEPTH]: DEPTH.RESOURCE, [HEADER.IF]: '(<urn:uuid:abc> ["W/\\"ETag\\""])' },
+ body: '<propfind xmlns="DAV:"><propname/></propfind>'
+ })
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+
+ await expect(guard.canActivate(ctx)).resolves.toBe(true)
+ expect(req.dav.depth).toBe(DEPTH.RESOURCE)
+ expect(req.dav.propfindMode).toBe(PROPSTAT.PROPNAME)
+ expectIfHeadersParsed(req)
+ })
+
+ it('invalid propfind mode -> 400', async () => {
+ const req = baseReq(HTTP_METHOD.PROPFIND, {
+ headers: {},
+ body: '<propfind xmlns="DAV:"><unknown/></propfind>'
+ })
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+ await expect(guard.canActivate(ctx)).rejects.toMatchObject({ status: HttpStatus.BAD_REQUEST })
+ })
+
+ it('invalid XML (with code) -> 400', async () => {
+ const req = baseReq(HTTP_METHOD.PROPFIND, {
+ headers: {},
+ body: '<bad'
+ } as any)
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+ await expect(guard.canActivate(ctx)).rejects.toMatchObject({ status: HttpStatus.BAD_REQUEST })
+ })
+
+ it('specific XML validation error handled -> 400', async () => {
+ const req = baseReq(HTTP_METHOD.PROPFIND, {
+ headers: {},
+ body: 'this is not XML at all'
+ })
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+ await expect(guard.canActivate(ctx)).rejects.toHaveProperty('status', HttpStatus.BAD_REQUEST)
+ })
+
+ it('skips body when parseBody returns false, still parses If header', async () => {
+ const spyParse = jest.spyOn(guard as any, 'parseBody').mockReturnValue(false as any)
+ const req = baseReq(HTTP_METHOD.PROPFIND, {
+ headers: { [HEADER.IF]: '(<urn:uuid:abc>)' },
+ body: undefined
+ })
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+
+ try {
+ await expect(guard.canActivate(ctx)).resolves.toBe(true)
+ expect(req.dav.body).toBeUndefined()
+ expect(req.dav.propfindMode).toBeUndefined()
+ expectIfHeadersParsed(req)
+ } finally {
+ spyParse.mockRestore()
+ }
+ })
+ })
+
+ describe('PROPPATCH', () => {
+ it('requires "propertyupdate" in body', async () => {
+ const req = baseReq(HTTP_METHOD.PROPPATCH, {
+ headers: {},
+ body: '<xml/>'
+ })
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+ await expect(guard.canActivate(ctx)).rejects.toMatchObject({ status: HttpStatus.BAD_REQUEST })
+ })
+
+ it('valid body and parses If header', async () => {
+ const req = baseReq(HTTP_METHOD.PROPPATCH, {
+ headers: { [HEADER.IF]: '(<urn:uuid:abc>)', [HEADER.DEPTH]: DEPTH.RESOURCE },
+ body: '<propertyupdate xmlns="DAV:"><set/></propertyupdate>'
+ })
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+ await expect(guard.canActivate(ctx)).resolves.toBe(true)
+ expect(req.dav.depth).toBe(DEPTH.RESOURCE)
+ expectIfHeadersParsed(req)
+ })
+ })
+
+ describe('LOCK', () => {
+ it('timeout=Infinite -> default timeout, owner from string, depth=resource', async () => {
+ const req = baseReq(HTTP_METHOD.LOCK, {
+ headers: { [HEADER.TIMEOUT]: 'Infinite', [HEADER.DEPTH]: DEPTH.RESOURCE },
+ body: '<lockinfo xmlns="DAV:"><lockscope><exclusive/></lockscope><owner>Custom Owner</owner></lockinfo>'
+ })
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+ await expect(guard.canActivate(ctx)).resolves.toBe(true)
+ expect(req.dav.lock.timeout).toBe(FilesLockManager.defaultLockTimeoutSeconds)
+ expect(req.dav.lock.lockscope).toBe(LOCK_SCOPE.EXCLUSIVE)
+ expect(req.dav.lock.owner).toContain('Custom Owner')
+ expect(req.dav.depth).toBe(DEPTH.RESOURCE)
+ })
+
+ it('timeout Second-10 + non-string owner -> default WebDAV owner, depth=infinity', async () => {
+ const req = baseReq(HTTP_METHOD.LOCK, {
+ headers: { [HEADER.TIMEOUT]: 'Second-10', [HEADER.DEPTH]: DEPTH.INFINITY },
+ body: '<lockinfo xmlns="DAV:"><lockscope><shared/></lockscope><owner><href>me</href></owner></lockinfo>'
+ })
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+ await expect(guard.canActivate(ctx)).resolves.toBe(true)
+ expect(req.dav.lock.timeout).toBe(10)
+ expect(req.dav.lock.lockscope).toBe(LOCK_SCOPE.SHARED)
+ expect(req.dav.lock.owner).toMatch(/^WebDAV - /)
+ expect(req.dav.depth).toBe(DEPTH.INFINITY)
+ })
+
+ it('clamps timeout Second-N to default when N exceeds default', async () => {
+ const big = FilesLockManager.defaultLockTimeoutSeconds + 1000
+ const req = baseReq(HTTP_METHOD.LOCK, {
+ headers: { [HEADER.TIMEOUT]: `Second-${big}` },
+ body: '<lockinfo xmlns="DAV:"><lockscope><exclusive/></lockscope></lockinfo>'
+ })
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+ await expect(guard.canActivate(ctx)).resolves.toBe(true)
+ expect(req.dav.lock.timeout).toBe(FilesLockManager.defaultLockTimeoutSeconds)
+ })
+
+ it('invalid timeout -> NaN (no fallback), depth=infinity', async () => {
+ const req = baseReq(HTTP_METHOD.LOCK, {
+ headers: { [HEADER.TIMEOUT]: 'Bad-Token', [HEADER.DEPTH]: 'x' as any },
+ body: '<lockinfo xmlns="DAV:"><lockscope><exclusive/></lockscope></lockinfo>'
+ })
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+ await expect(guard.canActivate(ctx)).resolves.toBe(true)
+ expect(Number.isNaN(req.dav.lock.timeout)).toBe(true)
+ expect(req.dav.depth).toBe(DEPTH.INFINITY)
+ })
+
+ it('handles parseInt exception during timeout parsing', async () => {
+ const req = baseReq(HTTP_METHOD.LOCK, {
+ headers: { [HEADER.TIMEOUT]: 'Second-' },
+ body: '<lockinfo xmlns="DAV:"><lockscope><exclusive/></lockscope></lockinfo>'
+ })
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+
+ const originalParseInt = global.parseInt
+ global.parseInt = jest.fn().mockImplementation(() => {
+ throw new Error('Forced parseInt error')
+ })
+
+ try {
+ await expect(guard.canActivate(ctx)).resolves.toBe(true)
+ expect(req.dav.lock).toBeDefined()
+ } finally {
+ global.parseInt = originalParseInt
+ }
+ })
+
+ it('timeout Infinite + empty IfHeader -> default timeout and ifHeaders undefined', async () => {
+ const spyIf = jest.spyOn(IfHeaderUtils, 'parseIfHeader').mockReturnValue([] as any)
+ const req = baseReq(HTTP_METHOD.LOCK, {
+ headers: { [HEADER.TIMEOUT]: 'Infinite', [HEADER.IF]: '(<any>)' },
+ body: '<lockinfo xmlns="DAV:"><lockscope><exclusive/></lockscope></lockinfo>'
+ })
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+
+ try {
+ await expect(guard.canActivate(ctx)).resolves.toBe(true)
+ expect(req.dav.lock.timeout).toBe(FilesLockManager.defaultLockTimeoutSeconds)
+ expect(req.dav.ifHeaders).toBeUndefined()
+ } finally {
+ spyIf.mockRestore()
+ }
+ })
+
+ it('missing lockinfo -> 400', async () => {
+ const req = baseReq(HTTP_METHOD.LOCK, {
+ headers: {},
+ body: '<notlockinfo xmlns="DAV:"/>'
+ })
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+ await expect(guard.canActivate(ctx)).rejects.toMatchObject({ status: HttpStatus.BAD_REQUEST })
+ })
+
+ it('invalid lockscope -> 400', async () => {
+ const req = baseReq(HTTP_METHOD.LOCK, {
+ headers: {},
+ body: '<lockinfo xmlns="DAV:"><lockscope><invalid/></lockscope></lockinfo>'
+ })
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+ await expect(guard.canActivate(ctx)).rejects.toMatchObject({ status: HttpStatus.BAD_REQUEST })
+ })
+
+ it('handles Object.keys(lockscope) exception with malformed lockscope -> 400', async () => {
+ const req = baseReq(HTTP_METHOD.LOCK, {
+ headers: {},
+ body: '<lockinfo xmlns="DAV:"><lockscope><exclusive/></lockscope></lockinfo>'
+ })
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+
+ jest.spyOn(guard as any, 'parseBody').mockImplementation(() => {
+ req.dav.body = {
+ lockinfo: {
+ lockscope: null
+ }
+ }
+ return true
+ })
+
+ await expect(guard.canActivate(ctx)).rejects.toMatchObject({
+ status: HttpStatus.BAD_REQUEST,
+ message: 'Invalid or undefined lockscope'
+ })
+ })
+
+ it('refresh (no body) -> dav.depth = null', async () => {
+ const req = baseReq(HTTP_METHOD.LOCK, {
+ headers: { [HEADER.DEPTH]: DEPTH.RESOURCE },
+ body: undefined
+ })
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+ await expect(guard.canActivate(ctx)).resolves.toBe(true)
+ expect(req.dav.depth).toBeNull()
+ })
+
+ it('no timeout header -> lock.timeout is undefined', async () => {
+ const req = baseReq(HTTP_METHOD.LOCK, {
+ headers: {},
+ body: '<lockinfo xmlns="DAV:"><lockscope><exclusive/></lockscope></lockinfo>'
+ })
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+ await expect(guard.canActivate(ctx)).resolves.toBe(true)
+ expect(req.dav.lock).toBeDefined()
+ expect(req.dav.lock.timeout).toBeUndefined()
+ })
+ })
+
+ describe('UNLOCK', () => {
+ it('missing lock-token -> 400', async () => {
+ const req = baseReq(HTTP_METHOD.UNLOCK)
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+ await expect(guard.canActivate(ctx)).rejects.toMatchObject({ status: HttpStatus.BAD_REQUEST })
+ })
+
+ it('sets token in dav.lock and parses If header', async () => {
+ const req = baseReq(HTTP_METHOD.UNLOCK, {
+ headers: { [HEADER.LOCK_TOKEN]: ' <abc> ', [HEADER.IF]: '(<urn:uuid:abc>)' }
+ })
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+ await expect(guard.canActivate(ctx)).resolves.toBe(true)
+ expect(req.dav.lock.token).toBe('abc')
+ expectIfHeadersParsed(req)
+ })
+ })
+
+ describe('PUT / DELETE', () => {
+ it('PUT: depth=0 and parses If header', async () => {
+ const req = baseReq(HTTP_METHOD.PUT, {
+ headers: { [HEADER.IF]: '(<urn:uuid:abc>)' }
+ })
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+ await expect(guard.canActivate(ctx)).resolves.toBe(true)
+ expect(req.dav.depth).toBe(DEPTH.RESOURCE)
+ expectIfHeadersParsed(req)
+ })
+
+ it('DELETE: parses If header', async () => {
+ const req = baseReq(HTTP_METHOD.DELETE, {
+ headers: { [HEADER.IF]: '(<urn:uuid:abc>)' }
+ })
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+ await expect(guard.canActivate(ctx)).resolves.toBe(true)
+ expectIfHeadersParsed(req)
+ })
+ })
+
+ describe('MKCOL', () => {
+ it('non-zero content-length -> 415', async () => {
+ const req = baseReq(HTTP_METHOD.MKCOL, {
+ headers: { 'content-length': '3' }
+ } as any)
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+ await expect(guard.canActivate(ctx)).rejects.toMatchObject({ status: HttpStatus.UNSUPPORTED_MEDIA_TYPE })
+ })
+
+ it('zero/absent content-length -> depth=0 and parses If header', async () => {
+ const req = baseReq(HTTP_METHOD.MKCOL, {
+ headers: { 'content-length': '0', [HEADER.IF]: '(<urn:uuid:abc>)' } as any
+ })
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+ await expect(guard.canActivate(ctx)).resolves.toBe(true)
+ expect(req.dav.depth).toBe(DEPTH.RESOURCE)
+ expectIfHeadersParsed(req)
+ })
+ })
+
+ describe('COPY / MOVE', () => {
+ it('COPY: missing Destination -> 400', async () => {
+ const req = baseReq(HTTP_METHOD.COPY)
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+ await expect(guard.canActivate(ctx)).rejects.toMatchObject({ status: HttpStatus.BAD_REQUEST })
+ })
+
+ it('COPY: invalid Destination base path -> 400', async () => {
+ ;(decodeUrl as jest.Mock).mockImplementation((s: string) => s)
+ ;(urlToPath as jest.Mock).mockImplementation((s: string) => '/not-webdav' + s)
+
+ const req = baseReq(HTTP_METHOD.COPY, {
+ headers: { [HEADER.DESTINATION]: '/wrong' }
+ })
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+ await expect(guard.canActivate(ctx)).rejects.toMatchObject({ status: HttpStatus.BAD_REQUEST })
+ })
+
+ it('COPY: valid Destination -> overwrite=true, move=false, depth=infinity and parses If header', async () => {
+ ;(decodeUrl as jest.Mock).mockImplementation((s: string) => s)
+ ;(urlToPath as jest.Mock).mockImplementation((_s: string) => '/webdav/base/path/target')
+
+ const req = baseReq(HTTP_METHOD.COPY, {
+ headers: { [HEADER.DESTINATION]: '/webdav/base/path/target', [HEADER.IF]: '(<urn:uuid:abc>)' }
+ })
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+ await expect(guard.canActivate(ctx)).resolves.toBe(true)
+ expect(req.dav.depth).toBe(DEPTH.INFINITY)
+ expect(req.dav.copyMove).toEqual({
+ overwrite: true,
+ destination: '/webdav/base/path/target',
+ isMove: false
+ })
+ expectIfHeadersParsed(req)
+ })
+
+ it('MOVE: isMove=true and overwrite=false when OVERWRITE header is "f", respects depth header', async () => {
+ ;(decodeUrl as jest.Mock).mockImplementation((s: string) => s)
+ ;(urlToPath as jest.Mock).mockImplementation((_s: string) => '/webdav/base/path/target2')
+
+ const req = baseReq(HTTP_METHOD.MOVE, {
+ headers: {
+ [HEADER.DESTINATION]: '/webdav/base/path/target2',
+ [HEADER.OVERWRITE]: 'f',
+ [HEADER.DEPTH]: DEPTH.RESOURCE
+ }
+ })
+ const res = makeRes()
+ const ctx = makeCtx(req, res)
+ await expect(guard.canActivate(ctx)).resolves.toBe(true)
+ expect(req.dav.depth).toBe(DEPTH.RESOURCE)
+ expect(req.dav.copyMove).toEqual({
+ overwrite: false,
+ destination: '/webdav/base/path/target2',
+ isMove: true
+ })
+ })
+ })
+})
diff --git a/backend/src/applications/webdav/guards/webdav-protocol.guard.ts b/backend/src/applications/webdav/guards/webdav-protocol.guard.ts
index 9420c95d..0914daca 100644
--- a/backend/src/applications/webdav/guards/webdav-protocol.guard.ts
+++ b/backend/src/applications/webdav/guards/webdav-protocol.guard.ts
@@ -39,8 +39,9 @@ export class WebDAVProtocolGuard implements CanActivate {
this.setDAVContext(req)
switch (req.method) {
case HTTP_METHOD.OPTIONS:
- this.optionsMethod(res)
- break
+ // hook to stop propagation and return headers on all webdav routes
+ res.headers(OPTIONS_HEADERS)
+ throw new HttpException(null, HttpStatus.OK)
case HTTP_METHOD.PROPFIND:
return this.propfindMethod(req)
case HTTP_METHOD.LOCK:
@@ -108,12 +109,6 @@ export class WebDAVProtocolGuard implements CanActivate {
}
}
- private optionsMethod(res: FastifyReply) {
- // hook to return headers on all webdav routes
- res.headers(OPTIONS_HEADERS)
- throw new HttpException(null, HttpStatus.OK)
- }
-
private propfindMethod(req: FastifyDAVRequest) {
req.dav.depth = (req.headers[HEADER.DEPTH] as string | undefined)?.toLowerCase()
if (!req.dav.depth || (req.dav.depth !== DEPTH.MEMBERS && req.dav.depth !== DEPTH.RESOURCE)) {
diff --git a/backend/src/applications/webdav/services/webdav-methods.service.spec.ts b/backend/src/applications/webdav/services/webdav-methods.service.spec.ts
index e0af66d8..82db7828 100644
--- a/backend/src/applications/webdav/services/webdav-methods.service.spec.ts
+++ b/backend/src/applications/webdav/services/webdav-methods.service.spec.ts
@@ -10,6 +10,7 @@ import { FilesLockManager } from '../../files/services/files-lock-manager.servic
import { FilesManager } from '../../files/services/files-manager.service'
import { dirName, isPathExists } from '../../files/utils/files'
import { SPACE_REPOSITORY } from '../../spaces/constants/spaces'
+import * as PathsUtils from '../../spaces/utils/paths'
import { haveSpaceEnvPermissions } from '../../spaces/utils/permissions'
import { STANDARD_PROPS } from '../constants/webdav'
import * as IfHeaderUtils from '../utils/if-header'
@@ -25,6 +26,15 @@ jest.mock('../../spaces/utils/permissions', () => ({
haveSpaceEnvPermissions: jest.fn()
}))
+jest.mock('../../spaces/utils/paths', () => {
+ const actual = jest.requireActual('../../spaces/utils/paths')
+ return { ...actual, dbFileFromSpace: jest.fn() }
+})
+
+jest.mock('../decorators/if-header.decorator', () => ({
+ IfHeaderDecorator: () => (_target?: any, _key?: string, _desc?: any) => undefined
+}))
+
describe(WebDAVMethods.name, () => {
let service: WebDAVMethods
let filesManager: {
@@ -472,26 +482,21 @@ describe(WebDAVMethods.name, () => {
})
describe('put', () => {
- it('returns 204 when file existed and sets etag header', async () => {
- filesManager.saveStream.mockResolvedValue(true)
+ it.each([
+ { existed: true, expected: HttpStatus.NO_CONTENT, checkEtag: true },
+ { existed: false, expected: HttpStatus.CREATED, checkEtag: false }
+ ])('returns correct status for PUT when existed=%s', async ({ existed, expected, checkEtag }) => {
+ filesManager.saveStream.mockResolvedValue(existed)
const req = baseReq({ method: 'PUT' })
const res = makeRes()
const result = await service.put(req, res)
- expect(result).toBe(res)
- expect(res.headers['etag']).toBeDefined()
- expect(res.statusCode).toBe(HttpStatus.NO_CONTENT)
- })
-
- it('returns 201 when file did not exist', async () => {
- filesManager.saveStream.mockResolvedValue(false)
- const req = baseReq({ method: 'PUT' })
- const res = makeRes()
-
- await service.put(req, res)
-
- expect(res.statusCode).toBe(HttpStatus.CREATED)
+ if (checkEtag) {
+ expect(res.headers['etag']).toBeDefined()
+ expect(result).toBe(res)
+ }
+ expect(res.statusCode).toBe(expected)
})
it('delegates errors to handleError', async () => {
@@ -828,6 +833,30 @@ describe(WebDAVMethods.name, () => {
expect(result).toBeUndefined()
})
+ it('aborts with 412 when destination If-Header haveLock mismatches', async () => {
+ const handler = (service as any)['webDAVHandler']
+ const dstSpace = { ...baseReq().space, url: '/dst', realPath: '/real/dst', dbFile: { path: 'dst' } }
+ jest.spyOn(handler, 'spaceEnv').mockResolvedValue(dstSpace)
+ ;(isPathExists as jest.Mock).mockResolvedValue(true)
+ filesLockManager.getLocksByPath.mockResolvedValue([{}]) // there is a lock, but mustMatch=false -> mismatch
+
+ const req = baseReq({
+ method: 'COPY',
+ dav: {
+ ...baseReq().dav,
+ copyMove: { destination: '/dst', isMove: false, overwrite: true },
+ ifHeaders: [{ path: '/dst', haveLock: { mustMatch: false } }]
+ }
+ })
+ const res = makeRes()
+
+ const result = await service.copyMove(req, res)
+
+ expect(result).toBeUndefined()
+ expect(res.statusCode).toBe(HttpStatus.PRECONDITION_FAILED)
+ expect(res.body).toBe('If header condition failed')
+ })
+
it('returns 204 when destination existed; 201 when not', async () => {
const handler = (service as any)['webDAVHandler']
jest.spyOn(handler, 'spaceEnv').mockResolvedValue({ ...baseReq().space, url: '/dst', realPath: '/real/dst', dbFile: { path: 'dst' } })
@@ -876,58 +905,80 @@ describe(WebDAVMethods.name, () => {
// Verify the log message includes an arrow to the destination (toUrl)
expect(logSpy).toHaveBeenCalledWith(expect.stringContaining(' -> /dst'))
})
- })
-
- describe('evaluateIfHeaders', () => {
- it('returns true when no headers', async () => {
- const req = baseReq({ dav: { ...baseReq().dav, ifHeaders: undefined } })
- const res = makeRes()
-
- const ok = await (service as any).evaluateIfHeaders(req, res)
-
- expect(ok).toBe(true)
- })
- it('fails with 412 on haveLock mismatch', async () => {
+ it('returns early when evaluateIfHeaders returns false (explicit spy)', async () => {
const req = baseReq({
+ method: 'COPY',
dav: {
...baseReq().dav,
- ifHeaders: [{ haveLock: { mustMatch: true } }]
+ copyMove: { destination: '/dst', isMove: false, overwrite: true },
+ ifHeaders: [{ path: '/dst' }]
}
})
const res = makeRes()
- filesLockManager.getLocksByPath.mockResolvedValue([])
+ const handler = (service as any)['webDAVHandler']
+ // Ensure destination space resolves so we reach the evaluateIfHeaders call
+ jest.spyOn(handler, 'spaceEnv').mockResolvedValue({ ...req.space, url: '/dst', realPath: '/real/dst', dbFile: { path: 'dst' } })
+ ;(isPathExists as jest.Mock).mockResolvedValue(true)
+ // Decorator is no-op (mocked), so copyMove calls evaluateIfHeaders once for destination: force it to return false
+ const spy = jest.spyOn<any, any>(service as any, 'evaluateIfHeaders').mockResolvedValue(false)
- const ok = await (service as any).evaluateIfHeaders(req, res)
+ const result = await service.copyMove(req, res as any)
- expect(ok).toBe(false)
- expect(res.statusCode).toBe(HttpStatus.PRECONDITION_FAILED)
+ expect(spy).toHaveBeenCalledTimes(1)
+ expect(result).toBeUndefined()
+ expect(filesManager.copyMove).not.toHaveBeenCalled()
})
+ })
- it('fails with 412 on token not found', async () => {
- const req = baseReq({
- dav: {
- ...baseReq().dav,
- ifHeaders: [{ token: { value: 'missing', mustMatch: true } }]
- }
- })
+ describe('evaluateIfHeaders', () => {
+ it('returns true when no headers', async () => {
+ const req = baseReq({ dav: { ...baseReq().dav, ifHeaders: undefined } })
const res = makeRes()
- filesLockManager.getLockByToken.mockResolvedValue(null)
const ok = await (service as any).evaluateIfHeaders(req, res)
- expect(ok).toBe(false)
- expect(res.statusCode).toBe(HttpStatus.PRECONDITION_FAILED)
+ expect(ok).toBe(true)
})
- it('fails with 412 on etag mismatch', async () => {
- ;(isPathExists as jest.Mock).mockResolvedValue(true)
- const req = baseReq({
- dav: {
- ...baseReq().dav,
- ifHeaders: [{ etag: { value: 'W/"bad"', mustMatch: true } }]
+ const negativeIfHeaderCases = [
+ {
+ name: 'haveLock mismatch',
+ dav: { ifHeaders: [{ haveLock: { mustMatch: true } }] },
+ setup: async () => {
+ // No lock present => match=false, mustMatch=true => mismatch
+ ;(PathsUtils.dbFileFromSpace as unknown as jest.Mock).mockReturnValue({ path: 'file.txt', spaceId: 1, inTrash: false })
+ filesLockManager.getLocksByPath.mockResolvedValue([])
}
- })
+ },
+ {
+ name: 'haveLock mismatch when locks exist but mustMatch=false',
+ dav: { ifHeaders: [{ haveLock: { mustMatch: false } }] },
+ setup: async () => {
+ // Lock present => match=true, mustMatch=false => mismatch
+ ;(PathsUtils.dbFileFromSpace as unknown as jest.Mock).mockReturnValue({ path: 'dst', spaceId: 1, inTrash: false })
+ filesLockManager.getLocksByPath.mockResolvedValue([{}])
+ }
+ },
+ {
+ name: 'token not found',
+ dav: { ifHeaders: [{ token: { value: 'missing', mustMatch: true } }] },
+ setup: async () => {
+ filesLockManager.getLockByToken.mockResolvedValue(null)
+ }
+ },
+ {
+ name: 'etag mismatch',
+ dav: { ifHeaders: [{ etag: { value: 'W/"bad"', mustMatch: true } }] },
+ setup: async () => {
+ ;(isPathExists as jest.Mock).mockResolvedValue(true)
+ }
+ }
+ ] as const
+
+ it.each(negativeIfHeaderCases)('fails with 412 on %s', async ({ dav, setup }) => {
+ await setup()
+ const req = baseReq({ dav: { ...baseReq().dav, ...dav } })
const res = makeRes()
const ok = await (service as any).evaluateIfHeaders(req, res)
@@ -1047,24 +1098,27 @@ describe(WebDAVMethods.name, () => {
})
describe('lockRefresh', () => {
- it('returns 400 when more than one or zero tokens in If header', async () => {
- const req = baseReq({ dav: { ...baseReq().dav, body: undefined, ifHeaders: [] } })
- const res = makeRes()
-
- await (service as any).lockRefresh(req, res, req.space.dbFile.path)
-
- expect(res.statusCode).toBe(HttpStatus.BAD_REQUEST)
- expect(res.body).toContain('Expected a lock token')
- })
+ const refresh400Cases = [
+ {
+ name: 'more than one or zero tokens in If header',
+ dav: { body: undefined, ifHeaders: [] },
+ expectMsg: 'Expected a lock token'
+ },
+ {
+ name: 'token extraction fails',
+ dav: { body: undefined, ifHeaders: [{ notAToken: true }] },
+ expectMsg: 'Unable to extract token'
+ }
+ ] as const
- it('returns 400 when token extraction fails', async () => {
- const req = baseReq({ dav: { ...baseReq().dav, body: undefined, ifHeaders: [{ notAToken: true }] } })
+ it.each(refresh400Cases)('returns 400 when %s', async ({ dav, expectMsg }) => {
+ const req = baseReq({ dav: { ...baseReq().dav, ...dav } })
const res = makeRes()
await (service as any).lockRefresh(req, res, req.space.dbFile.path)
expect(res.statusCode).toBe(HttpStatus.BAD_REQUEST)
- expect(res.body).toContain('Unable to extract token')
+ expect(res.body).toContain(expectMsg)
})
it('returns 412 when token not found or not matching URL', async () => {
diff --git a/backend/src/applications/webdav/webdav.controller.ts b/backend/src/applications/webdav/webdav.controller.ts
index 728a6c05..ac21f6d1 100644
--- a/backend/src/applications/webdav/webdav.controller.ts
+++ b/backend/src/applications/webdav/webdav.controller.ts
@@ -21,7 +21,7 @@ export class WebDAVController {
@Options()
serverOptions() {
- // OPTIONS method is handled in the `DavProtocolGuard`
+ // OPTIONS method is handled in the `DavProtocolGuard`, return empty response with headers
return
}
@@ -32,7 +32,7 @@ export class WebDAVController {
@Options(WEBDAV_BASE_PATH)
webdavOptions() {
- // OPTIONS method is handled in the `DavProtocolGuard`
+ // OPTIONS method is handled in the `DavProtocolGuard`, return empty response with headers
return
}