'use strict'; /** * Unit tests for server/routes/admin.js — user CRUD and config management. */ const express = require('express'); const http = require('http'); const { once } = require('events'); const crypto = require('crypto'); // ── child_process mock — controlled per test ────────────────────────────────── let mockExecFileImpl = null; jest.mock('child_process', () => { const real = jest.requireActual('child_process'); return { ...real, execFile: jest.fn((...args) => { const cb = args[args.length - 1]; if (typeof mockExecFileImpl === 'function') { mockExecFileImpl(...args); return; } // Default: simulate git not available. cb(new Error('git not found')); }), }; }); // ── in-memory DB mock ─────────────────────────────────────────────────────── jest.mock('../server/db', () => { const { Database } = require('node-sqlite3-wasm'); let db; function getDb () { if (!db) { db = new Database(':memory:'); db.exec(` CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL, is_admin INTEGER NOT NULL DEFAULT 0, permissions TEXT NOT NULL DEFAULT '{}' ); CREATE TABLE IF NOT EXISTS file_meta ( file_path TEXT PRIMARY KEY, uploader TEXT NOT NULL DEFAULT '', downloaders TEXT NOT NULL DEFAULT '[]' ); `); } return db; } return { getDb, initDb: getDb }; }); // ── config mock ───────────────────────────────────────────────────────────── const mockConfig = { port: 3000, paths: ['/mnt/data', '/mnt/docs'] }; jest.mock('../server/config', () => ({ loadConfig: () => ({ ...mockConfig }), saveConfig: (c) => Object.assign(mockConfig, c), getEffectivePaths: (p) => p, getAllowedRoot: () => null, })); // ── auth mock — bypass JWT verification ───────────────────────────────────── let mockUser = { id: 1, username: 'admin', isAdmin: true, permissions: {} }; jest.mock('../server/auth', () => ({ requireAuth: (req, res, next) => { req.user = mockUser; next(); }, requireAdmin: (req, res, next) => { if (!req.user.isAdmin) return res.status(403).json({ error: 'Admin required.' }); next(); }, createToken: () => 'mock-token', getClientIp: () => '127.0.0.1', getRegion: () => 'US:CA', })); const adminRoutes = require('../server/routes/admin'); const { getDb } = require('../server/db'); const bcrypt = require('bcrypt'); jest.setTimeout(30000); // ── seed a default admin before anything runs ──────────────────────────────── beforeAll(() => { const db = getDb(); const hash = bcrypt.hashSync('admin1234', 4); // low rounds for speed db.prepare('INSERT OR IGNORE INTO users (username, password_hash, is_admin, permissions) VALUES (?,?,1,?)') .run(['admin', hash, '{}']); }); // ── build minimal app ──────────────────────────────────────────────────────── let server; let baseUrl; let shutdownForRestartMock; beforeAll(async () => { const app = express(); shutdownForRestartMock = jest.fn(); app.set('shutdownForRestart', shutdownForRestartMock); app.use(express.json()); app.use('/api/admin', adminRoutes); app.use((err, req, res, next) => { res.status(err.status || 500).json({ error: err.message || 'Internal error' }); }); server = http.createServer(app); server.listen(0); await once(server, 'listening'); baseUrl = `http://127.0.0.1:${server.address().port}`; }); afterAll(() => server.close()); // ── helpers ────────────────────────────────────────────────────────────────── function req (method, path, body) { const payload = body ? JSON.stringify(body) : undefined; return new Promise((resolve, reject) => { const r = http.request(baseUrl + path, { method, headers: { 'Content-Type': 'application/json', ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}), }, }, res => { let data = ''; res.on('data', d => data += d); res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) })); }); r.on('error', reject); if (payload) r.write(payload); r.end(); }); } // ── tests ───────────────────────────────────────────────────────────────────── describe('GET /api/admin/users', () => { test('returns the list of users', async () => { const { status, body } = await req('GET', '/api/admin/users'); expect(status).toBe(200); expect(Array.isArray(body.users)).toBe(true); expect(body.users[0]).toMatchObject({ username: 'admin', isAdmin: true }); }); }); describe('POST /api/admin/users', () => { test('creates a new user', async () => { const { status, body } = await req('POST', '/api/admin/users', { username: 'bob', password: 'bobpass1', isAdmin: false, permissions: {}, }); expect(status).toBe(201); expect(body.ok).toBe(true); }); test('rejects duplicate username', async () => { const { status } = await req('POST', '/api/admin/users', { username: 'bob', password: 'bobpass2', isAdmin: false, permissions: {}, }); expect(status).toBe(409); }); test('rejects duplicate username with different case', async () => { const { status } = await req('POST', '/api/admin/users', { username: 'BoB', password: 'bobpass3', isAdmin: false, permissions: {}, }); expect(status).toBe(409); }); test('rejects short password', async () => { const { status } = await req('POST', '/api/admin/users', { username: 'carol', password: 'short', isAdmin: false, permissions: {}, }); expect(status).toBe(400); }); test('normalizes permissions so write implies read on create', async () => { const { status } = await req('POST', '/api/admin/users', { username: 'dora', password: 'dora-pass1', isAdmin: false, permissions: { data: { read: false, write: true } }, }); expect(status).toBe(201); const { body } = await req('GET', '/api/admin/users'); const dora = body.users.find(u => u.username === 'dora'); expect(dora.permissions).toMatchObject({ data: { read: true, write: true } }); }); }); describe('PATCH /api/admin/users/:id', () => { let bobId; beforeAll(async () => { const { body } = await req('GET', '/api/admin/users'); bobId = body.users.find(u => u.username === 'bob').id; }); test('updates permissions', async () => { const { status, body } = await req('PATCH', `/api/admin/users/${bobId}`, { permissions: { data: { read: true, write: false } }, }); expect(status).toBe(200); expect(body.ok).toBe(true); }); test('returns 404 for unknown user', async () => { const { status } = await req('PATCH', '/api/admin/users/99999', { isAdmin: false }); expect(status).toBe(404); }); test('normalizes permissions so write implies read on update', async () => { const { status } = await req('PATCH', `/api/admin/users/${bobId}`, { permissions: { data: { read: false, write: true } }, }); expect(status).toBe(200); const { body } = await req('GET', '/api/admin/users'); const bob = body.users.find(u => u.id === bobId); expect(bob.permissions).toMatchObject({ data: { read: true, write: true } }); }); test('rejects removing own admin privileges', async () => { const { status, body } = await req('PATCH', `/api/admin/users/${mockUser.id}`, { isAdmin: false, }); expect(status).toBe(400); expect(body.error).toMatch(/own admin privileges/i); const usersRes = await req('GET', '/api/admin/users'); const me = usersRes.body.users.find(u => String(u.id) === String(mockUser.id)); expect(me).toBeTruthy(); expect(me.isAdmin).toBe(true); }); }); describe('DELETE /api/admin/users/:id', () => { let bobId; beforeAll(async () => { const { body } = await req('GET', '/api/admin/users'); bobId = body.users.find(u => u.username === 'bob').id; }); test('cannot delete own account', async () => { // mock user id is 1 (admin); bob is a different id — but we test self-delete guard const adminId = mockUser.id; const { status } = await req('DELETE', `/api/admin/users/${adminId}`); expect(status).toBe(400); }); test('deletes another user', async () => { const { status, body } = await req('DELETE', `/api/admin/users/${bobId}`); expect(status).toBe(200); expect(body.ok).toBe(true); }); test('cannot delete the last admin', async () => { // Only 'admin' left; try to delete them (switch mockUser to be different) const { body: users } = await req('GET', '/api/admin/users'); const adminUser = users.users.find(u => u.username === 'admin'); const { status } = await req('DELETE', `/api/admin/users/${adminUser.id}`); // Our mockUser.id === 1 === adminUser.id, so it should fail with "cannot delete own account" expect([400]).toContain(status); }); }); describe('GET /api/admin/config', () => { test('returns port and paths', async () => { const { status, body } = await req('GET', '/api/admin/config'); expect(status).toBe(200); expect(body.port).toBe(3000); expect(Array.isArray(body.paths)).toBe(true); }); }); describe('PUT /api/admin/config', () => { test('saves new paths', async () => { const { status, body } = await req('PUT', '/api/admin/config', { paths: ['/mnt/newpath'], }); expect(status).toBe(200); expect(body.ok).toBe(true); }); test('rejects non-array paths', async () => { const { status } = await req('PUT', '/api/admin/config', { paths: 'notanarray' }); expect(status).toBe(400); }); test('rejects invalid port', async () => { const { status } = await req('PUT', '/api/admin/config', { paths: [], port: 99999 }); expect(status).toBe(400); }); }); describe('POST /api/admin/shutdown', () => { test('responds ok and invokes shutdown callback', async () => { shutdownForRestartMock.mockClear(); const { status, body } = await req('POST', '/api/admin/shutdown'); expect(status).toBe(200); expect(body.ok).toBe(true); // Shutdown invocation is deferred via setImmediate(). await new Promise(resolve => setImmediate(resolve)); expect(shutdownForRestartMock).toHaveBeenCalledTimes(1); }); }); describe('GET /api/admin/update-status', () => { const origInvocationId = process.env.INVOCATION_ID; afterEach(() => { mockExecFileImpl = null; if (origInvocationId === undefined) delete process.env.INVOCATION_ID; else process.env.INVOCATION_ID = origInvocationId; }); test('returns underSystemd=false when INVOCATION_ID is not set', async () => { delete process.env.INVOCATION_ID; const { status, body } = await req('GET', '/api/admin/update-status'); expect(status).toBe(200); expect(body.underSystemd).toBe(false); expect(body.commitsAhead).toEqual([]); }); test('returns underSystemd=true and commitsAhead when INVOCATION_ID is set and git reports commits', async () => { process.env.INVOCATION_ID = 'test-invocation-id'; // git fetch succeeds, then git log returns two commits. let callCount = 0; mockExecFileImpl = (_cmd, _args, _opts, cb) => { callCount++; if (callCount === 1) cb(null, { stdout: '', stderr: '' }); // git fetch else cb(null, { stdout: 'abc1234 Fix bug\ndef5678 Add feature\n', stderr: '' }); // git log }; const { status, body } = await req('GET', '/api/admin/update-status'); expect(status).toBe(200); expect(body.underSystemd).toBe(true); expect(body.commitsAhead).toEqual(['abc1234 Fix bug', 'def5678 Add feature']); }); test('returns underSystemd=true and empty commitsAhead when git is up to date', async () => { process.env.INVOCATION_ID = 'test-invocation-id'; let callCount = 0; mockExecFileImpl = (_cmd, _args, _opts, cb) => { callCount++; cb(null, { stdout: '', stderr: '' }); // fetch and log both return empty }; const { status, body } = await req('GET', '/api/admin/update-status'); expect(status).toBe(200); expect(body.underSystemd).toBe(true); expect(body.commitsAhead).toEqual([]); }); test('returns underSystemd=true and empty commitsAhead when git fails', async () => { process.env.INVOCATION_ID = 'test-invocation-id'; mockExecFileImpl = (_cmd, _args, _opts, cb) => { cb(new Error('git: not found')); }; const { status, body } = await req('GET', '/api/admin/update-status'); expect(status).toBe(200); expect(body.underSystemd).toBe(true); expect(body.commitsAhead).toEqual([]); }); });