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): align WebDAV cache TTL and invalidate stale auth
johavene952350a6bd7
diff --git a/backend/src/applications/users/services/admin-users-manager.service.spec.ts b/backend/src/applications/users/services/admin-users-manager.service.spec.tsindex a950a247..6fddd044 100644--- a/backend/src/applications/users/services/admin-users-manager.service.spec.ts+++ b/backend/src/applications/users/services/admin-users-manager.service.spec.ts@@ -56,6 +56,8 @@ describe(AdminUsersManager.name, () => {checkUserExists: MocksearchUsersOrGroups: MockclearWhiteListCaches: Mock+ clearWebDAVAuthCache: Mock+ allUserIdsFromGroupsAndSubGroups: Mock}updateUserGroups: MockupdateGuestManagers: Mock@@ -99,7 +101,9 @@ describe(AdminUsersManager.name, () => {checkGroupNameExists: vi.fn(),checkUserExists: vi.fn(),searchUsersOrGroups: vi.fn(),- clearWhiteListCaches: vi.fn()+ clearWhiteListCaches: vi.fn(),+ clearWebDAVAuthCache: vi.fn(),+ allUserIdsFromGroupsAndSubGroups: vi.fn().mockResolvedValue([])},updateUserGroups: vi.fn(),updateGuestManagers: vi.fn(),@@ -367,6 +371,7 @@ describe(AdminUsersManager.name, () => {fs.removeFiles.mockResolvedValueOnce(undefined)await expect(service.deleteUserOrGuest(10, 'john', { deleteSpace: true })).resolves.toBeUndefined()expect(adminQueriesMock.deleteUser).toHaveBeenCalledWith(10, 'john')+ expect(adminQueriesMock.usersQueries.clearWebDAVAuthCache).toHaveBeenCalledWith(10)expect(fs.isPathExists).toHaveBeenCalled()expect(fs.removeFiles).toHaveBeenCalled()@@ -465,9 +470,21 @@ describe(AdminUsersManager.name, () => {await expectHttp(service.updateGroup(5, {} as any))})+ it('clears WebDAV authentication for users affected by a group permission change', async () => {+ adminQueriesMock.usersQueries.allUserIdsFromGroupsAndSubGroups.mockResolvedValueOnce([10, 11])+ adminQueriesMock.updateGroup.mockResolvedValueOnce(true)+ adminQueriesMock.groupFromId.mockResolvedValueOnce({ id: 5, permissions: '' })++ await service.updateGroup(5, { permissions: '' } as any)++ expect(adminQueriesMock.usersQueries.clearWebDAVAuthCache).toHaveBeenCalledWith([10, 11])+ })+it('deleteGroup success / fail', async () => {+ adminQueriesMock.usersQueries.allUserIdsFromGroupsAndSubGroups.mockResolvedValueOnce([10, 11])adminQueriesMock.deleteGroup.mockResolvedValueOnce(true)await expect(service.deleteGroup(5)).resolves.toBeUndefined()+ expect(adminQueriesMock.usersQueries.clearWebDAVAuthCache).toHaveBeenCalledWith([10, 11])adminQueriesMock.deleteGroup.mockResolvedValueOnce(false)await expectHttp(service.deleteGroup(6))})diff --git a/backend/src/applications/users/services/admin-users-manager.service.ts b/backend/src/applications/users/services/admin-users-manager.service.tsindex 93f7e8d7..26a65df6 100644--- a/backend/src/applications/users/services/admin-users-manager.service.ts+++ b/backend/src/applications/users/services/admin-users-manager.service.ts@@ -180,7 +180,9 @@ export class AdminUsersManager {async deleteUserOrGuest(userId: number, userLogin: string, deleteUserDto: DeleteUserDto): Promise<void> {try {- if (await this.adminQueries.deleteUser(userId, userLogin)) {+ const deleted = await this.adminQueries.deleteUser(userId, userLogin)+ await this.adminQueries.usersQueries.clearWebDAVAuthCache(userId)+ if (deleted) {this.logger.log({ tag: this.deleteUserOrGuest.name, msg: `*${userLogin}* (${userId}) was deleted` })} else {this.logger.error({ tag: this.deleteUserOrGuest.name, msg: `*${userLogin}* (${userId}) was not deleted : not found` })@@ -270,9 +272,14 @@ export class AdminUsersManager {if (updateGroupDto.name) {await this.checkGroupNameExists(updateGroupDto.name)}+ const affectedUserIds =+ updateGroupDto.permissions !== undefined ? await this.adminQueries.usersQueries.allUserIdsFromGroupsAndSubGroups([groupId]) : []if (!(await this.adminQueries.updateGroup(groupId, updateGroupDto))) {throw new HttpException('Unable to update group', HttpStatus.INTERNAL_SERVER_ERROR)}+ if (affectedUserIds.length) {+ await this.adminQueries.usersQueries.clearWebDAVAuthCache(affectedUserIds)+ }// Clear whitelist caches when the group’s visibility is changedif (updateGroupDto.visibility !== undefined) {void this.adminQueries.usersQueries.clearWhiteListCaches('*')@@ -281,7 +288,11 @@ export class AdminUsersManager {}async deleteGroup(groupId: number): Promise<void> {+ const affectedUserIds = await this.adminQueries.usersQueries.allUserIdsFromGroupsAndSubGroups([groupId])if (await this.adminQueries.deleteGroup(groupId)) {+ if (affectedUserIds.length) {+ await this.adminQueries.usersQueries.clearWebDAVAuthCache(affectedUserIds)+ }this.logger.log({ tag: this.deleteGroup.name, msg: `group (${groupId}) was deleted` })} else {this.logger.warn({ tag: this.deleteGroup.name, msg: `group (${groupId}) does not exist` })diff --git a/backend/src/applications/users/services/admin-users-queries.service.ts b/backend/src/applications/users/services/admin-users-queries.service.tsindex 997d1ac2..aeb2dd7b 100644--- a/backend/src/applications/users/services/admin-users-queries.service.ts+++ b/backend/src/applications/users/services/admin-users-queries.service.ts@@ -204,6 +204,7 @@ export class AdminUsersQueries {)this.logger.log({ tag: this.updateUserGroups.name, msg: `user (${userId}) groups ${JSON.stringify(groups.add)} was added` })void this.usersQueries.clearWhiteListCaches([userId])+ await this.usersQueries.clearWebDAVAuthCache(userId)} catch (e) {this.logger.error({ tag: this.updateUserGroups.name, msg: `user (${userId}) groups ${JSON.stringify(groups.add)} was not added: ${e}` })throw new Error('User groups was not added')@@ -217,6 +218,7 @@ export class AdminUsersQueries {)this.logger.log({ tag: this.updateUserGroups.name, msg: `user (${userId}) groups ${JSON.stringify(groups.delete)} was deleted` })void this.usersQueries.clearWhiteListCaches([userId])+ await this.usersQueries.clearWebDAVAuthCache(userId)} catch (e) {this.logger.error({ tag: this.updateUserGroups.name, msg: `user (${userId}) groups ${JSON.stringify(groups.delete)} was not deleted: ${e}` })throw new Error('User groups was not deleted')@@ -273,6 +275,7 @@ export class AdminUsersQueries {)this.logger.log({ tag: this.addUsersToGroup.name, msg: `users (${userIds}) was added to group (${groupId})` })void this.usersQueries.clearWhiteListCaches(userIds)+ await this.usersQueries.clearWebDAVAuthCache(userIds)} catch (e) {this.logger.error({ tag: this.addUsersToGroup.name, msg: `unable to add users (${userIds}) to group (${groupId}) : ${e}` })throw new Error('Unable to add users to group')@@ -310,6 +313,7 @@ export class AdminUsersQueries {)this.logger.log({ tag: this.removeUserFromGroup.name, msg: `user (${userId}) was removed from group (${groupId})` })void this.usersQueries.clearWhiteListCaches([userId])+ await this.usersQueries.clearWebDAVAuthCache(userId)} catch (e) {this.logger.error({ tag: this.removeUserFromGroup.name, msg: `user (${userId}) or group (${groupId}) does not exist : ${e}` })throw new Error('Unable to remove user from group')diff --git a/backend/src/applications/users/services/users-manager.service.spec.ts b/backend/src/applications/users/services/users-manager.service.spec.tsindex 37a85e8c..a3d6dad7 100755--- a/backend/src/applications/users/services/users-manager.service.spec.ts+++ b/backend/src/applications/users/services/users-manager.service.spec.ts@@ -120,7 +120,15 @@ describe(UsersManager.name, () => {{ provide: AuthManager, useValue: {} },{ provide: NotificationsManager, useValue: { sendEmailNotification: vi.fn().mockResolvedValue(undefined) } },{ provide: DB_TOKEN_PROVIDER, useValue: {} },- { provide: Cache, useValue: { consumeRateLimit: vi.fn() } }+ {+ provide: Cache,+ useValue: {+ consumeRateLimit: vi.fn(),+ keys: vi.fn().mockResolvedValue([]),+ get: vi.fn(),+ mdel: vi.fn().mockResolvedValue(false)+ }+ }]}).compile()module.useLogger(['fatal'])@@ -136,6 +144,9 @@ describe(UsersManager.name, () => {beforeEach(() => {vi.mocked(cache.consumeRateLimit).mockReset()vi.mocked(cache.consumeRateLimit).mockResolvedValue({ totalHits: 1, timeToExpire: 60, isBlocked: false, timeToBlockExpire: 0 })+ cache.keys = vi.fn().mockResolvedValue([])+ cache.get = vi.fn()+ cache.mdel = vi.fn().mockResolvedValue(false)})afterEach(() => vi.restoreAllMocks())@@ -577,6 +588,7 @@ describe(UsersManager.name, () => {await expect(usersManager.consumeRecoveryCode(userTest.id, 'code-1')).resolves.toBe(true)await expect(usersManager.consumeRecoveryCode(userTest.id, 'code-1')).resolves.toBe(false)+ expect(cache.keys).toHaveBeenCalledWith(`${CACHE_AUTH_WEBDAV_PREFIX}-*`)expect(getCurrentSecrets()).toEqual({twoFaSecret: 'new-secret',recoveryCodes: ['code-2'],diff --git a/backend/src/applications/users/services/users-manager.service.ts b/backend/src/applications/users/services/users-manager.service.tsindex c5fe0767..506b51ec 100755--- a/backend/src/applications/users/services/users-manager.service.ts+++ b/backend/src/applications/users/services/users-manager.service.ts@@ -5,7 +5,6 @@ import { WriteStream } from 'fs'import { createWriteStream } from 'node:fs'import path from 'node:path'import { pipeline } from 'node:stream/promises'-import { CACHE_AUTH_WEBDAV_PREFIX } from '../../../authentication/constants/cache.js'import { AUTH_SCOPE } from '../../../authentication/constants/scope.js'import { LoginResponseDto } from '../../../authentication/dto/login-response.dto.js'import { AuthPasswordWorkLimitException } from '../../../authentication/errors/auth-password-work-limit.exception.js'@@ -308,6 +307,9 @@ export class UsersManager {result: undefined,secrets: { ...userSecrets, ...secrets }}))+ if ('twoFaSecret' in secrets) {+ await this.usersQueries.clearWebDAVAuthCache(userId)+ }} catch (e) {this.logger.error({ tag: this.updateSecrets.name, msg: `Unable to update secrets for user (${userId}) : ${e}` })throw new HttpException('Unable to update secrets', HttpStatus.INTERNAL_SERVER_ERROR)@@ -438,7 +440,7 @@ export class UsersManager {}if (appPassword.app === AUTH_SCOPE.WEBDAV) {// mutateUserSecrets has committed the revocation; cached Basic-auth results can now be discarded.- await this.clearWebDAVAuthCache(user.id).catch((e: Error) => this.logger.error({ tag: this.clearWebDAVAuthCache.name, msg: `${e}` }))+ await this.usersQueries.clearWebDAVAuthCache(user.id)}}@@ -730,22 +732,6 @@ export class UsersManager {return this.usersQueries.searchUsersOrGroups(searchMembersDto, user.id)}- private async clearWebDAVAuthCache(userId: number): Promise<void> {- // Cache keys contain a hash of login + clear password, which cannot be rebuilt from the stored bcrypt hash.- // Inspect cached values instead and remove every positive WebDAV authentication entry for this user.- const keys = await this.cache.keys(`${CACHE_AUTH_WEBDAV_PREFIX}-*`)- const keysToDelete: string[] = []- for (const key of keys) {- const cachedUser: null | undefined | Partial<UserModel> = await this.cache.get(key)- if (cachedUser?.id === userId) {- keysToDelete.push(key)- }- }- if (keysToDelete.length) {- await this.cache.mdel(keysToDelete)- }- }-private notifyTemporaryAccountLock(user: UserModel, ip: string): void {const notification = {app: NOTIFICATION_APP.AUTH_LOCKED,diff --git a/backend/src/applications/users/services/users-queries.service.spec.ts b/backend/src/applications/users/services/users-queries.service.spec.tsindex bf9ff680..1900b0d1 100644--- a/backend/src/applications/users/services/users-queries.service.spec.ts+++ b/backend/src/applications/users/services/users-queries.service.spec.ts@@ -1,3 +1,4 @@+import { CACHE_AUTH_WEBDAV_PREFIX } from '../../../authentication/constants/cache.js'import type { Cache } from '../../../infrastructure/cache/cache.service.js'import type { DBSchema } from '../../../infrastructure/database/interfaces/database.interface.js'import { UsersQueries } from './users-queries.service.js'@@ -21,3 +22,40 @@ describe(`${UsersQueries.name}.from`, () => {expect(execute).toHaveBeenCalledWith({ loginOrEmail: 'alice' })})})++describe(`${UsersQueries.name}.WebDAVAuthCache`, () => {+ it('clears only cached WebDAV authentications belonging to the targeted users', async () => {+ const cache = {+ keys: vi+ .fn()+ .mockResolvedValue([+ `${CACHE_AUTH_WEBDAV_PREFIX}-matching`,+ `${CACHE_AUTH_WEBDAV_PREFIX}-other`,+ `${CACHE_AUTH_WEBDAV_PREFIX}-second-match`,+ `${CACHE_AUTH_WEBDAV_PREFIX}-missing`+ ]),+ get: vi.fn().mockResolvedValueOnce({ id: 42 }).mockResolvedValueOnce({ id: 43 }).mockResolvedValueOnce({ id: 44 }).mockResolvedValueOnce(null),+ mdel: vi.fn().mockResolvedValue(true)+ } as unknown as Cache+ const usersQueries = new UsersQueries({} as DBSchema, cache)++ await usersQueries.clearWebDAVAuthCache([42, 44])++ expect(cache.keys).toHaveBeenCalledWith(`${CACHE_AUTH_WEBDAV_PREFIX}-*`)+ expect(cache.mdel).toHaveBeenCalledWith([`${CACHE_AUTH_WEBDAV_PREFIX}-matching`, `${CACHE_AUTH_WEBDAV_PREFIX}-second-match`])+ })++ it('invalidates WebDAV authentication after an auth-sensitive user update', async () => {+ const where = vi.fn().mockResolvedValue([{ affectedRows: 1 }])+ const set = vi.fn().mockReturnValue({ where })+ const db = { update: vi.fn().mockReturnValue({ set }) } as unknown as DBSchema+ const usersQueries = new UsersQueries(db, {} as Cache)+ const clearWebDAVAuthCache = vi.spyOn(usersQueries, 'clearWebDAVAuthCache').mockResolvedValue(undefined)++ await expect(usersQueries.updateUserOrGuest(42, { password: 'hash' })).resolves.toBe(true)+ await expect(usersQueries.updateUserOrGuest(42, { language: 'fr' })).resolves.toBe(true)++ expect(clearWebDAVAuthCache).toHaveBeenCalledTimes(1)+ expect(clearWebDAVAuthCache).toHaveBeenCalledWith(42)+ })+})diff --git a/backend/src/applications/users/services/users-queries.service.ts b/backend/src/applications/users/services/users-queries.service.tsindex aa34932b..86fecbbe 100644--- a/backend/src/applications/users/services/users-queries.service.ts+++ b/backend/src/applications/users/services/users-queries.service.ts@@ -2,6 +2,7 @@ import { Inject, Injectable, Logger } from '@nestjs/common'import { and, countDistinct, desc, eq, gte, inArray, isNotNull, isNull, like, lte, ne, notInArray, or, SelectedFields, SQL, sql } from 'drizzle-orm'import { alias } from 'drizzle-orm/mysql-core'import { MySql2PreparedQuery, MySqlQueryResult } from 'drizzle-orm/mysql2'+import { CACHE_AUTH_WEBDAV_PREFIX } from '../../../authentication/constants/cache.js'import { anonymizePassword, comparePassword, uniquePermissions } from '../../../common/functions.js'import { CacheDecorator } from '../../../infrastructure/cache/cache.decorator.js'import { Cache } from '../../../infrastructure/cache/cache.service.js'@@ -252,6 +253,9 @@ export class UsersQueries {1)this.logger.verbose({ tag: this.updateUserOrGuest.name, msg: `user (${userId}) was updated : ${JSON.stringify(anonymizePassword(set))}` })+ if (['login', 'email', 'password', 'isActive', 'role', 'permissions'].some((field) => field in set)) {+ await this.clearWebDAVAuthCache(userId)+ }return true} catch (e) {this.logger.error({@@ -834,6 +838,28 @@ export class UsersQueries {}}+ async clearWebDAVAuthCache(userIds: number | number[]): Promise<void> {+ try {+ const targetUserIds = new Set(Array.isArray(userIds) ? userIds : [userIds])+ if (!targetUserIds.size) return+ // Cache keys use a credential HMAC and cannot be rebuilt from the stored password hashes.+ // Inspect cached values and remove every positive WebDAV authentication entry for the targeted users.+ const keys = await this.cache.keys(`${CACHE_AUTH_WEBDAV_PREFIX}-*`)+ const keysToDelete: string[] = []+ for (const key of keys) {+ const cachedUser: null | undefined | Partial<UserModel> = await this.cache.get(key)+ if (cachedUser?.id !== undefined && targetUserIds.has(cachedUser.id)) {+ keysToDelete.push(key)+ }+ }+ if (keysToDelete.length) {+ await this.cache.mdel(keysToDelete)+ }+ } catch (e) {+ this.logger.error({ tag: this.clearWebDAVAuthCache.name, msg: `${e}` })+ }+ }+async allUserIdsFromGroupsAndSubGroups(groupIds: number[]): Promise<number[]> {if (!groupIds.length) return []const subGroup: any = alias(groups, 'subGroup')diff --git a/backend/src/applications/users/users.md b/backend/src/applications/users/users.mdindex c453bb40..0e1823b0 100644--- a/backend/src/applications/users/users.md+++ b/backend/src/applications/users/users.md@@ -64,8 +64,8 @@ the password-attempt limit does not suspend the account.`isActive` is the durable administrative switch for a local user record:- `isActive: false` is rejected by local password and app-password paths as well as by the LDAP and OIDC provider flows;-- new authentication and token refreshes reload the local user record and reject an inactive account. Already-issued access tokens and positive- WebDAV authentication cache entries remain usable until they expire;+- new authentication and token refreshes reload the local user record and reject an inactive account. Already-issued access tokens remain usable+ until they expire; positive WebDAV authentication cache entries are cleared when the account state changes;- the account remains disabled until an administrator reactivates it; there is no automatic expiration;- reactivating the account resets `passwordAttempts` to zero.diff --git a/backend/src/authentication/auth.md b/backend/src/authentication/auth.mdindex e39a5948..8489b78f 100644--- a/backend/src/authentication/auth.md+++ b/backend/src/authentication/auth.md@@ -133,9 +133,10 @@ WebDAV uses HTTP Basic authentication and cannot complete the interactive Sync-iThe primary password comparison is still executed for scoped-auth timing, but a successful primary-password match is ignored for 2FA-protected WebDAV.-Only successful WebDAV Basic-auth results are cached, for 900 seconds. Failed credentials and refusals caused by account state are never cached, so-credentials can be checked again immediately after an account is unlocked (subject to rate limits). Revoking a WebDAV app password clears cached-successful results for that user so the revoked password cannot continue to authenticate from cache.+Only successful WebDAV Basic-auth results are cached for the configured access-token lifetime (15 minutes by default). Failed credentials and+refusals caused by account state are never cached, so credentials can be checked again immediately after an account is unlocked (subject to rate+limits). Cached successful results for a user are cleared after changes to their login, email, password, active state, role, direct or group-derived+permissions, or TOTP state, after account deletion, and when a WebDAV app password is revoked.Cache keys use a domain-separated HMAC-SHA-256 keyed with the access-token secret; the cache therefore does not persist an unkeyed fast digest of thesubmitted password.diff --git a/backend/src/authentication/constants/cache.ts b/backend/src/authentication/constants/cache.tsindex 6393f780..30653984 100644--- a/backend/src/authentication/constants/cache.ts+++ b/backend/src/authentication/constants/cache.ts@@ -1,4 +1,3 @@// cache key = `auth-webdav-${HMAC-SHA-256(context + '\0' + login + '\0' + password, access-token secret)}` => successful UserModel onlyexport const CACHE_AUTH_WEBDAV_PREFIX = 'auth-webdav' as const-export const CACHE_AUTH_WEBDAV_TTL = 900 as constexport const CACHE_AUTH_RATE_LIMIT_PREFIX = 'auth-rate-limit' as constdiff --git a/backend/src/authentication/guards/auth-basic.strategy.ts b/backend/src/authentication/guards/auth-basic.strategy.tsindex 0931a09e..e1a76778 100644--- a/backend/src/authentication/guards/auth-basic.strategy.ts+++ b/backend/src/authentication/guards/auth-basic.strategy.ts@@ -5,11 +5,11 @@ import { instanceToPlain, plainToInstance } from 'class-transformer'import { FastifyRequest } from 'fastify'import { PinoLogger } from 'nestjs-pino'import { UserModel } from '../../applications/users/models/user.model.js'+import { convertHumanTimeToSeconds } from '../../common/functions.js'import { SERVER_NAME } from '../../common/shared.js'import { configuration } from '../../configuration/config.environment.js'import { Cache } from '../../infrastructure/cache/cache.service.js'import { AUTH_RATE_LIMIT_ERROR_MESSAGE } from '../constants/auth.js'-import { CACHE_AUTH_WEBDAV_TTL } from '../constants/cache.js'import { AUTH_SCOPE } from '../constants/scope.js'import { AuthPasswordWorkLimitException } from '../errors/auth-password-work-limit.exception.js'import { AuthProvider } from '../providers/auth-providers.models.js'@@ -19,6 +19,8 @@ import { HttpBasicStrategy } from './implementations/http-basic.strategy.js'@Injectable()export class AuthBasicStrategy extends PassportStrategy(HttpBasicStrategy, 'basic') implements AbstractStrategy {+ private static readonly cacheAuthWebDAVTTL = convertHumanTimeToSeconds(configuration.auth.token.access.expiration)+constructor(private readonly authProvider: AuthProvider,private readonly cache: Cache,@@ -59,7 +61,7 @@ export class AuthBasicStrategy extends PassportStrategy(HttpBasicStrategy, 'basiuserFromDB.removePassword()const userToCache: Record<string, any> = instanceToPlain(userFromDB, { excludePrefixes: ['_'] })this.cache- .set(basicAuthCacheKey, userToCache, CACHE_AUTH_WEBDAV_TTL)+ .set(basicAuthCacheKey, userToCache, AuthBasicStrategy.cacheAuthWebDAVTTL).catch((e: Error) => this.logger.error({ tag: this.validate.name, msg: `${e}` }))return userFromDB}