Sync-in · Sovereign platform for file storage, sharing, synchronization, and collaboration.
TypeScript cloud-alternativecollaborationcollaborative-editingdropboxfile-serverfile-sharingfile-storagefile-syncfull-text-searchhomelabnextcloudon-premiseopen-sourceprivacy-firstprivate-cloudrealtimesecureself-hostedstorage-serverwebdav
fix(backend:auth): enforce 2FA and isolate JWT token types
johaven3ec74e2ea1f5
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.tsindex a42a4270..37958171 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@@ -4,6 +4,7 @@ import { Test, TestingModule } from '@nestjs/testing'import { FastifyReply } from 'fastify'import fs from 'node:fs/promises'import { Readable } from 'node:stream'+import { TOKEN_TYPE } from '../../../../authentication/interfaces/token.interface'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'@@ -25,6 +26,7 @@ vi.mock('../../../users/utils/avatar')describe(CollaboraOnlineManager.name, () => {let service: CollaboraOnlineManagerlet filesLockManager: FilesLockManager+ let jwtService: JwtServiceconst mockUser: UserModel = {id: 1,@@ -82,6 +84,7 @@ describe(CollaboraOnlineManager.name, () => {module.useLogger(['fatal'])service = module.get<CollaboraOnlineManager>(CollaboraOnlineManager)filesLockManager = module.get<FilesLockManager>(FilesLockManager)+ jwtService = module.get<JwtService>(JwtService)})afterEach(() => {@@ -123,6 +126,12 @@ describe(CollaboraOnlineManager.name, () => {lockScope: LOCK_SCOPE.SHARED}))+ expect(jwtService.signAsync).toHaveBeenCalledWith(+ expect.objectContaining({+ tokenType: TOKEN_TYPE.COLLABORA_ONLINE+ }),+ expect.any(Object)+ )})it('should return settings with view mode when lock conflict exists', async () => {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.tsindex 49009b00..45368f4e 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@@ -4,6 +4,7 @@ import { FastifyReply } from 'fastify'import fs from 'node:fs/promises'import os from 'node:os'import path from 'node:path'+import { TOKEN_TYPE } from '../../../../authentication/interfaces/token.interface'import { convertHumanTimeToSeconds } from '../../../../common/functions'import { configuration } from '../../../../configuration/config.environment'import { ContextManager } from '../../../../infrastructure/context/services/context-manager.service'@@ -39,7 +40,7 @@ import {COLLABORA_WOPI_SRC_QUERY_PARAM_NAME} from './collabora-online.constants'import { CollaboraOnlineReqDto, CollaboraSaveDocumentDto } from './collabora-online.dtos'-import { CollaboraOnlineCheckFileInfo, FastifyCollaboraOnlineSpaceRequest, JwtCollaboraOnlinePayload } from './collabora-online.interface'+import type { CollaboraOnlineCheckFileInfo, FastifyCollaboraOnlineSpaceRequest, JwtPayloadCollaboraOnline } from './collabora-online.interface'import { API_COLLABORA_ONLINE_FILES } from './collabora-online.routes'import { FileEvent } from '../../events/file-events'import { ACTION } from '../../../../common/constants'@@ -228,6 +229,7 @@ export class CollaboraOnlineManager {// use refresh expiration to allow long sessionsreturn this.jwt.signAsync({+ tokenType: TOKEN_TYPE.COLLABORA_ONLINE,identity: {id: user.id,login: user.login,@@ -238,8 +240,8 @@ export class CollaboraOnlineManager {applications: user.applications,spaceUrl: space.url,dbFileHash: dbFileHash- } satisfies JwtCollaboraOnlinePayload- },+ }+ } satisfies Omit<JwtPayloadCollaboraOnline, 'exp'>,{secret: configuration.auth.token.access.secret,expiresIn: this.expirationdiff --git a/backend/src/applications/files/editors/collabora-online/collabora-online.controller.spec.ts b/backend/src/applications/files/editors/collabora-online/collabora-online.controller.spec.tsindex 756a31ab..ae5c2cb2 100644--- a/backend/src/applications/files/editors/collabora-online/collabora-online.controller.spec.ts+++ b/backend/src/applications/files/editors/collabora-online/collabora-online.controller.spec.ts@@ -1,10 +1,14 @@import { Test, TestingModule } from '@nestjs/testing'+import { GUARDS_METADATA } from '@nestjs/common/constants'import { ContextInterceptor } from '../../../../infrastructure/context/interceptors/context.interceptor'import { ContextManager } from '../../../../infrastructure/context/services/context-manager.service'+import { SpaceGuard } from '../../../spaces/guards/space.guard'import { SpacesManager } from '../../../spaces/services/spaces-manager.service'import { FilesMethods } from '../../services/files-methods.service'+import { COLLABORA_CONTEXT } from './collabora-online.constants'import { CollaboraOnlineManager } from './collabora-online-manager.service'import { CollaboraOnlineController } from './collabora-online.controller'+import { CollaboraOnlineGuard } from './collabora-online.guard'describe(CollaboraOnlineController.name, () => {let controller: CollaboraOnlineController@@ -27,4 +31,19 @@ describe(CollaboraOnlineController.name, () => {it('should be defined', () => {expect(controller).toBeDefined()})++ it('should use access authentication for settings and editor authentication for WOPI routes', () => {+ expect(Reflect.getMetadata(COLLABORA_CONTEXT, controller.collaboraOnlineSettings)).toBeUndefined()+ expect(Reflect.getMetadata(GUARDS_METADATA, controller.collaboraOnlineSettings)).toEqual([SpaceGuard])++ for (const handler of [+ controller.collaboraOnlineGetDocumentContent,+ controller.collaboraOnlineGetDocumentInfo,+ controller.collaboraOnlineSaveDocument,+ controller.collaboraOnlineManageLockOnDocument+ ]) {+ expect(Reflect.getMetadata(COLLABORA_CONTEXT, handler)).toBe(true)+ expect(Reflect.getMetadata(GUARDS_METADATA, handler)).toEqual([CollaboraOnlineGuard, SpaceGuard])+ }+ })})diff --git a/backend/src/applications/files/editors/collabora-online/collabora-online.controller.ts b/backend/src/applications/files/editors/collabora-online/collabora-online.controller.tsindex df51f08d..c50f0d6f 100644--- a/backend/src/applications/files/editors/collabora-online/collabora-online.controller.ts+++ b/backend/src/applications/files/editors/collabora-online/collabora-online.controller.ts@@ -1,8 +1,9 @@-import { Controller, Get, HttpCode, HttpStatus, Post, Request, Res, StreamableFile, UseInterceptors } from '@nestjs/common'+import { Controller, Get, HttpCode, HttpStatus, Post, Request, Res, StreamableFile, UseGuards, UseInterceptors } from '@nestjs/common'import { FastifyReply } from 'fastify'import { ContextInterceptor } from '../../../../infrastructure/context/interceptors/context.interceptor'import { SPACE_OPERATION } from '../../../spaces/constants/spaces'import { OverrideSpacePermission } from '../../../spaces/decorators/space-override-permission.decorator'+import { SpaceGuard } from '../../../spaces/guards/space.guard'import { FastifySpaceRequest } from '../../../spaces/interfaces/space-request.interface'import { FilesMethods } from '../../services/files-methods.service'import { CollaboraOnlineEnvironment } from './collabora-online-environment.decorator'@@ -12,7 +13,6 @@ import type { CollaboraOnlineCheckFileInfo } from './collabora-online.interface'import { COLLABORA_ONLINE_ROUTE } from './collabora-online.routes'@Controller(COLLABORA_ONLINE_ROUTE.BASE)-@CollaboraOnlineEnvironment()export class CollaboraOnlineController {constructor(private readonly filesMethods: FilesMethods,@@ -20,12 +20,14 @@ export class CollaboraOnlineController {) {}@Get(`${COLLABORA_ONLINE_ROUTE.SETTINGS}/*`)+ @UseGuards(SpaceGuard)@UseInterceptors(ContextInterceptor)collaboraOnlineSettings(@Request() req: FastifySpaceRequest): Promise<CollaboraOnlineReqDto> {return this.filesCollaboraOnlineService.getSettings(req.user, req.space)}@Get(`${COLLABORA_ONLINE_ROUTE.FILES}/:dbFileHash/${COLLABORA_ONLINE_ROUTE.CONTENTS}`)+ @CollaboraOnlineEnvironment()collaboraOnlineGetDocumentContent(@Request() req: FastifySpaceRequest,@Res({ passthrough: true }) res: FastifyReply@@ -34,11 +36,13 @@ export class CollaboraOnlineController {}@Get(`${COLLABORA_ONLINE_ROUTE.FILES}/:dbFileHash`)+ @CollaboraOnlineEnvironment()collaboraOnlineGetDocumentInfo(@Request() req: FastifySpaceRequest): Promise<StreamableFile | CollaboraOnlineCheckFileInfo> {return this.filesCollaboraOnlineService.checkFileInfo(req)}@Post(`${COLLABORA_ONLINE_ROUTE.FILES}/:dbFileHash/${COLLABORA_ONLINE_ROUTE.CONTENTS}`)+ @CollaboraOnlineEnvironment()@OverrideSpacePermission(SPACE_OPERATION.MODIFY)@HttpCode(HttpStatus.OK)collaboraOnlineSaveDocument(@Request() req: FastifySpaceRequest): Promise<CollaboraSaveDocumentDto> {@@ -46,6 +50,7 @@ export class CollaboraOnlineController {}@Post(`${COLLABORA_ONLINE_ROUTE.FILES}/:dbFileHash`)+ @CollaboraOnlineEnvironment()@OverrideSpacePermission(SPACE_OPERATION.MODIFY)@HttpCode(HttpStatus.OK)collaboraOnlineManageLockOnDocument(@Request() req: FastifySpaceRequest, @Res({ passthrough: true }) res: FastifyReply): Promise<void> {diff --git a/backend/src/applications/files/editors/collabora-online/collabora-online.guard.spec.ts b/backend/src/applications/files/editors/collabora-online/collabora-online.guard.spec.tsindex c626eeac..ff17d625 100644--- a/backend/src/applications/files/editors/collabora-online/collabora-online.guard.spec.ts+++ b/backend/src/applications/files/editors/collabora-online/collabora-online.guard.spec.ts@@ -3,7 +3,7 @@ import { ExecutionContext } from '@nestjs/common'import { JwtModule, JwtService } from '@nestjs/jwt'import { Test, TestingModule } from '@nestjs/testing'import { PinoLogger } from 'nestjs-pino'-import { JwtPayload } from '../../../../authentication/interfaces/jwt-payload.interface'+import { TOKEN_TYPE } from '../../../../authentication/interfaces/token.interface'import { configuration } from '../../../../configuration/config.environment'import { COLLABORA_TOKEN_QUERY_PARAM_NAME } from './collabora-online.constants'import { CollaboraOnlineGuard } from './collabora-online.guard'@@ -14,7 +14,8 @@ describe(CollaboraOnlineGuard.name, () => {let jwtService: JwtServicelet filesCollaboraGuard: CollaboraOnlineGuardlet context: DeepMocked<ExecutionContext>- let accessToken: string+ let collaboraToken: string+ let temporaryTwoFaToken: stringbeforeAll(async () => {const module: TestingModule = await Test.createTestingModule({@@ -34,16 +35,27 @@ describe(CollaboraOnlineGuard.name, () => {jwtService = module.get<JwtService>(JwtService)filesCollaboraGuard = module.get<CollaboraOnlineGuard>(CollaboraOnlineGuard)context = createMock<ExecutionContext>()- accessToken = await jwtService.signAsync({ identity: { id: 1, login: 'foo' } } as JwtPayload, {- secret: configuration.auth.token.access.secret,- expiresIn: 30- })+ collaboraToken = await jwtService.signAsync(+ { tokenType: TOKEN_TYPE.COLLABORA_ONLINE, identity: { id: 1, login: 'foo' } },+ {+ secret: configuration.auth.token.access.secret,+ expiresIn: 30+ }+ )+ temporaryTwoFaToken = await jwtService.signAsync(+ { tokenType: TOKEN_TYPE.ACCESS_2FA, identity: { id: 1, login: 'foo', twoFaEnabled: true } },+ {+ secret: configuration.auth.token.access.secret,+ expiresIn: 30+ }+ )})it('should be defined', () => {expect(jwtService).toBeDefined()expect(filesCollaboraGuard).toBeDefined()- expect(accessToken).toBeDefined()+ expect(collaboraToken).toBeDefined()+ expect(temporaryTwoFaToken).toBeDefined()})it('should not pass without a valid token', async () => {@@ -54,9 +66,12 @@ describe(CollaboraOnlineGuard.name, () => {await expect(filesCollaboraGuard.canActivate(context)).rejects.toThrow('Unauthorized')})- it('should pass with a (un)valid token', async () => {+ it('should pass with a valid Collabora token and reject an invalid token', async () => {context.switchToHttp().getRequest.mockReturnValue({- url: `${API_COLLABORA_ONLINE_FILES}?${COLLABORA_TOKEN_QUERY_PARAM_NAME}=${accessToken}`,+ url: `${API_COLLABORA_ONLINE_FILES}?${COLLABORA_TOKEN_QUERY_PARAM_NAME}=${collaboraToken}`,+ cookies: {+ [configuration.auth.token.access.name]: temporaryTwoFaToken+ },raw: { user: '' }})expect(await filesCollaboraGuard.canActivate(context)).toBe(true)@@ -66,4 +81,13 @@ describe(CollaboraOnlineGuard.name, () => {})await expect(filesCollaboraGuard.canActivate(context)).rejects.toThrow('Unauthorized')})++ it('should reject a temporary 2FA token', async () => {+ context.switchToHttp().getRequest.mockReturnValue({+ url: `${API_COLLABORA_ONLINE_FILES}?${COLLABORA_TOKEN_QUERY_PARAM_NAME}=${temporaryTwoFaToken}`,+ raw: { user: '' }+ })++ await expect(filesCollaboraGuard.canActivate(context)).rejects.toThrow('Unauthorized')+ })})diff --git a/backend/src/applications/files/editors/collabora-online/collabora-online.interface.ts b/backend/src/applications/files/editors/collabora-online/collabora-online.interface.tsindex 89304623..918b6bc8 100644--- a/backend/src/applications/files/editors/collabora-online/collabora-online.interface.ts+++ b/backend/src/applications/files/editors/collabora-online/collabora-online.interface.ts@@ -1,11 +1,17 @@-import type { JwtIdentityPayload } from '../../../../authentication/interfaces/jwt-payload.interface'+import type { JwtIdentityPayload, JwtPayloadBase } from '../../../../authentication/interfaces/jwt-payload.interface'+import { TOKEN_TYPE } from '../../../../authentication/interfaces/token.interface'import type { FastifySpaceRequest } from '../../../spaces/interfaces/space-request.interface'-export interface JwtCollaboraOnlinePayload extends JwtIdentityPayload {+export interface JwtIdentityCollaboraOnlinePayload extends JwtIdentityPayload {spaceUrl: stringdbFileHash: string}+export interface JwtPayloadCollaboraOnline extends JwtPayloadBase {+ identity: JwtIdentityCollaboraOnlinePayload+ tokenType: TOKEN_TYPE.COLLABORA_ONLINE+}+export interface FastifyCollaboraOnlineSpaceRequest extends FastifySpaceRequest {user: FastifySpaceRequest['user'] & { spaceUrl?: string; dbFileHash?: string }params: FastifySpaceRequest['params'] & { dbFileHash?: string }diff --git a/backend/src/applications/files/editors/collabora-online/collabora-online.strategy.ts b/backend/src/applications/files/editors/collabora-online/collabora-online.strategy.tsindex c6b47b54..e7dd32dd 100644--- a/backend/src/applications/files/editors/collabora-online/collabora-online.strategy.ts+++ b/backend/src/applications/files/editors/collabora-online/collabora-online.strategy.ts@@ -1,28 +1,28 @@-import { Injectable } from '@nestjs/common'+import { Injectable, UnauthorizedException } from '@nestjs/common'import { AbstractStrategy, PassportStrategy } from '@nestjs/passport'import { PinoLogger } from 'nestjs-pino'import { ExtractJwt, Strategy } from 'passport-jwt'-import { AuthTokenAccessStrategy } from '../../../../authentication/guards/auth-token-access.strategy'-import { JwtPayload } from '../../../../authentication/interfaces/jwt-payload.interface'+import { TOKEN_TYPE } from '../../../../authentication/interfaces/token.interface'import { configuration } from '../../../../configuration/config.environment'import { UserModel } from '../../../users/models/user.model'import { COLLABORA_TOKEN_QUERY_PARAM_NAME } from './collabora-online.constants'+import type { JwtPayloadCollaboraOnline } from './collabora-online.interface'@Injectable()export class CollaboraOnlineStrategy extends PassportStrategy(Strategy, 'filesCollaboraOnlineToken') implements AbstractStrategy {constructor(private readonly logger: PinoLogger) {super({- jwtFromRequest: ExtractJwt.fromExtractors([- AuthTokenAccessStrategy.extractJWTFromCookie,- ExtractJwt.fromUrlQueryParameter(COLLABORA_TOKEN_QUERY_PARAM_NAME)- ]),+ jwtFromRequest: ExtractJwt.fromUrlQueryParameter(COLLABORA_TOKEN_QUERY_PARAM_NAME),secretOrKey: configuration.auth.token.access.secret,ignoreExpiration: false,passReqToCallback: false})}- validate(jwtPayload: JwtPayload): UserModel {+ validate(jwtPayload: JwtPayloadCollaboraOnline): UserModel {+ if (jwtPayload.tokenType !== TOKEN_TYPE.COLLABORA_ONLINE) {+ throw new UnauthorizedException()+ }this.logger.assign({ user: jwtPayload.identity.login })return new UserModel(jwtPayload.identity)}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.tsindex 64e3cc7a..9209a7da 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@@ -4,6 +4,8 @@ import { JwtService } from '@nestjs/jwt'import { Test, TestingModule } from '@nestjs/testing'import { AxiosResponse } from 'axios'import { Readable } from 'stream'+import { Mocked } from 'vitest'+import { TOKEN_TYPE } from '../../../../authentication/interfaces/token.interface'import { Cache } from '../../../../infrastructure/cache/cache.service'import { ContextManager } from '../../../../infrastructure/context/services/context-manager.service'import type { SpaceEnv } from '../../../spaces/models/space-env.model'@@ -15,7 +17,6 @@ import { FilesLockManager } from '../../services/files-lock-manager.service'import * as filesUtils from '../../utils/files'import { OnlyOfficeManager } from './only-office-manager.service'import { ONLY_OFFICE_APP_LOCK } from './only-office.constants'-import { Mocked } from 'vitest'vi.mock('../../utils/files')vi.mock('../../../users/utils/avatar', () => ({@@ -135,6 +136,12 @@ describe(OnlyOfficeManager.name, () => {expect(result.config.editorConfig.mode).toBe(FILE_MODE.EDIT)expect(result.config.document.permissions.edit).toBe(true)expect(result.hasLock).toBe(false)+ expect(jwtService.signAsync).toHaveBeenCalledWith(+ expect.objectContaining({+ tokenType: TOKEN_TYPE.ONLY_OFFICE+ }),+ expect.any(Object)+ )})it('should throw error if document does not exist', async () => {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.tsindex 749cc8fc..4ff86e82 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@@ -7,6 +7,7 @@ import crypto from 'node:crypto'import os from 'node:os'import path from 'node:path'import { JwtIdentityPayload } from '../../../../authentication/interfaces/jwt-payload.interface'+import { TOKEN_TYPE } from '../../../../authentication/interfaces/token.interface'import { convertHumanTimeToSeconds } from '../../../../common/functions'import { encodeUrl } from '../../../../common/shared'import { configuration } from '../../../../configuration/config.environment'@@ -236,6 +237,7 @@ export class OnlyOfficeManager {// use refresh expiration to allow long sessionsreturn this.jwt.signAsync({+ tokenType: TOKEN_TYPE.ONLY_OFFICE,identity: {id: user.id,login: user.login,diff --git a/backend/src/applications/files/editors/only-office/only-office.controller.spec.ts b/backend/src/applications/files/editors/only-office/only-office.controller.spec.tsindex 35cc9223..e74c52bc 100644--- a/backend/src/applications/files/editors/only-office/only-office.controller.spec.ts+++ b/backend/src/applications/files/editors/only-office/only-office.controller.spec.ts@@ -1,11 +1,15 @@import { Test, TestingModule } from '@nestjs/testing'+import { GUARDS_METADATA } from '@nestjs/common/constants'import { ContextInterceptor } from '../../../../infrastructure/context/interceptors/context.interceptor'import { ContextManager } from '../../../../infrastructure/context/services/context-manager.service'+import { SpaceGuard } from '../../../spaces/guards/space.guard'import { SpacesManager } from '../../../spaces/services/spaces-manager.service'import { FILE_MODE } from '../../constants/operations'import { FilesMethods } from '../../services/files-methods.service'+import { ONLY_OFFICE_CONTEXT } from './only-office.constants'import { OnlyOfficeManager } from './only-office-manager.service'import { OnlyOfficeController } from './only-office.controller'+import { OnlyOfficeGuard } from './only-office.guard'describe(OnlyOfficeController.name, () => {let controller: OnlyOfficeController@@ -39,6 +43,16 @@ describe(OnlyOfficeController.name, () => {expect(controller).toBeDefined()})+ it('should use access authentication for settings and editor authentication for document routes', () => {+ expect(Reflect.getMetadata(ONLY_OFFICE_CONTEXT, controller.onlyOfficeSettings)).toBeUndefined()+ expect(Reflect.getMetadata(GUARDS_METADATA, controller.onlyOfficeSettings)).toEqual([SpaceGuard])++ for (const handler of [controller.onlyOfficeDocument, controller.onlyOfficeCallBack]) {+ expect(Reflect.getMetadata(ONLY_OFFICE_CONTEXT, handler)).toBe(true)+ expect(Reflect.getMetadata(GUARDS_METADATA, handler)).toEqual([OnlyOfficeGuard, SpaceGuard])+ }+ })+describe('onlyOfficeSettings', () => {it('should call manager with default mode "view" when mode is undefined', async () => {const user: any = { id: 1 }diff --git a/backend/src/applications/files/editors/only-office/only-office.controller.ts b/backend/src/applications/files/editors/only-office/only-office.controller.tsindex 815d0757..3227e8da 100644--- a/backend/src/applications/files/editors/only-office/only-office.controller.ts+++ b/backend/src/applications/files/editors/only-office/only-office.controller.ts@@ -1,9 +1,10 @@-import { Body, Controller, Get, HttpCode, HttpStatus, Post, Request, Res, StreamableFile, UseInterceptors } from '@nestjs/common'+import { Body, Controller, Get, HttpCode, HttpStatus, Post, Request, Res, StreamableFile, UseGuards, UseInterceptors } from '@nestjs/common'import { FastifyReply } from 'fastify'import { ContextInterceptor } from '../../../../infrastructure/context/interceptors/context.interceptor'import { SPACE_OPERATION } from '../../../spaces/constants/spaces'import { OverrideSpacePermission } from '../../../spaces/decorators/space-override-permission.decorator'import { GetSpace } from '../../../spaces/decorators/space.decorator'+import { SpaceGuard } from '../../../spaces/guards/space.guard'import { FastifySpaceRequest } from '../../../spaces/interfaces/space-request.interface'import { SpaceEnv } from '../../../spaces/models/space-env.model'import { GetUser } from '../../../users/decorators/user.decorator'@@ -15,7 +16,6 @@ import type { OnlyOfficeReqDto } from './only-office.dtos'import { API_ONLY_OFFICE, ONLY_OFFICE_ROUTE } from './only-office.routes'@Controller(API_ONLY_OFFICE)-@OnlyOfficeEnvironment()export class OnlyOfficeController {constructor(private readonly filesMethods: FilesMethods,@@ -23,17 +23,20 @@ export class OnlyOfficeController {) {}@Get(`${ONLY_OFFICE_ROUTE.SETTINGS}/*`)+ @UseGuards(SpaceGuard)@UseInterceptors(ContextInterceptor)onlyOfficeSettings(@Request() req: FastifySpaceRequest): Promise<OnlyOfficeReqDto> {return this.filesOnlyOfficeManager.getSettings(req.user, req.space, req)}@Get(`${ONLY_OFFICE_ROUTE.DOCUMENT}/*`)+ @OnlyOfficeEnvironment()onlyOfficeDocument(@Request() req: FastifySpaceRequest, @Res({ passthrough: true }) res: FastifyReply): Promise<StreamableFile> {return this.filesMethods.headOrGet(req, res)}@Post(`${ONLY_OFFICE_ROUTE.CALLBACK}/*`)+ @OnlyOfficeEnvironment()@OverrideSpacePermission(SPACE_OPERATION.MODIFY)@HttpCode(HttpStatus.OK)onlyOfficeCallBack(@GetUser() user: UserModel, @GetSpace() space: SpaceEnv, @Body('token') token: string) {diff --git a/backend/src/applications/files/editors/only-office/only-office.guard.spec.ts b/backend/src/applications/files/editors/only-office/only-office.guard.spec.tsindex e037c86b..3afa2717 100644--- a/backend/src/applications/files/editors/only-office/only-office.guard.spec.ts+++ b/backend/src/applications/files/editors/only-office/only-office.guard.spec.ts@@ -4,6 +4,7 @@ import { JwtModule, JwtService } from '@nestjs/jwt'import { Test, TestingModule } from '@nestjs/testing'import { PinoLogger } from 'nestjs-pino'import { JwtPayload } from '../../../../authentication/interfaces/jwt-payload.interface'+import { TOKEN_TYPE } from '../../../../authentication/interfaces/token.interface'import { configuration } from '../../../../configuration/config.environment'import { ONLY_OFFICE_TOKEN_QUERY_PARAM_NAME } from './only-office.constants'import { OnlyOfficeGuard } from './only-office.guard'@@ -14,7 +15,8 @@ describe(OnlyOfficeGuard.name, () => {let jwtService: JwtServicelet filesOnlyOfficeGuard: OnlyOfficeGuardlet context: DeepMocked<ExecutionContext>- let accessToken: string+ let onlyOfficeToken: string+ let temporaryTwoFaToken: stringbeforeAll(async () => {const module: TestingModule = await Test.createTestingModule({@@ -34,16 +36,24 @@ describe(OnlyOfficeGuard.name, () => {jwtService = module.get<JwtService>(JwtService)filesOnlyOfficeGuard = module.get<OnlyOfficeGuard>(OnlyOfficeGuard)context = createMock<ExecutionContext>()- accessToken = await jwtService.signAsync({ identity: { id: 1, login: 'foo' } } as JwtPayload, {+ onlyOfficeToken = await jwtService.signAsync({ tokenType: TOKEN_TYPE.ONLY_OFFICE, identity: { id: 1, login: 'foo' } } as JwtPayload, {secret: configuration.auth.token.access.secret,expiresIn: 30})+ temporaryTwoFaToken = await jwtService.signAsync(+ { tokenType: TOKEN_TYPE.ACCESS_2FA, identity: { id: 1, login: 'foo', twoFaEnabled: true } } as JwtPayload,+ {+ secret: configuration.auth.token.access.secret,+ expiresIn: 30+ }+ )})it('should be defined', () => {expect(jwtService).toBeDefined()expect(filesOnlyOfficeGuard).toBeDefined()- expect(accessToken).toBeDefined()+ expect(onlyOfficeToken).toBeDefined()+ expect(temporaryTwoFaToken).toBeDefined()})it('should not pass without a valid token', async () => {@@ -54,9 +64,12 @@ describe(OnlyOfficeGuard.name, () => {await expect(filesOnlyOfficeGuard.canActivate(context)).rejects.toThrow('Unauthorized')})- it('should pass with a (un)valid token', async () => {+ it('should pass with a valid OnlyOffice token and reject an invalid token', async () => {context.switchToHttp().getRequest.mockReturnValue({- url: `${API_ONLY_OFFICE_CALLBACK}?${ONLY_OFFICE_TOKEN_QUERY_PARAM_NAME}=${accessToken}`,+ url: `${API_ONLY_OFFICE_CALLBACK}?${ONLY_OFFICE_TOKEN_QUERY_PARAM_NAME}=${onlyOfficeToken}`,+ cookies: {+ [configuration.auth.token.access.name]: temporaryTwoFaToken+ },raw: { user: '' }})expect(await filesOnlyOfficeGuard.canActivate(context)).toBe(true)@@ -66,4 +79,13 @@ describe(OnlyOfficeGuard.name, () => {})await expect(filesOnlyOfficeGuard.canActivate(context)).rejects.toThrow('Unauthorized')})++ it('should reject a temporary 2FA token', async () => {+ context.switchToHttp().getRequest.mockReturnValue({+ url: `${API_ONLY_OFFICE_CALLBACK}?${ONLY_OFFICE_TOKEN_QUERY_PARAM_NAME}=${temporaryTwoFaToken}`,+ raw: { user: '' }+ })++ await expect(filesOnlyOfficeGuard.canActivate(context)).rejects.toThrow('Unauthorized')+ })})diff --git a/backend/src/applications/files/editors/only-office/only-office.strategy.ts b/backend/src/applications/files/editors/only-office/only-office.strategy.tsindex b85fb83c..a923f798 100644--- a/backend/src/applications/files/editors/only-office/only-office.strategy.ts+++ b/backend/src/applications/files/editors/only-office/only-office.strategy.ts@@ -1,9 +1,9 @@-import { Injectable } from '@nestjs/common'+import { Injectable, UnauthorizedException } from '@nestjs/common'import { AbstractStrategy, PassportStrategy } from '@nestjs/passport'import { PinoLogger } from 'nestjs-pino'import { ExtractJwt, Strategy } from 'passport-jwt'-import { AuthTokenAccessStrategy } from '../../../../authentication/guards/auth-token-access.strategy'import { JwtPayload } from '../../../../authentication/interfaces/jwt-payload.interface'+import { TOKEN_TYPE } from '../../../../authentication/interfaces/token.interface'import { configuration } from '../../../../configuration/config.environment'import { UserModel } from '../../../users/models/user.model'import { ONLY_OFFICE_TOKEN_QUERY_PARAM_NAME } from './only-office.constants'@@ -12,10 +12,7 @@ import { ONLY_OFFICE_TOKEN_QUERY_PARAM_NAME } from './only-office.constants'export class OnlyOfficeStrategy extends PassportStrategy(Strategy, 'filesOnlyOfficeToken') implements AbstractStrategy {constructor(private readonly logger: PinoLogger) {super({- jwtFromRequest: ExtractJwt.fromExtractors([- AuthTokenAccessStrategy.extractJWTFromCookie,- ExtractJwt.fromUrlQueryParameter(ONLY_OFFICE_TOKEN_QUERY_PARAM_NAME)- ]),+ jwtFromRequest: ExtractJwt.fromUrlQueryParameter(ONLY_OFFICE_TOKEN_QUERY_PARAM_NAME),secretOrKey: configuration.auth.token.access.secret,ignoreExpiration: false,passReqToCallback: false@@ -23,6 +20,9 @@ export class OnlyOfficeStrategy extends PassportStrategy(Strategy, 'filesOnlyOff}validate(jwtPayload: JwtPayload): UserModel {+ if (jwtPayload.tokenType !== TOKEN_TYPE.ONLY_OFFICE) {+ throw new UnauthorizedException()+ }this.logger.assign({ user: jwtPayload.identity.login })return new UserModel(jwtPayload.identity)}diff --git a/backend/src/applications/users/admin-users.controller.spec.ts b/backend/src/applications/users/admin-users.controller.spec.tsindex 37478cb3..51fd3132 100644--- a/backend/src/applications/users/admin-users.controller.spec.ts+++ b/backend/src/applications/users/admin-users.controller.spec.ts@@ -3,7 +3,7 @@ import { JwtService } from '@nestjs/jwt'import { Test, TestingModule } from '@nestjs/testing'import { AuthManager } from '../../authentication/auth.service'import { AuthProvider2FA } from '../../authentication/providers/two-fa/auth-provider-two-fa.service'-import { AuthTwoFaGuard } from '../../authentication/providers/two-fa/auth-two-fa-guard'+import { AuthTwoFaVerificationGuard } from '../../authentication/providers/two-fa/guards/auth-two-fa-verification.guard'import { exportConfiguration } from '../../configuration/config.environment'import { Cache } from '../../infrastructure/cache/cache.service'import { DB_TOKEN_PROVIDER } from '../../infrastructure/database/constants'@@ -29,7 +29,7 @@ describe(AdminUsersController.name, () => {useValue: {}},{ provide: AuthProvider2FA, useValue: {} },- { provide: AuthTwoFaGuard, useValue: {} },+ { provide: AuthTwoFaVerificationGuard, useValue: {} },{ provide: NotificationsManager, useValue: {} },{provide: FilesQuotaManager,diff --git a/backend/src/applications/users/admin-users.controller.ts b/backend/src/applications/users/admin-users.controller.tsindex fb23d901..a2bb8275 100644--- a/backend/src/applications/users/admin-users.controller.ts+++ b/backend/src/applications/users/admin-users.controller.ts@@ -1,7 +1,10 @@import { Body, Controller, Delete, Get, Param, ParseIntPipe, Patch, Post, Put, Res, Search, UseGuards } from '@nestjs/common'import { FastifyReply } from 'fastify'import { LoginResponseDto } from '../../authentication/dto/login-response.dto'-import { AuthTwoFaGuard, AuthTwoFaGuardWithoutPassword } from '../../authentication/providers/two-fa/auth-two-fa-guard'+import {+ AuthTwoFaVerificationGuard,+ AuthTwoFaVerificationWithoutPasswordGuard+} from '../../authentication/providers/two-fa/guards/auth-two-fa-verification.guard'import { GROUP_TYPE } from './constants/group'import { ADMIN_USERS_ROUTE } from './constants/routes'import { USER_ROLE } from './constants/user'@@ -37,7 +40,7 @@ export class AdminUsersController {}@Post(ADMIN_USERS_ROUTE.USERS)- @UseGuards(AuthTwoFaGuardWithoutPassword)+ @UseGuards(AuthTwoFaVerificationWithoutPasswordGuard)createUser(@Body() createUserDto: CreateUserDto): Promise<AdminUser> {return this.adminUsersManager.createUserOrGuest(createUserDto,@@ -47,13 +50,13 @@ export class AdminUsersController {}@Put(`${ADMIN_USERS_ROUTE.USERS}/:id`)- @UseGuards(AuthTwoFaGuardWithoutPassword)+ @UseGuards(AuthTwoFaVerificationWithoutPasswordGuard)updateUser(@Param('id', ParseIntPipe) userId: number, @Body() updateUserDto: UpdateUserDto): Promise<AdminUser> {return this.adminUsersManager.updateUserOrGuest(userId, updateUserDto)}@Delete(`${ADMIN_USERS_ROUTE.USERS}/:id`)- @UseGuards(AuthTwoFaGuard)+ @UseGuards(AuthTwoFaVerificationGuard)deleteUser(@Param('id', ParseIntPipe) userId: number, @Body() deleteUserDto: DeleteUserDto): Promise<void> {return this.adminUsersManager.deleteUserOrGuestFromAdmin(userId, { ...deleteUserDto, isGuest: false })}@@ -69,19 +72,19 @@ export class AdminUsersController {}@Post(ADMIN_USERS_ROUTE.GUESTS)- @UseGuards(AuthTwoFaGuardWithoutPassword)+ @UseGuards(AuthTwoFaVerificationWithoutPasswordGuard)createGuest(@GetUser() user: UserModel, @Body() createGuestDto: CreateUserDto): Promise<GuestUser> {return this.adminUsersManager.createGuest(user, createGuestDto)}@Put(`${ADMIN_USERS_ROUTE.GUESTS}/:id`)- @UseGuards(AuthTwoFaGuardWithoutPassword)+ @UseGuards(AuthTwoFaVerificationWithoutPasswordGuard)updateGuest(@Param('id', ParseIntPipe) guestId: number, @Body() updateGuestDto: UpdateUserDto): Promise<GuestUser> {return this.adminUsersManager.updateGuest(guestId, updateGuestDto)}@Delete(`${ADMIN_USERS_ROUTE.GUESTS}/:id`)- @UseGuards(AuthTwoFaGuard)+ @UseGuards(AuthTwoFaVerificationGuard)deleteGuest(@Param('id', ParseIntPipe) guestId: number, @Body() deleteUserDto: DeleteUserDto): Promise<void> {return this.adminUsersManager.deleteUserOrGuestFromAdmin(guestId, { ...deleteUserDto, isGuest: true })}@@ -141,7 +144,7 @@ export class AdminUsersController {}@Post(`${ADMIN_USERS_ROUTE.IMPERSONATE}/:id`)- @UseGuards(AuthTwoFaGuard)+ @UseGuards(AuthTwoFaVerificationGuard)impersonateUser(@GetUser() admin: UserModel,@Param('id', ParseIntPipe) userId: number,diff --git a/backend/src/applications/users/users.controller.ts b/backend/src/applications/users/users.controller.tsindex 9b245803..7705d8ce 100755--- a/backend/src/applications/users/users.controller.ts+++ b/backend/src/applications/users/users.controller.ts@@ -2,7 +2,7 @@ import { Body, Controller, Delete, Get, Header, Param, ParseIntPipe, Patch, Postimport { createReadStream } from 'fs'import { LoginResponseDto } from '../../authentication/dto/login-response.dto'import { FastifyAuthenticatedRequest } from '../../authentication/interfaces/auth-request.interface'-import { AuthTwoFaGuardWithoutPassword } from '../../authentication/providers/two-fa/auth-two-fa-guard'+import { AuthTwoFaVerificationWithoutPasswordGuard } from '../../authentication/providers/two-fa/guards/auth-two-fa-verification.guard'import { makeContentDispositionAttachment } from '../files/utils/send-file'import { USERS_ROUTE } from './constants/routes'import { USER_PERMISSION, USER_ROLE } from './constants/user'@@ -38,14 +38,14 @@ export class UsersController {@Get(`${USERS_ROUTE.ME}/${USERS_ROUTE.APP_PASSWORDS}`)@UserHaveRole(USER_ROLE.USER)- @UseGuards(AuthTwoFaGuardWithoutPassword)+ @UseGuards(AuthTwoFaVerificationWithoutPasswordGuard)listAppPasswords(@GetUser() user: UserModel): Promise<Omit<UserAppPassword, 'password'>[]> {return this.usersManager.listAppPasswords(user)}@Post(`${USERS_ROUTE.ME}/${USERS_ROUTE.APP_PASSWORDS}`)@UserHaveRole(USER_ROLE.USER)- @UseGuards(AuthTwoFaGuardWithoutPassword)+ @UseGuards(AuthTwoFaVerificationWithoutPasswordGuard)generateAppPassword(@GetUser() user: UserModel, @Body() userAppPasswordDto: UserAppPasswordDto): Promise<UserAppPassword> {return this.usersManager.generateAppPassword(user, userAppPasswordDto)}@@ -63,7 +63,7 @@ export class UsersController {}@Put(`${USERS_ROUTE.ME}/${USERS_ROUTE.PASSWORD}`)- @UseGuards(AuthTwoFaGuardWithoutPassword)+ @UseGuards(AuthTwoFaVerificationWithoutPasswordGuard)updatePassword(@GetUser() user: UserModel, @Body() userPasswordDto: UserUpdatePasswordDto) {return this.usersManager.updatePassword(user, userPasswordDto)}diff --git a/backend/src/authentication/auth.controller.spec.ts b/backend/src/authentication/auth.controller.spec.tsindex 44d32f91..3169621f 100755--- a/backend/src/authentication/auth.controller.spec.ts+++ b/backend/src/authentication/auth.controller.spec.ts@@ -1,8 +1,15 @@+import fastifyCookie, { sign } from '@fastify/cookie'+import { ExecutionContext, UnauthorizedException, ValidationPipe } from '@nestjs/common'import { ConfigModule, ConfigService } from '@nestjs/config'+import { APP_GUARD, Reflector } from '@nestjs/core'import { JwtService } from '@nestjs/jwt'import { PassportModule } from '@nestjs/passport'+import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify'import { Test, TestingModule } from '@nestjs/testing'+import { PinoLogger } from 'nestjs-pino'import { NotificationsManager } from '../applications/notifications/services/notifications-manager.service'+import { USER_ROLE } from '../applications/users/constants/user'+import { UserRolesGuard } from '../applications/users/guards/roles.guard'import { UserModel } from '../applications/users/models/user.model'import { UsersManager } from '../applications/users/services/users-manager.service'import { generateUserTest } from '../applications/users/utils/test'@@ -14,15 +21,24 @@ import { DB_TOKEN_PROVIDER } from '../infrastructure/database/constants'import { AuthConfig } from './auth.config'import { AuthController } from './auth.controller'import { AuthManager } from './auth.service'-import { TOKEN_PATHS } from './constants/auth'-import { LoginResponseDto } from './dto/login-response.dto'+import { ACCESS_KEY, CSRF_KEY, TOKEN_PATHS, TWO_FA_HEADER_CODE, TWO_FA_HEADER_PASSWORD } from './constants/auth'+import { API_AUTH_SETTINGS, API_AUTH_TOKEN, API_TWO_FA_ADMIN_RESET_USER, API_TWO_FA_ENABLE, API_TWO_FA_LOGIN_VERIFY } from './constants/routes'+import { AUTH_TOKEN_SKIP } from './decorators/auth-token-skip.decorator'+import { LoginResponseDto, LoginVerify2FaDto } from './dto/login-response.dto'+import { AuthLocalGuard } from './guards/auth-local.guard'+import { JwtPayload } from './interfaces/jwt-payload.interface'import { TOKEN_TYPE } from './interfaces/token.interface'import { AuthProvider2FA } from './providers/two-fa/auth-provider-two-fa.service'-import { AuthTwoFaGuard } from './providers/two-fa/auth-two-fa-guard'+import { AuthTokenTwoFaGuard } from './providers/two-fa/guards/auth-token-two-fa.guard'+import { AuthTokenTwoFaStrategy } from './providers/two-fa/guards/auth-token-two-fa.strategy'+import { AuthTwoFaVerificationGuard } from './providers/two-fa/guards/auth-two-fa-verification.guard'+import { TwoFaVerifyDto, TwoFaVerifyWithPasswordDto } from './providers/two-fa/auth-two-fa.dtos'describe(AuthController.name, () => {let module: TestingModulelet authController: AuthController+ let authManager: AuthManager+ let authProvider2FA: AuthProvider2FAlet authConfig: AuthConfiglet userTest: UserModel@@ -35,10 +51,10 @@ describe(AuthController.name, () => {AuthManager,JwtService,AuthProvider2FA,- AuthTwoFaGuard,+ AuthTwoFaVerificationGuard,{ provide: DB_TOKEN_PROVIDER, useValue: {} },{ provide: Cache, useValue: {} },- { provide: UsersManager, useValue: {} },+ { provide: UsersManager, useValue: { updateAccesses: vi.fn().mockResolvedValue(undefined) } },{ provide: NotificationsManager, useValue: {} }]}).compile()@@ -46,6 +62,8 @@ describe(AuthController.name, () => {module.useLogger(['fatal'])authConfig = module.get<ConfigService>(ConfigService).get<AuthConfig>('auth')authController = module.get<AuthController>(AuthController)+ authManager = module.get<AuthManager>(AuthManager)+ authProvider2FA = module.get<AuthProvider2FA>(AuthProvider2FA)userTest = new UserModel({ ...generateUserTest(), id: 888 }, false)})@@ -53,6 +71,11 @@ describe(AuthController.name, () => {await module.close()})+ beforeEach(() => {+ vi.restoreAllMocks()+ userTest.exp = undefined+ })+it('should be defined', () => {expect(authConfig).toBeDefined()expect(authController).toBeDefined()@@ -69,10 +92,40 @@ describe(AuthController.name, () => {expect(result.token.refresh_expiration).toBeCloseTo(convertHumanTimeToSeconds(authConfig.token.refresh.expiration) + currentTimeStamp(), -1)})+ it('should set temporary JWT cookies when login requires 2FA', async () => {+ const twoFaUser = new UserModel({ ...generateUserTest(), id: userTest.id, twoFaEnabled: true }, false)+ const res: any = { setCookie: vi.fn() }++ const result = await authController.login(twoFaUser, res)++ expect(result).toBeInstanceOf(LoginVerify2FaDto)+ expect(result.user).toEqual({ twoFaEnabled: true })+ expect(res.setCookie).toHaveBeenCalledTimes(2)+ expect(res.setCookie).toHaveBeenCalledWith(+ authConfig.token[TOKEN_TYPE.ACCESS_2FA].name,+ expect.any(String),+ expect.objectContaining({+ path: TOKEN_PATHS[TOKEN_TYPE.ACCESS_2FA],+ httpOnly: true+ })+ )+ expect(res.setCookie).toHaveBeenCalledWith(+ authConfig.token[TOKEN_TYPE.CSRF_2FA].name,+ expect.any(String),+ expect.objectContaining({+ path: TOKEN_PATHS[TOKEN_TYPE.CSRF_2FA],+ httpOnly: false+ })+ )+ })+it('should clear JWT in cookies', async () => {const res: any = { clearCookie: vi.fn() }await expect(authController.logout(res)).resolves.not.toThrow()expect(res.clearCookie).toHaveBeenCalledTimes(Object.keys(TOKEN_PATHS).length)+ for (const [type, path] of Object.entries(TOKEN_PATHS)) {+ expect(res.clearCookie).toHaveBeenCalledWith(authConfig.token[type].name, { path })+ }})it('should refresh JWT in cookies', async () => {@@ -105,6 +158,93 @@ describe(AuthController.name, () => {)})+ it('should return false when external authentication settings are disabled', () => {+ const authSettingsSpy = vi.spyOn(authManager, 'authSettings').mockReturnValue(false)++ expect(authController.authSettings()).toBe(false)+ expect(authSettingsSpy).toHaveBeenCalledOnce()+ })++ it('should return external authentication settings', () => {+ const settings = {+ loginUrl: '/api/auth/oidc/login',+ autoRedirect: true,+ buttonText: 'Continue with SSO'+ }+ vi.spyOn(authManager, 'authSettings').mockReturnValue(settings)++ expect(authController.authSettings()).toEqual(settings)+ })++ it('should initialize 2FA for the current user', async () => {+ const setup = { secret: 'secret', qrDataUrl: 'data:image/png;base64,test' }+ const initTwoFactorSpy = vi.spyOn(authProvider2FA, 'initTwoFactor').mockResolvedValue(setup)++ await expect(authController.twoFaInit(userTest)).resolves.toEqual(setup)+ expect(initTwoFactorSpy).toHaveBeenCalledWith(userTest)+ })++ it('should enable 2FA with the request and verification payload', async () => {+ const body: TwoFaVerifyWithPasswordDto = { code: '123456', password: 'password' }+ const req = { user: userTest, ip: '127.0.0.1' } as any+ const result = { success: true, message: '', recoveryCodes: ['code'] }+ const enableTwoFactorSpy = vi.spyOn(authProvider2FA, 'enableTwoFactor').mockResolvedValue(result)++ await expect(authController.twoFaEnable(body, req)).resolves.toEqual(result)+ expect(enableTwoFactorSpy).toHaveBeenCalledWith(body, req)+ })++ it('should disable 2FA with the request and verification payload', async () => {+ const body: TwoFaVerifyWithPasswordDto = { code: '123456', password: 'password' }+ const req = { user: userTest, ip: '127.0.0.1' } as any+ const result = { success: true, message: '' }+ const disableTwoFactorSpy = vi.spyOn(authProvider2FA, 'disableTwoFactor').mockResolvedValue(result)++ await expect(authController.twoFaDisable(body, req)).resolves.toEqual(result)+ expect(disableTwoFactorSpy).toHaveBeenCalledWith(body, req)+ })++ it('should create final cookies and clear the temporary cookie after successful 2FA login', async () => {+ const body: TwoFaVerifyDto = { code: '123456' }+ const twoFaUser = new UserModel({ ...generateUserTest(), id: userTest.id, twoFaEnabled: true }, false)+ const req = { user: twoFaUser, ip: '127.0.0.1' } as any+ const res: any = { setCookie: vi.fn(), clearCookie: vi.fn() }+ vi.spyOn(authProvider2FA, 'loadUser').mockResolvedValue(twoFaUser)+ vi.spyOn(authProvider2FA, 'validateTwoFactorCode').mockReturnValue({ success: true, message: '' })++ const result = await authController.twoFaLogin(body, req, res)++ expect(result).toEqual(expect.objectContaining({ success: true, user: twoFaUser }))+ expect(res.setCookie).toHaveBeenCalledTimes(4)+ expect(res.clearCookie).toHaveBeenCalledWith(ACCESS_KEY, {+ path: TOKEN_PATHS[TOKEN_TYPE.ACCESS_2FA],+ httpOnly: true+ })+ })++ it('should not create or clear cookies after failed 2FA login', async () => {+ const body: TwoFaVerifyDto = { code: '000000' }+ const twoFaUser = new UserModel({ ...generateUserTest(), id: userTest.id, twoFaEnabled: true }, false)+ const req = { user: twoFaUser, ip: '127.0.0.1' } as any+ const res: any = { setCookie: vi.fn(), clearCookie: vi.fn() }+ vi.spyOn(authProvider2FA, 'loadUser').mockResolvedValue(twoFaUser)+ vi.spyOn(authProvider2FA, 'validateTwoFactorCode').mockReturnValue({ success: false, message: 'Incorrect code or password' })++ const result = await authController.twoFaLogin(body, req, res)++ expect(result).toEqual({ success: false, message: 'Incorrect code or password' })+ expect(res.setCookie).not.toHaveBeenCalled()+ expect(res.clearCookie).not.toHaveBeenCalled()+ })++ it('should reset 2FA for the selected user', async () => {+ const result = { success: true, message: '' }+ const adminResetUserTwoFaSpy = vi.spyOn(authProvider2FA, 'adminResetUserTwoFa').mockResolvedValue(result)++ await expect(authController.twoFaReset(42)).resolves.toEqual(result)+ expect(adminResetUserTwoFaSpy).toHaveBeenCalledWith(42)+ })+it('should refresh JWT in response body', async () => {userTest.exp = currentTimeStamp() + convertHumanTimeToSeconds('30s')const result = await authController.refreshToken(userTest)@@ -122,3 +262,323 @@ describe(AuthController.name, () => {await expect(authController.refreshToken(userTest)).rejects.toThrow()})})++describe(`${AuthController.name} HTTP`, () => {+ let app: NestFastifyApplication+ let authManager: AuthManager+ let authProvider2FA: AuthProvider2FA+ let jwtService: JwtService+ let authConfig: AuthConfig+ let userTest: UserModel+ let requestUser: UserModel | undefined++ beforeAll(async () => {+ const testingModuleBuilder = Test.createTestingModule({+ imports: [await ConfigModule.forRoot({ load: [exportConfiguration], isGlobal: true }), PassportModule],+ controllers: [AuthController],+ providers: [+ ConfigService,+ AuthManager,+ JwtService,+ AuthProvider2FA,+ AuthTwoFaVerificationGuard,+ AuthTokenTwoFaGuard,+ AuthTokenTwoFaStrategy,+ UserRolesGuard,+ { provide: PinoLogger, useValue: { assign: vi.fn() } },+ {+ provide: APP_GUARD,+ inject: [Reflector],+ useFactory: (reflector: Reflector) => ({+ canActivate: (context: ExecutionContext) => {+ const skip = reflector.getAllAndOverride<boolean>(AUTH_TOKEN_SKIP, [context.getHandler(), context.getClass()])+ if (skip) return true+ if (!requestUser) throw new UnauthorizedException()+ context.switchToHttp().getRequest().user = requestUser+ return true+ }+ })+ },+ { provide: DB_TOKEN_PROVIDER, useValue: {} },+ { provide: Cache, useValue: {} },+ { provide: UsersManager, useValue: { updateAccesses: vi.fn().mockResolvedValue(undefined) } },+ { provide: NotificationsManager, useValue: {} }+ ]+ })+ testingModuleBuilder.overrideGuard(AuthLocalGuard).useValue({+ canActivate: (context: ExecutionContext) => {+ context.switchToHttp().getRequest().user = userTest+ return true+ }+ })+ const module: TestingModule = await testingModuleBuilder.compile()++ module.useLogger(['fatal'])+ authConfig = module.get<ConfigService>(ConfigService).get<AuthConfig>('auth')+ authManager = module.get<AuthManager>(AuthManager)+ authProvider2FA = module.get<AuthProvider2FA>(AuthProvider2FA)+ jwtService = module.get<JwtService>(JwtService)+ userTest = new UserModel({ ...generateUserTest(), id: 888 }, false)+ app = module.createNestApplication<NestFastifyApplication>(new FastifyAdapter())+ await app.register(fastifyCookie, { secret: authConfig.token.csrf.secret })+ app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true }))+ await app.init()+ await app.getHttpAdapter().getInstance().ready()+ })++ afterAll(async () => {+ await app.close()+ })++ beforeEach(() => {+ vi.restoreAllMocks()+ requestUser = undefined+ })++ function createTwoFaUser(role = USER_ROLE.USER): UserModel {+ return new UserModel({ ...generateUserTest(), id: userTest.id, role, secrets: { twoFaSecret: 'encrypted-secret' } }, false)+ }++ function injectToken(code?: string) {+ return app.inject({+ method: 'POST',+ url: API_AUTH_TOKEN,+ headers: code ? { [TWO_FA_HEADER_CODE]: code } : undefined,+ body: { login: userTest.login, password: userTest.password }+ })+ }++ it('should reject token issuance without a 2FA code', async () => {+ vi.spyOn(authProvider2FA, 'loadUser').mockResolvedValueOnce(createTwoFaUser())+ const getTokensSpy = vi.spyOn(authManager, 'getTokens')++ const response = await injectToken()++ expect(response.statusCode).toBe(403)+ expect(response.json().message).toBe('Missing TWO-FA code')+ expect(getTokensSpy).not.toHaveBeenCalled()+ })++ it('should reject token issuance with an invalid 2FA code', async () => {+ vi.spyOn(authProvider2FA, 'loadUser').mockResolvedValue(createTwoFaUser())+ vi.spyOn(authProvider2FA, 'validateTwoFactorCode').mockReturnValue({ success: false, message: 'Incorrect code or password' })+ const getTokensSpy = vi.spyOn(authManager, 'getTokens')++ const response = await injectToken('000000')++ expect(response.statusCode).toBe(403)+ expect(response.json().message).toBe('Incorrect code or password')+ expect(getTokensSpy).not.toHaveBeenCalled()+ })++ it('should issue tokens with a valid 2FA code', async () => {+ const twoFaUser = createTwoFaUser()+ vi.spyOn(authProvider2FA, 'loadUser').mockResolvedValue(twoFaUser)+ const validateTwoFactorCodeSpy = vi.spyOn(authProvider2FA, 'validateTwoFactorCode').mockReturnValue({ success: true, message: '' })+ const getTokensSpy = vi.spyOn(authManager, 'getTokens')++ const response = await injectToken('123456')++ expect(response.statusCode).toBe(201)+ expect(response.json()).toEqual(+ expect.objectContaining({+ [TOKEN_TYPE.ACCESS]: expect.any(String),+ [TOKEN_TYPE.REFRESH]: expect.any(String)+ })+ )+ expect(validateTwoFactorCodeSpy).toHaveBeenCalledWith('123456', twoFaUser.secrets.twoFaSecret)+ expect(getTokensSpy).toHaveBeenCalledWith(userTest)+ })++ it('should issue tokens without a 2FA code when 2FA is disabled', async () => {+ vi.spyOn(authProvider2FA, 'loadUser').mockResolvedValueOnce(userTest)+ const verifySpy = vi.spyOn(authProvider2FA, 'verify')+ const getTokensSpy = vi.spyOn(authManager, 'getTokens')++ const response = await injectToken()++ expect(response.statusCode).toBe(201)+ expect(verifySpy).not.toHaveBeenCalled()+ expect(getTokensSpy).toHaveBeenCalledWith(userTest)+ })++ it('should expose authentication settings without authentication', async () => {+ vi.spyOn(authManager, 'authSettings').mockReturnValue(false)++ const response = await app.inject({ method: 'GET', url: API_AUTH_SETTINGS })++ expect(response.statusCode).toBe(200)+ expect(response.json()).toBe(false)+ })++ it('should reject 2FA login verification without a temporary token', async () => {+ const response = await app.inject({+ method: 'POST',+ url: API_TWO_FA_LOGIN_VERIFY,+ body: { code: '123456' }+ })++ expect(response.statusCode).toBe(401)+ })++ it('should verify 2FA login through the temporary token guard', async () => {+ const twoFaUser = createTwoFaUser()+ const csrfToken = 'temporary-csrf-token'+ const temporaryToken = await jwtService.signAsync(+ {+ tokenType: TOKEN_TYPE.ACCESS_2FA,+ identity: {+ id: twoFaUser.id,+ login: twoFaUser.login,+ language: twoFaUser.language,+ role: twoFaUser.role,+ twoFaEnabled: true+ },+ csrf: csrfToken+ } as JwtPayload,+ {+ secret: authConfig.token[TOKEN_TYPE.ACCESS_2FA].secret,+ expiresIn: 30+ }+ )+ vi.spyOn(authProvider2FA, 'loadUser').mockResolvedValue(twoFaUser)+ vi.spyOn(authProvider2FA, 'validateTwoFactorCode').mockReturnValue({ success: true, message: '' })++ const response = await app.inject({+ method: 'POST',+ url: API_TWO_FA_LOGIN_VERIFY,+ headers: { [CSRF_KEY]: sign(csrfToken, authConfig.token.csrf.secret) },+ cookies: { [authConfig.token[TOKEN_TYPE.ACCESS_2FA].name]: temporaryToken },+ body: { code: '123456' }+ })++ expect(response.statusCode).toBe(201)+ expect(response.json()).toEqual(expect.objectContaining({ success: true }))+ const cookies = response.headers['set-cookie'] as string[]+ expect(cookies).toHaveLength(5)+ expect(cookies).toEqual(+ expect.arrayContaining([+ expect.stringMatching(new RegExp(`^${authConfig.token.access.name}=.+;.*Path=${TOKEN_PATHS[TOKEN_TYPE.ACCESS]}(?:;|$)`)),+ expect.stringMatching(new RegExp(`^${authConfig.token.refresh.name}=.+;.*Path=${TOKEN_PATHS[TOKEN_TYPE.REFRESH]}(?:;|$)`)),+ expect.stringMatching(new RegExp(`^${authConfig.token.ws.name}=.+;.*Path=${TOKEN_PATHS[TOKEN_TYPE.WS]}(?:;|$)`)),+ expect.stringMatching(new RegExp(`^${authConfig.token.csrf.name}=.+;.*Path=${TOKEN_PATHS[TOKEN_TYPE.CSRF]}(?:;|$)`)),+ expect.stringMatching(+ new RegExp(`^${authConfig.token[TOKEN_TYPE.ACCESS_2FA].name}=;.*Max-Age=0;.*Path=${TOKEN_PATHS[TOKEN_TYPE.ACCESS_2FA]}(?:;|$)`)+ )+ ])+ )+ })++ it('should reject unauthenticated requests to 2FA routes', async () => {+ const response = await app.inject({ method: 'GET', url: API_TWO_FA_ENABLE })++ expect(response.statusCode).toBe(401)+ })++ it('should allow a user to initialize 2FA', async () => {+ const setup = { secret: 'secret', qrDataUrl: 'data:image/png;base64,test' }+ requestUser = userTest+ const initTwoFactorSpy = vi.spyOn(authProvider2FA, 'initTwoFactor').mockResolvedValue(setup)++ const response = await app.inject({ method: 'GET', url: API_TWO_FA_ENABLE })++ expect(response.statusCode).toBe(200)+ expect(response.json()).toEqual(setup)+ expect(initTwoFactorSpy).toHaveBeenCalledWith(userTest)+ })++ it('should reject a user attempting an administrator 2FA reset', async () => {+ requestUser = userTest+ const adminResetUserTwoFaSpy = vi.spyOn(authProvider2FA, 'adminResetUserTwoFa')++ const response = await app.inject({+ method: 'POST',+ url: `${API_TWO_FA_ADMIN_RESET_USER}/42`+ })++ expect(response.statusCode).toBe(403)+ expect(adminResetUserTwoFaSpy).not.toHaveBeenCalled()+ })++ it('should allow an administrator to reset user 2FA', async () => {+ const administrator = createTwoFaUser(USER_ROLE.ADMINISTRATOR)+ requestUser = administrator+ const result = { success: true, message: '' }+ const loadUserSpy = vi.spyOn(authProvider2FA, 'loadUser').mockResolvedValue(administrator)+ const verifyUserPasswordSpy = vi.spyOn(authProvider2FA, 'verifyUserPassword').mockResolvedValue(undefined)+ const validateTwoFactorCodeSpy = vi.spyOn(authProvider2FA, 'validateTwoFactorCode').mockReturnValue({ success: true, message: '' })+ const adminResetUserTwoFaSpy = vi.spyOn(authProvider2FA, 'adminResetUserTwoFa').mockResolvedValue(result)++ const response = await app.inject({+ method: 'POST',+ url: `${API_TWO_FA_ADMIN_RESET_USER}/42`,+ headers: {+ [TWO_FA_HEADER_PASSWORD]: 'password',+ [TWO_FA_HEADER_CODE]: '123456'+ }+ })++ expect(response.statusCode).toBe(201)+ expect(response.json()).toEqual(result)+ expect(loadUserSpy).toHaveBeenCalledWith(administrator.id, expect.any(String))+ expect(verifyUserPasswordSpy).toHaveBeenCalledWith(administrator, 'password', expect.any(String))+ expect(validateTwoFactorCodeSpy).toHaveBeenCalledWith('123456', administrator.secrets.twoFaSecret)+ expect(adminResetUserTwoFaSpy).toHaveBeenCalledWith(42)+ })++ it('should reject an administrator 2FA reset without password', async () => {+ const administrator = createTwoFaUser(USER_ROLE.ADMINISTRATOR)+ requestUser = administrator+ vi.spyOn(authProvider2FA, 'loadUser').mockResolvedValue(administrator)+ const adminResetUserTwoFaSpy = vi.spyOn(authProvider2FA, 'adminResetUserTwoFa')++ const response = await app.inject({+ method: 'POST',+ url: `${API_TWO_FA_ADMIN_RESET_USER}/42`+ })++ expect(response.statusCode).toBe(403)+ expect(response.json().message).toBe('Missing TWO-FA password')+ expect(adminResetUserTwoFaSpy).not.toHaveBeenCalled()+ })++ it('should reject an administrator 2FA reset without TOTP verification', async () => {+ const administrator = createTwoFaUser(USER_ROLE.ADMINISTRATOR)+ requestUser = administrator+ vi.spyOn(authProvider2FA, 'loadUser').mockResolvedValue(administrator)+ const verifyUserPasswordSpy = vi.spyOn(authProvider2FA, 'verifyUserPassword').mockResolvedValue(undefined)+ const adminResetUserTwoFaSpy = vi.spyOn(authProvider2FA, 'adminResetUserTwoFa')++ const response = await app.inject({+ method: 'POST',+ url: `${API_TWO_FA_ADMIN_RESET_USER}/42`,+ headers: { [TWO_FA_HEADER_PASSWORD]: 'password' }+ })++ expect(response.statusCode).toBe(403)+ expect(response.json().message).toBe('Missing TWO-FA code')+ expect(verifyUserPasswordSpy).toHaveBeenCalledWith(administrator, 'password', expect.any(String))+ expect(adminResetUserTwoFaSpy).not.toHaveBeenCalled()+ })++ it('should reject a non-numeric user id for an administrator 2FA reset', async () => {+ const administrator = createTwoFaUser(USER_ROLE.ADMINISTRATOR)+ requestUser = administrator+ vi.spyOn(authProvider2FA, 'loadUser').mockResolvedValue(administrator)+ vi.spyOn(authProvider2FA, 'verifyUserPassword').mockResolvedValue(undefined)+ vi.spyOn(authProvider2FA, 'validateTwoFactorCode').mockReturnValue({ success: true, message: '' })+ const adminResetUserTwoFaSpy = vi.spyOn(authProvider2FA, 'adminResetUserTwoFa')++ const response = await app.inject({+ method: 'POST',+ url: `${API_TWO_FA_ADMIN_RESET_USER}/invalid`,+ headers: {+ [TWO_FA_HEADER_PASSWORD]: 'password',+ [TWO_FA_HEADER_CODE]: '123456'+ }+ })++ expect(response.statusCode).toBe(400)+ expect(adminResetUserTwoFaSpy).not.toHaveBeenCalled()+ })+})diff --git a/backend/src/authentication/auth.controller.ts b/backend/src/authentication/auth.controller.tsindex 546722b1..7fb43a33 100755--- a/backend/src/authentication/auth.controller.ts+++ b/backend/src/authentication/auth.controller.ts@@ -17,7 +17,8 @@ import { FastifyAuthenticatedRequest } from './interfaces/auth-request.interfaceimport { TOKEN_TYPE } from './interfaces/token.interface'import type { AuthOIDCSettings } from './providers/oidc/auth-oidc.interfaces'import { AuthProvider2FA } from './providers/two-fa/auth-provider-two-fa.service'-import { AuthTwoFaGuard } from './providers/two-fa/auth-two-fa-guard'+import { AuthTokenTwoFaGuard } from './providers/two-fa/guards/auth-token-two-fa.guard'+import { AuthTwoFaVerificationGuard, AuthTwoFaVerificationWithoutPasswordGuard } from './providers/two-fa/guards/auth-two-fa-verification.guard'import { TwoFaResponseDto, TwoFaVerifyDto, TwoFaVerifyWithPasswordDto } from './providers/two-fa/auth-two-fa.dtos'import { TwoFaSetup, TwoFaVerifyResult } from './providers/two-fa/auth-two-fa.interfaces'@@ -50,7 +51,7 @@ export class AuthController {@Post(AUTH_ROUTE.TOKEN)@AuthTokenSkip()- @UseGuards(AuthLocalGuard)+ @UseGuards(AuthLocalGuard, AuthTwoFaVerificationWithoutPasswordGuard)token(@GetUser() user: UserModel): Promise<TokenResponseDto> {return this.authManager.getTokens(user)}@@ -92,7 +93,8 @@ export class AuthController {}@Post(`${AUTH_ROUTE.TWO_FA_BASE}/${AUTH_ROUTE.TWO_FA_LOGIN_VERIFY}`)- @UseGuards(UserRolesGuard)+ @AuthTokenSkip()+ @UseGuards(AuthTokenTwoFaGuard, UserRolesGuard)@UserHaveRole(USER_ROLE.USER)async twoFaLogin(@Body() body: TwoFaVerifyDto,@@ -110,7 +112,7 @@ export class AuthController {}@Post(`${AUTH_ROUTE.TWO_FA_BASE}/${AUTH_ROUTE.TWO_FA_ADMIN_RESET_USER}/:id`)- @UseGuards(UserRolesGuard, AuthTwoFaGuard)+ @UseGuards(UserRolesGuard, AuthTwoFaVerificationGuard)@UserHaveRole(USER_ROLE.ADMINISTRATOR)twoFaReset(@Param('id', ParseIntPipe) userId: number): Promise<TwoFaVerifyResult> {return this.authProvider2FA.adminResetUserTwoFa(userId)diff --git a/backend/src/authentication/auth.e2e-spec.ts b/backend/src/authentication/auth.e2e-spec.tsindex 4f00412a..74b45abb 100644--- a/backend/src/authentication/auth.e2e-spec.ts+++ b/backend/src/authentication/auth.e2e-spec.ts@@ -129,6 +129,7 @@ describe('Auth (e2e)', () => {})expect(decodedToken.iat).toBeCloseTo(currentTimeStamp(), -1)expect(decodedToken.exp).toBeCloseTo(currentTimeStamp() + convertHumanTimeToSeconds(authConfig.token[cookie.type].expiration), -1)+ expect(decodedToken.tokenType).toBe(cookie.type)expect(decodedToken.identity.id).toBe(userTest.id)if (cookie.type === TOKEN_TYPE.REFRESH) {// needed for the following testsdiff --git a/backend/src/authentication/auth.module.ts b/backend/src/authentication/auth.module.tsindex 3cb4b318..26c90789 100755--- a/backend/src/authentication/auth.module.ts+++ b/backend/src/authentication/auth.module.ts@@ -21,6 +21,8 @@ import { AuthProvider } from './providers/auth-providers.models'import { selectAuthProvider } from './providers/auth-providers'import { AuthProviderOIDCModule } from './providers/oidc/auth-provider-oidc.module'import { AuthProvider2FA } from './providers/two-fa/auth-provider-two-fa.service'+import { AuthTokenTwoFaGuard } from './providers/two-fa/guards/auth-token-two-fa.guard'+import { AuthTokenTwoFaStrategy } from './providers/two-fa/guards/auth-token-two-fa.strategy'@Global()@Module({@@ -37,12 +39,14 @@ import { AuthProvider2FA } from './providers/two-fa/auth-provider-two-fa.serviceuseClass: AuthTokenAccessGuard},AuthTokenRefreshGuard,+ AuthTokenTwoFaGuard,AuthLocalGuard,AuthBasicGuard,AuthAnonymousGuard,AuthLocalStrategy,AuthTokenAccessStrategy,AuthTokenRefreshStrategy,+ AuthTokenTwoFaStrategy,AuthBasicStrategy,AuthAnonymousStrategy,AuthManager,diff --git a/backend/src/authentication/auth.service.ts b/backend/src/authentication/auth.service.tsindex 7219687a..b1a7a857 100755--- a/backend/src/authentication/auth.service.ts+++ b/backend/src/authentication/auth.service.ts@@ -108,7 +108,7 @@ export class AuthManager {}}- csrfValidation(req: FastifyRequest, jwtPayload: JwtPayload, type: TOKEN_TYPE.ACCESS | TOKEN_TYPE.REFRESH): void {+ csrfValidation(req: FastifyRequest, jwtPayload: JwtPayload, type: TOKEN_TYPE.ACCESS | TOKEN_TYPE.ACCESS_2FA | TOKEN_TYPE.REFRESH): void {// ignore safe methodsif (HTTP_CSRF_IGNORED_METHODS.has(req.method)) {return@@ -150,6 +150,7 @@ export class AuthManager {private jwtSign(user: UserModel, type: TOKEN_TYPE, expiration: number, csrfToken?: string): Promise<string> {return this.jwt.signAsync({+ tokenType: type,identity: {id: user.id,login: user.login,@@ -176,6 +177,7 @@ export class AuthManager {// Restrict the temporary token to the minimum required informationreturn this.jwt.signAsync({+ tokenType: type,identity: {id: user.id,login: user.login,diff --git a/backend/src/authentication/guards/auth-token-access.guard.spec.ts b/backend/src/authentication/guards/auth-token-access.guard.spec.tsindex 7203fb36..90d9bbe6 100644--- a/backend/src/authentication/guards/auth-token-access.guard.spec.ts+++ b/backend/src/authentication/guards/auth-token-access.guard.spec.ts@@ -33,6 +33,7 @@ describe(AuthTokenAccessGuard.name, () => {let reflector: Reflectorlet accessTokenWithoutCSRF: stringlet accessToken: string+ let temporaryTwoFaToken: stringlet context: DeepMocked<ExecutionContext>beforeAll(async () => {@@ -66,14 +67,24 @@ describe(AuthTokenAccessGuard.name, () => {authAccessGuard = new AuthTokenAccessGuard(reflector)authAnonymousStrategy = module.get<AuthAnonymousStrategy>(AuthAnonymousStrategy)authAnonymousGuard = module.get<AuthAnonymousGuard>(AuthAnonymousGuard)- accessToken = await jwtService.signAsync({ identity: { id: 1, login: 'foo' }, [TOKEN_TYPE.CSRF]: csrfToken } as JwtPayload, {- secret: authConfig.token.access.secret,- expiresIn: 30- })- accessTokenWithoutCSRF = await jwtService.signAsync({ identity: { id: 1, login: 'foo' } } as JwtPayload, {+ accessToken = await jwtService.signAsync(+ { tokenType: TOKEN_TYPE.ACCESS, identity: { id: 1, login: 'foo' }, [TOKEN_TYPE.CSRF]: csrfToken } as JwtPayload,+ {+ secret: authConfig.token.access.secret,+ expiresIn: 30+ }+ )+ accessTokenWithoutCSRF = await jwtService.signAsync({ tokenType: TOKEN_TYPE.ACCESS, identity: { id: 1, login: 'foo' } } as JwtPayload, {secret: authConfig.token.access.secret,expiresIn: 30})+ temporaryTwoFaToken = await jwtService.signAsync(+ { tokenType: TOKEN_TYPE.ACCESS_2FA, identity: { id: 1, login: 'foo', twoFaEnabled: true }, csrf: csrfToken } as JwtPayload,+ {+ secret: authConfig.token.access.secret,+ expiresIn: 30+ }+ )context = createMock<ExecutionContext>()})@@ -85,6 +96,7 @@ describe(AuthTokenAccessGuard.name, () => {expect(authAnonymousStrategy).toBeDefined()expect(accessToken).toBeDefined()expect(accessTokenWithoutCSRF).toBeDefined()+ expect(temporaryTwoFaToken).toBeDefined()expect(csrfToken).toBeDefined()})@@ -131,6 +143,16 @@ describe(AuthTokenAccessGuard.name, () => {await expect(authAccessGuard.canActivate(context)).rejects.toThrow('Unauthorized')})+ it('should reject a temporary 2FA token in the authorization header', async () => {+ context.switchToHttp().getRequest.mockReturnValue({+ raw: { user: '' },+ headers: {+ authorization: `Bearer ${temporaryTwoFaToken}`+ }+ })+ await expect(authAccessGuard.canActivate(context)).rejects.toThrow('Unauthorized')+ })+it('should throw an error with a valid access token in cookies and a missing CSRF in request header', async () => {context.switchToHttp().getRequest.mockReturnValue({raw: { user: '' },diff --git a/backend/src/authentication/guards/auth-token-access.strategy.ts b/backend/src/authentication/guards/auth-token-access.strategy.tsindex 3abed9a7..34eb4827 100755--- a/backend/src/authentication/guards/auth-token-access.strategy.ts+++ b/backend/src/authentication/guards/auth-token-access.strategy.ts@@ -1,4 +1,4 @@-import { Injectable } from '@nestjs/common'+import { Injectable, UnauthorizedException } from '@nestjs/common'import { AbstractStrategy, PassportStrategy } from '@nestjs/passport'import { FastifyRequest } from 'fastify'import { PinoLogger } from 'nestjs-pino'@@ -27,6 +27,9 @@ export class AuthTokenAccessStrategy extends PassportStrategy(Strategy, 'tokenAc}validate(req: FastifyRequest, jwtPayload: JwtPayload): UserModel {+ if (jwtPayload.tokenType !== TOKEN_TYPE.ACCESS) {+ throw new UnauthorizedException()+ }this.logger.assign({ user: jwtPayload.identity.login })this.authManager.csrfValidation(req, jwtPayload, TOKEN_TYPE.ACCESS)return new UserModel(jwtPayload.identity)diff --git a/backend/src/authentication/guards/auth-token-refresh.guard.spec.ts b/backend/src/authentication/guards/auth-token-refresh.guard.spec.tsindex ac64deb7..84677395 100644--- a/backend/src/authentication/guards/auth-token-refresh.guard.spec.ts+++ b/backend/src/authentication/guards/auth-token-refresh.guard.spec.ts@@ -24,6 +24,7 @@ describe(AuthTokenRefreshGuard.name, () => {let authRefreshGuard: AuthTokenRefreshGuardlet refreshToken: stringlet refreshTokenWithoutCSRF: string+ let accessTokenSignedWithRefreshSecret: stringlet context: DeepMocked<ExecutionContext>beforeAll(async () => {@@ -46,14 +47,24 @@ describe(AuthTokenRefreshGuard.name, () => {authConfig = module.get<ConfigService>(ConfigService).get<AuthConfig>('auth')jwtService = module.get<JwtService>(JwtService)authRefreshGuard = module.get<AuthTokenRefreshGuard>(AuthTokenRefreshGuard)- refreshToken = await jwtService.signAsync({ identity: { id: 1, login: 'foo' }, [TOKEN_TYPE.CSRF]: csrfToken } as JwtPayload, {- secret: authConfig.token.refresh.secret,- expiresIn: 30- })- refreshTokenWithoutCSRF = await jwtService.signAsync({ identity: { id: 1, login: 'foo' } } as JwtPayload, {+ refreshToken = await jwtService.signAsync(+ { tokenType: TOKEN_TYPE.REFRESH, identity: { id: 1, login: 'foo' }, [TOKEN_TYPE.CSRF]: csrfToken } as JwtPayload,+ {+ secret: authConfig.token.refresh.secret,+ expiresIn: 30+ }+ )+ refreshTokenWithoutCSRF = await jwtService.signAsync({ tokenType: TOKEN_TYPE.REFRESH, identity: { id: 1, login: 'foo' } } as JwtPayload, {secret: authConfig.token.refresh.secret,expiresIn: 30})+ accessTokenSignedWithRefreshSecret = await jwtService.signAsync(+ { tokenType: TOKEN_TYPE.ACCESS, identity: { id: 1, login: 'foo' } } as JwtPayload,+ {+ secret: authConfig.token.refresh.secret,+ expiresIn: 30+ }+ )context = createMock<ExecutionContext>()})@@ -63,6 +74,7 @@ describe(AuthTokenRefreshGuard.name, () => {expect(authRefreshGuard).toBeDefined()expect(refreshToken).toBeDefined()expect(refreshTokenWithoutCSRF).toBeDefined()+ expect(accessTokenSignedWithRefreshSecret).toBeDefined()expect(csrfToken).toBeDefined()})@@ -108,6 +120,16 @@ describe(AuthTokenRefreshGuard.name, () => {await expect(authRefreshGuard.canActivate(context)).rejects.toThrow('Unauthorized')})+ it('should reject a token with an invalid type', async () => {+ context.switchToHttp().getRequest.mockReturnValue({+ raw: { user: '' },+ headers: {+ authorization: `Bearer ${accessTokenSignedWithRefreshSecret}`+ }+ })+ await expect(authRefreshGuard.canActivate(context)).rejects.toThrow('Unauthorized')+ })+it('should throw an error with a valid refresh token in cookies and a missing CSRF in request header', async () => {context.switchToHttp().getRequest.mockReturnValue({raw: { user: '' },diff --git a/backend/src/authentication/guards/auth-token-refresh.strategy.ts b/backend/src/authentication/guards/auth-token-refresh.strategy.tsindex 0184fb36..80d1a1c5 100755--- a/backend/src/authentication/guards/auth-token-refresh.strategy.ts+++ b/backend/src/authentication/guards/auth-token-refresh.strategy.ts@@ -1,4 +1,4 @@-import { Injectable } from '@nestjs/common'+import { Injectable, UnauthorizedException } from '@nestjs/common'import { AbstractStrategy, PassportStrategy } from '@nestjs/passport'import { FastifyRequest } from 'fastify'import { PinoLogger } from 'nestjs-pino'@@ -27,6 +27,9 @@ export class AuthTokenRefreshStrategy extends PassportStrategy(Strategy, 'tokenR}validate(req: FastifyRequest, jwtPayload: JwtPayload): UserModel {+ if (jwtPayload.tokenType !== TOKEN_TYPE.REFRESH) {+ throw new UnauthorizedException()+ }this.logger.assign({ user: jwtPayload.identity.login })this.authManager.csrfValidation(req, jwtPayload, TOKEN_TYPE.REFRESH)// jwt expiration is used later to refresh cookiesdiff --git a/backend/src/authentication/interfaces/jwt-payload.interface.ts b/backend/src/authentication/interfaces/jwt-payload.interface.tsindex 46fe796e..04a87500 100644--- a/backend/src/authentication/interfaces/jwt-payload.interface.ts+++ b/backend/src/authentication/interfaces/jwt-payload.interface.ts@@ -1,3 +1,5 @@+import { TOKEN_TYPE } from './token.interface'+export class JwtIdentityPayload {id: numberlogin: string@@ -20,9 +22,18 @@ export class JwtIdentity2FaPayload {twoFaEnabled: true}-export class JwtPayload {- identity: JwtIdentityPayload+export interface JwtPayloadBase {csrf?: stringiat?: numberexp: number}++export type JwtPayload =+ | (JwtPayloadBase & {+ identity: JwtIdentityPayload+ tokenType: TOKEN_TYPE.ACCESS | TOKEN_TYPE.REFRESH | TOKEN_TYPE.WS | TOKEN_TYPE.ONLY_OFFICE+ })+ | (JwtPayloadBase & {+ identity: JwtIdentity2FaPayload+ tokenType: TOKEN_TYPE.ACCESS_2FA+ })diff --git a/backend/src/authentication/interfaces/token.interface.ts b/backend/src/authentication/interfaces/token.interface.tsindex 39cae539..a8ad9108 100644--- a/backend/src/authentication/interfaces/token.interface.ts+++ b/backend/src/authentication/interfaces/token.interface.ts@@ -4,5 +4,7 @@ export enum TOKEN_TYPE {REFRESH = 'refresh',WS = 'ws',CSRF = 'csrf',- CSRF_2FA = 'csrf_2fa'+ CSRF_2FA = 'csrf_2fa',+ COLLABORA_ONLINE = 'collabora_online',+ ONLY_OFFICE = 'only_office'}diff --git a/backend/src/authentication/providers/two-fa/guards/auth-token-two-fa.guard.spec.ts b/backend/src/authentication/providers/two-fa/guards/auth-token-two-fa.guard.spec.tsnew file mode 100644index 00000000..98abfcda--- /dev/null+++ b/backend/src/authentication/providers/two-fa/guards/auth-token-two-fa.guard.spec.ts@@ -0,0 +1,106 @@+import { sign } from '@fastify/cookie'+import { createMock, DeepMocked } from '@golevelup/ts-vitest'+import { ExecutionContext } from '@nestjs/common'+import { ConfigModule, ConfigService } from '@nestjs/config'+import { JwtModule, JwtService } from '@nestjs/jwt'+import { PassportModule } from '@nestjs/passport'+import { Test, TestingModule } from '@nestjs/testing'+import { PinoLogger } from 'nestjs-pino'+import crypto from 'node:crypto'+import { exportConfiguration } from '../../../../configuration/config.environment'+import { AuthConfig } from '../../../auth.config'+import { AuthManager } from '../../../auth.service'+import { CSRF_ERROR } from '../../../constants/auth'+import { JwtPayload } from '../../../interfaces/jwt-payload.interface'+import { TOKEN_TYPE } from '../../../interfaces/token.interface'+import { AuthTokenTwoFaGuard } from './auth-token-two-fa.guard'+import { AuthTokenTwoFaStrategy } from './auth-token-two-fa.strategy'++describe(AuthTokenTwoFaGuard.name, () => {+ const csrfToken = crypto.randomUUID()+ let authConfig: AuthConfig+ let authTokenTwoFaGuard: AuthTokenTwoFaGuard+ let context: DeepMocked<ExecutionContext>+ let temporaryTwoFaToken: string+ let accessToken: string++ beforeAll(async () => {+ const module: TestingModule = await Test.createTestingModule({+ imports: [await ConfigModule.forRoot({ load: [exportConfiguration], isGlobal: true }), JwtModule.register({ global: true }), PassportModule],+ providers: [+ AuthTokenTwoFaGuard,+ AuthTokenTwoFaStrategy,+ AuthManager,+ {+ provide: PinoLogger,+ useValue: {+ assign: () => undefined+ }+ }+ ]+ }).compile()++ authConfig = module.get<ConfigService>(ConfigService).get<AuthConfig>('auth')+ const jwtService = module.get<JwtService>(JwtService)+ authTokenTwoFaGuard = module.get<AuthTokenTwoFaGuard>(AuthTokenTwoFaGuard)+ temporaryTwoFaToken = await jwtService.signAsync(+ { tokenType: TOKEN_TYPE.ACCESS_2FA, identity: { id: 1, login: 'foo', twoFaEnabled: true }, csrf: csrfToken } as JwtPayload,+ {+ secret: authConfig.token[TOKEN_TYPE.ACCESS_2FA].secret,+ expiresIn: 30+ }+ )+ accessToken = await jwtService.signAsync({ tokenType: TOKEN_TYPE.ACCESS, identity: { id: 1, login: 'foo' }, csrf: csrfToken } as JwtPayload, {+ secret: authConfig.token[TOKEN_TYPE.ACCESS_2FA].secret,+ expiresIn: 30+ })+ context = createMock<ExecutionContext>()+ })++ it('should accept a temporary 2FA token from its cookie with CSRF', async () => {+ context.switchToHttp().getRequest.mockReturnValue({+ raw: { user: '' },+ headers: { [authConfig.token.csrf.name]: sign(csrfToken, authConfig.token.csrf.secret) },+ cookies: {+ [authConfig.token[TOKEN_TYPE.ACCESS_2FA].name]: temporaryTwoFaToken+ }+ })++ await expect(authTokenTwoFaGuard.canActivate(context)).resolves.toBe(true)+ })++ it('should reject a normal access token', async () => {+ context.switchToHttp().getRequest.mockReturnValue({+ raw: { user: '' },+ headers: { [authConfig.token.csrf.name]: sign(csrfToken, authConfig.token.csrf.secret) },+ cookies: {+ [authConfig.token[TOKEN_TYPE.ACCESS_2FA].name]: accessToken+ }+ })++ await expect(authTokenTwoFaGuard.canActivate(context)).rejects.toThrow('Unauthorized')+ })++ it('should reject a temporary 2FA token without CSRF', async () => {+ context.switchToHttp().getRequest.mockReturnValue({+ raw: { user: '' },+ headers: {},+ cookies: {+ [authConfig.token[TOKEN_TYPE.ACCESS_2FA].name]: temporaryTwoFaToken+ }+ })++ await expect(authTokenTwoFaGuard.canActivate(context)).rejects.toThrow(new RegExp(CSRF_ERROR.MISSING_HEADERS))+ })++ it('should not accept a temporary 2FA token as a bearer token', async () => {+ context.switchToHttp().getRequest.mockReturnValue({+ raw: { user: '' },+ headers: {+ authorization: `Bearer ${temporaryTwoFaToken}`+ }+ })++ await expect(authTokenTwoFaGuard.canActivate(context)).rejects.toThrow('Unauthorized')+ })+})diff --git a/backend/src/authentication/providers/two-fa/guards/auth-token-two-fa.guard.ts b/backend/src/authentication/providers/two-fa/guards/auth-token-two-fa.guard.tsnew file mode 100644index 00000000..39dabdfc--- /dev/null+++ b/backend/src/authentication/providers/two-fa/guards/auth-token-two-fa.guard.ts@@ -0,0 +1,16 @@+import { ExecutionContext, Injectable, Logger } from '@nestjs/common'+import { AuthGuard, IAuthGuard } from '@nestjs/passport'++@Injectable()+export class AuthTokenTwoFaGuard extends AuthGuard('tokenTwoFa') implements IAuthGuard {+ private readonly logger = new Logger(AuthTokenTwoFaGuard.name)++ handleRequest<TUser = any>(err: any, user: any, info: Error, ctx: ExecutionContext, status?: any): TUser {+ const req = this.getRequest(ctx)+ req.raw.user = user?.login || 'unauthorized'+ if (info) {+ this.logger.warn(`<${req.raw.user}> <${req.ip}> ${info}`)+ }+ return super.handleRequest(err, user, info, ctx, status)+ }+}diff --git a/backend/src/authentication/providers/two-fa/guards/auth-token-two-fa.strategy.ts b/backend/src/authentication/providers/two-fa/guards/auth-token-two-fa.strategy.tsnew file mode 100644index 00000000..245a655b--- /dev/null+++ b/backend/src/authentication/providers/two-fa/guards/auth-token-two-fa.strategy.ts@@ -0,0 +1,44 @@+import { Injectable, UnauthorizedException } from '@nestjs/common'+import { AbstractStrategy, PassportStrategy } from '@nestjs/passport'+import { FastifyRequest } from 'fastify'+import { PinoLogger } from 'nestjs-pino'+import { ExtractJwt, Strategy } from 'passport-jwt'+import { UserModel } from '../../../../applications/users/models/user.model'+import { configuration } from '../../../../configuration/config.environment'+import { AuthManager } from '../../../auth.service'+import { JwtPayload } from '../../../interfaces/jwt-payload.interface'+import { TOKEN_TYPE } from '../../../interfaces/token.interface'++@Injectable()+export class AuthTokenTwoFaStrategy extends PassportStrategy(Strategy, 'tokenTwoFa') implements AbstractStrategy {+ private static accessCookieName: string++ constructor(+ private readonly authManager: AuthManager,+ private readonly logger: PinoLogger+ ) {+ super({+ jwtFromRequest: ExtractJwt.fromExtractors([AuthTokenTwoFaStrategy.extractJWTFromCookie]),+ secretOrKey: configuration.auth.token[TOKEN_TYPE.ACCESS_2FA].secret,+ ignoreExpiration: false,+ passReqToCallback: true+ })+ AuthTokenTwoFaStrategy.accessCookieName = configuration.auth.token[TOKEN_TYPE.ACCESS_2FA].name+ }++ validate(req: FastifyRequest, jwtPayload: JwtPayload): UserModel {+ if (jwtPayload.tokenType !== TOKEN_TYPE.ACCESS_2FA) {+ throw new UnauthorizedException()+ }+ this.logger.assign({ user: jwtPayload.identity.login })+ this.authManager.csrfValidation(req, jwtPayload, TOKEN_TYPE.ACCESS_2FA)+ return new UserModel(jwtPayload.identity)+ }++ private static extractJWTFromCookie(req: FastifyRequest): string | null {+ if (typeof req.cookies === 'object' && req.cookies[AuthTokenTwoFaStrategy.accessCookieName] !== undefined) {+ return req.cookies[AuthTokenTwoFaStrategy.accessCookieName]+ }+ return null+ }+}diff --git a/backend/src/authentication/providers/two-fa/auth-two-fa-guard.ts b/backend/src/authentication/providers/two-fa/guards/auth-two-fa-verification.guard.tssimilarity index 64%rename from backend/src/authentication/providers/two-fa/auth-two-fa-guard.tsrename to backend/src/authentication/providers/two-fa/guards/auth-two-fa-verification.guard.tsindex f36e57d3..ebc9e83e 100644--- a/backend/src/authentication/providers/two-fa/auth-two-fa-guard.ts+++ b/backend/src/authentication/providers/two-fa/guards/auth-two-fa-verification.guard.ts@@ -1,19 +1,19 @@import { CanActivate, ExecutionContext, HttpException, HttpStatus, Injectable, mixin, Type } from '@nestjs/common'-import { configuration } from '../../../configuration/config.environment'-import { TWO_FA_HEADER_CODE, TWO_FA_HEADER_PASSWORD } from '../../constants/auth'-import { FastifyAuthenticatedRequest } from '../../interfaces/auth-request.interface'-import { AuthProvider2FA } from './auth-provider-two-fa.service'+import { configuration } from '../../../../configuration/config.environment'+import { TWO_FA_HEADER_CODE, TWO_FA_HEADER_PASSWORD } from '../../../constants/auth'+import { FastifyAuthenticatedRequest } from '../../../interfaces/auth-request.interface'+import { AuthProvider2FA } from '../auth-provider-two-fa.service'-export const AuthTwoFaGuard = AuthTwoFaGuardFactory()-export const AuthTwoFaGuardWithoutPassword = AuthTwoFaGuardFactory({ withPassword: false })+export const AuthTwoFaVerificationGuard = AuthTwoFaVerificationGuardFactory()+export const AuthTwoFaVerificationWithoutPasswordGuard = AuthTwoFaVerificationGuardFactory({ withPassword: false })-interface TwoFaGuardOptions {+interface TwoFaVerificationGuardOptions {withPassword?: boolean}-function AuthTwoFaGuardFactory(options: TwoFaGuardOptions = { withPassword: true }): Type<CanActivate> {+function AuthTwoFaVerificationGuardFactory(options: TwoFaVerificationGuardOptions = { withPassword: true }): Type<CanActivate> {@Injectable()- class MixinAuthTwoFaGuard implements CanActivate {+ class MixinAuthTwoFaVerificationGuard implements CanActivate {constructor(private readonly authProvider2FA: AuthProvider2FA) {}async canActivate(ctx: ExecutionContext): Promise<boolean> {@@ -45,5 +45,5 @@ function AuthTwoFaGuardFactory(options: TwoFaGuardOptions = { withPassword: true}}- return mixin(MixinAuthTwoFaGuard)+ return mixin(MixinAuthTwoFaVerificationGuard)}diff --git a/backend/src/infrastructure/websocket/adapters/web-socket.adapter.spec.ts b/backend/src/infrastructure/websocket/adapters/web-socket.adapter.spec.tsnew file mode 100644index 00000000..cabd1820--- /dev/null+++ b/backend/src/infrastructure/websocket/adapters/web-socket.adapter.spec.ts@@ -0,0 +1,73 @@+import 'reflect-metadata'+import { Socket } from 'socket.io'+import { TOKEN_TYPE } from '../../../authentication/interfaces/token.interface'+import { configuration } from '../../../configuration/config.environment'+import { WebSocketAdapter } from './web-socket.adapter'++describe(WebSocketAdapter.name, () => {+ const token = 'signed-token'+ const identity = { id: 1, login: 'foo' }+ let adapter: WebSocketAdapter+ let jwtService: { verify: ReturnType<typeof vi.fn> }+ let socket: Socket+ let next: ReturnType<typeof vi.fn>++ beforeEach(() => {+ jwtService = {+ verify: vi.fn()+ }+ adapter = Object.create(WebSocketAdapter.prototype)+ Object.assign(adapter, {+ jwtService,+ logger: {+ warn: vi.fn()+ }+ })+ socket = {+ request: {+ headers: {+ cookie: `${configuration.auth.token.ws.name}=${token}`+ }+ },+ handshake: {+ address: '127.0.0.1',+ headers: {+ 'user-agent': 'vitest'+ },+ url: '/'+ },+ id: 'socket-id'+ } as unknown as Socket+ next = vi.fn()+ })++ it('should authenticate a socket with a WebSocket token', () => {+ jwtService.verify.mockReturnValue({+ tokenType: TOKEN_TYPE.WS,+ identity+ })++ Reflect.apply(Reflect.get(adapter, 'authenticateSocket'), adapter, [socket, next])++ expect(jwtService.verify).toHaveBeenCalledWith(token, {+ secret: configuration.auth.token.ws.secret+ })+ expect(socket).toHaveProperty('user', identity)+ expect(next).toHaveBeenCalledWith()+ })++ it.each([TOKEN_TYPE.ACCESS, TOKEN_TYPE.REFRESH, undefined])('should reject a token with type %s', (tokenType) => {+ jwtService.verify.mockReturnValue({+ tokenType,+ identity+ })++ Reflect.apply(Reflect.get(adapter, 'authenticateSocket'), adapter, [socket, next])++ expect(socket).not.toHaveProperty('user')+ expect(next).toHaveBeenCalledOnce()+ expect(next.mock.calls[0][0]).toMatchObject({+ message: 'Unauthorized'+ })+ })+})diff --git a/backend/src/infrastructure/websocket/adapters/web-socket.adapter.ts b/backend/src/infrastructure/websocket/adapters/web-socket.adapter.tsindex 5c67289e..81d3f372 100644--- a/backend/src/infrastructure/websocket/adapters/web-socket.adapter.ts+++ b/backend/src/infrastructure/websocket/adapters/web-socket.adapter.ts@@ -8,6 +8,7 @@ import cluster from 'node:cluster'import { Namespace, ServerOptions, Socket } from 'socket.io'import { USERS_WS } from '../../../applications/users/constants/websocket'import { type JwtPayload } from '../../../authentication/interfaces/jwt-payload.interface'+import { TOKEN_TYPE } from '../../../authentication/interfaces/token.interface'import { configuration } from '../../../configuration/config.environment'import { getClientAddress } from '../utils'import { ClusterAdapter } from './cluster.adapter'@@ -87,6 +88,10 @@ export class WebSocketAdapter extends IoAdapter {this.onAuthError('Payload is missing', socket, next)return}+ if (payload.tokenType !== TOKEN_TYPE.WS) {+ this.onAuthError('Invalid token type', socket, next)+ return+ }Object.assign(socket, { user: payload.identity })next()}