"use strict"; // Tests for audit finding M1: the admin create-user flow must never provision // or return a user's TOTP seed or plaintext recovery codes. // // POST /api/admin/user/create used to generate a TOTP secret + QR data URL + // plaintext recovery codes and hand all three back in the JSON response, // where settings.js rendered them and offered them as a downloadable file. // That violates the exact policy the admin 2FA reset was redesigned around // (handleAdmin2faReset): the admin must NEVER learn the target user's TOTP // seed, or they could generate valid codes for that account and // non-repudiation is broken. The two flows now share one model: accounts are // created without a secret, and the user enrolls their own authenticator from // account security settings after their first login — the enrollment // endpoints (/api/account/2fa/generate, /api/account/2fa/generate-recovery) // bind the pending secret to the user's own session. // // index.js boots servers on require, so route-level behavior is locked with // source assertions (same technique as the other audit-*.test.js files). 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 SETTINGS_JS = path.join(ROOT, "public", "js", "settings.js"); const SETTINGS_EJS = path.join(ROOT, "views", "settings.ejs"); const RESET_MODULE_JS = path.join(ROOT, "services", "admin-2fa-reset.js"); const indexSource = fs.readFileSync(INDEX_JS, "utf8"); const resetModuleSource = fs.readFileSync(RESET_MODULE_JS, "utf8"); const settingsJsSource = fs.readFileSync(SETTINGS_JS, "utf8"); const settingsEjsSource = fs.readFileSync(SETTINGS_EJS, "utf8"); function countOccurrences(haystack, needle) { return haystack.split(needle).length - 1; } 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); } const CREATE_ROUTE = sliceBetween( indexSource, 'app.post("/api/admin/user/create"', 'app.post("/api/admin/branding/update"' ); // --------------------------------------------------------------------------- // Server: the create route neither generates nor returns 2FA material // --------------------------------------------------------------------------- test("create route performs no TOTP/recovery material generation", () => { for (const forbidden of [ "speakeasy.generateSecret", "speakeasy.otpauthURL", 'require("qrcode")', "generateHashedRecoveryCodes" ]) { assert.ok(!CREATE_ROUTE.includes(forbidden), `create route must not use ${forbidden}`); } }); test("create response carries no seed, QR, or recovery codes", () => { assert.ok(!CREATE_ROUTE.includes("secret:"), "response must not include a TOTP seed"); assert.ok(!CREATE_ROUTE.includes("qrCodeUrl"), "response must not include a QR data URL"); assert.ok(!CREATE_ROUTE.includes("recoveryCodes"), "response must not include plaintext recovery codes"); // Old clients key their render on this flag: false sends them down the // "created without 2FA" branch, so stale frontends stay coherent. assert.ok(CREATE_ROUTE.includes("has2FA: false"), "response must report has2FA: false"); assert.ok(CREATE_ROUTE.includes("message:"), "response must carry user-enrollment guidance"); }); test("created accounts start without a secret or recovery codes", () => { const commitSource = fs.readFileSync(path.join(ROOT, "services", "account-credentials.js"), "utf8"); assert.ok(CREATE_ROUTE.includes("createProvisionedAccount(db, currentAdmin"), "creation delegates to the actor-locked service"); const insertLine = commitSource.match(/INSERT INTO users[^\n]+/); assert.ok(insertLine, "the create INSERT must exist"); assert.ok(insertLine[0].includes("NULL"), "secret and recovery_codes must be NULL constants"); // No interpolation placeholders left for the material columns. assert.ok(!insertLine[0].includes("?, ?, ?, ?, ?, ?"), "the 6-placeholder INSERT must be gone"); }); test("the dead provisioning helper is fully removed from index.js", () => { assert.equal( countOccurrences(indexSource, "generateHashedRecoveryCodes"), 0, "generateHashedRecoveryCodes must not survive anywhere" ); }); test("stale clients may still send enableTwoFactor; it is parsed and ignored", () => { assert.ok( CREATE_ROUTE.includes("parseBoolean(req.body?.enableTwoFactor"), "the request field must be parsed (accept-and-ignore keeps legacy clients working)" ); assert.ok( CREATE_ROUTE.includes("Requested 2FA provisioning ignored"), "ignoring a provisioning request must be visible in the audit log" ); }); // --------------------------------------------------------------------------- // Policy parity with the admin 2FA reset (the reference implementation) // --------------------------------------------------------------------------- test("the reset-2fa policy statement is intact and the reset flow still generates no secret", () => { // The shared reset handler (and its policy comment) moved into // services/admin-2fa-reset.js with the pre-flight guard consolidation; the // pin follows it there. The slice still spans the policy statement through // the whole handler implementation, so the non-repudiation model and the // no-secret-minting rule are checked over the same code as before. const resetHandler = sliceBetween( resetModuleSource, "Security model: the admin must NEVER learn the target user's TOTP seed", "module.exports" ); assert.ok( resetHandler.includes("the admin must NEVER learn the target user's TOTP seed"), "the documented non-repudiation model must survive refactors" ); assert.ok( !resetHandler.includes("speakeasy.generateSecret"), "the admin reset must never mint a secret on the user's behalf" ); }); test("TOTP seeds are only ever generated inside user-self-service account routes", () => { // Exactly two generation sites may exist: the user's own enrollment and the // recovery-verified re-enrollment. Both bind the pending secret to the // requesting user's session — never to an admin response. assert.equal( countOccurrences(indexSource, "speakeasy.generateSecret"), 2, "exactly the two self-service enrollment endpoints may generate secrets" ); for (const route of ["/api/account/2fa/generate", "/api/account/2fa/generate-recovery"]) { const handler = sliceBetween( indexSource, `app.post("${route}"`, "req.session.pending2faSecret =" ); assert.ok(handler.includes("req.session.user"), `${route} must be bound to the requesting user's session`); } }); // --------------------------------------------------------------------------- // Frontend: no seed/QR/recovery rendering in the create + credentials flows // --------------------------------------------------------------------------- test("create modal has no 2FA provisioning toggle left", () => { assert.ok( !settingsEjsSource.includes('id="createUserEnableTwoFactor"'), "the enable-2FA checkbox must be gone from views/settings.ejs" ); assert.ok( !settingsJsSource.includes("createUserEnableTwoFactor"), "settings.js must not reference the removed checkbox" ); assert.ok( settingsEjsSource.includes("2FA is enrolled by the user, not provisioned here"), "the modal must explain the self-enrollment model instead" ); }); test("submitCreateUser no longer requests 2FA provisioning", () => { const submitFn = sliceBetween( settingsJsSource, "async function submitCreateUser()", "function openCredentialsModal" ); assert.ok(!submitFn.includes("enableTwoFactor"), "the create request body must not carry enableTwoFactor"); }); test("credentials modal markup has no QR/secret/recovery blocks", () => { for (const goneId of [ "credentialsQRCodeBlock", "credentialsSecretBlock", "credentialsRecoveryBlock" ]) { assert.ok(!settingsEjsSource.includes(`id="${goneId}"`), `${goneId} must be removed from the modal`); } });