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): resolve OIDC login collisions
johaven7a54b8eef46b
diff --git a/backend/src/authentication/providers/oidc/auth-oidc.constants.ts b/backend/src/authentication/providers/oidc/auth-oidc.constants.tsindex 249c66de..afbadb81 100644--- a/backend/src/authentication/providers/oidc/auth-oidc.constants.ts+++ b/backend/src/authentication/providers/oidc/auth-oidc.constants.ts@@ -1,3 +1,6 @@+export const OIDC_LOGIN_MAX_LENGTH = 255+export const OIDC_LOGIN_HASH_LENGTH = 12+export enum OAuthTokenEndpoint {ClientSecretPost = 'client_secret_post',ClientSecretBasic = 'client_secret_basic'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.tsindex ac723481..f151653d 100644--- a/backend/src/authentication/providers/oidc/auth-provider-oidc.service.spec.ts+++ b/backend/src/authentication/providers/oidc/auth-provider-oidc.service.spec.ts@@ -91,7 +91,7 @@ vi.mock('openid-client', () => {describe(AuthProviderOIDC.name, () => {let service: AuthProviderOIDClet usersManager: {- usersQueries: { bindExternalId: Mock }+ usersQueries: { bindExternalId: Mock; checkUserExists: Mock }findUser: MockfindUserByExternalIdOrEmail: MocklogUser: Mock@@ -124,7 +124,7 @@ describe(AuthProviderOIDC.name, () => {beforeAll(async () => {usersManager = {- usersQueries: { bindExternalId: vi.fn().mockResolvedValue(true) },+ usersQueries: { bindExternalId: vi.fn().mockResolvedValue(true), checkUserExists: vi.fn().mockResolvedValue(null) },findUser: vi.fn(),findUserByExternalIdOrEmail: vi.fn(),logUser: vi.fn(),@@ -156,6 +156,7 @@ describe(AuthProviderOIDC.name, () => {beforeEach(() => {vi.restoreAllMocks()vi.clearAllMocks()+ usersManager.usersQueries.checkUserExists.mockReset().mockResolvedValue(null);(service as any).config = null;(service as any).oidcConfig.security.supportPKCE = true;(service as any).oidcConfig.security.allowInsecureRequests = false@@ -363,12 +364,43 @@ describe(AuthProviderOIDC.name, () => {const result = await (service as any).processUserInfo(userInfo, userInfo.sub, '127.0.0.1')expect(adminUsersManager.createUserOrGuest).toHaveBeenCalledWith(- expect.objectContaining({ externalId: 'EXTERNAL-X', role: USER_ROLE.ADMINISTRATOR }),+ expect.objectContaining({ externalId: 'EXTERNAL-X', login: 'bob', role: USER_ROLE.ADMINISTRATOR }),USER_ROLE.ADMINISTRATOR)expect(result.role).toBe(USER_ROLE.ADMINISTRATOR)})+ it('adds a deterministic subject suffix when the initial OIDC login is already used', async () => {+ usersManager.findUserByExternalIdOrEmail.mockResolvedValue(null)+ usersManager.usersQueries.checkUserExists.mockResolvedValueOnce({ login: 'bob' })+ adminUsersManager.createUserOrGuest.mockResolvedValue({ id: 11, login: 'bob-e0274d686d67' })+ usersManager.fromUserId.mockResolvedValue({ id: 11, role: USER_ROLE.USER, login: 'bob-e0274d686d67', setFullName: vi.fn() } as any)+ const userInfo = { sub: 'EXTERNAL-X', email: '[email protected]', email_verified: true, preferred_username: 'bob' }++ await (service as any).processUserInfo(userInfo, userInfo.sub, '127.0.0.1')++ expect(usersManager.usersQueries.checkUserExists).toHaveBeenNthCalledWith(1, 'bob')+ expect(adminUsersManager.createUserOrGuest).toHaveBeenCalledWith(+ expect.objectContaining({ externalId: 'EXTERNAL-X', login: 'bob-e0274d686d67' }),+ USER_ROLE.USER+ )+ })++ it('truncates the initial login before adding the subject suffix', async () => {+ const baseLogin = 'a'.repeat(255)+ const expectedLogin = `${'a'.repeat(242)}-e0274d686d67`+ usersManager.findUserByExternalIdOrEmail.mockResolvedValue(null)+ usersManager.usersQueries.checkUserExists.mockResolvedValueOnce({ login: baseLogin })+ adminUsersManager.createUserOrGuest.mockResolvedValue({ id: 12, login: expectedLogin })+ usersManager.fromUserId.mockResolvedValue({ id: 12, role: USER_ROLE.USER, login: expectedLogin, setFullName: vi.fn() } as any)+ const userInfo = { sub: 'EXTERNAL-X', email: '[email protected]', email_verified: true, preferred_username: baseLogin }++ await (service as any).processUserInfo(userInfo, userInfo.sub, '127.0.0.1')++ expect(expectedLogin).toHaveLength(255)+ expect(adminUsersManager.createUserOrGuest).toHaveBeenCalledWith(expect.objectContaining({ login: expectedLogin }), USER_ROLE.USER)+ })+it('rejects OIDC profiles with unverified emails when verification is enabled', async () => {;(service as any).oidcConfig.security.requireVerifiedEmail = true@@ -493,6 +525,7 @@ describe(AuthProviderOIDC.name, () => {)expect(existingUser.login).toBe('alice')+ expect(usersManager.usersQueries.checkUserExists).not.toHaveBeenCalled()expect(adminUsersManager.updateUserOrGuest).not.toHaveBeenCalled()})diff --git a/backend/src/authentication/providers/oidc/auth-provider-oidc.service.ts b/backend/src/authentication/providers/oidc/auth-provider-oidc.service.tsindex efb8e526..fdbc57bd 100644--- a/backend/src/authentication/providers/oidc/auth-provider-oidc.service.ts+++ b/backend/src/authentication/providers/oidc/auth-provider-oidc.service.ts@@ -1,6 +1,7 @@import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'-import path from 'node:path'+import crypto from 'node:crypto'import fs from 'node:fs/promises'+import path from 'node:path'import { FastifyReply, FastifyRequest } from 'fastify'import {allowInsecureRequests,@@ -41,7 +42,7 @@ import { AuthProvider } from '../auth-providers.models'import { applyStorageQuotaToIdentity } from '../auth-providers.utils'import { OAuthDesktopCallBackURI, OAuthDesktopLoopbackPorts, OAuthDesktopPortParam } from './auth-oidc-desktop.constants'import type { AuthProviderOIDCConfig } from './auth-oidc.config'-import { OAuthCookie, OAuthCookieSettings, OAuthTokenEndpoint } from './auth-oidc.constants'+import { OAuthCookie, OAuthCookieSettings, OAuthTokenEndpoint, OIDC_LOGIN_HASH_LENGTH, OIDC_LOGIN_MAX_LENGTH } from './auth-oidc.constants'import { HttpService } from '@nestjs/axios'import { DownloadFileDto } from '../../../applications/files/dto/file-operations.dto'import { DownloadFile } from '../../../applications/files/utils/download-file'@@ -406,20 +407,7 @@ export class AuthProviderOIDC implements AuthProvider {externalId: string): Promise<UserModel> {if (user === null) {- // Create new user with a random password (required by the system but not used for OIDC login)- const userWithPassword = {- ...identity,- externalId,- password: generateShortUUID(24),- permissions: this.oidcConfig.options.autoCreatePermissions.join(',')- } as CreateUserDto & { externalId: string }- const createdUser = await this.adminUsersManager.createUserOrGuest(userWithPassword, identity.role)- const freshUser = await this.usersManager.fromUserId(createdUser.id)- if (!freshUser) {- this.logger.error({ tag: this.updateOrCreateUser.name, msg: `user was not found : ${createdUser.login} (${createdUser.id})` })- throw new HttpException('User not found', HttpStatus.NOT_FOUND)- }- return freshUser+ return this.createUser(identity, externalId)}// Check if user information has changed. The local login is initialized once and remains stable.@@ -457,6 +445,30 @@ export class AuthProviderOIDC implements AuthProvider {return user}+ private async createUser(identity: Omit<CreateUserDto, 'password'> & { password?: string }, externalId: string): Promise<UserModel> {+ let login = identity.login+ if (await this.usersManager.usersQueries.checkUserExists(login)) {+ const suffix = crypto.createHash('sha256').update(externalId).digest('hex').slice(0, OIDC_LOGIN_HASH_LENGTH)+ login = `${login.slice(0, OIDC_LOGIN_MAX_LENGTH - suffix.length - 1)}-${suffix}`+ }++ // A random password remains required by the local model but is not used for OIDC authentication.+ const userWithPassword = {+ ...identity,+ login,+ externalId,+ password: generateShortUUID(24),+ permissions: this.oidcConfig.options.autoCreatePermissions.join(',')+ } as CreateUserDto & { externalId: string }+ const createdUser = await this.adminUsersManager.createUserOrGuest(userWithPassword, identity.role)+ const freshUser = await this.usersManager.fromUserId(createdUser.id)+ if (!freshUser) {+ this.logger.error({ tag: this.createUser.name, msg: `user was not found : ${createdUser.login} (${createdUser.id})` })+ throw new HttpException('User not found', HttpStatus.NOT_FOUND)+ }+ return freshUser+ }+private async updatePictureUrl(user: UserModel, userInfo: UserInfoResponse): Promise<void> {const picture = userInfo.picturediff --git a/backend/src/authentication/providers/oidc/oidc.md b/backend/src/authentication/providers/oidc/oidc.mdindex ca9014c9..bdb21f20 100644--- a/backend/src/authentication/providers/oidc/oidc.md+++ b/backend/src/authentication/providers/oidc/oidc.md@@ -79,7 +79,7 @@ Unless specified otherwise, claims in this table are read from the UserInfo resp| UserInfo `sub` | Yes | Checked against the ID token subject unless `skipSubjectCheck` is enabled. || `email` | Yes | Trimmed, used for legacy account linking, and synchronized to the local profile. || `email_verified` | By default | Must be the boolean `true` when `requireVerifiedEmail` is enabled. |-| `preferred_username` | No | Initializes a new local login after trimming and lowercasing. |+| `preferred_username` | No | Supplies the trimmed and lowercased base for a new local login. || `given_name` / `family_name` | No | Synchronize the local first and last names. || `name` | No | Split into first and last names only when both structured name claims are absent. || `groups` / `roles` | No | Top-level arrays inspected for an exact `adminRoleOrGroup` match. |@@ -116,7 +116,7 @@ existing `externalId` values before users authenticate against the replacement pWhen `autoCreateUser` is enabled, a first successful login creates a local user with:-- the normalized `preferred_username`, or the email local-part, as `login`;+- the normalized `preferred_username`, or the email local-part, as the base `login`;- the required OIDC email;- the mapped first and last names;- the unchanged ID token `sub` as `externalId`;@@ -135,8 +135,11 @@ For an existing user, each successful OIDC login can synchronize:- avatar, when enabled.The local `login`, password, and permissions are not synchronized. In particular, `preferred_username` initializes the login but does not rename it on-later authentications. Automatic provisioning does not currently generate an alternative login when the derived value conflicts with an existing-unique local login.+later authentications.++OIDC does not guarantee that `preferred_username` is unique or stable. When the derived base login is already used, Sync-in appends a deterministic+lowercase hexadecimal SHA-256 suffix derived from the validated ID token `sub`; the raw subject is not exposed in the login. The base is truncated+when necessary to keep the generated login within 255 characters. The database unique index remains the final authority for the generated login.Profile update failures are logged without invalidating an otherwise successful OIDC authentication. Creation-time permissions are never reappliedto an existing user.@@ -238,4 +241,4 @@ existing IdP SSO session can authenticate the browser again without prompting fo- Public clients without a client secret are not exposed by the current validated configuration.- IdP tokens are not retained or refreshed; Sync-in issues and refreshes its own local tokens.- RP-initiated logout, front-channel logout, back-channel logout, and IdP token revocation are not implemented.-- Login renaming and automatic login collision resolution are not implemented.+- Login renaming is not implemented; the login assigned during OIDC account creation remains stable.diff --git a/environment/environment.dist.yaml b/environment/environment.dist.yamlindex e220b727..c2ec8f55 100755--- a/environment/environment.dist.yaml+++ b/environment/environment.dist.yaml@@ -209,7 +209,8 @@ auth:# Sync-in TOTP applies only to local password authentication.# Users are resolved by the OIDC `sub` first, then by email only when no external identity is linked yet.# The first successful email match stores `sub` as the user's external identity for subsequent logins.- # `preferred_username` initializes the local login for a new user but does not rename an existing local login.+ # `preferred_username` initializes the local login for a new user. A deterministic `sub`-based suffix resolves collisions.+ # The assigned local login remains stable on subsequent authentications.# issuerUrl: The URL of the OIDC provider's discovery endpoint# e.g.:# - Keycloak: https://auth.example.com/realms/my-realm