Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

quickshell/nuguland/test-fixtures/isolation.test.js

Raw
'use strict';

// Host-side tests must never reach the owner's live desktop session: every child
// starts through isolation.js with an allowlisted environment, private HOME, XDG
// and runtime directories, and at most a private bus that activates nothing.
// (A document portal activated on a test bus once unmounted the desktop's
// $XDG_RUNTIME_DIR/doc.) This proves the environment and the cleanup, then
// rejects any test file or runner that starts a process another way.
const assert = require('assert');
const fs = require('fs');
const os = require('os');
const path = require('path');
const { isolatedEnv, runIsolated, spawnIsolated } = require('./isolation.js');

const root = path.resolve(__dirname, '..');

// Desktop resources a caller could hold; none may reach a child.
const desktop = {
    DISPLAY: ':0', WAYLAND_DISPLAY: 'wayland-1', NIRI_SOCKET: '/run/user/1000/niri.sock',
    DBUS_SESSION_BUS_ADDRESS: 'unix:path=/run/user/1000/bus', DBUS_SYSTEM_BUS_ADDRESS: 'unix:path=/run/dbus/system_bus_socket',
    AT_SPI_BUS_ADDRESS: 'unix:path=/run/user/1000/at-spi/bus', SSH_AUTH_SOCK: '/run/user/1000/ssh', GNUPGHOME: '/home/owner/.gnupg',
    PULSE_SERVER: 'unix:/run/user/1000/pulse/native', PIPEWIRE_REMOTE: 'pipewire-0', WEZTERM_UNIX_SOCKET: '/run/user/1000/wezterm/sock',
    XDG_CONFIG_DIRS: '/home/owner/.config/xdg', XDG_DATA_DIRS: '/home/owner/.local/share/flatpak/exports/share',
    QT_QPA_PLATFORMTHEME: 'gtk3', LD_PRELOAD: '/home/owner/lib.so', NUGULAND_ISOLATION_PROBE: 'caller-only',
};
for (const [key, value] of Object.entries(desktop)) process.env[key] = value;

function alive(pid) {
    try {
        const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8');
        return stat.slice(stat.lastIndexOf(')') + 2)[0] !== 'Z';
    } catch {
        return false;
    }
}

function childEnv(run) {
    assert.ifError(run.error);
    assert.strictEqual(run.status, 0, String(run.stderr));
    return Object.fromEntries(String(run.stdout).split('\0').filter(Boolean).map(entry => {
        const index = entry.indexOf('=');
        return [entry.slice(0, index), entry.slice(index + 1)];
    }));
}

