mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-03 13:11:05 +00:00
- Test the 401 login fallback when the body is not JSON. - Flag bare sendBeacon calls and parse .js, .mjs and .cjs as JavaScript. - Record the change-password 403 in the CHANGELOG.
328 lines
13 KiB
JavaScript
328 lines
13 KiB
JavaScript
import ts from "typescript";
|
|
|
|
import assert from "node:assert/strict";
|
|
import { readdirSync, readFileSync } from "node:fs";
|
|
import { sep } from "node:path";
|
|
import { test } from "node:test";
|
|
import vm from "node:vm";
|
|
|
|
const output = ts.transpileModule(readFileSync(new URL("../src/lib/auth.ts", import.meta.url), "utf8"), {
|
|
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
|
|
}).outputText;
|
|
|
|
test("HTTPS marks the session cookie Secure while local HTTP remains usable", () => {
|
|
for (const protocol of ["https:", "http:"]) {
|
|
const storage = new Map();
|
|
const document = { cookie: "" };
|
|
const exports = {};
|
|
vm.runInNewContext(output, {
|
|
exports,
|
|
document,
|
|
window: { location: { protocol } },
|
|
localStorage: { setItem: (k, v) => storage.set(k, v) },
|
|
});
|
|
exports.auth.setToken("synthetic-session");
|
|
assert.equal(storage.get("artex_token"), "synthetic-session");
|
|
assert.equal(document.cookie.includes("; Secure"), protocol === "https:");
|
|
assert.ok(document.cookie.includes("SameSite=Lax"));
|
|
}
|
|
});
|
|
|
|
test("the route-guard cookie is a marker and never carries the session token", () => {
|
|
const storage = new Map();
|
|
const document = { cookie: "" };
|
|
const exports = {};
|
|
vm.runInNewContext(output, {
|
|
exports,
|
|
document,
|
|
window: { location: { protocol: "https:" } },
|
|
localStorage: { setItem: (k, v) => storage.set(k, v) },
|
|
});
|
|
exports.auth.setToken("synthetic.session.token");
|
|
assert.equal(storage.get("artex_token"), "synthetic.session.token");
|
|
assert.ok(document.cookie.startsWith("artex_token=1;"), document.cookie);
|
|
assert.ok(!document.cookie.includes("synthetic"), document.cookie);
|
|
});
|
|
|
|
// --- one 401 / 403 handler for every API call (src/lib/api-fetch.ts) ---
|
|
|
|
const transpile = (file) =>
|
|
ts.transpileModule(readFileSync(new URL(file, import.meta.url), "utf8"), {
|
|
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
|
|
}).outputText;
|
|
const sources = {
|
|
"@/lib/auth": output,
|
|
"@/lib/api-fetch": transpile("../src/lib/api-fetch.ts"),
|
|
"@/lib/api": transpile("../src/lib/api.ts"),
|
|
};
|
|
|
|
// browser loads the API client against a fake browser with a stored session.
|
|
// respond(url, init) returns { status, body } for each request.
|
|
function browser(respond, protocol = "https:") {
|
|
const storage = new Map([["artex_token", "synthetic-session"]]);
|
|
const window = { location: { protocol, href: "/tasks" } };
|
|
const document = { cookie: "artex_token=1" };
|
|
const requests = [];
|
|
const sseCalls = [];
|
|
const loaded = {};
|
|
const load = (name) => {
|
|
if (!loaded[name]) {
|
|
loaded[name] = {};
|
|
vm.runInNewContext(sources[name], {
|
|
exports: loaded[name],
|
|
require,
|
|
window,
|
|
// Empty base keeps sseUrl same-origin; the test checks the constructor arguments.
|
|
process: { env: { NEXT_PUBLIC_SSE_BASE: "" } },
|
|
document,
|
|
FormData,
|
|
URLSearchParams,
|
|
localStorage: {
|
|
getItem: (k) => storage.get(k) ?? null,
|
|
setItem: (k, v) => storage.set(k, v),
|
|
removeItem: (k) => storage.delete(k),
|
|
},
|
|
fetch: async (url, init) => {
|
|
requests.push({ url, init });
|
|
const { status, body = "" } = respond(url, init);
|
|
return {
|
|
status,
|
|
ok: status >= 200 && status < 300,
|
|
json: async () => JSON.parse(body),
|
|
text: async () => body,
|
|
blob: async () => body,
|
|
headers: { get: () => null },
|
|
};
|
|
},
|
|
});
|
|
}
|
|
return loaded[name];
|
|
};
|
|
function require(name) {
|
|
if (name in sources) return load(name);
|
|
if (name === "@/i18n") return { t: (key, vars) => key.replace(/\{(\w+)\}/g, (_, k) => String(vars?.[k])) };
|
|
if (name === "@/lib/mock/enabled") return { MOCK: false };
|
|
if (name === "@/lib/mock/handler") return { mockHandle: () => assert.fail("unexpected mock request") };
|
|
if (name === "@/lib/sse")
|
|
return {
|
|
SSEStream: class {
|
|
constructor(...args) {
|
|
sseCalls.push(args);
|
|
}
|
|
},
|
|
};
|
|
throw new Error(`Unexpected import: ${name}`);
|
|
}
|
|
return {
|
|
...load("@/lib/auth"),
|
|
...load("@/lib/api-fetch"),
|
|
...load("@/lib/api"),
|
|
sseCalls,
|
|
storage,
|
|
window,
|
|
document,
|
|
requests,
|
|
};
|
|
}
|
|
|
|
test("clearSession drops the token and the cookie and goes to /login", () => {
|
|
for (const protocol of ["https:", "http:"]) {
|
|
const b = browser(() => assert.fail("no request expected"), protocol);
|
|
b.clearSession();
|
|
assert.equal(b.storage.has("artex_token"), false);
|
|
assert.ok(b.document.cookie.startsWith("artex_token=;"), b.document.cookie);
|
|
assert.ok(b.document.cookie.includes("max-age=0"));
|
|
assert.ok(b.document.cookie.includes("SameSite=Lax"));
|
|
assert.equal(b.document.cookie.includes("; Secure"), protocol === "https:");
|
|
assert.equal(b.window.location.href, "/login");
|
|
}
|
|
});
|
|
|
|
test("apiFetch sends the bearer token and keeps the caller's headers", async () => {
|
|
const b = browser(() => ({ status: 200, body: "{}" }));
|
|
const r = await b.apiFetch("/intercept/tool-config", {
|
|
method: "PUT",
|
|
headers: { "Content-Type": "application/json" },
|
|
});
|
|
assert.equal(r.status, 200);
|
|
assert.equal(b.requests[0].url, "/api/intercept/tool-config");
|
|
assert.equal(b.requests[0].init.method, "PUT");
|
|
assert.equal(b.requests[0].init.headers.Authorization, "Bearer synthetic-session");
|
|
assert.equal(b.requests[0].init.headers["Content-Type"], "application/json");
|
|
assert.equal(b.window.location.href, "/tasks");
|
|
});
|
|
|
|
// http() and every API call that used to call fetch itself.
|
|
const callers = {
|
|
"http()": (b) => b.http("/tasks"),
|
|
workspaceUpload: (b) => b.api.workspaceUpload("dir", []),
|
|
workspaceDownload: (b) => b.api.workspaceDownload("a.txt"),
|
|
exportFindings: (b) => b.api.exportFindings({ format: "csv", scope: "all" }),
|
|
downloadFindingTrafficBody: (b) => b.api.downloadFindingTrafficBody("1", "2", "request"),
|
|
trafficBlob: (b) => b.api.trafficBlob("abc"),
|
|
trafficExportHAR: (b) => b.api.trafficExportHAR(),
|
|
report: (b) => b.api.report(),
|
|
chatUpload: (b) => b.api.chatUpload("task", "1", []),
|
|
uploadSkill: (b) => b.api.uploadSkill({ name: "s.zip" }),
|
|
changePassword: (b) => b.api.changePassword("old", "new"),
|
|
interceptGetToolConfig: (b) => b.api.interceptGetToolConfig(),
|
|
interceptSetToolConfig: (b) => b.api.interceptSetToolConfig([]),
|
|
};
|
|
|
|
for (const [name, call] of Object.entries(callers)) {
|
|
test(`${name}: a 401 clears the session and redirects to /login`, async () => {
|
|
const b = browser(() => ({ status: 401, body: '{"error":"token is invalid or expired"}' }));
|
|
await assert.rejects(call(b), /^Error: Unauthorized$/);
|
|
assert.equal(b.requests.length, 1);
|
|
assert.ok(b.requests[0].url.startsWith("/api/"), b.requests[0].url);
|
|
assert.equal(b.requests[0].init.headers.Authorization, "Bearer synthetic-session");
|
|
assert.equal(b.storage.has("artex_token"), false);
|
|
assert.ok(b.document.cookie.includes("max-age=0"), b.document.cookie);
|
|
assert.equal(b.window.location.href, "/login");
|
|
});
|
|
|
|
test(`${name}: a 403 throws ForbiddenError and keeps the session`, async () => {
|
|
const b = browser(() => ({ status: 403, body: '{"error":"Forbidden"}' }));
|
|
const err = await call(b).then(
|
|
() => assert.fail("expected a rejection"),
|
|
(e) => e,
|
|
);
|
|
assert.ok(err instanceof b.ForbiddenError, String(err));
|
|
assert.ok(err instanceof b.ApiError);
|
|
assert.equal(err.status, 403);
|
|
assert.equal(err.message, "Forbidden");
|
|
assert.equal(b.storage.get("artex_token"), "synthetic-session");
|
|
assert.equal(b.window.location.href, "/tasks");
|
|
});
|
|
}
|
|
|
|
test("a 403 without a JSON body keeps the status-based message http() used", async () => {
|
|
const b = browser(() => ({ status: 403, body: "" }));
|
|
await assert.rejects(b.http("/tasks", { method: "POST", body: "{}" }), (e) => {
|
|
assert.ok(e instanceof b.ForbiddenError);
|
|
assert.equal(e.message, "POST /tasks: 403");
|
|
return true;
|
|
});
|
|
});
|
|
|
|
test("other errors from http() are unchanged", async () => {
|
|
const b = browser(() => ({ status: 409, body: '{"error":"already running"}' }));
|
|
await assert.rejects(b.http("/tasks"), (e) => {
|
|
assert.ok(e instanceof b.ApiError);
|
|
assert.ok(!(e instanceof b.ForbiddenError));
|
|
assert.equal(e.status, 409);
|
|
assert.equal(e.message, "already running");
|
|
return true;
|
|
});
|
|
assert.equal(b.window.location.href, "/tasks");
|
|
});
|
|
|
|
test("openSSE wires the token getter and clearSession into SSEStream", () => {
|
|
const b = browser(() => assert.fail("no request expected"));
|
|
b.openSSE("/events");
|
|
assert.equal(b.sseCalls.length, 1);
|
|
const [url, getToken, unauthorized] = b.sseCalls[0];
|
|
assert.equal(url, "/events");
|
|
assert.equal(getToken, b.getToken);
|
|
assert.equal(unauthorized, b.clearSession);
|
|
});
|
|
|
|
test("a 401 from /auth/login keeps the session and reports the server message", async () => {
|
|
const b = browser(() => ({ status: 401, body: '{"error":"Incorrect username or password"}' }));
|
|
const err = await b.api.login("ARTEX", "wrong").then(
|
|
() => assert.fail("login should fail"),
|
|
(e) => e,
|
|
);
|
|
assert.ok(err instanceof b.ApiError, String(err));
|
|
assert.equal(err.status, 401);
|
|
assert.equal(err.message, "Incorrect username or password");
|
|
assert.equal(b.storage.get("artex_token"), "synthetic-session");
|
|
assert.equal(b.window.location.href, "/tasks");
|
|
assert.ok(!b.document.cookie.includes("max-age=0"), b.document.cookie);
|
|
});
|
|
|
|
test("a 401 from /auth/login without a JSON body falls back to Unauthorized", async () => {
|
|
const b = browser(() => ({ status: 401, body: "<html>401</html>" }));
|
|
const err = await b.api.login("ARTEX", "wrong").then(
|
|
() => assert.fail("login should fail"),
|
|
(e) => e,
|
|
);
|
|
assert.ok(err instanceof b.ApiError && err.status === 401 && err.message === "Unauthorized", String(err));
|
|
assert.equal(b.storage.get("artex_token"), "synthetic-session");
|
|
assert.equal(b.window.location.href, "/tasks");
|
|
});
|
|
|
|
test("changePassword keeps the session on a wrong current password", async () => {
|
|
const b = browser(() => ({ status: 403, body: '{"error":"Current password is wrong"}' }));
|
|
const err = await b.api.changePassword("old", "new").then(
|
|
() => assert.fail("change-password should fail"),
|
|
(e) => e,
|
|
);
|
|
assert.ok(err instanceof b.ForbiddenError, String(err));
|
|
assert.equal(err.status, 403);
|
|
assert.equal(err.message, "Current password is wrong");
|
|
assert.equal(b.storage.get("artex_token"), "synthetic-session");
|
|
assert.equal(b.window.location.href, "/tasks");
|
|
});
|
|
|
|
test("FormData uploads leave Content-Type to the browser", async () => {
|
|
for (const call of [
|
|
(b) => b.api.workspaceUpload("dir", []),
|
|
(b) => b.api.chatUpload("task", "1", []),
|
|
(b) => b.api.uploadSkill({ name: "s.zip" }),
|
|
]) {
|
|
const b = browser(() => ({ status: 200, body: "{}" }));
|
|
await call(b);
|
|
assert.equal(b.requests.length, 1);
|
|
assert.equal(new Headers(b.requests[0].init.headers).get("Content-Type"), null);
|
|
}
|
|
});
|
|
|
|
// Only the shared helper and the SSE client touch the network directly. Everything
|
|
// else goes through apiFetch, so 401 and 403 are handled in one place. The parse
|
|
// ignores comments and string literals; aliases of fetch cannot be detected.
|
|
test("no other source file calls the network directly", () => {
|
|
const src = new URL("../src/", import.meta.url);
|
|
const allowed = new Set(["lib/api-fetch.ts", "lib/sse.ts"]);
|
|
const direct = (file, text) => {
|
|
const kinds = {
|
|
tsx: ts.ScriptKind.TSX,
|
|
jsx: ts.ScriptKind.JSX,
|
|
js: ts.ScriptKind.JS,
|
|
mjs: ts.ScriptKind.JS,
|
|
cjs: ts.ScriptKind.JS,
|
|
};
|
|
const kind = kinds[file.slice(file.lastIndexOf(".") + 1)] ?? ts.ScriptKind.TS;
|
|
const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, kind);
|
|
let found = false;
|
|
const visit = (node) => {
|
|
if (found) return;
|
|
if (ts.isCallExpression(node)) {
|
|
const callee = node.expression;
|
|
if (ts.isIdentifier(callee)) {
|
|
if (callee.text === "fetch" || callee.text === "sendBeacon") found = true;
|
|
} else if (ts.isPropertyAccessExpression(callee)) {
|
|
const name = callee.name.text;
|
|
const base = callee.expression;
|
|
if (name === "fetch" && ts.isIdentifier(base) && ["window", "globalThis", "self"].includes(base.text))
|
|
found = true;
|
|
if (name === "sendBeacon") found = true;
|
|
}
|
|
} else if (ts.isNewExpression(node)) {
|
|
const callee = node.expression;
|
|
if (ts.isIdentifier(callee) && ["XMLHttpRequest", "EventSource"].includes(callee.text)) found = true;
|
|
}
|
|
ts.forEachChild(node, visit);
|
|
};
|
|
visit(sf);
|
|
return found;
|
|
};
|
|
const offenders = [];
|
|
for (const entry of readdirSync(src, { recursive: true })) {
|
|
const file = String(entry).split(sep).join("/");
|
|
if (!/\.(ts|tsx|js|mjs|cjs|jsx)$/.test(file) || allowed.has(file)) continue;
|
|
if (/\.(test|spec)\.[cm]?[jt]sx?$/.test(file)) continue;
|
|
if (direct(file, readFileSync(new URL(file, src), "utf8"))) offenders.push(file);
|
|
}
|
|
assert.deepEqual(offenders, []);
|
|
});
|