Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f

### Fixes & Improvements

- **Host daemons recover from changed local control permissions.** On Unix, startup restores its own control directory to `0700` and its own socket to `0600`, then reclaims the socket only if its daemon has died. A live daemon keeps its endpoint; symlinks, foreign-owned objects and unexpected file types still block replacement, and control clients still refuse insecure endpoints. Shutdown also removes its own socket if permissions changed while it ran. A permission mismatch no longer strands an otherwise recoverable host in a restart loop.
- **omp updates with ompweb: the omp row no longer runs `omp update`.** Each ompweb release ships its own omp runner, so Settings → Hosts shows the host's omp version with "Updated with ompweb" and no update button. Hosts refuse an omp update request, and `/api/omp-update` keeps only `restart`.
- **Sorting, pinning and reordering work in the cluster's sidebar group.** The group listed the cluster's shared projects first whatever the sort, and Move up/down, drag and pins only worked among projects of the same machine, so a pinned or alphabetically earlier project of a member could not move above a shared one. The group is now one list: the chosen sort, pins and manual order apply across shared projects and every member's own projects.
- **Cluster members install plugins from the source this machine installed them from.** A plugin installed here from Git (`github:…`, `git+…`) or a tarball URL is installed the same way on each member instead of as an unrelated npm package of the same name and version, and a member that already has that npm package replaces it. A plugin linked or installed from a local folder here is not installed on members; Settings → Hosts shows the member as failed and names the plugin to install there by hand. A source that installs a different version than this machine runs (an unpinned Git branch, for example) also shows the member as failed, with both versions. Credentials in a source never appear in the host daemon log.
Expand Down
87 changes: 69 additions & 18 deletions lib/hosts/host-control.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ test("non-socket and symlink endpoints are never removed by either client or ser
}
});

