From 293cd95ba6f55b3729f2ea53a82522861be9aa40 Mon Sep 17 00:00:00 2001 From: xEsiah Date: Mon, 19 Oct 2026 12:08:23 +0200 Subject: [PATCH] fix(api): folder traversal for shared subfolders, rehome folders on user deletion - GET /folders: allow listing children of intermediate folders leading to a shared descendant (canTraverse), filter children in application code since MariaDB forbids correlated recursive CTEs - Admin user deletion: shared folders are transferred to their best permission holder (admin > write > read, oldest); unshared folders are soft-deleted with their subtree; a shared child whose parent disappears is moved to root; permissions and stars of the deleted account are cleaned up - CI: label runners as [self-hosted, cohaise-cloud] to match the new dedicated gitea-runner --- .github/workflows/deploy.yml | 2 +- .github/workflows/pr.yml | 2 +- .github/workflows/renovate.yml | 2 +- backend/src/access.ts | 52 +++++++++++++++++++ backend/src/routes/admin.ts | 91 +++++++++++++++++++++++++++++++++- backend/src/routes/folders.ts | 28 +++++++---- 6 files changed, 162 insertions(+), 15 deletions(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 4fa468c..fd0e5d8 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -18,7 +18,7 @@ concurrency: jobs: deploy: - runs-on: self-hosted + runs-on: [self-hosted, cohaise-cloud] steps: - name: Fetch latest code and rebuild env: diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 0004725..4a8924b 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -7,7 +7,7 @@ on: jobs: create-pr: - runs-on: self-hosted + runs-on: [self-hosted, cohaise-cloud] permissions: contents: write pull-requests: write diff --git a/.github/workflows/renovate.yml b/.github/workflows/renovate.yml index 6a854cb..81b3bbf 100644 --- a/.github/workflows/renovate.yml +++ b/.github/workflows/renovate.yml @@ -11,7 +11,7 @@ concurrency: jobs: renovate: - runs-on: self-hosted + runs-on: [self-hosted, cohaise-cloud] steps: - name: Mettre à jour les dépendances env: diff --git a/backend/src/access.ts b/backend/src/access.ts index f971506..006f9c6 100644 --- a/backend/src/access.ts +++ b/backend/src/access.ts @@ -101,6 +101,58 @@ export const canManageFolder = async ( return row !== null; }; +/** + * Verifie si l'utilisateur peut traverser un dossier pour atteindre un + * sous-dossier auquel il a acces. Un dossier est traversable s'il y a un + * acces direct OU s'il existe un descendant non supprime ayant un acces + * direct valide (proprietaire, permission nominative, ou descendant public). + * Cela n'accorde PAS d'acces au contenu des dossiers intermediaires. + */ +export const canTraverse = async ( + db: Db, + user: SessionUser, + folderId: string, +): Promise => { + // Acces direct au dossier + const direct = await db.one( + `SELECT 1 AS granted + FROM folders f + WHERE f.id = ? AND f.deleted_at IS NULL + AND ( f.owner_id = ? + OR f.access_type = 'public' + OR EXISTS ( SELECT 1 FROM folder_permissions fp + WHERE fp.folder_id = f.id AND fp.user_id = ? + AND fp.level IN ('read', 'write', 'admin') + AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) ) + LIMIT 1`, + [folderId, user.id, user.id], + ); + if (direct !== null) return true; + + // Verifie s'il existe un descendant avec acces direct valide + const descendant = await db.one( + `WITH RECURSIVE descendants AS ( + SELECT id, parent_id FROM folders WHERE parent_id = ? AND deleted_at IS NULL + UNION ALL + SELECT f.id, f.parent_id FROM folders f + JOIN descendants d ON f.parent_id = d.id + WHERE f.deleted_at IS NULL + ) + SELECT 1 AS granted + FROM descendants d + JOIN folders f2 ON f2.id = d.id AND f2.deleted_at IS NULL + WHERE f2.owner_id = ? + OR f2.access_type = 'public' + OR EXISTS ( SELECT 1 FROM folder_permissions fp + WHERE fp.folder_id = f2.id AND fp.user_id = ? + AND fp.level IN ('read', 'write', 'admin') + AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) + LIMIT 1`, + [folderId, user.id, user.id], + ); + return descendant !== null; +}; + const clientIp = (context: Context, trustProxy: boolean): string | null => sharedClientIp(context, trustProxy); diff --git a/backend/src/routes/admin.ts b/backend/src/routes/admin.ts index 4ba56c7..f59f904 100644 --- a/backend/src/routes/admin.ts +++ b/backend/src/routes/admin.ts @@ -123,6 +123,90 @@ const generatePasswordValue = (): string => { return out; }; +/** + * Reprise des dossiers d'un compte supprime. Un dossier partage (permission + * nominative active vers un autre compte actif) survit avec un nouveau + * proprietaire : le meilleur candidat par niveau (admin puis write puis read), + * le plus ancien en cas d'egalite. Un dossier sans partage disparait avec son + * sous-arbre, a la maniere de `DELETE /folders/:id`. Un enfant partage dont le + * parent disparait remonte a la racine ; il en va de meme pour les dossiers + * d'autres comptes instales sous un dossier supprime, qui ne doivent pas + * devenir orphelins. Les permissions detenues par le compte supprime sur les + * dossiers d'autrui sont retirees. + */ +const rehomeUserFolders = async (db: Db, userId: string): Promise<{ kept: number; deleted: number }> => { + const folders = await db.query<{ id: string; parent_id: string | null }>( + "SELECT id, parent_id FROM folders WHERE owner_id = ? AND deleted_at IS NULL AND is_system = 0", + [userId], + ); + if (folders.length === 0) return { kept: 0, deleted: 0 }; + + const ids = folders.map((folder) => folder.id); + const placeholders = ids.map(() => "?").join(","); + + // Meilleur candidat par dossier : permission non expiree vers un compte actif. + const candidates = await db.query<{ + folder_id: string; + user_id: string; + level: string; + created_at: string; + }>( + `SELECT fp.folder_id, fp.user_id, fp.level, fp.created_at + FROM folder_permissions fp + JOIN users u ON u.id = fp.user_id AND u.deleted_at IS NULL AND u.is_active = 1 + WHERE fp.folder_id IN (${placeholders}) + AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) + ORDER BY FIELD(fp.level, 'admin', 'write', 'read'), fp.created_at ASC`, + [...ids], + ); + + const newOwner = new Map(); + for (const row of candidates) { + if (!newOwner.has(row.folder_id)) newOwner.set(row.folder_id, row.user_id); + } + + const owned = new Map(folders.map((folder) => [folder.id, folder.parent_id])); + const keepIds = [...newOwner.keys()]; + const deleteIds = ids.filter((id) => !newOwner.has(id)); + + await db.transaction(async (connection) => { + for (const [id, owner] of newOwner) { + const parentId = owned.get(id) ?? null; + // Parent supprime avec le compte : l'enfant partage remonte a la racine. + const parentGone = parentId !== null && owned.has(parentId) && !newOwner.has(parentId); + await connection.execute( + "UPDATE folders SET owner_id = ?, parent_id = ? WHERE id = ?", + [owner, parentGone ? null : parentId, id], + ); + } + + if (deleteIds.length > 0) { + const delPh = deleteIds.map(() => "?").join(","); + // Dossiers d'autres comptes installes sous un dossier supprime : a la racine. + await connection.execute( + `UPDATE folders SET parent_id = NULL + WHERE parent_id IN (${delPh}) AND deleted_at IS NULL + AND owner_id <> ? AND id NOT IN (${keepIds.map(() => "?").join(",") || "''"})`, + [...deleteIds, userId, ...(keepIds.length > 0 ? keepIds : [])], + ); + await connection.execute( + `UPDATE folders SET deleted_at = UTC_TIMESTAMP() WHERE id IN (${delPh}) AND deleted_at IS NULL`, + deleteIds, + ); + await connection.execute( + `UPDATE files SET deleted_at = UTC_TIMESTAMP() WHERE folder_id IN (${delPh}) AND deleted_at IS NULL`, + deleteIds, + ); + } + + // Permissions du compte supprime sur les dossiers d'autrui. + await connection.execute("DELETE FROM folder_permissions WHERE user_id = ?", [userId]); + await connection.execute("DELETE FROM user_file_stars WHERE user_id = ?", [userId]); + }); + + return { kept: keepIds.length, deleted: deleteIds.length }; +}; + export const registerAdminRoutes = (app: App, db: Db, config: Config): void => { app.use("/api/cloud/admin/*", attachUser(db)); app.use("/api/cloud/admin", attachUser(db)); @@ -317,8 +401,13 @@ export const registerAdminRoutes = (app: App, db: Db, config: Config): void => { [id], ); if (result.affectedRows === 0) throw AppError.notFound("Compte introuvable."); + + // Avant la reprise : les dossiers partages trouvent un nouveau proprietaire, + // les autres disparaissent avec leur sous-arbre. + const rehomed = await rehomeUserFolders(db, id); + await db.exec("UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ?", [id]); - return context.json({ ok: true }); + return context.json({ ok: true, folders: rehomed }); }); app.post("/api/cloud/admin/users/:id/reset-password", requireAuth, async (context) => { diff --git a/backend/src/routes/folders.ts b/backend/src/routes/folders.ts index c3be016..ff6e46f 100644 --- a/backend/src/routes/folders.ts +++ b/backend/src/routes/folders.ts @@ -10,7 +10,7 @@ import { type Config, type Db, } from "../lib/index.js"; -import { audit, canManageFolder, canRead, canWrite } from "../access.js"; +import { audit, canManageFolder, canTraverse, canWrite } from "../access.js"; const uuid = z .string() @@ -115,8 +115,8 @@ export const registerFolderRoutes = (app: App, db: Db, config: Config): void => } if (parentId !== null) { - // Contre l'IDOR : on ne liste un dossier que si la session y a acces. - if (!(await canRead(db, user, parentId))) { + // Permet la traversée vers un sous-dossier partage. + if (!(await canTraverse(db, user, parentId))) { throw AppError.notFound("Dossier introuvable."); } } @@ -125,17 +125,23 @@ export const registerFolderRoutes = (app: App, db: Db, config: Config): void => `${SELECT_FOLDER} WHERE f.deleted_at IS NULL AND (f.parent_id <=> ?) - AND ( ? = 1 - OR f.owner_id = ? - OR f.access_type = 'public' - OR EXISTS ( SELECT 1 FROM folder_permissions fp - WHERE fp.folder_id = f.id AND fp.user_id = ? - AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) ) ORDER BY f.name`, - [parentId, 0, user.id, user.id], + [parentId], ); - return context.json({ parentId, folders: rows.map(publicFolder) }); + // Un enfant est visible s'il est lisible directement ou s'il mene a un partage. + const visible: FolderRow[] = []; + for (const row of rows) { + if ( + user.role_slug === "admin" || + row.owner_id === user.id || + (await canTraverse(db, user, row.id)) + ) { + visible.push(row); + } + } + + return context.json({ parentId, folders: visible.map(publicFolder) }); }); app.post(