Skip to content

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

feat(backend:files): prevent file mutations in trash repository

johaven738402c13acb
diff --git a/backend/src/applications/files/editors/collabora-online/collabora-online-manager.service.spec.ts b/backend/src/applications/files/editors/collabora-online/collabora-online-manager.service.spec.ts
index dd4a778d..029e45dd 100644
--- a/backend/src/applications/files/editors/collabora-online/collabora-online-manager.service.spec.ts
+++ b/backend/src/applications/files/editors/collabora-online/collabora-online-manager.service.spec.ts
@@ -164,6 +164,19 @@ describe(CollaboraOnlineManager.name, () => {
expect(filesLockManager.checkConflicts).not.toHaveBeenCalled()
})
+ it('should return view mode when document is in trash repository', async () => {
+ const trashSpace = {
+ ...mockSpace,
+ envPermissions: SPACE_OPERATION.MODIFY,
+ inTrashRepository: true
+ } as unknown as SpaceEnv
+
+ const result = await service.getSettings(mockUser, trashSpace)
+
+ expect(result.mode).toBe(FILE_MODE.VIEW)
+ expect(filesLockManager.checkConflicts).not.toHaveBeenCalled()
+ })
+
it('should throw error when document extension is not supported', async () => {
const spaceWithUnsupportedFile = {
...mockSpace,
@@ -261,6 +274,32 @@ describe(CollaboraOnlineManager.name, () => {
expect(result.UserCanWrite).toBe(false)
})
+
+ it('should set UserCanWrite to false when document is in trash repository', async () => {
+ const mockStats = {
+ size: 1024,
+ mtime: new Date('2024-01-01T10:00:00Z')
+ }
+
+ const mockRequest = {
+ user: mockUser,
+ space: {
+ ...mockSpace,
+ envPermissions: SPACE_OPERATION.MODIFY,
+ inTrashRepository: true
+ }
+ } as unknown as FastifyCollaboraOnlineSpaceRequest
+
+ jest.spyOn(fs, 'stat').mockResolvedValue(mockStats as any)
+ jest.spyOn(filesUtils, 'fileName').mockReturnValue('document.docx')
+ jest.spyOn(filesUtils, 'genEtag').mockReturnValue('etag-123')
+ const { getAvatarBase64 } = await import('../../../users/utils/avatar')
+ ;(getAvatarBase64 as jest.Mock).mockResolvedValue('base64-avatar')
+
+ const result = await service.checkFileInfo(mockRequest)
+
+ expect(result.UserCanWrite).toBe(false)
+ })
})
describe('saveDocument', () => {
diff --git a/backend/src/applications/files/editors/collabora-online/collabora-online-manager.service.ts b/backend/src/applications/files/editors/collabora-online/collabora-online-manager.service.ts
index e49502c5..49009b00 100644
--- a/backend/src/applications/files/editors/collabora-online/collabora-online-manager.service.ts
+++ b/backend/src/applications/files/editors/collabora-online/collabora-online-manager.service.ts
@@ -7,9 +7,8 @@ import path from 'node:path'
import { convertHumanTimeToSeconds } from '../../../../common/functions'
import { configuration } from '../../../../configuration/config.environment'
import { ContextManager } from '../../../../infrastructure/context/services/context-manager.service'
-import { SPACE_OPERATION } from '../../../spaces/constants/spaces'
import type { SpaceEnv } from '../../../spaces/models/space-env.model'
-import { haveSpaceEnvPermissions } from '../../../spaces/utils/permissions'
+import { canModifySpaceEnv } from '../../../spaces/utils/permissions'
import type { UserModel } from '../../../users/models/user.model'
import { getAvatarBase64 } from '../../../users/utils/avatar'
import { DEPTH, LOCK_SCOPE } from '../../../webdav/constants/webdav'
@@ -64,7 +63,7 @@ export class CollaboraOnlineManager {
throw new HttpException('Document not supported', HttpStatus.BAD_REQUEST)
}
let hasLock: false | FileLockProps = false
- let mode: FILE_MODE = haveSpaceEnvPermissions(space, SPACE_OPERATION.MODIFY) ? FILE_MODE.EDIT : FILE_MODE.VIEW
+ let mode: FILE_MODE = canModifySpaceEnv(space) ? FILE_MODE.EDIT : FILE_MODE.VIEW
if (mode === FILE_MODE.EDIT) {
// Check lock conflicts
try {
@@ -101,7 +100,7 @@ export class CollaboraOnlineManager {
ReadOnly: false,
UserExtraInfo: { avatar: await getAvatarBase64(req.user.login) },
UserCanNotWriteRelative: true,
- UserCanWrite: haveSpaceEnvPermissions(req.space, SPACE_OPERATION.MODIFY),
+ UserCanWrite: canModifySpaceEnv(req.space),
UserCanRename: false,
SupportsUpdate: true,
SupportsRename: false,
diff --git a/backend/src/applications/files/editors/only-office/only-office-manager.service.spec.ts b/backend/src/applications/files/editors/only-office/only-office-manager.service.spec.ts
index 149a25d8..42143974 100644
--- a/backend/src/applications/files/editors/only-office/only-office-manager.service.spec.ts
+++ b/backend/src/applications/files/editors/only-office/only-office-manager.service.spec.ts
@@ -195,6 +195,19 @@ describe(OnlyOfficeManager.name, () => {
expect(result.config.document.permissions.edit).toBe(false)
})
+ it('should set mode to VIEW when document is in trash repository', async () => {
+ const trashSpaceEnv = {
+ ...mockSpaceEnv,
+ inTrashRepository: true
+ } as unknown as SpaceEnv
+
+ const result = await service.getSettings(mockUser, trashSpaceEnv, mockRequest)
+
+ expect(result.config.editorConfig.mode).toBe(FILE_MODE.VIEW)
+ expect(result.config.document.permissions.edit).toBe(false)
+ expect(filesLockManager.checkConflicts).not.toHaveBeenCalled()
+ })
+
it('should detect mobile user agent', async () => {
const mobileRequest = {
headers: {
diff --git a/backend/src/applications/files/editors/only-office/only-office-manager.service.ts b/backend/src/applications/files/editors/only-office/only-office-manager.service.ts
index ef6c7fce..96ed217d 100644
--- a/backend/src/applications/files/editors/only-office/only-office-manager.service.ts
+++ b/backend/src/applications/files/editors/only-office/only-office-manager.service.ts
@@ -13,10 +13,9 @@ import { configuration } from '../../../../configuration/config.environment'
import { Cache } from '../../../../infrastructure/cache/services/cache.service'
import { ContextManager } from '../../../../infrastructure/context/services/context-manager.service'
import { HTTP_METHOD } from '../../../applications.constants'
-import { SPACE_OPERATION } from '../../../spaces/constants/spaces'
import { FastifySpaceRequest } from '../../../spaces/interfaces/space-request.interface'
import type { SpaceEnv } from '../../../spaces/models/space-env.model'
-import { haveSpaceEnvPermissions } from '../../../spaces/utils/permissions'
+import { canModifySpaceEnv } from '../../../spaces/utils/permissions'
import type { UserModel } from '../../../users/models/user.model'
import { getAvatarBase64 } from '../../../users/utils/avatar'
import { DEPTH, LOCK_SCOPE } from '../../../webdav/constants/webdav'
@@ -81,7 +80,7 @@ export class OnlyOfficeManager {
throw new HttpException('Document not supported', HttpStatus.BAD_REQUEST)
}
let hasLock: false | FileLockProps = false
- let mode: FILE_MODE = haveSpaceEnvPermissions(space, SPACE_OPERATION.MODIFY) ? FILE_MODE.EDIT : FILE_MODE.VIEW
+ let mode: FILE_MODE = canModifySpaceEnv(space) ? FILE_MODE.EDIT : FILE_MODE.VIEW
if (mode === FILE_MODE.EDIT) {
// Check lock conflicts
try {
diff --git a/backend/src/applications/files/services/files-manager.service.spec.ts b/backend/src/applications/files/services/files-manager.service.spec.ts
index ff6373e1..440b669c 100644
--- a/backend/src/applications/files/services/files-manager.service.spec.ts
+++ b/backend/src/applications/files/services/files-manager.service.spec.ts
@@ -77,6 +77,47 @@ describe(FilesManager.name, () => {
;(filesUtils.isPathExists as jest.Mock).mockImplementation(async (p: string) => (p in values ? values[p] : fallback))
}
+ const makeTrashSpace = (overrides: Record<string, any> = {}) =>
+ makeSpace({
+ repository: 'trash',
+ url: 'trash/personal/file.txt',
+ realPath: '/data/users/john/trash/file.txt',
+ realBasePath: '/data/users/john/trash',
+ dbFile: { ownerId: 7, path: 'file.txt', inTrash: true },
+ inTrashRepository: true,
+ ...overrides
+ })
+
+ const createArchiveMock = () => {
+ const archive = new PassThrough() as PassThrough & {
+ directory: jest.Mock
+ file: jest.Mock
+ finalize: jest.Mock
+ }
+ archive.directory = jest.fn().mockReturnValue(archive)
+ archive.file = jest.fn().mockReturnValue(archive)
+ archive.finalize = jest.fn().mockImplementation(async () => {
+ archive.end()
+ })
+ ;(archiver as unknown as jest.Mock).mockReturnValueOnce(archive as any)
+ jest.spyOn(fs, 'createWriteStream').mockReturnValue(new PassThrough() as any)
+ return archive
+ }
+
+ const expectNoWriteOperations = () => {
+ expect(filesUtils.writeFromStream).not.toHaveBeenCalled()
+ expect(filesUtils.writeFromStreamAndChecksum).not.toHaveBeenCalled()
+ expect(filesUtils.makeDir).not.toHaveBeenCalled()
+ expect(filesUtils.createEmptyFile).not.toHaveBeenCalled()
+ expect(filesUtils.copyFileContent).not.toHaveBeenCalled()
+ expect(filesUtils.copyFiles).not.toHaveBeenCalled()
+ expect(filesUtils.moveFiles).not.toHaveBeenCalled()
+ expect(filesUtils.removeFiles).not.toHaveBeenCalled()
+ expect(filesLockManager.create).not.toHaveBeenCalled()
+ expect(filesLockManager.createOrRefresh).not.toHaveBeenCalled()
+ expect(filesLockManager.checkConflicts).not.toHaveBeenCalled()
+ }
+
beforeEach(async () => {
http = { axiosRef: jest.fn() }
filesQueries = {
@@ -153,373 +194,478 @@ describe(FilesManager.name, () => {
expect(sendFile).toBeInstanceOf(SendFile)
})
- it('saveStream should reject POST when resource already exists', async () => {
- const space = makeSpace()
- setPathExists({ [space.realPath]: true }, true)
-
- await expect(service.saveStream(user, space, { method: 'POST', headers: {}, raw: Readable.from(['x']) } as any)).rejects.toEqual(
- new FileError(HttpStatus.METHOD_NOT_ALLOWED, 'Resource already exists')
- )
- })
+ describe('saveStream', () => {
+ it('should reject POST when resource already exists', async () => {
+ const space = makeSpace()
+ setPathExists({ [space.realPath]: true }, true)
- it('saveStream should write stream, emit event and release lock', async () => {
- const space = makeSpace()
- setPathExists({ [space.realPath]: false, [path.dirname(space.realPath)]: true }, false)
- const emitSpy = jest.spyOn(FileEvent, 'emit')
-
- const result = await service.saveStream(user, space, { method: 'PUT', headers: {}, raw: Readable.from(['hello']) } as any)
+ await expect(service.saveStream(user, space, { method: 'POST', headers: {}, raw: Readable.from(['x']) } as any)).rejects.toEqual(
+ new FileError(HttpStatus.METHOD_NOT_ALLOWED, 'Resource already exists')
+ )
+ })
- expect(result).toBe(false)
- expect(filesLockManager.create).toHaveBeenCalledWith(user, space.dbFile, 'Sync-in', DEPTH.RESOURCE)
- expect(filesUtils.writeFromStream).toHaveBeenCalledWith(space.realPath, expect.anything(), 0)
- expect(filesLockManager.removeLock).toHaveBeenCalledWith('lock-1')
- expect(emitSpy).toHaveBeenCalledWith('event', { user, space, action: ACTION.ADD, rPath: space.realPath })
- })
+ it('should write stream, emit event and release lock', async () => {
+ const space = makeSpace()
+ setPathExists({ [space.realPath]: false, [path.dirname(space.realPath)]: true }, false)
+ const emitSpy = jest.spyOn(FileEvent, 'emit')
- it('saveStream should use DAV conflict checks and checksum mode when requested', async () => {
- const space = makeSpace()
- setPathExists({ [space.realPath]: true, [path.dirname(space.realPath)]: true }, true)
+ const result = await service.saveStream(user, space, { method: 'PUT', headers: {}, raw: Readable.from(['hello']) } as any)
- const checksum = await service.saveStream(
- user,
- space,
- { method: 'PUT', headers: { 'content-range': 'bytes 100-199/200' }, raw: Readable.from(['chunk']) } as any,
- { dav: { depth: DEPTH.RESOURCE, lockTokens: ['token'] }, checksumAlg: 'sha256' }
- )
+ expect(result).toBe(false)
+ expect(filesLockManager.create).toHaveBeenCalledWith(user, space.dbFile, 'Sync-in', DEPTH.RESOURCE)
+ expect(filesUtils.writeFromStream).toHaveBeenCalledWith(space.realPath, expect.anything(), 0)
+ expect(filesLockManager.removeLock).toHaveBeenCalledWith('lock-1')
+ expect(emitSpy).toHaveBeenCalledWith('event', { user, space, action: ACTION.ADD, rPath: space.realPath })
+ })
- expect(checksum).toBe('sha256-abc')
- expect(filesLockManager.checkConflicts).toHaveBeenCalledWith(space.dbFile, DEPTH.RESOURCE, { userId: 7, lockTokens: ['token'] })
- expect(filesLockManager.create).not.toHaveBeenCalled()
- expect(filesUtils.writeFromStreamAndChecksum).toHaveBeenCalled()
+ it('should use DAV conflict checks and checksum mode when requested', async () => {
+ const space = makeSpace()
+ setPathExists({ [space.realPath]: true, [path.dirname(space.realPath)]: true }, true)
+
+ const checksum = await service.saveStream(
+ user,
+ space,
+ { method: 'PUT', headers: { 'content-range': 'bytes 100-199/200' }, raw: Readable.from(['chunk']) } as any,
+ { dav: { depth: DEPTH.RESOURCE, lockTokens: ['token'] }, checksumAlg: 'sha256' }
+ )
+
+ expect(checksum).toBe('sha256-abc')
+ expect(filesLockManager.checkConflicts).toHaveBeenCalledWith(space.dbFile, DEPTH.RESOURCE, { userId: 7, lockTokens: ['token'] })
+ expect(filesLockManager.create).not.toHaveBeenCalled()
+ expect(filesUtils.writeFromStreamAndChecksum).toHaveBeenCalled()
+ })
})
- it('saveMultipart should write one PATCH part and emit update event', async () => {
- const space = makeSpace({
- url: 'files/personal/report.txt',
- realPath: '/data/users/john/files/report.txt',
- dbFile: { ownerId: 7, path: 'report.txt' }
- })
- setPathExists({ [path.dirname(space.realPath)]: true, [space.realPath]: true }, false)
- ;(filesUtils.isPathIsDir as jest.Mock).mockResolvedValue(true)
- const emitSpy = jest.spyOn(FileEvent, 'emit')
-
- const req = {
- method: 'PATCH',
- files: async function* () {
- yield { filename: 'ignored-on-patch.txt', file: Readable.from(['content']) }
+ describe('saveMultipart', () => {
+ it('should write one PATCH part and emit update event', async () => {
+ const space = makeSpace({
+ url: 'files/personal/report.txt',
+ realPath: '/data/users/john/files/report.txt',
+ dbFile: { ownerId: 7, path: 'report.txt' }
+ })
+ setPathExists({ [path.dirname(space.realPath)]: true, [space.realPath]: true }, false)
+ ;(filesUtils.isPathIsDir as jest.Mock).mockResolvedValue(true)
+ const emitSpy = jest.spyOn(FileEvent, 'emit')
+
+ const req = {
+ method: 'PATCH',
+ files: async function* () {
+ yield { filename: 'ignored-on-patch.txt', file: Readable.from(['content']) }
+ }
}
- }
- await service.saveMultipart(user, space, req as any)
+ await service.saveMultipart(user, space, req as any)
- expect(filesLockManager.createOrRefresh).toHaveBeenCalled()
- expect(filesUtils.writeFromStream).toHaveBeenCalledWith('/data/users/john/files/report.txt', expect.anything())
- expect(emitSpy).toHaveBeenCalledWith('event', expect.objectContaining({ action: ACTION.UPDATE, rPath: '/data/users/john/files/report.txt' }))
+ expect(filesLockManager.createOrRefresh).toHaveBeenCalled()
+ expect(filesUtils.writeFromStream).toHaveBeenCalledWith('/data/users/john/files/report.txt', expect.anything())
+ expect(emitSpy).toHaveBeenCalledWith('event', expect.objectContaining({ action: ACTION.UPDATE, rPath: '/data/users/john/files/report.txt' }))
+ })
})
- it('touch should fail when location does not exist', async () => {
- const space = makeSpace()
- ;(filesUtils.isPathExists as jest.Mock).mockResolvedValueOnce(false)
+ describe('touch', () => {
+ it('should fail when location does not exist', async () => {
+ const space = makeSpace()
+ ;(filesUtils.isPathExists as jest.Mock).mockResolvedValueOnce(false)
- await expect(service.touch(user, space, 123456)).rejects.toEqual(new FileError(HttpStatus.NOT_FOUND, 'Location not found'))
- })
+ await expect(service.touch(user, space, 123456)).rejects.toEqual(new FileError(HttpStatus.NOT_FOUND, 'Location not found'))
+ })
- it('touch should check locks and update mtime', async () => {
- const space = makeSpace()
- ;(filesUtils.isPathExists as jest.Mock).mockResolvedValueOnce(true)
+ it('should check locks and update mtime', async () => {
+ const space = makeSpace()
+ ;(filesUtils.isPathExists as jest.Mock).mockResolvedValueOnce(true)
- await service.touch(user, space, 111)
+ await service.touch(user, space, 111)
- expect(filesLockManager.checkConflicts).toHaveBeenCalledWith(space.dbFile, DEPTH.RESOURCE, { userId: 7 })
- expect(filesUtils.touchFile).toHaveBeenCalledWith(space.realPath, 111)
+ expect(filesLockManager.checkConflicts).toHaveBeenCalledWith(space.dbFile, DEPTH.RESOURCE, { userId: 7 })
+ expect(filesUtils.touchFile).toHaveBeenCalledWith(space.realPath, 111)
+ })
})
- it('mkFile should use sample document when requested', async () => {
- const space = makeSpace({ realPath: '/data/users/john/files/doc.docx' })
- ;(filesUtils.isPathExists as jest.Mock).mockResolvedValueOnce(false)
- const emitSpy = jest.spyOn(FileEvent, 'emit')
+ describe('creation', () => {
+ it('mkFile should use sample document when requested', async () => {
+ const space = makeSpace({ realPath: '/data/users/john/files/doc.docx' })
+ ;(filesUtils.isPathExists as jest.Mock).mockResolvedValueOnce(false)
+ const emitSpy = jest.spyOn(FileEvent, 'emit')
- await service.mkFile(user, space, false, true, true)
+ await service.mkFile(user, space, false, true, true)
- expect(filesUtils.copyFileContent).toHaveBeenCalledWith(expect.stringContaining('assets/samples/sample.docx'), '/data/users/john/files/doc.docx')
- expect(emitSpy).toHaveBeenCalledWith('event', { user, space, action: ACTION.ADD, rPath: space.realPath })
- })
+ expect(filesUtils.copyFileContent).toHaveBeenCalledWith(
+ expect.stringContaining('assets/samples/sample.docx'),
+ '/data/users/john/files/doc.docx'
+ )
+ expect(emitSpy).toHaveBeenCalledWith('event', { user, space, action: ACTION.ADD, rPath: space.realPath })
+ })
- it('mkDir should check conflicts and create directory', async () => {
- const space = makeSpace({ realPath: '/data/users/john/files/folder' })
- ;(filesUtils.isPathExists as jest.Mock).mockResolvedValueOnce(false).mockResolvedValueOnce(true)
+ it('mkDir should check conflicts and create directory', async () => {
+ const space = makeSpace({ realPath: '/data/users/john/files/folder' })
+ ;(filesUtils.isPathExists as jest.Mock).mockResolvedValueOnce(false).mockResolvedValueOnce(true)
- await service.mkDir(user, space, false, { depth: DEPTH.INFINITY, lockTokens: ['lt1'] })
+ await service.mkDir(user, space, false, { depth: DEPTH.INFINITY, lockTokens: ['lt1'] })
- expect(filesLockManager.checkConflicts).toHaveBeenCalledWith(space.dbFile, DEPTH.INFINITY, { userId: 7, lockTokens: ['lt1'] })
- expect(filesUtils.makeDir).toHaveBeenCalledWith('/data/users/john/files/folder', false)
+ expect(filesLockManager.checkConflicts).toHaveBeenCalledWith(space.dbFile, DEPTH.INFINITY, { userId: 7, lockTokens: ['lt1'] })
+ expect(filesUtils.makeDir).toHaveBeenCalledWith('/data/users/john/files/folder', false)
+ })
})
- it('copyMove should copy file and emit add event', async () => {
- const src = makeSpace({
- id: 10,
- url: 'files/personal/src.txt',
- realPath: '/data/users/john/files/src.txt',
- realBasePath: '/data/users/john/files',
- dbFile: { ownerId: 7, path: 'src.txt', inTrash: false }
- })
- const dst = makeSpace({
- id: 11,
- url: 'files/personal/dst.txt',
- realPath: '/data/users/john/files/dst.txt',
- realBasePath: '/data/users/john/files',
- dbFile: { ownerId: 7, path: 'dst.txt', inTrash: false },
- storageQuota: null
- })
- setPathExists(
+ describe('write protection in trash repository', () => {
+ it.each([
{
- [src.realPath]: true,
- [path.dirname(dst.realPath)]: true,
- [dst.realPath]: false
+ name: 'saveStream',
+ run: (space: any) => service.saveStream(user, space, { method: 'PUT', headers: {}, raw: Readable.from(['x']) } as any)
},
- false
- )
- ;(filesUtils.isPathIsDir as jest.Mock).mockResolvedValueOnce(false)
- const emitSpy = jest.spyOn(FileEvent, 'emit')
-
- await service.copyMove(user, src, dst, false)
-
- expect(filesLockManager.checkConflicts).toHaveBeenCalledWith(dst.dbFile, DEPTH.RESOURCE, { userId: 7, lockTokens: undefined })
- expect(filesUtils.copyFiles).toHaveBeenCalledWith(src.realPath, dst.realPath, false, false)
- expect(emitSpy).toHaveBeenCalledWith('event', { user, space: dst, action: ACTION.ADD, rPath: dst.realPath })
- })
-
- it('copyMove should move across spaces and update db', async () => {
- const src = makeSpace({
- id: 21,
- url: 'files/personal/src.txt',
- realPath: '/src-base/src.txt',
- realBasePath: '/src-base',
- dbFile: { ownerId: 7, path: 'src.txt', inTrash: false }
- })
- const dst = makeSpace({
- id: 22,
- url: 'files/project/dst.txt',
- realPath: '/dst-base/dst.txt',
- realBasePath: '/dst-base',
- dbFile: { ownerId: null, spaceId: 22, path: 'dst.txt', inTrash: false },
- storageQuota: null
- })
- setPathExists(
{
- [src.realPath]: true,
- [path.dirname(dst.realPath)]: true,
- [dst.realPath]: false
+ name: 'saveMultipart',
+ run: (space: any) =>
+ service.saveMultipart(user, space, {
+ method: 'POST',
+ files: async function* () {
+ yield { filename: 'file.txt', file: Readable.from(['x']) }
+ }
+ } as any)
},
- false
- )
- ;(filesUtils.isPathIsDir as jest.Mock).mockResolvedValueOnce(false)
- const emitSpy = jest.spyOn(FileEvent, 'emit')
-
- await service.copyMove(user, src, dst, true)
-
- expect(filesUtils.moveFiles).toHaveBeenCalledWith('/src-base/src.txt', '/dst-base/dst.txt', false)
- expect(filesQueries.moveFiles).toHaveBeenCalledWith(src.dbFile, dst.dbFile, false)
- expect(emitSpy).toHaveBeenCalledWith('event', { user, space: src, action: ACTION.DELETE_PERMANENTLY, rPath: '/src-base/src.txt' })
- expect(emitSpy).toHaveBeenCalledWith('event', { user, space: dst, action: ACTION.ADD, rPath: '/dst-base/dst.txt' })
- })
-
- it('delete should remove trash file, locks and db entries', async () => {
- const space = makeSpace({ inTrashRepository: true, realPath: '/data/users/john/trash/old.txt' })
- ;(filesUtils.isPathExists as jest.Mock).mockResolvedValueOnce(true)
- ;(filesUtils.isPathIsDir as jest.Mock).mockResolvedValueOnce(true)
- filesLockManager.getLocksByPath.mockResolvedValueOnce([{ key: 'lk-1' }])
- const emitSpy = jest.spyOn(FileEvent, 'emit')
-
- await service.delete(user, space)
-
- expect(filesUtils.removeFiles).toHaveBeenCalledWith('/data/users/john/trash/old.txt')
- expect(filesLockManager.removeChildLocks).toHaveBeenCalledWith(user, space.dbFile)
- expect(filesLockManager.removeLock).toHaveBeenCalledWith('lk-1')
- expect(filesQueries.deleteFiles).toHaveBeenCalledWith(space.dbFile, true, false)
- expect(emitSpy).toHaveBeenCalledWith('event', { user, space, action: ACTION.DELETE_PERMANENTLY, rPath: '/data/users/john/trash/old.txt' })
+ {
+ name: 'touch',
+ run: (space: any) => service.touch(user, space, 111)
+ },
+ {
+ name: 'mkFile',
+ run: (space: any) => service.mkFile(user, space)
+ },
+ {
+ name: 'mkDir',
+ run: (space: any) => service.mkDir(user, space)
+ },
+ {
+ name: 'downloadFromUrl',
+ run: (space: any) => service.downloadFromUrl(user, space, { url: 'https://example.org/file.txt' })
+ },
+ {
+ name: 'compress',
+ run: (space: any) =>
+ service.compress(user, space, {
+ name: 'archive',
+ extension: 'tar.gz',
+ compressInDirectory: true,
+ files: [{ name: 'file.txt', path: '/data/users/john/files/file.txt' }]
+ } as any)
+ },
+ {
+ name: 'decompress',
+ run: (space: any) => service.decompress(user, space)
+ },
+ {
+ name: 'copyMove',
+ run: (space: any) => {
+ const src = makeSpace({
+ id: 31,
+ url: 'files/personal/src.txt',
+ realPath: '/data/users/john/files/src.txt',
+ realBasePath: '/data/users/john/files',
+ dbFile: { ownerId: 7, path: 'src.txt', inTrash: false }
+ })
+ return service.copyMove(user, src, space, false)
+ }
+ }
+ ])('should reject $name in trash repository', async ({ run }) => {
+ const space = makeTrashSpace()
+ await expect(run(space)).rejects.toEqual(new FileError(HttpStatus.FORBIDDEN, 'The trash is read-only'))
+ expectNoWriteOperations()
+ })
})
- it('delete should force delete when trash path is not available', async () => {
- const space = makeSpace({ realPath: '/data/users/john/files/no-trash.txt', inTrashRepository: false })
- ;(filesUtils.isPathExists as jest.Mock).mockResolvedValueOnce(true)
- ;(filesUtils.isPathIsDir as jest.Mock).mockResolvedValueOnce(false)
- ;(spacesPathUtils.realTrashPathFromSpace as jest.Mock).mockReturnValueOnce(null)
-
- await service.delete(user, space)
+ describe('copyMove', () => {
+ it('should copy file and emit add event', async () => {
+ const src = makeSpace({
+ id: 10,
+ url: 'files/personal/src.txt',
+ realPath: '/data/users/john/files/src.txt',
+ realBasePath: '/data/users/john/files',
+ dbFile: { ownerId: 7, path: 'src.txt', inTrash: false }
+ })
+ const dst = makeSpace({
+ id: 11,
+ url: 'files/personal/dst.txt',
+ realPath: '/data/users/john/files/dst.txt',
+ realBasePath: '/data/users/john/files',
+ dbFile: { ownerId: 7, path: 'dst.txt', inTrash: false },
+ storageQuota: null
+ })
+ setPathExists(
+ {
+ [src.realPath]: true,
+ [path.dirname(dst.realPath)]: true,
+ [dst.realPath]: false
+ },
+ false
+ )
+ ;(filesUtils.isPathIsDir as jest.Mock).mockResolvedValueOnce(false)
+ const emitSpy = jest.spyOn(FileEvent, 'emit')
+
+ await service.copyMove(user, src, dst, false)
+
+ expect(filesLockManager.checkConflicts).toHaveBeenCalledWith(dst.dbFile, DEPTH.RESOURCE, { userId: 7, lockTokens: undefined })
+ expect(filesUtils.copyFiles).toHaveBeenCalledWith(src.realPath, dst.realPath, false, false)
+ expect(emitSpy).toHaveBeenCalledWith('event', { user, space: dst, action: ACTION.ADD, rPath: dst.realPath })
+ })
- expect(filesUtils.removeFiles).toHaveBeenCalledWith('/data/users/john/files/no-trash.txt')
- expect(filesQueries.deleteFiles).toHaveBeenCalledWith(space.dbFile, false, true)
+ it('should move across spaces and update db', async () => {
+ const src = makeSpace({
+ id: 21,
+ url: 'files/personal/src.txt',
+ realPath: '/src-base/src.txt',
+ realBasePath: '/src-base',
+ dbFile: { ownerId: 7, path: 'src.txt', inTrash: false }
+ })
+ const dst = makeSpace({
+ id: 22,
+ url: 'files/project/dst.txt',
+ realPath: '/dst-base/dst.txt',
+ realBasePath: '/dst-base',
+ dbFile: { ownerId: null, spaceId: 22, path: 'dst.txt', inTrash: false },
+ storageQuota: null
+ })
+ setPathExists(
+ {
+ [src.realPath]: true,
+ [path.dirname(dst.realPath)]: true,
+ [dst.realPath]: false
+ },
+ false
+ )
+ ;(filesUtils.isPathIsDir as jest.Mock).mockResolvedValueOnce(false)
+ const emitSpy = jest.spyOn(FileEvent, 'emit')
+
+ await service.copyMove(user, src, dst, true)
+
+ expect(filesUtils.moveFiles).toHaveBeenCalledWith('/src-base/src.txt', '/dst-base/dst.txt', false)
+ expect(filesQueries.moveFiles).toHaveBeenCalledWith(src.dbFile, dst.dbFile, false)
+ expect(emitSpy).toHaveBeenCalledWith('event', { user, space: src, action: ACTION.DELETE_PERMANENTLY, rPath: '/src-base/src.txt' })
+ expect(emitSpy).toHaveBeenCalledWith('event', { user, space: dst, action: ACTION.ADD, rPath: '/dst-base/dst.txt' })
+ })
})
- describe('downloadFromUrl dto validation', () => {
- it('should accept http and https schemes', () => {
- expect(transformAndValidate(DownloadFileDto, { url: 'https://example.org/file.txt' }).url).toBe('https://example.org/file.txt')
- expect(transformAndValidate(DownloadFileDto, { url: 'http://example.org/file.txt' }).url).toBe('http://example.org/file.txt')
+ describe('delete', () => {
+ it('should remove trash file, locks and db entries', async () => {
+ const space = makeSpace({ inTrashRepository: true, realPath: '/data/users/john/trash/old.txt' })
+ ;(filesUtils.isPathExists as jest.Mock).mockResolvedValueOnce(true)
+ ;(filesUtils.isPathIsDir as jest.Mock).mockResolvedValueOnce(true)
+ filesLockManager.getLocksByPath.mockResolvedValueOnce([{ key: 'lk-1' }])
+ const emitSpy = jest.spyOn(FileEvent, 'emit')
+
+ await service.delete(user, space)
+
+ expect(filesUtils.removeFiles).toHaveBeenCalledWith('/data/users/john/trash/old.txt')
+ expect(filesLockManager.removeChildLocks).toHaveBeenCalledWith(user, space.dbFile)
+ expect(filesLockManager.removeLock).toHaveBeenCalledWith('lk-1')
+ expect(filesQueries.deleteFiles).toHaveBeenCalledWith(space.dbFile, true, false)
+ expect(emitSpy).toHaveBeenCalledWith('event', { user, space, action: ACTION.DELETE_PERMANENTLY, rPath: '/data/users/john/trash/old.txt' })
})
- it('should reject non-http(s) schemes', () => {
- const invalidUrls = ['ftp://example.org/file.txt', 'file:///tmp/file.txt', 'ws://example.org/file.txt']
- for (const url of invalidUrls) {
- expect(() => transformAndValidate(DownloadFileDto, { url })).toThrow()
- }
- })
- })
+ it('should force delete when trash path is not available', async () => {
+ const space = makeSpace({ realPath: '/data/users/john/files/no-trash.txt', inTrashRepository: false })
+ ;(filesUtils.isPathExists as jest.Mock).mockResolvedValueOnce(true)
+ ;(filesUtils.isPathIsDir as jest.Mock).mockResolvedValueOnce(false)
+ ;(spacesPathUtils.realTrashPathFromSpace as jest.Mock).mockReturnValueOnce(null)
- it('downloadFromUrl should throw conflict when lock cannot be created', async () => {
- const space = makeSpace()
- filesLockManager.create.mockResolvedValueOnce([false, { key: 'other', owner: { id: 99 } }])
+ await service.delete(user, space)
- await expect(service.downloadFromUrl(user, space, { url: 'https://example.org/file.txt' })).rejects.toBeInstanceOf(LockConflict)
+ expect(filesUtils.removeFiles).toHaveBeenCalledWith('/data/users/john/files/no-trash.txt')
+ expect(filesQueries.deleteFiles).toHaveBeenCalledWith(space.dbFile, false, true)
+ })
})
- it('downloadFromUrl should handle HEAD+GET and emit task watch/event', async () => {
- const space = makeSpace({ task: { cacheKey: 'task-1', props: {} } })
- ;(filesUtils.uniqueFilePathFromDir as jest.Mock).mockResolvedValueOnce('/tmp/download.txt')
- http.axiosRef
- .mockResolvedValueOnce({
- headers: { 'content-length': '55' },
- request: { socket: { remoteAddress: '8.8.8.8' } }
+ describe('downloadFromUrl', () => {
+ describe('dto validation', () => {
+ it('should accept http and https schemes', () => {
+ expect(transformAndValidate(DownloadFileDto, { url: 'https://example.org/file.txt' }).url).toBe('https://example.org/file.txt')
+ expect(transformAndValidate(DownloadFileDto, { url: 'http://example.org/file.txt' }).url).toBe('http://example.org/file.txt')
})
- .mockResolvedValueOnce({
- data: Readable.from(['abc']),
- request: { socket: { remoteAddress: '8.8.8.8' } }
- })
- const taskEmitSpy = jest.spyOn(FileTaskEvent, 'emit')
- const fileEmitSpy = jest.spyOn(FileEvent, 'emit')
- await service.downloadFromUrl(user, space, { url: 'https://example.org/file.txt' })
+ it('should reject non-http(s) schemes', () => {
+ const invalidUrls = ['ftp://example.org/file.txt', 'file:///tmp/file.txt', 'ws://example.org/file.txt']
+ for (const url of invalidUrls) {
+ expect(() => transformAndValidate(DownloadFileDto, { url })).toThrow()
+ }
+ })
+ })
- expect(space.task.props.totalSize).toBe(55)
- expect(taskEmitSpy).toHaveBeenCalledWith('startWatch', space, FILE_OPERATION.DOWNLOAD, '/tmp/download.txt')
- expect(filesUtils.writeFromStream).toHaveBeenCalledWith('/tmp/download.txt', expect.anything())
- expect(filesLockManager.removeLock).toHaveBeenCalledWith('lock-1')
- expect(fileEmitSpy).toHaveBeenCalledWith('event', { user, space, action: ACTION.ADD, rPath: '/tmp/download.txt' })
- })
+ it('should throw conflict when lock cannot be created', async () => {
+ const space = makeSpace()
+ filesLockManager.create.mockResolvedValueOnce([false, { key: 'other', owner: { id: 99 } }])
- it('compress should archive files and emit events', async () => {
- const archive = new PassThrough() as PassThrough & {
- directory: jest.Mock
- file: jest.Mock
- finalize: jest.Mock
- }
- archive.directory = jest.fn().mockReturnValue(archive)
- archive.file = jest.fn().mockReturnValue(archive)
- archive.finalize = jest.fn().mockImplementation(async () => {
- archive.end()
+ await expect(service.downloadFromUrl(user, space, { url: 'https://example.org/file.txt' })).rejects.toBeInstanceOf(LockConflict)
})
- ;(archiver as unknown as jest.Mock).mockReturnValueOnce(archive as any)
- jest.spyOn(fs, 'createWriteStream').mockReturnValue(new PassThrough() as any)
- ;(filesUtils.uniqueFilePathFromDir as jest.Mock).mockResolvedValueOnce('/tmp/archive.tar.gz')
- ;(filesUtils.isPathIsDir as jest.Mock).mockImplementation(async (p: string) => p.endsWith('/dir'))
- const space = makeSpace({ realPath: '/data/users/john/files/source.txt', task: { cacheKey: 'task-c', props: {} } })
- const dto = {
- name: 'archive',
- extension: 'tar.gz',
- compressInDirectory: false,
- files: [
- { path: '/data/users/john/files/dir', name: 'dir', rootAlias: null },
- { path: '/data/users/john/files/file.txt', name: 'file.txt', rootAlias: null }
- ]
- } as any
- const taskEmitSpy = jest.spyOn(FileTaskEvent, 'emit')
-
- await service.compress(user, space, dto)
- expect(archiver as unknown as jest.Mock).toHaveBeenCalled()
- expect(archive.directory).toHaveBeenCalled()
- expect(archive.file).toHaveBeenCalled()
- expect(archive.finalize).toHaveBeenCalled()
- expect(taskEmitSpy).toHaveBeenCalledWith('startWatch', space, FILE_OPERATION.COMPRESS, '/tmp/archive.tar.gz')
+ it('should handle HEAD+GET and emit task watch/event', async () => {
+ const space = makeSpace({ task: { cacheKey: 'task-1', props: {} } })
+ ;(filesUtils.uniqueFilePathFromDir as jest.Mock).mockResolvedValueOnce('/tmp/download.txt')
+ http.axiosRef
+ .mockResolvedValueOnce({
+ headers: { 'content-length': '55' },
+ request: { socket: { remoteAddress: '8.8.8.8' } }
+ })
+ .mockResolvedValueOnce({
+ data: Readable.from(['abc']),
+ request: { socket: { remoteAddress: '8.8.8.8' } }
+ })
+ const taskEmitSpy = jest.spyOn(FileTaskEvent, 'emit')
+ const fileEmitSpy = jest.spyOn(FileEvent, 'emit')
+
+ await service.downloadFromUrl(user, space, { url: 'https://example.org/file.txt' })
+
+ expect(space.task.props.totalSize).toBe(55)
+ expect(taskEmitSpy).toHaveBeenCalledWith('startWatch', space, FILE_OPERATION.DOWNLOAD, '/tmp/download.txt')
+ expect(filesUtils.writeFromStream).toHaveBeenCalledWith('/tmp/download.txt', expect.anything())
+ expect(filesLockManager.removeLock).toHaveBeenCalledWith('lock-1')
+ expect(fileEmitSpy).toHaveBeenCalledWith('event', { user, space, action: ACTION.ADD, rPath: '/tmp/download.txt' })
+ })
})
- it('decompress should extract zip and release lock', async () => {
- const space = makeSpace({ realPath: '/data/users/john/files/archive.zip', task: { cacheKey: 'task-d', props: {} } })
- ;(filesUtils.isPathExists as jest.Mock).mockResolvedValueOnce(true)
- ;(filesUtils.uniqueFilePathFromDir as jest.Mock).mockResolvedValueOnce('/data/users/john/files/archive')
- const unzipSpy = jest.spyOn(unzipUtils, 'extractZip').mockResolvedValueOnce(undefined)
- const taskEmitSpy = jest.spyOn(FileTaskEvent, 'emit')
-
- await service.decompress(user, space)
+ describe('compress', () => {
+ it('should archive files and emit events', async () => {
+ const archive = createArchiveMock()
+ ;(filesUtils.uniqueFilePathFromDir as jest.Mock).mockResolvedValueOnce('/tmp/archive.tar.gz')
+ ;(filesUtils.isPathIsDir as jest.Mock).mockImplementation(async (p: string) => p.endsWith('/dir'))
+ const space = makeSpace({ realPath: '/data/users/john/files/source.txt', task: { cacheKey: 'task-c', props: {} } })
+ const dto = {
+ name: 'archive',
+ extension: 'tar.gz',
+ compressInDirectory: false,
+ files: [
+ { path: '/data/users/john/files/dir', name: 'dir', rootAlias: null },
+ { path: '/data/users/john/files/file.txt', name: 'file.txt', rootAlias: null }
+ ]
+ } as any
+ const taskEmitSpy = jest.spyOn(FileTaskEvent, 'emit')
+
+ await service.compress(user, space, dto)
+
+ expect(archiver as unknown as jest.Mock).toHaveBeenCalled()
+ expect(archive.directory).toHaveBeenCalled()
+ expect(archive.file).toHaveBeenCalled()
+ expect(archive.finalize).toHaveBeenCalled()
+ expect(taskEmitSpy).toHaveBeenCalledWith('startWatch', space, FILE_OPERATION.COMPRESS, '/tmp/archive.tar.gz')
+ })
- expect(filesUtils.makeDir).toHaveBeenCalledWith('/data/users/john/files/archive')
- expect(unzipSpy).toHaveBeenCalledWith('/data/users/john/files/archive.zip', '/data/users/john/files/archive')
- expect(taskEmitSpy).toHaveBeenCalledWith('startWatch', space, FILE_OPERATION.DECOMPRESS, '/data/users/john/files/archive')
- expect(filesLockManager.removeLock).toHaveBeenCalledWith('lock-1')
+ it('should allow archive export from trash when compressInDirectory is false', async () => {
+ const archive = createArchiveMock()
+ ;(filesUtils.uniqueFilePathFromDir as jest.Mock).mockResolvedValueOnce('/tmp/archive-trash.tar.gz')
+ ;(filesUtils.isPathIsDir as jest.Mock).mockResolvedValueOnce(false)
+ const emitSpy = jest.spyOn(FileEvent, 'emit')
+ const space = makeTrashSpace({
+ url: 'trash/personal/source.txt',
+ realPath: '/data/users/john/trash/source.txt',
+ dbFile: { ownerId: 7, path: 'source.txt', inTrash: true }
+ })
+ const dto = {
+ name: 'archive-trash',
+ extension: 'tar.gz',
+ compressInDirectory: false,
+ files: [{ path: '/data/users/john/trash/source.txt', name: 'source.txt', rootAlias: null }]
+ } as any
+
+ await expect(service.compress(user, space, dto)).resolves.toBeUndefined()
+ expect(filesLockManager.create).not.toHaveBeenCalled()
+ expect(archive.file).toHaveBeenCalled()
+ expect(emitSpy).toHaveBeenCalledWith('event', { user, space, action: ACTION.ADD, rPath: '/tmp/archive-trash.tar.gz' })
+ })
})
- it('decompress should extract tar formats via tar.extract', async () => {
- const space = makeSpace({ realPath: '/data/users/john/files/archive.tar.gz' })
- ;(filesUtils.isPathExists as jest.Mock).mockResolvedValueOnce(true)
- ;(filesUtils.uniqueFilePathFromDir as jest.Mock).mockResolvedValueOnce('/data/users/john/files/archive')
- ;(tar.extract as unknown as jest.Mock).mockResolvedValueOnce(undefined)
+ describe('decompress', () => {
+ it('should extract zip and release lock', async () => {
+ const space = makeSpace({ realPath: '/data/users/john/files/archive.zip', task: { cacheKey: 'task-d', props: {} } })
+ ;(filesUtils.isPathExists as jest.Mock).mockResolvedValueOnce(true)
+ ;(filesUtils.uniqueFilePathFromDir as jest.Mock).mockResolvedValueOnce('/data/users/john/files/archive')
+ const unzipSpy = jest.spyOn(unzipUtils, 'extractZip').mockResolvedValueOnce(undefined)
+ const taskEmitSpy = jest.spyOn(FileTaskEvent, 'emit')
- await service.decompress(user, space)
+ await service.decompress(user, space)
- expect(tar.extract).toHaveBeenCalledWith(
- expect.objectContaining({
- file: '/data/users/john/files/archive.tar.gz',
- cwd: '/data/users/john/files/archive',
- gzip: true
- })
- )
+ expect(filesUtils.makeDir).toHaveBeenCalledWith('/data/users/john/files/archive')
+ expect(unzipSpy).toHaveBeenCalledWith('/data/users/john/files/archive.zip', '/data/users/john/files/archive')
+ expect(taskEmitSpy).toHaveBeenCalledWith('startWatch', space, FILE_OPERATION.DECOMPRESS, '/data/users/john/files/archive')
+ expect(filesLockManager.removeLock).toHaveBeenCalledWith('lock-1')
+ })
+
+ it('should extract tar formats via tar.extract', async () => {
+ const space = makeSpace({ realPath: '/data/users/john/files/archive.tar.gz' })
+ ;(filesUtils.isPathExists as jest.Mock).mockResolvedValueOnce(true)
+ ;(filesUtils.uniqueFilePathFromDir as jest.Mock).mockResolvedValueOnce('/data/users/john/files/archive')
+ ;(tar.extract as unknown as jest.Mock).mockResolvedValueOnce(undefined)
+
+ await service.decompress(user, space)
+
+ expect(tar.extract).toHaveBeenCalledWith(
+ expect.objectContaining({
+ file: '/data/users/john/files/archive.tar.gz',
+ cwd: '/data/users/john/files/archive',
+ gzip: true
+ })
+ )
+ })
})
- it('generateThumbnail should validate image and return generated stream', async () => {
- const space = makeSpace({ realPath: '/data/users/john/files/image.png' })
- ;(filesUtils.isPathExists as jest.Mock).mockResolvedValueOnce(true)
- ;(filesUtils.getMimeType as jest.Mock).mockReturnValueOnce('image-png')
- const stream = Readable.from(['img'])
- jest.spyOn(imageUtils, 'generateThumbnail').mockReturnValueOnce(stream as any)
+ describe('generateThumbnail', () => {
+ it('should validate image and return generated stream', async () => {
+ const space = makeSpace({ realPath: '/data/users/john/files/image.png' })
+ ;(filesUtils.isPathExists as jest.Mock).mockResolvedValueOnce(true)
+ ;(filesUtils.getMimeType as jest.Mock).mockReturnValueOnce('image-png')
+ const stream = Readable.from(['img'])
+ jest.spyOn(imageUtils, 'generateThumbnail').mockReturnValueOnce(stream as any)
- const result = await service.generateThumbnail(space, 256)
+ const result = await service.generateThumbnail(space, 256)
- expect(result).toBe(stream)
+ expect(result).toBe(stream)
+ })
})
- it('lock should fail if resource does not exist', async () => {
- const space = makeSpace()
- ;(filesUtils.isPathExists as jest.Mock).mockResolvedValueOnce(false)
+ describe('locking', () => {
+ it('lock should fail if resource does not exist', async () => {
+ const space = makeSpace()
+ ;(filesUtils.isPathExists as jest.Mock).mockResolvedValueOnce(false)
- await expect(service.lock(user, space)).rejects.toEqual(new FileError(HttpStatus.BAD_REQUEST, 'Lock refresh must specify an existing resource'))
- })
+ await expect(service.lock(user, space)).rejects.toEqual(new FileError(HttpStatus.BAD_REQUEST, 'Lock refresh must specify an existing resource'))
+ })
- it('unlock should remove owned lock and reject foreign lock', async () => {
- const space = makeSpace()
- ;(filesUtils.isPathExists as jest.Mock).mockResolvedValue(true)
- filesLockManager.getLocksByPath.mockResolvedValueOnce([{ key: 'l1', owner: { id: 7 } }])
+ it('unlock should remove owned lock and reject foreign lock', async () => {
+ const space = makeSpace()
+ ;(filesUtils.isPathExists as jest.Mock).mockResolvedValue(true)
+ filesLockManager.getLocksByPath.mockResolvedValueOnce([{ key: 'l1', owner: { id: 7 } }])
- await service.unlock(user, space)
- expect(filesLockManager.removeLock).toHaveBeenCalledWith('l1')
+ await service.unlock(user, space)
+ expect(filesLockManager.removeLock).toHaveBeenCalledWith('l1')
- filesLockManager.getLocksByPath.mockResolvedValueOnce([{ key: 'l2', owner: { id: 99, login: 'alice' } }])
- await expect(service.unlock(user, space)).rejects.toEqual(
- new LockConflict({ key: 'l2', owner: { id: 99, login: 'alice' } } as any, 'Conflicting lock')
- )
- })
+ filesLockManager.getLocksByPath.mockResolvedValueOnce([{ key: 'l2', owner: { id: 99, login: 'alice' } }])
+ await expect(service.unlock(user, space)).rejects.toEqual(
+ new LockConflict({ key: 'l2', owner: { id: 99, login: 'alice' } } as any, 'Conflicting lock')
+ )
+ })
- it('unlockRequest should throw when lock list is empty and notify foreign owner otherwise', async () => {
- const space = makeSpace()
- filesLockManager.getLocksByPath.mockResolvedValueOnce([])
- await expect(service.unlockRequest(user, space)).rejects.toEqual(new FileError(HttpStatus.NOT_FOUND, 'Lock not found'))
-
- filesLockManager.getLocksByPath.mockResolvedValueOnce([{ key: 'l3', owner: { id: 42 } }])
- await service.unlockRequest(user, space)
- expect(notificationsManager.create).toHaveBeenCalledWith(
- [42],
- expect.objectContaining({ element: 'file.txt', url: 'files/personal' }),
- expect.objectContaining({ author: user, currentUrl: 'https://sync-in.example' })
- )
+ it('unlockRequest should throw when lock list is empty and notify foreign owner otherwise', async () => {
+ const space = makeSpace()
+ filesLockManager.getLocksByPath.mockResolvedValueOnce([])
+ await expect(service.unlockRequest(user, space)).rejects.toEqual(new FileError(HttpStatus.NOT_FOUND, 'Lock not found'))
+
+ filesLockManager.getLocksByPath.mockResolvedValueOnce([{ key: 'l3', owner: { id: 42 } }])
+ await service.unlockRequest(user, space)
+ expect(notificationsManager.create).toHaveBeenCalledWith(
+ [42],
+ expect.objectContaining({ element: 'file.txt', url: 'files/personal' }),
+ expect.objectContaining({ author: user, currentUrl: 'https://sync-in.example' })
+ )
+ })
})
- it('getSize should return directory size or file size depending on target type', async () => {
- const space = makeSpace()
- ;(filesUtils.isPathExists as jest.Mock).mockResolvedValue(true)
- ;(filesUtils.isPathIsDir as jest.Mock).mockResolvedValueOnce(true).mockResolvedValueOnce(false)
- ;(filesUtils.dirSize as jest.Mock).mockResolvedValueOnce([500, {}])
- ;(filesUtils.fileSize as jest.Mock).mockResolvedValueOnce(20)
+ describe('getSize', () => {
+ it('should return directory size or file size depending on target type', async () => {
+ const space = makeSpace()
+ ;(filesUtils.isPathExists as jest.Mock).mockResolvedValue(true)
+ ;(filesUtils.isPathIsDir as jest.Mock).mockResolvedValueOnce(true).mockResolvedValueOnce(false)
+ ;(filesUtils.dirSize as jest.Mock).mockResolvedValueOnce([500, {}])
+ ;(filesUtils.fileSize as jest.Mock).mockResolvedValueOnce(20)
- await expect(service.getSize(space)).resolves.toBe(500)
- await expect(service.getSize(space)).resolves.toBe(20)
+ await expect(service.getSize(space)).resolves.toBe(500)
+ await expect(service.getSize(space)).resolves.toBe(20)
+ })
})
})
diff --git a/backend/src/applications/files/services/files-manager.service.ts b/backend/src/applications/files/services/files-manager.service.ts
index 10a0ce3a..18ac5a44 100644
--- a/backend/src/applications/files/services/files-manager.service.ts
+++ b/backend/src/applications/files/services/files-manager.service.ts
@@ -98,6 +98,7 @@ export class FilesManager {
): Promise<boolean | string> {
// If tmpPath is used, we lock the final destination during the transfer
// space.realPath is replaced by tmpPath (if allowed). If the move operation failed, we remove the tmp file
+ this.checkNotTrashRepository(space)
const fExists = await isPathExists(space.realPath)
const fTmpExists = options?.tmpPath ? await isPathExists(options.tmpPath) : false
if (fExists && req.method === HTTP_METHOD.POST) {
@@ -192,6 +193,7 @@ export class FilesManager {
In this text-editing scenario, locking and refreshing occur automatically, but unlocking must be handled explicitly via
the `unlock` method.
*/
+ this.checkNotTrashRepository(space)
const overwrite = req.method === HTTP_METHOD.PUT
const patch = req.method === HTTP_METHOD.PATCH
const realParentPath = dirName(space.realPath)
@@ -268,6 +270,7 @@ export class FilesManager {
}
async touch(user: UserModel, space: SpaceEnv, mtime: number, checkLocks = true): Promise<void> {
+ this.checkNotTrashRepository(space)
if (!(await isPathExists(space.realPath))) {
throw new FileError(HttpStatus.NOT_FOUND, 'Location not found')
}
@@ -279,6 +282,7 @@ export class FilesManager {
}
async mkFile(user: UserModel, space: SpaceEnv, overwrite = false, checkLocks = true, checkDocument = false): Promise<void> {
+ this.checkNotTrashRepository(space)
checkFileName(space.realPath)
if (!overwrite && (await isPathExists(space.realPath))) {
throw new FileError(HttpStatus.BAD_REQUEST, 'Resource already exists')
@@ -299,6 +303,7 @@ export class FilesManager {
}
async mkDir(user: UserModel, space: SpaceEnv, recursive = false, dav?: { depth: LOCK_DEPTH; lockTokens: string[] }): Promise<void> {
+ this.checkNotTrashRepository(space)
checkFileName(space.realPath)
if (!recursive) {
if (await isPathExists(space.realPath)) {
@@ -321,6 +326,7 @@ export class FilesManager {
dav?: { depth: LOCK_DEPTH; lockTokens: string[] }
): Promise<void> {
// checks
+ this.checkNotTrashRepository(dstSpace)
if (!canAccessToSpace(user, dstSpace)) {
this.logger.warn({ tag: this.copyMove.name, msg: `is not allowed to access to this space repository : ${dstSpace.repository}` })
throw new FileError(HttpStatus.FORBIDDEN, 'You are not allowed to access to this repository')
@@ -503,6 +509,7 @@ export class FilesManager {
}
async downloadFromUrl(user: UserModel, space: SpaceEnv, downloadDto: DownloadFileDto): Promise<void> {
+ this.checkNotTrashRepository(space)
this.logger.log({ tag: this.downloadFromUrl.name, msg: `${downloadDto.url}` })
const rPath = await uniqueFilePathFromDir(space.realPath)
const dbFile = space.dbFile
@@ -528,6 +535,9 @@ export class FilesManager {
async compress(user: UserModel, space: SpaceEnv, dto: CompressFileDto): Promise<void> {
// This method is currently used only by files-methods.service, which handles input sanitization.
// If it is used in other services in the future, make sure to refactor accordingly to sanitize inputs properly.
+ if (dto.compressInDirectory) {
+ this.checkNotTrashRepository(space)
+ }
const srcPath = dirName(space.realPath)
const archiveExt = dto.name.endsWith(dto.extension) ? '' : `.${dto.extension}`
const dstPath = await uniqueFilePathFromDir(path.join(dto.compressInDirectory ? srcPath : user.tasksPath, `${dto.name}${archiveExt}`))
@@ -579,6 +589,7 @@ export class FilesManager {
async decompress(user: UserModel, space: SpaceEnv): Promise<void> {
// checks
+ this.checkNotTrashRepository(space)
if (!(await isPathExists(space.realPath))) {
throw new FileError(HttpStatus.NOT_FOUND, 'Location not found')
}
@@ -696,4 +707,10 @@ export class FilesManager {
return await fileSize(space.realPath)
}
}
+
+ private checkNotTrashRepository(space: SpaceEnv): void {
+ if (space.inTrashRepository) {
+ throw new FileError(HttpStatus.FORBIDDEN, 'The trash is read-only')
+ }
+ }
}
diff --git a/backend/src/applications/spaces/guards/space.guard.spec.ts b/backend/src/applications/spaces/guards/space.guard.spec.ts
index 7a50c309..8e81d736 100644
--- a/backend/src/applications/spaces/guards/space.guard.spec.ts
+++ b/backend/src/applications/spaces/guards/space.guard.spec.ts
@@ -377,6 +377,26 @@ describe(SpaceGuard.name, () => {
expect(await spacesGuard.canActivate(context)).toBe(true)
})
+ it('should fail for add and modify operations in trash repository', async () => {
+ userTest.role = USER_ROLE.USER
+ spacesManager.spaceEnv = jest.fn().mockReturnValue({
+ enabled: true,
+ inTrashRepository: true,
+ envPermissions: SPACE_ALL_OPERATIONS
+ } as Partial<SpaceEnv>)
+ for (const method of ['POST', 'PATCH']) {
+ context.switchToHttp().getRequest.mockReturnValueOnce({
+ method,
+ user: userTest,
+ params: { '*': 'trash/personal' }
+ })
+ await expect(spacesGuard.canActivate(context)).rejects.toMatchObject({
+ status: HttpStatus.FORBIDDEN,
+ message: 'The trash is read-only'
+ })
+ }
+ })
+
it('should fail with space disabled', async () => {
userTest.role = USER_ROLE.USER
spacesManager.spaceEnv = jest.fn().mockReturnValueOnce({
diff --git a/backend/src/applications/spaces/guards/space.guard.ts b/backend/src/applications/spaces/guards/space.guard.ts
index ed28b5fa..235003f8 100644
--- a/backend/src/applications/spaces/guards/space.guard.ts
+++ b/backend/src/applications/spaces/guards/space.guard.ts
@@ -42,6 +42,9 @@ export class SpaceGuard implements CanActivate {
throw new HttpException('You are not allowed to do this action', HttpStatus.FORBIDDEN)
}
if ([SPACE_OPERATION.ADD, SPACE_OPERATION.MODIFY].indexOf(permission) > -1) {
+ if (req.space.inTrashRepository) {
+ throw new HttpException('The trash is read-only', HttpStatus.FORBIDDEN)
+ }
if (req.space.quotaIsExceeded) {
logger.warn(`Storage quota exceeded for *${req.space.alias}* (${req.space.id})`)
throw new HttpException('Storage quota exceeded', HttpStatus.INSUFFICIENT_STORAGE)
diff --git a/backend/src/applications/spaces/utils/permissions.ts b/backend/src/applications/spaces/utils/permissions.ts
index ffa27e8d..14c8ca02 100644
--- a/backend/src/applications/spaces/utils/permissions.ts
+++ b/backend/src/applications/spaces/utils/permissions.ts
@@ -63,3 +63,7 @@ export function canAccessToSpace(user: UserModel, space: SpaceEnv): boolean {
}
return false
}
+
+export function canModifySpaceEnv(space: SpaceEnv): boolean {
+ return !space.inTrashRepository && haveSpaceEnvPermissions(space, SPACE_OPERATION.MODIFY)
+}
diff --git a/frontend/src/i18n/de.json b/frontend/src/i18n/de.json
index 56e36fbd..2fba1abb 100644
--- a/frontend/src/i18n/de.json
+++ b/frontend/src/i18n/de.json
@@ -130,6 +130,7 @@
"Storage Usage": "Speichernutzung",
"Space status": "Status des Bereichs",
"Storage quota exceeded": "Speicherkontingent überschritten",
+ "The trash is read-only": "Der Papierkorb ist schreibgeschützt",
"Storage quota will be exceeded": "Speicherkontingent wird überschritten",
"No more space available": "Kein Speicherplatz mehr verfügbar",
"available_space_is_low": "Verfügbarer Speicherplatz niedrig ( {{ nb }}% )",
diff --git a/frontend/src/i18n/es.json b/frontend/src/i18n/es.json
index bcef6b32..feb7ec58 100644
--- a/frontend/src/i18n/es.json
+++ b/frontend/src/i18n/es.json
@@ -130,6 +130,7 @@
"Storage Usage": "Uso de almacenamiento",
"Space status": "Estado del espacio",
"Storage quota exceeded": "Se ha superado la cuota de almacenamiento",
+ "The trash is read-only": "La papelera es de solo lectura",
"Storage quota will be exceeded": "Se superará la cuota de almacenamiento",
"No more space available": "No hay más espacio disponible",
"available_space_is_low": "Espacio disponible bajo ( {{ nb }}% )",
diff --git a/frontend/src/i18n/fr.json b/frontend/src/i18n/fr.json
index 2ec74a6f..fe7830b7 100644
--- a/frontend/src/i18n/fr.json
+++ b/frontend/src/i18n/fr.json
@@ -130,6 +130,7 @@
"Storage Usage": "Utilisation du stockage",
"Space status": "État de l'espace",
"Storage quota exceeded": "Le quota de stockage est dépassé",
+ "The trash is read-only": "La corbeille est en lecture seule",
"Storage quota will be exceeded": "Le quota de stockage sera dépassé",
"No more space available": "Plus d'espace disponible",
"available_space_is_low": "Espace disponible faible ( {{ nb }}% )",
diff --git a/frontend/src/i18n/hi.json b/frontend/src/i18n/hi.json
index 89631373..cdc74d85 100644
--- a/frontend/src/i18n/hi.json
+++ b/frontend/src/i18n/hi.json
@@ -130,6 +130,7 @@
"Storage Usage": "भंडारण उपयोग",
"Space status": "स्पेस स्थिति",
"Storage quota exceeded": "भंडारण कोटा पार हो गया",
+ "The trash is read-only": "ट्रैश केवल-पढ़ने योग्य है",
"Storage quota will be exceeded": "भंडारण कोटा पार हो जाएगा",
"No more space available": "कोई अतिरिक्त स्थान उपलब्ध नहीं",
"available_space_is_low": "उपलब्ध स्थान कम है ( {{ nb }}% )",
diff --git a/frontend/src/i18n/it.json b/frontend/src/i18n/it.json
index 1c4080bd..5fde9a48 100644
--- a/frontend/src/i18n/it.json
+++ b/frontend/src/i18n/it.json
@@ -130,6 +130,7 @@
"Storage Usage": "Utilizzo dell’archiviazione",
"Space status": "Stato dello spazio",
"Storage quota exceeded": "Quota di archiviazione superata",
+ "The trash is read-only": "Il cestino è di sola lettura",
"Storage quota will be exceeded": "La quota di archiviazione verrà superata",
"No more space available": "Nessuno spazio disponibile",
"available_space_is_low": "Spazio disponibile basso ( {{ nb }}% )",
diff --git a/frontend/src/i18n/ja.json b/frontend/src/i18n/ja.json
index 07fc7820..e6c4bdd4 100644
--- a/frontend/src/i18n/ja.json
+++ b/frontend/src/i18n/ja.json
@@ -130,6 +130,7 @@
"Storage Usage": "ストレージ使用量",
"Space status": "スペースの状態",
"Storage quota exceeded": "ストレージの割り当てを超えています",
+ "The trash is read-only": "ゴミ箱は読み取り専用です",
"Storage quota will be exceeded": "ストレージの割り当てを超過する見込みです",
"No more space available": "空き容量がありません",
"available_space_is_low": "空き容量が少ない({{ nb }}%)",
diff --git a/frontend/src/i18n/ko.json b/frontend/src/i18n/ko.json
index 0166c429..165112fc 100644
--- a/frontend/src/i18n/ko.json
+++ b/frontend/src/i18n/ko.json
@@ -130,6 +130,7 @@
"Storage Usage": "저장 사용량",
"Space status": "스페이스 상태",
"Storage quota exceeded": "저장 할당량을 초과했습니다",
+ "The trash is read-only": "휴지통은 읽기 전용입니다",
"Storage quota will be exceeded": "저장 할당량을 초과할 예정입니다",
"No more space available": "사용 가능한 공간이 없습니다",
"available_space_is_low": "사용 가능한 공간이 부족합니다 ({{ nb }}%)",
diff --git a/frontend/src/i18n/nl.json b/frontend/src/i18n/nl.json
index dc1f4591..09919bef 100644
--- a/frontend/src/i18n/nl.json
+++ b/frontend/src/i18n/nl.json
@@ -130,6 +130,7 @@
"Storage Usage": "Opslaggebruik",
"Space status": "Opslag-status",
"Storage quota exceeded": "Opslagquotum overschreden",
+ "The trash is read-only": "De prullenbak is alleen-lezen",
"Storage quota will be exceeded": "Opslagquotum wordt overschreden",
"No more space available": "Geen opslagruimte meer beschikbaar",
"available_space_is_low": "Beschikbare opslagruimte laag ( {{ nb }}% )",
diff --git a/frontend/src/i18n/pl.json b/frontend/src/i18n/pl.json
index d6dc5272..940f5a66 100644
--- a/frontend/src/i18n/pl.json
+++ b/frontend/src/i18n/pl.json
@@ -130,6 +130,7 @@
"Storage Usage": "Wykorzystanie przestrzeni",
"Space status": "Status przestrzeni",
"Storage quota exceeded": "Przekroczono limit przestrzeni",
+ "The trash is read-only": "Kosz jest tylko do odczytu",
"Storage quota will be exceeded": "Limit przestrzeni zostanie przekroczony",
"No more space available": "Brak dostępnego miejsca",
"available_space_is_low": "Mało dostępnego miejsca ({{ nb }}%)",
diff --git a/frontend/src/i18n/pt-BR.json b/frontend/src/i18n/pt-BR.json
index 1cafe294..813c4670 100644
--- a/frontend/src/i18n/pt-BR.json
+++ b/frontend/src/i18n/pt-BR.json
@@ -130,6 +130,7 @@
"Storage Usage": "Uso do armazenamento",
"Space status": "Status do espaço",
"Storage quota exceeded": "Cota de armazenamento excedida",
+ "The trash is read-only": "A lixeira é somente leitura",
"Storage quota will be exceeded": "A cota de armazenamento será excedida",
"No more space available": "Sem espaço disponível",
"available_space_is_low": "Pouco espaço disponível ({{ nb }}%)",
diff --git a/frontend/src/i18n/pt.json b/frontend/src/i18n/pt.json
index 88abcf29..55a0eb3e 100644
--- a/frontend/src/i18n/pt.json
+++ b/frontend/src/i18n/pt.json
@@ -130,6 +130,7 @@
"Storage Usage": "Uso do armazenamento",
"Space status": "Estado do espaço",
"Storage quota exceeded": "A cota de armazenamento foi excedida",
+ "The trash is read-only": "A lixeira é apenas de leitura",
"Storage quota will be exceeded": "A cota de armazenamento será excedida",
"No more space available": "Sem mais espaço disponível",
"available_space_is_low": "Espaço disponível baixo ( {{ nb }}% )",
diff --git a/frontend/src/i18n/ru.json b/frontend/src/i18n/ru.json
index 1ad39c69..8f5f54aa 100644
--- a/frontend/src/i18n/ru.json
+++ b/frontend/src/i18n/ru.json
@@ -130,6 +130,7 @@
"Storage Usage": "Использование хранилища",
"Space status": "Статус пространства",
"Storage quota exceeded": "Превышена квота хранилища",
+ "The trash is read-only": "Корзина доступна только для чтения",
"Storage quota will be exceeded": "Квота хранилища будет превышена",
"No more space available": "Место закончилось",
"available_space_is_low": "Мало свободного места ({{ nb }}%)",
diff --git a/frontend/src/i18n/tr.json b/frontend/src/i18n/tr.json
index 4b3ecd06..530d6ad9 100644
--- a/frontend/src/i18n/tr.json
+++ b/frontend/src/i18n/tr.json
@@ -130,6 +130,7 @@
"Storage Usage": "Depolama Kullanımı",
"Space status": "Alan durumu",
"Storage quota exceeded": "Depolama kotası aşıldı",
+ "The trash is read-only": "Çöp kutusu salt okunurdur",
"Storage quota will be exceeded": "Depolama kotası aşılacak",
"No more space available": "Boş alan kalmadı",
"available_space_is_low": "Kullanılabilir alan düşük ( {{ nb }}% )",
diff --git a/frontend/src/i18n/zh.json b/frontend/src/i18n/zh.json
index 64754a24..0947c0bc 100644
--- a/frontend/src/i18n/zh.json
+++ b/frontend/src/i18n/zh.json
@@ -130,6 +130,7 @@
"Storage Usage": "存储使用情况",
"Space status": "空间状态",
"Storage quota exceeded": "存储配额已超出",
+ "The trash is read-only": "回收站是只读的",
"Storage quota will be exceeded": "存储配额将被超出",
"No more space available": "没有更多可用空间",
"available_space_is_low": "可用空间不足( {{ nb }}% )",