BlueGit

timfa filemanager

Files

filemanager / tests / files.routes.test.js

files.routes.test.js

pip
timfa Tim Falken · pushed by timfa · 6 months ago
aefbcaaa History
files.routes.test.js 17.6 KiB Download Raw
1'use strict';
2
3const express = require('express');
4const fs = require('fs');
5const http = require('http');
6const os = require('os');
7const path = require('path');
8const { once } = require('events');
9
10let mockPaths = [];
11let mockRootAliases = {};
12let mockUser = { username: 'admin', isAdmin: true, permissions: {} };
13let mockThumbPath = null;
14let mockFolderImages = [];
15let mockFolderIconFile = null;
16let lastFolderIconAssignment = undefined;
17
18jest.mock('../server/db', () =>
19{
20 const { Database } = require('node-sqlite3-wasm');
21 let db;
22 function getDb ()
23 {
24 if (!db)
25 {
26 db = new Database(':memory:');
27 db.exec(`
28 CREATE TABLE IF NOT EXISTS users (
29 id INTEGER PRIMARY KEY AUTOINCREMENT,
30 username TEXT UNIQUE NOT NULL,
31 password_hash TEXT NOT NULL,
32 is_admin INTEGER NOT NULL DEFAULT 0,
33 permissions TEXT NOT NULL DEFAULT '{}'
34 );
35 CREATE TABLE IF NOT EXISTS file_meta (
36 file_path TEXT PRIMARY KEY,
37 uploader TEXT NOT NULL DEFAULT '',
38 downloaders TEXT NOT NULL DEFAULT '[]'
39 );
40 `);
41 }
42 return db;
43 }
44 return { getDb, initDb: getDb };
45});
46
47jest.mock('../server/config', () => ({
48 loadConfig: () => ({ port: 3000, paths: [...mockPaths], rootAliases: { ...mockRootAliases } }),
49 saveConfig: (config) =>
50 {
51 mockPaths = [...(config.paths || [])];
52 mockRootAliases = { ...(config.rootAliases || {}) };
53 },
54 getEffectivePaths: (paths) => paths,
55 getAllowedRoot: (targetPath, roots) =>
56 {
57 const path = require('path');
58 const absTarget = path.resolve(String(targetPath || ''));
59 return roots.find((root) =>
60 {
61 const absRoot = path.resolve(root);
62 return absTarget === absRoot || absTarget.startsWith(absRoot + path.sep);
63 }) || null;
64 },
65}));
66
67jest.mock('../server/auth', () => ({
68 requireAuth: (req, res, next) => { req.user = mockUser; next(); },
69}));
70
71jest.mock('../server/thumbnail-cache', () => ({
72 getCachedThumbnailInfo: async () =>
73 {
74 if (!mockThumbPath) return null;
75 return { thumbPath: mockThumbPath, contentType: 'image/webp' };
76 },
77 getImagesWithThumbnailsInDir: async () => mockFolderImages.slice(),
78 getFolderIconSourceFile: async () => mockFolderIconFile,
79 setFolderIconAssignment: async (folderPath, imagePath) =>
80 {
81 lastFolderIconAssignment = { folderPath, imagePath };
82 },
83}));
84
85const filesRoutes = require('../server/routes/files');
86const { getDb } = require('../server/db');
87
88let server;
89let baseUrl;
90let rootDir;
91
92beforeAll(async () =>
93{
94 rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-files-routes-'));
95 mockPaths = [rootDir];
96
97 const app = express();
98 app.use(express.json());
99 app.use('/api/files', filesRoutes);
100 app.use((err, req, res, next) =>
101 {
102 res.status(err.status || 500).json({ error: err.message || 'Internal error' });
103 });
104
105 server = http.createServer(app);
106 server.listen(0);
107 await once(server, 'listening');
108 baseUrl = `http://127.0.0.1:${server.address().port}`;
109});
110
111afterAll(() =>
112{
113 server.close();
114 fs.rmSync(rootDir, { recursive: true, force: true });
115});
116
117beforeEach(() =>
118{
119 fs.rmSync(rootDir, { recursive: true, force: true });
120 fs.mkdirSync(rootDir, { recursive: true });
121 mockRootAliases = {};
122 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
123 mockThumbPath = null;
124 mockFolderImages = [];
125 mockFolderIconFile = null;
126 lastFolderIconAssignment = undefined;
127 const db = getDb();
128 db.prepare('DELETE FROM file_meta').run([]);
129 db.prepare('DELETE FROM users').run([]);
130});
131
132function req (method, routePath, body)
133{
134 const payload = body ? JSON.stringify(body) : undefined;
135 return new Promise((resolve, reject) =>
136 {
137 const request = http.request(baseUrl + routePath, {
138 method,
139 headers: {
140 'Content-Type': 'application/json',
141 ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}),
142 },
143 }, res =>
144 {
145 let data = '';
146 res.on('data', chunk => data += chunk);
147 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));
148 });
149 request.on('error', reject);
150 if (payload) request.write(payload);
151 request.end();
152 });
153}
154
155function reqRaw (method, routePath)
156{
157 return new Promise((resolve, reject) =>
158 {
159 const request = http.request(baseUrl + routePath, { method }, res =>
160 {
161 const chunks = [];
162 res.on('data', chunk => chunks.push(Buffer.from(chunk)));
163 res.on('end', () => resolve({
164 status: res.statusCode,
165 headers: res.headers,
166 body: Buffer.concat(chunks),
167 }));
168 });
169 request.on('error', reject);
170 request.end();
171 });
172}
173
174describe('POST /api/files/move', () =>
175{
176 test('moves a file into another folder and rewrites metadata', async () =>
177 {
178 const from = path.join(rootDir, 'alpha.txt');
179 const toDir = path.join(rootDir, 'folder');
180 fs.writeFileSync(from, 'hello');
181 fs.mkdirSync(toDir);
182
183 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
184 .run([from, 'admin', '["alice"]']);
185
186 const { status, body } = await req('POST', '/api/files/move', { from, toDir });
187
188 expect(status).toBe(200);
189 expect(body.ok).toBe(true);
190 expect(fs.existsSync(from)).toBe(false);
191 expect(fs.existsSync(path.join(toDir, 'alpha.txt'))).toBe(true);
192
193 const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?').get([path.join(toDir, 'alpha.txt')]);
194 expect(meta).toMatchObject({ uploader: 'admin', downloaders: '["alice"]' });
195 });
196
197 test('moves a folder into another folder and rewrites descendant metadata', async () =>
198 {
199 const fromDir = path.join(rootDir, 'src-folder');
200 const nestedFile = path.join(fromDir, 'child.txt');
201 const toDir = path.join(rootDir, 'dest-folder');
202 fs.mkdirSync(fromDir);
203 fs.mkdirSync(toDir);
204 fs.writeFileSync(nestedFile, 'hello');
205
206 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
207 .run([nestedFile, 'admin', '[]']);
208
209 const { status } = await req('POST', '/api/files/move', { from: fromDir, toDir });
210
211 expect(status).toBe(200);
212 expect(fs.existsSync(fromDir)).toBe(false);
213 expect(fs.existsSync(path.join(toDir, 'src-folder', 'child.txt'))).toBe(true);
214
215 const movedMeta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?')
216 .get([path.join(toDir, 'src-folder', 'child.txt')]);
217 expect(movedMeta).toBeTruthy();
218 });
219
220 test('rejects moving a folder into itself', async () =>
221 {
222 const fromDir = path.join(rootDir, 'src-folder');
223 const childDir = path.join(fromDir, 'child');
224 fs.mkdirSync(childDir, { recursive: true });
225
226 const { status, body } = await req('POST', '/api/files/move', { from: fromDir, toDir: childDir });
227
228 expect(status).toBe(400);
229 expect(body.error).toMatch(/folder into itself/i);
230 });
231
232 test('overwrites an existing destination when conflict strategy is overwrite', async () =>
233 {
234 const sourceFile = path.join(rootDir, 'source.txt');
235 const destinationDir = path.join(rootDir, 'dest');
236 fs.mkdirSync(destinationDir);
237 fs.writeFileSync(sourceFile, 'new-content');
238 fs.writeFileSync(path.join(destinationDir, 'source.txt'), 'old-content');
239
240 const { status, body } = await req('POST', '/api/files/move', {
241 from: sourceFile,
242 toDir: destinationDir,
243 conflict: 'overwrite',
244 });
245
246 expect(status).toBe(200);
247 expect(body.conflictResolution).toBe('overwrite');
248 expect(fs.existsSync(sourceFile)).toBe(false);
249 expect(fs.readFileSync(path.join(destinationDir, 'source.txt'), 'utf8')).toBe('new-content');
250 });
251
252 test('renames destination when conflict strategy is rename', async () =>
253 {
254 const sourceFile = path.join(rootDir, 'report.txt');
255 const destinationDir = path.join(rootDir, 'dest');
256 fs.mkdirSync(destinationDir);
257 fs.writeFileSync(sourceFile, 'latest');
258 fs.writeFileSync(path.join(destinationDir, 'report.txt'), 'existing');
259
260 const { status, body } = await req('POST', '/api/files/move', {
261 from: sourceFile,
262 toDir: destinationDir,
263 conflict: 'rename',
264 });
265
266 expect(status).toBe(200);
267 expect(body.conflictResolution).toBe('rename');
268 expect(path.basename(body.path)).toBe('report (1).txt');
269 expect(fs.readFileSync(body.path, 'utf8')).toBe('latest');
270 expect(fs.readFileSync(path.join(destinationDir, 'report.txt'), 'utf8')).toBe('existing');
271 });
272});
273
274describe('root alias endpoints', () =>
275{
276 test('GET /api/files/roots returns alias label and original name', async () =>
277 {
278 mockRootAliases = { [path.resolve(rootDir)]: 'Workspace' };
279
280 const { status, body } = await req('GET', '/api/files/roots');
281
282 expect(status).toBe(200);
283 expect(body.roots).toHaveLength(1);
284 expect(body.roots[0]).toMatchObject({
285 path: rootDir,
286 label: 'Workspace',
287 alias: 'Workspace',
288 originalName: path.basename(rootDir),
289 });
290 });
291
292 test('POST /api/files/root-alias stores alias without renaming filesystem path', async () =>
293 {
294 const originalBase = path.basename(rootDir);
295 const { status, body } = await req('POST', '/api/files/root-alias', {
296 rootPath: rootDir,
297 alias: 'Shared Files',
298 });
299
300 expect(status).toBe(200);
301 expect(body.ok).toBe(true);
302 expect(body.root).toMatchObject({
303 path: rootDir,
304 label: 'Shared Files',
305 alias: 'Shared Files',
306 originalName: originalBase,
307 });
308 expect(fs.existsSync(rootDir)).toBe(true);
309
310 const afterRoots = await req('GET', '/api/files/roots');
311 expect(afterRoots.status).toBe(200);
312 expect(afterRoots.body.roots[0].label).toBe('Shared Files');
313 expect(afterRoots.body.roots[0].originalName).toBe(originalBase);
314 });
315
316 test('POST /api/files/root-alias rejects non-root paths', async () =>
317 {
318 const nested = path.join(rootDir, 'sub');
319 fs.mkdirSync(nested, { recursive: true });
320
321 const { status } = await req('POST', '/api/files/root-alias', {
322 rootPath: nested,
323 alias: 'Nested',
324 });
325
326 expect(status).toBe(400);
327 });
328});
329
330describe('GET /api/files/thumbnail', () =>
331{
332 test('returns 404 while cached thumbnail is not ready', async () =>
333 {
334 const source = path.join(rootDir, 'photo.jpg');
335 fs.writeFileSync(source, 'not-an-image');
336
337 const { status, body } = await req('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`);
338 expect(status).toBe(404);
339 expect(body.error).toMatch(/not ready/i);
340 });
341
342 test('serves cached thumbnail file when available', async () =>
343 {
344 const source = path.join(rootDir, 'photo.jpg');
345 const thumb = path.join(rootDir, 'photo-thumb.webp');
346 fs.writeFileSync(source, 'not-an-image');
347 fs.writeFileSync(thumb, 'webp-bytes');
348 mockThumbPath = thumb;
349
350 const response = await reqRaw('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`);
351 expect(response.status).toBe(200);
352 expect(String(response.headers['content-type'] || '')).toContain('image/webp');
353 expect(response.body.toString('utf8')).toBe('webp-bytes');
354 });
355});
356
357describe('GET /api/files/root-access', () =>
358{
359 test('returns users with R/R+W modes for an exact root path', async () =>
360 {
361 const label = path.basename(rootDir);
362 const db = getDb();
363 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
364 .run(['admin', 'x', 1, '{}']);
365 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
366 .run(['alice', 'x', 0, JSON.stringify({ [label]: { read: true, write: false } })]);
367 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
368 .run(['bob', 'x', 0, JSON.stringify({ [label]: { read: true, write: true } })]);
369 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
370 .run(['charlie', 'x', 0, JSON.stringify({ other: { read: true, write: false } })]);
371
372 const { status, body } = await req('GET', `/api/files/root-access?rootPath=${encodeURIComponent(rootDir)}`);
373 expect(status).toBe(200);
374 expect(body.root).toMatchObject({ path: rootDir, originalName: label });
375 expect(body.users).toEqual([
376 { username: 'admin', mode: 'R+W' },
377 { username: 'bob', mode: 'R+W' },
378 { username: 'alice', mode: 'R' },
379 ]);
380 });
381
382 test('rejects non-exact nested root paths', async () =>
383 {
384 const nested = path.join(rootDir, 'sub');
385 fs.mkdirSync(nested, { recursive: true });
386
387 const { status } = await req('GET', `/api/files/root-access?rootPath=${encodeURIComponent(nested)}`);
388 expect(status).toBe(400);
389 });
390});
391
392describe('folder icon endpoints', () =>
393{
394 test('GET /api/files/folder-images returns images that have cached thumbnails', async () =>
395 {
396 const subDir = path.join(rootDir, 'photos');
397 fs.mkdirSync(subDir);
398 const imgPath = path.join(subDir, 'a.jpg');
399 fs.writeFileSync(imgPath, 'img');
400
401 mockFolderImages = [{ filePath: imgPath, thumbRelPath: 'thumbs/a.jpg.webp' }];
402
403 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
404 expect(status).toBe(200);
405 expect(body.images).toHaveLength(1);
406 expect(body.images[0].filePath).toBe(imgPath);
407 });
408
409 test('GET /api/files/folder-images returns empty list when no thumbnails available', async () =>
410 {
411 mockFolderImages = [];
412
413 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
414 expect(status).toBe(200);
415 expect(body.images).toEqual([]);
416 });
417
418 test('GET /api/files/folder-icon returns null when no icon available', async () =>
419 {
420 mockFolderIconFile = null;
421
422 const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`);
423 expect(status).toBe(200);
424 expect(body.icon).toBeNull();
425 });
426
427 test('GET /api/files/folder-icon returns source file path when icon is available', async () =>
428 {
429 const imgPath = path.join(rootDir, 'cover.jpg');
430 fs.writeFileSync(imgPath, 'img');
431 mockFolderIconFile = imgPath;
432
433 const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`);
434 expect(status).toBe(200);
435 expect(body.icon).toMatchObject({ filePath: imgPath });
436 });
437
438 test('POST /api/files/folder-icon sets explicit assignment when thumbnail is ready', async () =>
439 {
440 const imgPath = path.join(rootDir, 'cover.jpg');
441 const thumbFile = path.join(rootDir, 'cover.webp');
442 fs.writeFileSync(imgPath, 'img');
443 fs.writeFileSync(thumbFile, 'webp');
444 mockThumbPath = thumbFile;
445
446 const { status, body } = await req('POST', '/api/files/folder-icon', {
447 folderPath: rootDir,
448 imagePath: imgPath,
449 });
450 expect(status).toBe(200);
451 expect(body.ok).toBe(true);
452 expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: imgPath });
453 });
454
455 test('POST /api/files/folder-icon rejects image without cached thumbnail', async () =>
456 {
457 const imgPath = path.join(rootDir, 'missing.jpg');
458 fs.writeFileSync(imgPath, 'img');
459 mockThumbPath = null;
460
461 const { status, body } = await req('POST', '/api/files/folder-icon', {
462 folderPath: rootDir,
463 imagePath: imgPath,
464 });
465 expect(status).toBe(404);
466 expect(body.error).toMatch(/thumbnail not ready/i);
467 });
468
469 test('POST /api/files/folder-icon clears assignment when imagePath is null', async () =>
470 {
471 const { status, body } = await req('POST', '/api/files/folder-icon', {
472 folderPath: rootDir,
473 imagePath: null,
474 });
475 expect(status).toBe(200);
476 expect(body.ok).toBe(true);
477 expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: null });
478 });
479
480 test('POST /api/files/folder-icon returns 403 for read-only user', async () =>
481 {
482 const label = path.basename(rootDir);
483 mockUser = {
484 username: 'reader',
485 isAdmin: false,
486 permissions: { [label]: { read: true, write: false } },
487 };
488
489 const imgPath = path.join(rootDir, 'photo.jpg');
490 fs.writeFileSync(imgPath, 'img');
491
492 const { status } = await req('POST', '/api/files/folder-icon', {
493 folderPath: rootDir,
494 imagePath: imgPath,
495 });
496 expect(status).toBe(403);
497 });
498});