Merged PR 2315: Auth stabilistatiion and hardening

Related work items: #23020
This commit is contained in:
Robert Bond
2026-05-14 08:55:49 +00:00
parent d295a507ac
commit d0b2fd077a
41 changed files with 1462 additions and 418 deletions
+8
View File
@@ -10,6 +10,10 @@ const runRouteStateHelperTests = require("./route-state-helper.test.cjs");
const runBreadcrumbRouteMapsHelperTests = require("./breadcrumb-route-maps-helper.test.cjs");
const runBreadcrumbsRouteMapStructureTests = require("./breadcrumbs-route-map-structure.test.cjs");
const runRepresentationBuildRepsArrRulesTests = require("./representation-build-reps-arr-rules.test.cjs");
const runSessionClientTests = require("./session-client-behaviour.test.cjs");
const runNewAppealLoaderGuardTests = require("./newappeal-loader-guards.test.cjs");
const runMyPortalLoaderGuardTests = require("./myportal-loader-guards.test.cjs");
const runRepresentationLoaderGuardTests = require("./representation-loader-guards.test.cjs");
const run = async () => {
await runCoreTokenTests();
@@ -24,6 +28,10 @@ const run = async () => {
await runBreadcrumbRouteMapsHelperTests();
await runBreadcrumbsRouteMapStructureTests();
await runRepresentationBuildRepsArrRulesTests();
await runSessionClientTests();
await runNewAppealLoaderGuardTests();
await runMyPortalLoaderGuardTests();
await runRepresentationLoaderGuardTests();
console.log("Phase 22 combined suite passed.");
};
@@ -0,0 +1,122 @@
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 loadMyPortalLoader = (overrides = {}) => {
const filePath = path.join(
__dirname,
"..",
"..",
"lib",
"myportal",
"loadMyPortalAppealPage.js"
);
let source = fs.readFileSync(filePath, "utf8");
source = source.replace(/import[\s\S]*?from\s+"[^"]+";\n?/g, "");
source = source.replace(
/export\s+async\s+function\s+loadMyPortalAppealPage/,
"async function loadMyPortalAppealPage"
);
source += "\nmodule.exports = { loadMyPortalAppealPage };\n";
const context = {
module: { exports: {} },
exports: {},
getSession: async () => ({ user: { id: "u-1", email: "x@y.z" } }),
getAppealsTypesForNewAppeal: async () => ({}),
getMandatoryFields: async () => ({}),
getPickLists: async () => ({}),
getFilesFromBlob: async () => ({}),
getProgressFromBlob: async () => ({}),
getPersonalAccount: async () => ({}),
getAwaitingSubmissionFromBlob: async () => ({}),
consoleLogger: () => {},
getIP: () => {},
readFormXml: () => ({ xmlStr: "<xml/>" }),
requireQueryParams: () => ({ ok: true }),
...overrides
};
vm.runInNewContext(source, context, { filename: filePath });
return context.module.exports;
};
test("myportal loader redirects to signin when session is missing", async () => {
const mod = loadMyPortalLoader({ getSession: async () => null });
const result = await mod.loadMyPortalAppealPage({
query: { appealtypes: "s78", apt: "1", casereference: "CAS-1" },
req: { cookies: { pinsUser: "contact-1" } }
});
assert.strictEqual(result.redirect.destination, "/auth/signin");
});
test("myportal loader redirects to signin when pinsUser cookie is missing", async () => {
const mod = loadMyPortalLoader();
const result = await mod.loadMyPortalAppealPage({
query: { appealtypes: "s78", apt: "1", casereference: "CAS-1" },
req: { cookies: {} }
});
assert.strictEqual(result.redirect.destination, "/auth/signin");
});
test("myportal loader returns query-param redirect when required query is missing", async () => {
const mod = loadMyPortalLoader({
requireQueryParams: () => ({
ok: false,
redirect: { destination: "/myportal", permanent: false }
})
});
const result = await mod.loadMyPortalAppealPage({
query: {},
req: { cookies: { pinsUser: "contact-1" } }
});
assert.strictEqual(result.redirect.destination, "/myportal");
});
test("myportal loader redirects to myportal when dependency fetch fails", async () => {
const mod = loadMyPortalLoader({
getMandatoryFields: async () => {
throw new Error("mandatory fields unavailable");
}
});
const result = await mod.loadMyPortalAppealPage({
query: { appealtypes: "s78", apt: "1", casereference: "CAS-1" },
req: { cookies: { pinsUser: "contact-1" } }
});
assert.strictEqual(result.redirect.destination, "/myportal");
});
const run = async () => {
let passed = 0;
for (const currentTest of tests) {
await currentTest.fn();
passed += 1;
}
console.log(
`Phase 22 myportal-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,122 @@
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 loadNewAppealLoader = (overrides = {}) => {
const filePath = path.join(
__dirname,
"..",
"..",
"lib",
"newappeal",
"loadNewAppealPage.js"
);
let source = fs.readFileSync(filePath, "utf8");
source = source.replace(/import[\s\S]*?from\s+"[^"]+";\n?/g, "");
source = source.replace(
/export\s+async\s+function\s+loadNewAppealPage/,
"async function loadNewAppealPage"
);
source += "\nmodule.exports = { loadNewAppealPage };\n";
const context = {
module: { exports: {} },
exports: {},
getSession: async () => ({ user: { id: "u-1", email: "x@y.z" } }),
getAppealsTypesForNewAppeal: async () => ({}),
getMandatoryFields: async () => ({}),
getPickLists: async () => ({}),
getProgressFromBlob: async () => ({}),
getPersonalAccount: async () => ({}),
consoleLogger: () => {},
getIP: () => {},
readFormXml: () => ({ xmlStr: "<xml/>" }),
requireQueryParams: () => ({ ok: true }),
...overrides
};
vm.runInNewContext(source, context, { filename: filePath });
return context.module.exports;
};
test("newappeal loader redirects to signin when session is missing", async () => {
const mod = loadNewAppealLoader({
getSession: async () => null
});
const result = await mod.loadNewAppealPage({
query: { appealtypes: "s78", apt: "1", id: "CASE-1" },
req: { cookies: { pinsUser: "contact-1" } }
});
assert.strictEqual(result.redirect.destination, "/auth/signin");
});
test("newappeal loader redirects to signin when pinsUser cookie is missing", async () => {
const mod = loadNewAppealLoader();
const result = await mod.loadNewAppealPage({
query: { appealtypes: "s78", apt: "1", id: "CASE-1" },
req: { cookies: {} }
});
assert.strictEqual(result.redirect.destination, "/auth/signin");
});
test("newappeal loader returns query-param redirect when required query is missing", async () => {
const mod = loadNewAppealLoader({
requireQueryParams: () => ({
ok: false,
redirect: { destination: "/myportal", permanent: false }
})
});
const result = await mod.loadNewAppealPage({
query: {},
req: { cookies: { pinsUser: "contact-1" } }
});
assert.strictEqual(result.redirect.destination, "/myportal");
});
test("newappeal loader redirects to myportal when dependency fetch fails", async () => {
const mod = loadNewAppealLoader({
getMandatoryFields: async () => {
throw new Error("mandatory fields unavailable");
}
});
const result = await mod.loadNewAppealPage({
query: { appealtypes: "s78", apt: "1", id: "CASE-1" },
req: { cookies: { pinsUser: "contact-1" } }
});
assert.strictEqual(result.redirect.destination, "/myportal");
});
const run = async () => {
let passed = 0;
for (const currentTest of tests) {
await currentTest.fn();
passed += 1;
}
console.log(
`Phase 22 newappeal-loader-guards tests passed (${passed}/${tests.length}).`
);
};
module.exports = run;
if (require.main === module) {
run().catch((error) => {
console.error(error);
process.exit(1);
});
}
@@ -30,7 +30,8 @@ module.exports = {
const context = {
module: { exports: {} },
exports: {},
require
require,
Date
};
vm.runInNewContext(source, context, { filename: filePath });
@@ -67,8 +68,15 @@ const baseInput = (overrides = {}) => ({
...overrides
});
const normalizeForAssertion = (value) =>
JSON.parse(JSON.stringify(value ?? null));
const buildOptions = (overrides = {}) =>
buildRepsArrFromContext(buildRepresentationContext(baseInput(overrides)));
normalizeForAssertion(
buildRepsArrFromContext(
buildRepresentationContext(baseInput(overrides))
)
);
test("baseline truth-table: non-DNS non-SIPS across windows/capacities/ownership", () => {
const capacities = [
@@ -227,13 +235,15 @@ test("DNS rules: statement/LIR ownership behaviour and questionnaire exclusion",
};
const dnsOptions = (overrides = {}) =>
buildRepsArrFromContext(
buildRepresentationContext(
baseInput({
appealType: APPEAL_TYPES.DNS,
detailsObj: dnsDetails,
...overrides
})
normalizeForAssertion(
buildRepsArrFromContext(
buildRepresentationContext(
baseInput({
appealType: APPEAL_TYPES.DNS,
detailsObj: dnsDetails,
...overrides
})
)
)
);
@@ -339,59 +349,69 @@ test("deduplication and ordering are stable", () => {
test("invalid or missing dates suppress date-gated options but SIPS consultation persists", () => {
assert.deepStrictEqual(
buildRepsArrFromContext(
buildRepresentationContext(
baseInput({
detailsObj: {
pinswg_statementduedate: "2026-04-30T00:00:00.000Z",
pinswg_finalcommentsduedate: "2026-05-25T00:00:00.000Z"
}
})
normalizeForAssertion(
buildRepsArrFromContext(
buildRepresentationContext(
baseInput({
detailsObj: {
pinswg_statementduedate: "2026-04-30T00:00:00.000Z",
pinswg_finalcommentsduedate:
"2026-05-25T00:00:00.000Z"
}
})
)
)
),
[]
);
assert.deepStrictEqual(
buildRepsArrFromContext(
buildRepresentationContext(
baseInput({
detailsObj: {
pinswg_startdate: "2026-04-01T00:00:00.000Z",
pinswg_finalcommentsduedate: "2026-05-25T00:00:00.000Z"
}
})
normalizeForAssertion(
buildRepsArrFromContext(
buildRepresentationContext(
baseInput({
detailsObj: {
pinswg_startdate: "2026-04-01T00:00:00.000Z",
pinswg_finalcommentsduedate:
"2026-05-25T00:00:00.000Z"
}
})
)
)
),
[]
);
assert.deepStrictEqual(
buildRepsArrFromContext(
buildRepresentationContext(
baseInput({
detailsObj: {
pinswg_startdate: "2026-04-01T00:00:00.000Z",
pinswg_statementduedate: "2026-04-30T00:00:00.000Z"
},
involvementType: INVOLVEMENT_TYPES.LPA,
now: new Date("2026-05-10T10:00:00.000Z")
})
normalizeForAssertion(
buildRepsArrFromContext(
buildRepresentationContext(
baseInput({
detailsObj: {
pinswg_startdate: "2026-04-01T00:00:00.000Z",
pinswg_statementduedate: "2026-04-30T00:00:00.000Z"
},
involvementType: INVOLVEMENT_TYPES.LPA,
now: new Date("2026-05-10T10:00:00.000Z")
})
)
)
),
[]
);
assert.deepStrictEqual(
buildRepsArrFromContext(
buildRepresentationContext(
baseInput({
appealType: APPEAL_TYPES.SIPS,
detailsObj: {},
selectedCapacity: "agent",
isNRW: true,
now: new Date("2026-06-20T10:00:00.000Z")
})
normalizeForAssertion(
buildRepsArrFromContext(
buildRepresentationContext(
baseInput({
appealType: APPEAL_TYPES.SIPS,
detailsObj: {},
selectedCapacity: "agent",
isNRW: true,
now: new Date("2026-06-20T10:00:00.000Z")
})
)
)
),
["Consultation Response", "Local Impact Report", "Marine Impact Report"]
@@ -0,0 +1,136 @@
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 loadRepresentationLoaders = (overrides = {}) => {
const filePath = path.join(
__dirname,
"..",
"..",
"lib",
"representation",
"pageLoaders.js"
);
let source = fs.readFileSync(filePath, "utf8");
source = source.replace(/import[\s\S]*?from\s+"[^"]+";\n?/g, "");
source = source.replace(/export\s+const\s+/g, "const ");
source +=
"\nmodule.exports = { loadRepresentationBootstrap, loadRepresentationPage };\n";
const context = {
module: { exports: {} },
exports: {},
getSession: async () => ({
user: { id: "u-1", email: "test@example.com" }
}),
getPortalLogin: async () => ({ value: [{ contactid: "contact-1" }] }),
getPersonalAccount: async () => ({ emailaddress1: "test@example.com" }),
getRepsFromBlob: async () => ({ value: [] }),
getBasicSearch: async () => ({
value: [
{
incidentid: "i-1",
ticketnumber: "CAS-1",
title: "Case",
pinswg_appealcasetype: 1
}
]
}),
getSearchDetails: async () => [{ value: [{}] }],
getCase: async () => ({}),
getPortalModuleDetails: async () => ({}),
getFormCollectionByID: () => ({ LogicalCollectionName: "x" }),
setAccountDetails: () => ({}),
setContainerID: () => ({}),
setCurrentReference: () => ({}),
setCurrentView: () => ({}),
setFilesForRepresentations: () => ({}),
setRepresentationCapacity: () => ({}),
setMyRepresentations: () => ({}),
setMyRepresentationsDetails: () => ({}),
setSearchDetails: () => ({}),
setSearchResults: () => ({}),
setSearch: () => ({}),
getRepsFilesBlobs: async () => ({}),
consoleLogger: () => {},
...overrides
};
vm.runInNewContext(source, context, { filename: filePath });
return context.module.exports;
};
test("representation bootstrap redirects to signin when session is missing", async () => {
const mod = loadRepresentationLoaders({ getSession: async () => null });
const result = await mod.loadRepresentationBootstrap({
ctx: { query: {} }
});
assert.strictEqual(result.redirect.destination, "/auth/signin");
});
test("representation bootstrap redirects to signin when contact is missing", async () => {
const mod = loadRepresentationLoaders({
getPortalLogin: async () => ({ value: [] })
});
const result = await mod.loadRepresentationBootstrap({
ctx: { query: {} }
});
assert.strictEqual(result.redirect.destination, "/auth/signin");
});
test("representation page redirects to myportal when case query is missing", async () => {
const mod = loadRepresentationLoaders();
const store = { dispatch: () => {} };
const result = await mod.loadRepresentationPage({
store,
ctx: { query: {} }
});
assert.strictEqual(result.redirect.destination, "/myportal");
});
test("representation page redirects to myportal when state exists but created is missing", async () => {
const mod = loadRepresentationLoaders();
const store = { dispatch: () => {} };
const result = await mod.loadRepresentationPage({
store,
ctx: { query: { case: "CAS-1", state: "x" } }
});
assert.strictEqual(result.redirect.destination, "/myportal");
});
test("representation page redirects to myportal when existing representation search has no result", async () => {
const mod = loadRepresentationLoaders({
getBasicSearch: async () => ({ value: [] })
});
const store = { dispatch: () => {} };
const result = await mod.loadRepresentationPage({
store,
ctx: { query: { case: "CAS-1", state: "x", created: "rep-1" } }
});
assert.strictEqual(result.redirect.destination, "/myportal");
});
const run = async () => {
let passed = 0;
for (const currentTest of tests) {
await currentTest.fn();
passed += 1;
}
console.log(
`Phase 22 representation-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,134 @@
const fs = require("fs");
const path = require("path");
const vm = require("vm");
const assert = require("assert");
const rootDir = path.resolve(__dirname, "..", "..");
const loadSessionClientModule = (injected = {}) => {
const filePath = path.join(rootDir, "lib", "auth", "sessionClient.js");
let source = fs.readFileSync(filePath, "utf8");
source = source.replace(/import[\s\S]*?from\s+"[^"]+";\n?/g, "");
source = source.replace(/export const\s+/g, "const ");
source +=
"\nmodule.exports = { buildSignedOutCallbackUrl, clearSessionArtifacts, performPortalSignOut };\n";
const context = {
module: { exports: {} },
exports: {},
require,
window: {
localStorage: {
clear: () => {}
}
},
destroyCookie: () => {},
signOut: async () => ({}),
...injected
};
vm.runInNewContext(source, context, { filename: filePath });
return context.module.exports;
};
const tests = [];
const test = (name, fn) => tests.push({ name, fn });
test("auth/sessionClient callback URL helper returns EN/CY expected routes", async () => {
const mod = loadSessionClientModule();
assert.strictEqual(mod.buildSignedOutCallbackUrl("cy"), "/cy/allgofnodi");
assert.strictEqual(mod.buildSignedOutCallbackUrl("en"), "/logout");
assert.strictEqual(mod.buildSignedOutCallbackUrl(undefined), "/logout");
});
test("auth/sessionClient clearSessionArtifacts clears storage and known auth cookies", async () => {
const destroyed = [];
let clearCalls = 0;
const mod = loadSessionClientModule({
destroyCookie: (_ctx, name, opts) => {
destroyed.push({ name, opts });
},
window: {
localStorage: {
clear: () => {
clearCalls += 1;
}
}
}
});
mod.clearSessionArtifacts();
assert.strictEqual(clearCalls, 1);
assert.deepStrictEqual(
JSON.parse(JSON.stringify(destroyed.map((d) => d.name))),
[
"next-auth.csrf-token",
"next-auth.callback-url",
"__Secure-next-auth.callback-url",
"pedw_locale",
"pinsUser"
]
);
assert.strictEqual(
destroyed.every((d) => d.opts.path === "/"),
true
);
});
test("auth/sessionClient performPortalSignOut supports locale string argument", async () => {
const signOutCalls = [];
const mod = loadSessionClientModule({
signOut: async (args) => {
signOutCalls.push(args);
return { ok: true };
}
});
await mod.performPortalSignOut("cy");
assert.strictEqual(signOutCalls.length, 1);
assert.strictEqual(signOutCalls[0].callbackUrl, "/cy/allgofnodi");
});
test("auth/sessionClient performPortalSignOut supports callback override and injected signOut", async () => {
const signOutCalls = [];
const mod = loadSessionClientModule();
await mod.performPortalSignOut({
locale: "en",
callbackUrl: "/",
signOutFn: async (args) => {
signOutCalls.push(args);
return { ok: true };
}
});
assert.strictEqual(signOutCalls.length, 1);
assert.strictEqual(signOutCalls[0].callbackUrl, "/");
});
const run = async () => {
let passed = 0;
for (const currentTest of tests) {
await currentTest.fn();
passed += 1;
}
console.log(
`Phase 22 session-client tests passed (${passed}/${tests.length}).`
);
};
module.exports = run;
if (require.main === module) {
run().catch((error) => {
console.error(error);
process.exit(1);
});
}