Skip to content

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

fix(backend:security): prevent path traversal & SSRF

johavend79d28c2d6cc
diff --git a/backend/src/applications/files/dto/file-operations.dto.ts b/backend/src/applications/files/dto/file-operations.dto.ts
index be7e579d..e77b4db2 100644
--- a/backend/src/applications/files/dto/file-operations.dto.ts
+++ b/backend/src/applications/files/dto/file-operations.dto.ts
@@ -6,6 +6,8 @@
import { Transform } from 'class-transformer'
import { ArrayMinSize, IsArray, IsBoolean, IsDefined, IsIn, IsInt, IsNotEmpty, IsOptional, IsString, IsUrl } from 'class-validator'
+import { RejectIfMatch } from '../../../common/decorators'
+import { regExpInvalidFileName } from '../../../common/shared'
import { tarExtension, tarGzExtension } from '../constants/compress'
export class CopyMoveFileDto {
@@ -15,13 +17,22 @@ export class CopyMoveFileDto {
@IsOptional()
@IsString()
+ @RejectIfMatch(regExpInvalidFileName, { message: 'Forbidden characters' })
// renaming use case
dstName?: string
}
export class DownloadFileDto {
@IsNotEmpty()
- @IsUrl()
+ @IsUrl({
+ // only allow HTTP(S)
+ protocols: ['http', 'https'],
+ require_protocol: true,
+ require_valid_protocol: true,
+ // reject exotic schemes and underscores
+ allow_underscores: false,
+ allow_trailing_dot: false
+ })
url: string
}
@@ -33,9 +44,10 @@ export class MakeFileDto {
}
export class CompressFileDto {
- @IsNotEmpty()
+ @IsOptional()
@IsString()
- name: string
+ @RejectIfMatch(regExpInvalidFileName, { message: 'Forbidden characters' })
+ name?: string // only used on frontend
@IsDefined()
@IsBoolean()
diff --git a/backend/src/applications/files/services/files-manager.service.ts b/backend/src/applications/files/services/files-manager.service.ts
index bd71f960..956c917c 100644
--- a/backend/src/applications/files/services/files-manager.service.ts
+++ b/backend/src/applications/files/services/files-manager.service.ts
@@ -7,6 +7,7 @@
import { HttpService } from '@nestjs/axios'
import { HttpStatus, Injectable, Logger } from '@nestjs/common'
import archiver, { Archiver, ArchiverError } from 'archiver'
+import { AxiosResponse } from 'axios'
import { PNGStream } from 'canvas'
import fs from 'node:fs'
import path from 'node:path'
@@ -33,6 +34,7 @@ import { FileLock } from '../interfaces/file-lock.interface'
import { FileError } from '../models/file-error'
import { LockConflict } from '../models/file-lock-error'
import {
+ checkFileName,
copyFiles,
createEmptyFile,
dirName,
@@ -45,6 +47,7 @@ import {
makeDir,
moveFiles,
removeFiles,
+ sanitizeName,
touchFile,
uniqueDatedFilePath,
uniqueFilePathFromDir,
@@ -53,6 +56,7 @@ import {
} from '../utils/files'
import { SendFile } from '../utils/send-file'
import { extractZip } from '../utils/unzip-file'
+import { regExpPrivateIP } from '../utils/url-file'
import { FilesLockManager } from './files-lock-manager.service'
import { FilesQueries } from './files-queries.service'
@@ -193,7 +197,8 @@ export class FilesManager {
}
for await (const part of req.files()) {
- const partFileName = part.filename.normalize()
+ // important: sanitize file names
+ const partFileName = sanitizeName(part.filename)
const dstDir = path.join(realParentPath, dirName(partFileName))
const dstFile = path.join(dstDir, fileName(partFileName))
// make dir in space
@@ -225,6 +230,7 @@ export class FilesManager {
}
async mkFile(user: UserModel, space: SpaceEnv, overwrite = false, checkLocks = true, checkDocument = false): Promise<void> {
+ checkFileName(space.realPath)
if (!overwrite && (await isPathExists(space.realPath))) {
throw new FileError(HttpStatus.BAD_REQUEST, 'Resource already exists')
}
@@ -243,6 +249,7 @@ export class FilesManager {
}
async mkDir(user: UserModel, space: SpaceEnv, recursive = false, dav?: { depth: LOCK_DEPTH; lockTokens: string[] }): Promise<void> {
+ checkFileName(space.realPath)
if (!recursive) {
if (await isPathExists(space.realPath)) {
throw new FileError(HttpStatus.METHOD_NOT_ALLOWED, 'Resource already exists')
@@ -412,8 +419,9 @@ export class FilesManager {
}
async downloadFromUrl(user: UserModel, space: SpaceEnv, url: string): Promise<void> {
- const rPath = await uniqueFilePathFromDir(space.realPath)
+ this.logger.log(`${this.downloadFromUrl.name} : ${url}`)
// create lock
+ const rPath = await uniqueFilePathFromDir(space.realPath)
const dbFile = space.dbFile
dbFile.path = path.join(dirName(dbFile.path), fileName(space.realPath))
const [ok, fileLock] = await this.filesLockManager.create(user, dbFile, DEPTH.RESOURCE)
@@ -422,26 +430,51 @@ export class FilesManager {
}
// tasking
if (space.task.cacheKey) {
+ let headRes: AxiosResponse
+
+ try {
+ headRes = await this.http.axiosRef({ method: HTTP_METHOD.HEAD, url: url, maxRedirects: 1 })
+ } catch (e) {
+ // release lock
+ await this.filesLockManager.removeLock(fileLock.key)
+ this.logger.error(`${this.downloadFromUrl.name} - ${url} : ${e}`)
+ throw new FileError(HttpStatus.BAD_REQUEST, 'Unable to download file')
+ }
+
+ if (regExpPrivateIP.test(headRes.request.socket.remoteAddress)) {
+ // release lock
+ await this.filesLockManager.removeLock(fileLock.key)
+ // prevent SSRF attack
+ throw new FileError(HttpStatus.FORBIDDEN, 'Access to internal IP addresses is forbidden')
+ }
+
+ // attempt to retrieve the Content-Length header
try {
- const pr = await this.http.axiosRef({ method: HTTP_METHOD.HEAD, url: url })
- if ('content-length' in pr.headers) {
- space.task.props.totalSize = parseInt(pr.headers['content-length'], 10) || null
+ if ('content-length' in headRes.headers) {
+ space.task.props.totalSize = parseInt(headRes.headers['content-length'], 10) || null
}
} catch (e) {
- this.logger.warn(`${this.downloadFromUrl.name} - ${e}`)
+ this.logger.debug(`${this.downloadFromUrl.name} - content-length : ${e}`)
}
FileTaskEvent.emit('startWatch', space, FILE_OPERATION.DOWNLOAD, rPath)
}
// do
try {
- const r = await this.http.axiosRef({ method: HTTP_METHOD.GET, url: url, responseType: 'stream' })
- await writeFromStream(rPath, r.data)
+ const getRes = await this.http.axiosRef({ method: HTTP_METHOD.GET, url: url, responseType: 'stream', maxRedirects: 1 })
+ if (regExpPrivateIP.test(getRes.request.socket.remoteAddress)) {
+ // Prevent SSRF attacks and perform a DNS-rebinding check if a HEAD request has already been made
+ throw new FileError(HttpStatus.FORBIDDEN, 'Access to internal IP addresses is forbidden')
+ }
+ await writeFromStream(rPath, getRes.data)
} finally {
+ // release lock
await this.filesLockManager.removeLock(fileLock.key)
}
}
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.
const srcPath = dirName(space.realPath)
// todo: a guest link tasksPath should be in specific directory (guest link has no home)
const dstPath = await uniqueFilePathFromDir(path.join(dto.compressInDirectory ? srcPath : user.tasksPath, `${dto.name}.${dto.extension}`))
diff --git a/backend/src/applications/files/services/files-methods.service.spec.ts b/backend/src/applications/files/services/files-methods.service.spec.ts
index ac89b4ab..2141c21a 100644
--- a/backend/src/applications/files/services/files-methods.service.spec.ts
+++ b/backend/src/applications/files/services/files-methods.service.spec.ts
@@ -5,29 +5,104 @@
*/
import { Test, TestingModule } from '@nestjs/testing'
+import path from 'node:path'
+import { transformAndValidate } from '../../../common/functions'
+import { Cache } from '../../../infrastructure/cache/services/cache.service'
+import { ContextManager } from '../../../infrastructure/context/services/context-manager.service'
import { DB_TOKEN_PROVIDER } from '../../../infrastructure/database/constants'
+import { NotificationsManager } from '../../notifications/services/notifications-manager.service'
+import { SharesManager } from '../../shares/services/shares-manager.service'
+import { SPACE_REPOSITORY } from '../../spaces/constants/spaces'
+import { SpaceEnv } from '../../spaces/models/space-env.model'
+import { SpaceModel } from '../../spaces/models/space.model'
import { SpacesManager } from '../../spaces/services/spaces-manager.service'
+import { SpacesQueries } from '../../spaces/services/spaces-queries.service'
+import { UserModel } from '../../users/models/user.model'
+import { UsersQueries } from '../../users/services/users-queries.service'
+import { generateUserTest } from '../../users/utils/test'
+import { tarExtension } from '../constants/compress'
+import { CompressFileDto, CopyMoveFileDto } from '../dto/file-operations.dto'
import { FilesManager } from './files-manager.service'
import { FilesMethods } from './files-methods.service'
describe(FilesMethods.name, () => {
let filesMethods: FilesMethods
+ let spacesManager: SpacesManager
+ let userTest: UserModel
+ const spaceEnv: Partial<SpaceEnv> = {
+ id: 1,
+ alias: 'project',
+ name: 'project',
+ enabled: true,
+ permissions: 'a:d:m:so',
+ role: 0,
+ realBasePath: SpaceModel.getFilesPath('project'),
+ realPath: path.join(SpaceModel.getFilesPath('project'), 'foo'),
+ url: `${SPACE_REPOSITORY.FILES}/project/foo`
+ }
beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [],
providers: [
FilesMethods,
+ SpacesManager,
{ provide: DB_TOKEN_PROVIDER, useValue: {} },
- { provide: SpacesManager, useValue: {} },
+ {
+ provide: Cache,
+ useValue: { get: () => null }
+ },
+ { provide: ContextManager, useValue: {} },
+ {
+ provide: NotificationsManager,
+ useValue: {}
+ },
+ { provide: UsersQueries, useValue: {} },
+ { provide: SharesManager, useValue: {} },
+ {
+ provide: SpacesQueries,
+ useValue: {
+ permissions: () => spaceEnv
+ }
+ },
{ provide: FilesManager, useValue: {} }
]
}).compile()
+ module.useLogger(['fatal'])
filesMethods = module.get<FilesMethods>(FilesMethods)
+ spacesManager = module.get<SpacesManager>(SpacesManager)
+ userTest = new UserModel(generateUserTest())
+ // mock
+ spacesManager.updateSpacesQuota = jest.fn().mockReturnValue(undefined)
})
it('should be defined', () => {
expect(filesMethods).toBeDefined()
+ expect(spacesManager).toBeDefined()
+ expect(userTest).toBeDefined()
+ })
+
+ it('should avoid path traversal on CopyMove action', async () => {
+ const copyMoveFileDto = { dstDirectory: '../../../foo', dstName: '../bar/../' } satisfies CopyMoveFileDto
+ expect(() => transformAndValidate(CompressFileDto, copyMoveFileDto satisfies CopyMoveFileDto)).toThrow()
+ await expect((filesMethods as any).copyMove(userTest, spaceEnv as SpaceEnv, copyMoveFileDto satisfies CopyMoveFileDto, false)).rejects.toThrow(
+ /is not valid/i
+ )
+ })
+
+ it('should avoid path traversal on Compress action', async () => {
+ const compressFileDto: CompressFileDto = {
+ name: '../../archive',
+ compressInDirectory: false,
+ files: [{ name: '../../foo', rootAlias: undefined }],
+ extension: tarExtension as typeof tarExtension
+ }
+ expect(() => transformAndValidate(CompressFileDto, compressFileDto satisfies CompressFileDto)).toThrow()
+ await expect(filesMethods.compress(userTest, spaceEnv as SpaceEnv, { ...(compressFileDto as CompressFileDto) })).rejects.toThrow(
+ /does not exist/i
+ )
+ compressFileDto.files[0].path = '../../../bar/../'
+ await expect(filesMethods.compress(userTest, spaceEnv as SpaceEnv, compressFileDto as CompressFileDto)).rejects.toThrow(/is not valid/i)
})
})
diff --git a/backend/src/applications/files/services/files-methods.service.ts b/backend/src/applications/files/services/files-methods.service.ts
index 92bde610..87dedc4f 100644
--- a/backend/src/applications/files/services/files-methods.service.ts
+++ b/backend/src/applications/files/services/files-methods.service.ts
@@ -16,7 +16,7 @@ import { FILE_OPERATION } from '../constants/operations'
import { CompressFileDto, CopyMoveFileDto, DownloadFileDto, MakeFileDto } from '../dto/file-operations.dto'
import { FileError } from '../models/file-error'
import { LockConflict } from '../models/file-lock-error'
-import { dirName, fileName, isPathExists, sanitizePathTraversal } from '../utils/files'
+import { checkFileName, dirName, fileName, isPathExists, sanitizeName } from '../utils/files'
import { SendFile } from '../utils/send-file'
import { FilesManager } from './files-manager.service'
@@ -96,6 +96,7 @@ export class FilesMethods {
}
async downloadFromUrl(user: UserModel, space: SpaceEnv, downloadDto: DownloadFileDto): Promise<void> {
+ checkFileName(space.realPath)
try {
return await this.filesManager.downloadFromUrl(user, space, downloadDto.url)
} catch (e) {
@@ -104,19 +105,31 @@ export class FilesMethods {
}
async compress(user: UserModel, space: SpaceEnv, compressFileDto: CompressFileDto): Promise<void> {
+ compressFileDto.name = checkFileName(space.realPath)
try {
for (const f of compressFileDto.files) {
+ // sanitize file name
+ f.name = sanitizeName(f.name)
// handles the case where the file is an anchored file
+ let baseSpace: SpaceEnv
if (f.path) {
- const srcSpace = await this.spacesManager.spaceEnv(user, f.path.split('/'))
- f.path = srcSpace.realPath
+ baseSpace = await this.spacesManager.spaceEnv(user, f.path.split('/'))
+ f.path = baseSpace.realPath
} else {
- f.path = f.rootAlias
- ? (await this.spacesManager.spaceEnv(user, path.join(dirName(space.url), f.rootAlias).split('/'))).realPath
- : path.join(dirName(space.realPath), f.name)
+ if (f.rootAlias) {
+ baseSpace = await this.spacesManager.spaceEnv(user, path.join(dirName(space.url), f.rootAlias).split('/'))
+ f.path = baseSpace.realPath
+ } else {
+ baseSpace = space
+ f.path = path.resolve(dirName(space.realPath), f.name)
+ }
+ }
+ // prevent path traversal
+ if (!f.path.startsWith(baseSpace.realBasePath)) {
+ return this.handleError(space, FILE_OPERATION.COMPRESS, new FileError(HttpStatus.FORBIDDEN, `${f.name} not allowed`))
}
if (!(await isPathExists(f.path))) {
- return this.handleError(space, FILE_OPERATION.COMPRESS, new FileError(HttpStatus.NOT_FOUND, `${f.name} does not exists`))
+ return this.handleError(space, FILE_OPERATION.COMPRESS, new FileError(HttpStatus.NOT_FOUND, `${f.name} does not exist`))
}
}
return await this.filesManager.compress(user, space, compressFileDto)
@@ -151,12 +164,10 @@ export class FilesMethods {
path: string
name: string
}> {
- const dstUrl = path.join(
- sanitizePathTraversal(copyMoveFileDto.dstDirectory),
- copyMoveFileDto.dstName ? sanitizePathTraversal(copyMoveFileDto.dstName) : fileName(space.realPath)
- )
- const dstSpace = await this.spacesManager.spaceEnv(user, dstUrl.split('/'))
+ const dstUrl = path.join(copyMoveFileDto.dstDirectory, copyMoveFileDto.dstName ? copyMoveFileDto.dstName : fileName(space.realPath))
+ let dstSpace: SpaceEnv
try {
+ dstSpace = await this.spacesManager.spaceEnv(user, dstUrl.split('/'))
await this.filesManager.copyMove(user, space, dstSpace, isMove)
} catch (e) {
this.handleError(space, isMove ? FILE_OPERATION.MOVE : FILE_OPERATION.COPY, e, dstSpace)
@@ -165,7 +176,7 @@ export class FilesMethods {
}
private handleError(space: SpaceEnv, action: string, e: any, dstSpace?: SpaceEnv) {
- this.logger.error(`unable to ${action} ${space.url}${dstSpace ? ` -> ${dstSpace.url}` : ''} : ${e}`)
+ this.logger.error(`unable to ${action} ${space.url}${dstSpace?.url ? ` -> ${dstSpace.url}` : ''} : ${e}`)
if (e instanceof LockConflict) {
throw new HttpException('The file is locked', HttpStatus.LOCKED)
} else if (e instanceof FileError) {
diff --git a/backend/src/applications/files/services/files-tasks-manager.service.ts b/backend/src/applications/files/services/files-tasks-manager.service.ts
index a0b01a04..cdd28842 100644
--- a/backend/src/applications/files/services/files-tasks-manager.service.ts
+++ b/backend/src/applications/files/services/files-tasks-manager.service.ts
@@ -39,11 +39,15 @@ export class FilesTasksManager {
)
}
- createTask(type: FILE_OPERATION, user: UserModel, space: SpaceEnv, dto: any, method: string): FileTask {
+ static getCacheKey(userId: number, taskId?: string): string {
+ return `${CACHE_TASK_PREFIX}-${userId}-${taskId || '*'}`
+ }
+
+ async createTask(type: FILE_OPERATION, user: UserModel, space: SpaceEnv, dto: any, method: string): Promise<FileTask> {
const taskId: string = crypto.randomUUID()
const cacheKey = FilesTasksManager.getCacheKey(user.id, taskId)
const newTask = new FileTask(taskId, type, dirName(space.url), fileName(space.url))
- this.storeTask(cacheKey, newTask)
+ await this.storeTask(cacheKey, newTask)
space.task = { cacheKey: cacheKey, props: {} }
this.filesMethods[method](user, space, dto)
.then((data: any) => {
@@ -109,10 +113,14 @@ export class FilesTasksManager {
return sendFile.stream(req, res)
}
- private storeTask(cacheKey: string, task: FileTask) {
+ private async storeTask(cacheKey: string, task: FileTask) {
task.startedAt = currentTimeStamp(null, true)
task.status = FileTaskStatus.PENDING
- this.cache.set(cacheKey, task, CACHE_TASK_TTL).catch((e: Error) => this.logger.error(`${this.storeTask.name} - ${e}`))
+ try {
+ await this.cache.set(cacheKey, task, CACHE_TASK_TTL)
+ } catch (e) {
+ this.logger.error(`${this.storeTask.name} - ${e}`)
+ }
}
private async setTaskDone(cacheKey: string, status: FileTaskStatus, result: any): Promise<void> {
@@ -227,8 +235,4 @@ export class FilesTasksManager {
space.task.props.progress = (100 * space.task.props.size) / space.task.props.totalSize
}
}
-
- static getCacheKey(userId: number, taskId?: string): string {
- return `${CACHE_TASK_PREFIX}-${userId}-${taskId || '*'}`
- }
}
diff --git a/backend/src/applications/files/utils/files.ts b/backend/src/applications/files/utils/files.ts
index d09a7e71..ae8fc79b 100644
--- a/backend/src/applications/files/utils/files.ts
+++ b/backend/src/applications/files/utils/files.ts
@@ -15,13 +15,30 @@ import path from 'node:path'
import { Readable } from 'node:stream'
import { pipeline } from 'node:stream/promises'
import { formatDateISOString } from '../../../common/functions'
-import { currentTimeStamp, regexAvoidPathTraversal } from '../../../common/shared'
+import { currentTimeStamp, isValidFileName, regExpPreventPathTraversal } from '../../../common/shared'
import { DEFAULT_HIGH_WATER_MARK, EXTRA_MIMES_TYPE } from '../constants/files'
import type { FileProps } from '../interfaces/file-props.interface'
import { FileError } from '../models/file-error'
-export function sanitizePathTraversal(fPath: string): string {
- return fPath.replace(regexAvoidPathTraversal, '')
+export function sanitizePath(fPath: string): string {
+ return path.normalize(fPath).replace(regExpPreventPathTraversal, '')
+}
+
+export function sanitizeName(name: string): string {
+ return name
+ .replace(/^\s+|[. ]+$/g, '') // trimStart + trimEnd + strip trailing dots
+ .replace(/[/\\]/g, '') // remove slashes
+ .replace(/\.\./g, '') // remove '..'
+}
+
+export function checkFileName(fPath: string): string {
+ const fName = fileName(fPath)
+ try {
+ isValidFileName(fName)
+ return fName
+ } catch {
+ throw new FileError(HttpStatus.BAD_REQUEST, 'Forbidden characters')
+ }
}
export function isPathExists(rPath: string): Promise<boolean> {
diff --git a/backend/src/applications/files/utils/url-file.ts b/backend/src/applications/files/utils/url-file.ts
new file mode 100644
index 00000000..f4fe8569
--- /dev/null
+++ b/backend/src/applications/files/utils/url-file.ts
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2012-2025 Johan Legrand <[email protected]>
+ * This file is part of Sync-in | The open source file sync and share solution
+ * See the LICENSE file for licensing details
+ */
+
+const parts = [
+ // IPv4 loopback (127.0.0.0/8)
+ '127\\.(?:\\d{1,3}\\.){2}\\d{1,3}',
+ // IPv4 link-local (169.254.0.0/16)
+ '169\\.254\\.\\d{1,3}\\.\\d{1,3}',
+ // IPv4 Carrier-grade NAT (100.64.0.0/10)
+ '100\\.(?:6[4-9]|[7-9]\\d|1[01]\\d|12[0-7])\\.\\d{1,3}\\.\\d{1,3}',
+ // IPv4 private (10.0.0.0/8)
+ '10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}',
+ // IPv4 private (192.168.0.0/16)
+ '192\\.168\\.\\d{1,3}\\.\\d{1,3}',
+ // IPv4 private (172.16.0.0/12)
+ '172\\.(?:1[6-9]|2\\d|3[0-1])\\.\\d{1,3}\\.\\d{1,3}',
+ // IPv4 & IPv6 loopback
+ '::1',
+ '::',
+ '0.0.0.0',
+ // IPv6 Unique Local Address (fc00::/7)
+ 'f[cd][0-9a-f]{2}:[0-9a-f:]+',
+ // IPv6 link-local (fe80::/10)
+ 'fe[89ab][0-9a-f]{2}:[0-9a-f:]+'
+]
+
+export const regExpPrivateIP = new RegExp(`^(?:${parts.join('|')})$`, 'i')
diff --git a/backend/src/applications/shares/dto/create-or-update-share.dto.ts b/backend/src/applications/shares/dto/create-or-update-share.dto.ts
index 71f3a51c..db107302 100644
--- a/backend/src/applications/shares/dto/create-or-update-share.dto.ts
+++ b/backend/src/applications/shares/dto/create-or-update-share.dto.ts
@@ -7,6 +7,7 @@
import { Transform, Type } from 'class-transformer'
import { IsArray, IsBoolean, IsEnum, IsInt, IsNotEmpty, IsOptional, IsString, ValidateIf, ValidateNested } from 'class-validator'
import { FileSpace } from '../../files/interfaces/file-space.interface'
+import { sanitizeName, sanitizePath } from '../../files/utils/files'
import { CreateOrUpdateLinkDto } from '../../links/dto/create-or-update-link.dto'
import { MEMBER_TYPE, MEMBER_TYPE_REVERSE } from '../../users/constants/member'
import { SHARE_TYPE } from '../constants/shares'
@@ -39,12 +40,12 @@ export class ShareMemberDto {
export class ShareFileSpaceRootDto {
@IsOptional()
@IsString()
- @Transform(({ value }) => (value ? value.trim() : ''))
+ @Transform(({ value }) => (value ? sanitizeName(value.trim()) : ''))
alias: string
@IsOptional()
@IsString()
- @Transform(({ value }) => (value ? value.trim() : ''))
+ @Transform(({ value }) => (value ? sanitizeName(value.trim()) : ''))
name: string
}
@@ -82,6 +83,7 @@ export class ShareFileDto implements Omit<FileSpace, 'mime' | 'name' | 'inTrash'
@IsNotEmpty()
@IsString()
+ @Transform(({ value }) => sanitizePath(value))
path: string
@IsOptional()
@@ -101,12 +103,12 @@ export class CreateOrUpdateShareDto {
@IsNotEmpty()
@IsString()
- @Transform(({ value }) => (value ? value.trim() : ''))
+ @Transform(({ value }) => (value ? sanitizeName(value.trim()) : ''))
name: string
@IsOptional()
@IsString()
- @Transform(({ value }) => (value ? value.trim() : ''))
+ @Transform(({ value }) => (value ? sanitizeName(value.trim()) : ''))
alias?: string
@IsOptional()
diff --git a/backend/src/applications/shares/services/shares-manager.service.ts b/backend/src/applications/shares/services/shares-manager.service.ts
index 3a3cc85a..3d81a75a 100644
--- a/backend/src/applications/shares/services/shares-manager.service.ts
+++ b/backend/src/applications/shares/services/shares-manager.service.ts
@@ -182,7 +182,14 @@ export class SharesManager {
l.permissions = intersectPermissions(space.envPermissions, l.permissions)
}
// check file
- space.setPaths(user, createOrUpdateShareDto.file.space.root.alias, createOrUpdateShareDto.file.path.split('/').slice(space.root.id ? 1 : 0))
+ try {
+ space.setPaths(user, createOrUpdateShareDto.file.space.root.alias, createOrUpdateShareDto.file.path.split('/').slice(space.root.id ? 1 : 0))
+ } catch (e) {
+ if (e instanceof FileError) {
+ throw new HttpException(e.message, e.httpCode)
+ }
+ throw new HttpException(e.message, HttpStatus.BAD_REQUEST)
+ }
if (!(await isPathExists(space.realPath))) {
this.logger.warn(`${this.createShare.name} - space location does not exist : *${space.alias}* (${space.id}) : ${space.realPath}`)
throw new HttpException('The location does not exist', HttpStatus.NOT_FOUND)
@@ -318,7 +325,14 @@ export class SharesManager {
// create a fake space env -> share env
const pShareEnv: Partial<ShareEnv> = new SpaceEnv(pShare, null, false)
- pShareEnv.setPaths(user, null, filePath.split('/'))
+ try {
+ pShareEnv.setPaths(user, null, filePath.split('/'))
+ } catch (e) {
+ if (e instanceof FileError) {
+ throw new HttpException(e.message, e.httpCode)
+ }
+ throw new HttpException(e.message, HttpStatus.BAD_REQUEST)
+ }
// check file
if (!(await isPathExists(pShareEnv.realPath))) {
this.logger.warn(
@@ -1088,7 +1102,6 @@ export class SharesManager {
}
private async notifyGuestLink(user: UserModel, link: SpaceMemberDto | ShareMemberDto, spaceOrShareName: string, action: ACTION) {
- console.log(spaceOrShareName, action, link)
if (!link.linkSettings.email) {
return
}
diff --git a/backend/src/applications/spaces/dto/create-or-update-space.dto.ts b/backend/src/applications/spaces/dto/create-or-update-space.dto.ts
index 30e638f4..ee715372 100644
--- a/backend/src/applications/spaces/dto/create-or-update-space.dto.ts
+++ b/backend/src/applications/spaces/dto/create-or-update-space.dto.ts
@@ -6,6 +6,7 @@
import { Transform, Type } from 'class-transformer'
import { ArrayMinSize, IsArray, IsBoolean, IsInt, IsNotEmpty, IsOptional, IsString, ValidateNested } from 'class-validator'
+import { sanitizeName } from '../../files/utils/files'
import { CreateOrUpdateLinkDto } from '../../links/dto/create-or-update-link.dto'
import { MEMBER_TYPE, MEMBER_TYPE_REVERSE } from '../../users/constants/member'
import { SPACE_ROLE } from '../constants/spaces'
@@ -23,7 +24,7 @@ export class SpaceMemberDto {
@IsNotEmpty()
@IsInt()
- spaceRole?: number
+ spaceRole?: SPACE_ROLE = SPACE_ROLE.IS_MEMBER
@IsOptional()
@IsString()
@@ -46,12 +47,12 @@ export class CreateOrUpdateSpaceDto {
@IsNotEmpty()
@IsString()
- @Transform(({ value }) => (value ? value.trim() : ''))
+ @Transform(({ value }) => (value ? sanitizeName(value.trim()) : ''))
name: string
@IsOptional()
@IsString()
- @Transform(({ value }) => (value ? value.trim() : ''))
+ @Transform(({ value }) => (value ? sanitizeName(value.trim()) : ''))
alias?: string
@IsOptional()
diff --git a/backend/src/applications/spaces/dto/space-roots.dto.ts b/backend/src/applications/spaces/dto/space-roots.dto.ts
index 2f2cf522..9ba6b1c9 100644
--- a/backend/src/applications/spaces/dto/space-roots.dto.ts
+++ b/backend/src/applications/spaces/dto/space-roots.dto.ts
@@ -6,6 +6,7 @@
import { Transform, Type } from 'class-transformer'
import { IsDefined, IsInt, IsNotEmpty, IsNotEmptyObject, IsObject, IsOptional, IsString, ValidateIf, ValidateNested } from 'class-validator'
+import { sanitizeName, sanitizePath } from '../../files/utils/files'
import { SPACE_ALIAS, SPACE_REPOSITORY } from '../constants/spaces'
import type { SpaceRootProps } from '../models/space-root-props.model'
@@ -19,14 +20,14 @@ class SpaceRootOwnerDto {
login: string
}
-class SpaceRootFileDto {
+export class SpaceRootFileDto {
@IsNotEmpty()
@IsInt()
id: number
@IsNotEmpty()
@IsString()
- @Transform(({ value }) => (value ? value.replace(`${SPACE_REPOSITORY.FILES}/${SPACE_ALIAS.PERSONAL}/`, '') : ''))
+ @Transform(({ value }) => (value ? sanitizePath(value).replace(`${SPACE_REPOSITORY.FILES}/${SPACE_ALIAS.PERSONAL}/`, '') : ''))
path: string
}
@@ -37,10 +38,12 @@ export class SpaceRootDto implements SpaceRootProps {
@IsNotEmpty()
@IsString()
+ @Transform(({ value }) => (value ? sanitizeName(value.trim()) : ''))
alias: string
@IsNotEmpty()
@IsString()
+ @Transform(({ value }) => (value ? sanitizeName(value.trim()) : ''))
name: string
@IsDefined()
diff --git a/backend/src/applications/spaces/models/space-env.model.ts b/backend/src/applications/spaces/models/space-env.model.ts
index 75b0c14a..37384313 100644
--- a/backend/src/applications/spaces/models/space-env.model.ts
+++ b/backend/src/applications/spaces/models/space-env.model.ts
@@ -121,6 +121,7 @@ export class SpaceEnv implements Pick<Space, 'id' | 'alias' | 'name' | 'enabled'
setPaths(user: UserModel, rootAlias: string, paths: string[]) {
this.paths = this.inSharesRepository && rootAlias ? [rootAlias, ...paths] : paths
if (!this.inSharesList) {
+ // realPathFromSpace may throw a FileError exception
;[this.realBasePath, this.realPath] = realPathFromSpace(user, this, true)
this.dbFile = dbFileFromSpace(user.id, this)
}
diff --git a/backend/src/applications/spaces/services/spaces-browser.service.ts b/backend/src/applications/spaces/services/spaces-browser.service.ts
index a72e0a97..00f61971 100644
--- a/backend/src/applications/spaces/services/spaces-browser.service.ts
+++ b/backend/src/applications/spaces/services/spaces-browser.service.ts
@@ -20,7 +20,7 @@ import { UserModel } from '../../users/models/user.model'
import { LOCK_SCOPE } from '../../webdav/constants/webdav'
import { SpaceFiles } from '../interfaces/space-files.interface'
import { SpaceEnv } from '../models/space-env.model'
-import { realPathFromRootFile, validRealPath } from '../utils/paths'
+import { realPathFromRootFile, IsRealPathIsDirAndExists } from '../utils/paths'
import { SpacesManager } from './spaces-manager.service'
import { SpacesQueries } from './spaces-queries.service'
@@ -119,7 +119,7 @@ export class SpacesBrowser {
if (space.inSharesList) return []
const fsFiles: FileProps[] = []
try {
- await validRealPath(space.realPath, true, true, space.realBasePath)
+ await IsRealPathIsDirAndExists(space.realPath)
} catch (e) {
this.logger.warn(`${this.parseFS.name} - ${space.realPath} : ${e.message}`)
throw new HttpException(e.message, e.httpCode)
diff --git a/backend/src/applications/spaces/services/spaces-manager.service.spec.ts b/backend/src/applications/spaces/services/spaces-manager.service.spec.ts
index d79143c9..800290e0 100644
--- a/backend/src/applications/spaces/services/spaces-manager.service.spec.ts
+++ b/backend/src/applications/spaces/services/spaces-manager.service.spec.ts
@@ -9,6 +9,7 @@ import { Test, TestingModule } from '@nestjs/testing'
import fs from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'
+import { transformAndValidate } from '../../../common/functions'
import { exportConfiguration } from '../../../configuration/config.environment'
import { Cache } from '../../../infrastructure/cache/services/cache.service'
import { ContextManager } from '../../../infrastructure/context/services/context-manager.service'
@@ -16,18 +17,21 @@ import { DB_TOKEN_PROVIDER } from '../../../infrastructure/database/constants'
import { FilesConfig } from '../../files/files.config'
import { FileError } from '../../files/models/file-error'
import { FilesQueries } from '../../files/services/files-queries.service'
-import { dirName, removeFiles } from '../../files/utils/files'
+import { removeFiles } from '../../files/utils/files'
import { LinksQueries } from '../../links/services/links-queries.service'
import { NotificationsManager } from '../../notifications/services/notifications-manager.service'
import { SharesManager } from '../../shares/services/shares-manager.service'
import { SharesQueries } from '../../shares/services/shares-queries.service'
+import { MEMBER_TYPE } from '../../users/constants/member'
import { UserModel } from '../../users/models/user.model'
import { UsersQueries } from '../../users/services/users-queries.service'
import { generateUserTest } from '../../users/utils/test'
import { SPACE_ALIAS, SPACE_ALL_OPERATIONS, SPACE_OPERATION, SPACE_PERMS_SEP, SPACE_REPOSITORY } from '../constants/spaces'
+import { CreateOrUpdateSpaceDto, SpaceMemberDto } from '../dto/create-or-update-space.dto'
+import { SpaceRootFileDto } from '../dto/space-roots.dto'
import { SpaceEnv } from '../models/space-env.model'
import { SpaceModel } from '../models/space.model'
-import { validRealPath } from '../utils/paths'
+import { IsRealPathIsDirAndExists } from '../utils/paths'
import { SpacesManager } from './spaces-manager.service'
import { SpacesQueries } from './spaces-queries.service'
@@ -83,6 +87,23 @@ describe(SpacesManager.name, () => {
expect(userTest).toBeDefined()
})
+ it('should prevent path traversal', () => {
+ const createOrUpdateSpaceDto = transformAndValidate(CreateOrUpdateSpaceDto, {
+ name: '../../../foo/..bar',
+ alias: '../../bar.',
+ managers: [transformAndValidate(SpaceMemberDto, { id: 0, type: MEMBER_TYPE.USER })]
+ } satisfies CreateOrUpdateSpaceDto)
+ expect(createOrUpdateSpaceDto.name).toEqual('foobar')
+ expect(createOrUpdateSpaceDto.alias).toEqual('bar')
+ const spaceRootFileDto = transformAndValidate(SpaceRootFileDto, { id: 0, path: '../../foo/bar' } satisfies SpaceRootFileDto)
+ expect(spaceRootFileDto.path).toEqual('foo/bar')
+ const spaceRootFileDto2 = transformAndValidate(SpaceRootFileDto, {
+ id: 0,
+ path: `${SPACE_REPOSITORY.FILES}/${SPACE_ALIAS.PERSONAL}/../../../foo/bar`
+ } satisfies SpaceRootFileDto)
+ expect(spaceRootFileDto2.path).toEqual('foo/bar')
+ })
+
it('should validate the permissions on personal & shares space', async () => {
const personalSpace = await spacesManager.spaceEnv(userTest, ['files', SPACE_ALIAS.PERSONAL])
expect(personalSpace.envPermissions).toBe(
@@ -98,13 +119,13 @@ describe(SpacesManager.name, () => {
for (const repository of [SPACE_REPOSITORY.FILES, SPACE_REPOSITORY.TRASH]) {
const spaceEnv = await spacesManager.spaceEnv(userTest, [repository, SPACE_ALIAS.PERSONAL, 'foo', 'bar'])
expect(spaceEnv.envPermissions).toBe(SPACE_ALL_OPERATIONS)
- await expect(validRealPath(spaceEnv.realPath, true, true, spaceEnv.realBasePath)).rejects.toThrow()
+ await expect(IsRealPathIsDirAndExists(spaceEnv.realPath)).rejects.toThrow()
const repoPath = UserModel.getRepositoryPath(userTest.login, spaceEnv.inTrashRepository)
await fs.mkdir(path.join(repoPath, 'foo', 'bar'), { recursive: true })
- await expect(validRealPath(spaceEnv.realPath, true, true, spaceEnv.realBasePath)).resolves.toBeUndefined()
+ await expect(IsRealPathIsDirAndExists(spaceEnv.realPath)).resolves.toBeUndefined()
await removeFiles(path.join(repoPath, 'foo', 'bar'))
try {
- await validRealPath(spaceEnv.realPath, true, true, spaceEnv.realBasePath)
+ await IsRealPathIsDirAndExists(spaceEnv.realPath)
} catch (e) {
expect(e).toBeInstanceOf(FileError)
}
@@ -123,10 +144,10 @@ describe(SpacesManager.name, () => {
spacesQueries.permissions = jest.fn().mockReturnValue(permissions)
for (const repository of [SPACE_REPOSITORY.FILES, SPACE_REPOSITORY.TRASH]) {
const spaceEnv = await spacesManager.spaceEnv(userTest, [repository, spaceAlias, 'foo', 'bar'])
- await expect(validRealPath(spaceEnv.realPath, true, true, spaceEnv.realBasePath)).rejects.toThrow()
+ await expect(IsRealPathIsDirAndExists(spaceEnv.realPath)).rejects.toThrow()
const repoPath = SpaceModel.getRepositoryPath(spaceAlias, spaceEnv.inTrashRepository)
await fs.mkdir(path.join(repoPath, spaceEnv.root.alias, ...spaceEnv.paths), { recursive: true })
- await expect(validRealPath(spaceEnv.realPath, true, true, spaceEnv.realBasePath)).resolves.toBeUndefined()
+ await expect(IsRealPathIsDirAndExists(spaceEnv.realPath)).resolves.toBeUndefined()
await removeFiles(path.join(repoPath, spaceEnv.root.alias, ...spaceEnv.paths))
}
})
@@ -143,9 +164,9 @@ describe(SpacesManager.name, () => {
const spaceEnv = await spacesManager.spaceEnv(userTest, [SPACE_REPOSITORY.FILES, spaceAlias, 'foo', 'bar'])
const rootPath = path.join(tmpDir, ...spaceEnv.paths)
await fs.mkdir(rootPath, { recursive: true })
- await expect(validRealPath(spaceEnv.realPath, true, true, spaceEnv.realBasePath)).resolves.toBeUndefined()
+ await expect(IsRealPathIsDirAndExists(spaceEnv.realPath)).resolves.toBeUndefined()
await removeFiles(rootPath)
- await expect(validRealPath(spaceEnv.realPath, true, true, spaceEnv.realBasePath)).rejects.toThrow()
+ await expect(IsRealPathIsDirAndExists(spaceEnv.realPath)).rejects.toThrow()
})
it(`should validate (or not) the space : ${spaceAlias} with a root (a file/directory from user)`, async () => {
@@ -166,23 +187,14 @@ describe(SpacesManager.name, () => {
spacesQueries.permissions = jest.fn().mockReturnValueOnce(permissions)
const spaceEnv = await spacesManager.spaceEnv(userTest, [SPACE_REPOSITORY.FILES, spaceAlias, 'document', 'bar'])
await fs.mkdir(path.join(UserModel.getFilesPath(userTest.login), 'foo', 'bar'), { recursive: true })
- await expect(validRealPath(spaceEnv.realPath, true, true, spaceEnv.realBasePath)).resolves.toBeUndefined()
+ await expect(IsRealPathIsDirAndExists(spaceEnv.realPath)).resolves.toBeUndefined()
await removeFiles(path.join(UserModel.getFilesPath(userTest.login), 'foo', 'bar'))
- await expect(validRealPath(spaceEnv.realPath, true, true, spaceEnv.realBasePath)).rejects.toThrow()
+ await expect(IsRealPathIsDirAndExists(spaceEnv.realPath)).rejects.toThrow()
delete spaceEnv.root.file.path
try {
- await validRealPath(spaceEnv.realPath, true, true, spaceEnv.realBasePath)
+ await IsRealPathIsDirAndExists(spaceEnv.realPath)
} catch (e) {
expect(e).toBeInstanceOf(FileError)
}
})
-
- it('should not pass the path validation (validRealPath)', async () => {
- const testPath = path.join(tmpDir, 'foo', 'bar')
- await expect(validRealPath(testPath, true, true, '/dev')).rejects.toThrow()
- await fs.mkdir(dirName(testPath), { recursive: true })
- await fs.writeFile(path.join(tmpDir, 'foo', 'bar'), '')
- await expect(validRealPath(testPath, true, true, dirName(testPath))).rejects.toThrow()
- await removeFiles(dirName(testPath))
- })
})
diff --git a/backend/src/applications/spaces/services/spaces-manager.service.ts b/backend/src/applications/spaces/services/spaces-manager.service.ts
index 599851a5..d80afef9 100644
--- a/backend/src/applications/spaces/services/spaces-manager.service.ts
+++ b/backend/src/applications/spaces/services/spaces-manager.service.ts
@@ -15,6 +15,7 @@ import { createSlug, regExpNumberSuffix } from '../../../common/shared'
import { Cache } from '../../../infrastructure/cache/services/cache.service'
import { ContextManager } from '../../../infrastructure/context/services/context-manager.service'
import { DEFAULT_FILTERS } from '../../files/constants/files'
+import { FileError } from '../../files/models/file-error'
import { dirListFileNames, dirSize, getProps, isPathExists, moveFiles, removeFiles } from '../../files/utils/files'
import { LINK_TYPE } from '../../links/constants/links'
import { NOTIFICATION_APP, NOTIFICATION_APP_EVENT } from '../../notifications/constants/notifications'
@@ -145,7 +146,7 @@ export class SpacesManager {
return space
} catch (e) {
this.logger.warn(`${this.spaceEnv.name} - *${space.alias}* : ${e}`)
- throw new HttpException(e.message, e.httpCode)
+ throw new HttpException(e.message, e instanceof FileError ? e.httpCode : HttpStatus.BAD_REQUEST)
}
}
@@ -724,7 +725,7 @@ export class SpacesManager {
await removeFiles(spaceLocation)
this.logger.warn(`${this.deleteSpaceLocation.name} - space *${spaceAlias}* location was deleted`)
} else {
- this.logger.warn(`${this.deleteSpaceLocation.name} - space *${spaceAlias}* location does not exists : ${spaceLocation}`)
+ this.logger.warn(`${this.deleteSpaceLocation.name} - space *${spaceAlias}* location does not exist : ${spaceLocation}`)
}
}
@@ -749,7 +750,7 @@ export class SpacesManager {
}
}
} else {
- this.logger.warn(`${this.renameSpaceLocation.name} - *${oldSpaceAlias}* space location does not exists : ${currentSpaceLocation}`)
+ this.logger.warn(`${this.renameSpaceLocation.name} - *${oldSpaceAlias}* space location does not exist : ${currentSpaceLocation}`)
return false
}
}
diff --git a/backend/src/applications/spaces/utils/paths.ts b/backend/src/applications/spaces/utils/paths.ts
index 27c7ac0c..04e647e3 100644
--- a/backend/src/applications/spaces/utils/paths.ts
+++ b/backend/src/applications/spaces/utils/paths.ts
@@ -5,26 +5,31 @@
*/
import { HttpStatus } from '@nestjs/common'
+import fs from 'fs/promises'
import path from 'node:path'
import { FileDBProps } from '../../files/interfaces/file-db-props.interface'
import { FileProps } from '../../files/interfaces/file-props.interface'
import { FileError } from '../../files/models/file-error'
-import { isPathExists, isPathIsDir } from '../../files/utils/files'
import { UserModel } from '../../users/models/user.model'
import { CACHE_QUOTA_SPACE_PREFIX, CACHE_QUOTA_USER_PREFIX } from '../constants/cache'
import { SPACE_REPOSITORY } from '../constants/spaces'
import { SpaceEnv } from '../models/space-env.model'
import { SpaceModel } from '../models/space.model'
-export async function validRealPath(rPath: string, onlyDir: boolean = true, mustExists: boolean = true, bPath?: string) {
- if (bPath && !rPath.startsWith(bPath)) {
- throw new FileError(HttpStatus.FORBIDDEN, 'Location is not allowed')
- }
- if (mustExists && !(await isPathExists(rPath))) {
- throw new FileError(HttpStatus.NOT_FOUND, 'Location not found')
- }
- if (onlyDir && !(await isPathIsDir(rPath))) {
- throw new FileError(HttpStatus.FORBIDDEN, 'Location is not a directory')
+export async function IsRealPathIsDirAndExists(rPath: string) {
+ try {
+ const stats = await fs.stat(rPath)
+ if (!stats.isDirectory()) {
+ throw new FileError(HttpStatus.BAD_REQUEST, 'Location is not a directory')
+ }
+ } catch (e) {
+ if (e instanceof FileError) {
+ throw new FileError(e.httpCode, e.message)
+ }
+ if (e.code === 'ENOENT') {
+ throw new FileError(HttpStatus.NOT_FOUND, 'Location not found')
+ }
+ throw new FileError(HttpStatus.BAD_REQUEST, e.message)
}
}
@@ -67,7 +72,11 @@ export function realPathFromSpace(user: UserModel, space: SpaceEnv, withBasePath
} else {
throw new FileError(HttpStatus.NOT_FOUND, 'Space root not found')
}
- const rPath = path.join(bPath, ...fPath)
+ const rPath = path.resolve(bPath, ...fPath)
+ // prevent path traversal
+ if (!rPath.startsWith(bPath)) {
+ throw new FileError(HttpStatus.FORBIDDEN, 'Location is not allowed')
+ }
return withBasePath ? [bPath, rPath] : rPath
}
diff --git a/backend/src/applications/spaces/utils/routes.ts b/backend/src/applications/spaces/utils/routes.ts
index 02c50118..adcc9776 100644
--- a/backend/src/applications/spaces/utils/routes.ts
+++ b/backend/src/applications/spaces/utils/routes.ts
@@ -4,8 +4,8 @@
* See the LICENSE file for licensing details
*/
-import { sanitizePathTraversal } from '../../files/utils/files'
+import { sanitizePath } from '../../files/utils/files'
export function PATH_TO_SPACE_SEGMENTS(path: string): string[] {
- return sanitizePathTraversal(path).split('/').filter(Boolean)
+ return sanitizePath(path).split('/').filter(Boolean)
}
diff --git a/backend/src/applications/sync/services/sync-manager.service.ts b/backend/src/applications/sync/services/sync-manager.service.ts
index 3ebff8ad..ed8f23d9 100644
--- a/backend/src/applications/sync/services/sync-manager.service.ts
+++ b/backend/src/applications/sync/services/sync-manager.service.ts
@@ -265,7 +265,7 @@ export class SyncManager {
}
private handleError(space: SpaceEnv, action: string, e: any, dstSpace?: SpaceEnv) {
- this.logger.error(`unable to ${action} ${space.url}${dstSpace ? ` -> ${dstSpace.url}` : ''} : ${e}`)
+ this.logger.error(`unable to ${action} ${space.url}${dstSpace?.url ? ` -> ${dstSpace.url}` : ''} : ${e}`)
if (e instanceof LockConflict) {
throw new HttpException('The file is locked', HttpStatus.LOCKED)
} else if (e instanceof FileError) {
diff --git a/backend/src/applications/sync/services/sync-paths-manager.service.ts b/backend/src/applications/sync/services/sync-paths-manager.service.ts
index bf535a75..b1cd5be6 100644
--- a/backend/src/applications/sync/services/sync-paths-manager.service.ts
+++ b/backend/src/applications/sync/services/sync-paths-manager.service.ts
@@ -57,7 +57,7 @@ export class SyncPathsManager {
}
const syncDBProps: SyncDBProps = await this.getDBProps(req.space)
- // ensures the right remote path is stored
+ // important : ensures the right remote path is used and stored
syncPathDto.remotePath = req.params['*']
// add permissions (skip end point protection using getEnvPermission)
syncPathDto.permissions = getEnvPermissions(req.space, req.space.root)
diff --git a/backend/src/applications/users/services/admin-users-manager.service.ts b/backend/src/applications/users/services/admin-users-manager.service.ts
index dd367c0c..382729b0 100644
--- a/backend/src/applications/users/services/admin-users-manager.service.ts
+++ b/backend/src/applications/users/services/admin-users-manager.service.ts
@@ -272,7 +272,7 @@ export class AdminUsersManager {
if (await this.adminQueries.deleteGroup(groupId)) {
this.logger.log(`${this.deleteGroup.name} - group (${groupId}) was deleted`)
} else {
- this.logger.warn(`${this.deleteGroup.name} - group (${groupId}) does not exists`)
+ this.logger.warn(`${this.deleteGroup.name} - group (${groupId}) does not exist`)
throw new HttpException('Unable to delete group', HttpStatus.BAD_REQUEST)
}
}
@@ -342,7 +342,7 @@ export class AdminUsersManager {
await removeFiles(userSpace)
this.logger.log(`${this.deleteUserSpace.name} - user space *${userLogin}* was deleted`)
} else {
- this.logger.warn(`${this.deleteUserSpace.name} - user space *${userLogin}* does not exists : ${userSpace}`)
+ this.logger.warn(`${this.deleteUserSpace.name} - user space *${userLogin}* does not exist : ${userSpace}`)
}
} catch (e) {
this.logger.warn(`${this.deleteUserSpace.name} - user space *${userLogin}* (${userSpace}) was not deleted : ${e}`)
@@ -369,7 +369,7 @@ export class AdminUsersManager {
}
}
} else {
- this.logger.warn(`${this.renameUserSpace.name} - user space *${oldLogin}* does not exists : ${currentUserSpace}`)
+ this.logger.warn(`${this.renameUserSpace.name} - user space *${oldLogin}* does not exist : ${currentUserSpace}`)
return false
}
}
diff --git a/backend/src/applications/users/services/admin-users-queries.service.ts b/backend/src/applications/users/services/admin-users-queries.service.ts
index 893cb9a8..a80d4f95 100644
--- a/backend/src/applications/users/services/admin-users-queries.service.ts
+++ b/backend/src/applications/users/services/admin-users-queries.service.ts
@@ -307,7 +307,7 @@ export class AdminUsersQueries {
this.logger.log(`${this.removeUserFromGroup.name} - user (${userId}) was removed from group (${groupId})`)
this.usersQueries.clearWhiteListCaches([userId])
} catch (e) {
- this.logger.error(`${this.removeUserFromGroup.name} - user (${userId}) or group (${groupId}) does not exists : ${e}`)
+ this.logger.error(`${this.removeUserFromGroup.name} - user (${userId}) or group (${groupId}) does not exist : ${e}`)
throw new Error('Unable to remove user from group')
}
}
diff --git a/backend/src/applications/users/services/users-manager.service.ts b/backend/src/applications/users/services/users-manager.service.ts
index 319d5b1d..5fe17113 100755
--- a/backend/src/applications/users/services/users-manager.service.ts
+++ b/backend/src/applications/users/services/users-manager.service.ts
@@ -349,7 +349,7 @@ export class UsersManager {
if (await this.usersQueries.deletePersonalGroup(groupId)) {
this.logger.log(`${this.deletePersonalGroup.name} - group (${groupId}) was deleted`)
} else {
- this.logger.warn(`${this.deletePersonalGroup.name} - group (${groupId}) does not exists`)
+ this.logger.warn(`${this.deletePersonalGroup.name} - group (${groupId}) does not exist`)
throw new HttpException('Unable to delete group', HttpStatus.BAD_REQUEST)
}
}
diff --git a/backend/src/common/decorators.ts b/backend/src/common/decorators.ts
new file mode 100644
index 00000000..46aaaf33
--- /dev/null
+++ b/backend/src/common/decorators.ts
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2012-2025 Johan Legrand <[email protected]>
+ * This file is part of Sync-in | The open source file sync and share solution
+ * See the LICENSE file for licensing details
+ */
+
+import { registerDecorator, ValidationArguments, ValidationOptions } from 'class-validator'
+
+export function RejectIfMatch(regex: RegExp, validationOptions?: ValidationOptions) {
+ return function (object: any, propertyName: string) {
+ registerDecorator({
+ name: 'RejectIfMatch',
+ target: object.constructor,
+ propertyName: propertyName,
+ options: validationOptions,
+ validator: {
+ validate(value: any, _args: ValidationArguments) {
+ return typeof value === 'string' && !regex.test(value)
+ },
+ defaultMessage(args: ValidationArguments) {
+ return `${args.property} ne doit pas correspondre à ${regex}`
+ }
+ }
+ })
+ }
+}
diff --git a/backend/src/common/shared.ts b/backend/src/common/shared.ts
index 461d4e97..003fbb57 100644
--- a/backend/src/common/shared.ts
+++ b/backend/src/common/shared.ts
@@ -4,8 +4,9 @@
* See the LICENSE file for licensing details
*/
-export const regExpInvalidFileName = /^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$|[<>:"/\\|?*]/
-export const regexAvoidPathTraversal = /\.\.\//g
+// eslint-disable-next-line no-control-regex
+export const regExpInvalidFileName = /^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$|[<>:"/\\|?*\x00-\x1f\x80-\x9f]/
+export const regExpPreventPathTraversal = /^(\.\.(\/|\\|$))+/
export const regExpNumberSuffix = /-\d+$/
export const forbiddenChars = '\\ / : * ? " < > |'