test("a symlink or non-private runtime directory is refused without changing it", unixOnly, async (t) => {
test("a symlink runtime directory is refused without changing it", unixOnly, async (t) => {
const f = await fixture(t);
const dir = dirname(f.path);
const target = join(f.scratch, "foreign-directory");
Expand All @@ -127,28 +127,79 @@ test("a symlink or non-private runtime directory is refused without changing it"
await assert.rejects(createHostControlServer(f.daemon.control, f.agent), /directory|symlink|unsafe|private/i);
assert.equal(lstatSync(dir).isSymbolicLink(), true);
unlinkSync(dir);
mkdirSync(dir, { mode: 0o755 });
await assert.rejects(createHostControlServer(f.daemon.control, f.agent), /permission|private|0700|unsafe/i);
assert.equal(lstatSync(dir).mode & 0o777, 0o755);
});

test("an actual refused stale owned socket is recovered after its process dies", unixOnly, async (t) => {
test("startup restores privacy on its owned runtime directory", unixOnly, async (t) => {
const f = await fixture(t);
mkdirSync(dirname(f.path), { recursive: true, mode: 0o700 });
const source = `const fs=require('node:fs');require('node:net').createServer().listen(${JSON.stringify(f.path)},()=>{fs.chmodSync(${JSON.stringify(f.path)},0o600);console.log('listening')});`;
const child = spawn(process.execPath, ["-e", source], { stdio: ["ignore", "pipe", "pipe"] });
let stdout = "";
child.stdout.on("data", (chunk) => { stdout += chunk; });
const exited = new Promise((resolve) => child.once("exit", resolve));
t.after(() => child.kill("SIGKILL"));
await until(() => stdout.includes("listening"), "the real Unix listener");
child.kill("SIGKILL");
await exited;
assert.equal(lstatSync(f.path).isSocket(), true, "the crashed process left its own endpoint");
await assert.rejects(rawRequest(f.path, '{"command":"status"}\n'), { code: "ECONNREFUSED" });
const dir = dirname(f.path);
mkdirSync(dir, { mode: 0o700 });
chmodSync(dir, 0o777);
const server = await createHostControlServer(f.daemon.control, f.agent);
t.after(() => server.close());
assert.equal((await requestHostControl("status", f.agent)).pid, process.pid);
assert.equal(lstatSync(dir).mode & 0o777, 0o700);
assert.equal((await requestHostControl("drain", f.agent)).drained, true);
});

test("repairing permissions never replaces a live daemon", unixOnly, async (t) => {
const f = await fixture(t);
const server = await createHostControlServer(f.daemon.control, f.agent);
t.after(() => server.close());
const before = lstatSync(f.path);
chmodSync(dirname(f.path), 0o777);
chmodSync(f.path, 0o666);
await assert.rejects(requestHostControl("drain", f.agent), /permission|private/i);
await assert.rejects(createHostControlServer(f.daemon.control, f.agent), /already|running|occupied|in use/i);
assert.equal(lstatSync(f.path).ino, before.ino);
assert.equal(lstatSync(dirname(f.path)).mode & 0o777, 0o700);
assert.equal(lstatSync(f.path).mode & 0o777, 0o600);
assert.equal((await requestHostControl("status", f.agent)).drained, false);
});

test("foreign-owned runtime directories are never repaired", { ...unixOnly, skip: process.platform === "win32" || process.getuid?.() !== 0 ? "Requires Unix root to create an actually foreign-owned directory" : false }, async (t) => {
const f = await fixture(t);
const dir = dirname(f.path);
mkdirSync(dir, { mode: 0o700 });
chmodSync(dir, 0o777);
chownSync(dir, 65534, 65534);
await assert.rejects(createHostControlServer(f.daemon.control, f.agent), /owner|owned|foreign|unsafe/i);
assert.equal(lstatSync(dir).mode & 0o777, 0o777);
assert.equal(lstatSync(dir).uid, 65534);
assert.equal(existsSync(f.path), false);
});

for (const [directoryMode, socketMode] of [[0o700, 0o600], [0o777, 0o666], [0o755, 0o000], [0o000, 0o000]]) {
test(`a crashed daemon recovers with directory ${directoryMode.toString(8)} and socket ${socketMode.toString(8)}`, unixOnly, async (t) => {
const f = await fixture(t);
mkdirSync(dirname(f.path), { recursive: true, mode: 0o700 });
const source = `const fs=require('node:fs');require('node:net').createServer().listen(${JSON.stringify(f.path)},()=>{fs.chmodSync(${JSON.stringify(f.path)},0o600);console.log('listening')});`;
const child = spawn(process.execPath, ["-e", source], { stdio: ["ignore", "pipe", "pipe"] });
let stdout = "";
child.stdout.on("data", (chunk) => { stdout += chunk; });
const exited = new Promise((resolve) => child.once("exit", resolve));
t.after(() => child.kill("SIGKILL"));
await until(() => stdout.includes("listening"), "the real Unix listener");
child.kill("SIGKILL");
await exited;
assert.equal(lstatSync(f.path).isSocket(), true, "the crashed process left its own endpoint");
await assert.rejects(rawRequest(f.path, '{"command":"status"}\n'), { code: "ECONNREFUSED" });
chmodSync(f.path, socketMode);
chmodSync(dirname(f.path), directoryMode);
const server = await createHostControlServer(f.daemon.control, f.agent);
t.after(() => server.close());
assert.equal(lstatSync(dirname(f.path)).mode & 0o777, 0o700);
assert.equal(lstatSync(f.path).mode & 0o777, 0o600);
assert.equal((await requestHostControl("status", f.agent)).pid, process.pid);
});
}

test("shutdown removes its own socket after permissions drift", unixOnly, async (t) => {
const f = await fixture(t);
const server = await createHostControlServer(f.daemon.control, f.agent);
t.after(() => server.close());
chmodSync(dirname(f.path), 0o777);
chmodSync(f.path, 0o666);
await server.close();
assert.equal(existsSync(f.path), false);
});

test("closing an endpoint never unlinks a replacement created after acquisition", unixOnly, async (t) => {
Expand Down
45 changes: 39 additions & 6 deletions lib/hosts/host-control.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// local users connect and whose name anyone may claim first, so the pipe name is random per start and every
// request carries a per-start token; both live only in a descriptor file in this user's agent directory.
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
import { chmodSync, linkSync, lstatSync, mkdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync, type Stats } from "node:fs";
import { chmodSync, closeSync, constants, fchmodSync, fstatSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, unlinkSync, writeFileSync, type Stats } from "node:fs";
import { createConnection, createServer, type Server } from "node:net";
import { basename, dirname, join, resolve } from "node:path";
import { getAgentDir } from "../omp/paths";
Expand Down Expand Up @@ -79,17 +79,45 @@ export function hostControlPath(agentDir = getAgentDir()): string {
return join(realpathSync("/tmp"), `ompweb-host-${process.getuid!()}-${hash}`, "control.sock");
}

function owned(path: string, kind: "directory" | "socket", mode: number): Stats {
function owned(path: string, kind: "directory" | "socket", mode?: number): Stats {
const stat = lstatSync(path);
if (stat.isSymbolicLink() || stat.uid !== process.getuid!() || (kind === "directory" ? !stat.isDirectory() : !stat.isSocket())) {
throw new Error(`Unsafe host control ${kind}: not an owned ${kind}`);
}
if ((stat.mode & 0o777) !== mode) throw new Error(`Host control ${kind} must have private ${mode.toString(8)} permissions`);
if (mode !== undefined && (stat.mode & 0o777) !== mode) throw new Error(`Host control ${kind} must have private ${mode.toString(8)} permissions`);
return stat;
}
const same = (left: Stats, right: Stats) => left.ino === right.ino && left.dev === right.dev && left.uid === right.uid && left.mode === right.mode;
const sameIdentity = (left: Stats, right: Stats) => left.ino === right.ino && left.dev === right.dev && left.uid === right.uid;
const same = (left: Stats, right: Stats) => sameIdentity(left, right) && left.mode === right.mode;

function secureDirectory(path: string): Stats {
const previous = owned(path, "directory");
const flags = constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW;
let fd: number;
try {
fd = openSync(path, flags);
} catch (error) {
if (errno(error) !== "EACCES") throw error;
const parent = lstatSync(dirname(path));
// A root-owned sticky parent prevents another UID replacing our unreadable directory during chmod.
if (!parent.isDirectory() || parent.uid !== 0 || !(parent.mode & 0o1000)
|| !sameIdentity(previous, owned(path, "directory"))) throw error;
chmodSync(path, 0o700);
fd = openSync(path, flags);
}
try {
if (!sameIdentity(previous, fstatSync(fd))) throw new Error("Host control directory changed during permission recovery");
// Repair the verified inode, never a pathname another local user could replace with a symlink.
if ((fstatSync(fd).mode & 0o777) !== 0o700) fchmodSync(fd, 0o700);
const current = owned(path, "directory", 0o700);
if (!same(fstatSync(fd), current)) throw new Error("Host control directory changed during permission recovery");
return current;
} finally {
closeSync(fd);
}
}
function removeOwn(path: string, acquired: Stats): void {
try { if (same(acquired, lstatSync(path))) unlinkSync(path); }
try { if (sameIdentity(acquired, lstatSync(path))) unlinkSync(path); }
catch (error) { if (errno(error) !== "ENOENT") throw error; }
}

Expand Down Expand Up @@ -182,10 +210,15 @@ export async function createHostControlServer(control: (command: HostControlComm
const path = hostControlPath(agentDir);
const dir = dirname(path);
try { mkdirSync(dir, { mode: 0o700 }); } catch (error) { if (errno(error) !== "EEXIST") throw error; }
owned(dir, "directory", 0o700);
const directory = secureDirectory(dir);
try {
const previous = owned(path, "socket");
// The directory is now private; tighten an owned socket before probing, including a mode-000 socket.
if ((previous.mode & 0o777) !== 0o600) chmodSync(path, 0o600);
const stale = owned(path, "socket", 0o600);
if (!sameIdentity(previous, stale)) throw new Error("Host control endpoint changed during permission recovery");
await refused(path);
if (!same(directory, owned(dir, "directory", 0o700))) throw new Error("Host control directory changed during stale recovery");
const current = owned(path, "socket", 0o600);
if (!same(stale, current)) throw new Error("Host control endpoint changed during stale recovery");
unlinkSync(path);
Expand Down
Loading