Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,302 @@
|
||||
"use strict";
|
||||
|
||||
// Tests for the file action-token mint gates on GET /api/servers/:name/permissions.
|
||||
//
|
||||
// The audit finding: every file token was minted under the wrong permission
|
||||
// gate (fileWrite+fileMkdir under files_create, fileDelete+fileRename under
|
||||
// files_delete, fileUpload+fileExtract+fileArchive under files_upload), while
|
||||
// the consumer endpoints accept other grants:
|
||||
// PUT /api/servers/:name/files/write accepts files_create OR files_write
|
||||
// POST /api/servers/:name/files/rename accepts files_rename (not files_delete)
|
||||
// POST /extract accepts files_create (not files_upload)
|
||||
// POST /archive accepts files_archive (not files_upload)
|
||||
// A single-perm user (e.g. files_write only) could pass an endpoint's perm gate
|
||||
// yet never receive its token; the client's 403-retry loop re-fetches this same
|
||||
// gated mint and fails closed forever with ACTION_TOKEN_INVALID.
|
||||
//
|
||||
// The fix mirrors each endpoint's accepted-permission check exactly in the mint
|
||||
// block. This file locks in:
|
||||
// 1. Mint eligibility: a user holding ANY permission an endpoint accepts gets
|
||||
// that endpoint's token; a user with none gets none (executed per-perms in
|
||||
// a vm sandbox with a recording issueActionToken stub).
|
||||
// 2. Token binding: the minted write token verifies through the real
|
||||
// verifyActionToken machinery (mint → verify roundtrip, same technique as
|
||||
// reinstall-route-protection).
|
||||
// 3. Endpoint acceptance sets unchanged (source assertions on each route's
|
||||
// perm gate — index.js and the nodes.js upload relay).
|
||||
// 4. Frontend contract: the client retry loop requests the matching token key
|
||||
// for each operation and gates the UI on the same perms the endpoints
|
||||
// accept, so a fixed mint alone unblocks single-perm users.
|
||||
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const vm = require("node:vm");
|
||||
const crypto = require("node:crypto");
|
||||
|
||||
const ROOT = path.join(__dirname, "..");
|
||||
const INDEX_JS = path.join(ROOT, "index.js");
|
||||
const NODES_JS = path.join(ROOT, "nodes.js");
|
||||
const BOT_JS = path.join(ROOT, "public", "js", "bot.js");
|
||||
|
||||
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
|
||||
const nodesSource = fs.readFileSync(NODES_JS, "utf8");
|
||||
const botSource = fs.readFileSync(BOT_JS, "utf8");
|
||||
|
||||
function extractRoute(source, routeMarker, nextRouteMarker) {
|
||||
const start = source.indexOf(routeMarker);
|
||||
assert.ok(start >= 0, `route marker not found: ${routeMarker}`);
|
||||
const end = source.indexOf(nextRouteMarker, start);
|
||||
assert.ok(end > start, `next route marker not found after route: ${nextRouteMarker}`);
|
||||
return source.slice(start, end);
|
||||
}
|
||||
|
||||
// Slice the mint block out of the permissions route and compile it into a
|
||||
// standalone function `mint(perms, issueActionToken, req)` so each permission
|
||||
// combination can be executed for real instead of pattern-matched.
|
||||
const MINT_START_MARKER = "const actionTokens = {};\n // Mint eligibility mirrors";
|
||||
const MINT_END_MARKER = "if (perms.store_access) {";
|
||||
const mintBlock = (() => {
|
||||
const start = indexSource.indexOf(MINT_START_MARKER);
|
||||
assert.ok(start >= 0, "mint block start marker not found (did the mint block move?)");
|
||||
const end = indexSource.indexOf(MINT_END_MARKER, start);
|
||||
assert.ok(end > start, "mint block end marker not found");
|
||||
return indexSource.slice(start, end);
|
||||
})();
|
||||
|
||||
function compileMint() {
|
||||
const sandbox = {};
|
||||
vm.createContext(sandbox);
|
||||
return vm.runInContext(
|
||||
`(function (perms, issueActionToken, req, serverName) {\n${mintBlock}\n return actionTokens;\n})`,
|
||||
sandbox
|
||||
);
|
||||
}
|
||||
|
||||
const MINT_SERVER_NAME = "srv-1";
|
||||
|
||||
function runMint(perms) {
|
||||
const mint = compileMint();
|
||||
const minted = [];
|
||||
const tokens = mint(
|
||||
perms,
|
||||
(req, action, resource, opts) => {
|
||||
minted.push({ action, resource, opts });
|
||||
return `tok:${action}`;
|
||||
},
|
||||
{},
|
||||
MINT_SERVER_NAME
|
||||
);
|
||||
return { tokens, minted };
|
||||
}
|
||||
|
||||
test("files_write-only user mints fileWrite (the audit's locked-out case)", () => {
|
||||
const { tokens, minted } = runMint({ files_write: true });
|
||||
assert.deepEqual(Object.keys(tokens), ["fileWrite"]);
|
||||
assert.equal(tokens.fileWrite, "tok:PUT /api/servers/:name/files/write");
|
||||
assert.equal(minted[0].action, "PUT /api/servers/:name/files/write");
|
||||
assert.deepEqual(minted[0].resource, { serverName: MINT_SERVER_NAME });
|
||||
});
|
||||
|
||||
test("files_create-only user mints fileWrite, fileMkdir and fileExtract", () => {
|
||||
const { tokens } = runMint({ files_create: true });
|
||||
assert.deepEqual(Object.keys(tokens).sort(), ["fileExtract", "fileMkdir", "fileWrite"]);
|
||||
assert.equal(tokens.fileExtract, "tok:POST /extract");
|
||||
});
|
||||
|
||||
test("files_rename-only user mints fileRename; files_archive-only mints fileArchive", () => {
|
||||
const rename = runMint({ files_rename: true });
|
||||
assert.deepEqual(Object.keys(rename.tokens), ["fileRename"]);
|
||||
assert.equal(rename.tokens.fileRename, "tok:POST /api/servers/:name/files/rename");
|
||||
assert.equal(rename.minted[0].opts.oneTime, true);
|
||||
|
||||
const archive = runMint({ files_archive: true });
|
||||
assert.deepEqual(Object.keys(archive.tokens), ["fileArchive"]);
|
||||
assert.equal(archive.tokens.fileArchive, "tok:POST /archive");
|
||||
});
|
||||
|
||||
test("files_upload-only user mints only fileUpload (extract/archive need other perms)", () => {
|
||||
const { tokens } = runMint({ files_upload: true });
|
||||
assert.deepEqual(Object.keys(tokens), ["fileUpload"]);
|
||||
assert.equal(tokens.fileUpload, "tok:POST /upload");
|
||||
});
|
||||
|
||||
test("files_delete-only user mints only fileDelete (rename needs files_rename)", () => {
|
||||
const { tokens } = runMint({ files_delete: true });
|
||||
assert.deepEqual(Object.keys(tokens), ["fileDelete"]);
|
||||
assert.equal(tokens.fileDelete, "tok:DELETE /api/servers/:name/files/delete");
|
||||
});
|
||||
|
||||
test("user with none of an endpoint's perms mints no token for it (fail closed)", () => {
|
||||
const { tokens } = runMint({});
|
||||
assert.deepEqual(tokens, {});
|
||||
const noFsPerms = runMint({ console_write: true, server_start: true });
|
||||
assert.deepEqual(noFsPerms.tokens, {});
|
||||
});
|
||||
|
||||
test("every token is still session+server bound through issueActionToken's resource arg", () => {
|
||||
const seen = [];
|
||||
const mint = compileMint();
|
||||
mint(
|
||||
{ files_create: true, files_write: true, files_rename: true, files_archive: true, files_upload: true },
|
||||
(req, action, resource) => {
|
||||
seen.push({ action, resource });
|
||||
return "tok";
|
||||
},
|
||||
{},
|
||||
MINT_SERVER_NAME
|
||||
);
|
||||
for (const entry of seen) {
|
||||
assert.deepEqual(entry.resource, { serverName: MINT_SERVER_NAME }, `${entry.action} must stay server-scoped`);
|
||||
}
|
||||
});
|
||||
|
||||
// The token helpers (safeCompare .. requireActionTokenOr403) form one
|
||||
// contiguous region in index.js; the one-time nonce claim machinery lives in a
|
||||
// separate region (same technique as reinstall-route-protection.test.js).
|
||||
function buildTokenSandbox() {
|
||||
const start = indexSource.indexOf("function safeCompare(a, b) {");
|
||||
const endMarker = "function readJson(file, fallback) {";
|
||||
const end = indexSource.indexOf(endMarker);
|
||||
assert.ok(start >= 0 && end > start, "token helper region not found");
|
||||
|
||||
const claimStart = indexSource.indexOf("const CONSUMED_ACTION_TOKEN_REDIS_PREFIX =");
|
||||
const claimEndMarker = "// Single-use consumption.";
|
||||
const claimEnd = indexSource.indexOf(claimEndMarker);
|
||||
assert.ok(claimStart >= 0 && claimEnd > claimStart, "consumed-token claim region not found");
|
||||
|
||||
const sandbox = {
|
||||
crypto,
|
||||
Buffer,
|
||||
Date,
|
||||
console: { log() { }, warn() { }, error() { } },
|
||||
process: { env: { ACTION_TOKEN_SECRET: "test-action-token-secret", SESSION_SECRET: "test-session-secret" } },
|
||||
SESSION_REVOKE_TARGET_TOKEN_TTL_MS: 10 * 60 * 1000,
|
||||
redisClient: undefined,
|
||||
getSessionDisplayId: (id) => String(id || ""),
|
||||
};
|
||||
vm.createContext(sandbox);
|
||||
vm.runInContext(indexSource.slice(claimStart, claimEnd), sandbox);
|
||||
vm.runInContext(indexSource.slice(start, end), sandbox);
|
||||
return sandbox;
|
||||
}
|
||||
|
||||
test("files_write-only flow: minted write token verifies against the write action; other actions reject it", async () => {
|
||||
const sandbox = buildTokenSandbox();
|
||||
const out = await vm.runInContext(`
|
||||
(async () => {
|
||||
const ACTION = "PUT /api/servers/:name/files/write";
|
||||
const RES = { serverName: "srv-1" };
|
||||
const req = { session: { user: "writer@example.com" }, sessionID: "sess-1", get: () => null, body: {} };
|
||||
const token = issueActionToken(req, ACTION, RES, { ttlSeconds: 300 });
|
||||
return ({
|
||||
verify: await verifyActionToken(req, token, ACTION, RES),
|
||||
wrongAction: await verifyActionToken(req, token, "POST /extract", RES),
|
||||
wrongServer: await verifyActionToken(req, token, ACTION, { serverName: "other" }),
|
||||
});
|
||||
})()
|
||||
`, sandbox);
|
||||
assert.equal(out.verify, true, "a files_write-only user's write token must verify for the write endpoint");
|
||||
assert.equal(out.wrongAction, false, "write token must not verify for a different action");
|
||||
assert.equal(out.wrongServer, false, "write token must stay bound to its server");
|
||||
});
|
||||
|
||||
test("requireActionTokenOr403 still fails closed without a token (write action)", async () => {
|
||||
const sandbox = buildTokenSandbox();
|
||||
const out = await vm.runInContext(`
|
||||
(async () => {
|
||||
const calls = { status: null, payload: null };
|
||||
const res = { status(c) { calls.status = c; return { json(p) { calls.payload = p; } }; } };
|
||||
const req = { session: { user: "writer@example.com" }, sessionID: "sess-1", get: () => null, body: {} };
|
||||
const ok = await requireActionTokenOr403(req, res, "PUT /api/servers/:name/files/write", { serverName: "srv-1" });
|
||||
return ({ ok, status: calls.status, code: calls.payload && calls.payload.code });
|
||||
})()
|
||||
`, sandbox);
|
||||
assert.equal(out.ok, false);
|
||||
assert.equal(out.status, 403);
|
||||
assert.equal(out.code, "ACTION_TOKEN_INVALID");
|
||||
});
|
||||
|
||||
// --- Endpoint acceptance sets are unchanged: each route still gates on exactly
|
||||
// --- the perms the mint block now mirrors.
|
||||
|
||||
test("write endpoint accepts files_create OR files_write (unchanged)", () => {
|
||||
const route = extractRoute(
|
||||
indexSource,
|
||||
'app.put("/api/servers/:name/files/write"',
|
||||
'app.post("/api/servers/:name/files/mkdir"'
|
||||
);
|
||||
assert.match(route, /requireActionTokenOr403\(req, res, "PUT \/api\/servers\/:name\/files\/write", \{ serverName: name \}\)/);
|
||||
assert.match(route, /const canCreate = admin \|\| !!perms\.files_create;/);
|
||||
assert.match(route, /const canWrite = admin \|\| !!perms\.files_write;/);
|
||||
assert.match(route, /if \(!canCreate && !canWrite\) return res\.status\(403\)\.json\(\{ error: "not authorized" \}\);/);
|
||||
});
|
||||
|
||||
test("mkdir/delete/rename endpoints keep their single-perm gates (unchanged)", () => {
|
||||
const mkdir = extractRoute(indexSource, 'app.post("/api/servers/:name/files/mkdir"', 'app.delete("/api/servers/:name/files/delete"');
|
||||
assert.match(mkdir, /requireActionTokenOr403\(req, res, "POST \/api\/servers\/:name\/files\/mkdir"/);
|
||||
assert.match(mkdir, /if \(!perms\.files_create\) return res\.status\(403\)\.json\(\{ error: "not authorized" \}\);/);
|
||||
|
||||
const del = extractRoute(indexSource, 'app.delete("/api/servers/:name/files/delete"', 'app.post("/api/servers/:name/files/rename"');
|
||||
assert.match(del, /requireActionTokenOr403\(req, res, "DELETE \/api\/servers\/:name\/files\/delete"/);
|
||||
assert.match(del, /if \(!perms\.files_delete\) return res\.status\(403\)\.json\(\{ error: "not authorized" \}\);/);
|
||||
|
||||
const rename = extractRoute(indexSource, 'app.post("/api/servers/:name/files/rename"', "function streamPanelUploadToNode(");
|
||||
assert.match(rename, /requireActionTokenOr403\(req, res, "POST \/api\/servers\/:name\/files\/rename"/);
|
||||
assert.match(rename, /if \(!perms\.files_rename\) return res\.status\(403\)\.json\(\{ error: "not authorized" \}\);/);
|
||||
});
|
||||
|
||||
test("upload/extract/archive endpoints keep their single-perm gates (unchanged)", () => {
|
||||
const upload = extractRoute(indexSource, 'app.post("/upload", serverFsUploadRateLimiter', 'app.post("/upload-url"');
|
||||
assert.match(upload, /requireActionTokenOr403\(req, res, "POST \/upload", \{ serverName: bot \}\)/);
|
||||
assert.match(upload, /const admin = await isAdmin\(req\);/);
|
||||
assert.match(upload, /if \(!perms\.files_upload && !admin\)/);
|
||||
assert.match(upload, /const createOnly = !admin && !perms\.files_write;/);
|
||||
|
||||
const extract = extractRoute(indexSource, 'app.post("/extract", serverFsMutateRateLimiter', 'app.post("/archive", serverFsMutateRateLimiter');
|
||||
assert.match(extract, /requireActionTokenOr403\(req, res, "POST \/extract", \{ serverName: bot \}\)/);
|
||||
// The admin bypass moved onto a pre-awaited variable so the same isAdmin
|
||||
// lookup can also derive the extract-no-clobber overwrite flag; both the
|
||||
// derivation and the files_create/admin gate stay pinned.
|
||||
assert.match(extract, /const admin = await isAdmin\(req\);/);
|
||||
assert.match(extract, /if \(!perms\.files_create && !admin\) return res\.status\(403\)\.json\(\{ error: "not authorized" \}\);/);
|
||||
|
||||
const archive = extractRoute(indexSource, 'app.post("/archive", serverFsMutateRateLimiter', 'app.post("/create"');
|
||||
assert.match(archive, /requireActionTokenOr403\(req, res, "POST \/archive", \{ serverName: bot \}\)/);
|
||||
assert.match(archive, /if \(!perms\.files_archive && !\(await isAdmin\(req\)\)\)/);
|
||||
});
|
||||
|
||||
test("node relay upload keeps verifying the same 'POST /upload' action under files_upload", () => {
|
||||
// The relay trims the server name so the verify pair is symmetric with the
|
||||
// mint (which trims req.params.name via sanitizeServerToken).
|
||||
assert.match(
|
||||
nodesSource,
|
||||
/await _requireActionTokenOr403\(req, res, "POST \/upload", \{ serverName: String\(req\.params\.name \|\| ""\)\.trim\(\) \}\)/,
|
||||
"relay must verify the same action the permissions endpoint mints for fileUpload"
|
||||
);
|
||||
const relayUpload = extractRoute(nodesSource, 'app.post("/api/nodes/server/:name/upload"', 'app.post("/api/nodes/server/:name/upload-url"');
|
||||
assert.match(relayUpload, /checkUserPerm\(req, req\.params\.name, "files_upload"\)/);
|
||||
});
|
||||
|
||||
// --- Frontend contract: retry loop + token-key mapping, so the mint fix alone
|
||||
// --- unblocks single-perm users.
|
||||
|
||||
test("bot.js retry loop re-fetches the mint on ACTION_TOKEN_INVALID and maps operations to the right token keys", () => {
|
||||
assert.match(botSource, /INVALID_ACTION_TOKEN_ERROR = 'invalid or missing action token'/);
|
||||
assert.match(
|
||||
botSource,
|
||||
/if \(retryOnInvalidToken && response\.status === 403\) \{[\s\S]*?isInvalidActionTokenErrorPayload\(errData\)[\s\S]*?response = await runRequest\(true\);/,
|
||||
"a 403 ACTION_TOKEN_INVALID must trigger one refreshed retry through ensureServerActionToken"
|
||||
);
|
||||
assert.match(botSource, /fetchWithServerActionToken\(`\/api\/servers\/\$\{encodeURIComponent\(serverName\)\}\/files\/write`[\s\S]*?'fileWrite'\)/);
|
||||
assert.match(botSource, /fetchWithServerActionToken\(url, requestOptions, 'fileExtract'\)/);
|
||||
assert.match(botSource, /fetchWithServerActionToken\(url, requestOptions, 'fileArchive'\)/);
|
||||
assert.match(botSource, /ensureServerActionToken\('fileUpload', \{ refresh: true \}\)/);
|
||||
});
|
||||
|
||||
test("bot.js UI gates extract/archive/write on the same perms the endpoints accept", () => {
|
||||
assert.match(botSource, /return hasPerm\('files_write'\) \|\| hasPerm\('files_create'\);/, "editor save gate");
|
||||
assert.match(botSource, /if \(isArchive && hasPerm\('files_create'\)\) \{/, "extract gate");
|
||||
assert.match(botSource, /const canArchive = hasPerm\('files_archive'\);/, "archive gate");
|
||||
});
|
||||
Reference in new issue
Block a user