Merge ITHC recovery into mitigation baseline
This commit is contained in:
@@ -155,7 +155,7 @@ test("createappealcompletemessage_api rejects missing hash with 400", async () =
|
||||
createBlob: async () => ({}),
|
||||
getCaseBlob: async () => ({}),
|
||||
createCaseCompleteMessage: async () => ({}),
|
||||
updateAccount: async () => ({}),
|
||||
updateCrmContact: async () => ({}),
|
||||
consoleLogger: () => {},
|
||||
_: { isEmpty: (value) => !value },
|
||||
nextConnect,
|
||||
|
||||
@@ -34,6 +34,8 @@ const loadModule = (relativePath, injected = {}) => {
|
||||
source += `\nif (typeof ${name} !== "undefined" && !module.exports.default) module.exports.default = ${name};\n`;
|
||||
});
|
||||
|
||||
source +=
|
||||
'\nif (typeof getCrmPersonalAccount !== "undefined") module.exports.getCrmPersonalAccount = getCrmPersonalAccount;\n';
|
||||
source +=
|
||||
'\nif (typeof respondSuccess !== "undefined") module.exports.respondSuccess = respondSuccess;\n';
|
||||
source +=
|
||||
@@ -48,6 +50,7 @@ const loadModule = (relativePath, injected = {}) => {
|
||||
exports: {},
|
||||
require,
|
||||
process,
|
||||
URL,
|
||||
console: {
|
||||
log: () => {},
|
||||
info: () => {},
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -149,7 +149,9 @@ const assertNoUploadWrites = (calls) => {
|
||||
};
|
||||
|
||||
test("upload rejects a missing NextAuth session before HMAC or Azure write", async () => {
|
||||
const loaded = loadUploadAuthorization({ getServerSession: async () => null });
|
||||
const loaded = loadUploadAuthorization({
|
||||
getServerSession: async () => null
|
||||
});
|
||||
const res = createRes();
|
||||
|
||||
await loaded.mod.default.handler(uploadAuthorizationRequest(), res);
|
||||
@@ -906,9 +908,15 @@ for (const inputCase of [
|
||||
{ name: "missing container", body: { container: undefined } },
|
||||
{ name: "malformed container", body: { container: "Invalid_Container" } },
|
||||
{ name: "missing case identifier", body: { casefolderID: undefined } },
|
||||
{ name: "case identifier path separator", body: { casefolderID: "TMP/CASE-1" } },
|
||||
{
|
||||
name: "case identifier path separator",
|
||||
body: { casefolderID: "TMP/CASE-1" }
|
||||
},
|
||||
{ name: "case identifier traversal segment", body: { casefolderID: ".." } },
|
||||
{ name: "case identifier control character", body: { casefolderID: "TMP\u0000CASE" } }
|
||||
{
|
||||
name: "case identifier control character",
|
||||
body: { casefolderID: "TMP\u0000CASE" }
|
||||
}
|
||||
]) {
|
||||
test(`admin case deletion rejects ${inputCase.name} without deletion`, async () => {
|
||||
const loaded = loadAdminCaseDeletion();
|
||||
@@ -917,7 +925,8 @@ for (const inputCase of [
|
||||
|
||||
request.body = { ...request.body, ...inputCase.body };
|
||||
Object.keys(request.body).forEach((key) => {
|
||||
if (typeof request.body[key] === "undefined") delete request.body[key];
|
||||
if (typeof request.body[key] === "undefined")
|
||||
delete request.body[key];
|
||||
});
|
||||
await loaded.mod.default(request, res);
|
||||
|
||||
@@ -938,10 +947,9 @@ test("valid administrator can delete a cross-container case prefix with the exis
|
||||
assert.deepStrictEqual(loaded.calls.deletion, [
|
||||
[request.body.container, request.body.casefolderID]
|
||||
]);
|
||||
assert.deepStrictEqual(
|
||||
JSON.parse(JSON.stringify(res.state.jsonBody)),
|
||||
{ data: loaded.payload }
|
||||
);
|
||||
assert.deepStrictEqual(JSON.parse(JSON.stringify(res.state.jsonBody)), {
|
||||
data: loaded.payload
|
||||
});
|
||||
});
|
||||
|
||||
test("admin case deletion dependency failure returns DELETE_BLOB_CASE_FAILED", async () => {
|
||||
@@ -1166,7 +1174,10 @@ test("valid administrative representation JSON edit preserves the existing mutat
|
||||
const updatedJson = JSON.parse(loaded.uploaded.content);
|
||||
assert.strictEqual(Object.hasOwn(updatedJson, "repComplete"), false);
|
||||
assert.strictEqual(updatedJson.containerID, loaded.sourceJson.containerID);
|
||||
assert.strictEqual(updatedJson.ticketnumber, loaded.sourceJson.ticketnumber);
|
||||
assert.strictEqual(
|
||||
updatedJson.ticketnumber,
|
||||
loaded.sourceJson.ticketnumber
|
||||
);
|
||||
assert.strictEqual(
|
||||
updatedJson.representationType,
|
||||
loaded.sourceJson.representationType
|
||||
@@ -1234,9 +1245,7 @@ test("deleteawaitingsubmissionfromblob accepts legacy deleteblob hash variant",
|
||||
getServerSession: async () => ({ user: { id: "container-1" } }),
|
||||
authOptions: () => ({}),
|
||||
hashAPIPath: (queryPath) =>
|
||||
queryPath.includes(
|
||||
"/api/file/deleteblob?container=container-1"
|
||||
)
|
||||
queryPath.includes("/api/file/deleteblob?container=container-1")
|
||||
? "&hash=expected"
|
||||
: "&hash=other",
|
||||
respondError: respondErrorMock,
|
||||
@@ -1545,6 +1554,10 @@ test("getrepsblob handler success returns representations payload", async () =>
|
||||
respondError: respondErrorMock,
|
||||
respondSuccess: respondSuccessMock,
|
||||
consoleLogger: () => {},
|
||||
getServerSession: async () => ({ user: { id: "c1" } }),
|
||||
authOptions: () => ({}),
|
||||
readAdminSessionCookie: () => null,
|
||||
validateAdminSession: () => false,
|
||||
getRepsBlobs: async () => [
|
||||
{ path: "c/ref_rep.json", name: "ref_rep.json" }
|
||||
],
|
||||
@@ -1603,6 +1616,10 @@ test("getrepsblob handler rejects invalid HMAC before Azure access", async () =>
|
||||
respondError: respondErrorMock,
|
||||
respondSuccess: respondSuccessMock,
|
||||
consoleLogger: () => {},
|
||||
getServerSession: async () => ({ user: { id: "c1" } }),
|
||||
authOptions: () => ({}),
|
||||
readAdminSessionCookie: () => null,
|
||||
validateAdminSession: () => false,
|
||||
getRepsBlobs: async () => {
|
||||
azureCalls += 1;
|
||||
return [];
|
||||
@@ -1692,7 +1709,12 @@ const appealCompletionSigningRequest = (pathValue) => ({
|
||||
});
|
||||
|
||||
for (const sessionCase of [
|
||||
{ name: "missing session", session: null, status: 401, code: "UNAUTHENTICATED" },
|
||||
{
|
||||
name: "missing session",
|
||||
session: null,
|
||||
status: 401,
|
||||
code: "UNAUTHENTICATED"
|
||||
},
|
||||
{ name: "session without user id", session: { user: {} } },
|
||||
{ name: "session with empty user id", session: { user: { id: "" } } },
|
||||
{
|
||||
@@ -1705,7 +1727,9 @@ for (const sessionCase of [
|
||||
}
|
||||
]) {
|
||||
test(`gethash rejects appeal completion signing for ${sessionCase.name} before HMAC generation`, async () => {
|
||||
const loaded = loadAppealCompletionSigning({ session: sessionCase.session });
|
||||
const loaded = loadAppealCompletionSigning({
|
||||
session: sessionCase.session
|
||||
});
|
||||
const res = createRes();
|
||||
|
||||
await loaded.mod.default.handler(appealCompletionSigningRequest(), res);
|
||||
@@ -1801,6 +1825,10 @@ test("getrepsblob handler dependency failure returns GET_REPS_BLOB_FAILED", asyn
|
||||
respondError: respondErrorMock,
|
||||
respondSuccess: respondSuccessMock,
|
||||
consoleLogger: () => {},
|
||||
getServerSession: async () => ({ user: { id: "c1" } }),
|
||||
authOptions: () => ({}),
|
||||
readAdminSessionCookie: () => null,
|
||||
validateAdminSession: () => false,
|
||||
getRepsBlobs: async () => {
|
||||
throw new Error("storage failure");
|
||||
},
|
||||
@@ -1828,6 +1856,10 @@ test("getrepsblob handler accepts encoded container hash variant", async () => {
|
||||
respondError: respondErrorMock,
|
||||
respondSuccess: respondSuccessMock,
|
||||
consoleLogger: () => {},
|
||||
getServerSession: async () => ({ user: { id: "cont/1" } }),
|
||||
authOptions: () => ({}),
|
||||
readAdminSessionCookie: () => null,
|
||||
validateAdminSession: () => false,
|
||||
getRepsBlobs: async () => [{ path: "cont/rep1.json" }],
|
||||
downloadAllRepsFiles: async () => ({ value: [{ id: "r-encoded" }] })
|
||||
});
|
||||
@@ -2256,14 +2288,29 @@ test("createrepcompletemessage rejects unsupported methods before authorization
|
||||
|
||||
for (const inputCase of [
|
||||
{ name: "missing container", query: { container: undefined } },
|
||||
{ name: "invalid container type", query: { container: ["user-container"] } },
|
||||
{
|
||||
name: "invalid container type",
|
||||
query: { container: ["user-container"] }
|
||||
},
|
||||
{ name: "malformed container", query: { container: "Invalid_Container" } },
|
||||
{ name: "missing case reference", query: { tempcaseref: undefined } },
|
||||
{ name: "unsafe case-reference path separator", query: { tempcaseref: "CAS/123" } },
|
||||
{ name: "unsafe case-reference traversal segment", query: { tempcaseref: ".." } },
|
||||
{
|
||||
name: "unsafe case-reference path separator",
|
||||
query: { tempcaseref: "CAS/123" }
|
||||
},
|
||||
{
|
||||
name: "unsafe case-reference traversal segment",
|
||||
query: { tempcaseref: ".." }
|
||||
},
|
||||
{ name: "missing representation identifier", query: { repid: undefined } },
|
||||
{ name: "unsafe representation path separator", query: { repid: "rep\\file" } },
|
||||
{ name: "unsafe representation control character", query: { repid: "rep\u0000file" } }
|
||||
{
|
||||
name: "unsafe representation path separator",
|
||||
query: { repid: "rep\\file" }
|
||||
},
|
||||
{
|
||||
name: "unsafe representation control character",
|
||||
query: { repid: "rep\u0000file" }
|
||||
}
|
||||
]) {
|
||||
test(`createrepcompletemessage rejects ${inputCase.name} before authorization work`, async () => {
|
||||
const loaded = loadOrdinaryRepCompletion();
|
||||
@@ -2272,7 +2319,8 @@ for (const inputCase of [
|
||||
|
||||
request.query = { ...request.query, ...inputCase.query };
|
||||
Object.keys(request.query).forEach((key) => {
|
||||
if (typeof request.query[key] === "undefined") delete request.query[key];
|
||||
if (typeof request.query[key] === "undefined")
|
||||
delete request.query[key];
|
||||
});
|
||||
await loaded.mod.default(request, res);
|
||||
|
||||
@@ -2416,7 +2464,13 @@ test("createrepcompletemessage dependency failure returns CREATE_REP_COMPLETE_ME
|
||||
});
|
||||
|
||||
const loadAdminRepCompletion = (overrides = {}) => {
|
||||
const calls = { noStore: 0, readSession: 0, validate: 0, origin: 0, queue: [] };
|
||||
const calls = {
|
||||
noStore: 0,
|
||||
readSession: 0,
|
||||
validate: 0,
|
||||
origin: 0,
|
||||
queue: []
|
||||
};
|
||||
const payload = { messageId: "admin-message" };
|
||||
const mod = loadModule("pages/api/admin/createrepcompletemessage.js", {
|
||||
respondError: respondErrorMock,
|
||||
@@ -2495,7 +2549,10 @@ for (const sessionCase of [
|
||||
}
|
||||
|
||||
for (const originCase of [
|
||||
{ name: "missing Origin", headers: { cookie: "pedw_admin_session=admin-token" } },
|
||||
{
|
||||
name: "missing Origin",
|
||||
headers: { cookie: "pedw_admin_session=admin-token" }
|
||||
},
|
||||
{
|
||||
name: "cross-origin request",
|
||||
headers: {
|
||||
@@ -2505,7 +2562,9 @@ for (const originCase of [
|
||||
}
|
||||
]) {
|
||||
test(`admin representation completion rejects ${originCase.name}`, async () => {
|
||||
const loaded = loadAdminRepCompletion({ hasTrustedSameOrigin: () => false });
|
||||
const loaded = loadAdminRepCompletion({
|
||||
hasTrustedSameOrigin: () => false
|
||||
});
|
||||
const res = createRes();
|
||||
|
||||
await loaded.mod.default(
|
||||
@@ -2533,7 +2592,8 @@ for (const inputCase of [
|
||||
|
||||
request.body = { ...request.body, ...inputCase.body };
|
||||
Object.keys(request.body).forEach((key) => {
|
||||
if (typeof request.body[key] === "undefined") delete request.body[key];
|
||||
if (typeof request.body[key] === "undefined")
|
||||
delete request.body[key];
|
||||
});
|
||||
await loaded.mod.default(request, res);
|
||||
|
||||
@@ -2825,7 +2885,13 @@ const loadOrdinaryRepsProxy = (overrides = {}) => {
|
||||
return "&hash=abc";
|
||||
},
|
||||
consoleLogger: () => {},
|
||||
process: { env: { API_ROOT: "http://example.com" } },
|
||||
BASE_URL: "http://example.com",
|
||||
process: {
|
||||
env: {
|
||||
API_ROOT: "http://example.com",
|
||||
NEXTAUTH_URL: "http://example.com"
|
||||
}
|
||||
},
|
||||
axios: {
|
||||
get: async (...args) => {
|
||||
calls.axios.push(args);
|
||||
@@ -2935,7 +3001,9 @@ for (const containerCase of [
|
||||
|
||||
test("getrepsblobproxy preserves signed path and response for owning user", async () => {
|
||||
const loaded = loadOrdinaryRepsProxy();
|
||||
const req = ordinaryRepsRequest();
|
||||
const req = ordinaryRepsRequest({
|
||||
headers: { cookie: "next-auth.session-token=test-session" }
|
||||
});
|
||||
const res = createRes();
|
||||
|
||||
await loaded.mod.default(req, res);
|
||||
@@ -2951,6 +3019,16 @@ test("getrepsblobproxy preserves signed path and response for owning user", asyn
|
||||
loaded.calls.axios[0][0],
|
||||
"http://example.com/api/file/getrepsblob?container=user-container&hash=abc"
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
JSON.parse(JSON.stringify(loaded.calls.axios[0][1])),
|
||||
{
|
||||
headers: {
|
||||
Authorization: "Bearer tok",
|
||||
Cookie: "next-auth.session-token=test-session"
|
||||
},
|
||||
maxRedirects: 0
|
||||
}
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
JSON.parse(JSON.stringify(res.state.jsonBody)),
|
||||
loaded.payload
|
||||
@@ -2986,6 +3064,7 @@ const loadAdminRepsProxy = (overrides = {}) => {
|
||||
const mod = loadModule("pages/api/admin/getrepsblobproxy.js", {
|
||||
respondError: respondErrorMock,
|
||||
respondSuccess: respondSuccessMock,
|
||||
ADMIN_SESSION_COOKIE: "pedw_admin_session",
|
||||
readAdminSessionCookie: () => "admin-token",
|
||||
validateAdminSession: () => true,
|
||||
hasTrustedSameOrigin: () => true,
|
||||
@@ -3000,7 +3079,13 @@ const loadAdminRepsProxy = (overrides = {}) => {
|
||||
return "&hash=abc";
|
||||
},
|
||||
consoleLogger: () => {},
|
||||
process: { env: { API_ROOT: "http://example.com" } },
|
||||
BASE_URL: "http://example.com",
|
||||
process: {
|
||||
env: {
|
||||
API_ROOT: "http://example.com",
|
||||
NEXTAUTH_URL: "http://example.com"
|
||||
}
|
||||
},
|
||||
axios: {
|
||||
get: async (...args) => {
|
||||
calls.axios.push(args);
|
||||
@@ -3051,7 +3136,9 @@ for (const adminSessionCase of [
|
||||
|
||||
for (const originCase of ["missing Origin", "cross-origin request"]) {
|
||||
test(`admin getrepsblobproxy rejects ${originCase} before proxy work`, async () => {
|
||||
const loaded = loadAdminRepsProxy({ hasTrustedSameOrigin: () => false });
|
||||
const loaded = loadAdminRepsProxy({
|
||||
hasTrustedSameOrigin: () => false
|
||||
});
|
||||
const req = adminRepsRequest();
|
||||
if (originCase === "missing Origin") delete req.headers.origin;
|
||||
if (originCase === "cross-origin request") {
|
||||
@@ -3125,6 +3212,16 @@ test("admin getrepsblobproxy preserves cross-container signed path and response"
|
||||
loaded.calls.axios[0][0],
|
||||
"http://example.com/api/file/getrepsblob?container=selected-user-container&hash=abc"
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
JSON.parse(JSON.stringify(loaded.calls.axios[0][1])),
|
||||
{
|
||||
headers: {
|
||||
Authorization: "Bearer tok",
|
||||
Cookie: "pedw_admin_session=admin-token"
|
||||
},
|
||||
maxRedirects: 0
|
||||
}
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
JSON.parse(JSON.stringify(res.state.jsonBody)),
|
||||
loaded.payload
|
||||
@@ -3156,6 +3253,19 @@ test("admin storage refresh uses dedicated POST proxy while ordinary callers rem
|
||||
assert.match(viewAllSource, /getRepsFromBlobProxy\(containerID\)/);
|
||||
});
|
||||
|
||||
test("admin getrepsblobproxy rejects untrusted internal destination before proxy work", async () => {
|
||||
const loaded = loadAdminRepsProxy({
|
||||
BASE_URL: "https://attacker.example"
|
||||
});
|
||||
const res = createRes();
|
||||
|
||||
await loaded.mod.default(adminRepsRequest(), res);
|
||||
|
||||
assert.strictEqual(res.state.statusCode, 403);
|
||||
assert.strictEqual(res.state.jsonBody.error.code, "FORBIDDEN");
|
||||
assertNoProxyWork(loaded.calls);
|
||||
});
|
||||
|
||||
test("admin storage completion uses dedicated POST route while ordinary completion remains unchanged", () => {
|
||||
const rootDir = path.resolve(__dirname, "..", "..");
|
||||
const adminSource = fs.readFileSync(
|
||||
@@ -3563,53 +3673,59 @@ const loadAppealCompletionDirect = ({ session, ...overrides } = {}) => {
|
||||
"customerid_contact@odata.bind":
|
||||
"/contacts(00000000-0000-0000-0000-000000000001)"
|
||||
};
|
||||
const mod = loadModule("pages/api/file/createappealcompletemessage_api.js", {
|
||||
nextConnect: createNextConnectMock(),
|
||||
middleware: () => {},
|
||||
respondError: respondErrorMock,
|
||||
respondSuccess: respondSuccessMock,
|
||||
authOptions: (req, res) => {
|
||||
calls.options.push([req, res]);
|
||||
return options;
|
||||
},
|
||||
getServerSession: async (...args) => {
|
||||
calls.session.push(args);
|
||||
return resolvedSession;
|
||||
},
|
||||
hashAPIPath: (queryPath) => {
|
||||
calls.hash.push(queryPath);
|
||||
return "&hash=expected";
|
||||
},
|
||||
getProgressBlobs: async (...args) => {
|
||||
calls.progress.push(args);
|
||||
return { path: "TMP-CASE-1/progress.json" };
|
||||
},
|
||||
downloadProgressFile: async (...args) => {
|
||||
calls.download.push(args);
|
||||
return args[1].endsWith("_case.json")
|
||||
? { ...caseObject }
|
||||
: { ...progress };
|
||||
},
|
||||
createBlob: async (...args) => {
|
||||
calls.createBlob.push(args);
|
||||
return {};
|
||||
},
|
||||
getCaseBlob: async (...args) => {
|
||||
calls.caseBlob.push(args);
|
||||
return {};
|
||||
},
|
||||
updateAccount: async (...args) => {
|
||||
calls.account.push(args);
|
||||
return {};
|
||||
},
|
||||
createCaseCompleteMessage: async (...args) => {
|
||||
calls.queue.push(args);
|
||||
return {};
|
||||
},
|
||||
consoleLogger: () => {},
|
||||
_: { isEmpty: (value) => value === undefined || value === null || value === "" },
|
||||
...overrides
|
||||
});
|
||||
const mod = loadModule(
|
||||
"pages/api/file/createappealcompletemessage_api.js",
|
||||
{
|
||||
nextConnect: createNextConnectMock(),
|
||||
middleware: () => {},
|
||||
respondError: respondErrorMock,
|
||||
respondSuccess: respondSuccessMock,
|
||||
authOptions: (req, res) => {
|
||||
calls.options.push([req, res]);
|
||||
return options;
|
||||
},
|
||||
getServerSession: async (...args) => {
|
||||
calls.session.push(args);
|
||||
return resolvedSession;
|
||||
},
|
||||
hashAPIPath: (queryPath) => {
|
||||
calls.hash.push(queryPath);
|
||||
return "&hash=expected";
|
||||
},
|
||||
getProgressBlobs: async (...args) => {
|
||||
calls.progress.push(args);
|
||||
return { path: "TMP-CASE-1/progress.json" };
|
||||
},
|
||||
downloadProgressFile: async (...args) => {
|
||||
calls.download.push(args);
|
||||
return args[1].endsWith("_case.json")
|
||||
? { ...caseObject }
|
||||
: { ...progress };
|
||||
},
|
||||
createBlob: async (...args) => {
|
||||
calls.createBlob.push(args);
|
||||
return {};
|
||||
},
|
||||
getCaseBlob: async (...args) => {
|
||||
calls.caseBlob.push(args);
|
||||
return {};
|
||||
},
|
||||
updateCrmContact: async (...args) => {
|
||||
calls.account.push(args);
|
||||
return {};
|
||||
},
|
||||
createCaseCompleteMessage: async (...args) => {
|
||||
calls.queue.push(args);
|
||||
return {};
|
||||
},
|
||||
consoleLogger: () => {},
|
||||
_: {
|
||||
isEmpty: (value) =>
|
||||
value === undefined || value === null || value === ""
|
||||
},
|
||||
...overrides
|
||||
}
|
||||
);
|
||||
|
||||
return { mod, calls, options };
|
||||
};
|
||||
@@ -3647,7 +3763,9 @@ for (const sessionCase of [
|
||||
}
|
||||
]) {
|
||||
test(`createappealcompletemessage_api blocks direct bypass with ${sessionCase.name} before HMAC or side effects`, async () => {
|
||||
const loaded = loadAppealCompletionDirect({ session: sessionCase.session });
|
||||
const loaded = loadAppealCompletionDirect({
|
||||
session: sessionCase.session
|
||||
});
|
||||
const res = createRes();
|
||||
|
||||
await loaded.mod.default.handler(appealCompletionDirectRequest(), res);
|
||||
@@ -3799,11 +3917,7 @@ test("createappealcompletemessage_api preserves owner payloads and downstream co
|
||||
]);
|
||||
assert.deepStrictEqual(loaded.calls.download, [
|
||||
["owner-container", "TMP-CASE-1/progress.json", "TMP-CASE-1"],
|
||||
[
|
||||
"owner-container",
|
||||
"TMP-CASE-1/TMP-CASE-1_case.json",
|
||||
"TMP-CASE-1"
|
||||
]
|
||||
["owner-container", "TMP-CASE-1/TMP-CASE-1_case.json", "TMP-CASE-1"]
|
||||
]);
|
||||
const savedProgress = JSON.parse(loaded.calls.createBlob[0][0]);
|
||||
assert.strictEqual(savedProgress.appealComplete, "TMP-CASE-1");
|
||||
@@ -3813,16 +3927,12 @@ test("createappealcompletemessage_api preserves owner payloads and downstream co
|
||||
"TMP-CASE-1"
|
||||
]);
|
||||
assert.strictEqual(loaded.calls.caseBlob.length, 1);
|
||||
assert.deepStrictEqual(
|
||||
JSON.parse(JSON.stringify(loaded.calls.account)),
|
||||
assert.deepStrictEqual(JSON.parse(JSON.stringify(loaded.calls.account)), [
|
||||
[
|
||||
[
|
||||
"00000000-0000-0000-0000-000000000001",
|
||||
{ pinswg_typeofinvolvement: 846040001 },
|
||||
true
|
||||
]
|
||||
"00000000-0000-0000-0000-000000000001",
|
||||
{ pinswg_typeofinvolvement: 846040001 }
|
||||
]
|
||||
);
|
||||
]);
|
||||
assert.deepStrictEqual(loaded.calls.queue, [
|
||||
["owner-container", "TMP-CASE-1"]
|
||||
]);
|
||||
@@ -3905,7 +4015,7 @@ test("createappealcompletemessage_api accepts encoded hash variant and returns s
|
||||
createBlob: async () => ({}),
|
||||
getCaseBlob: async () => ({}),
|
||||
createCaseCompleteMessage: async () => ({}),
|
||||
updateAccount: async () => ({}),
|
||||
updateCrmContact: async () => ({}),
|
||||
consoleLogger: () => {},
|
||||
_: { isEmpty: (v) => v === undefined || v === null || v === "" }
|
||||
}
|
||||
@@ -4987,7 +5097,9 @@ for (const endpoint of [
|
||||
|
||||
test(`${endpoint.name} rejects another user's container before privileged work`, async () => {
|
||||
const loaded = endpoint.load({
|
||||
getServerSession: async () => ({ user: { id: "different-container" } })
|
||||
getServerSession: async () => ({
|
||||
user: { id: "different-container" }
|
||||
})
|
||||
});
|
||||
const res = createRes();
|
||||
|
||||
@@ -5000,7 +5112,9 @@ for (const endpoint of [
|
||||
|
||||
test(`${endpoint.name} ignores a client-provided user identity`, async () => {
|
||||
const loaded = endpoint.load({
|
||||
getServerSession: async () => ({ user: { id: "different-container" } })
|
||||
getServerSession: async () => ({
|
||||
user: { id: "different-container" }
|
||||
})
|
||||
});
|
||||
const req = endpoint.request();
|
||||
req.body.userID = PDF_OWNER_CONTAINER;
|
||||
@@ -5064,27 +5178,23 @@ for (const containerCase of [
|
||||
});
|
||||
}
|
||||
|
||||
test("generatepdf rejects missing and conflicting draft-folder identifiers", async () => {
|
||||
for (const body of [
|
||||
{
|
||||
representationType: "Other",
|
||||
repfile_name: "rep-file",
|
||||
containerID: PDF_OWNER_CONTAINER
|
||||
},
|
||||
{
|
||||
representationType: "Other",
|
||||
repfile_name: "rep-file",
|
||||
containerID: PDF_OWNER_CONTAINER,
|
||||
ticketnumber: PDF_CASE_FOLDER,
|
||||
caseRef: "CASE-2"
|
||||
}
|
||||
]) {
|
||||
const loaded = loadGeneratePdf();
|
||||
const res = createRes();
|
||||
await loaded.mod.default(generatePdfRequest({ body }), res);
|
||||
assert.strictEqual(res.state.statusCode, 400);
|
||||
assertNoGeneratePdfWork(loaded.calls);
|
||||
}
|
||||
test("generatepdf rejects missing draft-folder identifiers", async () => {
|
||||
const loaded = loadGeneratePdf();
|
||||
const res = createRes();
|
||||
|
||||
await loaded.mod.default(
|
||||
generatePdfRequest({
|
||||
body: {
|
||||
representationType: "Other",
|
||||
repfile_name: "rep-file",
|
||||
containerID: PDF_OWNER_CONTAINER
|
||||
}
|
||||
}),
|
||||
res
|
||||
);
|
||||
|
||||
assert.strictEqual(res.state.statusCode, 400);
|
||||
assertNoGeneratePdfWork(loaded.calls);
|
||||
});
|
||||
|
||||
test("generateappealpdf rejects missing or malformed draft-folder identifiers", async () => {
|
||||
@@ -5150,7 +5260,9 @@ for (const endpoint of [
|
||||
|
||||
test(`${endpoint.name} rejects a valid HMAC for an unauthorised container`, async () => {
|
||||
const loaded = endpoint.load({
|
||||
getServerSession: async () => ({ user: { id: "different-container" } })
|
||||
getServerSession: async () => ({
|
||||
user: { id: "different-container" }
|
||||
})
|
||||
});
|
||||
const res = createRes();
|
||||
await loaded.mod.default(endpoint.request(), res);
|
||||
@@ -5174,6 +5286,51 @@ test("generatepdf owner success writes the PDF to the authorised container", asy
|
||||
assert.strictEqual(res.state.jsonBody.status, "success");
|
||||
});
|
||||
|
||||
test("generatepdf preserves ticketnumber precedence when references differ", async () => {
|
||||
const loaded = loadGeneratePdf();
|
||||
const res = createRes();
|
||||
|
||||
await loaded.mod.default(
|
||||
generatePdfRequest({
|
||||
body: {
|
||||
representationType: "Other",
|
||||
repfile_name: "rep-file",
|
||||
containerID: PDF_OWNER_CONTAINER,
|
||||
ticketnumber: PDF_CASE_FOLDER,
|
||||
caseRef: "CASE-2"
|
||||
}
|
||||
}),
|
||||
res
|
||||
);
|
||||
|
||||
assert.strictEqual(res.state.statusCode, 200);
|
||||
assert.strictEqual(loaded.calls.create.length, 1);
|
||||
assert.strictEqual(loaded.calls.create[0][1], PDF_OWNER_CONTAINER);
|
||||
assert.strictEqual(loaded.calls.create[0][2], PDF_CASE_FOLDER);
|
||||
assert.strictEqual(res.state.jsonBody.status, "success");
|
||||
});
|
||||
|
||||
test("generatepdf rejects malformed secondary case references", async () => {
|
||||
const loaded = loadGeneratePdf();
|
||||
const res = createRes();
|
||||
|
||||
await loaded.mod.default(
|
||||
generatePdfRequest({
|
||||
body: {
|
||||
representationType: "Other",
|
||||
repfile_name: "rep-file",
|
||||
containerID: PDF_OWNER_CONTAINER,
|
||||
ticketnumber: PDF_CASE_FOLDER,
|
||||
caseRef: "../other-case"
|
||||
}
|
||||
}),
|
||||
res
|
||||
);
|
||||
|
||||
assert.strictEqual(res.state.statusCode, 400);
|
||||
assertNoGeneratePdfWork(loaded.calls);
|
||||
});
|
||||
|
||||
test("generateappealpdf owner success reads and writes only the authorised container", async () => {
|
||||
const loaded = loadGenerateAppealPdf();
|
||||
const res = createRes();
|
||||
@@ -5457,10 +5614,7 @@ test("createcase_api creates both draft JSON blobs in the authenticated owner's
|
||||
assert.strictEqual(loaded.calls.caseBlob.length, 1);
|
||||
assert.strictEqual(loaded.calls.appealBlob.length, 1);
|
||||
assert.strictEqual(loaded.calls.caseBlob[0][0], CASE_OWNER_CONTAINER);
|
||||
assert.strictEqual(
|
||||
loaded.calls.caseBlob[0][1],
|
||||
GENERATED_CASE_REFERENCE
|
||||
);
|
||||
assert.strictEqual(loaded.calls.caseBlob[0][1], GENERATED_CASE_REFERENCE);
|
||||
assert.strictEqual(loaded.calls.appealBlob[0][1], CASE_OWNER_CONTAINER);
|
||||
assert.deepStrictEqual(
|
||||
JSON.parse(JSON.stringify(loaded.calls.caseBlob[0][2])),
|
||||
@@ -5469,10 +5623,12 @@ test("createcase_api creates both draft JSON blobs in the authenticated owner's
|
||||
assert.deepStrictEqual(JSON.parse(loaded.calls.appealBlob[0][0]), {
|
||||
pinswg_name: GENERATED_CASE_REFERENCE,
|
||||
pinswg_appealcasetype: "846040000",
|
||||
_pinswg_associatedlpa_value:
|
||||
"00000000-0000-4000-8000-000000000002"
|
||||
_pinswg_associatedlpa_value: "00000000-0000-4000-8000-000000000002"
|
||||
});
|
||||
assert.strictEqual(res.state.jsonBody.ticketnumber, GENERATED_CASE_REFERENCE);
|
||||
assert.strictEqual(
|
||||
res.state.jsonBody.ticketnumber,
|
||||
GENERATED_CASE_REFERENCE
|
||||
);
|
||||
assert.strictEqual(res.state.jsonBody.title, GENERATED_CASE_REFERENCE);
|
||||
assert.strictEqual(
|
||||
res.state.jsonBody.incidentid,
|
||||
@@ -5499,6 +5655,75 @@ test("createcase_api preserves the existing propagated token dependency failure
|
||||
assert.strictEqual(loaded.calls.appealBlob.length, 0);
|
||||
});
|
||||
|
||||
const loadRepresentationDeletion = (route, operationName, session) => {
|
||||
const calls = [];
|
||||
const mod = loadModule(route, {
|
||||
nextConnect: createNextConnectMock(),
|
||||
middleware: () => {},
|
||||
getServerSession: async () => session,
|
||||
authOptions: () => ({}),
|
||||
hashAPIPath: () => "&hash=expected",
|
||||
respondError: respondErrorMock,
|
||||
respondSuccess: respondSuccessMock,
|
||||
[operationName]: async (...args) => {
|
||||
calls.push(args);
|
||||
return { deleted: true };
|
||||
}
|
||||
});
|
||||
|
||||
return { mod, calls };
|
||||
};
|
||||
|
||||
test("whole-representation deletion remains cross-user protected with zero Azure operations", async () => {
|
||||
const loaded = loadRepresentationDeletion(
|
||||
"pages/api/file/deleteblobrep.js",
|
||||
"deleteBlobRep",
|
||||
{ user: { id: "different-container" } }
|
||||
);
|
||||
const res = createRes();
|
||||
|
||||
await loaded.mod.default.handler(
|
||||
{
|
||||
query: {
|
||||
container: "organisation-container",
|
||||
casefolderID: "CASE-1",
|
||||
repfile: "REP-1",
|
||||
hash: "expected"
|
||||
}
|
||||
},
|
||||
res
|
||||
);
|
||||
|
||||
assert.strictEqual(res.state.statusCode, 403);
|
||||
assert.strictEqual(res.state.jsonBody.error.code, "FORBIDDEN");
|
||||
assert.strictEqual(loaded.calls.length, 0);
|
||||
});
|
||||
|
||||
test("representation supporting-file deletion remains cross-user protected with zero Azure operations", async () => {
|
||||
const loaded = loadRepresentationDeletion(
|
||||
"pages/api/file/deleteblob.js",
|
||||
"deleteBlob",
|
||||
{ user: { id: "different-container" } }
|
||||
);
|
||||
const res = createRes();
|
||||
|
||||
await loaded.mod.default.handler(
|
||||
{
|
||||
query: {
|
||||
container: "organisation-container",
|
||||
casefolderID: "CASE-1/REP-1",
|
||||
blobname: "evidence.pdf",
|
||||
hash: "expected"
|
||||
}
|
||||
},
|
||||
res
|
||||
);
|
||||
|
||||
assert.strictEqual(res.state.statusCode, 403);
|
||||
assert.strictEqual(res.state.jsonBody.error.code, "FORBIDDEN");
|
||||
assert.strictEqual(loaded.calls.length, 0);
|
||||
});
|
||||
|
||||
const run = async () => {
|
||||
let passed = 0;
|
||||
for (const currentTest of tests) {
|
||||
|
||||
@@ -129,7 +129,7 @@ test("excluded route families remain outside this myportal slice", async () => {
|
||||
const pageSource = read("pages/myportal/index.js");
|
||||
|
||||
assert.match(portalSource, /\/api\/subscriptions\/get-watched-cases/);
|
||||
assert.match(pageSource, /getRepsFromBlob\(thisSession.user.id\)/);
|
||||
assert.match(pageSource, /getRepsFromBlob\(thisSession.user.id,\s*\{/);
|
||||
assert.match(
|
||||
pageSource,
|
||||
/getAwaitingSubmissionFromBlob\(thisSession.user.id\)/
|
||||
|
||||
@@ -6,10 +6,7 @@ const vm = require("vm");
|
||||
const tests = [];
|
||||
const test = (name, fn) => tests.push({ name, fn });
|
||||
|
||||
const loadAuthInternals = ({
|
||||
adapterFactory = () => ({}),
|
||||
resolveCrmLocale = async () => null
|
||||
} = {}) => {
|
||||
const loadAuthInternals = ({ adapterFactory = () => ({}) } = {}) => {
|
||||
const filePath = path.join(
|
||||
__dirname,
|
||||
"..",
|
||||
@@ -59,7 +56,7 @@ const loadAuthInternals = ({
|
||||
},
|
||||
NextAuth: () => ({}),
|
||||
EmailProvider: () => ({}),
|
||||
resolveCrmLocale,
|
||||
getPortalLogin: async () => ({ value: [] }),
|
||||
redactSensitive: (value) => value,
|
||||
consoleLogger: () => {},
|
||||
console: {
|
||||
|
||||
@@ -203,12 +203,6 @@ test("breadcrumbs/factory module includes expected mapped route definitions", as
|
||||
true,
|
||||
"Expected /account/personaldetails to be mapped in createDetailAndAccountRouteRenderers"
|
||||
);
|
||||
|
||||
assert.strictEqual(
|
||||
source.includes('"/account/changepassword": () =>'),
|
||||
true,
|
||||
"Expected /account/changepassword to be mapped in createDetailAndAccountRouteRenderers"
|
||||
);
|
||||
});
|
||||
|
||||
test("breadcrumbs/component composes mapped routes via imported factories and shared resolver", async () => {
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
const assert = require("assert");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const vm = require("vm");
|
||||
|
||||
const tests = [];
|
||||
const test = (name, fn) => tests.push({ name, fn });
|
||||
|
||||
const loadIndexLoader = (overrides = {}) => {
|
||||
const filePath = path.join(
|
||||
__dirname,
|
||||
"..",
|
||||
"..",
|
||||
"pages",
|
||||
"myportal",
|
||||
"index.js"
|
||||
);
|
||||
|
||||
let source = fs.readFileSync(filePath, "utf8");
|
||||
|
||||
// Execute only the server-side loader, not the React component.
|
||||
source = source.slice(source.indexOf("export const getServerSideProps"));
|
||||
source = source.slice(0, source.indexOf("const mapStateToProps"));
|
||||
|
||||
source = source.replace(
|
||||
/export\s+const\s+getServerSideProps\s*=/,
|
||||
"const getServerSideProps ="
|
||||
);
|
||||
source += "\nmodule.exports = { getServerSideProps };\n";
|
||||
|
||||
const dispatches = [];
|
||||
const store = {
|
||||
dispatch: (action) => dispatches.push(action)
|
||||
};
|
||||
|
||||
const context = {
|
||||
module: { exports: {} },
|
||||
exports: {},
|
||||
process: { env: {} },
|
||||
console: { error: () => {} },
|
||||
wrapper: {
|
||||
getServerSideProps: (factory) => async (ctx) => factory(store)(ctx)
|
||||
},
|
||||
getSession: async () => ({
|
||||
user: {
|
||||
id: "session-user-1",
|
||||
email: "user@example.com"
|
||||
}
|
||||
}),
|
||||
getIP: () => {},
|
||||
consoleLogger: () => {},
|
||||
getPortalLogin: async () => ({
|
||||
value: [{ contactid: "crm-contact-1" }]
|
||||
}),
|
||||
createContainerProxy: async () => {},
|
||||
getCrmPersonalAccount: async () => ({
|
||||
firstname: "Test",
|
||||
pinswg_typeofinvolvement: 0,
|
||||
pinswg_preferredlanguage: 0
|
||||
}),
|
||||
getMyCases: async () => ({ value: [] }),
|
||||
getMyLPACases: async () => ({ value: [] }),
|
||||
getRepsFromBlob: async () => ({ value: [] }),
|
||||
getWatchedCases: async () => ({ value: [] }),
|
||||
getAwaitingSubmissionFromBlob: async () => ({ value: [] }),
|
||||
splitWatchedCasesBySubmissionState: () => ({
|
||||
watchedCases: { value: [] },
|
||||
submittedRepresentations: { value: [] }
|
||||
}),
|
||||
getPortalModuleDetails: async () => ({}),
|
||||
getFormCollectionByID: () => ({
|
||||
LogicalCollectionName: "pinswg_cases"
|
||||
}),
|
||||
pLimit: () => (fn) => fn(),
|
||||
setLocale: (value) => ({ type: "locale", value }),
|
||||
setShowReps: () => ({ type: "showReps" }),
|
||||
setAccountDetails: (value) => ({ type: "accountDetails", value }),
|
||||
setLoggedInUserId: (value) => ({ type: "loggedInUserId", value }),
|
||||
setMyCases: () => ({ type: "myCases" }),
|
||||
setMyCasesDetails: () => ({ type: "myCasesDetails" }),
|
||||
setMyRepresentations: () => ({ type: "myRepresentations" }),
|
||||
setMyRepresentationsDetails: () => ({
|
||||
type: "myRepresentationsDetails"
|
||||
}),
|
||||
setWatchedCases: () => ({ type: "watchedCases" }),
|
||||
setWatchedCasesDetails: () => ({ type: "watchedCasesDetails" }),
|
||||
setMySubmittedReps: () => ({ type: "mySubmittedReps" }),
|
||||
setMySubmittedRepsDetails: () => ({
|
||||
type: "mySubmittedRepsDetails"
|
||||
}),
|
||||
setAwaitingSubmissionFromBlob: () => ({
|
||||
type: "awaitingSubmission"
|
||||
}),
|
||||
setAwaitingSubmissionDetails: () => ({
|
||||
type: "awaitingSubmissionDetails"
|
||||
}),
|
||||
setContainerID: () => ({ type: "containerID" }),
|
||||
...overrides
|
||||
};
|
||||
|
||||
vm.runInNewContext(source, context, { filename: filePath });
|
||||
|
||||
return {
|
||||
getServerSideProps: context.module.exports.getServerSideProps,
|
||||
dispatches
|
||||
};
|
||||
};
|
||||
|
||||
const createContext = () => ({
|
||||
req: {
|
||||
cookies: {},
|
||||
headers: { cookie: "" }
|
||||
},
|
||||
locale: "en"
|
||||
});
|
||||
|
||||
test("missing session redirects to signin", async () => {
|
||||
const loader = loadIndexLoader({
|
||||
getSession: async () => null
|
||||
});
|
||||
|
||||
const result = await loader.getServerSideProps(createContext());
|
||||
|
||||
assert.strictEqual(result.redirect.destination, "/auth/signin");
|
||||
});
|
||||
|
||||
test("missing session identity redirects to signin", async () => {
|
||||
const loader = loadIndexLoader({
|
||||
getSession: async () => ({
|
||||
user: { id: "session-user-1" }
|
||||
})
|
||||
});
|
||||
|
||||
const result = await loader.getServerSideProps(createContext());
|
||||
|
||||
assert.strictEqual(result.redirect.destination, "/auth/signin");
|
||||
});
|
||||
|
||||
test("CRM contact lookup failure redirects to signin", async () => {
|
||||
const loader = loadIndexLoader({
|
||||
getPortalLogin: async () => {
|
||||
throw new Error("CRM unavailable");
|
||||
}
|
||||
});
|
||||
|
||||
const result = await loader.getServerSideProps(createContext());
|
||||
|
||||
assert.strictEqual(result.redirect.destination, "/auth/signin");
|
||||
});
|
||||
|
||||
test("missing CRM contact redirects to signin", async () => {
|
||||
const loader = loadIndexLoader({
|
||||
getPortalLogin: async () => ({ value: [] })
|
||||
});
|
||||
|
||||
const result = await loader.getServerSideProps(createContext());
|
||||
|
||||
assert.strictEqual(result.redirect.destination, "/auth/signin");
|
||||
});
|
||||
|
||||
test("personal account lookup exception redirects to error page", async () => {
|
||||
const loader = loadIndexLoader({
|
||||
getCrmPersonalAccount: async () => {
|
||||
throw new Error("CRM account lookup failed");
|
||||
}
|
||||
});
|
||||
|
||||
const result = await loader.getServerSideProps(createContext());
|
||||
|
||||
assert.strictEqual(result.redirect.destination, "/myportal/error");
|
||||
});
|
||||
|
||||
test("missing personal account redirects to error page", async () => {
|
||||
const loader = loadIndexLoader({
|
||||
getCrmPersonalAccount: async () => null
|
||||
});
|
||||
|
||||
const result = await loader.getServerSideProps(createContext());
|
||||
|
||||
assert.strictEqual(result.redirect.destination, "/myportal/error");
|
||||
});
|
||||
|
||||
test("personal account error response redirects to error page", async () => {
|
||||
const loader = loadIndexLoader({
|
||||
getCrmPersonalAccount: async () => ({
|
||||
errorCode: "CRM_CONTACT_MISSING"
|
||||
})
|
||||
});
|
||||
|
||||
const result = await loader.getServerSideProps(createContext());
|
||||
|
||||
assert.strictEqual(result.redirect.destination, "/myportal/error");
|
||||
});
|
||||
|
||||
test("successful lookup uses contact resolved from session email", async () => {
|
||||
let capturedEmail;
|
||||
let capturedContactId;
|
||||
|
||||
const loader = loadIndexLoader({
|
||||
getPortalLogin: async (email) => {
|
||||
capturedEmail = email;
|
||||
return { value: [{ contactid: "crm-contact-123" }] };
|
||||
},
|
||||
getCrmPersonalAccount: async (contactId) => {
|
||||
capturedContactId = contactId;
|
||||
return {
|
||||
firstname: "Test",
|
||||
pinswg_typeofinvolvement: 0,
|
||||
pinswg_preferredlanguage: 0
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
const result = await loader.getServerSideProps(createContext());
|
||||
|
||||
assert.strictEqual(capturedEmail, "user@example.com");
|
||||
assert.strictEqual(capturedContactId, "crm-contact-123");
|
||||
assert.strictEqual(result.props.containerID, "session-user-1");
|
||||
|
||||
const accountDispatch = loader.dispatches.find(
|
||||
(action) => action.type === "accountDetails"
|
||||
);
|
||||
|
||||
assert.strictEqual(accountDispatch.value.firstname, "Test");
|
||||
});
|
||||
|
||||
const run = async () => {
|
||||
let passed = 0;
|
||||
|
||||
for (const currentTest of tests) {
|
||||
await currentTest.fn();
|
||||
passed += 1;
|
||||
}
|
||||
|
||||
console.log(
|
||||
`Phase 22 myportal-index-loader-guards tests passed (${passed}/${tests.length}).`
|
||||
);
|
||||
};
|
||||
|
||||
module.exports = run;
|
||||
|
||||
if (require.main === module) {
|
||||
run().catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
const assert = require("assert");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const vm = require("vm");
|
||||
|
||||
const tests = [];
|
||||
const test = (name, fn) => tests.push({ name, fn });
|
||||
|
||||
const loadViewAllLoader = (overrides = {}) => {
|
||||
const filePath = path.join(
|
||||
__dirname,
|
||||
"..",
|
||||
"..",
|
||||
"pages",
|
||||
"myportal",
|
||||
"viewall.js"
|
||||
);
|
||||
|
||||
let source = fs.readFileSync(filePath, "utf8");
|
||||
|
||||
// Execute the actual SSR loader, excluding the React component.
|
||||
const start = source.indexOf("export const getServerSideProps");
|
||||
const end = source.indexOf("const mapStateToProps", start);
|
||||
|
||||
assert.ok(start >= 0, "SSR loader declaration not found");
|
||||
assert.ok(end > start, "SSR loader boundary not found");
|
||||
|
||||
source = source.slice(start, end);
|
||||
source = source.replace(
|
||||
/export\s+const\s+getServerSideProps\s*=/,
|
||||
"const getServerSideProps ="
|
||||
);
|
||||
source += "\nmodule.exports = { getServerSideProps };\n";
|
||||
|
||||
const dispatches = [];
|
||||
const store = {
|
||||
dispatch: (action) => dispatches.push(action)
|
||||
};
|
||||
|
||||
const action = (type) => (value) => ({ type, value });
|
||||
|
||||
const context = {
|
||||
module: { exports: {} },
|
||||
exports: {},
|
||||
console: {
|
||||
log: () => {},
|
||||
error: () => {}
|
||||
},
|
||||
wrapper: {
|
||||
getServerSideProps: (factory) => async (ctx) => factory(store)(ctx)
|
||||
},
|
||||
getSession: async () => ({
|
||||
user: {
|
||||
id: "session-user-1",
|
||||
email: "user@example.com"
|
||||
}
|
||||
}),
|
||||
getPortalLogin: async () => ({
|
||||
value: [{ contactid: "crm-contact-1" }]
|
||||
}),
|
||||
getCrmPersonalAccount: async () => ({
|
||||
firstname: "Test",
|
||||
pinswg_typeofinvolvement: 0
|
||||
}),
|
||||
consoleLogger: () => {},
|
||||
pLimit: () => (fn) => fn(),
|
||||
getMyCases: async () => ({ value: [] }),
|
||||
getMyLPACases: async () => ({ value: [] }),
|
||||
getWatchedCases: async () => ({ value: [] }),
|
||||
getRepsFromBlob: async () => ({ value: [] }),
|
||||
getAwaitingSubmissionFromBlob: async () => ({ value: [] }),
|
||||
splitWatchedCasesBySubmissionState: () => ({
|
||||
watchedCases: [],
|
||||
submittedRepresentations: []
|
||||
}),
|
||||
getPortalModuleDetails: async () => ({}),
|
||||
getFormCollectionByID: () => ({
|
||||
LogicalCollectionName: "pinswg_cases"
|
||||
}),
|
||||
getBasicSearch: async () => ({ value: [] }),
|
||||
setAccountDetails: action("accountDetails"),
|
||||
setLoggedInUserId: action("loggedInUserId"),
|
||||
setContainerID: action("containerID"),
|
||||
setCurrentView: action("currentView"),
|
||||
setMyCases: action("myCases"),
|
||||
setMyCasesDetails: action("myCasesDetails"),
|
||||
setWatchedCases: action("watchedCases"),
|
||||
setWatchedCasesDetails: action("watchedCasesDetails"),
|
||||
setMySubmittedReps: action("mySubmittedReps"),
|
||||
setMySubmittedRepsDetails: action("mySubmittedRepsDetails"),
|
||||
setMyRepresentations: action("myRepresentations"),
|
||||
setMyRepresentationsDetails: action("myRepresentationsDetails"),
|
||||
setAwaitingSubmissionFromBlob: action("awaitingSubmission"),
|
||||
setAwaitingSubmissionDetails: action("awaitingSubmissionDetails"),
|
||||
setSearchResults: action("searchResults"),
|
||||
setSearch: action("search"),
|
||||
...overrides
|
||||
};
|
||||
|
||||
vm.runInNewContext(source, context, { filename: filePath });
|
||||
|
||||
return {
|
||||
getServerSideProps: context.module.exports.getServerSideProps,
|
||||
dispatches
|
||||
};
|
||||
};
|
||||
|
||||
const createContext = (key = "myCases") => ({
|
||||
query: { key },
|
||||
req: { cookies: {} },
|
||||
locale: "en"
|
||||
});
|
||||
|
||||
const getDispatch = (loader, type) =>
|
||||
loader.dispatches.find((item) => item.type === type);
|
||||
|
||||
test("invalid view category redirects before account lookup", async () => {
|
||||
let accountLookupCalled = false;
|
||||
|
||||
const loader = loadViewAllLoader({
|
||||
getCrmPersonalAccount: async () => {
|
||||
accountLookupCalled = true;
|
||||
return {};
|
||||
}
|
||||
});
|
||||
|
||||
const result = await loader.getServerSideProps(createContext("invalid"));
|
||||
|
||||
assert.strictEqual(result.redirect.destination, "/myportal");
|
||||
assert.strictEqual(accountLookupCalled, false);
|
||||
});
|
||||
|
||||
test("missing session redirects to signin", async () => {
|
||||
const loader = loadViewAllLoader({
|
||||
getSession: async () => null
|
||||
});
|
||||
|
||||
const result = await loader.getServerSideProps(createContext());
|
||||
|
||||
assert.strictEqual(result.redirect.destination, "/auth/signin");
|
||||
});
|
||||
|
||||
test("missing session email redirects to signin", async () => {
|
||||
const loader = loadViewAllLoader({
|
||||
getSession: async () => ({
|
||||
user: { id: "session-user-1" }
|
||||
})
|
||||
});
|
||||
|
||||
const result = await loader.getServerSideProps(createContext());
|
||||
|
||||
assert.strictEqual(result.redirect.destination, "/auth/signin");
|
||||
});
|
||||
|
||||
test("missing CRM contact redirects to signin", async () => {
|
||||
const loader = loadViewAllLoader({
|
||||
getPortalLogin: async () => ({ value: [] })
|
||||
});
|
||||
|
||||
const result = await loader.getServerSideProps(createContext());
|
||||
|
||||
assert.strictEqual(result.redirect.destination, "/auth/signin");
|
||||
});
|
||||
|
||||
test("personal account exception redirects to error page", async () => {
|
||||
const loader = loadViewAllLoader({
|
||||
getCrmPersonalAccount: async () => {
|
||||
throw new Error("CRM unavailable");
|
||||
}
|
||||
});
|
||||
|
||||
const result = await loader.getServerSideProps(createContext());
|
||||
|
||||
assert.strictEqual(result.redirect.destination, "/myportal/error");
|
||||
});
|
||||
|
||||
test("missing personal account redirects to error page", async () => {
|
||||
const loader = loadViewAllLoader({
|
||||
getCrmPersonalAccount: async () => null
|
||||
});
|
||||
|
||||
const result = await loader.getServerSideProps(createContext());
|
||||
|
||||
assert.strictEqual(result.redirect.destination, "/myportal/error");
|
||||
});
|
||||
|
||||
test("personal account error response redirects to error page", async () => {
|
||||
const loader = loadViewAllLoader({
|
||||
getCrmPersonalAccount: async () => ({
|
||||
errorCode: "CRM_CONTACT_MISSING"
|
||||
})
|
||||
});
|
||||
|
||||
const result = await loader.getServerSideProps(createContext());
|
||||
|
||||
assert.strictEqual(result.redirect.destination, "/myportal/error");
|
||||
});
|
||||
|
||||
test("successful lookup uses session-resolved CRM contact", async () => {
|
||||
let capturedEmail;
|
||||
let capturedContactId;
|
||||
|
||||
const accountDetails = {
|
||||
firstname: "Test",
|
||||
pinswg_typeofinvolvement: 0
|
||||
};
|
||||
|
||||
const loader = loadViewAllLoader({
|
||||
getPortalLogin: async (email) => {
|
||||
capturedEmail = email;
|
||||
return {
|
||||
value: [{ contactid: "crm-contact-123" }]
|
||||
};
|
||||
},
|
||||
getCrmPersonalAccount: async (contactId) => {
|
||||
capturedContactId = contactId;
|
||||
return accountDetails;
|
||||
}
|
||||
});
|
||||
|
||||
const result = await loader.getServerSideProps(createContext());
|
||||
|
||||
assert.strictEqual(capturedEmail, "user@example.com");
|
||||
assert.strictEqual(capturedContactId, "crm-contact-123");
|
||||
assert.ok(result.props);
|
||||
|
||||
assert.strictEqual(
|
||||
getDispatch(loader, "accountDetails").value.firstname,
|
||||
"Test"
|
||||
);
|
||||
assert.strictEqual(
|
||||
getDispatch(loader, "loggedInUserId").value,
|
||||
"crm-contact-123"
|
||||
);
|
||||
assert.strictEqual(
|
||||
getDispatch(loader, "containerID").value,
|
||||
"session-user-1"
|
||||
);
|
||||
assert.strictEqual(
|
||||
getDispatch(loader, "currentView").value.viewKey,
|
||||
"myCases"
|
||||
);
|
||||
});
|
||||
|
||||
test("all supported view categories load successfully", async () => {
|
||||
const categories = [
|
||||
"myCases",
|
||||
"watchedCases",
|
||||
"mySubmittedReps",
|
||||
"myRepresentations",
|
||||
"awaitingSubmissionDetails"
|
||||
];
|
||||
|
||||
for (const category of categories) {
|
||||
const loader = loadViewAllLoader();
|
||||
|
||||
const result = await loader.getServerSideProps(createContext(category));
|
||||
|
||||
assert.ok(result.props, `${category} should return props`);
|
||||
|
||||
assert.strictEqual(
|
||||
getDispatch(loader, "currentView").value.viewKey,
|
||||
category
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("LPA account uses associated LPA for case lookup", async () => {
|
||||
let capturedLpaId;
|
||||
let personalCaseLookupCalled = false;
|
||||
|
||||
const loader = loadViewAllLoader({
|
||||
getCrmPersonalAccount: async () => ({
|
||||
pinswg_typeofinvolvement: 846040012,
|
||||
"pinswg_contact_associatedlpa@OData.Community.Display.V1.FormattedValue":
|
||||
"lpa-123"
|
||||
}),
|
||||
getMyLPACases: async (lpaId) => {
|
||||
capturedLpaId = lpaId;
|
||||
return { value: [] };
|
||||
},
|
||||
getMyCases: async () => {
|
||||
personalCaseLookupCalled = true;
|
||||
return { value: [] };
|
||||
}
|
||||
});
|
||||
|
||||
await loader.getServerSideProps(createContext());
|
||||
|
||||
assert.strictEqual(capturedLpaId, "lpa-123");
|
||||
assert.strictEqual(personalCaseLookupCalled, false);
|
||||
});
|
||||
|
||||
const run = async () => {
|
||||
let passed = 0;
|
||||
|
||||
for (const currentTest of tests) {
|
||||
await currentTest.fn();
|
||||
passed += 1;
|
||||
}
|
||||
|
||||
console.log(
|
||||
`Phase 22 myportal-viewall-loader-guards tests passed (${passed}/${tests.length}).`
|
||||
);
|
||||
};
|
||||
|
||||
module.exports = run;
|
||||
|
||||
if (require.main === module) {
|
||||
run().catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
@@ -1,242 +0,0 @@
|
||||
const assert = require("assert");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const vm = require("vm");
|
||||
|
||||
const rootDir = path.resolve(__dirname, "..", "..");
|
||||
const tests = [];
|
||||
const test = (name, fn) => tests.push({ name, fn });
|
||||
|
||||
const loadModule = (relativePath, injected = {}) => {
|
||||
const filePath = path.join(rootDir, relativePath);
|
||||
let source = fs.readFileSync(filePath, "utf8");
|
||||
const exportNames = Array.from(
|
||||
source.matchAll(/export const\s+(\w+)\s*=/g)
|
||||
).map((match) => match[1]);
|
||||
|
||||
source = source.replace(/import[\s\S]*?from\s+"[^"]+";\n?/g, "");
|
||||
source = source.replace(/export const\s+/g, "const ");
|
||||
source = source.replace(
|
||||
/export default async function\s+(\w+)\s*\(/g,
|
||||
"async function $1("
|
||||
);
|
||||
source += `\nmodule.exports = { ${exportNames.join(", ")} };\n`;
|
||||
source +=
|
||||
'\nif (typeof handler !== "undefined") module.exports.default = handler;\n';
|
||||
|
||||
const context = {
|
||||
module: { exports: {} },
|
||||
exports: {},
|
||||
require,
|
||||
process,
|
||||
console: { log: () => {}, info: () => {}, warn: () => {}, error: () => {} },
|
||||
...injected
|
||||
};
|
||||
|
||||
vm.runInNewContext(source, context, { filename: filePath });
|
||||
return context.module.exports;
|
||||
};
|
||||
|
||||
const normalize = (value) => JSON.parse(JSON.stringify(value));
|
||||
|
||||
const createRes = () => {
|
||||
const state = { statusCode: null, jsonBody: undefined };
|
||||
|
||||
return {
|
||||
state,
|
||||
status(code) {
|
||||
state.statusCode = code;
|
||||
return this;
|
||||
},
|
||||
json(body) {
|
||||
state.jsonBody = body;
|
||||
return body;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const loadLocaleResolver = ({ relayGetData }) =>
|
||||
loadModule("lib/auth/resolveCrmLocale.js", {
|
||||
azureHeadersPaged: (accessToken) => ({ accessToken }),
|
||||
escapeODataString: (value) => value.trim().replace(/'/g, "''"),
|
||||
consoleLogger: () => {},
|
||||
relayGetData,
|
||||
RELAY_POLICY_STRICT_LOGIN: {
|
||||
method: "GET",
|
||||
timeoutMs: 5000,
|
||||
maxRetries: 0,
|
||||
retryBaseDelayMs: 0,
|
||||
retryMaxDelayMs: 0
|
||||
}
|
||||
});
|
||||
|
||||
test("pre-auth CRM locale lookup returns Welsh and selects only language", async () => {
|
||||
let capturedRequest;
|
||||
const mod = loadLocaleResolver({
|
||||
relayGetData: async (request) => {
|
||||
capturedRequest = request;
|
||||
return {
|
||||
data: {
|
||||
value: [
|
||||
{
|
||||
pinswg_preferredlanguage: 846040000,
|
||||
contactid: "must-not-be-returned",
|
||||
firstname: "Must not be returned"
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
const result = await mod.resolveCrmLocale(" Person@Example.com ");
|
||||
const selectClause = new URLSearchParams(
|
||||
capturedRequest.queryUrl.split("?")[1]
|
||||
).get("$select");
|
||||
|
||||
assert.strictEqual(result, "cy");
|
||||
assert.match(capturedRequest.queryUrl, /\$filter=emailaddress1 eq /);
|
||||
assert.match(capturedRequest.queryUrl, /statuscode eq 1/);
|
||||
assert.strictEqual(selectClause, "pinswg_preferredlanguage");
|
||||
assert.ok(result === "en" || result === "cy" || result === null);
|
||||
for (const field of [
|
||||
"contactid",
|
||||
"emailaddress1",
|
||||
"firstname",
|
||||
"lastname",
|
||||
"yomifullname"
|
||||
]) {
|
||||
assert.doesNotMatch(selectClause, new RegExp(field));
|
||||
assert.doesNotMatch(result, new RegExp(field));
|
||||
}
|
||||
});
|
||||
|
||||
test("pre-auth CRM locale lookup returns English for a non-Welsh value", async () => {
|
||||
const mod = loadLocaleResolver({
|
||||
relayGetData: async () => ({
|
||||
data: { value: [{ pinswg_preferredlanguage: 846040001 }] }
|
||||
})
|
||||
});
|
||||
|
||||
assert.strictEqual(await mod.resolveCrmLocale("person@example.com"), "en");
|
||||
});
|
||||
|
||||
test("pre-auth CRM locale lookup returns null for no contact", async () => {
|
||||
const mod = loadLocaleResolver({
|
||||
relayGetData: async () => ({ data: { value: [] } })
|
||||
});
|
||||
|
||||
assert.strictEqual(await mod.resolveCrmLocale("person@example.com"), null);
|
||||
});
|
||||
|
||||
test("pre-auth CRM locale lookup preserves first-contact duplicate semantics", async () => {
|
||||
const mod = loadLocaleResolver({
|
||||
relayGetData: async () => ({
|
||||
data: {
|
||||
value: [
|
||||
{ pinswg_preferredlanguage: 846040001 },
|
||||
{ pinswg_preferredlanguage: 846040000 }
|
||||
]
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
assert.strictEqual(await mod.resolveCrmLocale("person@example.com"), "en");
|
||||
});
|
||||
|
||||
test("pre-auth CRM locale lookup rejects malformed email without CRM access", async () => {
|
||||
let relayCalls = 0;
|
||||
const mod = loadLocaleResolver({
|
||||
relayGetData: async () => {
|
||||
relayCalls += 1;
|
||||
return { data: { value: [] } };
|
||||
}
|
||||
});
|
||||
|
||||
assert.strictEqual(await mod.resolveCrmLocale("not-an-email"), null);
|
||||
assert.strictEqual(relayCalls, 0);
|
||||
});
|
||||
|
||||
test("pre-auth CRM locale lookup fails closed without leaking CRM details", async () => {
|
||||
const mod = loadLocaleResolver({
|
||||
relayGetData: async () => {
|
||||
throw new Error("CRM secret response details");
|
||||
}
|
||||
});
|
||||
|
||||
assert.strictEqual(await mod.resolveCrmLocale("person@example.com"), null);
|
||||
});
|
||||
|
||||
test("pre-auth CRM locale lookup escapes OData apostrophes", async () => {
|
||||
let queryUrl;
|
||||
const mod = loadLocaleResolver({
|
||||
relayGetData: async (request) => {
|
||||
queryUrl = request.queryUrl;
|
||||
return { data: { value: [] } };
|
||||
}
|
||||
});
|
||||
|
||||
await mod.resolveCrmLocale("o'connor@example.com");
|
||||
|
||||
assert.match(queryUrl, /o''connor@example\.com/);
|
||||
});
|
||||
|
||||
test("public sign-in locale route preserves response without CRM lookup", async () => {
|
||||
const source = fs.readFileSync(
|
||||
path.join(rootDir, "pages/api/auth/resolve-locale.js"),
|
||||
"utf8"
|
||||
);
|
||||
const mod = loadModule("pages/api/auth/resolve-locale.js");
|
||||
const res = createRes();
|
||||
|
||||
await mod.default(
|
||||
{
|
||||
method: "POST",
|
||||
body: { email: "other@example.com", locale: "cy" },
|
||||
query: {},
|
||||
cookies: {}
|
||||
},
|
||||
res
|
||||
);
|
||||
|
||||
assert.strictEqual(res.state.statusCode, 200);
|
||||
assert.deepStrictEqual(normalize(res.state.jsonBody), { locale: "cy" });
|
||||
assert.doesNotMatch(source, /getPortalLogin|resolveCrmLocale|relayGetData/);
|
||||
});
|
||||
|
||||
test("both pre-auth callers no longer depend on getPortalLogin", () => {
|
||||
const nextAuthSource = fs.readFileSync(
|
||||
path.join(rootDir, "pages/api/auth/[...nextauth].js"),
|
||||
"utf8"
|
||||
);
|
||||
const routeSource = fs.readFileSync(
|
||||
path.join(rootDir, "pages/api/auth/resolve-locale.js"),
|
||||
"utf8"
|
||||
);
|
||||
|
||||
assert.doesNotMatch(nextAuthSource, /getPortalLogin/);
|
||||
assert.doesNotMatch(routeSource, /getPortalLogin/);
|
||||
assert.match(nextAuthSource, /resolveCrmLocale/);
|
||||
});
|
||||
|
||||
const run = async () => {
|
||||
let passed = 0;
|
||||
|
||||
for (const currentTest of tests) {
|
||||
await currentTest.fn();
|
||||
passed += 1;
|
||||
}
|
||||
|
||||
console.log(
|
||||
`Phase 22 pre-auth locale tests passed (${passed}/${tests.length}).`
|
||||
);
|
||||
};
|
||||
|
||||
if (require.main === module) {
|
||||
run().catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = run;
|
||||
@@ -0,0 +1,157 @@
|
||||
const assert = require("assert");
|
||||
const {
|
||||
loadModule,
|
||||
createRes,
|
||||
createNextConnectMock,
|
||||
respondSuccessMock,
|
||||
respondErrorMock
|
||||
} = require("../phase21/_shared.cjs");
|
||||
|
||||
const tests = [];
|
||||
const test = (name, fn) => tests.push({ name, fn });
|
||||
|
||||
const loadRepresentationList = ({ session = null, administrator = false } = {}) => {
|
||||
const calls = { list: [], download: [] };
|
||||
const mod = loadModule("pages/api/file/getrepsblob.js", {
|
||||
nextConnect: createNextConnectMock(),
|
||||
middleware: () => {},
|
||||
getServerSession: async () => session,
|
||||
authOptions: () => ({}),
|
||||
readAdminSessionCookie: () =>
|
||||
administrator ? "valid-admin-session" : null,
|
||||
validateAdminSession: () => administrator,
|
||||
hashAPIPath: () => "&hash=expected",
|
||||
respondError: respondErrorMock,
|
||||
respondSuccess: respondSuccessMock,
|
||||
consoleLogger: () => {},
|
||||
getRepsBlobs: async (...args) => {
|
||||
calls.list.push(args);
|
||||
return [{ path: "CASE/REP_rep.json" }];
|
||||
},
|
||||
downloadAllRepsFiles: async (...args) => {
|
||||
calls.download.push(args);
|
||||
return { value: [{ id: "rep-1" }] };
|
||||
}
|
||||
});
|
||||
|
||||
return { mod, calls };
|
||||
};
|
||||
|
||||
const representationListRequest = (query = {}) => ({
|
||||
query: {
|
||||
container: "organisation-container",
|
||||
hash: "expected",
|
||||
...query
|
||||
},
|
||||
headers: {}
|
||||
});
|
||||
|
||||
test("representation listing rejects a missing session before Azure access", async () => {
|
||||
const loaded = loadRepresentationList();
|
||||
const res = createRes();
|
||||
|
||||
await loaded.mod.default.handler(representationListRequest(), res);
|
||||
|
||||
assert.strictEqual(res.state.statusCode, 403);
|
||||
assert.strictEqual(res.state.jsonBody.error.code, "FORBIDDEN");
|
||||
assert.strictEqual(loaded.calls.list.length, 0);
|
||||
assert.strictEqual(loaded.calls.download.length, 0);
|
||||
});
|
||||
|
||||
test("representation listing rejects cross-user container access before Azure access", async () => {
|
||||
const loaded = loadRepresentationList({
|
||||
session: { user: { id: "different-container" } }
|
||||
});
|
||||
const res = createRes();
|
||||
|
||||
await loaded.mod.default.handler(representationListRequest(), res);
|
||||
|
||||
assert.strictEqual(res.state.statusCode, 403);
|
||||
assert.strictEqual(loaded.calls.list.length, 0);
|
||||
assert.strictEqual(loaded.calls.download.length, 0);
|
||||
});
|
||||
|
||||
test("representation listing preserves authorised organisation-container access", async () => {
|
||||
const loaded = loadRepresentationList({
|
||||
session: { user: { id: "organisation-container" } }
|
||||
});
|
||||
const res = createRes();
|
||||
|
||||
await loaded.mod.default.handler(representationListRequest(), res);
|
||||
|
||||
assert.strictEqual(res.state.statusCode, 200);
|
||||
assert.deepStrictEqual(loaded.calls.list, [["organisation-container"]]);
|
||||
assert.strictEqual(loaded.calls.download.length, 1);
|
||||
});
|
||||
|
||||
test("representation listing preserves existing administrative access", async () => {
|
||||
const loaded = loadRepresentationList({ administrator: true });
|
||||
const res = createRes();
|
||||
|
||||
await loaded.mod.default.handler(representationListRequest(), res);
|
||||
|
||||
assert.strictEqual(res.state.statusCode, 200);
|
||||
assert.strictEqual(loaded.calls.list.length, 1);
|
||||
});
|
||||
|
||||
test("representation listing rejects a missing identifier before authentication or Azure access", async () => {
|
||||
let sessionCalls = 0;
|
||||
const loaded = loadRepresentationList({
|
||||
session: { user: { id: "organisation-container" } }
|
||||
});
|
||||
loaded.mod = loadModule("pages/api/file/getrepsblob.js", {
|
||||
nextConnect: createNextConnectMock(),
|
||||
middleware: () => {},
|
||||
getServerSession: async () => {
|
||||
sessionCalls += 1;
|
||||
return { user: { id: "organisation-container" } };
|
||||
},
|
||||
authOptions: () => ({}),
|
||||
readAdminSessionCookie: () => null,
|
||||
validateAdminSession: () => false,
|
||||
hashAPIPath: () => "&hash=expected",
|
||||
respondError: respondErrorMock,
|
||||
respondSuccess: respondSuccessMock,
|
||||
consoleLogger: () => {},
|
||||
getRepsBlobs: async () => {
|
||||
loaded.calls.list.push([]);
|
||||
return [];
|
||||
},
|
||||
downloadAllRepsFiles: async () => {
|
||||
loaded.calls.download.push([]);
|
||||
return {};
|
||||
}
|
||||
});
|
||||
const res = createRes();
|
||||
|
||||
await loaded.mod.default.handler(
|
||||
representationListRequest({ container: "" }),
|
||||
res
|
||||
);
|
||||
|
||||
assert.strictEqual(res.state.statusCode, 400);
|
||||
assert.strictEqual(res.state.jsonBody.error.code, "MISSING_REQUIRED_QUERY");
|
||||
assert.strictEqual(sessionCalls, 0);
|
||||
assert.strictEqual(loaded.calls.list.length, 0);
|
||||
assert.strictEqual(loaded.calls.download.length, 0);
|
||||
});
|
||||
|
||||
const run = async () => {
|
||||
let passed = 0;
|
||||
for (const currentTest of tests) {
|
||||
await currentTest.fn();
|
||||
passed += 1;
|
||||
}
|
||||
console.log(
|
||||
`Representation listing ownership tests passed (${passed}/${tests.length}).`
|
||||
);
|
||||
};
|
||||
|
||||
module.exports = run;
|
||||
|
||||
if (require.main === module) {
|
||||
run().catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
@@ -65,6 +65,93 @@ test("document/getAwaitingSubmissionFromBlob logs and returns undefined on failu
|
||||
assert.strictEqual(logger.calls.length, 1);
|
||||
});
|
||||
|
||||
test("document/getRepsFromBlob forwards cookies only to trusted origin without redirects", async () => {
|
||||
const axios = createAxiosMock();
|
||||
const logger = createLoggerMock();
|
||||
|
||||
axios.getHandler = async () => ({
|
||||
data: { value: ["representation"] }
|
||||
});
|
||||
|
||||
const document = loadServiceModule("documentDirectService.js", {
|
||||
axios,
|
||||
BASE_URL: "http://example.local",
|
||||
consoleLogger: logger.consoleLogger,
|
||||
hashAPIPath: () => "&hash=abc123"
|
||||
});
|
||||
|
||||
const result = await document.getRepsFromBlob("container-1", {
|
||||
headers: {
|
||||
Cookie: "next-auth.session-token=test-session"
|
||||
}
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(normalize(result), {
|
||||
value: ["representation"]
|
||||
});
|
||||
|
||||
assert.strictEqual(axios.calls.length, 1);
|
||||
assert.strictEqual(
|
||||
axios.calls[0].url,
|
||||
"http://example.local/api/file/getrepsblob?container=container-1&hash=abc123"
|
||||
);
|
||||
assert.strictEqual(
|
||||
axios.calls[0].config.headers.Cookie,
|
||||
"next-auth.session-token=test-session"
|
||||
);
|
||||
assert.strictEqual(axios.calls[0].config.maxRedirects, 0);
|
||||
assert.strictEqual(logger.calls.length, 0);
|
||||
});
|
||||
|
||||
test("document/getRepsFromBlob rejects untrusted origin before HTTP request", async () => {
|
||||
const axios = createAxiosMock();
|
||||
const logger = createLoggerMock();
|
||||
|
||||
const document = loadServiceModule("documentDirectService.js", {
|
||||
axios,
|
||||
BASE_URL: "https://untrusted.example",
|
||||
consoleLogger: logger.consoleLogger,
|
||||
hashAPIPath: () => "&hash=abc123"
|
||||
});
|
||||
|
||||
await assert.rejects(
|
||||
document.getRepsFromBlob("container-1", {
|
||||
headers: {
|
||||
Cookie: "next-auth.session-token=test-session"
|
||||
}
|
||||
}),
|
||||
/Untrusted representation request destination/
|
||||
);
|
||||
|
||||
assert.strictEqual(axios.calls.length, 0);
|
||||
assert.strictEqual(logger.calls.length, 0);
|
||||
});
|
||||
|
||||
test("document/getRepsFromBlob preserves requests without forwarded cookies", async () => {
|
||||
const axios = createAxiosMock();
|
||||
const logger = createLoggerMock();
|
||||
|
||||
axios.getHandler = async () => ({
|
||||
data: { value: ["representation"] }
|
||||
});
|
||||
|
||||
const document = loadServiceModule("documentDirectService.js", {
|
||||
axios,
|
||||
BASE_URL: "http://example.local",
|
||||
consoleLogger: logger.consoleLogger,
|
||||
hashAPIPath: () => "&hash=abc123"
|
||||
});
|
||||
|
||||
const result = await document.getRepsFromBlob("container-1");
|
||||
|
||||
assert.deepStrictEqual(normalize(result), {
|
||||
value: ["representation"]
|
||||
});
|
||||
assert.strictEqual(axios.calls.length, 1);
|
||||
assert.strictEqual(axios.calls[0].config, undefined);
|
||||
assert.strictEqual(logger.calls.length, 0);
|
||||
});
|
||||
|
||||
test("portal/deleteWatchedCases uses signer hash and returns data", async () => {
|
||||
const axios = createAxiosMock();
|
||||
const logger = createLoggerMock();
|
||||
|
||||
@@ -140,7 +140,7 @@ test("createappealcompletemessage_api rejects invalid hash with 400", async () =
|
||||
createBlob: async () => {},
|
||||
getCaseBlob: async () => {},
|
||||
createCaseCompleteMessage: () => {},
|
||||
updateAccount: async () => {},
|
||||
updateCrmContact: async () => {},
|
||||
_: { isEmpty: (value) => !value },
|
||||
nextConnect,
|
||||
middleware: () => {}
|
||||
|
||||
@@ -89,8 +89,8 @@ const loadServiceModule = (fileName, injected = {}) => {
|
||||
return injected.axios(config).then((response) => response.data);
|
||||
};
|
||||
|
||||
const defaultGetFileJson = (url) => {
|
||||
return defaultGetJson(url);
|
||||
const defaultGetFileJson = (url, config) => {
|
||||
return defaultGetJson(url, config);
|
||||
};
|
||||
|
||||
const defaultBuildHashedQueryUrl = async (queryUrl) => {
|
||||
@@ -207,8 +207,14 @@ const loadServiceModule = (fileName, injected = {}) => {
|
||||
module: { exports: {} },
|
||||
exports: {},
|
||||
require,
|
||||
URL,
|
||||
URLSearchParams,
|
||||
encodeURIComponent,
|
||||
process: injected.process || {
|
||||
env: {
|
||||
NEXTAUTH_URL: "http://example.local"
|
||||
}
|
||||
},
|
||||
FormData: global.FormData,
|
||||
console: {
|
||||
log: () => {},
|
||||
|
||||
Reference in New Issue
Block a user