TASK22057: phase17 closeout hash/input consistency hardening

This commit is contained in:
2026-03-13 18:43:42 +00:00
parent 36d35f9549
commit daa38d6459
7 changed files with 411 additions and 33 deletions
+19
View File
@@ -549,6 +549,25 @@
- Applied small view-all presentation cleanup and watched-case refresh filtering adjustment. - Applied small view-all presentation cleanup and watched-case refresh filtering adjustment.
- Added missing `myportal` namespace mapping in `i18n.js` for `/newappeal/[appealtypes]`. - Added missing `myportal` namespace mapping in `i18n.js` for `/newappeal/[appealtypes]`.
## Phase 17 closeout status (2026-03-13)
- Working branch created from `origin/SIPS-Development`:
- `TASK22057-phase17-hardening-closeout`
- Completed remaining closeout hardening slice for sensitive file handlers:
- `pages/api/file/generatepdf.js`
- `pages/api/file/generateappealpdf.js`
- `pages/api/file/createappealcompletemessageproxy_api.js`
- Applied consistency-only updates:
- standardized missing/invalid hash 400 negative paths in selected PDF handlers
- standardized required-input 400 guards where route contract requires it
- removed noisy direct logs from touched sensitive handlers
- preserved existing response shapes/signatures
- Added focused behavioural coverage:
- `tests/phase17/service-behaviour.test.cjs` (6/6 passing)
- includes missing/invalid hash negative-path checks and valid-input proxy happy-path contract check
- Broader consistency scan note:
- no additional broad hash/400 consistency gaps were identified in `pages/api/endpoint/**` in this pass.
## Likely next steps ## Likely next steps
1. Stabilize and simplify breadcrumb/back-link decision logic with focused regression checks. 1. Stabilize and simplify breadcrumb/back-link decision logic with focused regression checks.
+44
View File
@@ -1112,3 +1112,47 @@ Validation:
Follow-ups: Follow-ups:
- Keep delete calls consistently keyed on case reference across portal/view-all/top-three variants. - Keep delete calls consistently keyed on case reference across portal/view-all/top-three variants.
---
### CL-031: Phase 17 closeout — remaining sensitive file handler consistency hardening
date: 2026-03-13
author: Cline
scope: `pages/api/file/{generatepdf,generateappealpdf,createappealcompletemessageproxy_api}.js`, `tests/phase17/service-behaviour.test.cjs`, `memory-bank/*`
type: change
rationale: Complete the remaining small hardening closeout slice in this stream by standardizing hash/input negative-path behavior and reducing noisy logging in the last priority-sensitive file handlers.
impact: Consistent 400 behavior for missing/invalid hash and missing required inputs in selected handlers; preserved response shapes/signatures.
status: completed
Summary:
- Branch created from `origin/SIPS-Development`: `TASK22057-phase17-hardening-closeout`.
- Hardened:
- `generatepdf.js`
- `generateappealpdf.js`
- `createappealcompletemessageproxy_api.js`
- Added early 400 guards for missing/invalid hash and required params where applicable.
- Removed noisy direct logging in touched handlers.
- Added focused test pack `tests/phase17/service-behaviour.test.cjs`.
Validation:
- `node tests/phase6/service-parity.test.cjs` -> pass
- `node tests/phase6/service-behaviour.test.cjs` -> pass (8/8)
- `node tests/phase7/service-behaviour.test.cjs` -> pass (12/12)
- `node tests/phase8/service-behaviour.test.cjs` -> pass (5/5)
- `node tests/phase9/service-behaviour.test.cjs` -> pass (5/5)
- `node tests/phase10/service-behaviour.test.cjs` -> pass (5/5)
- `node tests/phase11/service-behaviour.test.cjs` -> pass (4/4)
- `node tests/phase12/service-behaviour.test.cjs` -> pass (4/4)
- `node tests/phase13/service-behaviour.test.cjs` -> pass (7/7)
- `node tests/phase14/service-behaviour.test.cjs` -> pass (9/9)
- `node tests/phase15/service-behaviour.test.cjs` -> pass (5/5)
- `node tests/phase16/service-behaviour.test.cjs` -> pass (4/4)
- `node tests/phase17/service-behaviour.test.cjs` -> pass (6/6)
- `npm run lint` -> warnings only (pre-existing `react-hooks/exhaustive-deps` warnings)
Follow-ups:
- If desired, run additional integrated HTTP/manual checks in an environment with full relay/storage dependencies for end-to-end happy-path confirmation beyond mocked behaviour tests.
@@ -577,6 +577,41 @@ Status key: `[x] done`, `[ ] pending`
- Revert commit `d32d7d0` to restore prior myportal/i18n state. - Revert commit `d32d7d0` to restore prior myportal/i18n state.
### Phase 17 closeout snapshot (2026-03-13)
Status key: `[x] done`, `[ ] pending`
1. `[x]` Create new branch from `origin/SIPS-Development` with required work item prefix
- branch: `TASK22057-phase17-hardening-closeout`
2. `[x]` Complete remaining consistency-only hardening targets in `pages/api/file/**`
- `pages/api/file/generatepdf.js`
- `pages/api/file/generateappealpdf.js`
- `pages/api/file/createappealcompletemessageproxy_api.js`
3. `[x]` Standardize negative-path behavior and logging discipline
- explicit early 400 guards for missing/invalid hash where applicable
- explicit early 400 guards for missing required params where applicable
- noisy direct logs removed from touched handlers
- response-shape/signature contracts preserved
4. `[x]` Add focused Phase 17 tests
- added `tests/phase17/service-behaviour.test.cjs`
- includes missing/invalid hash negative-path checks
- includes missing required-param checks
- includes valid-input happy-path check for proxy contract
5. `[x]` Execute required validation bundle
- phase6 parity + phase6phase17 behaviour tests -> pass
- lint -> warnings only (pre-existing)
6. `[x]` Consistency scan for remaining `pages/api/**`
- no additional broad hash/400 consistency gaps identified in `pages/api/endpoint/**` during this pass
### Phase 17 rollback notes
- Revert these files to rollback the full closeout slice:
- `pages/api/file/generatepdf.js`
- `pages/api/file/generateappealpdf.js`
- `pages/api/file/createappealcompletemessageproxy_api.js`
- `tests/phase17/service-behaviour.test.cjs`
- Re-run phase6phase17 baseline tests and lint after rollback to confirm parity.
## Safe execution mode for migration chunks (required) ## Safe execution mode for migration chunks (required)
To reduce terminal hangs during bulk migration work, run refactor chunks in **safe stepwise mode** instead of long chained commands. To reduce terminal hangs during bulk migration work, run refactor chunks in **safe stepwise mode** instead of long chained commands.
@@ -2,10 +2,6 @@ import { hashAPIPath } from "../../../actions/core/hash";
import { getToken } from "../../../actions/core/token"; import { getToken } from "../../../actions/core/token";
import { azureHeaders } from "../../../actions/core/headers"; import { azureHeaders } from "../../../actions/core/headers";
import { consoleLogger } from "../../../actions/core/logger"; import { consoleLogger } from "../../../actions/core/logger";
import {
getBlobs,
createCaseCompleteMessage
} from "../../../actions/azurestorage";
import axios from "axios"; import axios from "axios";
import nextConnect from "next-connect"; import nextConnect from "next-connect";
@@ -14,32 +10,32 @@ import middleware from "../middleware/middleware";
const ApiProxy = nextConnect(); const ApiProxy = nextConnect();
ApiProxy.use(middleware); ApiProxy.use(middleware);
const BASE_URL = process.env.API_ROOT || `http://localhost:${port}`;
const hasValue = (value) =>
typeof value === "string" && value.trim().length > 0;
ApiProxy.get(async (req, res) => { ApiProxy.get(async (req, res) => {
var containerName = req.query.container; var containerName = req.query.container;
var tempCaseRef = req.query.tempcaseref; var tempCaseRef = req.query.tempcaseref;
console.log("/////Create Case Message:\n", tempCaseRef, "\n//////////////"); if (!hasValue(containerName) || !hasValue(tempCaseRef)) {
return res.status(400).json();
//console.log(hashAPIPath(checkquerypath), checkHash); }
//console.log(hashAPIPath(checkquerypath) == "&hash=" + checkHash);
var token = await getToken(); var token = await getToken();
var queryUrl = var queryUrl =
"/api/file/createappealcompletemessageproxy_api?container=" + "/api/file/createappealcompletemessage_api?container=" +
containerID + containerName +
"&tempcaseref=" + "&tempcaseref=" +
caseReference; tempCaseRef;
var config = { return axios
method: "get", .get(
url: WEBAPI_URL + queryUrl + hashAPIPath(queryUrl) BASE_URL + queryUrl + hashAPIPath(queryUrl),
}; azureHeaders(token.access_token)
)
return axios(config)
.then((res) => {
return res.data;
})
.then(({ data }) => { .then(({ data }) => {
res.status(200).json(data); res.status(200).json(data);
}) })
+21 -7
View File
@@ -114,13 +114,32 @@ export default async function handler(req, res) {
var checkHash = req.query.hash; var checkHash = req.query.hash;
var appealType = req.query.appealType; var appealType = req.query.appealType;
let appealBodyObj = req.body; //JSON.parse(req.body); let appealBodyObj =
typeof req.body === "string" ? JSON.parse(req.body) : req.body;
var containerID = appealBodyObj.containerID; var containerID = appealBodyObj.containerID;
var casefolderID = appealBodyObj.casefolderID; var casefolderID = appealBodyObj.casefolderID;
var caseRef = appealBodyObj.caseRef; var caseRef = appealBodyObj.caseRef;
var filesList = appealBodyObj.filesList;
var checkquerypath = "/api/file/generateappealpdf"; var checkquerypath = "/api/file/generateappealpdf";
if (
typeof checkHash === "undefined" ||
checkHash.length === 0 ||
typeof appealType === "undefined" ||
String(appealType).length === 0 ||
typeof containerID === "undefined" ||
String(containerID).length === 0 ||
typeof casefolderID === "undefined" ||
String(casefolderID).length === 0
) {
return res.status(400).json();
}
checkquerypath = checkquerypath + "?appealType=" + appealType;
if (hashAPIPath(checkquerypath) != "&hash=" + checkHash) {
return res.status(400).json();
}
// Create Document Component // Create Document Component
const MyDocument = (values) => { const MyDocument = (values) => {
switch (values.docProps.pinswg_appealcasetype) { switch (values.docProps.pinswg_appealcasetype) {
@@ -200,11 +219,6 @@ export default async function handler(req, res) {
containerID, containerID,
blobProgress.pinswg_name || blobProgress.caseObj.ticketnumber blobProgress.pinswg_name || blobProgress.caseObj.ticketnumber
).then((data) => { ).then((data) => {
console.log(
"///////////////////////////////////\nfile created: " +
`/files/${pdfFileName}.pdf`,
"\n/////////////////////////"
);
return res.status(200).json({ return res.status(200).json({
status: "success", status: "success",
data: data, data: data,
+15 -6
View File
@@ -178,13 +178,27 @@ export default async function handler(req, res) {
var checkquerypath = "/api/file/generatepdf"; var checkquerypath = "/api/file/generatepdf";
if (shouldDownload) {
checkquerypath += "?download=true";
}
if (typeof checkHash === "undefined" || checkHash.length === 0) {
return res.status(400).json();
}
if (
hashAPIPath(checkquerypath) !=
(checkquerypath.indexOf("?") > -1 ? "&hash=" : "?hash=") + checkHash
) {
return res.status(400).json();
}
//console.log("-------", checkHash); //console.log("-------", checkHash);
//console.log(hashAPIPath(checkquerypath) == "?hash=" + checkHash); //console.log(hashAPIPath(checkquerypath) == "?hash=" + checkHash);
//console.log(casefolderID, caseRef); //console.log(casefolderID, caseRef);
// Create Document Component // Create Document Component
const MyDocument = (values) => { const MyDocument = (values) => {
console.log(values.docProps.locale);
switch (values.docProps.representationType) { switch (values.docProps.representationType) {
case "Questionnaire": case "Questionnaire":
switch (values.docProps.appealType) { switch (values.docProps.appealType) {
@@ -325,11 +339,6 @@ export default async function handler(req, res) {
reqBodyobj.repfile_name reqBodyobj.repfile_name
) )
.then((data) => { .then((data) => {
console.log(
"///////////////////////////////////\nrep pdf file created: " +
`${caseRef}/files/${reqBodyobj.repfile_name}.pdf`,
"\n/////////////////////////"
);
if (shouldDownload) { if (shouldDownload) {
const filename = `${reqBodyobj.repfile_name || "questionnaire"}.pdf`; const filename = `${reqBodyobj.repfile_name || "questionnaire"}.pdf`;
res.setHeader("Content-Type", "application/pdf"); res.setHeader("Content-Type", "application/pdf");
+261
View File
@@ -0,0 +1,261 @@
const fs = require("fs");
const path = require("path");
const vm = require("vm");
const assert = require("assert");
const rootDir = path.resolve(__dirname, "..", "..");
const loadModule = (relativePath, injected = {}) => {
const filePath = path.join(rootDir, relativePath);
let source = fs.readFileSync(filePath, "utf8");
source = source.replace(/import[\s\S]*?from\s+"[^"]+";\n?/g, "");
source = source.replace(
/ReactPDF\.renderToStream\(\s*<MyDocument[\s\S]*?\/>(?:\s*)\)/g,
"ReactPDF.renderToStream({})"
);
source = source.replace(
/export default async function\s+(\w+)\s*\(/,
"async function $1("
);
source = source.replace(/export const\s+/g, "const ");
source = source.replace(
/export default\s+(\w+);/g,
"module.exports.default = $1;"
);
source +=
'\nif (typeof ApiProxy !== "undefined" && !module.exports.default) module.exports.default = ApiProxy;\n';
source +=
'\nif (typeof handler !== "undefined" && !module.exports.default) module.exports.default = handler;\n';
const context = {
module: { exports: {} },
exports: {},
require,
process,
console: {
log: () => {},
info: () => {},
warn: () => {},
error: () => {}
},
port: 3000,
...injected
};
vm.runInNewContext(source, context, { filename: filePath });
return context.module.exports;
};
const createRes = () => {
const state = {
statusCode: null,
jsonBody: undefined
};
return {
state,
status(code) {
state.statusCode = code;
return this;
},
json(payload) {
state.jsonBody = payload;
return payload;
}
};
};
const tests = [];
const test = (name, fn) => tests.push({ name, fn });
const createNextConnectMock = () => {
const router = {
handler: null,
use: () => {},
get(fn) {
this.handler = fn;
},
post(fn) {
this.handler = fn;
}
};
return () => router;
};
test("generatepdf rejects missing hash with 400", async () => {
const createRepPDFBlobCalls = [];
const mod = loadModule("pages/api/file/generatepdf.js", {
hashAPIPath: () => "?hash=expected",
ReactPDF: {
renderToStream: async () => ({
on: (event, cb) => {
if (event === "data") cb(Buffer.from("pdf"));
if (event === "end") cb();
}
})
},
createRepPDFBlob: async (...args) => {
createRepPDFBlobCalls.push(args);
return { ok: true };
},
consoleLogger: () => {}
});
const req = { query: {}, body: { caseRef: "c1", repfile_name: "r1" } };
const res = createRes();
await mod.default(req, res);
assert.strictEqual(res.state.statusCode, 400);
assert.strictEqual(createRepPDFBlobCalls.length, 0);
});
test("generatepdf rejects invalid hash with 400", async () => {
const mod = loadModule("pages/api/file/generatepdf.js", {
hashAPIPath: () => "?hash=expected",
ReactPDF: {
renderToStream: async () => ({
on: (event, cb) => {
if (event === "data") cb(Buffer.from("pdf"));
if (event === "end") cb();
}
})
},
createRepPDFBlob: async () => ({ ok: true }),
consoleLogger: () => {}
});
const req = {
query: { hash: "wrong" },
body: { caseRef: "c1", repfile_name: "r1" }
};
const res = createRes();
await mod.default(req, res);
assert.strictEqual(res.state.statusCode, 400);
});
test("generateappealpdf rejects missing required input with 400", async () => {
const calls = [];
const mod = loadModule("pages/api/file/generateappealpdf.js", {
hashAPIPath: () => "&hash=expected",
getTempCaseBlob: async (...args) => {
calls.push(args);
return {};
},
getProgressBlobs: async () => ({ path: "p1" }),
downloadProgressFile: async () => ({ filesList: [] }),
getPickLists: async () => ({}),
ReactPDF: {
renderToStream: async () => ({
on: (event, cb) => {
if (event === "data") cb(Buffer.from("pdf"));
if (event === "end") cb();
}
})
},
createAppealPDFBlob: async () => ({ ok: true })
});
const req = { query: { hash: "expected" }, body: {} };
const res = createRes();
await mod.default(req, res);
assert.strictEqual(res.state.statusCode, 400);
assert.strictEqual(calls.length, 0);
});
test("generateappealpdf rejects invalid hash with 400", async () => {
const mod = loadModule("pages/api/file/generateappealpdf.js", {
hashAPIPath: () => "&hash=expected",
getTempCaseBlob: async () => ({}),
getProgressBlobs: async () => ({ path: "p1" }),
downloadProgressFile: async () => ({ filesList: [] }),
getPickLists: async () => ({}),
ReactPDF: {
renderToStream: async () => ({
on: (event, cb) => {
if (event === "data") cb(Buffer.from("pdf"));
if (event === "end") cb();
}
})
},
createAppealPDFBlob: async () => ({ ok: true })
});
const req = {
query: { hash: "wrong", appealType: "846040000" },
body: { containerID: "c1", casefolderID: "case-1", filesList: [] }
};
const res = createRes();
await mod.default(req, res);
assert.strictEqual(res.state.statusCode, 400);
});
test("createappealcompletemessageproxy_api rejects missing params with 400", async () => {
const mod = loadModule(
"pages/api/file/createappealcompletemessageproxy_api.js",
{
getToken: async () => ({ access_token: "t" }),
hashAPIPath: () => "&hash=expected",
azureHeaders: () => ({}),
axios: { get: async () => ({ data: { ok: true } }) },
consoleLogger: () => {},
nextConnect: createNextConnectMock(),
middleware: () => {}
}
);
const req = { query: { container: "c1" } };
const res = createRes();
await mod.default.handler(req, res);
assert.strictEqual(res.state.statusCode, 400);
});
test("createappealcompletemessageproxy_api valid input returns 200", async () => {
const mod = loadModule(
"pages/api/file/createappealcompletemessageproxy_api.js",
{
getToken: async () => ({ access_token: "t" }),
hashAPIPath: () => "&hash=expected",
azureHeaders: () => ({}),
axios: {
get: async () => ({ data: { status: "success" } })
},
consoleLogger: () => {},
nextConnect: createNextConnectMock(),
middleware: () => {}
}
);
const req = { query: { container: "c1", tempcaseref: "tmp-1" } };
const res = createRes();
await mod.default.handler(req, res);
assert.strictEqual(res.state.statusCode, 200);
assert.deepStrictEqual(JSON.parse(JSON.stringify(res.state.jsonBody)), {
status: "success"
});
});
const run = async () => {
let passed = 0;
for (const currentTest of tests) {
await currentTest.fn();
passed += 1;
}
console.log(
`Phase 17 behavioural tests passed (${passed}/${tests.length}).`
);
};
run().catch((error) => {
console.error(error);
process.exit(1);
});