async function main() {
    const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'nuguland-isolation-'));
    try {
        // (a) The environment a child actually receives.
        const env = childEnv(runIsolated('/usr/bin/env', ['-0'], { directory: tmp, encoding: 'utf8' }));
        const expected = isolatedEnv(tmp);
        assert.deepStrictEqual(env, expected, 'the child sees exactly the isolated environment');
        const inherited = /^(?:PATH|LANG|LANGUAGE|LC_\w+|TERM|TZ|USER|LOGNAME|TMPDIR)$/;
        const owned = ['HOME', 'XDG_RUNTIME_DIR', 'XDG_CONFIG_HOME', 'XDG_STATE_HOME', 'XDG_CACHE_HOME', 'XDG_DATA_HOME',
            'DBUS_SESSION_BUS_ADDRESS', 'DBUS_SYSTEM_BUS_ADDRESS', 'QT_QPA_PLATFORM', 'QT_QPA_PLATFORMTHEME', 'QT_QUICK_BACKEND',
            'QT_NO_XDG_DESKTOP_PORTAL', 'QS_NO_RELOAD_POPUP', 'NO_AT_BRIDGE'];
        for (const key of Object.keys(env))
            assert(inherited.test(key) || owned.includes(key), `${key} is not allowlisted`);
        for (const key of Object.keys(desktop))
            if (!owned.includes(key)) assert.strictEqual(env[key], undefined, `${key} is not inherited`);
        for (const key of owned.slice(0, 6)) {
            assert.strictEqual(path.dirname(env[key]), tmp, `${key} is private`);
            assert(fs.statSync(env[key]).isDirectory(), `${key} exists`);
        }
        assert.strictEqual(fs.statSync(env.XDG_RUNTIME_DIR).mode & 0o777, 0o700, 'private 0700 runtime');
        const bus = `unix:path=${path.join(env.XDG_RUNTIME_DIR, 'bus')}`;
        assert.strictEqual(env.DBUS_SESSION_BUS_ADDRESS, bus);
        assert.strictEqual(env.DBUS_SYSTEM_BUS_ADDRESS, bus, 'the system bus is the private bus or nothing');
        assert.strictEqual(env.QT_QPA_PLATFORM, 'offscreen');
        assert.strictEqual(env.QT_QPA_PLATFORMTHEME, '');
        assert.strictEqual(env.NO_AT_BRIDGE, '1');
        for (const key of [...Object.keys(desktop).filter(key => !key.startsWith('LD_') && !key.startsWith('NUGULAND_')), 'HOME', 'XDG_STATE_HOME'])
            assert.throws(() => isolatedEnv(tmp, { [key]: 'x' }), /never take/, `${key} cannot be passed back in`);
        assert.strictEqual(isolatedEnv(tmp, { NUGULAND_ISOLATION_PROBE: 'test' }).NUGULAND_ISOLATION_PROBE, 'test');

        // Without `bus`, neither bus is reachable; the caller's addresses are ignored.
        for (const scope of ['--user', '--system']) {
            const run = runIsolated('busctl', [scope, 'list', '--no-legend'], { directory: tmp, encoding: 'utf8', timeout: 10_000 });
            assert.notStrictEqual(run.status, 0, `${scope} bus unreachable without a private bus: ${run.stdout}`);
        }
        // With `bus`, both name one private bus that can activate nothing but itself.
        for (const scope of ['--user', '--system']) {
            const run = runIsolated('busctl', [scope, 'list', '--activatable', '--no-legend'], { directory: tmp, bus: true, encoding: 'utf8', timeout: 10_000 });
            assert.strictEqual(run.status, 0, run.stderr);
            assert.deepStrictEqual(run.stdout.trim().split('\n').map(line => line.split(/\s+/)[0]), ['org.freedesktop.DBus'], run.stdout);
        }
        assert.doesNotMatch(fs.readFileSync(path.join(tmp, 'session-bus.conf'), 'utf8'), /servicedir/, 'no service directories');
        const busEnv = childEnv(runIsolated('/usr/bin/env', ['-0'], { directory: tmp, bus: true, encoding: 'utf8' }));
        assert(busEnv.DBUS_SESSION_BUS_ADDRESS.startsWith(`${bus},`), busEnv.DBUS_SESSION_BUS_ADDRESS);
        assert.strictEqual(busEnv.DBUS_SYSTEM_BUS_ADDRESS, bus);
        assert(!fs.existsSync(path.join(env.XDG_RUNTIME_DIR, 'bus')), 'the private bus is gone after its run');

        // Nothing a child leaves behind outlives its run, also on timeout.
        const background = 'sleep 60 >/dev/null 2>&1 & echo $!';
        const orphan = Number(runIsolated('/bin/sh', ['-c', background], { encoding: 'utf8' }).stdout);
        assert(orphan > 0 && !alive(orphan), 'synchronous run stopped its group');
        const timed = runIsolated('/bin/sh', ['-c', `${background}; exec sleep 60 >/dev/null 2>&1`], { encoding: 'utf8', timeout: 300 });
        assert.strictEqual(timed.signal, 'SIGTERM');
        assert(!alive(Number(timed.stdout)), 'timed-out run stopped its group');
        const child = spawnIsolated('/bin/sh', ['-c', background], { stdio: ['ignore', 'pipe', 'ignore'] });
        let output = '';
        child.stdout.on('data', data => { output += data; });
        await new Promise(resolve => child.once('close', resolve));
        assert(!alive(Number(output)), 'asynchronous run stopped its group before close');
        // A descendant that keeps the child's pipe open cannot hold the run open.
        const holder = spawnIsolated('/bin/sh', ['-c', 'sleep 60 & echo $!'], { stdio: ['ignore', 'pipe', 'ignore'] });
        let held = '';
        holder.stdout.on('data', data => { held += data; });
        await new Promise((resolve, reject) => {
            const deadline = setTimeout(() => reject(new Error('a descendant holding a pipe kept the run open')), 5000);
            holder.once('close', () => { clearTimeout(deadline); resolve(); });
        });
        assert(Number(held) > 0 && !alive(Number(held)), 'asynchronous run stopped a pipe-holding descendant');

        // (b) No test file or runner starts a process another way.
        assert.deepStrictEqual(violations('old.js', [
            `const { spawnSync } = require('${'child'}_process');`,
            `spawnSync('qs', [], { env: { ...process${''}.env, XDG_RUNTIME_DIR: tmp } });`,
            `const env = Object.assign({}, process${''}.env);`,
            `spawn('x', [], { env: process${''}.env });`,
        ].join('\n')).length, 4, 'the old pattern fails the guard');
        assert.strictEqual(violations('old.mjs', `import { spawn } from 'node:${'child'}_process';`).length, 1);
        const files = sources();
        for (const runner of ['load-test.mjs', 'stress-test.mjs', 'ui-test.test.mjs', 'test-fixtures/offscreen.mjs', 'test-fixtures/ipc-selftest.js', 'test-fixtures/isolation.test.js'])
            assert(files.includes(runner), `${runner} is guarded`);
        assert.deepStrictEqual(files.flatMap(file => violations(file, fs.readFileSync(path.join(root, file), 'utf8'))), []);
        // ui-test.mjs and its fixtures run inside the sandbox; its outer runner hands
        // bwrap nothing: a cleared environment and no shared namespaces.
        const ui = fs.readFileSync(path.join(root, 'ui-test.mjs'), 'utf8');
        for (const flag of ['--unshare-all', '--clearenv', '--die-with-parent']) assert(ui.includes(`'${flag}'`), flag);
    } finally {
        fs.rmSync(tmp, { recursive: true, force: true });
    }
}

// Test files anywhere, the host runners, and the shared test fixtures; ui-test.mjs,
// test-fixtures/ui/ and feature fixtures/ run only inside the ui-test sandbox.
function sources() {
    return fs.globSync('**/*.{js,mjs}', { cwd: root, exclude: ['**/node_modules/**', '**/vault-native/**', '**/.git/**'] })
        .filter(file => /\.test\.m?js$/.test(file) || ['load-test.mjs', 'stress-test.mjs'].includes(file)
            || (path.dirname(file) === 'test-fixtures' && file !== 'test-fixtures/isolation.js'))
        .sort();
}

function violations(file, text) {
    const found = [];
    if (/\bchild_process\b|\bprocess\.binding\b/.test(text))
        found.push(`${file}: starts processes outside test-fixtures/isolation.js`);
    for (const pattern of [/\.\.\.\s*process\.env\b/, /Object\.assign\([^)]*\bprocess\.env\b/, /\benv\s*:\s*process\.env\b/])
        if (pattern.test(text)) found.push(`${file}: hands a child the caller's environment (${pattern.source})`);
    return found;
}

main().then(() => console.log('isolation.test.js: ALL PASS'), error => {
    console.error(error);
    process.exitCode = 1;
});