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 @@
|
||||
// Standalone verification harness for Finding 6:
|
||||
// Step-up auth and rate limiting on template mutating routes and store sync.
|
||||
// Run: node scripts/verify-template-stepup.js
|
||||
|
||||
const assert = require("assert");
|
||||
const crypto = require("crypto");
|
||||
const express = require("express");
|
||||
const session = require("express-session");
|
||||
const http = require("http");
|
||||
const { rateLimit } = require("express-rate-limit");
|
||||
|
||||
// 1. Replicate the exact limiter from index.js:2950-3006
|
||||
function hasDestructiveActionCredentialPayload(req) {
|
||||
const body = req?.body || {};
|
||||
const password = typeof body.currentPassword === "string" ? body.currentPassword : "";
|
||||
const twoFactorCode = typeof body.twoFactorCode === "string" ? body.twoFactorCode : "";
|
||||
return !!password || !!twoFactorCode;
|
||||
}
|
||||
|
||||
function sessionRevoke2faRateLimiterFactory() {
|
||||
const sessionLimiter = rateLimit({
|
||||
windowMs: 10 * 60 * 1000,
|
||||
max: 8,
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
keyGenerator: (req) => {
|
||||
const email = String(req.session?.user || "anon").trim().toLowerCase();
|
||||
const sid = String(req.sessionID || "no-session");
|
||||
return `session-revoke-verify:${email}:${sid}`;
|
||||
},
|
||||
skip: (req) => !hasDestructiveActionCredentialPayload(req),
|
||||
handler: (req, res) => {
|
||||
res.status(429).json({ error: "Too many verification attempts. Please wait 10 minutes and try again.", code: "verification-rate-limit" });
|
||||
}
|
||||
});
|
||||
|
||||
const emailLimiter = rateLimit({
|
||||
windowMs: 10 * 60 * 1000,
|
||||
max: 24,
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
keyGenerator: (req) => {
|
||||
const email = String(req.session?.user || "anon").trim().toLowerCase();
|
||||
return `session-revoke-verify-email:${email}`;
|
||||
},
|
||||
skip: (req) => !hasDestructiveActionCredentialPayload(req),
|
||||
handler: (req, res) => {
|
||||
res.status(429).json({ error: "Too many verification attempts. Please wait 10 minutes and try again.", code: "verification-rate-limit" });
|
||||
}
|
||||
});
|
||||
|
||||
return (req, res, next) => {
|
||||
emailLimiter(req, res, (err) => {
|
||||
if (err) return next(err);
|
||||
sessionLimiter(req, res, next);
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
// 2. Mock step-up with scoped grace grants mirroring index.js:4943-4993
|
||||
const mockGrants = new Map(); // grantId -> { email, scopeKey, useCount, expiresAt }
|
||||
let nextGrantId = 1;
|
||||
|
||||
function mockRequireDestructiveActionStepUp(req, res, subject, { scopeKey = "" } = {}) {
|
||||
const grantId = req.session?.grantId;
|
||||
const grant = grantId ? mockGrants.get(grantId) : null;
|
||||
|
||||
// Grace check
|
||||
if (grant && grant.expiresAt > Date.now() && grant.useCount < 5) {
|
||||
if (!grant.scopeKey || grant.scopeKey === scopeKey) {
|
||||
grant.useCount += 1;
|
||||
return { ok: true, usedGrace: true };
|
||||
}
|
||||
}
|
||||
|
||||
// Check credentials
|
||||
if (!hasDestructiveActionCredentialPayload(req)) {
|
||||
res.status(403).json({ error: "Current password is required", code: "password-required" });
|
||||
return { ok: false };
|
||||
}
|
||||
|
||||
const password = req.body?.currentPassword;
|
||||
if (password !== "correct-horse-battery") {
|
||||
res.status(403).json({ error: "Incorrect current password", code: "invalid-password" });
|
||||
return { ok: false };
|
||||
}
|
||||
|
||||
// Mint new grant pre-bound to scopeKey
|
||||
const newGrantId = `grant-${nextGrantId++}`;
|
||||
mockGrants.set(newGrantId, {
|
||||
email: req.session.user,
|
||||
scopeKey,
|
||||
useCount: 1,
|
||||
expiresAt: Date.now() + 5 * 60 * 1000,
|
||||
});
|
||||
req.session.grantId = newGrantId;
|
||||
return { ok: true, usedGrace: false };
|
||||
}
|
||||
|
||||
function buildApp() {
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use(session({ secret: crypto.randomBytes(32).toString("hex"), resave: false, saveUninitialized: true }));
|
||||
|
||||
// Login shim
|
||||
app.post("/login", (req, res) => {
|
||||
req.session.user = req.body.email || "admin@example.com";
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
const limiter = sessionRevoke2faRateLimiterFactory();
|
||||
|
||||
// POST /api/settings/templates
|
||||
app.post("/api/settings/templates", limiter, (req, res) => {
|
||||
const cleanId = String(req.body?.id || "").trim().toLowerCase();
|
||||
if (!cleanId) return res.status(400).json({ error: "invalid id" });
|
||||
const stepUp = mockRequireDestructiveActionStepUp(req, res, `Template create "${cleanId}"`, { scopeKey: `template:${cleanId}` });
|
||||
if (!stepUp.ok) return;
|
||||
res.json({ ok: true, template: { id: cleanId }, usedGrace: stepUp.usedGrace });
|
||||
});
|
||||
|
||||
// PUT /api/settings/templates/:id
|
||||
app.put("/api/settings/templates/:id", limiter, (req, res) => {
|
||||
const targetId = req.params.id;
|
||||
const stepUp = mockRequireDestructiveActionStepUp(req, res, `Template update "${targetId}"`, { scopeKey: `template:${targetId}` });
|
||||
if (!stepUp.ok) return;
|
||||
res.json({ ok: true, template: { id: targetId }, usedGrace: stepUp.usedGrace });
|
||||
});
|
||||
|
||||
// DELETE /api/settings/templates/:id
|
||||
app.delete("/api/settings/templates/:id", limiter, (req, res) => {
|
||||
const cleanId = req.params.id;
|
||||
const stepUp = mockRequireDestructiveActionStepUp(req, res, `Template delete "${cleanId}"`, { scopeKey: `template:${cleanId}` });
|
||||
if (!stepUp.ok) return;
|
||||
res.json({ ok: true, removed: cleanId, usedGrace: stepUp.usedGrace });
|
||||
});
|
||||
|
||||
// POST /api/settings/template-store/sync
|
||||
app.post("/api/settings/template-store/sync", limiter, (req, res) => {
|
||||
const stepUp = mockRequireDestructiveActionStepUp(req, res, "Template store sync", { scopeKey: "template-store:sync" });
|
||||
if (!stepUp.ok) return;
|
||||
res.json({ ok: true, manifest: {}, usedGrace: stepUp.usedGrace });
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
function startServer(app) {
|
||||
return new Promise((resolve) => {
|
||||
const server = app.listen(0, "127.0.0.1", () => resolve(server));
|
||||
});
|
||||
}
|
||||
|
||||
function request(server, path, { cookie, body, method = "POST" } = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const { port } = server.address();
|
||||
const data = body ? JSON.stringify(body) : null;
|
||||
const req = http.request(
|
||||
{
|
||||
host: "127.0.0.1",
|
||||
port,
|
||||
path,
|
||||
method,
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
...(cookie ? { cookie } : {}),
|
||||
...(data ? { "content-length": Buffer.byteLength(data) } : {}),
|
||||
},
|
||||
},
|
||||
(res) => {
|
||||
let buf = "";
|
||||
res.on("data", (c) => (buf += c));
|
||||
res.on("end", () => {
|
||||
const setCookie = res.headers["set-cookie"];
|
||||
resolve({
|
||||
status: res.statusCode,
|
||||
headers: res.headers,
|
||||
body: buf ? JSON.parse(buf) : null,
|
||||
cookie: setCookie ? setCookie[0].split(";")[0] : cookie,
|
||||
});
|
||||
});
|
||||
}
|
||||
);
|
||||
req.on("error", reject);
|
||||
if (data) req.write(data);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
async function run() {
|
||||
const app = buildApp();
|
||||
const server = await startServer(app);
|
||||
|
||||
try {
|
||||
// 1. Log in
|
||||
const loginRes = await request(server, "/login", { body: { email: "admin@adpanel.io" } });
|
||||
const cookie = loginRes.cookie;
|
||||
|
||||
// 2. Verify: initial request without credentials triggers 403 password-required
|
||||
const unauthedCreate = await request(server, "/api/settings/templates", {
|
||||
cookie,
|
||||
body: { id: "custom-game" }
|
||||
});
|
||||
assert.strictEqual(unauthedCreate.status, 403);
|
||||
assert.strictEqual(unauthedCreate.body.code, "password-required");
|
||||
console.log("PASS 1: uncredentialed create challenged with 403 password-required");
|
||||
|
||||
// 3. Verify: request with wrong password fails
|
||||
const wrongPassCreate = await request(server, "/api/settings/templates", {
|
||||
cookie,
|
||||
body: { id: "custom-game", currentPassword: "wrong-password" }
|
||||
});
|
||||
assert.strictEqual(wrongPassCreate.status, 403);
|
||||
assert.strictEqual(wrongPassCreate.body.code, "invalid-password");
|
||||
console.log("PASS 2: wrong credential rejected with 403 invalid-password");
|
||||
|
||||
// 4. Verify: request with valid credential succeeds and mints a scoped grant
|
||||
const validCreate = await request(server, "/api/settings/templates", {
|
||||
cookie,
|
||||
body: { id: "custom-game", currentPassword: "correct-horse-battery" }
|
||||
});
|
||||
assert.strictEqual(validCreate.status, 200);
|
||||
assert.strictEqual(validCreate.body.usedGrace, false);
|
||||
console.log("PASS 3: valid credential creates template and mints grant");
|
||||
|
||||
// 5. Verify: follow-up PUT on the SAME template uses grace grant silently
|
||||
const graceUpdate = await request(server, "/api/settings/templates/custom-game", {
|
||||
cookie,
|
||||
method: "PUT",
|
||||
body: { name: "Updated Game" }
|
||||
});
|
||||
assert.strictEqual(graceUpdate.status, 200);
|
||||
assert.strictEqual(graceUpdate.body.usedGrace, true);
|
||||
console.log("PASS 4: follow-up update on same scope uses grace grant without prompt");
|
||||
|
||||
// 6. Verify: PUT on a DIFFERENT template cannot use the grant (scope isolation)
|
||||
const crossTemplateUpdate = await request(server, "/api/settings/templates/other-game", {
|
||||
cookie,
|
||||
method: "PUT",
|
||||
body: { name: "Other Game" }
|
||||
});
|
||||
assert.strictEqual(crossTemplateUpdate.status, 403);
|
||||
assert.strictEqual(crossTemplateUpdate.body.code, "password-required");
|
||||
console.log("PASS 5: update on different template rejects mismatched scope grant");
|
||||
|
||||
// 7. Verify: DELETE on the authorized template uses the grant
|
||||
const graceDelete = await request(server, "/api/settings/templates/custom-game", {
|
||||
cookie,
|
||||
method: "DELETE",
|
||||
body: {}
|
||||
});
|
||||
assert.strictEqual(graceDelete.status, 200);
|
||||
assert.strictEqual(graceDelete.body.usedGrace, true);
|
||||
console.log("PASS 6: DELETE with JSON body on same scope uses grace grant");
|
||||
|
||||
// 8. Verify: store sync demands its own scope "template-store:sync"
|
||||
const syncRes = await request(server, "/api/settings/template-store/sync", {
|
||||
cookie,
|
||||
body: {}
|
||||
});
|
||||
assert.strictEqual(syncRes.status, 403);
|
||||
assert.strictEqual(syncRes.body.code, "password-required");
|
||||
console.log("PASS 7: store sync demands isolated scope (cannot ride template grant)");
|
||||
|
||||
// 9. Verify: rate limiter trips at 8 attempts for credential guesses
|
||||
const attackLogin = await request(server, "/login", { body: { email: "victim-admin@adpanel.io" } });
|
||||
const attackCookie = attackLogin.cookie;
|
||||
|
||||
for (let i = 0; i < 8; i++) {
|
||||
const res = await request(server, "/api/settings/templates", {
|
||||
cookie: attackCookie,
|
||||
body: { id: "pwn", currentPassword: `guess-${i}` }
|
||||
});
|
||||
assert.strictEqual(res.status, 403);
|
||||
}
|
||||
const rateLimitedRes = await request(server, "/api/settings/templates", {
|
||||
cookie: attackCookie,
|
||||
body: { id: "pwn", currentPassword: "guess-8" }
|
||||
});
|
||||
assert.strictEqual(rateLimitedRes.status, 429);
|
||||
assert.strictEqual(rateLimitedRes.body.code, "verification-rate-limit");
|
||||
console.log("PASS 8: rate limiter trips at 8 credential attempts with 429 verification-rate-limit");
|
||||
|
||||
// 10. Verify: uncredentialed requests are NOT counted against the rate limiter
|
||||
const unauthedAfterLimit = await request(server, "/api/settings/templates", {
|
||||
cookie: attackCookie,
|
||||
body: { id: "pwn" }
|
||||
});
|
||||
assert.strictEqual(unauthedAfterLimit.status, 403);
|
||||
assert.strictEqual(unauthedAfterLimit.body.code, "password-required");
|
||||
console.log("PASS 9: uncredentialed requests are skipped by rate limiter (no DoS on normal flow)");
|
||||
|
||||
console.log("\nALL TEMPLATE STEP-UP & RATE LIMITER TESTS PASSED SUCCESSFULLY!");
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
}
|
||||
|
||||
run().catch((err) => {
|
||||
console.error("TEST FAILED:", err);
|
||||
process.exit(1);
|
||||
});
|
||||
Reference in new issue
Block a user