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(auth): require step-up for app password mutations
johavendb19b3ee4904
diff --git a/backend/src/applications/users/users.controller.ts b/backend/src/applications/users/users.controller.tsindex 7705d8ce..32d907b3 100755--- a/backend/src/applications/users/users.controller.ts+++ b/backend/src/applications/users/users.controller.ts@@ -2,7 +2,10 @@ 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 { AuthTwoFaVerificationWithoutPasswordGuard } from '../../authentication/providers/two-fa/guards/auth-two-fa-verification.guard'+import {+ AuthTwoFaVerificationOrPasswordGuard,+ 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,20 +41,20 @@ export class UsersController {@Get(`${USERS_ROUTE.ME}/${USERS_ROUTE.APP_PASSWORDS}`)@UserHaveRole(USER_ROLE.USER)- @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(AuthTwoFaVerificationWithoutPasswordGuard)+ @UseGuards(AuthTwoFaVerificationOrPasswordGuard)generateAppPassword(@GetUser() user: UserModel, @Body() userAppPasswordDto: UserAppPasswordDto): Promise<UserAppPassword> {return this.usersManager.generateAppPassword(user, userAppPasswordDto)}@Delete(`${USERS_ROUTE.ME}/${USERS_ROUTE.APP_PASSWORDS}/:name`)@UserHaveRole(USER_ROLE.USER)+ @UseGuards(AuthTwoFaVerificationOrPasswordGuard)deleteAppPassword(@GetUser() user: UserModel, @Param('name') name: string): Promise<void> {return this.usersManager.deleteAppPassword(user, name)}diff --git a/backend/src/authentication/providers/two-fa/guards/auth-two-fa-verification.guard.spec.ts b/backend/src/authentication/providers/two-fa/guards/auth-two-fa-verification.guard.spec.tsnew file mode 100644index 00000000..0965730e--- /dev/null+++ b/backend/src/authentication/providers/two-fa/guards/auth-two-fa-verification.guard.spec.ts@@ -0,0 +1,125 @@+import { createMock, DeepMocked } from '@golevelup/ts-vitest'+import { CanActivate, ExecutionContext } from '@nestjs/common'+import { Test, TestingModule } from '@nestjs/testing'+import type { MockInstance } from 'vitest'+import { UserModel } from '../../../../applications/users/models/user.model'+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 type { TwoFaVerifyDto } from '../auth-two-fa.dtos'+import type { TwoFaVerifyResult } from '../auth-two-fa.interfaces'+import { AuthTwoFaVerificationOrPasswordGuard } from './auth-two-fa-verification.guard'++type VerifyWithoutLogin = (verifyDto: TwoFaVerifyDto, req: FastifyAuthenticatedRequest) => Promise<TwoFaVerifyResult>++describe(AuthTwoFaVerificationOrPasswordGuard.name, () => {+ const originalTotpEnabled = configuration.auth.mfa.totp.enabled+ const userWithTotp = { id: 1, twoFaEnabled: true } as UserModel+ const userWithoutTotp = { id: 1, twoFaEnabled: false } as UserModel+ let guard: CanActivate+ let authProvider2FA: DeepMocked<AuthProvider2FA>++ beforeAll(async () => {+ authProvider2FA = createMock<AuthProvider2FA>()+ const module: TestingModule = await Test.createTestingModule({+ providers: [+ AuthTwoFaVerificationOrPasswordGuard,+ {+ provide: AuthProvider2FA,+ useValue: authProvider2FA+ }+ ]+ }).compile()++ guard = module.get<CanActivate>(AuthTwoFaVerificationOrPasswordGuard)+ })++ beforeEach(() => {+ configuration.auth.mfa.totp.enabled = true+ vi.resetAllMocks()+ })++ afterAll(() => {+ configuration.auth.mfa.totp.enabled = originalTotpEnabled+ })++ it('should verify TOTP without requiring the password when the user has TOTP enabled', async () => {+ authProvider2FA.loadUser.mockResolvedValue(userWithTotp)+ mockVerifyResult(authProvider2FA, { success: true, message: '' })++ const context = makeContext({ [TWO_FA_HEADER_CODE]: '123456' })++ await expect(guard.canActivate(context)).resolves.toBe(true)+ expect(authProvider2FA.loadUser).toHaveBeenCalledWith(userWithTotp.id, '127.0.0.1')+ expect(authProvider2FA.verifyUserPassword).not.toHaveBeenCalled()+ expect(authProvider2FA.verify).toHaveBeenCalledWith({ code: '123456' }, context.switchToHttp().getRequest())+ })++ it('should require the current password instead of TOTP when the user has no TOTP enabled', async () => {+ authProvider2FA.loadUser.mockResolvedValue(userWithoutTotp)+ authProvider2FA.verifyUserPassword.mockResolvedValue(undefined)++ await expect(guard.canActivate(makeContext({ [TWO_FA_HEADER_PASSWORD]: 'password' }))).resolves.toBe(true)+ expect(authProvider2FA.verifyUserPassword).toHaveBeenCalledWith(userWithoutTotp, 'password', '127.0.0.1')+ expect(authProvider2FA.verify).not.toHaveBeenCalled()+ })++ it('should require the current password when global TOTP is disabled', async () => {+ configuration.auth.mfa.totp.enabled = false+ authProvider2FA.loadUser.mockResolvedValue(userWithTotp)+ authProvider2FA.verifyUserPassword.mockResolvedValue(undefined)++ await expect(guard.canActivate(makeContext({ [TWO_FA_HEADER_PASSWORD]: 'password' }))).resolves.toBe(true)+ expect(authProvider2FA.verifyUserPassword).toHaveBeenCalledWith(userWithTotp, 'password', '127.0.0.1')+ expect(authProvider2FA.verify).not.toHaveBeenCalled()+ })++ it('should reject the request when the password fallback is missing', async () => {+ authProvider2FA.loadUser.mockResolvedValue(userWithoutTotp)++ await expect(guard.canActivate(makeContext())).rejects.toThrow('Missing TWO-FA password')+ expect(authProvider2FA.verifyUserPassword).not.toHaveBeenCalled()+ expect(authProvider2FA.verify).not.toHaveBeenCalled()+ })++ it('should reject the request when the password fallback is invalid', async () => {+ authProvider2FA.loadUser.mockResolvedValue(userWithoutTotp)+ authProvider2FA.verifyUserPassword.mockRejectedValue(new Error('Invalid password'))++ await expect(guard.canActivate(makeContext({ [TWO_FA_HEADER_PASSWORD]: 'wrong-password' }))).rejects.toThrow('Invalid password')+ expect(authProvider2FA.verifyUserPassword).toHaveBeenCalledWith(userWithoutTotp, 'wrong-password', '127.0.0.1')+ expect(authProvider2FA.verify).not.toHaveBeenCalled()+ })++ it('should reject the request when the TOTP code is missing', async () => {+ authProvider2FA.loadUser.mockResolvedValue(userWithTotp)++ await expect(guard.canActivate(makeContext())).rejects.toThrow('Missing TWO-FA code')+ expect(authProvider2FA.verifyUserPassword).not.toHaveBeenCalled()+ expect(authProvider2FA.verify).not.toHaveBeenCalled()+ })++ it('should reject the request when the TOTP code is invalid', async () => {+ authProvider2FA.loadUser.mockResolvedValue(userWithTotp)+ mockVerifyResult(authProvider2FA, { success: false, message: 'Invalid TOTP code' })++ await expect(guard.canActivate(makeContext({ [TWO_FA_HEADER_CODE]: '000000' }))).rejects.toThrow('Invalid TOTP code')+ expect(authProvider2FA.verifyUserPassword).not.toHaveBeenCalled()+ expect(authProvider2FA.verify).toHaveBeenCalledWith({ code: '000000' }, expect.any(Object))+ })+})++function mockVerifyResult(authProvider2FA: DeepMocked<AuthProvider2FA>, result: TwoFaVerifyResult): void {+ ;(authProvider2FA.verify as unknown as MockInstance<VerifyWithoutLogin>).mockResolvedValue(result)+}++function makeContext(headers: Record<string, string> = {}): DeepMocked<ExecutionContext> {+ const context = createMock<ExecutionContext>()+ context.switchToHttp().getRequest.mockReturnValue({+ user: { id: 1 },+ ip: '127.0.0.1',+ headers+ } as FastifyAuthenticatedRequest)+ return context+}diff --git a/backend/src/authentication/providers/two-fa/guards/auth-two-fa-verification.guard.ts b/backend/src/authentication/providers/two-fa/guards/auth-two-fa-verification.guard.tsindex ebc9e83e..04c7597b 100644--- a/backend/src/authentication/providers/two-fa/guards/auth-two-fa-verification.guard.ts+++ b/backend/src/authentication/providers/two-fa/guards/auth-two-fa-verification.guard.ts@@ -6,8 +6,10 @@ import { AuthProvider2FA } from '../auth-provider-two-fa.service'export const AuthTwoFaVerificationGuard = AuthTwoFaVerificationGuardFactory()export const AuthTwoFaVerificationWithoutPasswordGuard = AuthTwoFaVerificationGuardFactory({ withPassword: false })+export const AuthTwoFaVerificationOrPasswordGuard = AuthTwoFaVerificationGuardFactory({ passwordFallback: true, withPassword: false })interface TwoFaVerificationGuardOptions {+ passwordFallback?: booleanwithPassword?: boolean}@@ -19,15 +21,16 @@ function AuthTwoFaVerificationGuardFactory(options: TwoFaVerificationGuardOptionasync canActivate(ctx: ExecutionContext): Promise<boolean> {const req: FastifyAuthenticatedRequest = ctx.switchToHttp().getRequest()const user = await this.authProvider2FA.loadUser(req.user.id, req.ip)+ const twoFaEnabled = configuration.auth.mfa.totp.enabled && user.twoFaEnabled- if (options.withPassword) {+ if (options.withPassword || (options.passwordFallback && !twoFaEnabled)) {if (!req.headers[TWO_FA_HEADER_PASSWORD]) {throw new HttpException('Missing TWO-FA password', HttpStatus.FORBIDDEN)}await this.authProvider2FA.verifyUserPassword(user, req.headers[TWO_FA_HEADER_PASSWORD] as string, req.ip)}- if (!configuration.auth.mfa.totp.enabled || !user.twoFaEnabled) {+ if (!twoFaEnabled) {return true}diff --git a/frontend/src/app/applications/admin/admin.service.ts b/frontend/src/app/applications/admin/admin.service.tsindex 82560aab..7b326162 100644--- a/frontend/src/app/applications/admin/admin.service.ts+++ b/frontend/src/app/applications/admin/admin.service.ts@@ -46,6 +46,8 @@ import {import type { IndexingStatus } from '@sync-in-server/backend/src/applications/files/interfaces/indexing.interface'import type { SPACE_OPERATION } from '@sync-in-server/backend/src/applications/spaces/constants/spaces'+type OptionalTwoFaHeaders = HttpHeaders | undefined+@Injectable({providedIn: 'root'})@@ -68,19 +70,26 @@ export class AdminService {.pipe(map((u) => (isGuest ? new GuestUserModel(u) : new AdminUserModel(u))))}- createUser(createUserDto: CreateUserDto, twoFaHeaders: HttpHeaders, isGuest?: false): Observable<AdminUserModel>- createUser(createUserDto: CreateUserDto, twoFaHeaders: HttpHeaders, isGuest: true): Observable<GuestUserModel>- createUser(createUserDto: CreateUserDto, twoFaHeaders: HttpHeaders, isGuest = false): Observable<AdminUserModel | GuestUserModel> {+ createUser(createUserDto: CreateUserDto, twoFaHeaders: OptionalTwoFaHeaders, isGuest?: false): Observable<AdminUserModel>+ createUser(createUserDto: CreateUserDto, twoFaHeaders: OptionalTwoFaHeaders, isGuest: true): Observable<GuestUserModel>+ createUser(createUserDto: CreateUserDto, twoFaHeaders: OptionalTwoFaHeaders, isGuest = false): Observable<AdminUserModel | GuestUserModel> {return this.http- .post<AdminUser | GuestUser>(isGuest ? API_ADMIN_GUESTS : API_ADMIN_USERS, createUserDto, { headers: twoFaHeaders })+ .post<AdminUser | GuestUser>(isGuest ? API_ADMIN_GUESTS : API_ADMIN_USERS, createUserDto, twoFaHeaders ? { headers: twoFaHeaders } : undefined).pipe(map((u) => (isGuest ? new GuestUserModel(u) : new AdminUserModel(u))))}- updateUser(userId: number, updateUserDto: UpdateUserDto, twoFaHeaders: HttpHeaders, isGuest?: false): Observable<AdminUserModel>- updateUser(userId: number, updateUserDto: UpdateUserDto, twoFaHeaders: HttpHeaders, isGuest: true): Observable<GuestUserModel>- updateUser(userId: number, updateUserDto: UpdateUserDto, twoFaHeaders: HttpHeaders, isGuest = false): Observable<AdminUserModel | GuestUserModel> {+ updateUser(userId: number, updateUserDto: UpdateUserDto, twoFaHeaders: OptionalTwoFaHeaders, isGuest?: false): Observable<AdminUserModel>+ updateUser(userId: number, updateUserDto: UpdateUserDto, twoFaHeaders: OptionalTwoFaHeaders, isGuest: true): Observable<GuestUserModel>+ updateUser(+ userId: number,+ updateUserDto: UpdateUserDto,+ twoFaHeaders: OptionalTwoFaHeaders,+ isGuest = false+ ): Observable<AdminUserModel | GuestUserModel> {return this.http- .put<AdminUser | GuestUser>(`${isGuest ? API_ADMIN_GUESTS : API_ADMIN_USERS}/${userId}`, updateUserDto, { headers: twoFaHeaders })+ .put<+ AdminUser | GuestUser+ >(`${isGuest ? API_ADMIN_GUESTS : API_ADMIN_USERS}/${userId}`, updateUserDto, twoFaHeaders ? { headers: twoFaHeaders } : undefined).pipe(map((u) => (isGuest ? new GuestUserModel(u) : new AdminUserModel(u))))}diff --git a/frontend/src/app/applications/users/components/dialogs/user-auth-manage-app-passwords-dialog.component.ts b/frontend/src/app/applications/users/components/dialogs/user-auth-manage-app-passwords-dialog.component.tsindex 9e7ebb12..2bd4d5c8 100644--- a/frontend/src/app/applications/users/components/dialogs/user-auth-manage-app-passwords-dialog.component.ts+++ b/frontend/src/app/applications/users/components/dialogs/user-auth-manage-app-passwords-dialog.component.ts@@ -64,8 +64,12 @@ export class UserAuthManageAppPasswordsDialogComponent {this.layout.closeDialog()}- deleteAppPassword(passwordName: string) {- this.userService.deleteAppPassword(passwordName).subscribe({+ async deleteAppPassword(passwordName: string) {+ const auth2FaHeaders: false | HttpHeaders = await this.userService.auth2FaVerifyDialog(false, true)+ if (auth2FaHeaders === false) {+ return+ }+ this.userService.deleteAppPassword(passwordName, auth2FaHeaders).subscribe({next: () => {this.appPasswords = this.appPasswords.filter((pwd) => pwd.name !== passwordName)this.nbAppPasswords.emit(this.appPasswords.length)@@ -81,7 +85,7 @@ export class UserAuthManageAppPasswordsDialogComponent {return}}- const auth2FaHeaders: false | HttpHeaders = await this.userService.auth2FaVerifyDialog()+ const auth2FaHeaders: false | HttpHeaders = await this.userService.auth2FaVerifyDialog(false, true)if (auth2FaHeaders === false) {return}diff --git a/frontend/src/app/applications/users/components/user-account.component.ts b/frontend/src/app/applications/users/components/user-account.component.tsindex 97069cfe..303459ca 100644--- a/frontend/src/app/applications/users/components/user-account.component.ts+++ b/frontend/src/app/applications/users/components/user-account.component.ts@@ -238,11 +238,7 @@ export class UserAccountComponent implements OnInit, OnDestroy {}async manageAppPasswords() {- const auth2FaHeaders: false | HttpHeaders = await this.userService.auth2FaVerifyDialog()- if (auth2FaHeaders === false) {- return- }- this.userService.listAppPasswords(auth2FaHeaders).subscribe({+ this.userService.listAppPasswords().subscribe({next: (appPasswords: Omit<UserAppPassword, 'password'>[]) => {const modalRef: BsModalRef<UserAuthManageAppPasswordsDialogComponent> = this.layout.openDialog(UserAuthManageAppPasswordsDialogComponent,diff --git a/frontend/src/app/applications/users/user.service.ts b/frontend/src/app/applications/users/user.service.tsindex 05c1d9cd..7c90134d 100644--- a/frontend/src/app/applications/users/user.service.ts+++ b/frontend/src/app/applications/users/user.service.ts@@ -69,6 +69,8 @@ import { UserOnlineModel } from './models/user-online.model'import { myAvatarUrl } from './user.functions'import type { LoginResponseDto } from '@sync-in-server/backend/src/authentication/dto/login-response.dto'+type Auth2FaVerifyDialogResult = false | HttpHeaders | undefined+@Injectable({ providedIn: 'root' })export class UserService {private readonly http = inject(HttpClient)@@ -218,8 +220,8 @@ export class UserService {})}- changePassword(userPasswordDto: UserUpdatePasswordDto, twoFaHeaders: HttpHeaders): Observable<any> {- return this.http.put(API_USERS_MY_PASSWORD, userPasswordDto, { headers: twoFaHeaders })+ changePassword(userPasswordDto: UserUpdatePasswordDto, twoFaHeaders: HttpHeaders | undefined): Observable<any> {+ return this.http.put(API_USERS_MY_PASSWORD, userPasswordDto, twoFaHeaders ? { headers: twoFaHeaders } : undefined)}changeLanguage(userLanguageDto: UserLanguageDto): Observable<any> {@@ -310,16 +312,16 @@ export class UserService {}}- listAppPasswords(twoFaHeaders: HttpHeaders): Observable<Omit<UserAppPassword, 'password'>[]> {- return this.http.get<Omit<UserAppPassword, 'password'>[]>(API_USERS_MY_APP_PASSWORDS, { headers: twoFaHeaders })+ listAppPasswords(): Observable<Omit<UserAppPassword, 'password'>[]> {+ return this.http.get<Omit<UserAppPassword, 'password'>[]>(API_USERS_MY_APP_PASSWORDS)}generateAppPassword(userAppPasswordDto: UserAppPasswordDto, twoFaHeaders: HttpHeaders): Observable<UserAppPassword> {return this.http.post<UserAppPassword>(API_USERS_MY_APP_PASSWORDS, userAppPasswordDto, { headers: twoFaHeaders })}- deleteAppPassword(name: string): Observable<void> {- return this.http.delete<void>(`${API_USERS_MY_APP_PASSWORDS}/${name}`)+ deleteAppPassword(name: string, twoFaHeaders: HttpHeaders): Observable<void> {+ return this.http.delete<void>(`${API_USERS_MY_APP_PASSWORDS}/${name}`, { headers: twoFaHeaders })}init2Fa(): Observable<TwoFaSetup> {@@ -338,15 +340,19 @@ export class UserService {return this.http.post<TwoFaVerifyResult>(`${API_TWO_FA_ADMIN_RESET_USER}/${userId}`, null, { headers: twoFaHeaders })}- async auth2FaVerifyDialog(withPassword = false): Promise<false | HttpHeaders> {+ async auth2FaVerifyDialog(withPassword: true, passwordFallback?: boolean): Promise<false | HttpHeaders>+ async auth2FaVerifyDialog(withPassword: false, passwordFallback: true): Promise<false | HttpHeaders>+ async auth2FaVerifyDialog(withPassword?: false, passwordFallback?: false): Promise<Auth2FaVerifyDialogResult>+ async auth2FaVerifyDialog(withPassword = false, passwordFallback = false): Promise<Auth2FaVerifyDialogResult> {// returns: false (dialog closed), undefined (no check), `HttpHeaders` (code and/or password to check)const TwoFaEnabled = this.store.server().twoFaEnabled && this.user.twoFaEnabled- if (withPassword || TwoFaEnabled) {+ const requirePassword = withPassword || (passwordFallback && !TwoFaEnabled)+ if (requirePassword || TwoFaEnabled) {return new Promise((resolve) => {const modalRef: BsModalRef<UserAuth2FaVerifyDialogComponent> = this.layout.openDialog(UserAuth2FaVerifyDialogComponent,'xs',- { initialState: { withPassword: withPassword, withTwoFaEnabled: TwoFaEnabled } },+ { initialState: { withPassword: requirePassword, withTwoFaEnabled: TwoFaEnabled } },{ keyboard: false })modalRef.content.isValid = (result: false | HttpHeaders) => {