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

+791
View File
@@ -0,0 +1,791 @@
"use strict";
// adpanel:wildcard-revoke-conflict — a per-server "Revoke" must never claim
// success while wildcard access still grants access.
//
// The audited defect: POST /api/settings/accounts/:email/remove with a
// specific server against an account holding the literal user_access "all"
// wildcard row usually deleted NO row (the DELETE is keyed on
// (user_id, server_name), and the grant lives in the "all" row) — yet
// removeAccessForEmail still answered true and the route reached
// { ok: true }, retracted nothing wildcard-scoped and logged an
// access_change audit entry, while userHasAccessToServer kept granting the
// target EVERY current and future server via the wildcard row.
//
// The fix (route-level, the write primitive stays untouched): AFTER step-up
// (an unverified caller cannot probe whether an account holds wildcard access
// — the 403 challenge path reveals nothing) and BEFORE removeAccessForEmail
// (the pinned step-up < removeAccessForEmail < cancelSchedulesCreatedBy <
// cancelQueuedAiAgentJobsForUser orderings stay untouched), the route reads
// the target's access list and refuses a per-server revoke while the wildcard
// row exists: 409 { error, wildcardConflict: true }, no deletion, no retract
// passes, no ok:true. The explicit "all" revoke proceeds exactly as today
// (deletes the literal row only; specific rows deliberately remain; the
// wildcard retract passes keep their isWildcard scoping); the wildcard row is
// never expanded into a snapshot of individual grants.
//
// Frontend (public/js/settings.js revokeAccessWithVerification): the existing
// non-ok path already surfaces the backend refusal through the established
// modalFeedback pattern (security-modal feedback when the modal is open, else
// alert) and returns before the success path — pinned here so the 409 can
// never be eaten as a success or as a credential challenge, and the policy
// stays single-sourced on the backend (the client does not re-implement the
// wildcard check).
//
// index.js boots servers on require, so behavior is proven with the house
// vm-extraction technique (tests/credential-change-atomic-guard.test.js): the
// REAL route statement plus the REAL access helpers (getUserIdByEmail,
// getAccessListForEmail, removeAccessForEmail) run against a stateful fake db
// modeling the users/user_access rows, with fake step-up/token/admin deps.
// settings.js is one giant IIFE that cannot be required, so its revoke flow
// is pinned by extracting the REAL function and by source assertions on the
// shipped slice (the convention of tests/audit-l3-l5-access-stepup.test.js).
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 ROOT = path.join(__dirname, "..");
const INDEX_JS = path.join(ROOT, "index.js");
const SETTINGS_JS = path.join(ROOT, "public", "js", "settings.js");
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
const settingsJsSource = fs.readFileSync(SETTINGS_JS, "utf8");
function countOccurrences(haystack, needle) {
return haystack.split(needle).length - 1;
}
// Paren-balanced extraction of a full `app.post(...);` statement (skips
// strings and comments so adpanel: comments cannot desync the tracker).
// Verbatim from tests/credential-change-atomic-guard.test.js.
function extractRouteStatement(source, marker) {
const start = source.indexOf(marker);
assert.ok(start >= 0, `route marker not found: ${marker}`);
let i = start;
let depth = 0;
let started = false;
let inString = null;
while (i < source.length) {
const ch = source[i];
if (inString) {
if (ch === "\\") { i += 2; continue; }
if (ch === inString) inString = null;
i += 1;
continue;
}
if (ch === "/" && source[i + 1] === "/") {
const j = source.indexOf("\n", i);
i = j < 0 ? source.length : j;
continue;
}
if (ch === "/" && source[i + 1] === "*") {
const j = source.indexOf("*/", i + 2);
i = j < 0 ? source.length : j + 2;
continue;
}
if (ch === '"' || ch === "'" || ch === "`") { inString = ch; i += 1; continue; }
if (ch === "(") { depth += 1; started = true; }
else if (ch === ")") { depth -= 1; }
if (started && depth === 0) {
let end = i + 1;
while (end < source.length && source[end] === ";") end += 1;
return source.slice(start, end);
}
i += 1;
}
assert.fail(`unbalanced route statement: ${marker}`);
}
// Extract a full top-level function declaration by brace matching (skipping
// line/block comments and string literals), so behavior pins evaluate the
// SHIPPED source rather than a re-typed copy of it. The `async` modifier is
// part of the match when present (detector-cluster-shared convention).
function extractFunction(source, name) {
let start = source.indexOf(`async function ${name}(`);
if (start < 0) {
start = source.indexOf(`function ${name}(`);
assert.ok(start >= 0, `function not found: ${name}`);
}
let i = source.indexOf("{", start);
let depth = 0;
let inLine = false;
let inBlock = false;
let quote = null;
for (; i < source.length; i++) {
const c = source[i];
const n = source[i + 1];
if (inLine) {
if (c === "\n") inLine = false;
continue;
}
if (inBlock) {
if (c === "*" && n === "/") { inBlock = false; i++; }
continue;
}
if (quote) {
if (c === "\\") { i++; continue; }
if (c === quote) quote = null;
continue;
}
if (c === "/" && n === "/") { inLine = true; i++; continue; }
if (c === "/" && n === "*") { inBlock = true; i++; continue; }
if (c === "'" || c === '"' || c === "`") { quote = c; continue; }
if (c === "{") depth++;
else if (c === "}") {
depth--;
if (depth === 0) return source.slice(start, i + 1);
}
}
throw new Error(`unbalanced braces while extracting ${name}`);
}
function sliceBetween(source, startMarker, endMarker) {
const start = source.indexOf(startMarker);
assert.ok(start >= 0, `start marker not found: ${startMarker}`);
const end = source.indexOf(endMarker, start + startMarker.length);
assert.ok(end > start, `end marker not found after start: ${endMarker}`);
return source.slice(start, end);
}
// The exact refusal contract (single source of truth for the wording).
const WILDCARD_CONFLICT_MESSAGE =
"This account holds wildcard access to all servers. Revoke the wildcard access first, then grant individual servers.";
const ROUTE_REMOVE = 'app.post("/api/settings/accounts/:email/remove"';
const removeRouteStatement = extractRouteStatement(indexSource, ROUTE_REMOVE);
// The REAL access primitives the route composes, evaluated in the same vm
// context as the route so behavior tests exercise the shipped code, not a
// re-typed copy.
const accessHelperSource = [
extractFunction(indexSource, "getUserIdByEmail"),
extractFunction(indexSource, "getAccessListForEmail"),
extractFunction(indexSource, "removeAccessForEmail"),
].join("\n\n");
// ---------------------------------------------------------------------------
// Behavior — the REAL /remove route over a stateful users/user_access fake db
// ---------------------------------------------------------------------------
const TARGET_USER = { id: 7, email: "target@example.test", admin: 0, suspended: 0 };
const ACTOR_USER = { id: 1, email: "admin@example.test", admin: 1, suspended: 0, session_epoch: 11 };
const USERS = [TARGET_USER, ACTOR_USER];
// Stateful fake db: models the users id lookup, the access-list JOIN select
// and the (user_id, server_name) DELETE with real row state. Any other SQL is
// a test bug (so a snapshot-conversion INSERT would fail loudly).
function makeAccessDb({ users, accessRows }) {
const state = { accessRows: accessRows.map((r) => ({ ...r })) };
const queries = [];
const db = {
state,
queries,
async query(sql, params) {
queries.push({ sql, params });
if (sql === "SELECT id FROM users WHERE LOWER(email) = LOWER(?) LIMIT 1") {
const email = String(params[0] || "").toLowerCase();
const u = users.find((x) => x.email.toLowerCase() === email);
return u ? [{ id: u.id }] : [];
}
if (sql === "SELECT ua.server_name FROM user_access ua JOIN users u ON u.id = ua.user_id WHERE LOWER(u.email) = LOWER(?)") {
const email = String(params[0] || "").toLowerCase();
const u = users.find((x) => x.email.toLowerCase() === email);
if (!u) return [];
return state.accessRows.filter((r) => r.user_id === u.id).map((r) => ({ server_name: r.server_name }));
}
if (sql === "DELETE FROM user_access WHERE user_id = ? AND server_name = ?") {
const [userId, serverName] = params;
const before = state.accessRows.length;
state.accessRows = state.accessRows.filter((r) => !(r.user_id === userId && r.server_name === serverName));
return { affectedRows: before - state.accessRows.length };
}
throw new Error(`unexpected db.query in test: ${sql}`);
},
};
db.pool = { getConnection: async () => ({
beginTransaction: async () => {}, commit: async () => {}, rollback: async () => {}, release() {},
execute: async (sql, params) => {
if (sql.startsWith("SELECT id, admin")) return [users.filter((user) => user.admin).map((user) => ({ ...user, suspended: 0 }))];
if (sql.startsWith("SELECT id, email")) return [users.filter((user) => user.id === params[0])];
if (sql === "SELECT server_name FROM user_access WHERE user_id = ?") return [state.accessRows.filter((row) => row.user_id === params[0])];
return [await db.query(sql, params)];
}
}) };
return db;
}
function makeRes() {
const res = { statusCode: 0, body: null, headers: {}, headersSent: false };
res.status = (code) => { res.statusCode = code; res.headersSent = true; return res; };
res.json = (body) => { res.body = body; return res; };
res.set = (name, value) => { res.headers[name] = value; return res; };
return res;
}
function makeHarness({
users = USERS,
accessRows = [],
stepUpOk = true,
jobsStillAuthorized = false,
serversIndex = [{ name: "alpha" }, { name: "beta" }],
} = {}) {
const db = makeAccessDb({ users, accessRows });
const calls = [];
const logs = { security: [], warn: [] };
const sandbox = {
...require("../services/account-actions"),
app: { post: () => { } },
sessionRevoke2faRateLimiter: {},
isAdmin: async () => true,
requireActionTokenOr403: async () => true,
findUserByEmail: async (email) => {
const needle = String(email || "").toLowerCase();
return users.find((x) => x.email.toLowerCase() === needle) || null;
},
requireDestructiveActionStepUp: async (req, res, currentUser, subject, options) => {
calls.push(["stepUp", subject, options && options.scopeKey, options && options.credentialFlow]);
if (!stepUpOk) {
// The real gate writes its challenge onto the response and answers not-ok.
res.status(403).json({ error: "Current password is required", code: "password-required" });
return { ok: false };
}
return { ok: true, graceExpiresAt: 1710000000000 };
},
db,
syncSocketAccessForEmail: async (email) => { calls.push(["socketSync", email]); },
findServer: async () => null,
getCanonicalServerName: () => null,
cancelSchedulesCreatedBy: async (user, options) => { calls.push(["cancelSchedules", user, options]); },
loadServersIndex: async () => serversIndex.map((e) => ({ ...e })),
schedulerActionStillAuthorizedAfterPermChange: async (email, actionType, serverName) => {
calls.push(["pred", email, actionType, serverName]);
return !!jobsStillAuthorized;
},
cancelQueuedAiAgentJobsForUser: async (userId, options) => { calls.push(["cancelJobs", userId, options]); },
PLANNER_AGENT_JOB_SOURCES: new Set(["planner_next_to_agent", "scheduler_planner_next"]),
recordActivity: (server, type, details, actor, ip) => {
calls.push(["activity", server, type, details, actor]);
},
stripLogControlChars: (s) => String(s == null ? "" : s),
getRequestIp: () => "127.0.0.1",
console: {
log: (...args) => {
const line = args.join(" ");
if (line.includes("[SECURITY]")) logs.security.push(line);
},
warn: (...args) => logs.warn.push(args.join(" ")),
error: () => { },
},
JSON,
String,
Number,
Array,
Object,
Promise,
Set,
};
async function run({ email = "target@example.test", server } = {}) {
const captured = [];
const ctx = vm.createContext({ ...sandbox, app: { post: (...args) => captured.push(args) } });
vm.runInContext(accessHelperSource, ctx, { filename: "index.js[access-helpers]" });
vm.runInContext(removeRouteStatement, ctx, { filename: "index.js[/remove]" });
assert.equal(captured.length, 1, "exactly one route registration in the extracted statement");
const handler = captured[0][2];
assert.equal(typeof handler, "function");
const req = {
params: { email },
body: { server, expectedTargetId: users.find((user) => user.email.toLowerCase() === email.toLowerCase())?.id },
is: (t) => (t === "application/json" ? "application/json" : false),
session: { user: "admin@example.test" },
headers: {},
};
const res = makeRes();
await handler(req, res, (err) => { throw err; });
return res;
}
return { db, calls, logs, run };
}
test("per-server revoke without a wildcard row: still ok:true, the row is deleted, the retract passes run, sockets sync", async () => {
const h = makeHarness({ accessRows: [{ user_id: 7, server_name: "alpha" }] });
const res = await h.run({ server: "alpha" });
assert.equal(res.statusCode, 0, "200 via res.json");
assert.deepEqual(res.body, { ok: true, graceExpiresAt: 1710000000000 });
assert.deepEqual(h.db.state.accessRows, [], "the specific row is deleted");
assert.deepEqual(h.db.queries.filter((q) => q.sql.startsWith("DELETE FROM user_access")).length, 1);
// The shared socket sync inside the write primitive ran exactly once.
assert.deepEqual(h.calls.filter((c) => c[0] === "socketSync").map((c) => c[1]), ["target@example.test"]);
// Schedule pass: scoped to the removed server with the pinned reason.
const sched = h.calls.find((c) => c[0] === "cancelSchedules");
assert.ok(sched, "the schedule re-validation pass ran");
assert.equal(sched[1].id, 7);
assert.equal(sched[1].email, "target@example.test");
assert.deepEqual(sched[2], { serverName: "alpha", reauthorize: true, reason: "server access removed" });
// Jobs pass: gated by the ONE shared predicate, scoped to the removed
// server + the planner sources with the pinned terminal reason.
const pred = h.calls.find((c) => c[0] === "pred");
assert.ok(pred, "the shared reauthorize predicate ran");
assert.deepEqual(pred.slice(1), ["target@example.test", "planner_next_to_agent", "alpha"]);
const cancel = h.calls.find((c) => c[0] === "cancelJobs");
assert.ok(cancel, "the queued planner-job retract ran");
assert.equal(cancel[1], 7, "keyed on the target row's user_id");
assert.equal(cancel[2].serverName, "alpha");
assert.deepEqual(Array.from(cancel[2].sources).sort(), ["planner_next_to_agent", "scheduler_planner_next"]);
assert.equal(cancel[2].error, "planner_access_revoked");
// The three-way audit trail.
assert.ok(
h.logs.security.some((l) => l.includes("[SECURITY] Server access removed") && l.includes("Server: alpha") && !l.includes("(wildcard)")),
"the [SECURITY] console line is written without the wildcard marker"
);
assert.ok(h.calls.some((c) => c[0] === "activity" && c[1] === "alpha" && c[2] === "access_change"));
assert.ok(h.calls.some((c) => c[0] === "activity" && c[1] === "_system" && c[2] === "access_change"));
});
test("per-server revoke against a wildcard holder: 409 wildcardConflict, zero rows changed, zero retracts, no misleading success", async () => {
const h = makeHarness({
accessRows: [
{ user_id: 7, server_name: "all" },
{ user_id: 7, server_name: "alpha" },
],
});
const res = await h.run({ server: "alpha" });
assert.equal(res.statusCode, 409);
assert.equal(res.body.wildcardConflict, true, "the refusal carries the wildcardConflict marker");
assert.equal(res.body.error, WILDCARD_CONFLICT_MESSAGE, "the message is truthful and actionable");
assert.equal(res.body.ok, undefined, "no success fields on the refusal");
// Zero rows changed: the wildcard row is INTACT (future-server semantics
// preserved) and the specific row is untouched too.
assert.deepEqual(h.db.state.accessRows, [
{ user_id: 7, server_name: "all" },
{ user_id: 7, server_name: "alpha" },
]);
assert.deepEqual(h.db.queries.filter((q) => q.sql.startsWith("DELETE FROM user_access")).length, 0, "no deletion ran");
assert.deepEqual(
h.db.queries.filter((q) => q.sql.includes("SELECT ua.server_name")).length,
1,
"exactly one access-list read (the guard's own lookup)"
);
assert.deepEqual(h.db.queries.filter((q) => q.sql.includes("INSERT INTO user_access")).length, 0);
// Zero retracts, no audit trail, no socket sync — nothing may run that
// implies the access actually changed.
for (const kind of ["cancelSchedules", "cancelJobs", "pred", "activity", "socketSync"]) {
assert.equal(h.calls.filter((c) => c[0] === kind).length, 0, `${kind} must not run on the refusal`);
}
assert.equal(h.logs.security.length, 0, "no [SECURITY] access-removed line on the refusal");
assert.deepEqual(
h.calls.filter((c) => c[0] === "stepUp").length,
1,
"the step-up itself still ran (the refusal sits after it)"
);
});
test("explicit 'all' revoke: ok:true, the 'all' row gone, specific rows intact (no snapshot conversion), wildcard retract scoping intact", async () => {
const h = makeHarness({
accessRows: [
{ user_id: 7, server_name: "all" },
{ user_id: 7, server_name: "alpha" },
],
});
const res = await h.run({ server: "all" });
assert.equal(res.statusCode, 0, "200 via res.json");
assert.deepEqual(res.body, { ok: true, graceExpiresAt: 1710000000000 });
assert.deepEqual(
h.db.state.accessRows,
[{ user_id: 7, server_name: "alpha" }],
"the literal 'all' row is deleted; the specific rows deliberately remain — the wildcard is NOT expanded into a snapshot of individual grants"
);
assert.deepEqual(
h.db.queries.filter((q) => q.sql.includes("INSERT INTO user_access")).length,
0,
"no INSERT anywhere — the explicit wildcard revoke deletes the row, never expands it"
);
assert.deepEqual(h.calls.filter((c) => c[0] === "socketSync").length, 1, "sockets still sync after the global revoke");
// Wildcard retract scoping: the schedule pass revalidates across ALL the
// target's schedules (reauthorize shape without a serverName scope) and the
// jobs pass sweeps the servers index, retracting per server where the
// shared predicate fails.
const sched = h.calls.find((c) => c[0] === "cancelSchedules");
assert.ok(sched, "the schedule pass ran for the wildcard revoke");
assert.deepEqual(sched[2], { reauthorize: true, reason: "server access removed" }, "wildcard branch: no serverName scope");
assert.deepEqual(
h.calls.filter((c) => c[0] === "pred").map((c) => c[3]),
["alpha", "beta"],
"the jobs pass sweeps the servers index for a wildcard removal"
);
assert.equal(h.calls.filter((c) => c[0] === "cancelJobs").length, 2, "per-server retracts fire where the predicate fails");
// Wildcard audit scoping: no per-server activity record for the wildcard
// token (no server named "all" exists — the reserved-name guard blocks it),
// the system-wide record stays.
assert.ok(!h.calls.some((c) => c[0] === "activity" && c[1] === "all"), "no per-server activity record keyed on the wildcard token");
assert.ok(h.calls.some((c) => c[0] === "activity" && c[1] === "_system"));
assert.ok(
h.logs.security.some((l) => l.includes("Server access removed (wildcard)") && l.includes("Server: all")),
"the [SECURITY] line carries the (wildcard) marker"
);
});
test("step-up still precedes the wildcard check: a 403 challenge path never probes whether a wildcard exists", async () => {
const h = makeHarness({
accessRows: [
{ user_id: 7, server_name: "all" },
{ user_id: 7, server_name: "alpha" },
],
stepUpOk: false,
});
const res = await h.run({ server: "alpha" });
assert.equal(res.statusCode, 403, "the step-up challenge answers before any access-list read");
assert.equal(res.body.code, "password-required");
assert.deepEqual(h.calls.filter((c) => c[0] === "stepUp").length, 1);
assert.deepEqual(
h.db.queries.filter((q) => q.sql.includes("SELECT ua.server_name")).length,
0,
"the access list is NEVER read on the challenge path — an unverified caller cannot probe wildcard state"
);
assert.deepEqual(h.db.queries.filter((q) => q.sql.startsWith("DELETE FROM user_access")).length, 0);
for (const kind of ["cancelSchedules", "cancelJobs", "socketSync", "activity"]) {
assert.equal(h.calls.filter((c) => c[0] === kind).length, 0, `${kind} must not run on the challenge path`);
}
assert.deepEqual(h.db.state.accessRows, [
{ user_id: 7, server_name: "all" },
{ user_id: 7, server_name: "alpha" },
], "nothing mutates on the challenge path");
});
test("the wildcard row is intact after every refusal, and repeated refusals stay stable", async () => {
const h = makeHarness({
accessRows: [
{ user_id: 7, server_name: "all" },
{ user_id: 7, server_name: "alpha" },
{ user_id: 7, server_name: "beta" },
],
});
for (const server of ["alpha", "beta"]) {
const res = await h.run({ server });
assert.equal(res.statusCode, 409);
assert.equal(res.body.wildcardConflict, true);
}
assert.deepEqual(h.db.state.accessRows, [
{ user_id: 7, server_name: "all" },
{ user_id: 7, server_name: "alpha" },
{ user_id: 7, server_name: "beta" },
], "every refusal leaves all rows — including the future-server wildcard — untouched");
});
// ---------------------------------------------------------------------------
// Source pins — the guard's placement and the untouched pinned orderings
// ---------------------------------------------------------------------------
test("source: the wildcard guard sits between step-up and the mutation; the pinned orderings and the /add slice are untouched", () => {
const stmt = removeRouteStatement;
// The refusal contract strings live in the route statement.
assert.ok(stmt.includes("res.status(409).json({"), "the refusal answers 409");
assert.ok(stmt.includes("wildcardConflict: true"), "the refusal body carries the wildcardConflict marker");
assert.ok(stmt.includes(WILDCARD_CONFLICT_MESSAGE), "the truthful, actionable message ships in the route");
// The guard reads the target's access list and refuses only for a per-server
// revoke (the explicit "all" revoke bypasses it, exactly like the route's
// own isWildcard branch).
assert.ok(
stmt.includes('const targetAccessList = await getAccessListForEmail(email);'),
"the guard must load the target's access list through the ONE reader helper"
);
assert.ok(stmt.includes('server !== "all"'), "the guard must not fire on the explicit 'all' revoke");
assert.ok(stmt.includes('.toLowerCase() === "all"'), "the list check mirrors the ONE wildcard reader (userHasAccessToServer lowercases before matching)");
// Placement: step-up < guard < removeAccessForEmail < cancelSchedulesCreatedBy
// < cancelQueuedAiAgentJobsForUser — the step-up-before-mutation pin
// (audit-l3-l5) and the mutation < retract-passes pin
// (agent-job-suspension-gate) stay intact with the guard wedged in between.
const stepUpIdx = stmt.indexOf("requireDestructiveActionStepUp");
const guardIdx = stmt.indexOf("const targetAccessList = await getAccessListForEmail(email);");
const removeIdx = stmt.indexOf("changeAccountAccess(db, currentUser, targetUser, server, false)");
const schedIdx = stmt.indexOf("cancelSchedulesCreatedBy(targetUser");
const jobsIdx = stmt.indexOf("cancelQueuedAiAgentJobsForUser(targetUser.id");
assert.ok(stepUpIdx >= 0 && guardIdx >= 0 && removeIdx >= 0 && schedIdx >= 0 && jobsIdx >= 0, "all five anchors exist in the route statement");
assert.ok(
stepUpIdx < guardIdx && guardIdx < removeIdx && removeIdx < schedIdx && schedIdx < jobsIdx,
"step-up < wildcard guard < removeAccessForEmail < schedule pass < jobs pass"
);
// The route's own wildcard branch keeps its single explicit comparison, and
// the /add slice (delimited by the /remove registration) keeps exactly one
// wildcard comparison — the guard must never leak wildcard text into /add.
assert.equal(
countOccurrences(stmt, 'server === "all"'),
1,
"the route's isWildcard comparison stays unique inside the /remove statement"
);
const addSlice = indexSource.slice(
indexSource.indexOf('app.post("/api/settings/accounts/:email/add"'),
indexSource.indexOf('app.post("/api/settings/accounts/:email/remove"')
);
assert.equal(
countOccurrences(addSlice, 'server === "all"'),
1,
"the /add slice keeps exactly its one wildcard comparison (nothing added there)"
);
// The wildcard row is never expanded into a snapshot of individual grants
// anywhere in the route.
assert.ok(!stmt.includes("INSERT"), "the /remove route must never write access rows — revoke only deletes/refuses");
// The write primitive stays policy-free: removeAccessForEmail remains the
// generic (user_id, server_name) deleter; the wildcard policy has its ONE
// home in the route.
const removeHelper = extractFunction(indexSource, "removeAccessForEmail");
assert.ok(!removeHelper.includes('"all"'), "removeAccessForEmail must stay wildcard-agnostic — the refusal policy lives in the route, not in the write primitive");
});
test("source: the refusal body carries no challenge codes, so the client cannot misroute it through the credential-challenge handler", () => {
const stmt = removeRouteStatement;
const guardIdx = stmt.indexOf("wildcardConflict: true");
assert.ok(guardIdx >= 0, "the guard exists");
// The refusal is keyed by wildcardConflict + a plain error string; the
// client's isAccountActionChallengeCode keys on data.code, so a refusal
// carrying a challenge code would be eaten by the challenge handler instead
// of being surfaced.
for (const code of ["password-required", "invalid-password", "2fa-required", "invalid-2fa", "verification-rate-limit"]) {
const refusalBody = stmt.slice(guardIdx);
assert.ok(
!refusalBody.includes(`"${code}"`),
`the refusal body must not carry the "${code}" challenge code`
);
}
});
// ---------------------------------------------------------------------------
// Frontend — the revoke flow surfaces the backend refusal, never fake success
// ---------------------------------------------------------------------------
// Behavior harness: the REAL revokeAccessWithVerification extracted from the
// settings.js IIFE, run in a vm with fake DOM/session deps. The REAL
// isAccountActionChallengeCode (and its code list) is shipped too, so the
// "409 is not a credential challenge" property is exercised, not assumed.
const REAL_CHALLENGE_CONST = (() => {
const start = settingsJsSource.indexOf("const ACCOUNT_ACTION_CHALLENGE_CODES =");
assert.ok(start >= 0, "ACCOUNT_ACTION_CHALLENGE_CODES not found");
const end = settingsJsSource.indexOf(";", start);
return settingsJsSource.slice(start, end + 1);
})();
const REAL_CHALLENGE_CHECK = extractFunction(settingsJsSource, "isAccountActionChallengeCode");
const REAL_REVOKE_FN = extractFunction(settingsJsSource, "revokeAccessWithVerification");
function makeFrontendHarness({ responseData, overlayShown = true, graceActive = true } = {}) {
const calls = [];
const sessionsState = {
graceExpiresAt: 0,
selectedAccessRevoke: { email: "target@example.test", server: "alpha", button: { disabled: false } },
};
const sourceButton = sessionsState.selectedAccessRevoke.button;
const sandbox = {
window: {},
fetch: async () => responseData,
alert: (m) => calls.push(["alert", m]),
sessionsState,
isGraceActive: () => graceActive,
validateSessionRevokeAccountCredentials: () => true,
sessionRevokeModalOverlay: { classList: { contains: () => overlayShown } },
showSessionRevokeModalFeedback: (m, isErr) => calls.push(["modalFeedback", m, !!isErr]),
sessionRevokeModalConfirm: { disabled: false, innerHTML: "" },
restoreSecurityModalConfirmButton: () => calls.push(["restoreConfirm"]),
collectAccountActionCredentialPayload: (body) => { calls.push(["payload", body && body.server]); return body; },
sessionRevokeTwoFactorInput: null,
sessionRevokeTotpSection: null,
sessionRevokeTotpInput: null,
accountsListEl: { _actionTokens: { removeAccess: "tok-1" } },
loadAccounts: async () => { calls.push(["loadAccounts"]); },
openRevokeAccessVerificationModal: () => { calls.push(["reopenRevokeModal"]); },
handleSessionRevokeAccountChallenge: (data) => { calls.push(["challenge", data && data.code]); return true; },
updateSessionsHeaderMeta: () => calls.push(["headerMeta"]),
closeSessionRevokeModal: () => calls.push(["closeRevokeModal"]),
setSavedPerms: (email, server, perms) => calls.push(["setSavedPerms", email, server, perms]),
showSuccessToast: (m) => calls.push(["toast", m]),
accountModalOverlay: { classList: { contains: () => true } },
openManageAccessModal: (email) => calls.push(["reopenManage", email]),
console: { error: () => { } },
JSON,
String,
Number,
Object,
Promise,
};
let handler = null;
const ctx = vm.createContext(sandbox);
vm.runInContext(fs.readFileSync(path.join(ROOT, "public", "js", "settings-account-targets.js"), "utf8"), ctx);
sandbox.window.ADPanelAccountTargets.update([{ id: 7, email: "target@example.test" }]);
sessionsState.selectedAccessRevoke.accountTarget = sandbox.window.ADPanelAccountTargets.select("target@example.test");
vm.runInContext(`${REAL_CHALLENGE_CONST}\n${REAL_CHALLENGE_CHECK}`, ctx, { filename: "settings.js[challenge-check]" });
vm.runInContext(REAL_REVOKE_FN, ctx, { filename: "settings.js[revokeAccessWithVerification]" });
handler = vm.runInContext("revokeAccessWithVerification", ctx, { filename: "settings.js[revoke-fn-ref]" });
assert.equal(typeof handler, "function");
return {
calls,
sessionsState,
sourceButton,
run: (email = "target@example.test", server = "alpha") => handler(email, server, ""),
};
}
test("frontend: a wildcardConflict 409 surfaces the backend message through the established feedback path and never fakes success", async () => {
const h = makeFrontendHarness({
responseData: {
ok: false,
status: 409,
json: async () => ({ error: WILDCARD_CONFLICT_MESSAGE, wildcardConflict: true }),
},
});
await h.run();
// The refusal is surfaced through the established pattern with the backend's
// own message (single source of truth), as an ERROR.
assert.deepEqual(
h.calls.find((c) => c[0] === "modalFeedback" || c[0] === "alert"),
["modalFeedback", WILDCARD_CONFLICT_MESSAGE, true],
"the security modal is open, so the message must ride showSessionRevokeModalFeedback(message, true)"
);
// NOT success: no toast, no saved-perms clear, no success close, no manage
// modal reopen, no header-meta grace update.
for (const kind of ["toast", "setSavedPerms", "closeRevokeModal", "reopenManage", "headerMeta"]) {
assert.equal(h.calls.filter((c) => c[0] === kind).length, 0, `${kind} must not run on the refusal`);
}
assert.equal(h.sessionsState.graceExpiresAt, 0, "the local grace must not be set from a refusal");
// The 409 is NOT misread as a credential challenge and does not trigger a
// token refresh.
assert.equal(h.calls.filter((c) => c[0] === "challenge").length, 0, "the wildcard refusal must not be consumed as a password/TOTP challenge");
assert.equal(h.calls.filter((c) => c[0] === "loadAccounts").length, 0, "the wildcard refusal must not trigger the token refresh path");
// The request carried the target server via the shared credential payload
// helper, and the finally block restored the controls.
assert.deepEqual(h.calls.find((c) => c[0] === "payload"), ["payload", "alpha"]);
assert.equal(h.sourceButton.disabled, false, "the row button is re-enabled by the finally block");
assert.ok(h.calls.some((c) => c[0] === "restoreConfirm"), "the confirm button is restored by the finally block");
});
test("frontend: with the security modal closed the refusal falls back to alert(message) — same established pattern", async () => {
const h = makeFrontendHarness({
overlayShown: false,
responseData: {
ok: false,
status: 409,
json: async () => ({ error: WILDCARD_CONFLICT_MESSAGE, wildcardConflict: true }),
},
});
await h.run();
assert.deepEqual(
h.calls.find((c) => c[0] === "modalFeedback" || c[0] === "alert"),
["alert", WILDCARD_CONFLICT_MESSAGE],
"modal closed -> alert fallback"
);
for (const kind of ["toast", "setSavedPerms", "closeRevokeModal"]) {
assert.equal(h.calls.filter((c) => c[0] === kind).length, 0, `${kind} must not run on the refusal`);
}
});
test("frontend: the ok path keeps the existing success behavior byte-for-byte (toast, perms clear, success close, manage reopen)", async () => {
const h = makeFrontendHarness({
responseData: {
ok: true,
status: 200,
json: async () => ({ ok: true, graceExpiresAt: 555 }),
},
});
await h.run();
assert.deepEqual(h.calls.find((c) => c[0] === "toast"), ["toast", "Access revoked for target@example.test on alpha"], "the success toast is unchanged");
assert.deepEqual(h.calls.find((c) => c[0] === "setSavedPerms"), ["setSavedPerms", "target@example.test", "alpha", {}], "the saved-perms clear is unchanged");
assert.ok(h.calls.some((c) => c[0] === "closeRevokeModal"), "the success close is unchanged");
assert.deepEqual(h.calls.find((c) => c[0] === "reopenManage"), ["reopenManage", "target@example.test"], "the manage-access modal reopen is unchanged");
assert.equal(h.sessionsState.graceExpiresAt, 555, "the grace timestamp is stored from the success payload");
assert.deepEqual(
h.calls.filter((c) => c[0] === "modalFeedback" || c[0] === "alert").length,
0,
"no error feedback on the success path"
);
});
test("source: settings.js keeps exactly one /remove fetch whose non-ok path returns before the success path and does not duplicate the wildcard policy", () => {
assert.equal(
countOccurrences(settingsJsSource, "/remove`"),
1,
"exactly one /remove fetch may exist, inside revokeAccessWithVerification"
);
const fn = sliceBetween(
settingsJsSource,
"async function revokeAccessWithVerification(",
"function openAgentAccessVerificationModal("
);
// The established feedback closure exists (security modal -> error feedback,
// else alert).
assert.ok(fn.includes("const modalFeedback = (message) => {"), "the modalFeedback closure stays");
assert.ok(
fn.includes("showSessionRevokeModalFeedback(message, true)") && fn.includes("else alert(message);"),
"the established error-surfacing pattern stays: modal feedback when open, else alert"
);
// Ordering: challenge handling, then the token retry, then the generic
// error feedback — all INSIDE the !res.ok block, all returning before the
// success path.
const nonOkIdx = fn.indexOf("if (!res.ok) {");
const challengeIdx = fn.indexOf("isAccountActionChallengeCode(data, true)");
const tokenIdx = fn.indexOf("data.error === 'invalid or missing action token'");
const feedbackIdx = fn.indexOf("modalFeedback(data.error || 'Failed to revoke access.')");
const successIdx = fn.indexOf("setSavedPerms(targetEmail, targetServer, {})");
const toastIdx = fn.indexOf("showSuccessToast(");
assert.ok(nonOkIdx >= 0 && challengeIdx > nonOkIdx && tokenIdx > challengeIdx && feedbackIdx > tokenIdx, "the non-ok ladder keeps its order");
assert.ok(successIdx > feedbackIdx && toastIdx > successIdx, "the success path must only be reachable after the non-ok branches returned");
const nonOkBlock = fn.slice(nonOkIdx, successIdx);
assert.ok(
(nonOkBlock.match(/return;/g) || []).length >= 3,
"every non-ok branch (challenge / expired token / generic error) stops with an early return — a refusal can never fall through into the success path"
);
// Single source of truth: the client surfaces the backend's message and
// never re-implements the wildcard policy client-side.
assert.ok(
!fn.includes("wildcardConflict"),
"the revoke flow must not branch on the wildcard policy marker — it renders data.error from the backend"
);
// The step-up credential payload tail stays byte-identical (mirrors the
// audit-l3-l5 pin) and the token retry stays scoped to the action-token
// error string only.
assert.ok(fn.includes("collectAccountActionCredentialPayload("), "the revoke request must collect its step-up credentials with the shared payload helper");
assert.ok(
fn.includes("}, sessionRevokeTwoFactorInput, sessionRevokeTotpSection, sessionRevokeTotpInput))"),
"the payload helper must read the shared modal's credential pair"
);
assert.ok(
fn.includes("data.error === 'invalid or missing action token'") &&
fn.indexOf("data.error === 'invalid or missing action token'") < feedbackIdx,
"the retry-once stays bound to the action-token error string"
);
});