mirror of
https://github.com/screentinker/screentinker.git
synced 2026-08-13 22:03:13 -06:00
The subprocess-booting test suites hand-picked fixed ports in a cramped ~3955-4021 range, and 156-schedule-read-path deviated to a RANDOM port (3900 + rand%90) that overlapped those fixed ports. Under CI load two servers could race on the same port, surfacing as flaky "no such table: devices" / "FOREIGN KEY constraint failed" (a server answering a request against a half-migrated or wrong DB). It's environmental — the suites pass locally and in isolation. Fix: a shared test/helpers/free-port.js (bind :0 on loopback, read the OS-assigned port, release) called in before() so every suite gets a guaranteed-unique ephemeral port — concurrent suites can no longer collide, and no one has to hand-assign ports. - Codemod converted 30 suites: const PORT = <fixed|random> -> let PORT (+ BASE) assigned via `PORT = await freePort()` at the top of before(). - 3 hand-fixed (different structure): 148-eviction-storm (lowercase `base`), boot-health (no before() — allocates PORT + a throwaway SEED_PORT inside the test, replacing the hardcoded 3894), totp-keyrotation (no before() — allocates at the test start before bootServer()). No fixed 39xx/40xx ports remain. Full server suite 435/435; the 4 hand-touched suites pass in isolation. Pure test-infra change — no app code touched.
79 lines
4.3 KiB
JavaScript
79 lines
4.3 KiB
JavaScript
'use strict';
|
|
|
|
// #146 P1.4 — POST /api/devices/:id/{block,unblock} is a real lever now; its authz path
|
|
// must be covered, not just the happy path. Proves: the owner can block; a
|
|
// cross-workspace user CANNOT; a workspace_viewer CANNOT; unauthenticated CANNOT.
|
|
// Booted server + JWT; device + viewer membership seeded via the DB file.
|
|
|
|
const { test, before, after } = require('node:test');
|
|
const assert = require('node:assert/strict');
|
|
const { spawn } = require('node:child_process');
|
|
const path = require('node:path');
|
|
const os = require('node:os');
|
|
const fs = require('node:fs');
|
|
const crypto = require('node:crypto');
|
|
const Database = require('better-sqlite3');
|
|
|
|
const { freePort } = require('./helpers/free-port');
|
|
let PORT, BASE;
|
|
const DATA_DIR = path.join(os.tmpdir(), 'st-blockauthz-' + crypto.randomBytes(4).toString('hex'));
|
|
let proc, db;
|
|
|
|
before(async () => {
|
|
PORT = await freePort();
|
|
BASE = `http://127.0.0.1:${PORT}`;
|
|
const logFd = fs.openSync(path.join(os.tmpdir(), 'st-blockauthz.log'), 'w');
|
|
proc = spawn('node', ['server.js'], {
|
|
cwd: path.join(__dirname, '..'),
|
|
env: { ...process.env, DATA_DIR, SELF_HOSTED: 'true', PORT: String(PORT), NODE_ENV: 'test' },
|
|
stdio: ['ignore', logFd, logFd],
|
|
});
|
|
let up = false;
|
|
for (let i = 0; i < 80; i++) {
|
|
try { const r = await fetch(BASE + '/api/status'); if (r.ok) { up = true; break; } } catch { /* not yet */ }
|
|
await new Promise(r => setTimeout(r, 250));
|
|
}
|
|
if (!up) throw new Error('server did not boot');
|
|
db = new Database(path.join(DATA_DIR, 'db', 'remote_display.db'));
|
|
});
|
|
after(() => { try { db && db.close(); } catch { /* */ } try { proc.kill('SIGKILL'); } catch { /* */ } });
|
|
|
|
const jf = async (p, opts = {}) => { const r = await fetch(BASE + p, opts); let b = null; try { b = await r.json(); } catch { /* */ } return { status: r.status, body: b }; };
|
|
const reg = (o) => ({ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(o) });
|
|
const post = (tok) => ({ method: 'POST', headers: tok ? { Authorization: 'Bearer ' + tok } : {} });
|
|
|
|
test('block/unblock authz: owner allowed; cross-workspace, viewer, and anon denied', async () => {
|
|
const emailA = 'a' + crypto.randomBytes(4).toString('hex') + '@x.local';
|
|
const emailB = 'b' + crypto.randomBytes(4).toString('hex') + '@x.local';
|
|
const jwtA = (await jf('/api/auth/register', reg({ email: emailA, password: 'Passw0rd123' }))).body.token;
|
|
const jwtB = (await jf('/api/auth/register', reg({ email: emailB, password: 'Passw0rd123' }))).body.token;
|
|
assert.ok(jwtA && jwtB, 'both users registered');
|
|
|
|
const userA = db.prepare('SELECT id FROM users WHERE email = ?').get(emailA).id;
|
|
const userB = db.prepare('SELECT id FROM users WHERE email = ?').get(emailB).id;
|
|
const wsA = db.prepare("SELECT workspace_id FROM workspace_members WHERE user_id = ? AND role = 'workspace_admin'").get(userA).workspace_id;
|
|
|
|
// a device in A's workspace
|
|
db.prepare("INSERT INTO devices (id, name, status, workspace_id) VALUES ('authz-dev', 'D', 'offline', ?)").run(wsA);
|
|
|
|
// 1) anon -> 401
|
|
assert.equal((await jf('/api/devices/authz-dev/block', post(null))).status, 401, 'unauthenticated cannot block');
|
|
|
|
// 2) cross-workspace user B (not a member of A's workspace) -> 403
|
|
assert.equal((await jf('/api/devices/authz-dev/block', post(jwtB))).status, 403, 'cross-workspace user cannot block');
|
|
|
|
// 3) owner A -> 200, and the DB reflects it
|
|
const okBlock = await jf('/api/devices/authz-dev/block', post(jwtA));
|
|
assert.equal(okBlock.status, 200, 'owner can block');
|
|
assert.equal(db.prepare("SELECT blocked FROM devices WHERE id = 'authz-dev'").get().blocked, 1, 'blocked persisted');
|
|
|
|
// 4) make B a workspace_viewer in A's workspace -> still denied (read-only)
|
|
db.prepare("INSERT INTO workspace_members (workspace_id, user_id, role) VALUES (?, ?, 'workspace_viewer')").run(wsA, userB);
|
|
assert.equal((await jf('/api/devices/authz-dev/unblock', post(jwtB))).status, 403, 'a workspace_viewer cannot unblock');
|
|
assert.equal(db.prepare("SELECT blocked FROM devices WHERE id = 'authz-dev'").get().blocked, 1, 'still blocked — viewer write was denied');
|
|
|
|
// 5) owner A can unblock -> 200
|
|
assert.equal((await jf('/api/devices/authz-dev/unblock', post(jwtA))).status, 200, 'owner can unblock');
|
|
assert.equal(db.prepare("SELECT blocked FROM devices WHERE id = 'authz-dev'").get().blocked, 0, 'unblocked');
|
|
});
|