Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

quickshell/nuguland/test-fixtures/isolation.js

Raw
'use strict';

// The one route by which host-side tests and runners start processes; outside the
// ui-test sandbox nothing else may spawn (isolation.test.js enforces it).
//
// A child gets an allowlisted environment, never the caller's: private HOME, XDG
// and 0700 runtime directories under the test's directory, offscreen Qt with an
// empty platform theme, and no display, compositor, agent, or desktop bus. Its
// session and system bus addresses both name `<runtime>/bus`, which exists only
// while `bus: true` runs a private bus there that can activate nothing.
// Every child leads its own process group; once it exits, the group is stopped
// and awaited, bounded, so no process outlives the run or its directories.
//
// Incident: a document portal activated on a test bus that shared the desktop's
// runtime directory unmounted the desktop's $XDG_RUNTIME_DIR/doc.
const assert = require('assert');
const childProcess = require('child_process');
const fs = require('fs');
const os = require('os');
const path = require('path');

const inherited = /^(?:PATH|LANG|LANGUAGE|LC_\w+|TERM|TZ|USER|LOGNAME|TMPDIR)$/;
// Desktop session resources and the variables the isolation itself owns.
const reserved = /^(?:HOME|XDG_\w+|DISPLAY|WAYLAND_\w+|NIRI_\w+|DBUS_\w+|AT_SPI_\w+|NO_AT_BRIDGE|SSH_\w+|GPG_\w+|GNUPGHOME|PULSE_\w+|PIPEWIRE_\w+|WEZTERM_\w+|DESKTOP_\w+|QT_\w+|QS_\w+)$/;

// A session bus with no service directories: nothing can be bus-activated on it.
function busConfig(socket) {
    return `<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
 "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
  <type>session</type>
  <listen>unix:path=${socket}</listen>
  <auth>EXTERNAL</auth>
  <policy context="default">
    <allow send_destination="*" eavesdrop="true"/>
    <allow eavesdrop="true"/>
    <allow own="*"/>
  </policy>
</busconfig>
`;
}

// `extra` adds test variables (fixture PATH, markers, LD_PRELOAD doubles); it can
// never reintroduce a desktop resource or override the isolation.
function isolatedEnv(directory, extra = {}) {
    const dirs = {
        HOME: 'home', XDG_RUNTIME_DIR: 'runtime', XDG_CONFIG_HOME: 'config',
        XDG_STATE_HOME: 'state', XDG_CACHE_HOME: 'cache', XDG_DATA_HOME: 'data',
    };
    const env = {};
    for (const [key, value] of Object.entries(process.env))
        if (inherited.test(key)) env[key] = value;
    for (const [key, name] of Object.entries(dirs)) {
        env[key] = path.join(directory, name);
        fs.mkdirSync(env[key], { recursive: true, mode: 0o700 });
    }
    fs.chmodSync(env.XDG_RUNTIME_DIR, 0o700);
    const bus = `unix:path=${path.join(env.XDG_RUNTIME_DIR, 'bus')}`;
    Object.assign(env, {
        DBUS_SESSION_BUS_ADDRESS: bus,
        DBUS_SYSTEM_BUS_ADDRESS: bus,
        QT_QPA_PLATFORM: 'offscreen',
        // The desktop's platform theme (e.g. gtk3) needs a display and aborts offscreen.
        QT_QPA_PLATFORMTHEME: '',
        QT_QUICK_BACKEND: 'software',
        QT_NO_XDG_DESKTOP_PORTAL: '1',
        QS_NO_RELOAD_POPUP: '1',
        NO_AT_BRIDGE: '1',
    });
    for (const [key, value] of Object.entries(extra)) {
        assert(!reserved.test(key), `isolated children never take ${key} from a caller`);
        if (value !== undefined) env[key] = String(value);
    }
    return env;
}

function launch(directory, command, args, bus) {
    if (!bus) return [command, args];
    const config = path.join(directory, 'session-bus.conf');
    fs.writeFileSync(config, busConfig(path.join(directory, 'runtime', 'bus')));
    return ['dbus-run-session', [`--config-file=${config}`, '--', command, ...args]];
}

// Stop the process group and wait, bounded, until no live member remains. The
// leader may be an unreaped zombie, so only non-zombie members count.
function stopGroup(pid) {
    const alive = () => fs.readdirSync('/proc').some(entry => {
        if (!/^\d+$/.test(entry)) return false;
        let stat;
        try {
            stat = fs.readFileSync(`/proc/${entry}/stat`, 'utf8');
        } catch {
            return false;
        }
        const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
        return Number(fields[2]) === pid && fields[0] !== 'Z';
    });
    if (!alive()) return;
    try {
        process.kill(-pid, 'SIGTERM');
    } catch (error) {
        if (error.code === 'ESRCH') return;
        throw error;
    }
    for (let waited = 0; alive(); waited += 20) {
        if (waited >= 5000) {
            process.kill(-pid, 'SIGKILL');
            assert.fail(`isolated process group ${pid} did not exit within 5 s`);
        }
        Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
    }
}

// Without `directory`, the run owns a temporary one and removes it afterwards.
function owned(directory) {
    return directory ? { root: directory, remove() {} } : {
        root: fs.mkdtempSync(path.join(os.tmpdir(), 'nuguland-isolated-')),
        remove() { fs.rmSync(this.root, { recursive: true, force: true }); },
    };
}

// spawnSync in isolation; returns once the child's whole process group is gone.
function runIsolated(command, args = [], { directory, env, bus = false, ...options } = {}) {
    const dir = owned(directory);
    try {
        const [file, argv] = launch(dir.root, command, args, bus);
        const run = childProcess.spawnSync(file, argv, { ...options, env: isolatedEnv(dir.root, env), detached: true });
        if (run.pid) stopGroup(run.pid);
        return run;
    } finally {
        dir.remove();
    }
}

// spawn in isolation; the child's process group is stopped when the child exits
// (a descendant holding its pipes would otherwise keep 'close' from ever coming)
// and is gone before any other 'close' listener runs. stopGroup(child.pid) ends it early.
function spawnIsolated(command, args = [], { directory, env, bus = false, ...options } = {}) {
    const dir = owned(directory);
    let child;
    try {
        const [file, argv] = launch(dir.root, command, args, bus);
        child = childProcess.spawn(file, argv, { ...options, env: isolatedEnv(dir.root, env), detached: true });
    } catch (error) {
        dir.remove();
        throw error;
    }
    child.once('exit', () => stopGroup(child.pid));
    child.once('close', () => {
        try {
            if (child.pid) stopGroup(child.pid);
        } finally {
            dir.remove();
        }
    });
    return child;
}

module.exports = { isolatedEnv, runIsolated, spawnIsolated, stopGroup };