Skip to content

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

fix(backend:auth): validate current user state for active sessions

johaven10223551aef7
diff --git a/backend/src/applications/users/services/users-manager.service.spec.ts b/backend/src/applications/users/services/users-manager.service.spec.ts
index 758ba44a..b03952e6 100755
--- a/backend/src/applications/users/services/users-manager.service.spec.ts
+++ b/backend/src/applications/users/services/users-manager.service.spec.ts
@@ -17,7 +17,7 @@ import { fileName, isPathExists } from '../../files/utils/files'
import { NotificationsManager } from '../../notifications/services/notifications-manager.service'
import { GROUP_TYPE } from '../constants/group'
import { MEMBER_TYPE } from '../constants/member'
-import { USER_GROUP_ROLE, USER_MAX_PASSWORD_ATTEMPTS, USER_ROLE } from '../constants/user'
+import { USER_GROUP_ROLE, USER_MAX_PASSWORD_ATTEMPTS, USER_PERMISSION, USER_ROLE } from '../constants/user'
import { CreateUserDto } from '../dto/create-or-update-user.dto'
import { DeleteUserDto } from '../dto/delete-user.dto'
import { UserModel } from '../models/user.model'
@@ -150,6 +150,56 @@ describe(UsersManager.name, () => {
expect(me2.user.clientId).toBe('CID')
})
+ it('should resolve token users from current database state', async () => {
+ const authUser = new UserModel({
+ ...generateUserTest(),
+ id: 42,
+ role: USER_ROLE.ADMINISTRATOR,
+ applications: Object.values(USER_PERMISSION),
+ clientId: 'client-id',
+ exp: 1234
+ } as any)
+ const currentUser = {
+ ...generateUserTest(),
+ id: 42,
+ role: USER_ROLE.USER,
+ permissions: USER_PERMISSION.SPACES
+ }
+ usersQueriesService.from = vi.fn().mockResolvedValue(currentUser)
+
+ const resolved = await usersManager.fromAuthToken(authUser)
+
+ expect(resolved.role).toBe(USER_ROLE.USER)
+ expect(resolved.applications).toEqual([USER_PERMISSION.SPACES])
+ expect(resolved.clientId).toBe('client-id')
+ expect(resolved.exp).toBe(1234)
+
+ usersQueriesService.from = vi.fn().mockResolvedValue({ ...currentUser, isActive: false })
+ await expect(usersManager.fromAuthToken(authUser)).resolves.toBeNull()
+ })
+
+ it('should validate the source administrator before restoring impersonation', async () => {
+ const authUser = new UserModel({
+ ...generateUserTest(),
+ id: 42,
+ impersonatedFromId: 1,
+ impersonatedClientId: 'admin-client'
+ } as any)
+ const currentUser = { ...generateUserTest(), id: 42 }
+ const admin = { ...generateUserTest(), id: 1, role: USER_ROLE.ADMINISTRATOR }
+ usersQueriesService.from = vi.fn().mockImplementation(async (id: number) => (id === authUser.id ? currentUser : admin))
+
+ const resolved = await usersManager.fromAuthToken(authUser)
+
+ expect(resolved.impersonatedFromId).toBe(admin.id)
+ expect(resolved.impersonatedClientId).toBe('admin-client')
+
+ const formerAdmin = { ...generateUserTest(), id: 1, role: USER_ROLE.USER }
+ usersQueriesService.from = vi.fn().mockImplementation(async (id: number) => (id === authUser.id ? currentUser : formerAdmin))
+
+ await expect(usersManager.fromAuthToken(authUser)).resolves.toBeNull()
+ })
+
it('paths + avatars (default/generate) + create/delete user', async () => {
await expect(ensurePaths()).resolves.not.toThrow()
expect(await isPathExists(userTest.filesPath)).toBe(true)
diff --git a/backend/src/applications/users/services/users-manager.service.ts b/backend/src/applications/users/services/users-manager.service.ts
index c01e1164..d922d863 100755
--- a/backend/src/applications/users/services/users-manager.service.ts
+++ b/backend/src/applications/users/services/users-manager.service.ts
@@ -59,6 +59,24 @@ export class UsersManager {
return user ? new UserModel(user, true) : null
}
+ async fromAuthToken(authUser: UserModel): Promise<UserModel | null> {
+ const user = await this.fromUserId(authUser.id)
+ if (!user?.isActive || user.passwordAttempts >= USER_MAX_PASSWORD_ATTEMPTS) {
+ return null
+ }
+ if (authUser.impersonatedFromId) {
+ const impersonatingUser = await this.fromUserId(authUser.impersonatedFromId)
+ if (!impersonatingUser?.isActive || !impersonatingUser.isAdmin || impersonatingUser.passwordAttempts >= USER_MAX_PASSWORD_ATTEMPTS) {
+ return null
+ }
+ user.impersonatedFromId = authUser.impersonatedFromId
+ user.impersonatedClientId = authUser.impersonatedClientId
+ }
+ user.clientId = authUser.clientId
+ user.exp = authUser.exp
+ return user
+ }
+
async findUser(loginOrEmail: string, removePassword: false): Promise<UserModel>
async findUser(loginOrEmail: string, removePassword?: true): Promise<Omit<UserModel, 'password'>>
async findUser(loginOrEmail: string, removePassword: boolean = true): Promise<Omit<UserModel, 'password'>> {
diff --git a/backend/src/authentication/guards/auth-token-access.guard.spec.ts b/backend/src/authentication/guards/auth-token-access.guard.spec.ts
index 90d9bbe6..83f3f154 100644
--- a/backend/src/authentication/guards/auth-token-access.guard.spec.ts
+++ b/backend/src/authentication/guards/auth-token-access.guard.spec.ts
@@ -8,6 +8,7 @@ import { PassportModule } from '@nestjs/passport'
import { Test, TestingModule } from '@nestjs/testing'
import { PinoLogger } from 'nestjs-pino'
import crypto from 'node:crypto'
+import { UserModel } from '../../applications/users/models/user.model'
import { UsersManager } from '../../applications/users/services/users-manager.service'
import { WEB_DAV_CONTEXT, WebDAVContext } from '../../applications/webdav/decorators/webdav-context.decorator'
import { exportConfiguration } from '../../configuration/config.environment'
@@ -35,6 +36,9 @@ describe(AuthTokenAccessGuard.name, () => {
let accessToken: string
let temporaryTwoFaToken: string
let context: DeepMocked<ExecutionContext>
+ const usersManager = {
+ fromAuthToken: vi.fn(async (user: UserModel): Promise<UserModel | null> => user)
+ }
beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
@@ -51,7 +55,7 @@ describe(AuthTokenAccessGuard.name, () => {
AuthAnonymousStrategy,
AuthAnonymousGuard,
AuthManager,
- { provide: UsersManager, useValue: {} },
+ { provide: UsersManager, useValue: usersManager },
{
provide: PinoLogger,
useValue: {
@@ -121,6 +125,17 @@ describe(AuthTokenAccessGuard.name, () => {
expect(await authAccessGuard.canActivate(context)).toBe(true)
})
+ it('should reject a valid access token when the current user is unavailable', async () => {
+ usersManager.fromAuthToken.mockResolvedValueOnce(null)
+ context.switchToHttp().getRequest.mockReturnValue({
+ raw: { user: '' },
+ headers: {
+ authorization: `Bearer ${accessToken}`
+ }
+ })
+ await expect(authAccessGuard.canActivate(context)).rejects.toThrow('Unauthorized')
+ })
+
it('should throw an error with an invalid access token in cookies', async () => {
// Cookies test
context.switchToHttp().getRequest.mockReturnValue({
diff --git a/backend/src/authentication/guards/auth-token-access.strategy.ts b/backend/src/authentication/guards/auth-token-access.strategy.ts
index 34eb4827..62e497c5 100755
--- a/backend/src/authentication/guards/auth-token-access.strategy.ts
+++ b/backend/src/authentication/guards/auth-token-access.strategy.ts
@@ -4,6 +4,7 @@ import { FastifyRequest } from 'fastify'
import { PinoLogger } from 'nestjs-pino'
import { ExtractJwt, Strategy } from 'passport-jwt'
import { UserModel } from '../../applications/users/models/user.model'
+import { UsersManager } from '../../applications/users/services/users-manager.service'
import { configuration } from '../../configuration/config.environment'
import { AuthManager } from '../auth.service'
import { JwtPayload } from '../interfaces/jwt-payload.interface'
@@ -15,6 +16,7 @@ export class AuthTokenAccessStrategy extends PassportStrategy(Strategy, 'tokenAc
constructor(
private readonly authManager: AuthManager,
+ private readonly usersManager: UsersManager,
private readonly logger: PinoLogger
) {
super({
@@ -26,13 +28,17 @@ export class AuthTokenAccessStrategy extends PassportStrategy(Strategy, 'tokenAc
AuthTokenAccessStrategy.accessCookieName = configuration.auth.token.access.name
}
- validate(req: FastifyRequest, jwtPayload: JwtPayload): UserModel {
+ async validate(req: FastifyRequest, jwtPayload: JwtPayload): Promise<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)
+ const user = await this.usersManager.fromAuthToken(new UserModel(jwtPayload.identity))
+ if (!user) {
+ throw new UnauthorizedException()
+ }
+ return user
}
static extractJWTFromCookie(req: FastifyRequest): string | null {
diff --git a/backend/src/authentication/guards/auth-token-refresh.guard.spec.ts b/backend/src/authentication/guards/auth-token-refresh.guard.spec.ts
index 84677395..9a5d305a 100644
--- a/backend/src/authentication/guards/auth-token-refresh.guard.spec.ts
+++ b/backend/src/authentication/guards/auth-token-refresh.guard.spec.ts
@@ -7,6 +7,7 @@ import { PassportModule } from '@nestjs/passport'
import { Test, TestingModule } from '@nestjs/testing'
import { PinoLogger } from 'nestjs-pino'
import crypto from 'node:crypto'
+import { UserModel } from '../../applications/users/models/user.model'
import { UsersManager } from '../../applications/users/services/users-manager.service'
import { exportConfiguration } from '../../configuration/config.environment'
import { AuthConfig } from '../auth.config'
@@ -26,6 +27,9 @@ describe(AuthTokenRefreshGuard.name, () => {
let refreshTokenWithoutCSRF: string
let accessTokenSignedWithRefreshSecret: string
let context: DeepMocked<ExecutionContext>
+ const usersManager = {
+ fromAuthToken: vi.fn(async (user: UserModel): Promise<UserModel | null> => user)
+ }
beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
@@ -34,7 +38,7 @@ describe(AuthTokenRefreshGuard.name, () => {
AuthTokenRefreshGuard,
AuthTokenRefreshStrategy,
AuthManager,
- { provide: UsersManager, useValue: {} },
+ { provide: UsersManager, useValue: usersManager },
{
provide: PinoLogger,
useValue: {
@@ -99,6 +103,17 @@ describe(AuthTokenRefreshGuard.name, () => {
expect(await authRefreshGuard.canActivate(context)).toBe(true)
})
+ it('should reject a valid refresh token when the current user is unavailable', async () => {
+ usersManager.fromAuthToken.mockResolvedValueOnce(null)
+ context.switchToHttp().getRequest.mockReturnValue({
+ raw: { user: '' },
+ headers: {
+ authorization: `Bearer ${refreshToken}`
+ }
+ })
+ await expect(authRefreshGuard.canActivate(context)).rejects.toThrow('Unauthorized')
+ })
+
it('should throw an error with an invalid refresh token in cookies', 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.ts
index 80d1a1c5..687ebf8b 100755
--- a/backend/src/authentication/guards/auth-token-refresh.strategy.ts
+++ b/backend/src/authentication/guards/auth-token-refresh.strategy.ts
@@ -4,6 +4,7 @@ import { FastifyRequest } from 'fastify'
import { PinoLogger } from 'nestjs-pino'
import { ExtractJwt, Strategy } from 'passport-jwt'
import { UserModel } from '../../applications/users/models/user.model'
+import { UsersManager } from '../../applications/users/services/users-manager.service'
import { configuration } from '../../configuration/config.environment'
import { AuthManager } from '../auth.service'
import { JwtPayload } from '../interfaces/jwt-payload.interface'
@@ -15,6 +16,7 @@ export class AuthTokenRefreshStrategy extends PassportStrategy(Strategy, 'tokenR
constructor(
private readonly authManager: AuthManager,
+ private readonly usersManager: UsersManager,
private readonly logger: PinoLogger
) {
super({
@@ -26,14 +28,17 @@ export class AuthTokenRefreshStrategy extends PassportStrategy(Strategy, 'tokenR
AuthTokenRefreshStrategy.refreshCookieName = configuration.auth.token.refresh.name
}
- validate(req: FastifyRequest, jwtPayload: JwtPayload): UserModel {
+ async validate(req: FastifyRequest, jwtPayload: JwtPayload): Promise<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 cookies
- return new UserModel({ ...jwtPayload.identity, exp: jwtPayload.exp })
+ const user = await this.usersManager.fromAuthToken(new UserModel({ ...jwtPayload.identity, exp: jwtPayload.exp }))
+ if (!user) {
+ throw new UnauthorizedException()
+ }
+ return user
}
private static extractJWTFromCookie(req: FastifyRequest): string | null {
diff --git a/backend/src/infrastructure/websocket/adapters/web-socket.adapter.spec.ts b/backend/src/infrastructure/websocket/adapters/web-socket.adapter.spec.ts
index cabd1820..6881ffbc 100644
--- a/backend/src/infrastructure/websocket/adapters/web-socket.adapter.spec.ts
+++ b/backend/src/infrastructure/websocket/adapters/web-socket.adapter.spec.ts
@@ -1,5 +1,6 @@
import 'reflect-metadata'
import { Socket } from 'socket.io'
+import { UserModel } from '../../../applications/users/models/user.model'
import { TOKEN_TYPE } from '../../../authentication/interfaces/token.interface'
import { configuration } from '../../../configuration/config.environment'
import { WebSocketAdapter } from './web-socket.adapter'
@@ -9,6 +10,7 @@ describe(WebSocketAdapter.name, () => {
const identity = { id: 1, login: 'foo' }
let adapter: WebSocketAdapter
let jwtService: { verify: ReturnType<typeof vi.fn> }
+ let usersManager: { fromAuthToken: ReturnType<typeof vi.fn> }
let socket: Socket
let next: ReturnType<typeof vi.fn>
@@ -16,9 +18,13 @@ describe(WebSocketAdapter.name, () => {
jwtService = {
verify: vi.fn()
}
+ usersManager = {
+ fromAuthToken: vi.fn(async (user: UserModel): Promise<UserModel | null> => user)
+ }
adapter = Object.create(WebSocketAdapter.prototype)
Object.assign(adapter, {
jwtService,
+ usersManager,
logger: {
warn: vi.fn()
}
@@ -41,28 +47,29 @@ describe(WebSocketAdapter.name, () => {
next = vi.fn()
})
- it('should authenticate a socket with a WebSocket token', () => {
+ it('should authenticate a socket with a WebSocket token', async () => {
jwtService.verify.mockReturnValue({
tokenType: TOKEN_TYPE.WS,
identity
})
- Reflect.apply(Reflect.get(adapter, 'authenticateSocket'), adapter, [socket, next])
+ await 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(usersManager.fromAuthToken).toHaveBeenCalledOnce()
+ expect(socket).toHaveProperty('user')
expect(next).toHaveBeenCalledWith()
})
- it.each([TOKEN_TYPE.ACCESS, TOKEN_TYPE.REFRESH, undefined])('should reject a token with type %s', (tokenType) => {
+ it.each([TOKEN_TYPE.ACCESS, TOKEN_TYPE.REFRESH, undefined])('should reject a token with type %s', async (tokenType) => {
jwtService.verify.mockReturnValue({
tokenType,
identity
})
- Reflect.apply(Reflect.get(adapter, 'authenticateSocket'), adapter, [socket, next])
+ await Reflect.apply(Reflect.get(adapter, 'authenticateSocket'), adapter, [socket, next])
expect(socket).not.toHaveProperty('user')
expect(next).toHaveBeenCalledOnce()
@@ -70,4 +77,19 @@ describe(WebSocketAdapter.name, () => {
message: 'Unauthorized'
})
})
+
+ it('should reject a WebSocket token when the current user is unavailable', async () => {
+ jwtService.verify.mockReturnValue({
+ tokenType: TOKEN_TYPE.WS,
+ identity
+ })
+ usersManager.fromAuthToken.mockResolvedValue(null)
+
+ await Reflect.apply(Reflect.get(adapter, 'authenticateSocket'), adapter, [socket, next])
+
+ expect(socket).not.toHaveProperty('user')
+ 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.ts
index 81d3f372..e202af50 100644
--- a/backend/src/infrastructure/websocket/adapters/web-socket.adapter.ts
+++ b/backend/src/infrastructure/websocket/adapters/web-socket.adapter.ts
@@ -7,6 +7,8 @@ import { parse } from 'cookie'
import cluster from 'node:cluster'
import { Namespace, ServerOptions, Socket } from 'socket.io'
import { USERS_WS } from '../../../applications/users/constants/websocket'
+import { UserModel } from '../../../applications/users/models/user.model'
+import { UsersManager } from '../../../applications/users/services/users-manager.service'
import { type JwtPayload } from '../../../authentication/interfaces/jwt-payload.interface'
import { TOKEN_TYPE } from '../../../authentication/interfaces/token.interface'
import { configuration } from '../../../configuration/config.environment'
@@ -20,11 +22,13 @@ export class WebSocketAdapter extends IoAdapter {
private readonly app: NestFastifyApplication
private readonly logger: Logger = new Logger(WebSocketAdapter.name)
private readonly jwtService: JwtService
+ private readonly usersManager: UsersManager
constructor(app: NestFastifyApplication) {
super(app)
this.app = app
this.jwtService = app.get<JwtService>(JwtService)
+ this.usersManager = app.get<UsersManager>(UsersManager)
}
async initAdapter() {
@@ -70,7 +74,7 @@ export class WebSocketAdapter extends IoAdapter {
}
}
- private authenticateSocket(socket: Socket, next: (err?: Error) => void) {
+ private async authenticateSocket(socket: Socket, next: (err?: Error) => void) {
const cookies = socket.request.headers.cookie ? parse(socket.request.headers.cookie) : {}
const token = cookies[configuration.auth.token.ws.name]
if (!token) {
@@ -92,7 +96,18 @@ export class WebSocketAdapter extends IoAdapter {
this.onAuthError('Invalid token type', socket, next)
return
}
- Object.assign(socket, { user: payload.identity })
+ let user: UserModel
+ try {
+ user = await this.usersManager.fromAuthToken(new UserModel(payload.identity))
+ } catch (e) {
+ this.onAuthError(e.message, socket, next)
+ return
+ }
+ if (!user) {
+ this.onAuthError('User is unavailable', socket, next)
+ return
+ }
+ Object.assign(socket, { user })
next()
}