Skip to content

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

test(backend): complete unit tests for OIDC/LDAP/SYNC

johavena213078954e6
diff --git a/backend/src/applications/sync/services/sync-paths-manager.service.spec.ts b/backend/src/applications/sync/services/sync-paths-manager.service.spec.ts
index 623a0fdb..94b29732 100644
--- a/backend/src/applications/sync/services/sync-paths-manager.service.spec.ts
+++ b/backend/src/applications/sync/services/sync-paths-manager.service.spec.ts
@@ -460,18 +460,22 @@ describe(SyncPathsManager.name, () => {
it('should throw BAD_REQUEST for shares list selection', async () => {
await expect((service as any).getDBProps({ inSharesList: true } as any)).rejects.toMatchObject({
status: HttpStatus.BAD_REQUEST,
- message: 'Sync all shares is not supported, you must select a sub-directory'
+ message: 'Syncing all shares is not supported. Please select a subdirectory'
})
})
- it('should return ownerId only for personal space at root', async () => {
- const res = await (service as any).getDBProps({
- inSharesList: false,
- inPersonalSpace: true,
- paths: [],
- dbFile: { ownerId: 42 }
- } as any)
- expect(res).toEqual({ ownerId: 42 })
+ it('should throw BAD_REQUEST for personal space selection', async () => {
+ await expect(
+ (service as any).getDBProps({
+ inSharesList: false,
+ inPersonalSpace: true,
+ paths: [],
+ dbFile: { ownerId: 42 }
+ } as any)
+ ).rejects.toMatchObject({
+ status: HttpStatus.BAD_REQUEST,
+ message: 'Syncing all personal files is not supported. Please select a subdirectory'
+ })
})
it('should return ownerId and fileId for personal space subdir', async () => {
@@ -488,7 +492,7 @@ describe(SyncPathsManager.name, () => {
it('should throw BAD_REQUEST for whole files repository without alias', async () => {
await expect((service as any).getDBProps({ inFilesRepository: true, root: { alias: null }, paths: [] } as any)).rejects.toMatchObject({
status: HttpStatus.BAD_REQUEST,
- message: 'Sync all space is not yet supported, you must select a sub-directory'
+ message: 'Syncing the entire space is not yet supported. Please select a subdirectory'
})
})
diff --git a/backend/src/authentication/providers/ldap/auth-provider-ldap.service.spec.ts b/backend/src/authentication/providers/ldap/auth-provider-ldap.service.spec.ts
index 64ad037c..2d6e67da 100644
--- a/backend/src/authentication/providers/ldap/auth-provider-ldap.service.spec.ts
+++ b/backend/src/authentication/providers/ldap/auth-provider-ldap.service.spec.ts
@@ -8,15 +8,16 @@ import { Test, TestingModule } from '@nestjs/testing'
import { Mocked } from 'jest-mock'
import { Client, InvalidCredentialsError } from 'ldapts'
import { CONNECT_ERROR_CODE } from '../../../app.constants'
+import { USER_PERMISSION, USER_ROLE } from '../../../applications/users/constants/user'
import { UserModel } from '../../../applications/users/models/user.model'
import { AdminUsersManager } from '../../../applications/users/services/admin-users-manager.service'
import { UsersManager } from '../../../applications/users/services/users-manager.service'
import * as commonFunctions from '../../../common/functions'
import { configuration } from '../../../configuration/config.environment'
-import { LDAP_LOGIN_ATTR } from './auth-ldap.constants'
+import type { AuthMethodLDAPConfig } from './auth-ldap.config'
+import { LDAP_COMMON_ATTR, LDAP_LOGIN_ATTR } from './auth-ldap.constants'
import { AuthProviderLDAP } from './auth-provider-ldap.service'
-// Mock ldapts Client to simulate LDAP behaviors
jest.mock('ldapts', () => {
const actual = jest.requireActual('ldapts')
const mockClientInstance = {
@@ -25,68 +26,79 @@ jest.mock('ldapts', () => {
unbind: jest.fn()
}
const Client = jest.fn().mockImplementation(() => mockClientInstance)
- // Conserver tous les autres exports réels (dont EqualityFilter, AndFilter, InvalidCredentialsError, etc.)
return { ...actual, Client }
})
-// --- Test helpers (DRY) ---
-// Reusable LDAP mocks
-const mockBindResolve = (ldapClient: any) => {
- ldapClient.bind.mockResolvedValue(undefined)
- ldapClient.unbind.mockResolvedValue(undefined)
-}
-const mockBindRejectInvalid = (ldapClient: any, InvalidCredentialsErrorCtor: any, message = 'invalid') => {
- ldapClient.bind.mockRejectedValue(new InvalidCredentialsErrorCtor(message))
- ldapClient.unbind.mockResolvedValue(undefined)
-}
-const mockSearchEntries = (ldapClient: any, entries: any[]) => {
- ldapClient.search.mockResolvedValue({ searchEntries: entries })
-}
-const mockSearchReject = (ldapClient: any, err: Error) => {
- ldapClient.search.mockRejectedValue(err)
-}
-// User factory
const buildUser = (overrides: Partial<UserModel> = {}) =>
({
id: 0,
login: 'john',
password: 'hashed',
+ role: USER_ROLE.USER,
isGuest: false,
isActive: true,
+ isAdmin: false,
makePaths: jest.fn().mockResolvedValue(undefined),
- setFullName: jest.fn(), // needed when firstName/lastName change
+ setFullName: jest.fn(),
...overrides
}) as any
-// --------------------------
+const ldapClient = {
+ bind: jest.fn(),
+ search: jest.fn(),
+ unbind: jest.fn()
+}
+;(Client as Mocked<any>).mockImplementation(() => ldapClient)
describe(AuthProviderLDAP.name, () => {
let authMethodLdapService: AuthProviderLDAP
let usersManager: Mocked<UsersManager>
let adminUsersManager: Mocked<AdminUsersManager>
- const ldapClient = {
- bind: jest.fn(),
- search: jest.fn(),
- unbind: jest.fn()
- }
- ;(Client as Mocked<any>).mockImplementation(() => ldapClient)
- // Local helpers (need access to authMethodLdapService and ldapClient in this scope)
- const setupLdapSuccess = (entries: any[]) => {
- mockBindResolve(ldapClient)
- mockSearchEntries(ldapClient, entries)
+ type LdapConfigOverrides = Omit<Partial<AuthMethodLDAPConfig>, 'attributes' | 'options'> & {
+ attributes?: Partial<AuthMethodLDAPConfig['attributes']>
+ options?: Partial<AuthMethodLDAPConfig['options']>
}
- const spyLoggerError = () => jest.spyOn(authMethodLdapService['logger'], 'error').mockImplementation(() => undefined as any)
- beforeAll(async () => {
- configuration.auth.ldap = {
+ const setLdapConfig = (overrides: LdapConfigOverrides = {}) => {
+ const base: AuthMethodLDAPConfig = {
servers: ['ldap://localhost:389'],
- attributes: { login: LDAP_LOGIN_ATTR.UID, email: 'mail' },
+ attributes: { login: LDAP_LOGIN_ATTR.UID, email: LDAP_COMMON_ATTR.MAIL },
baseDN: 'ou=people,dc=example,dc=org',
- filter: ''
+ filter: '',
+ options: {
+ autoCreateUser: true,
+ autoCreatePermissions: [],
+ enablePasswordAuthFallback: true
+ }
+ }
+ const next: AuthMethodLDAPConfig = {
+ ...base,
+ ...overrides,
+ attributes: { ...base.attributes, ...(overrides.attributes || {}) },
+ options: { ...base.options, ...(overrides.options || {}) }
}
+ configuration.auth.ldap = next
+ ;(authMethodLdapService as any).ldapConfig = next
+ ;(authMethodLdapService as any).isAD = [LDAP_LOGIN_ATTR.SAM, LDAP_LOGIN_ATTR.UPN].includes(next.attributes.login)
+ }
+
+ const mockBindResolve = () => {
+ ldapClient.bind.mockResolvedValue(undefined)
+ ldapClient.unbind.mockResolvedValue(undefined)
+ }
+ const mockBindRejectInvalid = (message = 'invalid') => {
+ ldapClient.bind.mockRejectedValue(new InvalidCredentialsError(message))
+ ldapClient.unbind.mockResolvedValue(undefined)
+ }
+
+ const mockSearchEntries = (entries: any[]) => {
+ ldapClient.search.mockResolvedValue({ searchEntries: entries })
+ }
+
+ beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
AuthProviderLDAP,
@@ -116,6 +128,16 @@ describe(AuthProviderLDAP.name, () => {
usersManager = module.get<Mocked<UsersManager>>(UsersManager)
})
+ beforeEach(() => {
+ jest.clearAllMocks()
+ setLdapConfig()
+ usersManager.updateAccesses.mockResolvedValue(undefined)
+ })
+
+ afterEach(() => {
+ jest.restoreAllMocks()
+ })
+
it('should be defined', () => {
expect(authMethodLdapService).toBeDefined()
expect(usersManager).toBeDefined()
@@ -124,270 +146,260 @@ describe(AuthProviderLDAP.name, () => {
})
it('should authenticate a guest user via database and bypass LDAP', async () => {
- // Arrange
const guestUser: any = { id: 1, login: 'guest1', isGuest: true, isActive: true }
usersManager.findUser.mockResolvedValue(guestUser)
const dbAuthResult: any = { ...guestUser, token: 'jwt' }
usersManager.logUser.mockResolvedValue(dbAuthResult)
+
const res = await authMethodLdapService.validateUser('guest1', 'pass', '127.0.0.1')
+
expect(res).toEqual(dbAuthResult)
- expect(usersManager.logUser).toHaveBeenCalledWith(guestUser, 'pass', '127.0.0.1')
- expect(Client).not.toHaveBeenCalled() // client should not be constructed
+ expect(usersManager.logUser).toHaveBeenCalledWith(guestUser, 'pass', '127.0.0.1', undefined)
+ expect(Client).not.toHaveBeenCalled()
+ })
+
+ it('should bypass LDAP when scope is provided', async () => {
+ const user = buildUser({ id: 12 })
+ usersManager.findUser.mockResolvedValue(user)
+ usersManager.logUser.mockResolvedValue(user)
+
+ const res = await authMethodLdapService.validateUser('john', 'app-password', '10.0.0.2', 'webdav' as any)
+
+ expect(res).toBe(user)
+ expect(usersManager.logUser).toHaveBeenCalledWith(user, 'app-password', '10.0.0.2', 'webdav')
+ expect(Client).not.toHaveBeenCalled()
})
- it('should throw FORBIDDEN for locked account and resolve null for LDAP login mismatch', async () => {
- // Phase 1: locked account
+ it('should throw FORBIDDEN for locked account', async () => {
usersManager.findUser.mockResolvedValue({ login: 'john', isGuest: false, isActive: false } as UserModel)
- const loggerErrorSpy1 = jest.spyOn(authMethodLdapService['logger'], 'error').mockImplementation(() => undefined as any)
+ const loggerErrorSpy = jest.spyOn(authMethodLdapService['logger'], 'error').mockImplementation(() => undefined as any)
+
await expect(authMethodLdapService.validateUser('john', 'pwd')).rejects.toThrow(/account locked/i)
- expect(loggerErrorSpy1).toHaveBeenCalled()
+ expect(loggerErrorSpy).toHaveBeenCalled()
+ })
- // Phase 2: mismatch between requested login and LDAP returned login -> service renvoie null
- const existingUser: any = buildUser({ id: 8 })
+ it('should return null on invalid LDAP credentials without fallback', async () => {
+ const existingUser: any = buildUser({ id: 1 })
usersManager.findUser.mockResolvedValue(existingUser)
- mockBindResolve(ldapClient)
- mockSearchEntries(ldapClient, [{ uid: 'jane', cn: 'john', mail: '[email protected]' }])
- await expect(authMethodLdapService.validateUser('john', 'pwd')).rejects.toThrow(/account matching error/i)
+ mockBindRejectInvalid('invalid credentials')
+
+ const res = await authMethodLdapService.validateUser('john', 'badpwd', '10.0.0.1')
+
+ expect(res).toBeNull()
+ expect(usersManager.logUser).not.toHaveBeenCalled()
+ expect(usersManager.updateAccesses).not.toHaveBeenCalled()
})
- it('should handle invalid LDAP credentials for both existing and unknown users', async () => {
- // Phase 1: existing user -> updateAccesses invoked with success=false and logger.error intercepted
- const existingUser: any = buildUser({ id: 1 })
+ it('should return null when LDAP search yields no entries or throws', async () => {
+ const existingUser: any = buildUser({ id: 10 })
usersManager.findUser.mockResolvedValue(existingUser)
- // Make LDAP bind throw InvalidCredentialsError
- mockBindRejectInvalid(ldapClient, InvalidCredentialsError, 'invalid credentials')
- // Force updateAccesses to reject to hit the catch and logger.error
- const loggerErrorSpy = jest.spyOn(authMethodLdapService['logger'], 'error').mockImplementation(() => undefined as any)
- usersManager.updateAccesses.mockRejectedValueOnce(new Error('updateAccesses boom'))
- const res1 = await authMethodLdapService.validateUser('john', 'badpwd', '10.0.0.1')
- expect(res1).toBeNull()
- expect(usersManager.updateAccesses).toHaveBeenCalledWith(existingUser, '10.0.0.1', false)
- expect(loggerErrorSpy).toHaveBeenCalled()
+ mockBindResolve()
+ mockSearchEntries([])
- // Phase 2: unknown user → no access update
- usersManager.updateAccesses.mockClear()
- usersManager.findUser.mockResolvedValue(null)
- ldapClient.bind.mockRejectedValue(new InvalidCredentialsError('invalid'))
- ldapClient.unbind.mockResolvedValue(undefined)
- const res2 = await authMethodLdapService.validateUser('jane', 'badpwd')
- expect(res2).toBeNull()
+ const resA = await authMethodLdapService.validateUser('john', 'pwd')
+
+ expect(resA).toBeNull()
+
+ ldapClient.search.mockRejectedValue(new Error('search failed'))
+ const resB = await authMethodLdapService.validateUser('john', 'pwd')
+
+ expect(resB).toBeNull()
expect(usersManager.updateAccesses).not.toHaveBeenCalled()
})
- it('should handle LDAP new-user flow: missing fields, creation success, and multi-email selection', async () => {
- // Phase 1: incomplete LDAP entry -> null + error log, no creation
+ it('should fallback to local auth when LDAP is unavailable and fallback is enabled', async () => {
+ const existingUser: any = buildUser({ id: 2 })
+ usersManager.findUser.mockResolvedValue(existingUser)
+ usersManager.logUser.mockResolvedValue(existingUser)
+ const err = Object.assign(new Error('connect ECONNREFUSED'), { code: Array.from(CONNECT_ERROR_CODE)[0] })
+ ldapClient.bind.mockRejectedValue({ errors: [err] })
+ ldapClient.unbind.mockResolvedValue(undefined)
+
+ const res = await authMethodLdapService.validateUser('john', 'pwd', '10.0.0.3')
+
+ expect(res).toBe(existingUser)
+ expect(usersManager.logUser).toHaveBeenCalledWith(existingUser, 'pwd', '10.0.0.3')
+ })
+
+ it('should throw SERVICE_UNAVAILABLE when LDAP is unavailable and fallback is disabled', async () => {
+ setLdapConfig({ options: { enablePasswordAuthFallback: false } })
+ const existingUser: any = buildUser({ id: 3 })
+ usersManager.findUser.mockResolvedValue(existingUser)
+ const err = Object.assign(new Error('connect ECONNREFUSED'), { code: Array.from(CONNECT_ERROR_CODE)[0] })
+ ldapClient.bind.mockRejectedValue({ errors: [err] })
+ ldapClient.unbind.mockResolvedValue(undefined)
+
+ await expect(authMethodLdapService.validateUser('john', 'pwd')).rejects.toThrow(/authentication service error/i)
+ })
+
+ it('should allow admin local fallback when LDAP is unavailable even if fallback is disabled', async () => {
+ setLdapConfig({ options: { enablePasswordAuthFallback: false } })
+ const existingUser: any = buildUser({ id: 4, isAdmin: true })
+ usersManager.findUser.mockResolvedValue(existingUser)
+ usersManager.logUser.mockResolvedValue(existingUser)
+ const err = Object.assign(new Error('connect ECONNREFUSED'), { code: Array.from(CONNECT_ERROR_CODE)[0] })
+ ldapClient.bind.mockRejectedValue({ errors: [err] })
+ ldapClient.unbind.mockResolvedValue(undefined)
+
+ const res = await authMethodLdapService.validateUser('john', 'pwd')
+
+ expect(res).toBe(existingUser)
+ expect(usersManager.logUser).toHaveBeenCalledWith(existingUser, 'pwd', undefined)
+ })
+
+ it('should return null when LDAP entry lacks required fields', async () => {
usersManager.findUser.mockResolvedValue(null)
- mockBindResolve(ldapClient)
- // Simulate an entry with missing mail
- mockSearchEntries(ldapClient, [{ uid: 'jane', cn: 'Jane Doe', mail: undefined }])
+ mockBindResolve()
+ mockSearchEntries([{ uid: 'jane', cn: 'Jane Doe', mail: undefined }])
const loggerErrorSpy = jest.spyOn(authMethodLdapService['logger'], 'error').mockImplementation(() => undefined as any)
- const resA = await authMethodLdapService.validateUser('jane', 'pwd')
- expect(resA).toBeNull()
+
+ const res = await authMethodLdapService.validateUser('jane', 'pwd')
+
+ expect(res).toBeNull()
expect(adminUsersManager.createUserOrGuest).not.toHaveBeenCalled()
expect(loggerErrorSpy).toHaveBeenCalled()
+ })
+
+ it('should throw UNAUTHORIZED when autoCreateUser is disabled', async () => {
+ setLdapConfig({ options: { autoCreateUser: false } })
+ usersManager.findUser.mockResolvedValue(null)
+ const checkAuthSpy = jest.spyOn<any, any>(authMethodLdapService as any, 'checkAuth').mockResolvedValue({
+ uid: 'john',
+ })
+
+ await expect(authMethodLdapService.validateUser('john', 'pwd')).rejects.toThrow(/user not found/i)
+ checkAuthSpy.mockRestore()
+ })
- // Phase 2: create a new user (success, single email)
- // Stub directement checkAuth pour retourner une entrée LDAP valide
- const checkAuthSpy = jest.spyOn<any, any>(authMethodLdapService as any, 'checkAuth')
- checkAuthSpy.mockResolvedValueOnce({ uid: 'john', cn: 'John Doe', mail: '[email protected]' } as any)
- adminUsersManager.createUserOrGuest.mockClear()
+ it('should create a new admin user with permissions and name parsed from LDAP', async () => {
+ setLdapConfig({
+ options: {
+ adminGroup: 'Admins',
+ autoCreatePermissions: [USER_PERMISSION.PERSONAL_SPACE, USER_PERMISSION.WEBDAV]
+ }
+ })
usersManager.findUser.mockResolvedValue(null)
+ mockBindResolve()
+ mockSearchEntries([
+ {
+ uid: 'john',
+ givenName: 'John',
+ sn: 'Doe',
+ memberOf: ['CN=Admins,OU=Groups,DC=example,DC=org']
+ }
+ ])
const createdUser: any = { id: 2, login: 'john', isGuest: false, isActive: true, makePaths: jest.fn() }
adminUsersManager.createUserOrGuest.mockResolvedValue(createdUser)
- // If the service reloads the user via fromUserId after creation
usersManager.fromUserId.mockResolvedValue(createdUser)
- // Cover the success-flow catch branch
- const loggerErrorSpy2 = spyLoggerError()
- usersManager.updateAccesses.mockRejectedValueOnce(new Error('updateAccesses success flow boom'))
- const resB = await authMethodLdapService.validateUser('john', 'pwd', '192.168.1.10')
+
+ const res = await authMethodLdapService.validateUser('john', 'pwd', '192.168.1.10')
+
expect(adminUsersManager.createUserOrGuest).toHaveBeenCalledWith(
- { login: 'john', email: '[email protected]', password: 'pwd', firstName: 'John', lastName: 'Doe', role: 1 },
- expect.anything() // USER_ROLE.USER
+ {
+ login: 'john',
+ email: '[email protected]',
+ password: 'pwd',
+ role: USER_ROLE.ADMINISTRATOR,
+ firstName: 'John',
+ lastName: 'Doe',
+ permissions: 'personal_space,webdav_access'
+ },
+ USER_ROLE.ADMINISTRATOR
)
- expect(resB).toBe(createdUser)
+ expect(res).toBe(createdUser)
expect(usersManager.updateAccesses).toHaveBeenCalledWith(createdUser, '192.168.1.10', true)
- expect(loggerErrorSpy2).toHaveBeenCalled()
- // Phase 3: multiple emails -> keep the first
- adminUsersManager.createUserOrGuest.mockClear()
- usersManager.findUser.mockResolvedValue(null)
- setupLdapSuccess([{ uid: 'multi', cn: 'Multi Mail', mail: ['[email protected]', '[email protected]'] }])
- const createdUser2: any = { id: 9, login: 'multi', makePaths: jest.fn() }
- adminUsersManager.createUserOrGuest.mockResolvedValue(createdUser2)
- usersManager.fromUserId.mockResolvedValue(createdUser2)
- const resC = await authMethodLdapService.validateUser('multi', 'pwd')
- expect(adminUsersManager.createUserOrGuest).toHaveBeenCalledWith(expect.objectContaining({ email: '[email protected]' }), expect.anything())
- expect(resC).toBe(createdUser2)
})
- it('should update existing user profile when LDAP identity changed (except password assigned back)', async () => {
- // Arrange: existing user with different profile and an old password
- const existingUser: any = buildUser({ id: 5 })
+ it('should keep admin role when adminGroup is not configured', async () => {
+ setLdapConfig({ options: { adminGroup: undefined } })
+ const existingUser: any = buildUser({ id: 5, role: USER_ROLE.ADMINISTRATOR })
+ usersManager.findUser.mockResolvedValue(existingUser)
+ mockBindResolve()
+ mockSearchEntries([{ uid: 'john', cn: 'John Doe', mail: '[email protected]' }])
+ jest.spyOn(commonFunctions, 'comparePassword').mockResolvedValue(true)
+
+ await authMethodLdapService.validateUser('john', 'pwd')
+
+ expect(adminUsersManager.updateUserOrGuest).toHaveBeenCalled()
+ const updateArgs = adminUsersManager.updateUserOrGuest.mock.calls[0][1]
+ expect(updateArgs).toEqual(expect.objectContaining({ email: '[email protected]' }))
+ expect(updateArgs).toEqual(expect.not.objectContaining({ role: expect.anything() }))
+ })
+
+ it('should update existing user and avoid reassigning password locally', async () => {
+ const existingUser: any = buildUser({ id: 6 })
usersManager.findUser.mockResolvedValue(existingUser)
- // LDAP succeeds and returns different email and same uid
- setupLdapSuccess([{ uid: 'john', cn: 'John Doe', mail: '[email protected]' }])
- // Admin manager successfully updates a user
- adminUsersManager.updateUserOrGuest.mockResolvedValue(undefined)
- // Ensure password is considered changed so the update payload includes it,
- // which then triggers the deletion and local assignment branches after update
+ mockBindResolve()
+ mockSearchEntries([{ uid: 'john', displayName: 'Jane Doe', mail: '[email protected]' }])
const compareSpy = jest.spyOn(commonFunctions, 'comparePassword').mockResolvedValue(false)
+ const splitSpy = jest.spyOn(commonFunctions, 'splitFullName').mockReturnValue({ firstName: 'Jane', lastName: 'Doe' })
+
const res = await authMethodLdapService.validateUser('john', 'new-plain-password', '127.0.0.2')
+
expect(adminUsersManager.updateUserOrGuest).toHaveBeenCalledWith(
- 5,
+ 6,
expect.objectContaining({
- firstName: 'John',
+ firstName: 'Jane',
lastName: 'Doe'
})
)
- // Password should not be assigned back onto the user object (it is deleted before Object.assign)
expect(existingUser.password).toBe('hashed')
- // Other fields should be updated locally
- expect(existingUser.email).toBe('[email protected]')
- expect(existingUser).toMatchObject({ firstName: 'John', lastName: 'Doe' })
- // Accesses updated as success
+ expect(existingUser).toMatchObject({ email: '[email protected]', firstName: 'Jane', lastName: 'Doe' })
+ expect(existingUser.setFullName).toHaveBeenCalledWith(true)
expect(usersManager.updateAccesses).toHaveBeenCalledWith(existingUser, '127.0.0.2', true)
- // Returned user is the same instance
expect(res).toBe(existingUser)
- // Second run: password unchanged (comparePassword => true) to cover the null branch for password
- adminUsersManager.updateUserOrGuest.mockClear()
- usersManager.updateAccesses.mockClear()
- // Force another non-password change so an update occurs
- existingUser.email = '[email protected]'
- compareSpy.mockResolvedValue(true)
- const res2 = await authMethodLdapService.validateUser('john', 'same-plain-password', '127.0.0.3')
- // Update should be called without password, only with changed fields
- expect(adminUsersManager.updateUserOrGuest).toHaveBeenCalled()
- const updateArgs = adminUsersManager.updateUserOrGuest.mock.calls[0]
- expect(updateArgs[0]).toBe(5)
- expect(updateArgs[1]).toEqual(
- expect.objectContaining({
- })
- )
- expect(updateArgs[1]).toEqual(expect.not.objectContaining({ password: expect.anything() }))
- // Password remains unchanged locally
- expect(existingUser.password).toBe('hashed')
- // Accesses updated as success
- expect(usersManager.updateAccesses).toHaveBeenCalledWith(existingUser, '127.0.0.3', true)
- // Returned user is the same instance
- expect(res2).toBe(existingUser)
- // Third run: no changes at all (identityHasChanged is empty) to cover the else branch
- adminUsersManager.updateUserOrGuest.mockClear()
- usersManager.updateAccesses.mockClear()
- compareSpy.mockResolvedValue(true)
- // Local user already matches LDAP identity; call again
- const res3 = await authMethodLdapService.validateUser('john', 'same-plain-password', '127.0.0.4')
- // No update should be triggered
- expect(adminUsersManager.updateUserOrGuest).not.toHaveBeenCalled()
- // Access should still be updated as success
- expect(usersManager.updateAccesses).toHaveBeenCalledWith(existingUser, '127.0.0.4', true)
- // Returned user is the same instance
- expect(res3).toBe(existingUser)
+ compareSpy.mockRestore()
+ splitSpy.mockRestore()
})
- it('should log failed access when LDAP search returns no entry or throws after bind', async () => {
- // Phase 1: no entry found after a successful bind -> failed access
- const existingUser: any = { id: 7, login: 'ghost', isGuest: false, isActive: true }
+ it('should throw FORBIDDEN when LDAP login does not match user login', async () => {
+ const existingUser: any = buildUser({ id: 7, login: 'john' })
usersManager.findUser.mockResolvedValue(existingUser)
- setupLdapSuccess([])
- const resA = await authMethodLdapService.validateUser('ghost', 'pwd', '10.10.0.1')
- expect(resA).toBeNull()
- expect(usersManager.updateAccesses).toHaveBeenCalledWith(existingUser, '10.10.0.1', false)
+ mockBindResolve()
+ mockSearchEntries([{ uid: 'jane', cn: 'Jane Doe', mail: '[email protected]' }])
- // Phase 2: exception during search after a bind -> failed access
- jest.clearAllMocks()
- const existingUser2: any = { id: 10, login: 'john', isGuest: false, isActive: true }
- usersManager.findUser.mockResolvedValue(existingUser2)
- mockBindResolve(ldapClient)
- mockSearchReject(ldapClient, new Error('search failed'))
- const resB = await authMethodLdapService.validateUser('john', 'pwd', '1.1.1.1')
- expect(resB).toBeNull()
- expect(usersManager.updateAccesses).toHaveBeenCalledWith(existingUser2, '1.1.1.1', false)
+ await expect(authMethodLdapService.validateUser('john', 'pwd')).rejects.toThrow(/account matching error/i)
})
- it('should allow app password when LDAP fails and scope is provided', async () => {
- const existingUser: any = buildUser({ id: 42 })
- usersManager.findUser.mockResolvedValue(existingUser)
- // LDAP invalid credentials
- mockBindRejectInvalid(ldapClient, InvalidCredentialsError, 'invalid credentials')
- // App password success
- usersManager.validateAppPassword.mockResolvedValue(true)
- const res = await authMethodLdapService.validateUser('john', 'app-password', '10.0.0.2', 'webdav' as any)
- expect(res).toBe(existingUser)
- expect(usersManager.validateAppPassword).toHaveBeenCalledWith(existingUser, 'app-password', '10.0.0.2', 'webdav')
- expect(usersManager.updateAccesses).toHaveBeenCalledWith(existingUser, '10.0.0.2', true)
+ it('should build LDAP logins and filters for AD and standard LDAP', () => {
+ setLdapConfig({ attributes: { login: LDAP_LOGIN_ATTR.UPN }, upnSuffix: 'sync-in.com', filter: '(memberOf=cn=staff)' })
+ const adLogin = (authMethodLdapService as any).buildLdapLogin('john')
+ expect(adLogin).toBe('[email protected]')
+ const adFilter = (authMethodLdapService as any).buildUserFilter('SYNC-IN\\john', '(memberOf=cn=staff)')
+ expect(adFilter).toContain('(sAMAccountName=john)')
+ expect(adFilter).toContain('(userPrincipalName=john)')
+ expect(adFilter).toContain('(mail=john)')
+ expect(adFilter).toContain('(memberOf=cn=staff)')
+
+ setLdapConfig({ attributes: { login: LDAP_LOGIN_ATTR.UID }, filter: '(department=IT)' })
+ const ldapFilter = (authMethodLdapService as any).buildUserFilter('john', '(department=IT)')
+ expect(ldapFilter).toContain('(uid=john)')
+ expect(ldapFilter).toContain('(cn=john)')
+ expect(ldapFilter).toContain('(mail=john)')
+ expect(ldapFilter).toContain('(department=IT)')
})
- it('should throw 500 when LDAP connection error occurs during bind', async () => {
- // Arrange: no existing user to reach checkAuth flow
- usersManager.findUser.mockResolvedValue(null)
- const err1 = new Error('socket hang up')
- const err2 = Object.assign(new Error('connect ECONNREFUSED'), { code: Array.from(CONNECT_ERROR_CODE)[0] })
- ldapClient.bind.mockRejectedValue({ errors: [err1, err2] })
- ldapClient.unbind.mockResolvedValue(undefined)
-
- // First scenario: recognized connection error -> throws 500
- await expect(authMethodLdapService.validateUser('john', 'pwd')).rejects.toThrow(/authentication service/i)
-
- // Second scenario: generic error (no code, not InvalidCredentialsError) -> resolves to null and no access update
- ldapClient.bind.mockReset()
- ldapClient.unbind.mockReset()
- usersManager.updateAccesses.mockClear()
- usersManager.findUser.mockResolvedValue(null as any)
- ldapClient.bind.mockRejectedValue(new Error('unexpected failure'))
- ldapClient.unbind.mockResolvedValue(undefined)
+ it('should normalize LDAP entries for memberOf and array attributes', () => {
+ const entry = {
+ uid: ['john'],
+ memberOf: ['CN=Admins,OU=Groups,DC=example,DC=org', 'CN=Staff,OU=Groups,DC=example,DC=org']
+ }
- const res = await authMethodLdapService.validateUser('john', 'pwd')
- expect(res).toBeNull()
- expect(usersManager.updateAccesses).not.toHaveBeenCalled()
- })
+ const normalized = (authMethodLdapService as any).convertToLdapUserEntry(entry)
- it('should log update failure when updating existing user', async () => {
- // Arrange: existing user with changed identity
- const existingUser: any = buildUser({ id: 11, email: '[email protected]' })
- usersManager.findUser.mockResolvedValue(existingUser)
- // Ensure LDAP loginAttribute matches uid for this test (a previous test sets it to 'cn')
- setupLdapSuccess([{ uid: 'john', cn: 'John Doe', mail: '[email protected]' }])
- adminUsersManager.updateUserOrGuest.mockRejectedValue(new Error('db error'))
- // Force identity to be considered changed only for this test
- jest.spyOn(commonFunctions, 'comparePassword').mockResolvedValue(false)
- jest.spyOn(commonFunctions, 'splitFullName').mockReturnValue({ firstName: 'John', lastName: 'Doe' })
- const res = await authMethodLdapService.validateUser('john', 'pwd')
- expect(adminUsersManager.updateUserOrGuest).toHaveBeenCalled()
- // Local fields unchanged since update failed
- expect(existingUser.email).toBe('[email protected]')
- expect(res).toBe(existingUser)
+ expect(normalized.uid).toBe('john')
+ expect(normalized.mail).toBe('[email protected]')
+ expect(normalized.memberOf).toEqual(['Admins', 'Staff'])
})
- it('should skip non-matching LDAP entries then update user with changed password without reassigning it', async () => {
- // Phase A: LDAP returns an entry but loginAttribute value does not match -> checkAccess returns false (covers return after loop)
- const userA: any = { id: 20, login: 'john', isGuest: false, isActive: true }
- usersManager.findUser.mockResolvedValue(userA)
- ldapClient.bind.mockResolvedValue(undefined)
-
- // Phase B: Matching entry + password considered changed -> updateUserOrGuest called, password not reassigned locally
- jest.clearAllMocks()
- const userB: any = buildUser({ id: 21, email: '[email protected]' })
- usersManager.findUser.mockResolvedValue(userB)
- setupLdapSuccess([{ uid: 'john', cn: 'John Doe', mail: '[email protected]' }])
- adminUsersManager.updateUserOrGuest.mockResolvedValue(undefined)
-
- // Force password to be considered changed to execute deletion + Object.assign branch
- jest.spyOn(commonFunctions, 'comparePassword').mockResolvedValue(false)
- jest.spyOn(commonFunctions, 'splitFullName').mockReturnValue({ firstName: 'John', lastName: 'Doe' })
- const resB = await authMethodLdapService.validateUser('john', 'newpwd', '4.4.4.4')
-
- // Line 132: updateUserOrGuest call
- expect(adminUsersManager.updateUserOrGuest).toHaveBeenCalledWith(
- 21,
- expect.objectContaining({ email: '[email protected]', firstName: 'John', lastName: 'Doe' })
- )
-
- // Lines 139-142: password removed from local assign, other fields assigned
- expect(userB.password).toBe('hashed')
- expect(userB.email).toBe('[email protected]')
- expect(userB).toMatchObject({ firstName: 'John', lastName: 'Doe' })
- expect(resB).toBe(userB)
+ it('should build LDAP logins for SAM account name when netbiosName is set', () => {
+ setLdapConfig({ attributes: { login: LDAP_LOGIN_ATTR.SAM }, netbiosName: 'SYNC' })
+ const samLogin = (authMethodLdapService as any).buildLdapLogin('john')
+ expect(samLogin).toBe('SYNC\\john')
})
})
diff --git a/backend/src/authentication/providers/oidc/auth-provider-oidc.service.spec.ts b/backend/src/authentication/providers/oidc/auth-provider-oidc.service.spec.ts
new file mode 100644
index 00000000..78eee58b
--- /dev/null
+++ b/backend/src/authentication/providers/oidc/auth-provider-oidc.service.spec.ts
@@ -0,0 +1,252 @@
+/*
+ * Copyright (C) 2012-2026 Johan Legrand <[email protected]>
+ * This file is part of Sync-in | The open source file sync and share solution
+ * See the LICENSE file for licensing details
+ */
+
+import { HttpStatus } from '@nestjs/common'
+import { Test, TestingModule } from '@nestjs/testing'
+import {
+ authorizationCodeGrant,
+ AuthorizationResponseError,
+ calculatePKCECodeChallenge,
+ fetchUserInfo,
+ randomNonce,
+ randomPKCECodeVerifier,
+ randomState
+} from 'openid-client'
+import { USER_ROLE } from '../../../applications/users/constants/user'
+import { AdminUsersManager } from '../../../applications/users/services/admin-users-manager.service'
+import { UsersManager } from '../../../applications/users/services/users-manager.service'
+import { OAuthCookie } from './auth-oidc.constants'
+import { AuthProviderOIDC } from './auth-provider-oidc.service'
+
+jest.mock('../../../configuration/config.environment', () => ({
+ configuration: {
+ auth: {
+ oidc: {
+ issuerUrl: 'https://issuer.example.test',
+ clientId: 'client-id',
+ clientSecret: 'client-secret',
+ redirectUri: 'https://api.example.test/auth/oidc/callback',
+ security: {
+ scope: 'openid profile email',
+ tokenSigningAlg: 'RS256',
+ userInfoSigningAlg: 'RS256',
+ tokenEndpointAuthMethod: 'client_secret_basic',
+ skipSubjectCheck: false
+ },
+ options: {
+ enablePasswordAuth: false,
+ autoCreateUser: true,
+ adminRoleOrGroup: 'admins',
+ autoCreatePermissions: ['read']
+ }
+ }
+ }
+ }
+}))
+
+jest.mock('openid-client', () => {
+ class AuthorizationResponseError extends Error {
+ code: string
+ error_description: string
+ constructor(message: string, options: { cause: URLSearchParams }) {
+ super(message)
+ this.code = 'authorization_response_error'
+ this.error_description = options?.cause?.get('error_description') ?? message
+ }
+ }
+
+ return {
+ allowInsecureRequests: jest.fn(),
+ authorizationCodeGrant: jest.fn(),
+ AuthorizationResponseError,
+ calculatePKCECodeChallenge: jest.fn(),
+ ClientSecretBasic: jest.fn(),
+ ClientSecretPost: jest.fn(),
+ Configuration: class {},
+ discovery: jest.fn(),
+ fetchUserInfo: jest.fn(),
+ IDToken: class {},
+ None: jest.fn(),
+ randomNonce: jest.fn(),
+ randomPKCECodeVerifier: jest.fn(),
+ randomState: jest.fn(),
+ skipSubjectCheck: Symbol('skipSubjectCheck'),
+ UserInfoResponse: class {}
+ }
+})
+
+describe(AuthProviderOIDC.name, () => {
+ let service: AuthProviderOIDC
+ let usersManager: {
+ findUser: jest.Mock
+ logUser: jest.Mock
+ updateAccesses: jest.Mock
+ fromUserId: jest.Mock
+ }
+ let adminUsersManager: {
+ createUserOrGuest: jest.Mock
+ updateUserOrGuest: jest.Mock
+ }
+
+ const makeConfig = (supportsPKCE = true) => ({
+ serverMetadata: () => ({
+ supportsPKCE: () => supportsPKCE,
+ authorization_endpoint: 'https://issuer.example.test/authorize'
+ })
+ })
+
+ const makeReply = () => ({
+ header: jest.fn().mockReturnThis(),
+ setCookie: jest.fn(),
+ clearCookie: jest.fn()
+ })
+
+ beforeAll(async () => {
+ usersManager = {
+ findUser: jest.fn(),
+ logUser: jest.fn(),
+ updateAccesses: jest.fn().mockResolvedValue(undefined),
+ fromUserId: jest.fn()
+ }
+ adminUsersManager = {
+ createUserOrGuest: jest.fn(),
+ updateUserOrGuest: jest.fn()
+ }
+
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [{ provide: UsersManager, useValue: usersManager }, { provide: AdminUsersManager, useValue: adminUsersManager }, AuthProviderOIDC]
+ }).compile()
+
+ module.useLogger(['fatal'])
+ service = module.get<AuthProviderOIDC>(AuthProviderOIDC)
+ })
+
+ beforeEach(() => {
+ jest.restoreAllMocks()
+ jest.clearAllMocks()
+ })
+
+ it('returns null when user is not found', async () => {
+ usersManager.findUser.mockResolvedValue(null)
+
+ const result = await service.validateUser('john', 'secret')
+
+ expect(result).toBeNull()
+ expect(usersManager.findUser).toHaveBeenCalledWith('john', false)
+ expect(usersManager.logUser).not.toHaveBeenCalled()
+ })
+
+ it('allows local password auth for guest users', async () => {
+ const guestUser = { id: 1, isGuest: true, isAdmin: false } as any
+ usersManager.findUser.mockResolvedValue(guestUser)
+ usersManager.logUser.mockResolvedValue(guestUser)
+
+ const result = await service.validateUser('guest', 'secret')
+
+ expect(usersManager.logUser).toHaveBeenCalledWith(guestUser, 'secret', undefined, undefined)
+ expect(result).toBe(guestUser)
+ })
+
+ it('builds the authorization url with PKCE data and cookies', async () => {
+ jest.spyOn(service, 'getConfig').mockResolvedValue(makeConfig(true) as any)
+ ;(randomState as jest.Mock).mockReturnValue('state-1')
+ ;(randomNonce as jest.Mock).mockReturnValue('nonce-1')
+ ;(randomPKCECodeVerifier as jest.Mock).mockReturnValue('verifier-1')
+ ;(calculatePKCECodeChallenge as jest.Mock).mockResolvedValue('challenge-1')
+ const reply = makeReply()
+
+ const authUrl = await service.getAuthorizationUrl(reply as any)
+
+ expect(reply.header).toHaveBeenCalled()
+ expect(reply.setCookie).toHaveBeenCalledWith(OAuthCookie.State, 'state-1', expect.any(Object))
+ expect(reply.setCookie).toHaveBeenCalledWith(OAuthCookie.Nonce, 'nonce-1', expect.any(Object))
+ expect(reply.setCookie).toHaveBeenCalledWith(OAuthCookie.CodeVerifier, 'verifier-1', expect.any(Object))
+ const url = new URL(authUrl)
+ expect(url.searchParams.get('code_challenge')).toBe('challenge-1')
+ expect(url.searchParams.get('client_id')).toBe('client-id')
+ })
+
+ it('handles callback success and clears cookies', async () => {
+ const config = makeConfig(true)
+ jest.spyOn(service, 'getConfig').mockResolvedValue(config as any)
+ const processSpy = jest.spyOn(service as any, 'processUserInfo').mockResolvedValue({ id: 7 } as any)
+ ;(authorizationCodeGrant as jest.Mock).mockResolvedValue({
+ claims: () => ({ sub: 'subject-1' }),
+ access_token: 'access-token'
+ })
+ ;(fetchUserInfo as jest.Mock).mockResolvedValue({ sub: 'subject-1', email: '[email protected]', preferred_username: 'alice' })
+ const req = {
+ cookies: {
+ [OAuthCookie.State]: 'state-1',
+ [OAuthCookie.Nonce]: 'nonce-1',
+ [OAuthCookie.CodeVerifier]: 'verifier-1'
+ },
+ ip: '127.0.0.1'
+ }
+ const reply = makeReply()
+
+ const result = await service.handleCallback(req as any, reply as any, { code: 'abc' })
+
+ expect(result).toEqual({ id: 7 })
+ expect(processSpy).toHaveBeenCalledWith({ sub: 'subject-1', email: '[email protected]', preferred_username: 'alice' }, '127.0.0.1')
+ expect(reply.clearCookie).toHaveBeenCalledWith(OAuthCookie.State, { path: '/' })
+ expect(reply.clearCookie).toHaveBeenCalledWith(OAuthCookie.Nonce, { path: '/' })
+ expect(reply.clearCookie).toHaveBeenCalledWith(OAuthCookie.CodeVerifier, { path: '/' })
+ })
+
+ it('rejects callback when state is missing', async () => {
+ jest.spyOn(service, 'getConfig').mockResolvedValue(makeConfig(false) as any)
+ const reply = makeReply()
+ const req = { cookies: {}, ip: '127.0.0.1' }
+
+ await expect(service.handleCallback(req as any, reply as any, { code: 'abc' })).rejects.toMatchObject({ status: HttpStatus.BAD_REQUEST })
+ expect(reply.clearCookie).toHaveBeenCalledWith(OAuthCookie.State, { path: '/' })
+ })
+
+ it('maps AuthorizationResponseError to BAD_REQUEST', async () => {
+ jest.spyOn(service, 'getConfig').mockResolvedValue(makeConfig(false) as any)
+ ;(authorizationCodeGrant as jest.Mock).mockRejectedValue(
+ new AuthorizationResponseError('access_denied', {
+ cause: new URLSearchParams('error=access_denied&error_description=No access')
+ })
+ )
+ const req = {
+ cookies: {
+ [OAuthCookie.State]: 'state-1',
+ [OAuthCookie.Nonce]: 'nonce-1'
+ },
+ ip: '127.0.0.1'
+ }
+ const reply = makeReply()
+
+ await expect(service.handleCallback(req as any, reply as any, { code: 'abc' })).rejects.toMatchObject({
+ status: HttpStatus.BAD_REQUEST,
+ message: 'No access'
+ })
+ })
+
+ it('builds the redirect callback url with token expirations', () => {
+ const url = service.getRedirectCallbackUrl(10, 20)
+ const parsed = new URL(url)
+ expect(parsed.hash).toContain('access_expiration=10')
+ expect(parsed.hash).toContain('refresh_expiration=20')
+ })
+
+ it('creates identities with admin role when claims match', async () => {
+ usersManager.findUser.mockResolvedValue(null)
+ adminUsersManager.createUserOrGuest.mockResolvedValue({ id: 10, login: 'bob' })
+ usersManager.fromUserId.mockResolvedValue({ id: 10, role: USER_ROLE.ADMINISTRATOR, login: 'bob', setFullName: jest.fn() } as any)
+ const userInfo = { sub: 'x', email: '[email protected]', preferred_username: 'bob', groups: ['admins'] }
+
+ const result = await (service as any).processUserInfo(userInfo, '127.0.0.1')
+
+ expect(adminUsersManager.createUserOrGuest).toHaveBeenCalledWith(
+ expect.objectContaining({ role: USER_ROLE.ADMINISTRATOR }),
+ USER_ROLE.ADMINISTRATOR
+ )
+ expect(result.role).toBe(USER_ROLE.ADMINISTRATOR)
+ })
+})
diff --git a/backend/src/authentication/providers/oidc/auth-provider-oidc.service.ts b/backend/src/authentication/providers/oidc/auth-provider-oidc.service.ts
index e5764c6a..07359af8 100644
--- a/backend/src/authentication/providers/oidc/auth-provider-oidc.service.ts
+++ b/backend/src/authentication/providers/oidc/auth-provider-oidc.service.ts
@@ -74,9 +74,6 @@ export class AuthProviderOIDC implements AuthProvider {
async getConfig(): Promise<Configuration> {
if (!this.config) {
this.config = await this.initializeOIDCClient()
- if (!this.config) {
- throw new HttpException('Failed to initialize OIDC client', HttpStatus.INTERNAL_SERVER_ERROR)
- }
}
return this.config
}
@@ -217,15 +214,25 @@ export class AuthProviderOIDC implements AuthProvider {
},
this.getTokenAuthMethod(this.oidcConfig.security.tokenEndpointAuthMethod, this.oidcConfig.clientSecret),
{
- execute: [allowInsecureRequests], // allow HTTP for development
+ execute: [allowInsecureRequests],
timeout: 6000
}
)
this.logger.log(`${this.initializeOIDCClient.name} - OIDC client initialized successfully for issuer: ${this.oidcConfig.issuerUrl}`)
return config
} catch (error) {
- this.logger.error(`${this.initializeOIDCClient.name} - Failed to initialize OIDC client: ${error?.cause || error}`)
- return null
+ this.logger.error(`${this.initializeOIDCClient.name} - OIDC client initialization failed: ${error?.cause || error}`)
+ switch (error.cause?.code) {
+ case 'ECONNREFUSED':
+ case 'ENOTFOUND':
+ throw new HttpException('OIDC provider unavailable', HttpStatus.SERVICE_UNAVAILABLE)
+
+ case 'ETIMEDOUT':
+ throw new HttpException('OIDC provider timeout', HttpStatus.GATEWAY_TIMEOUT)
+
+ default:
+ throw new HttpException('OIDC client initialization failed', HttpStatus.INTERNAL_SERVER_ERROR)
+ }
}
}