Skip to content

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

fix(backend:auth): invalidate WebDAV cache on app password deletion

johaven6dae2848960c
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 77604a3a..303e1e14 100755
--- a/backend/src/applications/users/services/users-manager.service.spec.ts
+++ b/backend/src/applications/users/services/users-manager.service.spec.ts
@@ -7,6 +7,7 @@ import os from 'node:os'
import path from 'node:path'
import { Readable } from 'node:stream'
import { AuthManager } from '../../../authentication/auth.service'
+import { CACHE_AUTH_WEBDAV_PREFIX } from '../../../authentication/constants/cache'
import { AUTH_SCOPE } from '../../../authentication/constants/scope'
import { comparePassword } from '../../../common/functions'
import * as imageModule from '../../../common/image'
@@ -49,6 +50,7 @@ describe(UsersManager.name, () => {
let adminUsersManager: AdminUsersManager
let adminUsersQueries: AdminUsersQueries
let usersQueriesService: UsersQueries
+ let cache: Cache
let userTest: UserModel
let deleteUserDto: DeleteUserDto
let testDataPath: string
@@ -112,6 +114,7 @@ describe(UsersManager.name, () => {
adminUsersManager = module.get(AdminUsersManager)
adminUsersQueries = module.get(AdminUsersQueries)
usersQueriesService = module.get(UsersQueries)
+ cache = module.get(Cache)
userTest = new UserModel(generateUserTest(), false)
deleteUserDto = { deleteSpace: true, isGuest: false } satisfies DeleteUserDto
})
@@ -339,6 +342,49 @@ describe(UsersManager.name, () => {
expect(comparePassword).toHaveBeenCalledWith('pwd', 'APP_HASH')
})
+ it('deletes WebDAV auth cache entries for the user when deleting a WebDAV app password', async () => {
+ const secrets = {
+ appPasswords: [
+ { name: 'webdav-client', app: AUTH_SCOPE.WEBDAV, password: 'HASH' },
+ { name: 'desktop-client', app: AUTH_SCOPE.CLIENT, password: 'HASH' }
+ ]
+ }
+ usersQueriesService.getUserSecrets = vi.fn().mockResolvedValue(secrets)
+ usersQueriesService.updateUserOrGuest = vi.fn().mockResolvedValue(true)
+ cache.keys = vi
+ .fn()
+ .mockResolvedValue([`${CACHE_AUTH_WEBDAV_PREFIX}-match`, `${CACHE_AUTH_WEBDAV_PREFIX}-other`, `${CACHE_AUTH_WEBDAV_PREFIX}-failed`])
+ cache.get = vi
+ .fn()
+ .mockResolvedValueOnce({ id: userTest.id })
+ .mockResolvedValueOnce({ id: userTest.id + 1 })
+ .mockResolvedValueOnce(null)
+ cache.mdel = vi.fn().mockResolvedValue(true)
+
+ await expect(usersManager.deleteAppPassword(userTest, 'webdav-client')).resolves.toBeUndefined()
+
+ expect(usersQueriesService.updateUserOrGuest).toHaveBeenCalledWith(userTest.id, {
+ secrets: { appPasswords: [{ name: 'desktop-client', app: AUTH_SCOPE.CLIENT, password: 'HASH' }] }
+ })
+ expect(cache.keys).toHaveBeenCalledWith(`${CACHE_AUTH_WEBDAV_PREFIX}-*`)
+ expect(cache.mdel).toHaveBeenCalledWith([`${CACHE_AUTH_WEBDAV_PREFIX}-match`])
+ })
+
+ it('does not delete WebDAV auth cache entries when deleting another app password scope', async () => {
+ const secrets = {
+ appPasswords: [{ name: 'desktop-client', app: AUTH_SCOPE.CLIENT, password: 'HASH' }]
+ }
+ usersQueriesService.getUserSecrets = vi.fn().mockResolvedValue(secrets)
+ usersQueriesService.updateUserOrGuest = vi.fn().mockResolvedValue(true)
+ cache.keys = vi.fn()
+ cache.mdel = vi.fn()
+
+ await expect(usersManager.deleteAppPassword(userTest, 'desktop-client')).resolves.toBeUndefined()
+
+ expect(cache.keys).not.toHaveBeenCalled()
+ expect(cache.mdel).not.toHaveBeenCalled()
+ })
+
it('compareUserPassword + updateLanguage + updatePassword branches', async () => {
usersQueriesService.compareUserPassword = vi.fn().mockResolvedValue(true)
await expect(usersManager.compareUserPassword(1, 'p')).resolves.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 a73ce393..bc6dd28e 100755
--- a/backend/src/applications/users/services/users-manager.service.ts
+++ b/backend/src/applications/users/services/users-manager.service.ts
@@ -5,6 +5,7 @@ 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'
import { AUTH_SCOPE } from '../../../authentication/constants/scope'
import { LoginResponseDto } from '../../../authentication/dto/login-response.dto'
import { FastifyAuthenticatedRequest } from '../../../authentication/interfaces/auth-request.interface'
@@ -14,6 +15,7 @@ import { comparePassword, hashPassword } from '../../../common/functions'
import { convertTempImageToPng, generateAvatar, imgMimeTypePrefix, pngMimeType, svgMimeType } from '../../../common/image'
import { createLightSlug, genPassword } from '../../../common/shared'
import { configuration, serverConfig } from '../../../configuration/config.environment'
+import { Cache } from '../../../infrastructure/cache/cache.service'
import { isPathExists, removeFiles, sanitizeName } from '../../files/utils/files'
import { NOTIFICATION_APP, NOTIFICATION_APP_EVENT } from '../../notifications/constants/notifications'
import { NotificationsManager } from '../../notifications/services/notifications-manager.service'
@@ -51,7 +53,8 @@ export class UsersManager {
constructor(
public readonly usersQueries: UsersQueries,
private readonly adminUsersManager: AdminUsersManager,
- private readonly notificationsManager: NotificationsManager
+ private readonly notificationsManager: NotificationsManager,
+ private readonly cache: Cache
) {}
async fromUserId(id: number): Promise<UserModel> {
@@ -314,13 +317,17 @@ export class UsersManager {
async deleteAppPassword(user: UserModel, passwordName: string): Promise<void> {
const secrets = await this.usersQueries.getUserSecrets(user.id)
- if (!Array.isArray(secrets.appPasswords) || !secrets.appPasswords.find((p: UserAppPassword) => p.name === passwordName)) {
+ const appPassword = Array.isArray(secrets.appPasswords) ? secrets.appPasswords.find((p: UserAppPassword) => p.name === passwordName) : undefined
+ if (!appPassword) {
throw new HttpException('App password not found', HttpStatus.NOT_FOUND)
}
secrets.appPasswords = secrets.appPasswords.filter((p: UserAppPassword) => p.name !== passwordName)
if (!(await this.usersQueries.updateUserOrGuest(user.id, { secrets: secrets }))) {
throw new HttpException('Unable to delete app password', HttpStatus.INTERNAL_SERVER_ERROR)
}
+ if (appPassword.app === AUTH_SCOPE.WEBDAV) {
+ await this.clearWebDAVAuthCache(user.id).catch((e: Error) => this.logger.error({ tag: this.clearWebDAVAuthCache.name, msg: `${e}` }))
+ }
}
async validateAppPassword(user: UserModel, password: string, ip: string, scope: AUTH_SCOPE): Promise<boolean> {
@@ -596,6 +603,20 @@ export class UsersManager {
return this.usersQueries.searchUsersOrGroups(searchMembersDto, user.id)
}
+ private async clearWebDAVAuthCache(userId: number): Promise<void> {
+ 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 notifyAccountLocked(user: UserModel, ip: string) {
this.notificationsManager
.sendEmailNotification([user], {
diff --git a/backend/src/authentication/constants/cache.ts b/backend/src/authentication/constants/cache.ts
new file mode 100644
index 00000000..4586b6fc
--- /dev/null
+++ b/backend/src/authentication/constants/cache.ts
@@ -0,0 +1,3 @@
+// cache key = `auth-webdav-${sha256(login + password)}` => UserModel | null
+export const CACHE_AUTH_WEBDAV_PREFIX = 'auth-webdav' as const
+export const CACHE_AUTH_WEBDAV_TTL = 900 as const
diff --git a/backend/src/authentication/guards/auth-basic.strategy.ts b/backend/src/authentication/guards/auth-basic.strategy.ts
index 6d4b9e24..910443e0 100644
--- a/backend/src/authentication/guards/auth-basic.strategy.ts
+++ b/backend/src/authentication/guards/auth-basic.strategy.ts
@@ -7,15 +7,13 @@ import { genHash } from '../../applications/files/utils/files'
import { UserModel } from '../../applications/users/models/user.model'
import { SERVER_NAME } from '../../common/shared'
import { Cache } from '../../infrastructure/cache/cache.service'
+import { CACHE_AUTH_WEBDAV_PREFIX, CACHE_AUTH_WEBDAV_TTL } from '../constants/cache'
import { AUTH_SCOPE } from '../constants/scope'
import { AuthProvider } from '../providers/auth-providers.models'
import { HttpBasicStrategy } from './implementations/http-basic.strategy'
@Injectable()
export class AuthBasicStrategy extends PassportStrategy(HttpBasicStrategy, 'basic') implements AbstractStrategy {
- private readonly CACHE_TTL = 900
- private readonly CACHE_KEY_PREFIX = 'auth-webdav'
-
constructor(
private readonly authProvider: AuthProvider,
private readonly cache: Cache,
@@ -27,7 +25,7 @@ export class AuthBasicStrategy extends PassportStrategy(HttpBasicStrategy, 'basi
async validate(req: FastifyRequest, loginOrEmail: string, password: string): Promise<Omit<UserModel, 'password'> | null> {
loginOrEmail = loginOrEmail.trim()
this.logger.assign({ user: loginOrEmail })
- const basicAuthCacheKey = `${this.CACHE_KEY_PREFIX}-${genHash(`${loginOrEmail}\u0000${password}`, 'sha256')}`
+ const basicAuthCacheKey = `${CACHE_AUTH_WEBDAV_PREFIX}-${genHash(`${loginOrEmail}\u0000${password}`, 'sha256')}`
const userFromCache: null | undefined | Partial<UserModel> = await this.cache.get(basicAuthCacheKey)
if (userFromCache === null) {
// not authorized
@@ -43,7 +41,9 @@ export class AuthBasicStrategy extends PassportStrategy(HttpBasicStrategy, 'basi
userFromDB.removePassword()
}
const userToCache: Record<string, any> | null = userFromDB ? instanceToPlain(userFromDB, { excludePrefixes: ['_'] }) : null
- this.cache.set(basicAuthCacheKey, userToCache, this.CACHE_TTL).catch((e: Error) => this.logger.error({ tag: this.validate.name, msg: `${e}` }))
+ this.cache
+ .set(basicAuthCacheKey, userToCache, CACHE_AUTH_WEBDAV_TTL)
+ .catch((e: Error) => this.logger.error({ tag: this.validate.name, msg: `${e}` }))
return userFromDB
}
}