Skip to content

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

fix(backend:auth): derive basic auth cache key from hashed credentials instead of Authorization header

johavenbe98defb7aaf
diff --git a/backend/src/applications/files/utils/files.ts b/backend/src/applications/files/utils/files.ts
index 65461b4d..a143a3ef 100644
--- a/backend/src/applications/files/utils/files.ts
+++ b/backend/src/applications/files/utils/files.ts
@@ -107,12 +107,16 @@ export function genEtag(file?: Pick<FileProps, 'size' | 'mtime'>, rPath?: string
return weakPrefix ? `W/"${etag}"` : etag
}
+export function genHash(str: string, algo = 'md5', encoding: crypto.BinaryToTextEncoding = 'hex'): string {
+ return crypto.createHash(algo).update(str).digest(encoding)
+}
+
export function genUniqHashFromFileDBProps(dbFile: FileDBProps) {
const dbFileString = `${Object.keys(dbFile)
.sort()
.map((k) => `${k}=${String(dbFile[k])}`)
.join('|')}`
- return crypto.createHash(DEFAULT_CHECKSUM_ALGORITHM).update(dbFileString, 'utf-8').digest('hex')
+ return genHash(dbFileString, DEFAULT_CHECKSUM_ALGORITHM)
}
export function removeFiles(rPath: string): Promise<void> {
diff --git a/backend/src/authentication/guards/auth-basic.strategy.ts b/backend/src/authentication/guards/auth-basic.strategy.ts
index df920e62..9d814deb 100644
--- a/backend/src/authentication/guards/auth-basic.strategy.ts
+++ b/backend/src/authentication/guards/auth-basic.strategy.ts
@@ -3,6 +3,7 @@ import { AbstractStrategy, PassportStrategy } from '@nestjs/passport'
import { instanceToPlain, plainToInstance } from 'class-transformer'
import { FastifyRequest } from 'fastify'
import { PinoLogger } from 'nestjs-pino'
+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/services/cache.service'
@@ -25,10 +26,9 @@ export class AuthBasicStrategy extends PassportStrategy(HttpBasicStrategy, 'basi
async validate(req: FastifyRequest, loginOrEmail: string, password: string): Promise<Omit<UserModel, 'password'> | null> {
loginOrEmail = loginOrEmail.trim()
- password = password.trim()
this.logger.assign({ user: loginOrEmail })
- const authBasicUser = `${this.CACHE_KEY_PREFIX}-${req.headers['authorization'].split(' ').at(-1).toLowerCase()}`
- const userFromCache: any = await this.cache.get(authBasicUser)
+ const basicAuthCacheKey = `${this.CACHE_KEY_PREFIX}-${genHash(`${loginOrEmail}\u0000${password}`, 'sha256')}`
+ const userFromCache: null | undefined | Partial<UserModel> = await this.cache.get(basicAuthCacheKey)
if (userFromCache === null) {
// not authorized
return null
@@ -43,7 +43,7 @@ export class AuthBasicStrategy extends PassportStrategy(HttpBasicStrategy, 'basi
userFromDB.removePassword()
}
const userToCache: Record<string, any> | null = userFromDB ? instanceToPlain(userFromDB, { excludePrefixes: ['_'] }) : null
- this.cache.set(authBasicUser, userToCache, this.CACHE_TTL).catch((e: Error) => this.logger.error({ tag: this.validate.name, msg: `${e}` }))
+ this.cache.set(basicAuthCacheKey, userToCache, this.CACHE_TTL).catch((e: Error) => this.logger.error({ tag: this.validate.name, msg: `${e}` }))
return userFromDB
}
}
diff --git a/backend/src/authentication/guards/auth-local.strategy.ts b/backend/src/authentication/guards/auth-local.strategy.ts
index ccc98037..d5e6cc8b 100755
--- a/backend/src/authentication/guards/auth-local.strategy.ts
+++ b/backend/src/authentication/guards/auth-local.strategy.ts
@@ -17,7 +17,6 @@ export class AuthLocalStrategy extends PassportStrategy(Strategy, 'local') imple
async validate(req: FastifyRequest, loginOrEmail: string, password: string): Promise<UserModel> {
loginOrEmail = loginOrEmail.trim()
- password = password.trim()
this.logger.assign({ user: loginOrEmail })
const user: UserModel = await this.authProvider.validateUser(loginOrEmail, password, req.ip)
if (user) {
diff --git a/backend/src/authentication/guards/implementations/http-digest.strategy.ts b/backend/src/authentication/guards/implementations/http-digest.strategy.ts
index 6b3002b7..e049788c 100644
--- a/backend/src/authentication/guards/implementations/http-digest.strategy.ts
+++ b/backend/src/authentication/guards/implementations/http-digest.strategy.ts
@@ -1,5 +1,5 @@
-import crypto from 'node:crypto'
import { Strategy as PassportStrategy } from 'passport-strategy'
+import { genHash } from '../../../applications/files/utils/files'
export interface DigestValidateParams {
nonce?: string
@@ -43,10 +43,6 @@ export type HttpDigestStrategyOptionsNoReq = HttpDigestStrategyOptionsBase & {
passReqToCallback?: false | undefined
}
-function md5(str: string, encoding: crypto.BinaryToTextEncoding = 'hex'): string {
- return crypto.createHash('md5').update(str).digest(encoding)
-}
-
function nonce(len: number): string {
const buf: string[] = []
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
@@ -141,13 +137,13 @@ export class HttpDigestStrategy extends PassportStrategy {
ha1 = (secret as any).ha1
} else {
// password en clair (peu probable)
- ha1 = md5(`${creds.username}:${creds.realm}:${String(secret)}`)
+ ha1 = genHash(`${creds.username}:${creds.realm}:${String(secret)}`)
}
} else if (algo === 'MD5-sess') {
// idem digest.js (note: nonce/cnonce init non gérés)
const base =
- typeof secret === 'object' && (secret as any).ha1 ? (secret as any).ha1 : md5(`${creds.username}:${creds.realm}:${String(secret)}`)
- ha1 = md5(`${base}:${creds.nonce}:${creds.cnonce}`)
+ typeof secret === 'object' && (secret as any).ha1 ? (secret as any).ha1 : genHash(`${creds.username}:${creds.realm}:${String(secret)}`)
+ ha1 = genHash(`${base}:${creds.nonce}:${creds.cnonce}`)
} else {
return this.fail(400 as any)
}
@@ -155,7 +151,7 @@ export class HttpDigestStrategy extends PassportStrategy {
// compute HA2
let ha2: string
if (!creds.qop || creds.qop === 'auth') {
- ha2 = md5(`${req.method}:${creds.uri}`)
+ ha2 = genHash(`${req.method}:${creds.uri}`)
} else if (creds.qop === 'auth-int') {
return this.error(new Error('auth-int not implemented'))
} else {
@@ -165,9 +161,9 @@ export class HttpDigestStrategy extends PassportStrategy {
// compute expected digest
let digest: string
if (!creds.qop) {
- digest = md5(`${ha1}:${creds.nonce}:${ha2}`)
+ digest = genHash(`${ha1}:${creds.nonce}:${ha2}`)
} else if (creds.qop === 'auth' || creds.qop === 'auth-int') {
- digest = md5(`${ha1}:${creds.nonce}:${creds.nc}:${creds.cnonce}:${creds.qop}:${ha2}`)
+ digest = genHash(`${ha1}:${creds.nonce}:${creds.nc}:${creds.cnonce}:${creds.qop}:${ha2}`)
} else {
return this.fail(400 as any)
}