BlueGit

timfa filemanager

Files

filemanager / tests / admin.routes.test.js

admin.routes.test.js

admin.routes.test.js 8.8 KiB Download Raw
1'use strict';
2
3/**
4 * Unit tests for server/routes/admin.js — user CRUD and config management.
5 */
6
7const express = require('express');
8const http = require('http');
9const { once } = require('events');
10const crypto = require('crypto');
11
12// ── in-memory DB mock ───────────────────────────────────────────────────────
13jest.mock('../server/db', () => {
14 const { Database } = require('node-sqlite3-wasm');
15 let db;
16 function getDb() {
17 if (!db) {
18 db = new Database(':memory:');
19 db.exec(`
20 CREATE TABLE IF NOT EXISTS users (
21 id INTEGER PRIMARY KEY AUTOINCREMENT,
22 username TEXT UNIQUE NOT NULL,
23 password_hash TEXT NOT NULL,
24 is_admin INTEGER NOT NULL DEFAULT 0,
25 permissions TEXT NOT NULL DEFAULT '{}'
26 );
27 CREATE TABLE IF NOT EXISTS file_meta (
28 file_path TEXT PRIMARY KEY,
29 uploader TEXT NOT NULL DEFAULT '',
30 downloaders TEXT NOT NULL DEFAULT '[]'
31 );
32 `);
33 }
34 return db;
35 }
36 return { getDb, initDb: getDb };
37});
38
39// ── config mock ─────────────────────────────────────────────────────────────
40const mockConfig = { port: 3000, paths: ['/mnt/data', '/mnt/docs'] };
41jest.mock('../server/config', () => ({
42 loadConfig: () => ({ ...mockConfig }),
43 saveConfig: (c) => Object.assign(mockConfig, c),
44 getEffectivePaths: (p) => p,
45 getAllowedRoot: () => null,
46}));
47
48// ── auth mock — bypass JWT verification ─────────────────────────────────────
49let mockUser = { id: 1, username: 'admin', isAdmin: true, permissions: {} };
50jest.mock('../server/auth', () => ({
51 requireAuth: (req, res, next) => { req.user = mockUser; next(); },
52 requireAdmin: (req, res, next) => {
53 if (!req.user.isAdmin) return res.status(403).json({ error: 'Admin required.' });
54 next();
55 },
56 createToken: () => 'mock-token',
57 getClientIp: () => '127.0.0.1',
58 getRegion: () => 'US:CA',
59}));
60
61const adminRoutes = require('../server/routes/admin');
62const { getDb } = require('../server/db');
63const bcrypt = require('bcrypt');
64
65jest.setTimeout(30000);
66
67// ── seed a default admin before anything runs ────────────────────────────────
68beforeAll(() => {
69 const db = getDb();
70 const hash = bcrypt.hashSync('admin1234', 4); // low rounds for speed
71 db.prepare('INSERT OR IGNORE INTO users (username, password_hash, is_admin, permissions) VALUES (?,?,1,?)')
72 .run(['admin', hash, '{}']);
73});
74
75// ── build minimal app ────────────────────────────────────────────────────────
76let server;
77let baseUrl;
78let shutdownForRestartMock;
79
80beforeAll(async () => {
81 const app = express();
82 shutdownForRestartMock = jest.fn();
83 app.set('shutdownForRestart', shutdownForRestartMock);
84 app.use(express.json());
85 app.use('/api/admin', adminRoutes);
86 app.use((err, req, res, next) => {
87 res.status(err.status || 500).json({ error: err.message || 'Internal error' });
88 });
89 server = http.createServer(app);
90 server.listen(0);
91 await once(server, 'listening');
92 baseUrl = `http://127.0.0.1:${server.address().port}`;
93});
94
95afterAll(() => server.close());
96
97// ── helpers ──────────────────────────────────────────────────────────────────
98function req(method, path, body) {
99 const payload = body ? JSON.stringify(body) : undefined;
100 return new Promise((resolve, reject) => {
101 const r = http.request(baseUrl + path, {
102 method,
103 headers: {
104 'Content-Type': 'application/json',
105 ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}),
106 },
107 }, res => {
108 let data = '';
109 res.on('data', d => data += d);
110 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));
111 });
112 r.on('error', reject);
113 if (payload) r.write(payload);
114 r.end();
115 });
116}
117
118// ── tests ─────────────────────────────────────────────────────────────────────
119
120describe('GET /api/admin/users', () => {
121 test('returns the list of users', async () => {
122 const { status, body } = await req('GET', '/api/admin/users');
123 expect(status).toBe(200);
124 expect(Array.isArray(body.users)).toBe(true);
125 expect(body.users[0]).toMatchObject({ username: 'admin', isAdmin: true });
126 });
127});
128
129describe('POST /api/admin/users', () => {
130 test('creates a new user', async () => {
131 const { status, body } = await req('POST', '/api/admin/users', {
132 username: 'bob', password: 'bobpass1', isAdmin: false, permissions: {},
133 });
134 expect(status).toBe(201);
135 expect(body.ok).toBe(true);
136 });
137
138 test('rejects duplicate username', async () => {
139 const { status } = await req('POST', '/api/admin/users', {
140 username: 'bob', password: 'bobpass2', isAdmin: false, permissions: {},
141 });
142 expect(status).toBe(409);
143 });
144
145 test('rejects short password', async () => {
146 const { status } = await req('POST', '/api/admin/users', {
147 username: 'carol', password: 'short', isAdmin: false, permissions: {},
148 });
149 expect(status).toBe(400);
150 });
151});
152
153describe('PATCH /api/admin/users/:id', () => {
154 let bobId;
155
156 beforeAll(async () => {
157 const { body } = await req('GET', '/api/admin/users');
158 bobId = body.users.find(u => u.username === 'bob').id;
159 });
160
161 test('updates permissions', async () => {
162 const { status, body } = await req('PATCH', `/api/admin/users/${bobId}`, {
163 permissions: { data: { read: true, write: false } },
164 });
165 expect(status).toBe(200);
166 expect(body.ok).toBe(true);
167 });
168
169 test('returns 404 for unknown user', async () => {
170 const { status } = await req('PATCH', '/api/admin/users/99999', { isAdmin: false });
171 expect(status).toBe(404);
172 });
173});
174
175describe('DELETE /api/admin/users/:id', () => {
176 let bobId;
177
178 beforeAll(async () => {
179 const { body } = await req('GET', '/api/admin/users');
180 bobId = body.users.find(u => u.username === 'bob').id;
181 });
182
183 test('cannot delete own account', async () => {
184 // mock user id is 1 (admin); bob is a different id — but we test self-delete guard
185 const adminId = mockUser.id;
186 const { status } = await req('DELETE', `/api/admin/users/${adminId}`);
187 expect(status).toBe(400);
188 });
189
190 test('deletes another user', async () => {
191 const { status, body } = await req('DELETE', `/api/admin/users/${bobId}`);
192 expect(status).toBe(200);
193 expect(body.ok).toBe(true);
194 });
195
196 test('cannot delete the last admin', async () => {
197 // Only 'admin' left; try to delete them (switch mockUser to be different)
198 const { body: users } = await req('GET', '/api/admin/users');
199 const adminUser = users.users.find(u => u.username === 'admin');
200 const { status } = await req('DELETE', `/api/admin/users/${adminUser.id}`);
201 // Our mockUser.id === 1 === adminUser.id, so it should fail with "cannot delete own account"
202 expect([400]).toContain(status);
203 });
204});
205
206describe('GET /api/admin/config', () => {
207 test('returns port and paths', async () => {
208 const { status, body } = await req('GET', '/api/admin/config');
209 expect(status).toBe(200);
210 expect(body.port).toBe(3000);
211 expect(Array.isArray(body.paths)).toBe(true);
212 });
213});
214
215describe('PUT /api/admin/config', () => {
216 test('saves new paths', async () => {
217 const { status, body } = await req('PUT', '/api/admin/config', {
218 paths: ['/mnt/newpath'],
219 });
220 expect(status).toBe(200);
221 expect(body.ok).toBe(true);
222 });
223
224 test('rejects non-array paths', async () => {
225 const { status } = await req('PUT', '/api/admin/config', { paths: 'notanarray' });
226 expect(status).toBe(400);
227 });
228
229 test('rejects invalid port', async () => {
230 const { status } = await req('PUT', '/api/admin/config', { paths: [], port: 99999 });
231 expect(status).toBe(400);
232 });
233});
234
235describe('POST /api/admin/shutdown', () => {
236 test('responds ok and invokes shutdown callback', async () => {
237 shutdownForRestartMock.mockClear();
238 const { status, body } = await req('POST', '/api/admin/shutdown');
239 expect(status).toBe(200);
240 expect(body.ok).toBe(true);
241
242 // Shutdown invocation is deferred via setImmediate().
243 await new Promise(resolve => setImmediate(resolve));
244 expect(shutdownForRestartMock).toHaveBeenCalledTimes(1);
245 });
246});