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(auth): WebDAV basic auth fails with ":" in password (#104)
Johan Legrand9671b71e5a4f
diff --git a/backend/src/authentication/guards/auth-basic.guard.spec.ts b/backend/src/authentication/guards/auth-basic.guard.spec.tsindex 4126cf24..6a3192b9 100644--- a/backend/src/authentication/guards/auth-basic.guard.spec.ts+++ b/backend/src/authentication/guards/auth-basic.guard.spec.ts@@ -83,6 +83,24 @@ describe(AuthBasicGuard.name, () => {expect(userTest.password).toBeUndefined()})+ it('should validate the user authentication with password containing colon', async () => {+ const passwordWithColon = 'pass:word:123'+ const userWithColonPassword = new UserModel({ ...generateUserTest(), password: passwordWithColon }, false)+ const encodedAuthWithColon = Buffer.from(`${userWithColonPassword.login}:${passwordWithColon}`).toString('base64')++ authMethod.validateUser = jest.fn().mockImplementation((login: string, password: string) => {+ expect(login).toBe(userWithColonPassword.login)+ expect(password).toBe(passwordWithColon)+ return userWithColonPassword+ })+ context.switchToHttp().getRequest.mockReturnValue({+ raw: { user: '' },+ headers: { authorization: `Basic ${encodedAuthWithColon}` }+ })+ expect(await authBasicGuard.canActivate(context)).toBe(true)+ expect(userWithColonPassword.password).toBeUndefined()+ })+it('should validate the user authentication with cache', async () => {cache.get = jest.fn().mockReturnValueOnce(userTest)context.switchToHttp().getRequest.mockReturnValue({diff --git a/backend/src/authentication/guards/auth-basic.strategy.ts b/backend/src/authentication/guards/auth-basic.strategy.tsindex 86bf5b51..98813ccb 100644--- a/backend/src/authentication/guards/auth-basic.strategy.ts+++ b/backend/src/authentication/guards/auth-basic.strategy.ts@@ -9,15 +9,15 @@ import { AbstractStrategy, PassportStrategy } from '@nestjs/passport'import { instanceToPlain, plainToInstance } from 'class-transformer'import { FastifyRequest } from 'fastify'import { PinoLogger } from 'nestjs-pino'-import { BasicStrategy } from 'passport-http'import { UserModel } from '../../applications/users/models/user.model'import { SERVER_NAME } from '../../common/shared'import { Cache } from '../../infrastructure/cache/services/cache.service'import { AUTH_SCOPE } from '../constants/scope'import { AuthMethod } from '../models/auth-method'+import { HttpBasicStrategy } from './implementations/http-basic.strategy'@Injectable()-export class AuthBasicStrategy extends PassportStrategy(BasicStrategy, 'basic') implements AbstractStrategy {+export class AuthBasicStrategy extends PassportStrategy(HttpBasicStrategy, 'basic') implements AbstractStrategy {private readonly CACHE_TTL = 900private readonly CACHE_KEY_PREFIX = 'auth-webdav'@@ -41,7 +41,7 @@ export class AuthBasicStrategy extends PassportStrategy(BasicStrategy, 'basic')}if (userFromCache !== undefined) {// cached- // warning: plainToInstance do not use constructor to instantiate class+ // warning: plainToInstance do not use constructor to instantiate the classreturn plainToInstance(UserModel, userFromCache)}const userFromDB: UserModel = await this.authMethod.validateUser(loginOrEmail, password, req.ip, AUTH_SCOPE.WEBDAV)diff --git a/backend/src/authentication/guards/auth-digest.strategy.ts b/backend/src/authentication/guards/auth-digest.strategy.tsindex 2a308629..28872a40 100644--- a/backend/src/authentication/guards/auth-digest.strategy.ts+++ b/backend/src/authentication/guards/auth-digest.strategy.ts@@ -7,21 +7,42 @@// import { Injectable } from '@nestjs/common'// import { PassportStrategy } from '@nestjs/passport'// import { PinoLogger } from 'nestjs-pino'-// import { DigestStrategy, DigestStrategyOptions } from 'passport-http'-// import { SERVER_NAME } from '../../app.constants'-// import { AuthManager } from '../services/auth-manager.service'+// import { SERVER_NAME } from '../../common/shared'+//+// import { HttpDigestStrategy } from './implementations/http-digest.strategy'//// @Injectable()-// export class AuthDigestStrategy extends PassportStrategy(DigestStrategy, 'digest') {-// constructor(-// private authManager: AuthManager,-// private readonly logger: PinoLogger-// ) {-// super({ realm: SERVER_NAME } satisfies DigestStrategyOptions)+// export class AuthDigestStrategy extends PassportStrategy(HttpDigestStrategy, 'digest') {+// constructor(private readonly logger: PinoLogger) {+// super({+// realm: SERVER_NAME,+// // Recommended options for RFC-compliant Digest (required for security)+// qop: 'auth',+// algorithm: 'MD5'+// // Optional anti-replay validation hook+// // validate: (params, done) => done(null, true),+// })// }//-// validate(loginOrEmail: string) {+// async validate(loginOrEmail: string) {+// loginOrEmail = loginOrEmail.trim()+// this.logger.assign({ user: loginOrEmail })+//+// // ⚠️ TO ADAPT: Digest authentication requires a server-side secret:+// // - ideally a stored { ha1 } value (HA1 = MD5(username:realm:password))+// // - otherwise the clear-text "password" (less secure, but possible)+// //// // return [loginOrEmail, { ha1: '4befe40c6af915eca11de84be07a1f21' }]-// return [loginOrEmail, 'password']+// // return [loginOrEmail, 'password']+//+// // Method to get digest secret+// const { user, ha1, password } = getDigestSecret(loginOrEmail, SERVER_NAME)+//+// if (!user) return null+//+// if (ha1) return [user, { ha1 }]+// if (password) return [user, password]+//+// return null// }// }diff --git a/backend/src/authentication/guards/implementations/http-basic.strategy.ts b/backend/src/authentication/guards/implementations/http-basic.strategy.tsnew file mode 100644index 00000000..1a9ab7b9--- /dev/null+++ b/backend/src/authentication/guards/implementations/http-basic.strategy.ts@@ -0,0 +1,91 @@+/*+ * 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 { Strategy as PassportStrategy } from 'passport-strategy'++export type BasicVerifyCallback = (err?: any, user?: any) => void++export type BasicVerifyFunction = (userid: string, password: string, done: BasicVerifyCallback) => void++export type BasicVerifyFunctionWithRequest = (req: any, userid: string, password: string, done: BasicVerifyCallback) => void++function splitFirst(str: string, sep: string): [string] | [string, string] {+ const i = str.indexOf(sep)+ if (i < 0) return [str]+ return [str.substring(0, i), str.substring(i + 1)]+}++export interface HttpBasicStrategyOptions {+ realm?: string+ passReqToCallback?: boolean+}++/**+ * Pure HTTP Basic authentication strategy+ **/+export class HttpBasicStrategy extends PassportStrategy {+ name = 'basic'++ private readonly verify: BasicVerifyFunction | BasicVerifyFunctionWithRequest+ private readonly realm: string+ private readonly passReqToCallback: boolean++ constructor(options: HttpBasicStrategyOptions = {}, verify: BasicVerifyFunction | BasicVerifyFunctionWithRequest) {+ super()++ if (!verify) {+ throw new TypeError('HttpBasicStrategy requires a verify callback')+ }++ this.verify = verify+ this.realm = options.realm ?? 'Sync-in'+ this.passReqToCallback = !!options.passReqToCallback+ }++ authenticate(req: any): void {+ const authorization: string | undefined = req?.headers?.authorization+ if (!authorization) {+ return this.fail(this.challenge(), 401)+ }++ const parts = authorization.split(' ')+ if (parts.length !== 2) {+ return this.fail(400)+ }++ if (!/^Basic$/i.test(parts[0])) {+ return this.fail(this.challenge(), 401)+ }++ let decoded: string+ try {+ decoded = Buffer.from(parts[1], 'base64').toString()+ } catch {+ return this.fail(400)+ }++ const [userid, password] = splitFirst(decoded, ':')+ if (password === undefined) {+ return this.fail(400)+ }++ const verified: BasicVerifyCallback = (err, user) => {+ if (err) return this.error(err)+ if (!user) return this.fail(this.challenge(), 401)+ return this.success(user)+ }++ if (this.passReqToCallback) {+ ;(this.verify as BasicVerifyFunctionWithRequest)(req, userid, password, verified)+ } else {+ ;(this.verify as BasicVerifyFunction)(userid, password, verified)+ }+ }++ private challenge(): string {+ return `Basic realm="${this.realm}"`+ }+}diff --git a/backend/src/authentication/guards/implementations/http-digest.strategy.ts b/backend/src/authentication/guards/implementations/http-digest.strategy.tsnew file mode 100644index 00000000..ecc85cfd--- /dev/null+++ b/backend/src/authentication/guards/implementations/http-digest.strategy.ts@@ -0,0 +1,212 @@+/*+ * 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 crypto from 'node:crypto'+import { Strategy as PassportStrategy } from 'passport-strategy'++export interface DigestValidateParams {+ nonce?: string+ cnonce?: string+ nc?: string+ opaque?: string+}++export type DigestValidateCallback = (err?: any, valid?: boolean) => void++// ⚠️ verify (secret callback) : on attend un "user container" qui contient aussi le secret+export type DigestVerifyCallback = (err?: any, result?: any) => void++export type DigestVerifyFunction = (username: string, done: DigestVerifyCallback) => void+export type DigestVerifyFunctionWithRequest = (req: any, username: string, done: DigestVerifyCallback) => void++export type DigestSecret =+ | string // password en clair (rare)+ | { ha1: string } // recommandé : HA1 = MD5(username:realm:password)++export interface DigestVerifyResult {+ user: any+ secret: DigestSecret+}++export interface HttpDigestStrategyOptionsBase {+ realm?: string+ domain?: string | string[]+ opaque?: string+ algorithm?: 'MD5' | 'MD5-sess'+ qop?: ('auth' | 'auth-int')[] | 'auth' | 'auth-int'+ // optionnel : anti-replay+ validate?: (params: DigestValidateParams, done: DigestValidateCallback) => void+}++export type HttpDigestStrategyOptionsWithReq = HttpDigestStrategyOptionsBase & {+ passReqToCallback: true+}++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'+ const charlen = chars.length+ for (let i = 0; i < len; ++i) {+ buf.push(chars[(Math.random() * charlen) | 0])+ }+ return buf.join('')+}++// parsing identique à digest.js+function parse(params: string): Record<string, string> {+ const opts: Record<string, string> = {}+ const tokens = params.split(/,(?=(?:[^"]|"[^"]*")*$)/)+ for (const token of tokens) {+ const m = /(\w+)=["]?([^"]+)["]?$/.exec(token)+ if (m) opts[m[1]] = m[2]+ }+ return opts+}++export class HttpDigestStrategy extends PassportStrategy {+ name = 'digest'++ private readonly realm: string+ private readonly domain?: string[]+ private readonly opaque?: string+ private readonly algorithm?: 'MD5' | 'MD5-sess'+ private readonly qop?: ('auth' | 'auth-int')[]+ private readonly passReqToCallback: boolean+ private readonly validateCb?: (params: DigestValidateParams, done: DigestValidateCallback) => void++ private readonly verify: DigestVerifyFunction | DigestVerifyFunctionWithRequest++ // overloads typés selon passReqToCallback+ constructor(options: HttpDigestStrategyOptionsWithReq, verify: DigestVerifyFunctionWithRequest)+ constructor(options?: HttpDigestStrategyOptionsNoReq, verify?: DigestVerifyFunction)+ constructor(+ options: HttpDigestStrategyOptionsWithReq | HttpDigestStrategyOptionsNoReq = {},+ verify?: DigestVerifyFunction | DigestVerifyFunctionWithRequest+ ) {+ super()+ if (!verify) throw new Error('HTTP Digest authentication strategy requires a secret function')++ this.verify = verify+ this.realm = options.realm ?? 'Users'++ if (options.domain) this.domain = Array.isArray(options.domain) ? options.domain : [options.domain]+ this.opaque = options.opaque+ this.algorithm = options.algorithm+ this.qop = options.qop ? (Array.isArray(options.qop) ? options.qop : [options.qop]) : undefined++ this.validateCb = options.validate+ this.passReqToCallback = (options as HttpDigestStrategyOptionsWithReq).passReqToCallback === true+ }++ authenticate(req: any): void {+ const authorization: string | undefined = req?.headers?.authorization+ if (!authorization) {+ return this.fail(this.challenge(), 401)+ }++ const parts = authorization.split(' ')+ if (parts.length < 2) return this.fail(400 as any)++ const scheme = parts[0]+ const params = parts.slice(1).join(' ')+ if (!/Digest/i.test(scheme)) {+ return this.fail(this.challenge(), 401)+ }++ const creds = parse(params)+ if (Object.keys(creds).length === 0) return this.fail(400 as any)+ if (!creds.username) return this.fail(this.challenge(), 401)++ // Même check que digest.js : req.url doit matcher creds.uri+ // (en Fastify, req.url inclut la querystring, ce qui est généralement OK)+ if (req.url !== creds.uri) return this.fail(400 as any)++ const verified: DigestVerifyCallback = (err, result) => {+ if (err) return this.error(err)+ if (!result || !result.user) return this.fail(this.challenge(), 401)++ const { user, secret } = result as DigestVerifyResult+ if (!secret) return this.fail(400 as any)++ // compute HA1+ let ha1: string+ const algo = creds.algorithm || 'MD5'+ if (algo === 'MD5') {+ if (typeof secret === 'object' && (secret as any).ha1) {+ ha1 = (secret as any).ha1+ } else {+ // password en clair (peu probable)+ ha1 = md5(`${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}`)+ } else {+ return this.fail(400 as any)+ }++ // compute HA2+ let ha2: string+ if (!creds.qop || creds.qop === 'auth') {+ ha2 = md5(`${req.method}:${creds.uri}`)+ } else if (creds.qop === 'auth-int') {+ return this.error(new Error('auth-int not implemented'))+ } else {+ return this.fail(400 as any)+ }++ // compute expected digest+ let digest: string+ if (!creds.qop) {+ digest = md5(`${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}`)+ } else {+ return this.fail(400 as any)+ }++ if (creds.response !== digest) {+ return this.fail(this.challenge(), 401)+ }++ if (this.validateCb) {+ return this.validateCb({ nonce: creds.nonce, cnonce: creds.cnonce, nc: creds.nc, opaque: creds.opaque }, (e, ok) => {+ if (e) return this.error(e)+ if (!ok) return this.fail(this.challenge(), 401)+ return this.success(user)+ })+ }++ return this.success(user)+ }++ if (this.passReqToCallback) {+ ;(this.verify as DigestVerifyFunctionWithRequest)(req, creds.username, verified)+ } else {+ ;(this.verify as DigestVerifyFunction)(creds.username, verified)+ }+ }++ private challenge(): string {+ let challenge = `Digest realm="${this.realm}"`+ if (this.domain) challenge += `, domain="${this.domain.join(' ')}"`+ challenge += `, nonce="${nonce(32)}"`+ if (this.opaque) challenge += `, opaque="${this.opaque}"`+ if (this.algorithm) challenge += `, algorithm=${this.algorithm}`+ if (this.qop) challenge += `, qop="${this.qop.join(',')}"`+ return challenge+ }+}