Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

+147
View File
@@ -0,0 +1,147 @@
"use strict";
// The accounts :email routes re-decoded req.params.email with
// decodeURIComponent after Express had already percent-decoded it once.
// Express 4 decodes every route param exactly one time, so the second decode
// only ever fired on params that legitimately contain "%"-sequences — and
// "%" is a legal email local-part character (normalizeProvisionedEmail
// accepts it). Two consequences, both admin-action integrity bugs:
//
// 1. Wrong-target actions. For the routes whose action tokens are not
// target-bound (add/remove access, agent-access, grant-perms,
// change-password) the handler resolved findUserByEmail(decoded).
// When a second account existed whose email equals the decoded form,
// managing "bob%61@x.com" actually mutated "boba@x.com" — password
// reset, session eviction, ACL rewrite — and the [SECURITY] audit
// lines recorded the decoded email, shifting attribution too.
//
// 2. Dead destructive ops. Suspension/deletion verify a one-time token
// minted (in GET /api/settings/accounts) for the real target email.
// Verified against the decoded email the binding never matched, so any
// account with a "%xx"-pattern email could never be suspended or
// deleted through the panel (403 "invalid or missing action token").
// Fail-closed, but the accounts were permanently unmanageable.
//
// The routes now use req.params.email exactly as the framework decoded it
// (same remediation as the server :name routes, audit P4.1), which is also
// what the shipped settings UI already sends: it decodes the data-email
// attribute back to the raw address and re-encodes it with
// encodeURIComponent at fetch time, so the wire form is the canonical
// single encoding.
//
// index.js boots servers on require, so the source pattern is locked with
// assertions (same technique as audit-p32-p41-p42.test.js) and the Express
// param-decoding contract the fix relies on is exercised behaviorally
// against the installed express with the eight shipped route shapes.
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const ROOT = path.join(__dirname, "..");
const INDEX_JS = path.join(ROOT, "index.js");
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
const ACCOUNT_ROUTES = [
'app.post("/api/settings/accounts/:email/add"',
'app.post("/api/settings/accounts/:email/remove"',
'app.post("/api/settings/accounts/:email/agent-access"',
'app.get("/api/settings/accounts/:email/perms"',
'app.post("/api/settings/accounts/:email/grant-perms"',
'app.post("/api/settings/accounts/:email/suspension"',
'app.delete("/api/settings/accounts/:email"',
'app.post("/api/settings/accounts/:email/change-password"',
];
test("accounts :email routes contain no second decode of the param", () => {
assert.ok(
!indexSource.includes("decodeURIComponent(req.params.email"),
"req.params.email is already decoded by Express; a second decode mangles %-sequence emails and can resolve a different account"
);
});
test("every accounts :email route reads the param directly as decoded", () => {
for (const marker of ACCOUNT_ROUTES) {
const start = indexSource.indexOf(marker);
assert.ok(start >= 0, `route must still exist: ${marker}`);
const end = indexSource.indexOf("\napp.", start + 1);
const handler = indexSource.slice(start, end > 0 ? end : undefined);
assert.ok(
handler.includes('String(req.params.email || "").trim()'),
`${marker} must read req.params.email directly (single decode)`
);
}
});
test("the target-bound token checks still bind the decoded email", () => {
// Suspension and deletion verify one-time tokens minted for the real
// target email; the binding must be computed from the same value the
// client encoded, or %-bearing accounts can never be suspended/deleted.
const suspension = indexSource.indexOf('app.post("/api/settings/accounts/:email/suspension"');
const deleteAt = indexSource.indexOf('app.delete("/api/settings/accounts/:email"');
const changePassword = indexSource.indexOf('app.post("/api/settings/accounts/:email/change-password"');
const endOfRoutes = indexSource.indexOf("\napp.get(\"/api/servers/:name/files/list\"", changePassword);
const slice = indexSource.slice(suspension, endOfRoutes);
assert.ok(slice.includes('requireActionTokenOr403(req, res, "POST /api/settings/accounts/:email/suspension", { targetEmail: targetEmailLower, targetId: req.body?.expectedTargetId })'));
assert.ok(slice.includes('requireActionTokenOr403(req, res, "DELETE /api/settings/accounts/:email", { targetEmail: targetEmailLower, targetId: req.body?.expectedTargetId })'));
assert.ok(
slice.slice(changePassword - suspension).indexOf("requireActionTokenOr403") >= 0,
"change-password keeps its action-token gate"
);
});
test("the accounts list still mints delete/suspension tokens for the real stored email", () => {
const start = indexSource.indexOf('app.get("/api/settings/accounts"');
const end = indexSource.indexOf('app.post("/api/settings/accounts/:email/add"', start);
const handler = indexSource.slice(start, end);
assert.ok(handler.includes('{ targetEmail: emailLower, targetId: Number(u.id) }'), "target binding must come from stored email and immutable row id");
assert.ok(handler.includes('targetEmail: emailLower'), "both deleteToken and suspensionToken must stay target-bound");
});
test("non-param decodes stay in place (no overzealous sweep)", () => {
// Raw req.path / URL.pathname segments and URL credentials are still
// percent-encoded; their decodes are correct and must not be removed.
assert.ok(indexSource.includes("decodeServerPathSegment"), "raw req.path decodes must remain");
assert.ok(indexSource.includes("rawName = decodeURIComponent(rawName)"), "import filename decodes must remain");
assert.ok(indexSource.includes("decodeURIComponent(url.password)"), "URL credential decodes must remain");
});
test("behavioral: Express decodes :email params exactly once (the contract the fix relies on)", async () => {
const express = require("express");
const app = express();
for (const marker of ACCOUNT_ROUTES) {
const route = marker.split("(")[1].replace(/"/g, "");
app.all(route, (req, res) => res.json({ email: req.params.email }));
}
const server = app.listen(0, "127.0.0.1");
await new Promise((resolve) => server.once("listening", resolve));
try {
const port = server.address().port;
const base = `http://127.0.0.1:${port}`;
// The canonical wire form of "bob%61@x.com" (encodeURIComponent) must
// round-trip to the stored address on every route shape.
for (const marker of ACCOUNT_ROUTES) {
const route = marker.split("(")[1].replace(/"/g, "");
const urlPath = route.replace(":email", encodeURIComponent("bob%61@x.com"));
const method = route === "/api/settings/accounts/:email" ? "DELETE" : "POST";
const res = await fetch(base + urlPath, { method });
assert.equal(res.status, 200, route);
const body = await res.json();
assert.equal(body.email, "bob%61@x.com", `param must arrive single-decoded on ${route}`);
}
// A plain email is untouched (guards against regressions that would
// break every non-% address).
const plain = await (await fetch(`${base}/api/settings/accounts/${encodeURIComponent("admin@example.com")}/add`, { method: "POST" })).json();
assert.equal(plain.email, "admin@example.com");
// A malformed %-sequence never reaches a handler: Express itself fails
// the request with 400, so the direct read cannot see garbage.
const malformed = await fetch(`${base}/api/settings/accounts/bob%zz@x.com/add`, { method: "POST" });
assert.equal(malformed.status, 400);
} finally {
server.close();
}
});