diff --git a/tests/image-bytes.mjs b/tests/image-bytes.mjs index 4325e38..d1a6793 100644 --- a/tests/image-bytes.mjs +++ b/tests/image-bytes.mjs @@ -15,3 +15,14 @@ export const webpL = (w = 4, h = 4) => { const x = Buffer.alloc(5); x[0] = 0x2f; export const webpLossy = (w = 4, h = 4) => { const x = Buffer.alloc(10); Buffer.from([0x9d, 0x01, 0x2a]).copy(x, 3); x.writeUInt16LE(w, 6); x.writeUInt16LE(h, 8); return riff("VP8 ", x); }; export const svg = Buffer.from(''); + +// A Persona's image directory as the installer leaves it: group-inherited and setgid (2750), empty. Not the mouth's to chmod. +import { chmodSync, mkdirSync, mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +export function personaStoreRoot() { + const root = join(mkdtempSync(join(tmpdir(), "images-")), "eureka"); + mkdirSync(root); + chmodSync(root, 0o2750); + return root; +} diff --git a/tests/persona-chat-images.test.mjs b/tests/persona-chat-images.test.mjs index 9c5f010..691f322 100644 --- a/tests/persona-chat-images.test.mjs +++ b/tests/persona-chat-images.test.mjs @@ -3,12 +3,11 @@ import test from "node:test"; import assert from "node:assert/strict"; import { createHash } from "node:crypto"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { chmodSync, chownSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs"; import { join } from "node:path"; -import { MAX_BYTES, MAX_PIXELS, RETAIN_MS, ROOM_CAP_BYTES, classify, createImageStore, fetchImage, sniff } from "../tools/persona-chat-images.mjs"; +import { FETCH_TIMEOUT_MS, MAX_BYTES, MAX_PIXELS, RETAIN_MS, ROOM_CAP_BYTES, classify, createImageStore, fetchImage, sniff } from "../tools/persona-chat-images.mjs"; import * as docs from "../tools/persona-chat-documents.mjs"; -import { gif, jpeg, png, svg, webpL, webpLossy, webpX } from "./image-bytes.mjs"; +import { gif, jpeg, personaStoreRoot, png, svg, webpL, webpLossy, webpX } from "./image-bytes.mjs"; const sha = data => createHash("sha256").update(data).digest("hex"); const HS = "http://hs.test"; @@ -36,6 +35,25 @@ test("fetch uses this Persona's token on the authenticated media path of its own assert.equal(f.calls[0].init.redirect, "error"); }); +test("a redirect is refused, not followed: a fetch that honours redirect:error fails the request", async () => { + // The stub behaves as fetch does: with redirect "error" a redirect response throws; with "follow" it would serve the image from elsewhere. + const redirecting = async (url, init) => { + if (init.redirect === "error") throw new TypeError("fetch failed: redirect"); + return new Response(png(), { status: 200 }); + }; + assert.deepEqual(await get(redirecting), { refusal: "fetch-failed" }); +}); + +test("a fetch that never answers is abandoned at the timeout, and the default is 30 s", async () => { + assert.equal(FETCH_TIMEOUT_MS, 30000); + let seen; + const hanging = (url, init) => new Promise((_, reject) => { seen = init.signal; init.signal.addEventListener("abort", () => reject(init.signal.reason)); }); + const started = Date.now(); + assert.deepEqual(await fetchImage({ fetch: hanging, homeserver: HS, token: "tok-own", mxc, timeoutMs: 50 }), { refusal: "fetch-failed" }); + assert.ok(seen instanceof AbortSignal && seen.aborted); + assert.ok(Date.now() - started < 5000); +}); + test("only a plain mxc url is fetched: no other scheme, no path climbing, nothing missing", async () => { for (const url of [undefined, null, 5, "https://evil.example/x.png", "mxc://gamecult.test/../etc", "mxc://gamecult.test/a/b", "mxc://gamecult.test/a?x=1", "mxc://gamecult.test/", "http://gamecult.test/_matrix/media/x"]) { const f = fakeFetch({ body: png() }); @@ -111,7 +129,7 @@ test("an error status, a missing body or a throwing fetch is a fetch failure", a // ---- the store ---- function storeIn(clock = { t: Date.now() }) { - const root = join(mkdtempSync(join(tmpdir(), "images-")), "eureka"); + const root = personaStoreRoot(); return { root, clock, store: createImageStore({ root, now: () => clock.t }) }; } const files = root => readdirSync(root).flatMap(d => readdirSync(join(root, d)).map(f => `${d}/${f}`)); @@ -136,18 +154,40 @@ test("a sender-chosen name never reaches the disk: the store takes no name at al assert.deepEqual(readdirSync(root).filter(d => !/^[0-9a-f]{64}$/.test(d)), []); }); -test("files are 0640 and directories 0750 with the setgid bit kept, whatever the umask, and no temp file is left", () => { +test("files are 0640 and room directories 0750 plus the setgid they inherit, whatever the umask, and no temp file is left", () => { const old = process.umask(0o077); try { const { root, store } = storeIn(); const ref = store.put("!r:x", png(), "image/png"); assert.equal(statSync(join(root, ref.path)).mode & 0o7777, 0o640); assert.equal(statSync(join(root, ref.path, "..")).mode & 0o7777, 0o2750); - assert.equal(statSync(root).mode & 0o777, 0o750); + assert.equal(statSync(root).mode & 0o7777, 0o2750, "the Persona's directory is the installer's: untouched"); assert.deepEqual(readdirSync(join(root, ref.path, "..")).filter(n => n.startsWith(".tmp-")), []); } finally { process.umask(old); } }); +test("a room directory takes the Persona directory's group by inheritance: it is never chmodded, so a non-member's chmod cannot strip setgid", () => { + // bifrost is not in the Persona's group. Stand in for that with a group the test user belongs to that is not its own. + const other = process.getgroups().find(g => g !== process.getgid()); + if (other === undefined) return; // no second group to inherit from: the next test covers the missing-setgid refusal + const { root, store } = storeIn(); + try { chownSync(root, process.getuid(), other); } catch { return; } // a sandbox that will not hand the directory to that group cannot show inheritance + chmodSync(root, 0o2750); + const ref = store.put("!r:x", png(), "image/png"); + assert.equal(statSync(join(root, ref.path, "..")).gid, other); + assert.equal(statSync(join(root, ref.path)).gid, other); + assert.equal(statSync(join(root, ref.path, "..")).mode & 0o2000, 0o2000); +}); + +test("a Persona directory without setgid refuses the image: nothing is written, and the directories are not chmodded to hide it", () => { + const { root, store } = storeIn(); + chmodSync(root, 0o750); + assert.throws(() => store.put("!r:x", png(), "image/png"), { code: "ENOSETGID" }); + assert.deepEqual(files(root), []); + assert.equal(statSync(root).mode & 0o7777, 0o750, "the installer's directory keeps its mode"); + assert.equal(statSync(join(root, sha("!r:x"))).mode & 0o7777, 0o750, "the room directory it made is left as mkdir made it"); +}); + test("a write that cannot finish leaves no temp file and no partial image under the final name", () => { const { root, store } = storeIn(); const bytes = png(6, 6); diff --git a/tests/persona-matrix-mouth.test.mjs b/tests/persona-matrix-mouth.test.mjs index 62100b7..680eef8 100644 --- a/tests/persona-matrix-mouth.test.mjs +++ b/tests/persona-matrix-mouth.test.mjs @@ -7,6 +7,7 @@ import { existsSync, mkdtempSync, statSync as stat } from "node:fs"; import { tmpdir } from "node:os"; import { createHash } from "node:crypto"; import { createImageStore, RETAIN_MS } from "../tools/persona-chat-images.mjs"; +import { personaStoreRoot } from "./image-bytes.mjs"; import * as docs from "../tools/persona-chat-documents.mjs"; import { gif, png, svg } from "./image-bytes.mjs"; import { createMouth, bodyText, createBrakeReader, guarded, redact, roomsFor, projectRoomsVariable } from "../tools/persona-matrix-mouth.mjs"; @@ -788,7 +789,7 @@ const imageTimeline = (events, room = IMG_ROOM) => ({ }); const served = bytes => (bearer, server, id) => (bearer === TOKEN && server === "gamecult.test" && id === "AbC_123-x" ? { status: 200, body: bytes } : { status: 401, body: "" }); function imageSetup(clock = { t: Date.now() }) { - const root = join(mkdtempSync(join(tmpdir(), "mouth-images-")), "eureka"); + const root = personaStoreRoot(); return { root, clock, images: createImageStore({ root, now: () => clock.t }) }; } async function receive(events, { media: mediaFn, room, images, mouthOptions = {} } = {}) { diff --git a/tools/persona-chat-images.mjs b/tools/persona-chat-images.mjs index 1e3fd67..19f19db 100644 --- a/tools/persona-chat-images.mjs +++ b/tools/persona-chat-images.mjs @@ -5,7 +5,7 @@ // are never read), the size and pixel counts are bounded before anything decodes the image, and every name on disk is // generated here from hashes. Refusals are a fixed word list so a refusal can be printed without printing sender text. import { createHash, randomBytes } from "node:crypto"; -import { chmodSync, closeSync, fsyncSync, mkdirSync, openSync, readdirSync, renameSync, statSync, unlinkSync, writeSync } from "node:fs"; +import { closeSync, fsyncSync, mkdirSync, openSync, readdirSync, renameSync, statSync, unlinkSync, writeSync } from "node:fs"; import { join } from "node:path"; export const MAX_BYTES = 5 * 1024 * 1024; @@ -13,8 +13,8 @@ export const MAX_PIXELS = 40_000_000; export const ROOM_CAP_BYTES = 50 * 1024 * 1024; export const RETAIN_MS = 24 * 60 * 60 * 1000; export const FILE_MODE = 0o640; -export const DIR_MODE = 0o2750; // setgid is kept: the group of the Persona's directory is inherited by what lands in it -const FETCH_TIMEOUT_MS = 30000; +export const DIR_MODE = 0o750; // a room directory's mode at mkdir; its setgid bit comes from the Persona's directory, never from a chmod +export const FETCH_TIMEOUT_MS = 30000; // Why an image was not stored. Printed in the delivery's text line, so only these words ever are. export const refusals = Object.freeze(["encrypted", "no-url", "fetch-failed", "too-big", "wrong-type", "bad-header", "too-many-pixels", "store-failed"]); @@ -87,10 +87,10 @@ export function classify(bytes) { // GET the attachment named by `mxc` as this Persona: its token, its homeserver, the authenticated media path. The // body is read stream-wise and abandoned the moment it passes the cap, whatever Content-Length said. // Returns { bytes, mime, ext } or { refusal }. -export async function fetchImage({ fetch: httpFetch, homeserver, token, mxc }) { +export async function fetchImage({ fetch: httpFetch, homeserver, token, mxc, timeoutMs = FETCH_TIMEOUT_MS }) { const named = typeof mxc === "string" ? MXC.exec(mxc) : null; if (!named) return { refusal: "no-url" }; - const signal = AbortSignal.timeout(FETCH_TIMEOUT_MS); + const signal = AbortSignal.timeout(timeoutMs); try { const response = await httpFetch(`${homeserver}/_matrix/client/v1/media/download/${named[1]}/${named[2]}`, { method: "GET", headers: { authorization: `Bearer ${token}` }, redirect: "error", signal, @@ -165,17 +165,24 @@ export function createImageStore({ root, now = Date.now, log = () => {} }) { const ext = EXT[mime]; const path = `${room}/${digest}.${ext}`; const dir = join(root, room); - const created = mkdirSync(root, { recursive: true }); - if (created) chmodSync(root, 0o750); - mkdirSync(dir, { recursive: true }); - chmodSync(dir, DIR_MODE); - const temp = join(dir, `.tmp-${randomBytes(8).toString("hex")}`); - const fd = openSync(temp, "wx", FILE_MODE); + // The Persona's directory (`root`) belongs to the installer: bifrost:mind-, 2750. It is never chmodded here, and + // neither is a room directory: bifrost is not in the Persona's group, and a chmod by a non-member clears setgid. A room + // directory inherits group and setgid from `root` at mkdir; if it did not, a file in it would take bifrost's group and the + // Persona's reader could not open it, so the image is refused instead. + // No chmod can set the group bits without risking setgid, so the creation modes must be exact: a fixed umask (it only + // withholds other-access) for the mkdir and the open, restored at once. Synchronous, so nothing else runs under it. + const umask = process.umask(0o027); + let temp, fd; + try { + mkdirSync(dir, { recursive: true, mode: DIR_MODE }); + if ((statSync(dir).mode & 0o2000) === 0) throw Object.assign(new Error("image directory lacks the setgid bit"), { code: "ENOSETGID" }); + temp = join(dir, `.tmp-${randomBytes(8).toString("hex")}`); + fd = openSync(temp, "wx", FILE_MODE); + } finally { process.umask(umask); } try { writeSync(fd, bytes); fsyncSync(fd); } finally { closeSync(fd); } - chmodSync(temp, FILE_MODE); try { renameSync(temp, join(dir, `${digest}.${ext}`)); } catch (error) { try { unlinkSync(temp); } catch { /* gone */ } throw error; } entries.set(path, { room, size: bytes.length, storedAt: now(), seq: entries.get(path)?.seq ?? null }); evict(room, path);