Skip to content

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

fix(backend:files): centralize file id validation and resolution

johaven0148bfeacb05
diff --git a/backend/src/applications/comments/services/comments-manager.service.spec.ts b/backend/src/applications/comments/services/comments-manager.service.spec.ts
index 34959798..8dead7c8 100644
--- a/backend/src/applications/comments/services/comments-manager.service.spec.ts
+++ b/backend/src/applications/comments/services/comments-manager.service.spec.ts
@@ -92,6 +92,7 @@ describe(CommentsManager.name, () => {
vi.mocked(getProps).mockResolvedValue({ name: 'file.txt', path: 'folder' } as FileProps)
vi.mocked(dirName).mockReturnValue('/space/folder')
vi.mocked(fileName).mockReturnValue('file.txt')
+ filesQueries.getOrCreateSpaceFile.mockImplementation(async (fileId: number) => fileId)
})
it('should be defined', () => {
@@ -100,7 +101,7 @@ describe(CommentsManager.name, () => {
describe('getComments', () => {
it('returns [] if no fileId', async () => {
- filesQueries.getSpaceFileId.mockResolvedValue(0)
+ filesQueries.getSpaceFileId.mockResolvedValue(undefined)
const res = await commentsManager.getComments(user, makeSpace())
@@ -147,7 +148,7 @@ describe(CommentsManager.name, () => {
})
it('rejects BAD_REQUEST if provided fileId mismatches', async () => {
- filesQueries.getSpaceFileId.mockResolvedValue(100)
+ filesQueries.getOrCreateSpaceFile.mockRejectedValueOnce(new HttpException('File id mismatch', HttpStatus.BAD_REQUEST))
await expect(commentsManager.createComment(user, makeSpace(), { fileId: 101, content: 'x' } as any)).rejects.toMatchObject({
status: HttpStatus.BAD_REQUEST
@@ -157,7 +158,6 @@ describe(CommentsManager.name, () => {
it('uses getOrCreate when fileId > 0 but file is not yet indexed', async () => {
const space = makeSpace()
const fileProps = { name: 'file.txt', path: 'folder', id: undefined }
- filesQueries.getSpaceFileId.mockResolvedValue(undefined)
filesQueries.getOrCreateSpaceFile.mockResolvedValue(77)
commentQueries.createComment.mockResolvedValue(1)
commentQueries.getComments.mockResolvedValue([{ id: 1, fileId: 77, content: 'hi' }])
@@ -165,9 +165,8 @@ describe(CommentsManager.name, () => {
const res = await commentsManager.createComment(user, space, { fileId: 42, content: 'hi' } as any)
- expect(filesQueries.getSpaceFileId).toHaveBeenCalledTimes(1)
- expect(filesQueries.getSpaceFileId).toHaveBeenCalledWith(fileProps, space.dbFile)
- expect(filesQueries.getOrCreateSpaceFile).toHaveBeenCalledWith(42, fileProps, space.dbFile)
+ expect(filesQueries.getSpaceFileId).not.toHaveBeenCalled()
+ expect(filesQueries.getOrCreateSpaceFile).toHaveBeenCalledWith(42, fileProps, space.dbFile, { rejectIdMismatch: true })
expect(commentQueries.createComment).toHaveBeenCalledWith(42, 77, 'hi')
expect(res).toMatchObject({ id: 1, fileId: 77, content: 'hi' })
})
@@ -186,7 +185,7 @@ describe(CommentsManager.name, () => {
// Let the microtask run the catch of createComment
await new Promise((r) => setImmediate(r))
- expect(filesQueries.getOrCreateSpaceFile).toHaveBeenCalledWith(-1, fileProps, space.dbFile)
+ expect(filesQueries.getOrCreateSpaceFile).toHaveBeenCalledWith(-1, fileProps, space.dbFile, { rejectIdMismatch: true })
expect(filesQueries.getSpaceFileId).not.toHaveBeenCalled()
expect(commentQueries.createComment).toHaveBeenCalledWith(42, 555, 'hello')
expect(notificationsManager.create).not.toHaveBeenCalled()
@@ -197,7 +196,7 @@ describe(CommentsManager.name, () => {
})
it('notifies members when present', async () => {
- filesQueries.getSpaceFileId.mockResolvedValue(10)
+ filesQueries.getOrCreateSpaceFile.mockResolvedValue(10)
commentQueries.createComment.mockResolvedValue(1)
commentQueries.getComments.mockResolvedValue([{ id: 1, fileId: 10, content: 'c' }])
commentQueries.membersToNotify.mockResolvedValue([{ id: 2, email: '[email protected]' }])
@@ -236,7 +235,7 @@ describe(CommentsManager.name, () => {
})
it('logs an error if notificationsManager.create rejects (covers catch in notify)', async () => {
- filesQueries.getSpaceFileId.mockResolvedValue(10)
+ filesQueries.getOrCreateSpaceFile.mockResolvedValue(10)
commentQueries.createComment.mockResolvedValue(1)
commentQueries.getComments.mockResolvedValue([{ id: 1, fileId: 10, content: 'c' }])
commentQueries.membersToNotify.mockResolvedValue([{ id: 2, email: '[email protected]' }])
@@ -254,7 +253,7 @@ describe(CommentsManager.name, () => {
})
it('does not notify if no members', async () => {
- filesQueries.getSpaceFileId.mockResolvedValue(10)
+ filesQueries.getOrCreateSpaceFile.mockResolvedValue(10)
commentQueries.createComment.mockResolvedValue(1)
commentQueries.getComments.mockResolvedValue([{ id: 1 }])
commentQueries.membersToNotify.mockResolvedValue([])
diff --git a/backend/src/applications/comments/services/comments-manager.service.ts b/backend/src/applications/comments/services/comments-manager.service.ts
index 49d98384..6a0f1a2f 100644
--- a/backend/src/applications/comments/services/comments-manager.service.ts
+++ b/backend/src/applications/comments/services/comments-manager.service.ts
@@ -24,8 +24,8 @@ export class CommentsManager {
) {}
async getComments(user: UserModel, space: SpaceEnv): Promise<Comment[]> {
- const fileId: number = await this.getFileId(space)
- if (!fileId) {
+ const fileId = await this.getFileId(space)
+ if (fileId === undefined) {
return []
}
return this.commentQueries.getComments(user.id, space.dbFile?.ownerId === user.id, fileId)
@@ -38,19 +38,7 @@ export class CommentsManager {
// Maybe to implement later
throw new HttpException('Not supported on this kind of location', HttpStatus.BAD_REQUEST)
}
- let fileId: number
- if (createCommentDto.fileId > 0) {
- const dbFileId = await this.getFileId(space)
- if (dbFileId === undefined) {
- fileId = await this.getFileId(space, createCommentDto.fileId)
- } else if (createCommentDto.fileId !== dbFileId) {
- throw new HttpException('File id mismatch', HttpStatus.BAD_REQUEST)
- } else {
- fileId = dbFileId
- }
- } else {
- fileId = await this.getFileId(space, createCommentDto.fileId)
- }
+ const fileId = await this.getFileId(space, createCommentDto.fileId)
const commentId: number = await this.commentQueries.createComment(user.id, fileId, createCommentDto.content)
this.notify(user, fileId, space, createCommentDto.content).catch((e: Error) => this.logger.error({ tag: this.createComment.name, msg: `${e}` }))
return (await this.commentQueries.getComments(user.id, space.dbFile?.ownerId === user.id, null, commentId))[0]
@@ -81,14 +69,16 @@ export class CommentsManager {
}
}
+ private async getFileId(space: SpaceEnv): Promise<number | undefined>
+ private async getFileId(space: SpaceEnv, fileId: number): Promise<number>
private async getFileId(space: SpaceEnv, fileId?: number): Promise<number | undefined> {
if (!(await isPathExists(space.realPath))) {
throw new HttpException('Location not found', HttpStatus.NOT_FOUND)
}
const fileProps: FileProps = { ...(await getProps(space.realPath, space.dbFile.path)), id: undefined }
- if (fileId) {
+ if (fileId !== undefined) {
// get or create
- return this.filesQueries.getOrCreateSpaceFile(fileId, fileProps, space.dbFile)
+ return this.filesQueries.getOrCreateSpaceFile(fileId, fileProps, space.dbFile, { rejectIdMismatch: true })
} else {
// get only
return this.filesQueries.getSpaceFileId(fileProps, space.dbFile)
diff --git a/backend/src/applications/files/services/files-favorites-manager.service.spec.ts b/backend/src/applications/files/services/files-favorites-manager.service.spec.ts
index e7afe1e4..d1d423a8 100644
--- a/backend/src/applications/files/services/files-favorites-manager.service.spec.ts
+++ b/backend/src/applications/files/services/files-favorites-manager.service.spec.ts
@@ -1,4 +1,4 @@
-import { HttpStatus } from '@nestjs/common'
+import { HttpException, HttpStatus } from '@nestjs/common'
import { Test, TestingModule } from '@nestjs/testing'
import { SharesQueries } from '../../shares/services/shares-queries.service'
import { SPACE_ALIAS } from '../../spaces/constants/spaces'
@@ -20,7 +20,6 @@ vi.mock('../utils/files', () => ({
describe(FilesFavoritesManager.name, () => {
let service: FilesFavoritesManager
let filesQueries: {
- getSpaceFileId: Mock
getOrCreateSpaceFile: Mock
}
let filesFavoritesQueries: {
@@ -38,7 +37,6 @@ describe(FilesFavoritesManager.name, () => {
vi.mocked(isPathExists).mockResolvedValue(true)
vi.mocked(getProps).mockResolvedValue({ name: 'file.txt', path: 'docs' } as FileProps)
filesQueries = {
- getSpaceFileId: vi.fn(),
getOrCreateSpaceFile: vi.fn()
}
filesFavoritesQueries = {
@@ -161,33 +159,32 @@ describe(FilesFavoritesManager.name, () => {
})
it('should add an already indexed favorite', async () => {
- filesQueries.getSpaceFileId.mockResolvedValueOnce(42)
+ filesQueries.getOrCreateSpaceFile.mockResolvedValueOnce(42)
+ const space = makeSpace()
- await expect(service.addFavorite(userWithPermissions(), makeSpace(), 42)).resolves.toEqual({ fileId: 42 })
+ await expect(service.addFavorite(userWithPermissions(), space, 42)).resolves.toEqual({ fileId: 42 })
- expect(filesQueries.getOrCreateSpaceFile).not.toHaveBeenCalled()
+ const fileProps = { name: 'file.txt', path: 'docs', id: undefined }
+ expect(filesQueries.getOrCreateSpaceFile).toHaveBeenCalledWith(42, fileProps, space.dbFile, { rejectIdMismatch: true })
expect(filesFavoritesQueries.addFavorite).toHaveBeenCalledWith(7, 42)
})
it('should index an untracked file before adding it', async () => {
- filesQueries.getSpaceFileId.mockResolvedValueOnce(undefined)
filesQueries.getOrCreateSpaceFile.mockResolvedValueOnce(84)
const space = makeSpace()
await expect(service.addFavorite(userWithPermissions(), space, -1)).resolves.toEqual({ fileId: 84 })
const fileProps = { name: 'file.txt', path: 'docs', id: undefined }
- expect(filesQueries.getSpaceFileId).toHaveBeenCalledWith(fileProps, space.dbFile)
- expect(filesQueries.getOrCreateSpaceFile).toHaveBeenCalledWith(-1, fileProps, space.dbFile)
+ expect(filesQueries.getOrCreateSpaceFile).toHaveBeenCalledWith(-1, fileProps, space.dbFile, { rejectIdMismatch: true })
expect(filesFavoritesQueries.addFavorite).toHaveBeenCalledWith(7, 84)
})
it('should reject a favorite when the provided file id does not match the indexed file', async () => {
- filesQueries.getSpaceFileId.mockResolvedValueOnce(43)
+ filesQueries.getOrCreateSpaceFile.mockRejectedValueOnce(new HttpException('File id mismatch', HttpStatus.BAD_REQUEST))
await expect(service.addFavorite(userWithPermissions(), makeSpace(), 42)).rejects.toMatchObject({ status: HttpStatus.BAD_REQUEST })
- expect(filesQueries.getOrCreateSpaceFile).not.toHaveBeenCalled()
expect(filesFavoritesQueries.addFavorite).not.toHaveBeenCalled()
})
diff --git a/backend/src/applications/files/services/files-favorites-manager.service.ts b/backend/src/applications/files/services/files-favorites-manager.service.ts
index c29623c0..310d796a 100644
--- a/backend/src/applications/files/services/files-favorites-manager.service.ts
+++ b/backend/src/applications/files/services/files-favorites-manager.service.ts
@@ -85,7 +85,11 @@ export class FilesFavoritesManager {
async addFavorite(user: UserModel, space: SpaceEnv, fileId: number): Promise<FileFavoriteIdentity> {
this.checkSupportedTarget(space)
- const resolvedFileId = await this.resolveFileId(space, fileId)
+ if (!(await isPathExists(space.realPath))) {
+ throw new HttpException('Location not found', HttpStatus.NOT_FOUND)
+ }
+ const fileProps: FileProps = { ...(await getProps(space.realPath, space.dbFile.path)), id: undefined }
+ const resolvedFileId = await this.filesQueries.getOrCreateSpaceFile(fileId, fileProps, space.dbFile, { rejectIdMismatch: true })
await this.filesFavoritesQueries.addFavorite(user.id, resolvedFileId)
return { fileId: resolvedFileId }
}
@@ -94,21 +98,6 @@ export class FilesFavoritesManager {
return this.filesFavoritesQueries.removeFavorite(user.id, fileId)
}
- private async resolveFileId(space: SpaceEnv, fileId: number): Promise<number> {
- if (!(await isPathExists(space.realPath))) {
- throw new HttpException('Location not found', HttpStatus.NOT_FOUND)
- }
- const fileProps: FileProps = { ...(await getProps(space.realPath, space.dbFile.path)), id: undefined }
- const dbFileId = await this.filesQueries.getSpaceFileId(fileProps, space.dbFile)
- if (dbFileId !== undefined) {
- if (fileId > 0 && fileId !== dbFileId) {
- throw new HttpException('File id mismatch', HttpStatus.BAD_REQUEST)
- }
- return dbFileId
- }
- return this.filesQueries.getOrCreateSpaceFile(fileId, fileProps, space.dbFile)
- }
-
private checkSupportedTarget(space: SpaceEnv): void {
if (space.inTrashRepository) {
throw new HttpException('The trash is read-only', HttpStatus.FORBIDDEN)
diff --git a/backend/src/applications/files/services/files-queries.service.spec.ts b/backend/src/applications/files/services/files-queries.service.spec.ts
new file mode 100644
index 00000000..45b00e19
--- /dev/null
+++ b/backend/src/applications/files/services/files-queries.service.spec.ts
@@ -0,0 +1,60 @@
+import { HttpStatus } from '@nestjs/common'
+import type { FileDBProps } from '../interfaces/file-db-props.interface'
+import type { FileProps } from '../interfaces/file-props.interface'
+import { FilesQueries } from './files-queries.service'
+
+describe(FilesQueries.name, () => {
+ const file = { name: 'file.txt', path: 'docs', isDir: false } as FileProps
+ const dbFile = { ownerId: 7, inTrash: false, path: 'docs/file.txt' } satisfies FileDBProps
+ let service: FilesQueries
+ let select: ReturnType<typeof vi.fn>
+
+ beforeEach(() => {
+ const limit = vi.fn().mockResolvedValue([])
+ const where = vi.fn().mockReturnValue({ limit })
+ const from = vi.fn().mockReturnValue({ where })
+ select = vi.fn().mockReturnValue({ from })
+ service = new FilesQueries({ select } as any)
+ vi.spyOn(service['logger'], 'warn').mockImplementation(() => undefined)
+ vi.spyOn(service, 'getSpaceFileId').mockResolvedValue(43)
+ })
+
+ it('rejects a positive id that differs from the existing file', async () => {
+ await expect(service.getOrCreateSpaceFile(42, file, dbFile, { rejectIdMismatch: true })).rejects.toMatchObject({
+ status: HttpStatus.BAD_REQUEST,
+ response: 'File id mismatch'
+ })
+ })
+
+ it('accepts a positive id that matches the existing file', async () => {
+ vi.mocked(service.getSpaceFileId).mockResolvedValueOnce(42)
+
+ await expect(service.getOrCreateSpaceFile(42, file, dbFile, { rejectIdMismatch: true })).resolves.toBe(42)
+ })
+
+ it.each([0, Number.MAX_SAFE_INTEGER + 1])('rejects the invalid space file id %s', async (fileId) => {
+ await expect(service.getOrCreateSpaceFile(fileId, file, dbFile)).rejects.toMatchObject({
+ status: HttpStatus.BAD_REQUEST,
+ response: 'Invalid file id'
+ })
+ expect(select).not.toHaveBeenCalled()
+ expect(service.getSpaceFileId).not.toHaveBeenCalled()
+ })
+
+ it.each([0, Number.MAX_SAFE_INTEGER + 1])('rejects the invalid user file id %s', async (fileId) => {
+ await expect(service.getOrCreateUserFile(7, { ...file, id: fileId })).rejects.toMatchObject({
+ status: HttpStatus.BAD_REQUEST,
+ response: 'Invalid file id'
+ })
+ expect(select).not.toHaveBeenCalled()
+ })
+
+ it('keeps the previous reconciliation behavior by default', async () => {
+ await expect(service.getOrCreateSpaceFile(42, file, dbFile)).resolves.toBe(43)
+ })
+
+ it('accepts a negative inode in strict mode', async () => {
+ await expect(service.getOrCreateSpaceFile(-42, file, dbFile, { rejectIdMismatch: true })).resolves.toBe(43)
+ expect(select).not.toHaveBeenCalled()
+ })
+})
diff --git a/backend/src/applications/files/services/files-queries.service.ts b/backend/src/applications/files/services/files-queries.service.ts
index 96d1d548..b6ebcda6 100644
--- a/backend/src/applications/files/services/files-queries.service.ts
+++ b/backend/src/applications/files/services/files-queries.service.ts
@@ -1,11 +1,11 @@
-import { Inject, Injectable, Logger } from '@nestjs/common'
+import { HttpException, HttpStatus, Inject, Injectable, Logger } from '@nestjs/common'
import { and, desc, eq, getTableColumns, inArray, isNotNull, isNull, or, SelectedFields, sql, SQL } from 'drizzle-orm'
import { DB_TOKEN_PROVIDER } from '../../../infrastructure/database/constants'
import { DBSchema } from '../../../infrastructure/database/interfaces/database.interface'
import { concatDistinctObjectsInArray, convertToWhere, dbCheckAffectedRows, dbGetInsertedId } from '../../../infrastructure/database/utils'
import { fileHasCommentsSubquerySQL } from '../../comments/schemas/comments.schema'
import { shares } from '../../shares/schemas/shares.schema'
-import type { SpaceBrowseContext, SpaceBrowseDetails } from '../../spaces/interfaces/space-files.interface'
+import type { GetOrCreateSpaceFileOptions, SpaceBrowseContext, SpaceBrowseDetails } from '../../spaces/interfaces/space-files.interface'
import { spacesRoots } from '../../spaces/schemas/spaces-roots.schema'
import { spaces } from '../../spaces/schemas/spaces.schema'
import { syncClients } from '../../sync/schemas/sync-clients.schema'
@@ -17,7 +17,7 @@ import { File } from '../schemas/file.interface'
import { filesFavorites } from '../schemas/files-favorites.schema'
import { filesRecents } from '../schemas/files-recents.schema'
import { childFilesMatch, childFilesReplacePath, childPathMatch, filePathSQL, files } from '../schemas/files.schema'
-import { dirName, fileName, isPathInside } from '../utils/files'
+import { assertValidFileId, dirName, fileName, isPathInside } from '../utils/files'
@Injectable()
export class FilesQueries {
@@ -93,7 +93,8 @@ export class FilesQueries {
}
async getOrCreateUserFile(userId: number, file: FileProps): Promise<number> {
- if (file.id && file.id > 0) {
+ assertValidFileId(file.id)
+ if (file.id > 0) {
const [searchFileInDB] = await this.db
.select({ id: files.id })
.from(files)
@@ -108,7 +109,8 @@ export class FilesQueries {
return dbGetInsertedId(await this.db.insert(files).values({ ...file, id: undefined, ownerId: userId } as File))
}
- async getOrCreateSpaceFile(fileId: number, file: FileProps, dbFile: FileDBProps): Promise<number> {
+ async getOrCreateSpaceFile(fileId: number, file: FileProps, dbFile: FileDBProps, options: GetOrCreateSpaceFileOptions = {}): Promise<number> {
+ assertValidFileId(fileId)
// `isDir` is intentionally excluded here: this flow reconciles an existing path before insert,
// even if the caller has a stale file/dir kind for the same location.
const fileInDB = {
@@ -116,7 +118,7 @@ export class FilesQueries {
name: file.name,
path: file.path
}
- const hasDbFileId = Number.isSafeInteger(fileId) && fileId > 0
+ const hasDbFileId = fileId > 0
if (hasDbFileId) {
const [searchFileInDB] = await this.db
.select({ id: files.id })
@@ -136,7 +138,12 @@ export class FilesQueries {
// Before inserting, check whether a record already exists at this path to avoid
// creating duplicate rows when repeated calls index the same file.
const existingId = await this.getSpaceFileId(file, dbFile, { withDir: false })
- if (existingId !== undefined) return existingId
+ if (existingId !== undefined) {
+ if (options.rejectIdMismatch && hasDbFileId && existingId !== fileId) {
+ throw new HttpException('File id mismatch', HttpStatus.BAD_REQUEST)
+ }
+ return existingId
+ }
// `fileInDB` keeps the DB scope and uses the `FileProps` path/name.
return dbGetInsertedId(await this.db.insert(files).values({ ...file, ...fileInDB, id: undefined } as File))
diff --git a/backend/src/applications/files/utils/files.ts b/backend/src/applications/files/utils/files.ts
index 6b843b0a..988a9cf0 100644
--- a/backend/src/applications/files/utils/files.ts
+++ b/backend/src/applications/files/utils/files.ts
@@ -1,4 +1,4 @@
-import { HttpStatus } from '@nestjs/common'
+import { HttpException, HttpStatus } from '@nestjs/common'
import { WriteStream } from 'fs'
import fse from 'fs-extra'
import mime from 'mime-types'
@@ -50,6 +50,12 @@ export function sanitizeName(name: string): string {
.replace(/^\s+|[. ]+$/g, '') // trimStart + trimEnd + strip trailing dots
}
+export function assertValidFileId(fileId: number): void {
+ if (!Number.isSafeInteger(fileId) || fileId === 0) {
+ throw new HttpException('Invalid file id', HttpStatus.BAD_REQUEST)
+ }
+}
+
export function checkFileName(fPath: string): string {
const fName = fileName(fPath)
try {
diff --git a/backend/src/applications/shares/services/shares-manager.service.ts b/backend/src/applications/shares/services/shares-manager.service.ts
index 7f69e6d7..ec393aa1 100644
--- a/backend/src/applications/shares/services/shares-manager.service.ts
+++ b/backend/src/applications/shares/services/shares-manager.service.ts
@@ -220,7 +220,9 @@ export class SharesManager {
if (!isSpaceRoot && !isExternalSpaceRoot) {
const fileProps: FileProps = { ...(await getProps(space.realPath, space.dbFile.path)), id: undefined }
// get or create file id
- share.fileId = await this.spacesQueries.getOrCreateSpaceFile(createOrUpdateShareDto.file.id, fileProps, space.dbFile)
+ share.fileId = await this.spacesQueries.getOrCreateSpaceFile(createOrUpdateShareDto.file.id, fileProps, space.dbFile, {
+ rejectIdMismatch: true
+ })
}
} else {
// unexpected case
@@ -387,7 +389,9 @@ export class SharesManager {
if (!isLinkedToShareSpaceRoot && !isLinkedToShareExternalPath) {
// fileId is mandatory for a file in a child share
const fileProps: FileProps = { ...(await getProps(pShareEnv.realPath, pShareEnv.dbFile.path)), id: undefined }
- fileId = await this.spacesQueries.getOrCreateSpaceFile(createOrUpdateShareDto.file.id, fileProps, pShareEnv.dbFile)
+ fileId = await this.spacesQueries.getOrCreateSpaceFile(createOrUpdateShareDto.file.id, fileProps, pShareEnv.dbFile, {
+ rejectIdMismatch: true
+ })
}
const share: Partial<Share> = {
diff --git a/backend/src/applications/spaces/interfaces/space-files.interface.ts b/backend/src/applications/spaces/interfaces/space-files.interface.ts
index c495c3ef..e42ea3b4 100644
--- a/backend/src/applications/spaces/interfaces/space-files.interface.ts
+++ b/backend/src/applications/spaces/interfaces/space-files.interface.ts
@@ -12,6 +12,10 @@ export type SpaceBrowseDetails = {
favorites: boolean
} | null
+export interface GetOrCreateSpaceFileOptions {
+ rejectIdMismatch?: boolean
+}
+
export interface SpaceFiles {
space: {
alias: string
diff --git a/backend/src/applications/spaces/services/spaces-queries.service.ts b/backend/src/applications/spaces/services/spaces-queries.service.ts
index 1dcf2225..b55f2105 100644
--- a/backend/src/applications/spaces/services/spaces-queries.service.ts
+++ b/backend/src/applications/spaces/services/spaces-queries.service.ts
@@ -38,7 +38,7 @@ import { usersGroups } from '../../users/schemas/users-groups.schema'
import { userFullNameSQL, users } from '../../users/schemas/users.schema'
import { SPACE_ROLE } from '../constants/spaces'
import { SpaceMemberDto } from '../dto/create-or-update-space.dto'
-import type { SpaceBrowseDetails } from '../interfaces/space-files.interface'
+import type { GetOrCreateSpaceFileOptions, SpaceBrowseDetails } from '../interfaces/space-files.interface'
import { SpaceEnv } from '../models/space-env.model'
import { SpaceProps } from '../models/space-props.model'
import { SpaceRootProps } from '../models/space-root-props.model'
@@ -708,8 +708,8 @@ export class SpacesQueries {
return this.filesQueries.getOrCreateUserFile(userId, file)
}
- getOrCreateSpaceFile(fileId: number, file: FileProps, dbFile: FileDBProps): Promise<number> {
- return this.filesQueries.getOrCreateSpaceFile(fileId, file, dbFile)
+ getOrCreateSpaceFile(fileId: number, file: FileProps, dbFile: FileDBProps, options: GetOrCreateSpaceFileOptions = {}): Promise<number> {
+ return this.filesQueries.getOrCreateSpaceFile(fileId, file, dbFile, options)
}
async clearCachePermissions(spaceAlias: string, rootAliases?: string[], userIds?: number[]) {
diff --git a/backend/src/applications/sync/services/sync-paths-manager.service.spec.ts b/backend/src/applications/sync/services/sync-paths-manager.service.spec.ts
index 4354f960..84243f9c 100644
--- a/backend/src/applications/sync/services/sync-paths-manager.service.spec.ts
+++ b/backend/src/applications/sync/services/sync-paths-manager.service.spec.ts
@@ -65,7 +65,7 @@ describe(SyncPathsManager.name, () => {
let service: SyncPathsManager
let spacesManager: { spaceEnv: Mock }
let usersQueries: Record<string, Mock>
- let filesQueries: { getSpaceFileId: Mock; getOrCreateSpaceFile: Mock }
+ let filesQueries: { getOrCreateSpaceFile: Mock }
let notificationsManager: { create: Mock }
let syncQueries: {
getClient: Mock
@@ -84,7 +84,6 @@ describe(SyncPathsManager.name, () => {
spacesManager = { spaceEnv: vi.fn() }
usersQueries = {}
filesQueries = {
- getSpaceFileId: vi.fn(),
getOrCreateSpaceFile: vi.fn()
}
notificationsManager = {
@@ -102,7 +101,9 @@ describe(SyncPathsManager.name, () => {
}
vi.mocked(isPathExists).mockReset()
vi.mocked(isPathIsDir).mockReset()
- vi.mocked(getProps).mockReset()
+ vi.mocked(getProps)
+ .mockReset()
+ .mockResolvedValue({ id: -1, name: 'file' } as FileProps)
vi.mocked(getEnvPermissions).mockReset().mockReturnValue('server-perms')
vi.mocked(currentTimeStamp).mockReset().mockReturnValue(1000)
@@ -583,28 +584,16 @@ describe(SyncPathsManager.name, () => {
})
})
- describe('getOrCreateFileId (private) branches', () => {
- it('should return existing file id without creation', async () => {
- vi.mocked(getProps).mockResolvedValue({ name: 'file' } as FileProps)
- filesQueries.getSpaceFileId.mockResolvedValue(101)
+ describe('getOrCreateFileId (private)', () => {
+ it('should resolve or create a file id from its inode', async () => {
+ vi.mocked(getProps).mockResolvedValue({ id: -101, name: 'file' } as FileProps)
+ filesQueries.getOrCreateSpaceFile.mockResolvedValue(101)
const id = await (service as any).getOrCreateFileId({
realPath: '/rp',
dbFile: { path: '.' }
})
expect(id).toBe(101)
- expect(filesQueries.getOrCreateSpaceFile).not.toHaveBeenCalled()
- })
-
- it('should create file when not exists and return its id', async () => {
- vi.mocked(getProps).mockResolvedValue({ id: 999, name: 'file' } as FileProps)
- filesQueries.getSpaceFileId.mockResolvedValue(0)
- filesQueries.getOrCreateSpaceFile.mockResolvedValue(202)
- const id = await (service as any).getOrCreateFileId({
- realPath: '/rp',
- dbFile: { path: '.' }
- })
- expect(id).toBe(202)
- expect(filesQueries.getOrCreateSpaceFile).toHaveBeenCalledWith(0, expect.objectContaining({ id: undefined }), { path: '.' })
+ expect(filesQueries.getOrCreateSpaceFile).toHaveBeenCalledWith(-101, expect.objectContaining({ id: undefined }), { path: '.' })
})
})
})
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 bdaea9bf..2be59e7d 100644
--- a/backend/src/applications/sync/services/sync-paths-manager.service.ts
+++ b/backend/src/applications/sync/services/sync-paths-manager.service.ts
@@ -218,11 +218,7 @@ export class SyncPathsManager {
private async getOrCreateFileId(space: SpaceEnv): Promise<number> {
const fileProps: FileProps = await getProps(space.realPath, space.dbFile.path)
- let fileId: number = await this.filesQueries.getSpaceFileId(fileProps, space.dbFile)
- if (!fileId) {
- fileId = await this.filesQueries.getOrCreateSpaceFile(fileId, { ...fileProps, id: undefined }, space.dbFile)
- }
- return fileId
+ return this.filesQueries.getOrCreateSpaceFile(fileProps.id, { ...fileProps, id: undefined }, space.dbFile)
}
private async notify(userId: number, action: ACTION, remotePath: string) {