Skip to content

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

fix(backend:links): atomically enforce public link access limits

johavenf1895c8dd97b
diff --git a/backend/src/applications/links/services/links-manager.service.spec.ts b/backend/src/applications/links/services/links-manager.service.spec.ts
index 8b51d051..c245ead2 100644
--- a/backend/src/applications/links/services/links-manager.service.spec.ts
+++ b/backend/src/applications/links/services/links-manager.service.spec.ts
@@ -51,7 +51,7 @@ describe(LinksManager.name, () => {
linksQueriesMock = {
linkFromUUID: vi.fn(),
spaceLink: vi.fn(),
- incrementLinkNbAccess: vi.fn().mockResolvedValue(undefined)
+ consumeLinkAccess: vi.fn().mockResolvedValue(true)
} as any
usersManagerMock = {
@@ -113,6 +113,7 @@ describe(LinksManager.name, () => {
beforeEach(() => {
vi.clearAllMocks()
+ linksQueriesMock.consumeLinkAccess.mockResolvedValue(true)
})
it('should be defined', () => {
@@ -200,20 +201,14 @@ describe(LinksManager.name, () => {
stream: vi.fn().mockResolvedValueOnce(streamable)
} as any)
- // cover: incrementLinkNbAccess.catch(...) should log an error when the query rejects
- const logErrorSpy = vi.spyOn((service as any).logger, 'error').mockImplementation(() => undefined as any)
- linksQueriesMock.incrementLinkNbAccess.mockRejectedValueOnce(new Error('increment boom'))
-
const result = await service.linkDownload(identity, link.uuid, req, res)
expect(result).toBe(streamable)
expect(filesManagerMock.sendFileFromSpace).toHaveBeenCalled()
- expect(linksQueriesMock.incrementLinkNbAccess).toHaveBeenCalledWith(link.uuid)
+ expect(linksQueriesMock.consumeLinkAccess).toHaveBeenCalledWith(link.uuid)
// Assert repository selection for a share file (space falsy)
// should call spacesManager.spaceEnv with SHARES and share alias when link.space is falsy
expect(spacesManagerMock.spaceEnv).toHaveBeenCalledWith(expect.anything(), ['shares', 'share-alias'])
- // should log error when increment fails
- expect(logErrorSpy).toHaveBeenCalled()
})
it('authenticates and returns cookies when link targets a directory and user is different', async () => {
@@ -223,7 +218,6 @@ describe(LinksManager.name, () => {
space: { alias: 'files', name: 'My Space' },
share: { isDir: true, name: 'ignored', alias: 'ignored' }
} as any
- linksQueriesMock.spaceLink.mockResolvedValueOnce(spaceLink)
const loginDto: any = { token: 'jwt' }
authManagerMock.setCookies.mockResolvedValueOnce(loginDto)
@@ -235,6 +229,7 @@ describe(LinksManager.name, () => {
const result = await service.linkAccess(identity, link.uuid, req, res)
expect(result).toBe(loginDto)
+ expect(linksQueriesMock.consumeLinkAccess).toHaveBeenCalledWith(link.uuid)
expect(usersManagerMock.updateAccesses).toHaveBeenCalledWith(expect.anything(), req.ip, true)
expect(authManagerMock.setCookies).toHaveBeenCalled()
// additionally cover the "space truthy" branch by calling the private helper directly
@@ -254,21 +249,38 @@ describe(LinksManager.name, () => {
})
})
- it('returns undefined for already authenticated directory access (same user) and does not set cookies or increment', async () => {
+ it('keeps an authenticated directory session after the limit is reached without consuming another access', async () => {
const sameUserIdentity = { id: baseLink.user.id, login: 'john' }
- const link = { ...baseLink, requireAuth: true }
+ const link = { ...baseLink, requireAuth: true, limitAccess: 1, nbAccess: 1 }
linksQueriesMock.linkFromUUID.mockResolvedValueOnce(link)
- const spaceLink = {
- space: { alias: 'files', name: 'Space' },
- share: { isDir: true, name: 'dir', alias: 'share' }
- } as any
- linksQueriesMock.spaceLink.mockResolvedValueOnce(spaceLink)
const result = await service.linkAccess(sameUserIdentity as any, link.uuid, req, res)
expect(result.user.id).toEqual(baseLink.user.id)
expect(authManagerMock.setCookies).not.toHaveBeenCalled()
- expect(linksQueriesMock.incrementLinkNbAccess).not.toHaveBeenCalled()
+ expect(linksQueriesMock.consumeLinkAccess).not.toHaveBeenCalled()
+ })
+
+ it('downloads through an existing link session after the limit is reached without consuming another access', async () => {
+ const sameUserIdentity = { id: baseLink.user.id, login: 'john' }
+ const link = { ...baseLink, requireAuth: true, limitAccess: 1, nbAccess: 1 }
+ const spaceLink = {
+ space: null,
+ share: { isDir: false, name: 'file.txt', alias: 'share-alias' }
+ } as any
+ const streamable = { some: 'stream' } as any
+ linksQueriesMock.linkFromUUID.mockResolvedValueOnce(link)
+ linksQueriesMock.spaceLink.mockResolvedValueOnce(spaceLink)
+ spacesManagerMock.spaceEnv.mockResolvedValueOnce({} as any)
+ filesManagerMock.sendFileFromSpace.mockReturnValueOnce({
+ checks: vi.fn().mockResolvedValueOnce(undefined),
+ stream: vi.fn().mockResolvedValueOnce(streamable)
+ } as any)
+
+ const result = await service.linkDownload(sameUserIdentity as any, link.uuid, req, res)
+
+ expect(result).toBe(streamable)
+ expect(linksQueriesMock.consumeLinkAccess).not.toHaveBeenCalled()
})
it('throws INTERNAL_SERVER_ERROR when file checks fail during streaming', async () => {
@@ -290,7 +302,19 @@ describe(LinksManager.name, () => {
await expect(service.linkDownload(identity, link.uuid, req, res)).rejects.toMatchObject({
status: 500
})
- expect(linksQueriesMock.incrementLinkNbAccess).toHaveBeenCalledWith(link.uuid)
+ expect(linksQueriesMock.consumeLinkAccess).toHaveBeenCalledWith(link.uuid)
+ })
+
+ it('does not issue a session when no access can be consumed', async () => {
+ const link = { ...baseLink, limitAccess: 1 }
+ linksQueriesMock.linkFromUUID.mockResolvedValueOnce(link)
+ linksQueriesMock.consumeLinkAccess.mockResolvedValueOnce(false)
+
+ await expect(service.linkAccess(identity, link.uuid, req, res)).rejects.toMatchObject({
+ status: HttpStatus.BAD_REQUEST,
+ response: 'exceeded'
+ })
+ expect(authManagerMock.setCookies).not.toHaveBeenCalled()
})
})
@@ -315,6 +339,7 @@ describe(LinksManager.name, () => {
expect(result).toBe(loginDto)
expect(usersManagerMock.validatePasswordAttempts).toHaveBeenCalledWith(expect.objectContaining({ id: link.user.id }))
expect(usersManagerMock.compareUserPassword).toHaveBeenCalledWith(link.user.id, 'secret')
+ expect(linksQueriesMock.consumeLinkAccess).toHaveBeenCalledWith(link.uuid)
expect(usersManagerMock.updateAccesses).toHaveBeenCalledWith(expect.anything(), req.ip, true)
expect(authManagerMock.setCookies).toHaveBeenCalled()
// should log error when updateAccesses fails in successful authentication
diff --git a/backend/src/applications/links/services/links-manager.service.ts b/backend/src/applications/links/services/links-manager.service.ts
index 867e6072..894bdb17 100644
--- a/backend/src/applications/links/services/links-manager.service.ts
+++ b/backend/src/applications/links/services/links-manager.service.ts
@@ -63,9 +63,9 @@ export class LinksManager {
}
const user = new UserModel(link.user)
if (link.user.id !== identity.id) {
- // Authenticate user to allow access to the directory
+ // Authenticate the link user for subsequent access
+ await this.consumeLinkAccess(link)
this.logger.log({ tag: this.linkAccess.name, msg: `*${user.login}* (${user.id}) is logged` })
- this.incrementLinkNbAccess(link)
this.usersManager.updateAccesses(user, req.ip, true).catch((e: Error) => this.logger.error({ tag: this.linkAccess.name, msg: `${e}` }))
return this.authManager.setCookies(user, res)
}
@@ -85,9 +85,11 @@ export class LinksManager {
throw new HttpException('This link does not allow file download', HttpStatus.BAD_REQUEST)
}
const user = new UserModel(link.user)
- // Download the file (authentication has been verified before)
+ // A direct download without an existing link session consumes an access
+ if (link.user.id !== identity.id) {
+ await this.consumeLinkAccess(link)
+ }
this.logger.log({ tag: this.linkDownload.name, msg: `*${user.login}* (${user.id}) downloading ${spaceLink.share.name}` })
- this.incrementLinkNbAccess(link)
const spaceEnv: SpaceEnv = await this.spaceEnvFromLink(user, spaceLink)
const sendFile: SendFile = this.filesManager.sendFileFromSpace(spaceEnv, spaceLink.share.name)
try {
@@ -115,6 +117,7 @@ export class LinksManager {
this.logger.warn({ tag: this.linkAuthentication.name, msg: `*${user.login}* (${user.id}) : auth failed` })
throw new HttpException(LINK_ERROR.UNAUTHORIZED, HttpStatus.FORBIDDEN)
}
+ await this.consumeLinkAccess(link)
// authenticate user to allow access
this.logger.log({ tag: this.linkAuthentication.name, msg: `*${user.login}* (${user.id}) is logged` })
return this.authManager.setCookies(user, res)
@@ -141,7 +144,7 @@ export class LinksManager {
if (!link.user.isActive) {
return LINK_ERROR.DISABLED
}
- if (link.limitAccess !== 0 && link.nbAccess >= link.limitAccess) {
+ if (link.user.id !== identity.id && link.limitAccess !== 0 && link.nbAccess >= link.limitAccess) {
return LINK_ERROR.EXCEEDED
}
if (link.expiresAt && new Date() >= link.expiresAt) {
@@ -153,7 +156,9 @@ export class LinksManager {
return true
}
- private incrementLinkNbAccess(link: LinkAsUser) {
- this.linksQueries.incrementLinkNbAccess(link.uuid).catch((e: Error) => this.logger.error({ tag: this.incrementLinkNbAccess.name, msg: `${e}` }))
+ private async consumeLinkAccess(link: LinkAsUser): Promise<void> {
+ if (!(await this.linksQueries.consumeLinkAccess(link.uuid))) {
+ throw new HttpException(LINK_ERROR.EXCEEDED, HttpStatus.BAD_REQUEST)
+ }
}
}
diff --git a/backend/src/applications/links/services/links-queries.service.spec.ts b/backend/src/applications/links/services/links-queries.service.spec.ts
new file mode 100644
index 00000000..60b80ee7
--- /dev/null
+++ b/backend/src/applications/links/services/links-queries.service.spec.ts
@@ -0,0 +1,31 @@
+import { MySqlDialect } from 'drizzle-orm/mysql-core'
+import type { Cache } from '../../../infrastructure/cache/cache.service'
+import { LinksQueries } from './links-queries.service'
+
+describe(LinksQueries.name, () => {
+ let service: LinksQueries
+ let updateWhere: ReturnType<typeof vi.fn>
+ let updateLimit: ReturnType<typeof vi.fn>
+
+ beforeEach(() => {
+ updateLimit = vi.fn().mockResolvedValue([{ affectedRows: 1 }])
+ updateWhere = vi.fn().mockReturnValue({ limit: updateLimit })
+ const set = vi.fn().mockReturnValue({ where: updateWhere })
+ const update = vi.fn().mockReturnValue({ set })
+ service = new LinksQueries({ update } as any, {} as Cache)
+ })
+
+ it('atomically consumes an access only while the current counter is below the limit', async () => {
+ await expect(service.consumeLinkAccess('uuid-123')).resolves.toBe(true)
+ expect(updateLimit).toHaveBeenCalledWith(1)
+
+ const condition = new MySqlDialect().sqlToQuery(updateWhere.mock.calls[0][0])
+ expect(condition.sql).toContain('`links`.`uuid` = ?')
+ expect(condition.sql).toContain('`links`.`limitAccess` = ?')
+ expect(condition.sql).toContain('`links`.`nbAccess` < `links`.`limitAccess`')
+ expect(condition.params).toEqual(['uuid-123', 0])
+
+ updateLimit.mockResolvedValueOnce([{ affectedRows: 0 }])
+ await expect(service.consumeLinkAccess('uuid-123')).resolves.toBe(false)
+ })
+})
diff --git a/backend/src/applications/links/services/links-queries.service.ts b/backend/src/applications/links/services/links-queries.service.ts
index 0aa2d1a1..f917f27a 100644
--- a/backend/src/applications/links/services/links-queries.service.ts
+++ b/backend/src/applications/links/services/links-queries.service.ts
@@ -1,10 +1,10 @@
import { Inject, Injectable } from '@nestjs/common'
-import { and, eq, getTableColumns, isNotNull, isNull, or, sql } from 'drizzle-orm'
+import { and, eq, getTableColumns, isNotNull, isNull, lt, or, sql } from 'drizzle-orm'
import { alias } from 'drizzle-orm/mysql-core'
import { Cache } from '../../../infrastructure/cache/cache.service'
import { DB_TOKEN_PROVIDER } from '../../../infrastructure/database/constants'
import type { DBSchema } from '../../../infrastructure/database/interfaces/database.interface'
-import { dbGetInsertedId } from '../../../infrastructure/database/utils'
+import { dbCheckAffectedRows, dbGetInsertedId } from '../../../infrastructure/database/utils'
import { files } from '../../files/schemas/files.schema'
import type { ShareMembers } from '../../shares/schemas/share-members.interface'
import type { Share } from '../../shares/schemas/share.interface'
@@ -182,12 +182,16 @@ export class LinksQueries {
}
}
- async incrementLinkNbAccess(uuid: string) {
- await this.db
- .update(links)
- .set({ nbAccess: sql`${links.nbAccess} + 1` } as Record<keyof Link, any>)
- .where(eq(links.uuid, uuid))
- .limit(1)
+ async consumeLinkAccess(uuid: string): Promise<boolean> {
+ return dbCheckAffectedRows(
+ await this.db
+ .update(links)
+ .set({ nbAccess: sql`${links.nbAccess} + 1` } as Record<keyof Link, any>)
+ .where(and(eq(links.uuid, uuid), or(eq(links.limitAccess, 0), lt(links.nbAccess, links.limitAccess))))
+ .limit(1),
+ 1,
+ false
+ )
}
async isUniqueUUID(userId: number, uuid: string) {