Merge ITHC recovery into mitigation baseline
This commit is contained in:
@@ -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);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user