Contents
@@ -199,6 +235,14 @@ const StoragePage = (props) => {
export const getServerSideProps = wrapper.getServerSideProps(
(store) => async (ctx) => {
const { query, req, res } = ctx;
+ const adminSession = readAdminSessionCookie(req);
+
+ if (!validateAdminSession(adminSession)) {
+ return {
+ redirect: { destination: "/admin/login", permanent: false }
+ };
+ }
+
// IP restriction check
const ALLOWED_IPS = process.env.ALLOWED_IPS
? process.env.ALLOWED_IPS.split(",").map((ip) => ip.trim())
diff --git a/pages/admin/login.js b/pages/admin/login.js
new file mode 100644
index 00000000..9a9029ff
--- /dev/null
+++ b/pages/admin/login.js
@@ -0,0 +1,155 @@
+import Head from "next/head";
+import { useRouter } from "next/router";
+import { useState } from "react";
+import CookieBanner from "../../components/cookieBanner";
+import Footer from "../../components/footer";
+import Header from "../../components/header";
+import {
+ readAdminSessionCookie,
+ validateAdminSession
+} from "../../lib/admin/adminAuth";
+
+const AdminLoginPage = () => {
+ const router = useRouter();
+ const [passphrase, setPassphrase] = useState("");
+ const [error, setError] = useState("");
+ const [submitting, setSubmitting] = useState(false);
+
+ const handleSubmit = async (event) => {
+ event.preventDefault();
+ setError("");
+ setSubmitting(true);
+
+ try {
+ const response = await fetch("/api/admin/auth/login", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ credentials: "same-origin",
+ body: JSON.stringify({ passphrase })
+ });
+
+ if (!response.ok) {
+ setError("Sign in failed. Check the details and try again.");
+ return;
+ }
+
+ await router.replace("/admin");
+ } catch (_error) {
+ setError("Sign in failed. Check the details and try again.");
+ } finally {
+ setSubmitting(false);
+ }
+ };
+
+ return (
+
+
+
Administrative sign in
+
+
+
+
+
+
+
+
+ Administrative sign in
+
+
+ {error && (
+
+
+ There is a problem
+
+
+
+ )}
+
+
+
+
+
+
+
+
+ );
+};
+
+export const getServerSideProps = async ({ req }) => {
+ const adminSession = readAdminSessionCookie(req);
+
+ if (validateAdminSession(adminSession)) {
+ return {
+ redirect: { destination: "/admin", permanent: false }
+ };
+ }
+
+ return { props: {} };
+};
+
+export default AdminLoginPage;
\ No newline at end of file
diff --git a/pages/api/admin/auth/login.js b/pages/api/admin/auth/login.js
new file mode 100644
index 00000000..facba52c
--- /dev/null
+++ b/pages/api/admin/auth/login.js
@@ -0,0 +1,39 @@
+import {
+ createAdminSessionCookie,
+ hasTrustedSameOrigin,
+ issueAdminSession,
+ setAdminAuthNoStore,
+ validateAdminPassphrase
+} from "../../../../lib/admin/adminAuth";
+import { respondError, respondSuccess } from "../../middleware/apiResponse";
+
+const forbidden = (res) =>
+ respondError(res, {
+ status: 403,
+ code: "FORBIDDEN",
+ message: "Request not permitted"
+ });
+
+export default async function handler(req, res) {
+ setAdminAuthNoStore(res);
+ res.setHeader("Allow", "POST");
+
+ if (req.method !== "POST") {
+ return respondError(res, {
+ status: 405,
+ code: "METHOD_NOT_ALLOWED",
+ message: "Method not allowed"
+ });
+ }
+
+ if (!hasTrustedSameOrigin(req)) return forbidden(res);
+
+ const passphrase = req.body?.passphrase;
+ if (!validateAdminPassphrase(passphrase)) return forbidden(res);
+
+ const token = issueAdminSession();
+ if (!token) return forbidden(res);
+
+ res.setHeader("Set-Cookie", createAdminSessionCookie(token));
+ return respondSuccess(res, { authenticated: true });
+}
\ No newline at end of file
diff --git a/pages/api/admin/auth/logout.js b/pages/api/admin/auth/logout.js
new file mode 100644
index 00000000..5d276e11
--- /dev/null
+++ b/pages/api/admin/auth/logout.js
@@ -0,0 +1,30 @@
+import {
+ createClearedAdminSessionCookie,
+ hasTrustedSameOrigin,
+ setAdminAuthNoStore
+} from "../../../../lib/admin/adminAuth";
+import { respondError, respondSuccess } from "../../middleware/apiResponse";
+
+export default async function handler(req, res) {
+ setAdminAuthNoStore(res);
+ res.setHeader("Allow", "POST");
+
+ if (req.method !== "POST") {
+ return respondError(res, {
+ status: 405,
+ code: "METHOD_NOT_ALLOWED",
+ message: "Method not allowed"
+ });
+ }
+
+ if (!hasTrustedSameOrigin(req)) {
+ return respondError(res, {
+ status: 403,
+ code: "FORBIDDEN",
+ message: "Request not permitted"
+ });
+ }
+
+ res.setHeader("Set-Cookie", createClearedAdminSessionCookie());
+ return respondSuccess(res, { authenticated: false });
+}
\ No newline at end of file
diff --git a/pages/api/admin/auth/session.js b/pages/api/admin/auth/session.js
new file mode 100644
index 00000000..d80d231d
--- /dev/null
+++ b/pages/api/admin/auth/session.js
@@ -0,0 +1,24 @@
+import {
+ readAdminSessionCookie,
+ setAdminAuthNoStore,
+ validateAdminSession
+} from "../../../../lib/admin/adminAuth";
+import { respondError, respondSuccess } from "../../middleware/apiResponse";
+
+export default async function handler(req, res) {
+ setAdminAuthNoStore(res);
+ res.setHeader("Allow", "GET");
+
+ if (req.method !== "GET") {
+ return respondError(res, {
+ status: 405,
+ code: "METHOD_NOT_ALLOWED",
+ message: "Method not allowed"
+ });
+ }
+
+ const token = readAdminSessionCookie(req);
+ return respondSuccess(res, {
+ authenticated: validateAdminSession(token)
+ });
+}
\ No newline at end of file
diff --git a/pages/api/admin/createrepcompletemessage.js b/pages/api/admin/createrepcompletemessage.js
new file mode 100644
index 00000000..abc5a92b
--- /dev/null
+++ b/pages/api/admin/createrepcompletemessage.js
@@ -0,0 +1,82 @@
+import { createRepCompleteMessage } from "../../../actions/azurestorage";
+import { consoleLogger } from "../../../actions/core/logger";
+import {
+ hasTrustedSameOrigin,
+ readAdminSessionCookie,
+ setAdminAuthNoStore,
+ validateAdminSession
+} from "../../../lib/admin/adminAuth";
+import { respondError, respondSuccess } from "../middleware/apiResponse";
+
+const forbidden = (res) =>
+ respondError(res, {
+ status: 403,
+ code: "FORBIDDEN",
+ message: "Request not permitted"
+ });
+
+const isValidContainer = (value) =>
+ typeof value === "string" &&
+ value.length >= 3 &&
+ value.length <= 63 &&
+ /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
+
+const isValidPathSegment = (value) =>
+ typeof value === "string" &&
+ value.length > 0 &&
+ value.length <= 255 &&
+ value === value.trim() &&
+ value !== "." &&
+ value !== ".." &&
+ !/[\\/\u0000-\u001f\u007f]/.test(value);
+
+export default async function handler(req, res) {
+ setAdminAuthNoStore(res);
+ res.setHeader("Allow", "POST");
+
+ if (req.method !== "POST") {
+ return respondError(res, {
+ status: 405,
+ code: "METHOD_NOT_ALLOWED",
+ message: "Method not allowed"
+ });
+ }
+
+ const adminSession = readAdminSessionCookie(req);
+ if (!validateAdminSession(adminSession)) {
+ return forbidden(res);
+ }
+
+ if (!hasTrustedSameOrigin(req)) {
+ return forbidden(res);
+ }
+
+ const { container, tempcaseref, repid } = req.body ?? {};
+ if (
+ !isValidContainer(container) ||
+ !isValidPathSegment(tempcaseref) ||
+ !isValidPathSegment(repid)
+ ) {
+ return respondError(res, {
+ status: 400,
+ code: "INVALID_REQUEST",
+ message: "Invalid request"
+ });
+ }
+
+ try {
+ const data = await createRepCompleteMessage(
+ container,
+ tempcaseref,
+ repid
+ );
+ return respondSuccess(res, data);
+ } catch (error) {
+ consoleLogger(error);
+ return respondError(res, {
+ status: 400,
+ code: "CREATE_REP_COMPLETE_MESSAGE_FAILED",
+ message: "Failed to create representation complete message"
+ });
+ }
+}
\ No newline at end of file
diff --git a/pages/api/admin/deleteblobcase.js b/pages/api/admin/deleteblobcase.js
new file mode 100644
index 00000000..67f7a741
--- /dev/null
+++ b/pages/api/admin/deleteblobcase.js
@@ -0,0 +1,71 @@
+import { deleteBlobCase } from "../../../actions/azurestorage";
+import {
+ hasTrustedSameOrigin,
+ readAdminSessionCookie,
+ setAdminAuthNoStore,
+ validateAdminSession
+} from "../../../lib/admin/adminAuth";
+import { respondError, respondSuccess } from "../middleware/apiResponse";
+
+const forbidden = (res) =>
+ respondError(res, {
+ status: 403,
+ code: "FORBIDDEN",
+ message: "Request not permitted"
+ });
+
+const isValidContainer = (value) =>
+ typeof value === "string" &&
+ value.length >= 3 &&
+ value.length <= 63 &&
+ /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
+
+const isValidPathSegment = (value) =>
+ typeof value === "string" &&
+ value.length > 0 &&
+ value.length <= 255 &&
+ value === value.trim() &&
+ value !== "." &&
+ value !== ".." &&
+ !/[\\/\u0000-\u001f\u007f]/.test(value);
+
+export default async function handler(req, res) {
+ setAdminAuthNoStore(res);
+ res.setHeader("Allow", "POST");
+
+ if (req.method !== "POST") {
+ return respondError(res, {
+ status: 405,
+ code: "METHOD_NOT_ALLOWED",
+ message: "Method not allowed"
+ });
+ }
+
+ const adminSession = readAdminSessionCookie(req);
+ if (
+ !validateAdminSession(adminSession) ||
+ !hasTrustedSameOrigin(req)
+ ) {
+ return forbidden(res);
+ }
+
+ const { container, casefolderID } = req.body ?? {};
+ if (!isValidContainer(container) || !isValidPathSegment(casefolderID)) {
+ return respondError(res, {
+ status: 400,
+ code: "INVALID_REQUEST",
+ message: "Invalid request"
+ });
+ }
+
+ try {
+ const data = await deleteBlobCase(container, casefolderID);
+ return respondSuccess(res, { data });
+ } catch (_error) {
+ return respondError(res, {
+ status: 400,
+ code: "DELETE_BLOB_CASE_FAILED",
+ message: "Unable to delete blob case"
+ });
+ }
+}
\ No newline at end of file
diff --git a/pages/api/admin/deleteblobrep.js b/pages/api/admin/deleteblobrep.js
new file mode 100644
index 00000000..78c56cca
--- /dev/null
+++ b/pages/api/admin/deleteblobrep.js
@@ -0,0 +1,78 @@
+import { deleteBlobRep } from "../../../actions/azurestorage";
+import {
+ hasTrustedSameOrigin,
+ readAdminSessionCookie,
+ setAdminAuthNoStore,
+ validateAdminSession
+} from "../../../lib/admin/adminAuth";
+import { respondError, respondSuccess } from "../middleware/apiResponse";
+
+const forbidden = (res) =>
+ respondError(res, {
+ status: 403,
+ code: "FORBIDDEN",
+ message: "Request not permitted"
+ });
+
+const isValidContainer = (value) =>
+ typeof value === "string" &&
+ value.length >= 3 &&
+ value.length <= 63 &&
+ /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
+
+const isValidPathSegment = (value) =>
+ typeof value === "string" &&
+ value.length > 0 &&
+ value.length <= 255 &&
+ value === value.trim() &&
+ value !== "." &&
+ value !== ".." &&
+ !/[\\/\u0000-\u001f\u007f]/.test(value);
+
+export default async function handler(req, res) {
+ setAdminAuthNoStore(res);
+ res.setHeader("Allow", "POST");
+
+ if (req.method !== "POST") {
+ return respondError(res, {
+ status: 405,
+ code: "METHOD_NOT_ALLOWED",
+ message: "Method not allowed"
+ });
+ }
+
+ const adminSession = readAdminSessionCookie(req);
+ if (
+ !validateAdminSession(adminSession) ||
+ !hasTrustedSameOrigin(req)
+ ) {
+ return forbidden(res);
+ }
+
+ const { container, casefolderID, repfile } = req.body ?? {};
+ if (
+ !isValidContainer(container) ||
+ !isValidPathSegment(casefolderID) ||
+ !isValidPathSegment(repfile)
+ ) {
+ return respondError(res, {
+ status: 400,
+ code: "INVALID_REQUEST",
+ message: "Invalid request"
+ });
+ }
+
+ try {
+ const data = await deleteBlobRep(
+ container,
+ `${casefolderID}/${repfile}`
+ );
+ return respondSuccess(res, { data });
+ } catch (_error) {
+ return respondError(res, {
+ status: 400,
+ code: "DELETE_BLOB_REP_FAILED",
+ message: "Unable to delete blob representation"
+ });
+ }
+}
\ No newline at end of file
diff --git a/pages/api/admin/editRepJson.js b/pages/api/admin/editRepJson.js
new file mode 100644
index 00000000..4306cd81
--- /dev/null
+++ b/pages/api/admin/editRepJson.js
@@ -0,0 +1,126 @@
+import { DefaultAzureCredential } from "@azure/identity";
+import { BlobServiceClient } from "@azure/storage-blob";
+import { consoleLogger } from "../../../actions/core/logger";
+import {
+ hasTrustedSameOrigin,
+ readAdminSessionCookie,
+ setAdminAuthNoStore,
+ validateAdminSession
+} from "../../../lib/admin/adminAuth";
+import { respondError, respondSuccess } from "../middleware/apiResponse";
+
+const forbidden = (res) =>
+ respondError(res, {
+ status: 403,
+ code: "FORBIDDEN",
+ message: "Request not permitted"
+ });
+
+const isValidContainer = (value) =>
+ typeof value === "string" &&
+ value.length >= 3 &&
+ value.length <= 63 &&
+ /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
+
+const isValidBlobName = (value) =>
+ typeof value === "string" &&
+ value.length > 0 &&
+ value.length <= 1024 &&
+ value === value.trim() &&
+ !/[\\\u0000-\u001f\u007f]/.test(value) &&
+ value.split("/").every((segment) => segment && segment !== "." && segment !== "..");
+
+export default async function handler(req, res) {
+ setAdminAuthNoStore(res);
+ res.setHeader("Allow", "POST");
+
+ if (req.method !== "POST") {
+ return respondError(res, {
+ status: 405,
+ code: "METHOD_NOT_ALLOWED",
+ message: "Method not allowed"
+ });
+ }
+
+ const adminSession = readAdminSessionCookie(req);
+ if (
+ !validateAdminSession(adminSession) ||
+ !hasTrustedSameOrigin(req)
+ ) {
+ return forbidden(res);
+ }
+
+ const { container, blobName } = req.body ?? {};
+ if (!isValidContainer(container) || !isValidBlobName(blobName)) {
+ return respondError(res, {
+ status: 400,
+ code: "INVALID_REQUEST",
+ message: "Invalid request"
+ });
+ }
+
+ try {
+ const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME;
+ const creds = new DefaultAzureCredential();
+ const blobServiceClient = new BlobServiceClient(
+ `https://${accountName}.blob.core.windows.net`,
+ creds
+ );
+
+ const containerClient = blobServiceClient.getContainerClient(container);
+ const blockBlobClient = containerClient.getBlockBlobClient(blobName);
+
+ const downloadResponse = await blockBlobClient.download(0);
+ const downloaded = await streamToString(
+ downloadResponse.readableStreamBody
+ );
+ const json = JSON.parse(downloaded);
+
+ if ("repComplete" in json) {
+ delete json.repComplete;
+ }
+
+ const tags = {
+ containerid: json.containerID,
+ caseID: json.ticketnumber,
+ blobType: "Representation"
+ };
+
+ const updatedContent = JSON.stringify(json, null, 2);
+
+ await blockBlobClient.upload(
+ updatedContent,
+ Buffer.byteLength(updatedContent),
+ {
+ blobHTTPHeaders: { blobContentType: "application/json" }
+ }
+ );
+
+ await blockBlobClient.setTags(tags);
+ await blockBlobClient.setMetadata(tags);
+
+ return respondSuccess(res, {
+ message: "repComplete removed successfully"
+ });
+ } catch (error) {
+ consoleLogger(error);
+ return respondError(res, {
+ status: 500,
+ code: "EDIT_REP_JSON_FAILED",
+ message: "Failed to edit rep.json"
+ });
+ }
+}
+
+async function streamToString(readableStream) {
+ return new Promise((resolve, reject) => {
+ const chunks = [];
+ readableStream.on("data", (data) => {
+ chunks.push(data.toString());
+ });
+ readableStream.on("end", () => {
+ resolve(chunks.join(""));
+ });
+ readableStream.on("error", reject);
+ });
+}
\ No newline at end of file
diff --git a/pages/api/admin/getrepsblobproxy.js b/pages/api/admin/getrepsblobproxy.js
new file mode 100644
index 00000000..a8b1ba65
--- /dev/null
+++ b/pages/api/admin/getrepsblobproxy.js
@@ -0,0 +1,97 @@
+import { BASE_URL } from "../../../actions/core/env";
+import { getToken } from "../../../actions/core/token";
+import { azureHeaders } from "../../../actions/core/headers";
+import { consoleLogger } from "../../../actions/core/logger";
+import { hashAPIPath } from "../../../actions/core/hash";
+import axios from "axios";
+import {
+ ADMIN_SESSION_COOKIE,
+ hasTrustedSameOrigin,
+ readAdminSessionCookie,
+ setAdminAuthNoStore,
+ validateAdminSession
+} from "../../../lib/admin/adminAuth";
+import { respondError, respondSuccess } from "../middleware/apiResponse";
+
+const isTrustedInternalDestination = () => {
+ try {
+ return (
+ new URL(BASE_URL).origin ===
+ new URL(process.env.NEXTAUTH_URL).origin
+ );
+ } catch {
+ return false;
+ }
+};
+
+const forbidden = (res) =>
+ respondError(res, {
+ status: 403,
+ code: "FORBIDDEN",
+ message: "Request not permitted"
+ });
+
+const isValidContainer = (value) =>
+ typeof value === "string" &&
+ value.length >= 3 &&
+ value.length <= 63 &&
+ /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
+
+export default async function handler(req, res) {
+ setAdminAuthNoStore(res);
+ res.setHeader("Allow", "POST");
+
+ if (req.method !== "POST") {
+ return respondError(res, {
+ status: 405,
+ code: "METHOD_NOT_ALLOWED",
+ message: "Method not allowed"
+ });
+ }
+
+ const adminSession = readAdminSessionCookie(req);
+ if (!validateAdminSession(adminSession) || !hasTrustedSameOrigin(req)) {
+ return forbidden(res);
+ }
+
+ const { container } = req.body ?? {};
+ if (!isValidContainer(container)) {
+ return respondError(res, {
+ status: 400,
+ code: "INVALID_REQUEST",
+ message: "Invalid request"
+ });
+ }
+
+ if (!isTrustedInternalDestination()) {
+ return forbidden(res);
+ }
+
+ const token = await getToken();
+ const queryUrl =
+ "/api/file/getrepsblob?container=" + encodeURIComponent(container);
+
+ try {
+ const config = azureHeaders(token.access_token);
+
+ const { data } = await axios.get(
+ BASE_URL + queryUrl + hashAPIPath(queryUrl),
+ {
+ ...config,
+ headers: {
+ ...config.headers,
+ Cookie: `${ADMIN_SESSION_COOKIE}=${encodeURIComponent(adminSession)}`
+ },
+ maxRedirects: 0
+ }
+ );
+ return respondSuccess(res, data);
+ } catch (error) {
+ consoleLogger(error);
+ return respondError(res, {
+ status: 400,
+ code: "GET_REPS_BLOB_PROXY_FAILED",
+ message: "Failed to fetch representation blobs"
+ });
+ }
+}
diff --git a/pages/api/auth/[...nextauth].js b/pages/api/auth/[...nextauth].js
index 96c5f8b2..ac88da54 100644
--- a/pages/api/auth/[...nextauth].js
+++ b/pages/api/auth/[...nextauth].js
@@ -13,7 +13,7 @@
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { PrismaClient } from "@prisma/client";
import NextAuth from "next-auth";
-import EmailProvider from "next-auth/providers/email";
+import EmailProvider from "../../../lib/auth/email-provider";
import { consoleLogger, redactSensitive } from "../../../actions/core/logger";
import { getPortalLogin } from "../../../actions/services/accountService";
@@ -199,7 +199,7 @@ const resolveRequestLocale = (req) => {
return resolved;
};
-const authOptions = (req, res) => {
+export const authOptions = (req, res) => {
const requestLocale = resolveRequestLocale(req);
const verificationTokenCompletion = createVerificationTokenCompletion();
diff --git a/pages/api/doc.ts b/pages/api/doc.ts
deleted file mode 100644
index 9054f053..00000000
--- a/pages/api/doc.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { withSwagger } from 'next-swagger-doc';
-
-const swaggerHandler = withSwagger({
- definition: {
- openapi: '3.0.0',
- info: {
- title: 'PEDW Example',
- version: '0.1.0',
- },
- },
- schemaFolders: ['models'],
-});
-export default swaggerHandler();
\ No newline at end of file
diff --git a/pages/api/endpoint/createcase_api.js b/pages/api/endpoint/createcase_api.js
deleted file mode 100644
index 469b9e3c..00000000
--- a/pages/api/endpoint/createcase_api.js
+++ /dev/null
@@ -1,150 +0,0 @@
-/**
- * @swagger
- * /api/endpoint/createcase_api:
- * post:
- * tags: [Case]
- * description: Create case
- * summary: Phase 2
- * parameters:
- * - name: body
- * in: requestbody
- * required: true
- * example: {}
- * schema:
- * type: object
- * - name: contactid
- * in: query
- * required: true
- * example: pinswg_planningappeals78s
- * schema:
- * type: string
- * - name: appealTypeId
- * in: query
- * required: true
- * example: pinswg_planningappeals78id
- * schema:
- * type: string
- * - name: containername
- * in: query
- * required: true
- * example: pinswg_planningappeals78id
- * schema:
- * type: string
- * - name: lpaID
- * in: query
- * required: true
- * example: pinswg_planningappeals78id
- * schema:
- * type: string
- * responses:
- * 200:
- * description: Success
- */
-
-import axios from "axios";
-import { consoleLogger } from "../../../actions/core/logger";
-import { getToken } from "../../../actions/core/token";
-import { getCaseBlob } from "../../../actions/azurestorage";
-import { hashAPIPath } from "../../../actions/core/hash";
-import { respondError, respondSuccess } from "../middleware/apiResponse";
-
-const WEBAPI_URL =
- process.env.RELAY_ROOT ||
- "https://dev-pedw-ns.servicebus.windows.net/dev-pedw-hc/";
-
-export default async function ApiProxy(req, res) {
- const createCaseBody = req.body;
- const contactid = req.query.contactid;
- const appealTypeId = req.query.appealTypeId;
- const containerName = req.query.containername;
- const lpaID = req.query.lpaID;
- const queryUrl = "incidents";
-
- if (!createCaseBody || typeof createCaseBody !== "object") {
- return respondError(res, {
- status: 400,
- code: "CASE_PAYLOAD_REQUIRED",
- message: "Case payload is required"
- });
- }
- if (typeof contactid !== "string" || contactid.trim().length === 0) {
- return respondError(res, {
- status: 400,
- code: "CONTACT_ID_REQUIRED",
- message: "contactid is required"
- });
- }
- if (typeof appealTypeId !== "string" || appealTypeId.trim().length === 0) {
- return respondError(res, {
- status: 400,
- code: "APPEAL_TYPE_ID_REQUIRED",
- message: "appealTypeId is required"
- });
- }
- if (
- typeof containerName !== "string" ||
- containerName.trim().length === 0
- ) {
- return respondError(res, {
- status: 400,
- code: "CONTAINER_NAME_REQUIRED",
- message: "containername is required"
- });
- }
- if (typeof lpaID !== "string" || lpaID.trim().length === 0) {
- return respondError(res, {
- status: 400,
- code: "LPA_ID_REQUIRED",
- message: "lpaID is required"
- });
- }
-
- try {
- const token = await getToken();
-
- const data = {
- "title": "insertion test case",
- "caseorigincode": 3,
- "servicestage": 1,
- "customerid_contact@odata.bind": "/contacts(" + contactid + ")",
- "pinswg_appealcasetype": appealTypeId,
- "pinswg_AssociatedLPA@odata.bind": "/accounts(" + lpaID + ")"
- };
- const newData = Object.assign(data, createCaseBody);
-
- delete newData.lpaTypes;
- delete newData.appealTypes;
-
- console.log("/////Create Case:\n", newData, "\n//////////////");
-
- const config = {
- method: "post",
- url: WEBAPI_URL + queryUrl + hashAPIPath(queryUrl),
- headers: {
- "OData-MaxVersion": "4.0",
- "OData-Version": "4.0",
- "Accept": "application/json",
- "Prefer": 'odata.include-annotations="*",return=representation',
- "Authorization": "Bearer " + token.access_token,
- "Content-Type": "application/json"
- },
- data: JSON.stringify(newData)
- };
-
- const { data: responseData } = await axios(config);
- await getCaseBlob(
- containerName,
- responseData.ticketnumber,
- createCaseBody
- );
-
- return respondSuccess(res, responseData);
- } catch (error) {
- consoleLogger(error);
- return respondError(res, {
- status: 400,
- code: "CASE_CREATE_FAILED",
- message: "Failed to create case"
- });
- }
-}
diff --git a/pages/api/endpoint/createcrmtask_api.js b/pages/api/endpoint/createcrmtask_api.js
index af2f66b1..964a3247 100644
--- a/pages/api/endpoint/createcrmtask_api.js
+++ b/pages/api/endpoint/createcrmtask_api.js
@@ -1,46 +1,3 @@
-/**
- * @swagger
- * /api/endpoint/createcase_api:
- * post:
- * tags: [Case]
- * description: Create case
- * summary: Phase 2
- * parameters:
- * - name: body
- * in: requestbody
- * required: true
- * example: {}
- * schema:
- * type: object
- * - name: contactid
- * in: query
- * required: true
- * example: pinswg_planningappeals78s
- * schema:
- * type: string
- * - name: appealTypeId
- * in: query
- * required: true
- * example: pinswg_planningappeals78id
- * schema:
- * type: string
- * - name: containername
- * in: query
- * required: true
- * example: pinswg_planningappeals78id
- * schema:
- * type: string
- * - name: lpaID
- * in: query
- * required: true
- * example: pinswg_planningappeals78id
- * schema:
- * type: string
- * responses:
- * 200:
- * description: Success
- */
-
import axios from "axios";
import { isNonEmptyString, sanitizeString } from "../../../actions/core/guards";
import { consoleLogger } from "../../../actions/core/logger";
diff --git a/pages/api/endpoint/createwatchedcases_api.js b/pages/api/endpoint/createwatchedcases_api.js
index 0c67b6a2..aad9fff9 100644
--- a/pages/api/endpoint/createwatchedcases_api.js
+++ b/pages/api/endpoint/createwatchedcases_api.js
@@ -16,38 +16,73 @@ import { getToken } from "../../../actions/core/token";
import { hashAPIPath } from "../../../actions/core/hash";
import { respondError, respondSuccess } from "../middleware/apiResponse";
import { relayGetData } from "../middleware/relayForwarding";
+import { getServerSession } from "next-auth/next";
+import { authOptions } from "../auth/[...nextauth]";
+import { azureHeaders } from "../../../actions/core/headers";
+import { escapeODataString } from "../../../actions/core/guards";
const WEBAPI_URL =
process.env.RELAY_ROOT ||
"https://dev-pedw-ns.servicebus.windows.net/dev-pedw-hc/";
+const GUID_PATTERN =
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
const recordExists = async (incidentId, contactId, accessToken) => {
const filter = `$filter=pinswg_WatchedCase/incidentid eq ${incidentId} and pinswg_Contact/contactid eq ${contactId}`;
- const queryUrl = `pinswg_watchlists?${filter}`;
+ const queryUrl =
+ `pinswg_watchlists?${filter}` +
+ "&$select=pinswg_watchlistid,_pinswg_contact_value,_pinswg_watchedcase_value,pinswg_representationsubmitted";
- try {
- const response = await relayGetData({
- queryUrl,
- accessToken,
- requestOptionsBuilder: (token) => ({
- headers: {
- Authorization: "Bearer " + token,
- Accept: "application/json"
- }
- })
- });
+ const response = await relayGetData({
+ queryUrl,
+ accessToken,
+ requestOptionsBuilder: (token) => ({
+ headers: {
+ Authorization: "Bearer " + token,
+ Accept: "application/json"
+ }
+ })
+ });
- if (response.data.value && response.data.value.length > 0) {
- return response.data.value[0]; // return the existing record
- }
+ const records = response?.data?.value;
- return null;
- } catch (err) {
- throw err;
+ if (!Array.isArray(records)) {
+ return {
+ status: "invalid",
+ records: []
+ };
}
+
+ return {
+ status: "found",
+ records
+ };
};
export default async function ApiProxy(req, res) {
+ if (req.method !== "POST") {
+ return respondError(res, {
+ status: 405,
+ code: "METHOD_NOT_ALLOWED",
+ message: "Only POST is supported"
+ });
+ }
+
+ const session = await getServerSession(req, res, authOptions(req, res));
+ const authenticatedEmail = session?.user?.email;
+
+ if (
+ typeof authenticatedEmail !== "string" ||
+ authenticatedEmail.trim().length === 0
+ ) {
+ return respondError(res, {
+ status: 401,
+ code: "UNAUTHENTICATED",
+ message: "Authentication required"
+ });
+ }
+
const data = req.body;
const watchedCaseBind = data?.["pinswg_WatchedCase@odata.bind"];
const contactBind = data?.["pinswg_Contact@odata.bind"];
@@ -66,8 +101,13 @@ export default async function ApiProxy(req, res) {
});
}
- const watchedCaseMatch = watchedCaseBind.match(/\(([^)]+)\)/);
- const contactMatch = contactBind.match(/\(([^)]+)\)/);
+ const watchedCaseMatch = watchedCaseBind.match(
+ /^\/incidents\(([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\)$/i
+ );
+
+ const contactMatch = contactBind.match(
+ /^\/contacts\(([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\)$/i
+ );
if (!watchedCaseMatch || !contactMatch) {
return respondError(res, {
@@ -79,26 +119,118 @@ export default async function ApiProxy(req, res) {
try {
const token = await getToken();
-
const incidentId = watchedCaseMatch[1];
const contactId = contactMatch[1];
- const existingRecord = await recordExists(
+ const escapedEmail = escapeODataString(authenticatedEmail);
+
+ const contactQueryUrl =
+ "contacts?$filter=emailaddress1 eq '" +
+ escapedEmail +
+ "' and statuscode eq 1&$select=contactid";
+
+ const contactResponse = await relayGetData({
+ queryUrl: contactQueryUrl,
+ accessToken: token.access_token,
+ requestOptionsBuilder: (accessToken) => azureHeaders(accessToken)
+ });
+
+ const contacts = contactResponse?.data?.value;
+
+ if (
+ !Array.isArray(contacts) ||
+ contacts.length !== 1 ||
+ typeof contacts[0]?.contactid !== "string" ||
+ !GUID_PATTERN.test(contacts[0].contactid.trim())
+ ) {
+ return respondError(res, {
+ status: 403,
+ code: "CONTACT_IDENTITY_NOT_RESOLVED",
+ message: "Request not permitted"
+ });
+ }
+
+ if (
+ contactId.trim().toLowerCase() !==
+ contacts[0].contactid.trim().toLowerCase()
+ ) {
+ return respondError(res, {
+ status: 403,
+ code: "CONTACT_OWNERSHIP_MISMATCH",
+ message: "Request not permitted"
+ });
+ }
+
+ const lookup = await recordExists(
incidentId,
contactId,
token.access_token
);
- let method, queryUrl;
-
- if (existingRecord) {
- method = "patch";
- queryUrl = `pinswg_watchlists(${existingRecord.pinswg_watchlistid})`;
- } else {
- method = "post";
- queryUrl = "pinswg_watchlists";
+ if (lookup.status === "invalid") {
+ return respondError(res, {
+ status: 500,
+ code: "WATCHLIST_LOOKUP_FAILED",
+ message: "Unable to verify existing watched-case records"
+ });
}
+ const records = lookup.records;
+
+ const isRepresentationSubmission =
+ data?.pinswg_representationsubmitted != null;
+
+ // Validate every returned record before considering it for an update.
+ const validRecords = records.every((record) => {
+ const recordID = record?.pinswg_watchlistid;
+ const recordContactID = record?._pinswg_contact_value;
+ const recordCaseID = record?._pinswg_watchedcase_value;
+
+ return (
+ typeof recordID === "string" &&
+ GUID_PATTERN.test(recordID) &&
+ typeof recordContactID === "string" &&
+ GUID_PATTERN.test(recordContactID) &&
+ typeof recordCaseID === "string" &&
+ GUID_PATTERN.test(recordCaseID) &&
+ recordContactID.toLowerCase() === contactId.toLowerCase() &&
+ recordCaseID.toLowerCase() === incidentId.toLowerCase()
+ );
+ });
+
+ if (!validRecords) {
+ return respondError(res, {
+ status: 403,
+ code: "WATCHLIST_OWNERSHIP_MISMATCH",
+ message: "Request not permitted"
+ });
+ }
+
+ const watchingOnlyRecords = records.filter(
+ (record) => record.pinswg_representationsubmitted == null
+ );
+
+ let existingRecord;
+
+ if (isRepresentationSubmission) {
+ // Reuse a watching-only record for the first representation.
+ // Never overwrite an earlier representation submission.
+ existingRecord =
+ watchingOnlyRecords.length === 1
+ ? watchingOnlyRecords[0]
+ : null;
+ } else {
+ // Watching or subscribing: prefer a watching-only record.
+ // Otherwise reuse an existing representation-associated record.
+ existingRecord = watchingOnlyRecords[0] ?? records[0] ?? null;
+ }
+
+ const method = existingRecord ? "patch" : "post";
+
+ const queryUrl = existingRecord
+ ? `pinswg_watchlists(${existingRecord.pinswg_watchlistid})`
+ : "pinswg_watchlists";
+
const config = {
method: method,
url: WEBAPI_URL + queryUrl + hashAPIPath(queryUrl),
@@ -110,7 +242,10 @@ export default async function ApiProxy(req, res) {
Authorization: "Bearer " + token.access_token,
"Content-Type": "application/json"
},
- data: JSON.stringify(data)
+ data: JSON.stringify({
+ ...data,
+ "pinswg_Contact@odata.bind": `/contacts(${contacts[0].contactid.trim()})`
+ })
};
const result = await axios(config);
diff --git a/pages/api/endpoint/deletemyrepresentations_api.js b/pages/api/endpoint/deletemyrepresentations_api.js
deleted file mode 100644
index 62e02b46..00000000
--- a/pages/api/endpoint/deletemyrepresentations_api.js
+++ /dev/null
@@ -1,66 +0,0 @@
-/**
- * @swagger
- * /api/endpoint/deleteamyrepresentations_api:
- * delete:
- * tags: [Portal,Representations]
- * summary: Phase 2
- * description: Delete my representations
- * responses:
- * 200:
- * description: Success
- */
-
-import axios from "axios";
-import { consoleLogger } from "../../../actions/core/logger";
-import { getToken } from "../../../actions/core/token";
-
-import { hashAPIPath } from "../../../actions/core/hash";
-import { respondError, respondSuccess } from "../middleware/apiResponse";
-
-const WEBAPI_URL =
- process.env.RELAY_ROOT ||
- "https://dev-pedw-ns.servicebus.windows.net/dev-pedw-hc/";
-
-export default async function ApiProxy(req, res) {
- const myRepresentationsID = req.query.myRepresentationsID;
-
- if (
- typeof myRepresentationsID !== "string" ||
- myRepresentationsID.trim().length === 0
- ) {
- return respondError(res, {
- status: 400,
- code: "MY_REPRESENTATION_ID_REQUIRED",
- message: "myRepresentationsID is required"
- });
- }
-
- try {
- const token = await getToken();
- const queryUrl =
- "pinswg_representationses(" + myRepresentationsID + ")";
-
- const config = {
- method: "delete",
- url: WEBAPI_URL + queryUrl + hashAPIPath(queryUrl),
- headers: {
- "OData-MaxVersion": "4.0",
- "OData-Version": "4.0",
- Accept: "application/json",
- Prefer: 'odata.include-annotations="*",return=representation',
- Authorization: "Bearer " + token.access_token,
- "Content-Type": "application/json"
- }
- };
-
- const { data } = await axios(config);
- return respondSuccess(res, data);
- } catch (error) {
- consoleLogger(error);
- return respondError(res, {
- status: 400,
- code: "MY_REPRESENTATION_DELETE_FAILED",
- message: "Failed to delete representation"
- });
- }
-}
diff --git a/pages/api/endpoint/deletewatchedcases_api.js b/pages/api/endpoint/deletewatchedcases_api.js
index 5c59ecff..af4aad28 100644
--- a/pages/api/endpoint/deletewatchedcases_api.js
+++ b/pages/api/endpoint/deletewatchedcases_api.js
@@ -11,32 +11,143 @@
*/
import axios from "axios";
+import { getServerSession } from "next-auth/next";
+import { azureHeaders } from "../../../actions/core/headers";
+import { escapeODataString } from "../../../actions/core/guards";
import { consoleLogger } from "../../../actions/core/logger";
import { getToken } from "../../../actions/core/token";
import { hashAPIPath } from "../../../actions/core/hash";
+import { authOptions } from "../auth/[...nextauth]";
import { respondError, respondSuccess } from "../middleware/apiResponse";
+import { relayGetData } from "../middleware/relayForwarding";
const WEBAPI_URL =
process.env.RELAY_ROOT ||
"https://dev-pedw-ns.servicebus.windows.net/dev-pedw-hc/";
+const GUID_PATTERN =
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+const normaliseGuid = (value) => value.trim().toLowerCase();
+
export default async function ApiProxy(req, res) {
const watchedCaseID = req.query.watchedCaseID;
if (
typeof watchedCaseID !== "string" ||
- watchedCaseID.trim().length === 0
+ !GUID_PATTERN.test(watchedCaseID)
) {
return respondError(res, {
status: 400,
- code: "WATCHED_CASE_ID_REQUIRED",
- message: "watchedCaseID is required"
+ code: "INVALID_WATCHED_CASE_ID",
+ message: "watchedCaseID must be a valid GUID"
+ });
+ }
+
+ if (req.method !== "DELETE") {
+ return respondError(res, {
+ status: 405,
+ code: "METHOD_NOT_ALLOWED",
+ message: "Only DELETE is supported"
+ });
+ }
+
+ const session = await getServerSession(req, res, authOptions(req, res));
+ const authenticatedEmail = session?.user?.email;
+
+ if (
+ typeof authenticatedEmail !== "string" ||
+ authenticatedEmail.trim().length === 0
+ ) {
+ return respondError(res, {
+ status: 401,
+ code: "UNAUTHENTICATED",
+ message: "Authentication required"
});
}
try {
const token = await getToken();
- const queryUrl = "pinswg_watchlists(" + watchedCaseID + ")";
+ const requestOptionsBuilder = (accessToken) => azureHeaders(accessToken);
+ const escapedEmail = escapeODataString(authenticatedEmail);
+ const contactQueryUrl =
+ "contacts?$filter=emailaddress1 eq '" +
+ escapedEmail +
+ "' and statuscode eq 1&$select=contactid";
+ const contactResponse = await relayGetData({
+ queryUrl: contactQueryUrl,
+ accessToken: token.access_token,
+ requestOptionsBuilder
+ });
+ const contacts = contactResponse?.data?.value;
+
+ if (!Array.isArray(contacts)) {
+ return respondError(res, {
+ status: 500,
+ code: "CONTACT_LOOKUP_FAILED",
+ message: "Unable to verify portal contact"
+ });
+ }
+
+ if (
+ contacts.length !== 1 ||
+ typeof contacts[0]?.contactid !== "string" ||
+ !GUID_PATTERN.test(contacts[0].contactid.trim())
+ ) {
+ return respondError(res, {
+ status: 403,
+ code: "CONTACT_IDENTITY_NOT_RESOLVED",
+ message: "Request not permitted"
+ });
+ }
+
+ const normalisedWatchedCaseID = normaliseGuid(watchedCaseID);
+ const watchlistQueryUrl =
+ "pinswg_watchlists(" +
+ normalisedWatchedCaseID +
+ ")?$select=pinswg_watchlistid,_pinswg_contact_value";
+ let watchlistResponse;
+
+ try {
+ watchlistResponse = await relayGetData({
+ queryUrl: watchlistQueryUrl,
+ accessToken: token.access_token,
+ requestOptionsBuilder
+ });
+ } catch (error) {
+ if (error?.response?.status === 404) {
+ return respondError(res, {
+ status: 404,
+ code: "WATCHED_CASE_NOT_FOUND",
+ message: "Watched case not found"
+ });
+ }
+
+ throw error;
+ }
+
+ const watchlist = watchlistResponse?.data;
+ const watchlistContactID = watchlist?._pinswg_contact_value;
+ const watchlistRecordID = watchlist?.pinswg_watchlistid;
+
+ if (
+ typeof watchlistRecordID !== "string" ||
+ !GUID_PATTERN.test(watchlistRecordID.trim()) ||
+ normaliseGuid(watchlistRecordID) !== normalisedWatchedCaseID ||
+ typeof watchlistContactID !== "string" ||
+ !GUID_PATTERN.test(watchlistContactID.trim()) ||
+ normaliseGuid(watchlistContactID) !==
+ normaliseGuid(contacts[0].contactid)
+ ) {
+ return respondError(res, {
+ status: 404,
+ code: "WATCHED_CASE_NOT_FOUND",
+ message: "Watched case not found"
+ });
+ }
+
+ const queryUrl =
+ "pinswg_watchlists(" + normalisedWatchedCaseID + ")";
const config = {
method: "delete",
@@ -56,7 +167,7 @@ export default async function ApiProxy(req, res) {
} catch (error) {
consoleLogger(error);
return respondError(res, {
- status: 400,
+ status: 500,
code: "WATCHED_CASE_DELETE_FAILED",
message: "Failed to delete watched case"
});
diff --git a/pages/api/endpoint/gethash_api.js b/pages/api/endpoint/gethash_api.js
index f0ef869e..fb3e28f9 100644
--- a/pages/api/endpoint/gethash_api.js
+++ b/pages/api/endpoint/gethash_api.js
@@ -1,12 +1,25 @@
import { hashAPIPath } from "../../../actions/core/hash";
import nextConnect from "next-connect";
-import { getSession } from "next-auth/react";
+import { getServerSession } from "next-auth/next";
+import { authOptions } from "../auth/[...nextauth]";
import { respondError, respondSuccess } from "../middleware/apiResponse";
const ApiProxy = nextConnect();
+const isValidContainer = (value) =>
+ typeof value === "string" &&
+ value.length >= 3 &&
+ value.length <= 63 &&
+ /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
+
+const isValidTempCaseRef = (value) =>
+ typeof value === "string" &&
+ value.length <= 100 &&
+ !value.includes("..") &&
+ /^[A-Za-z0-9](?:[A-Za-z0-9/-]*[A-Za-z0-9])?$/.test(value);
+
ApiProxy.get(async (req, res) => {
- const session = await getSession({ req });
+ const session = await getServerSession(req, res, authOptions(req, res));
if (!session) {
return respondError(res, {
@@ -25,8 +38,8 @@ ApiProxy.get(async (req, res) => {
const allowedPrefix = [
"/api/endpoint/getportallogin_api",
- "/api/endpoint/deletemyrepresentations_api",
"/api/endpoint/deletewatchedcases_api",
+ "/api/subscriptions/delete-watched-case",
"/api/file/upload",
"/api/file/uploadsinglefile",
"/api/file/deleteblobcase",
@@ -41,7 +54,7 @@ ApiProxy.get(async (req, res) => {
typeof queryPath !== "string" ||
queryPath.length === 0 ||
!queryPath.startsWith("/api/") ||
- !allowedPrefix.some((prefix) => queryPath.startsWith(prefix)) ||
+ !allowedPrefix.includes(queryPath) ||
queryPath.includes("/api/endpoint/gethash_api")
) {
return respondError(res, {
@@ -51,6 +64,59 @@ ApiProxy.get(async (req, res) => {
});
}
+ if (
+ queryPath.startsWith("/api/file/createappealcompletemessage_api") &&
+ queryPath !== "/api/file/createappealcompletemessage_api"
+ ) {
+ return respondError(res, {
+ status: 400,
+ code: "INVALID_HASH_PATH",
+ message: "Invalid path for hash generation"
+ });
+ }
+
+ if (queryPath === "/api/file/createappealcompletemessage_api") {
+ let completionPath;
+
+ try {
+ completionPath = new URL(rawQueryPath, "http://localhost");
+ } catch (_error) {
+ return respondError(res, {
+ status: 400,
+ code: "INVALID_HASH_PATH",
+ message: "Invalid path for hash generation"
+ });
+ }
+
+ const containerName = completionPath.searchParams.get("container");
+ const tempCaseRef = completionPath.searchParams.get("tempcaseref");
+
+ if (
+ !isValidContainer(containerName) ||
+ !isValidTempCaseRef(tempCaseRef) ||
+ completionPath.searchParams.getAll("container").length !== 1 ||
+ completionPath.searchParams.getAll("tempcaseref").length !== 1
+ ) {
+ return respondError(res, {
+ status: 400,
+ code: "INVALID_HASH_PATH",
+ message: "Invalid path for hash generation"
+ });
+ }
+
+ if (
+ typeof session?.user?.id !== "string" ||
+ session.user.id.length === 0 ||
+ session.user.id !== containerName
+ ) {
+ return respondError(res, {
+ status: 403,
+ code: "FORBIDDEN",
+ message: "Request not permitted"
+ });
+ }
+ }
+
return respondSuccess(res, { hash: hashAPIPath(rawQueryPath) });
});
diff --git a/pages/api/endpoint/getlogin_api.js b/pages/api/endpoint/getlogin_api.js
deleted file mode 100644
index 3e00ea8a..00000000
--- a/pages/api/endpoint/getlogin_api.js
+++ /dev/null
@@ -1,69 +0,0 @@
-/**
- * @swagger
- * /api/endpoint/getlogin_api:
- * get:
- * tags: [Login]
- * description: Returns the hello world
- * summary: Phase 2
- * parameters:
- * - name: emailaddress
- * in: query
- * required: true
- * schema:
- * type: string
- * - name: pwd
- * in: query
- * required: true
- * schema:
- * type: string
- * responses:
- * 200:
- * description: hello world
- */
-
-import { azureHeadersPaged } from "../../../actions/core/headers";
-import { respondError } from "../middleware/apiResponse";
-import { relayGet } from "../middleware/relayForwarding";
-import { RELAY_POLICY_STRICT_LOGIN } from "../middleware/relayPolicyPresets";
-
-export default async function ApiProxy(req, res) {
- const emailAddress = req.query.emailAddress;
- const pwd = req.query.pwd;
-
- if (typeof emailAddress !== "string" || emailAddress.trim().length === 0) {
- return respondError(res, {
- status: 400,
- code: "EMAIL_ADDRESS_REQUIRED",
- message: "emailAddress is required"
- });
- }
-
- if (typeof pwd !== "string" || pwd.trim().length === 0) {
- return respondError(res, {
- status: 400,
- code: "PASSWORD_REQUIRED",
- message: "pwd is required"
- });
- }
-
- const queryUrl =
- "contacts?$filter=emailaddress1 eq '" +
- emailAddress +
- "' and pinswg_custom_password eq '" +
- pwd +
- "'&$count=true&$select=emailaddress1,contactid,pinswg_custom_password,yomifullname,firstname,lastname";
-
- const relayPolicy = RELAY_POLICY_STRICT_LOGIN;
-
- return relayGet({
- queryUrl,
- res,
- requestOptionsBuilder: (accessToken) => azureHeadersPaged(accessToken),
- relayPolicy,
- errorResponse: {
- status: 400,
- code: "LOGIN_FETCH_FAILED",
- message: "Failed to fetch login details"
- }
- });
-}
diff --git a/pages/api/endpoint/updateaccount_api.js b/pages/api/endpoint/updateaccount_api.js
index 7f7c1f34..1f3149f7 100644
--- a/pages/api/endpoint/updateaccount_api.js
+++ b/pages/api/endpoint/updateaccount_api.js
@@ -1,37 +1,68 @@
-/**
- * @swagger
- * /api/endpoint/updateaccount_api:
- * patch:
- * tags: [Account]
- * description: Update account
- * summary: Phase 2
- * responses:
- * 200:
- * description: Success
- */
-
-import axios from "axios";
import { consoleLogger } from "../../../actions/core/logger";
-import { getToken } from "../../../actions/core/token";
-import { hashAPIPath } from "../../../actions/core/hash";
import { respondError, respondSuccess } from "../middleware/apiResponse";
+import { updateCrmContact } from "../../../lib/server/updateCrmContact";
+import { getServerSession } from "next-auth/next";
+import { authOptions } from "../auth/[...nextauth]";
+import { getToken } from "../../../actions/core/token";
+import { relayGetData } from "../middleware/relayForwarding";
+import { azureHeaders } from "../../../actions/core/headers";
+import { escapeODataString } from "../../../actions/core/guards";
-const WEBAPI_URL =
- process.env.RELAY_ROOT ||
- "https://dev-pedw-ns.servicebus.windows.net/dev-pedw-hc/";
+const GUID_PATTERN =
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+const ALLOWED_ACCOUNT_FIELDS = new Set([
+ "pinswg_preferredlanguage",
+ "firstname",
+ "lastname",
+ "telephone1",
+ "pinswg_companyname",
+ "address1_line1",
+ "address1_line2",
+ "address1_city",
+ "address1_county",
+ "address1_postalcode"
+]);
export default async function ApiProxy(req, res) {
- const contactId = req.query.contactId;
-
- if (typeof contactId !== "string" || contactId.trim().length === 0) {
+ if (req.method !== "POST") {
+ res.setHeader("Allow", "POST");
return respondError(res, {
- status: 400,
- code: "CONTACT_ID_REQUIRED",
- message: "contactId is required"
+ status: 405,
+ code: "METHOD_NOT_ALLOWED",
+ message: "Method not allowed"
});
}
- if (!req.body || Object.keys(req.body).length === 0) {
+ const session = await getServerSession(req, res, authOptions(req, res));
+
+ if (
+ typeof session?.user?.email !== "string" ||
+ session.user.email.trim().length === 0
+ ) {
+ return respondError(res, {
+ status: 401,
+ code: "UNAUTHENTICATED",
+ message: "Authentication required"
+ });
+ }
+
+ const contactId = req.query.contactId;
+
+ if (typeof contactId !== "string" || !GUID_PATTERN.test(contactId.trim())) {
+ return respondError(res, {
+ status: 400,
+ code: "INVALID_CONTACT_ID",
+ message: "A valid contactId is required"
+ });
+ }
+
+ if (
+ !req.body ||
+ typeof req.body !== "object" ||
+ Array.isArray(req.body) ||
+ Object.keys(req.body).length === 0
+ ) {
return respondError(res, {
status: 400,
code: "ACCOUNT_UPDATE_PAYLOAD_REQUIRED",
@@ -41,25 +72,62 @@ export default async function ApiProxy(req, res) {
try {
const token = await getToken();
- const data = JSON.stringify(req.body);
- const queryUrl = "contacts(" + contactId + ")";
- const config = {
- method: "patch",
- url: WEBAPI_URL + queryUrl + hashAPIPath(queryUrl),
- headers: {
- "OData-MaxVersion": "4.0",
- "OData-Version": "4.0",
- Accept: "application/json",
- Prefer: 'odata.include-annotations="*",return=representation',
- Authorization: "Bearer " + token.access_token,
- "Content-Type": "application/json"
- },
- data
- };
+ const escapedEmail = escapeODataString(session.user.email);
- const response = await axios(config);
- return respondSuccess(res, response.data);
+ const contactQueryUrl =
+ "contacts?$filter=emailaddress1 eq '" +
+ escapedEmail +
+ "' and statuscode eq 1&$select=contactid";
+
+ const contactResponse = await relayGetData({
+ queryUrl: contactQueryUrl,
+ accessToken: token.access_token,
+ requestOptionsBuilder: (accessToken) => azureHeaders(accessToken)
+ });
+
+ const contacts = contactResponse?.data?.value;
+
+ if (
+ !Array.isArray(contacts) ||
+ contacts.length !== 1 ||
+ typeof contacts[0]?.contactid !== "string" ||
+ !GUID_PATTERN.test(contacts[0].contactid.trim())
+ ) {
+ return respondError(res, {
+ status: 403,
+ code: "CONTACT_IDENTITY_NOT_RESOLVED",
+ message: "Request not permitted"
+ });
+ }
+
+ if (
+ contactId.trim().toLowerCase() !==
+ contacts[0].contactid.trim().toLowerCase()
+ ) {
+ return respondError(res, {
+ status: 403,
+ code: "CONTACT_OWNERSHIP_MISMATCH",
+ message: "Request not permitted"
+ });
+ }
+
+ const updatePayload = Object.fromEntries(
+ Object.entries(req.body).filter(([field]) =>
+ ALLOWED_ACCOUNT_FIELDS.has(field)
+ )
+ );
+
+ if (Object.keys(updatePayload).length === 0) {
+ return respondError(res, {
+ status: 400,
+ code: "NO_ALLOWED_ACCOUNT_FIELDS",
+ message: "No permitted account fields supplied"
+ });
+ }
+
+ const data = await updateCrmContact(contactId.trim(), updatePayload);
+ return respondSuccess(res, data);
} catch (error) {
consoleLogger(error);
return respondError(res, {
diff --git a/pages/api/endpoint/updatepassword_api.js b/pages/api/endpoint/updatepassword_api.js
deleted file mode 100644
index dc8a64cb..00000000
--- a/pages/api/endpoint/updatepassword_api.js
+++ /dev/null
@@ -1,71 +0,0 @@
-/**
- * @swagger
- * /api/endpoint/updatepassword_api:
- * patch:
- * tags: [Account]
- * description: Update password
- * summary: Phase 2
- * responses:
- * 200:
- * description: Success
- */
-
-import axios from "axios";
-import { consoleLogger } from "../../../actions/core/logger";
-import { getToken } from "../../../actions/core/token";
-import { hashAPIPath } from "../../../actions/core/hash";
-import { respondError, respondSuccess } from "../middleware/apiResponse";
-
-const WEBAPI_URL =
- process.env.RELAY_ROOT ||
- "https://dev-pedw-ns.servicebus.windows.net/dev-pedw-hc/";
-
-export default async function ApiProxy(req, res) {
- const contactId = req.query.contactId;
-
- if (typeof contactId !== "string" || contactId.trim().length === 0) {
- return respondError(res, {
- status: 400,
- code: "CONTACT_ID_REQUIRED",
- message: "contactId is required"
- });
- }
-
- if (!req.body || Object.keys(req.body).length === 0) {
- return respondError(res, {
- status: 400,
- code: "PASSWORD_UPDATE_PAYLOAD_REQUIRED",
- message: "Password update payload is required"
- });
- }
-
- try {
- const token = await getToken();
- const data = JSON.stringify(req.body);
- const queryUrl = "contacts(" + contactId + ")";
-
- const config = {
- method: "patch",
- url: WEBAPI_URL + queryUrl + hashAPIPath(queryUrl),
- headers: {
- "OData-MaxVersion": "4.0",
- "OData-Version": "4.0",
- Accept: "application/json",
- Prefer: 'odata.include-annotations="*",return=representation',
- Authorization: "Bearer " + token.access_token,
- "Content-Type": "application/json"
- },
- data
- };
-
- const response = await axios(config);
- return respondSuccess(res, response.data);
- } catch (error) {
- consoleLogger(error);
- return respondError(res, {
- status: 400,
- code: "PASSWORD_UPDATE_FAILED",
- message: "Failed to update password"
- });
- }
-}
diff --git a/pages/api/file/createappealcompletemessage_api.js b/pages/api/file/createappealcompletemessage_api.js
index 17c43b1e..03401963 100644
--- a/pages/api/file/createappealcompletemessage_api.js
+++ b/pages/api/file/createappealcompletemessage_api.js
@@ -1,4 +1,4 @@
-import { updateAccount } from "../../../actions/services/accountService";
+import { updateCrmContact } from "../../../lib/server/updateCrmContact";
import { hashAPIPath } from "../../../actions/core/hash";
import { consoleLogger } from "../../../actions/core/logger";
import {
@@ -13,10 +13,34 @@ import _ from "lodash";
import nextConnect from "next-connect";
import middleware from "../middleware/middleware";
import { respondError, respondSuccess } from "../middleware/apiResponse";
+import { getServerSession } from "next-auth/next";
+import { authOptions } from "../auth/[...nextauth]";
const ApiProxy = nextConnect();
ApiProxy.use(middleware);
+const hasValue = (value) =>
+ typeof value === "string" && value.trim().length > 0;
+
+const isValidContainer = (value) =>
+ typeof value === "string" &&
+ value.length >= 3 &&
+ value.length <= 63 &&
+ /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
+
+const isValidTempCaseRef = (value) =>
+ typeof value === "string" &&
+ value.length <= 100 &&
+ !value.includes("..") &&
+ /^[A-Za-z0-9](?:[A-Za-z0-9/-]*[A-Za-z0-9])?$/.test(value);
+
+const forbidden = (res) =>
+ respondError(res, {
+ status: 403,
+ code: "FORBIDDEN",
+ message: "Request not permitted"
+ });
+
ApiProxy.get(async (req, res) => {
const containerName = req.query.container;
const tempCaseRef = req.query.tempcaseref;
@@ -24,12 +48,9 @@ ApiProxy.get(async (req, res) => {
const checkHash = req.query.hash;
if (
- typeof containerName === "undefined" ||
- containerName.length === 0 ||
- typeof tempCaseRef === "undefined" ||
- tempCaseRef.length === 0 ||
- typeof checkHash === "undefined" ||
- checkHash.length === 0
+ !hasValue(containerName) ||
+ !hasValue(tempCaseRef) ||
+ !hasValue(checkHash)
) {
return respondError(res, {
status: 400,
@@ -38,6 +59,23 @@ ApiProxy.get(async (req, res) => {
});
}
+ if (!isValidContainer(containerName) || !isValidTempCaseRef(tempCaseRef)) {
+ return respondError(res, {
+ status: 400,
+ code: "INVALID_REQUEST",
+ message: "Invalid request"
+ });
+ }
+
+ const session = await getServerSession(req, res, authOptions(req, res));
+ if (
+ typeof session?.user?.id !== "string" ||
+ session.user.id.length === 0 ||
+ session.user.id !== containerName
+ ) {
+ return forbidden(res);
+ }
+
const hashCandidatePaths = [
"/api/file/createappealcompletemessage_api?container=" +
containerName +
@@ -117,13 +155,9 @@ ApiProxy.get(async (req, res) => {
if (typeofinvolvement != 846040000) {
void (async () => {
try {
- await updateAccount(
- contactId[1],
- {
- pinswg_typeofinvolvement: 846040001
- },
- true
- );
+ await updateCrmContact(contactId[1], {
+ pinswg_typeofinvolvement: 846040001
+ });
} catch (error) {
consoleLogger(error);
}
diff --git a/pages/api/file/createappealcompletemessageproxy_api.js b/pages/api/file/createappealcompletemessageproxy_api.js
index 81d3c443..0e89180e 100644
--- a/pages/api/file/createappealcompletemessageproxy_api.js
+++ b/pages/api/file/createappealcompletemessageproxy_api.js
@@ -4,6 +4,8 @@ import { azureHeaders } from "../../../actions/core/headers";
import { consoleLogger } from "../../../actions/core/logger";
import axios from "axios";
import { respondError, respondSuccess } from "../middleware/apiResponse";
+import { getServerSession } from "next-auth/next";
+import { authOptions } from "../auth/[...nextauth]";
import nextConnect from "next-connect";
import middleware from "../middleware/middleware";
@@ -16,6 +18,25 @@ const BASE_URL = process.env.API_ROOT || `http://localhost:${port}`;
const hasValue = (value) =>
typeof value === "string" && value.trim().length > 0;
+const isValidContainer = (value) =>
+ typeof value === "string" &&
+ value.length >= 3 &&
+ value.length <= 63 &&
+ /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
+
+const isValidTempCaseRef = (value) =>
+ typeof value === "string" &&
+ value.length <= 100 &&
+ !value.includes("..") &&
+ /^[A-Za-z0-9](?:[A-Za-z0-9/-]*[A-Za-z0-9])?$/.test(value);
+
+const forbidden = (res) =>
+ respondError(res, {
+ status: 403,
+ code: "FORBIDDEN",
+ message: "Request not permitted"
+ });
+
ApiProxy.get(async (req, res) => {
const containerName = req.query.container;
const tempCaseRef = req.query.tempcaseref;
@@ -28,6 +49,26 @@ ApiProxy.get(async (req, res) => {
});
}
+ if (
+ !isValidContainer(containerName) ||
+ !isValidTempCaseRef(tempCaseRef)
+ ) {
+ return respondError(res, {
+ status: 400,
+ code: "INVALID_REQUEST",
+ message: "Invalid request"
+ });
+ }
+
+ const session = await getServerSession(req, res, authOptions(req, res));
+ if (
+ typeof session?.user?.id !== "string" ||
+ session.user.id.length === 0 ||
+ session.user.id !== containerName
+ ) {
+ return forbidden(res);
+ }
+
const token = await getToken();
const queryUrl =
@@ -37,9 +78,17 @@ ApiProxy.get(async (req, res) => {
encodeURIComponent(tempCaseRef);
try {
+ const requestOptions = azureHeaders(token.access_token);
+ if (typeof req.headers?.cookie === "string") {
+ requestOptions.headers = {
+ ...requestOptions.headers,
+ cookie: req.headers.cookie
+ };
+ }
+
const { data } = await axios.get(
BASE_URL + queryUrl + hashAPIPath(queryUrl),
- azureHeaders(token.access_token)
+ requestOptions
);
return respondSuccess(res, data);
} catch (error) {
diff --git a/pages/api/file/createcase_api.js b/pages/api/file/createcase_api.js
index 95360e26..1b3d8c4b 100644
--- a/pages/api/file/createcase_api.js
+++ b/pages/api/file/createcase_api.js
@@ -9,30 +9,59 @@ import { getTempCaseRef } from "../../../components/utils";
import { v4 as uuidv4 } from "uuid";
import { hashAPIPath } from "../../../actions/core/hash";
import { respondError, respondSuccess } from "../middleware/apiResponse";
+import { getServerSession } from "next-auth/next";
+import { authOptions } from "../auth/[...nextauth]";
const WEBAPI_URL =
process.env.RELAY_ROOT ||
"https://dev-pedw-ns.servicebus.windows.net/dev-pedw-hc/";
+const hasValue = (value) =>
+ typeof value === "string" && value.trim().length > 0;
+
+const isValidContainer = (value) =>
+ typeof value === "string" &&
+ value.length >= 3 &&
+ value.length <= 63 &&
+ /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
+
+const isValidDraftFolder = (value) =>
+ typeof value === "string" &&
+ value.length <= 100 &&
+ !value.includes("..") &&
+ /^[A-Za-z0-9](?:[A-Za-z0-9/-]*[A-Za-z0-9])?$/.test(value);
+
+const forbidden = (res) =>
+ respondError(res, {
+ status: 403,
+ code: "FORBIDDEN",
+ message: "Request not permitted"
+ });
+
export default async function ApiProxy(req, res) {
- var createCaseBody = req.body;
+ let createCaseBody;
+ try {
+ createCaseBody =
+ typeof req.body === "string" ? JSON.parse(req.body) : req.body;
+ } catch (_error) {
+ return respondError(res, {
+ status: 400,
+ code: "INVALID_REQUEST",
+ message: "Invalid request"
+ });
+ }
+
var contactid = req.query.contactid;
var appealTypeId = req.query.appealTypeId;
var containerName = req.query.containername;
var lpaID = req.query.lpaID;
var queryUrl = "incidents";
- var token = await getToken();
- var tempCaseRef = getTempCaseRef();
if (
- typeof contactid === "undefined" ||
- contactid.length === 0 ||
- typeof appealTypeId === "undefined" ||
- appealTypeId.length === 0 ||
- typeof containerName === "undefined" ||
- containerName.length === 0 ||
- typeof lpaID === "undefined" ||
- lpaID.length === 0
+ !hasValue(contactid) ||
+ !hasValue(appealTypeId) ||
+ !hasValue(containerName) ||
+ !hasValue(lpaID)
) {
return respondError(res, {
status: 400,
@@ -42,6 +71,46 @@ export default async function ApiProxy(req, res) {
});
}
+ if (
+ !createCaseBody ||
+ typeof createCaseBody !== "object" ||
+ Array.isArray(createCaseBody) ||
+ !isValidContainer(containerName) ||
+ ["container", "containerID", "containername"].some(
+ (key) => Object.prototype.hasOwnProperty.call(createCaseBody, key)
+ ) ||
+ ["container", "containerID"].some((key) =>
+ Object.prototype.hasOwnProperty.call(req.query, key)
+ )
+ ) {
+ return respondError(res, {
+ status: 400,
+ code: "INVALID_REQUEST",
+ message: "Invalid request"
+ });
+ }
+
+ const session = await getServerSession(req, res, authOptions(req, res));
+ if (
+ typeof session?.user?.id !== "string" ||
+ session.user.id.length === 0 ||
+ session.user.id !== containerName
+ ) {
+ return forbidden(res);
+ }
+
+ var tempCaseRef = getTempCaseRef();
+
+ if (!isValidDraftFolder(tempCaseRef)) {
+ return respondError(res, {
+ status: 400,
+ code: "INVALID_REQUEST",
+ message: "Invalid request"
+ });
+ }
+
+ var token = await getToken();
+
var data = {
"title": tempCaseRef,
"ticketnumber": tempCaseRef,
diff --git a/pages/api/file/createrepcompletemessage_api.js b/pages/api/file/createrepcompletemessage_api.js
index bff12c91..94311d16 100644
--- a/pages/api/file/createrepcompletemessage_api.js
+++ b/pages/api/file/createrepcompletemessage_api.js
@@ -1,18 +1,42 @@
-import {
- getBlobs,
- createRepCompleteMessage
-} from "../../../actions/azurestorage";
+import { createRepCompleteMessage } from "../../../actions/azurestorage";
import { hashAPIPath } from "../../../actions/core/hash";
import { consoleLogger } from "../../../actions/core/logger";
import { respondError, respondSuccess } from "../middleware/apiResponse";
+import { getSession } from "next-auth/react";
-import nextConnect from "next-connect";
-import middleware from "../middleware/middleware";
+const forbidden = (res) =>
+ respondError(res, {
+ status: 403,
+ code: "FORBIDDEN",
+ message: "Request not permitted"
+ });
-const ApiProxy = nextConnect();
-ApiProxy.use(middleware);
+const isValidContainer = (value) =>
+ typeof value === "string" &&
+ value.length >= 3 &&
+ value.length <= 63 &&
+ /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
+
+const isValidPathSegment = (value) =>
+ typeof value === "string" &&
+ value.length > 0 &&
+ value.length <= 255 &&
+ value === value.trim() &&
+ value !== "." &&
+ value !== ".." &&
+ !/[\\/\u0000-\u001f\u007f]/.test(value);
+
+export default async function handler(req, res) {
+ res.setHeader("Allow", "GET");
+
+ if (req.method !== "GET") {
+ return respondError(res, {
+ status: 405,
+ code: "METHOD_NOT_ALLOWED",
+ message: "Method not allowed"
+ });
+ }
-ApiProxy.get(async (req, res) => {
const containerName = req.query.container;
const tempCaseRef = req.query.tempcaseref;
const filename = req.query.repid;
@@ -20,13 +44,13 @@ ApiProxy.get(async (req, res) => {
if (
typeof containerName === "undefined" ||
- containerName.length === 0 ||
+ containerName === "" ||
typeof tempCaseRef === "undefined" ||
- tempCaseRef.length === 0 ||
+ tempCaseRef === "" ||
typeof filename === "undefined" ||
- filename.length === 0 ||
+ filename === "" ||
typeof checkHash === "undefined" ||
- checkHash.length === 0
+ checkHash === ""
) {
return respondError(res, {
status: 400,
@@ -35,6 +59,28 @@ ApiProxy.get(async (req, res) => {
});
}
+ if (
+ !isValidContainer(containerName) ||
+ !isValidPathSegment(tempCaseRef) ||
+ !isValidPathSegment(filename) ||
+ typeof checkHash !== "string"
+ ) {
+ return respondError(res, {
+ status: 400,
+ code: "INVALID_REQUEST",
+ message: "Invalid request"
+ });
+ }
+
+ const session = await getSession({ req });
+ if (
+ typeof session?.user?.id !== "string" ||
+ session.user.id.length === 0 ||
+ session.user.id !== containerName
+ ) {
+ return forbidden(res);
+ }
+
const hashCandidatePaths = [
"/api/file/createrepcompletemessage_api?container=" +
containerName +
@@ -77,12 +123,10 @@ ApiProxy.get(async (req, res) => {
message: "Failed to create representation complete message"
});
}
-});
+}
export const config = {
api: {
bodyParser: false
}
};
-
-export default ApiProxy;
diff --git a/pages/api/file/deleteawaitingsubmissionfromblob.js b/pages/api/file/deleteawaitingsubmissionfromblob.js
index 4740aa45..f4af12c6 100644
--- a/pages/api/file/deleteawaitingsubmissionfromblob.js
+++ b/pages/api/file/deleteawaitingsubmissionfromblob.js
@@ -1,6 +1,8 @@
import { hashAPIPath } from "../../../actions/core/hash";
import { deleteBlob } from "../../../actions/azurestorage";
import { respondError, respondSuccess } from "../middleware/apiResponse";
+import { getServerSession } from "next-auth/next";
+import { authOptions } from "../auth/[...nextauth]";
import nextConnect from "next-connect";
import middleware from "../middleware/middleware";
@@ -8,6 +10,22 @@ import middleware from "../middleware/middleware";
const ApiProxy = nextConnect();
ApiProxy.use(middleware);
+const forbidden = (res) =>
+ respondError(res, {
+ status: 403,
+ code: "FORBIDDEN",
+ message: "Request not permitted"
+ });
+
+const hasValue = (value) =>
+ typeof value === "string" && value.trim().length > 0;
+
+const isValidContainer = (value) =>
+ typeof value === "string" &&
+ value.length >= 3 &&
+ value.length <= 63 &&
+ /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
+
ApiProxy.get(async (req, res) => {
const containerName = req.query.container;
const casefolderID = req.query.casefolderID;
@@ -15,14 +33,10 @@ ApiProxy.get(async (req, res) => {
const checkHash = req.query.hash;
if (
- typeof containerName === "undefined" ||
- containerName.length === 0 ||
- typeof casefolderID === "undefined" ||
- casefolderID.length === 0 ||
- typeof blobName === "undefined" ||
- blobName.length === 0 ||
- typeof checkHash === "undefined" ||
- checkHash.length === 0
+ !hasValue(containerName) ||
+ !hasValue(casefolderID) ||
+ !hasValue(blobName) ||
+ !hasValue(checkHash)
) {
return respondError(res, {
status: 400,
@@ -34,6 +48,23 @@ ApiProxy.get(async (req, res) => {
const casefolderIDTrimmed = casefolderID.trim();
const blobNameTrimmed = blobName.trim();
+ if (!isValidContainer(containerName)) {
+ return respondError(res, {
+ status: 400,
+ code: "INVALID_REQUEST",
+ message: "Invalid request"
+ });
+ }
+
+ const session = await getServerSession(req, res, authOptions(req, res));
+ if (
+ typeof session?.user?.id !== "string" ||
+ session.user.id.length === 0 ||
+ session.user.id !== containerName
+ ) {
+ return forbidden(res);
+ }
+
const hashCandidatePaths = [
"/api/file/deleteawaitingsubmissionfromblob?container=" +
containerName +
diff --git a/pages/api/file/deleteblob.js b/pages/api/file/deleteblob.js
index 5402078b..2736f848 100644
--- a/pages/api/file/deleteblob.js
+++ b/pages/api/file/deleteblob.js
@@ -1,6 +1,8 @@
import { hashAPIPath } from "../../../actions/core/hash";
import { deleteBlob } from "../../../actions/azurestorage";
import { respondError, respondSuccess } from "../middleware/apiResponse";
+import { getServerSession } from "next-auth/next";
+import { authOptions } from "../auth/[...nextauth]";
import nextConnect from "next-connect";
import middleware from "../middleware/middleware";
@@ -8,6 +10,22 @@ import middleware from "../middleware/middleware";
const ApiProxy = nextConnect();
ApiProxy.use(middleware);
+const forbidden = (res) =>
+ respondError(res, {
+ status: 403,
+ code: "FORBIDDEN",
+ message: "Request not permitted"
+ });
+
+const hasValue = (value) =>
+ typeof value === "string" && value.trim().length > 0;
+
+const isValidContainer = (value) =>
+ typeof value === "string" &&
+ value.length >= 3 &&
+ value.length <= 63 &&
+ /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
+
ApiProxy.get(async (req, res) => {
const containerName = req.query.container;
const casefolderID = req.query.casefolderID;
@@ -15,14 +33,10 @@ ApiProxy.get(async (req, res) => {
const checkHash = req.query.hash;
if (
- typeof containerName === "undefined" ||
- containerName.length === 0 ||
- typeof casefolderID === "undefined" ||
- casefolderID.length === 0 ||
- typeof blobName === "undefined" ||
- blobName.length === 0 ||
- typeof checkHash === "undefined" ||
- checkHash.length === 0
+ !hasValue(containerName) ||
+ !hasValue(casefolderID) ||
+ !hasValue(blobName) ||
+ !hasValue(checkHash)
) {
return respondError(res, {
status: 400,
@@ -34,6 +48,23 @@ ApiProxy.get(async (req, res) => {
const casefolderIDTrimmed = casefolderID.trim();
const blobNameTrimmed = blobName.trim();
+ if (!isValidContainer(containerName)) {
+ return respondError(res, {
+ status: 400,
+ code: "INVALID_REQUEST",
+ message: "Invalid request"
+ });
+ }
+
+ const session = await getServerSession(req, res, authOptions(req, res));
+ if (
+ typeof session?.user?.id !== "string" ||
+ session.user.id.length === 0 ||
+ session.user.id !== containerName
+ ) {
+ return forbidden(res);
+ }
+
const hashCandidatePaths = [
"/api/file/deleteblob?container=" +
containerName +
diff --git a/pages/api/file/deleteblobcase.js b/pages/api/file/deleteblobcase.js
index 62764132..002068a4 100644
--- a/pages/api/file/deleteblobcase.js
+++ b/pages/api/file/deleteblobcase.js
@@ -1,6 +1,8 @@
import { hashAPIPath } from "../../../actions/core/hash";
import { deleteBlobCase } from "../../../actions/azurestorage";
import { respondError, respondSuccess } from "../middleware/apiResponse";
+import { getServerSession } from "next-auth/next";
+import { authOptions } from "../auth/[...nextauth]";
import nextConnect from "next-connect";
import middleware from "../middleware/middleware";
@@ -8,6 +10,13 @@ import middleware from "../middleware/middleware";
const ApiProxy = nextConnect();
ApiProxy.use(middleware);
+const forbidden = (res) =>
+ respondError(res, {
+ status: 403,
+ code: "FORBIDDEN",
+ message: "Request not permitted"
+ });
+
ApiProxy.get(async (req, res) => {
const containerName = req.query.container;
const casefolderID = req.query.casefolderID;
@@ -30,6 +39,15 @@ ApiProxy.get(async (req, res) => {
const casefolderIDTrimmed = casefolderID.trim();
+ const session = await getServerSession(req, res, authOptions(req, res));
+ if (
+ typeof session?.user?.id !== "string" ||
+ session.user.id.length === 0 ||
+ session.user.id !== containerName
+ ) {
+ return forbidden(res);
+ }
+
const hashCandidatePaths = [
"/api/file/deleteblobcase?container=" +
containerName +
diff --git a/pages/api/file/deleteblobrep.js b/pages/api/file/deleteblobrep.js
index b327837c..d6c7f3f0 100644
--- a/pages/api/file/deleteblobrep.js
+++ b/pages/api/file/deleteblobrep.js
@@ -1,6 +1,8 @@
import { hashAPIPath } from "../../../actions/core/hash";
import { deleteBlobRep } from "../../../actions/azurestorage";
import { respondError, respondSuccess } from "../middleware/apiResponse";
+import { getServerSession } from "next-auth/next";
+import { authOptions } from "../auth/[...nextauth]";
import nextConnect from "next-connect";
import middleware from "../middleware/middleware";
@@ -8,6 +10,13 @@ import middleware from "../middleware/middleware";
const ApiProxy = nextConnect();
ApiProxy.use(middleware);
+const forbidden = (res) =>
+ respondError(res, {
+ status: 403,
+ code: "FORBIDDEN",
+ message: "Request not permitted"
+ });
+
ApiProxy.get(async (req, res) => {
const containerName = req.query.container;
const casefolderID = req.query.casefolderID;
@@ -34,6 +43,15 @@ ApiProxy.get(async (req, res) => {
const casefolderIDTrimmed = casefolderID.trim();
const repfileTrimmed = repfile.trim();
+ const session = await getServerSession(req, res, authOptions(req, res));
+ if (
+ typeof session?.user?.id !== "string" ||
+ session.user.id.length === 0 ||
+ session.user.id !== containerName
+ ) {
+ return forbidden(res);
+ }
+
const hashCandidatePaths = [
"/api/file/deleteblobrep?container=" +
containerName +
diff --git a/pages/api/file/editRepJson.js b/pages/api/file/editRepJson.js
index e301ade4..ad7b3dd1 100644
--- a/pages/api/file/editRepJson.js
+++ b/pages/api/file/editRepJson.js
@@ -1,96 +1,9 @@
-import { DefaultAzureCredential } from "@azure/identity";
-import { BlobServiceClient } from "@azure/storage-blob";
-import { consoleLogger } from "../../../actions/core/logger";
-import { respondError, respondSuccess } from "../middleware/apiResponse";
+import { respondError } from "../middleware/apiResponse";
export default async function handler(req, res) {
- if (req.method !== "POST") {
- return respondError(res, {
- status: 405,
- code: "METHOD_NOT_ALLOWED",
- message: "Method not allowed"
- });
- }
-
- const { container, blobName } = req.body;
-
- if (!container || !blobName) {
- return respondError(res, {
- status: 400,
- code: "MISSING_REQUIRED_BODY",
- message: "Missing container or blobName"
- });
- }
-
- try {
- const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME;
- const creds = new DefaultAzureCredential();
- const blobServiceClient = new BlobServiceClient(
- `https://${accountName}.blob.core.windows.net`,
- creds
- );
-
- const containerClient = blobServiceClient.getContainerClient(container);
- const blockBlobClient = containerClient.getBlockBlobClient(blobName);
-
- // Download blob content
- const downloadResponse = await blockBlobClient.download(0);
- const downloaded = await streamToString(
- downloadResponse.readableStreamBody
- );
-
- // Parse JSON
- const json = JSON.parse(downloaded);
-
- // Remove repComplete element if it exists
- if ("repComplete" in json) {
- delete json.repComplete;
- }
-
- const tags = {
- containerid: json.containerID,
- caseID: json.ticketnumber,
- blobType: "Representation"
- };
-
- // Convert back to string
- const updatedContent = JSON.stringify(json, null, 2);
-
- // Upload updated content (overwrite)
- await blockBlobClient.upload(
- updatedContent,
- Buffer.byteLength(updatedContent),
- {
- blobHTTPHeaders: { blobContentType: "application/json" }
- }
- );
-
- const withTags = await blockBlobClient.setTags(tags);
- const withMeta = await blockBlobClient.setMetadata(tags);
-
- return respondSuccess(res, {
- message: "repComplete removed successfully"
- });
- } catch (error) {
- consoleLogger(error);
- return respondError(res, {
- status: 500,
- code: "EDIT_REP_JSON_FAILED",
- message: "Failed to edit rep.json"
- });
- }
-}
-
-// Helper function to read stream to string
-async function streamToString(readableStream) {
- return new Promise((resolve, reject) => {
- const chunks = [];
- readableStream.on("data", (data) => {
- chunks.push(data.toString());
- });
- readableStream.on("end", () => {
- resolve(chunks.join(""));
- });
- readableStream.on("error", reject);
+ return respondError(res, {
+ status: 410,
+ code: "ENDPOINT_RETIRED",
+ message: "Endpoint retired"
});
}
diff --git a/pages/api/file/generateappealpdf.js b/pages/api/file/generateappealpdf.js
index 34fc1119..3f014bbc 100644
--- a/pages/api/file/generateappealpdf.js
+++ b/pages/api/file/generateappealpdf.js
@@ -85,27 +85,68 @@ import { getPickLists } from "../../../actions/services/referenceDataService";
import { planningappeals78_pdf } from "../../../components/pdftemplates/planningappeals78_pdf";
import { other_pdf } from "../../../components/pdftemplates/other_pdf";
import { respondError, respondSuccess } from "../middleware/apiResponse";
+import { getServerSession } from "next-auth/next";
+import { authOptions } from "../auth/[...nextauth]";
//const ApiProxy = nextConnect();
// ApiProxy.use(middleware);
// ApiProxy.post(async (req, res) => {
+const isValidContainer = (value) =>
+ typeof value === "string" &&
+ value.length >= 3 &&
+ value.length <= 63 &&
+ /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
+
+const isValidDraftFolder = (value) =>
+ typeof value === "string" &&
+ value.length <= 100 &&
+ !value.includes("..") &&
+ /^[A-Za-z0-9](?:[A-Za-z0-9/-]*[A-Za-z0-9])?$/.test(value);
+
+const forbidden = (res) =>
+ respondError(res, {
+ status: 403,
+ code: "FORBIDDEN",
+ message: "Request not permitted"
+ });
+
export default async function handler(req, res) {
const checkHash = req.query.hash;
const appealType = req.query.appealType;
const isDownload = req.query?.download === "true";
- let appealBodyObj =
- typeof req.body === "string" ? JSON.parse(req.body) : req.body;
+ let appealBodyObj;
+ try {
+ appealBodyObj =
+ typeof req.body === "string" ? JSON.parse(req.body) : req.body;
+ } catch (_error) {
+ return respondError(res, {
+ status: 400,
+ code: "INVALID_REQUEST",
+ message: "Invalid request"
+ });
+ }
+
+ if (
+ !appealBodyObj ||
+ typeof appealBodyObj !== "object" ||
+ Array.isArray(appealBodyObj)
+ ) {
+ return respondError(res, {
+ status: 400,
+ code: "INVALID_REQUEST",
+ message: "Invalid request"
+ });
+ }
+
const containerID = appealBodyObj.containerID;
const casefolderID = appealBodyObj.casefolderID;
const locale = appealBodyObj.locale || "en";
let checkquerypath = "/api/file/generateappealpdf";
if (
- typeof checkHash === "undefined" ||
- checkHash.length === 0 ||
typeof appealType === "undefined" ||
String(appealType).length === 0 ||
typeof containerID === "undefined" ||
@@ -121,6 +162,45 @@ export default async function handler(req, res) {
});
}
+ if (
+ typeof appealType !== "string" ||
+ !isValidContainer(containerID) ||
+ !isValidDraftFolder(casefolderID) ||
+ (typeof req.query.download !== "undefined" &&
+ typeof req.query.download !== "string") ||
+ [
+ "container",
+ "containerID",
+ "casefolderID",
+ "caseRef",
+ "ticketnumber"
+ ].some((key) => Object.prototype.hasOwnProperty.call(req.query, key))
+ ) {
+ return respondError(res, {
+ status: 400,
+ code: "INVALID_REQUEST",
+ message: "Invalid request"
+ });
+ }
+
+ const session = await getServerSession(req, res, authOptions(req, res));
+ if (
+ typeof session?.user?.id !== "string" ||
+ session.user.id.length === 0 ||
+ session.user.id !== containerID
+ ) {
+ return forbidden(res);
+ }
+
+ if (typeof checkHash !== "string" || checkHash.length === 0) {
+ return respondError(res, {
+ status: 400,
+ code: "MISSING_REQUIRED_QUERY",
+ message:
+ "hash, appealType, containerID and casefolderID are required"
+ });
+ }
+
checkquerypath =
checkquerypath +
"?appealType=" +
diff --git a/pages/api/file/generatepdf.js b/pages/api/file/generatepdf.js
index 9963dd9f..67d7e05d 100644
--- a/pages/api/file/generatepdf.js
+++ b/pages/api/file/generatepdf.js
@@ -84,16 +84,58 @@ import { writtenStatement_pdf } from "../../../components/pdftemplates/writtenSt
import { other_pdf } from "../../../components/pdftemplates/other_pdf";
import { consoleLogger } from "../../../actions/core/logger";
import { respondError, respondSuccess } from "../middleware/apiResponse";
+import { getServerSession } from "next-auth/next";
+import { authOptions } from "../auth/[...nextauth]";
//const ApiProxy = nextConnect();
// ApiProxy.use(middleware);
// ApiProxy.post(async (req, res) => {
+const isValidContainer = (value) =>
+ typeof value === "string" &&
+ value.length >= 3 &&
+ value.length <= 63 &&
+ /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
+
+const isValidDraftFolder = (value) =>
+ typeof value === "string" &&
+ value.length <= 100 &&
+ !value.includes("..") &&
+ /^[A-Za-z0-9](?:[A-Za-z0-9/-]*[A-Za-z0-9])?$/.test(value);
+
+const forbidden = (res) =>
+ respondError(res, {
+ status: 403,
+ code: "FORBIDDEN",
+ message: "Request not permitted"
+ });
+
export default async function handler(req, res) {
const shouldDownload = req.query.download === "true";
const checkHash = req.query.hash;
- let reqBodyobj =
- typeof req.body === "string" ? JSON.parse(req.body) : req.body;
+ let reqBodyobj;
+ try {
+ reqBodyobj =
+ typeof req.body === "string" ? JSON.parse(req.body) : req.body;
+ } catch (_error) {
+ return respondError(res, {
+ status: 400,
+ code: "INVALID_REQUEST",
+ message: "Invalid request"
+ });
+ }
+
+ if (
+ !reqBodyobj ||
+ typeof reqBodyobj !== "object" ||
+ Array.isArray(reqBodyobj)
+ ) {
+ return respondError(res, {
+ status: 400,
+ code: "INVALID_REQUEST",
+ message: "Invalid request"
+ });
+ }
const cleanFilesList = (blobList) => {
let newblobList = Array.isArray(blobList?.filesList)
@@ -164,7 +206,54 @@ export default async function handler(req, res) {
checkquerypath += "?download=true";
}
- if (typeof checkHash === "undefined" || checkHash.length === 0) {
+ if (
+ typeof containerID === "undefined" ||
+ String(containerID).length === 0 ||
+ typeof caseRef === "undefined" ||
+ String(caseRef).length === 0
+ ) {
+ return respondError(res, {
+ status: 400,
+ code: "MISSING_REQUIRED_QUERY",
+ message: "containerID and case reference are required"
+ });
+ }
+
+ if (
+ !isValidContainer(containerID) ||
+ !isValidDraftFolder(caseRef) ||
+ ["ticketnumber", "caseRef"].some(
+ (key) =>
+ Object.prototype.hasOwnProperty.call(reqBodyobj, key) &&
+ !isValidDraftFolder(reqBodyobj[key])
+ ) ||
+ (typeof req.query.download !== "undefined" &&
+ typeof req.query.download !== "string") ||
+ [
+ "container",
+ "containerID",
+ "casefolderID",
+ "caseRef",
+ "ticketnumber"
+ ].some((key) => Object.prototype.hasOwnProperty.call(req.query, key))
+ ) {
+ return respondError(res, {
+ status: 400,
+ code: "INVALID_REQUEST",
+ message: "Invalid request"
+ });
+ }
+
+ const session = await getServerSession(req, res, authOptions(req, res));
+ if (
+ typeof session?.user?.id !== "string" ||
+ session.user.id.length === 0 ||
+ session.user.id !== containerID
+ ) {
+ return forbidden(res);
+ }
+
+ if (typeof checkHash !== "string" || checkHash.length === 0) {
return respondError(res, {
status: 400,
code: "HASH_REQUIRED",
diff --git a/pages/api/file/getawaitingsubmissionfromblobproxy.js b/pages/api/file/getawaitingsubmissionfromblobproxy.js
index 3dcda590..8b2ceb6e 100644
--- a/pages/api/file/getawaitingsubmissionfromblobproxy.js
+++ b/pages/api/file/getawaitingsubmissionfromblobproxy.js
@@ -4,16 +4,38 @@ import { consoleLogger } from "../../../actions/core/logger";
import { hashAPIPath } from "../../../actions/core/hash";
import axios from "axios";
import { respondError, respondSuccess } from "../middleware/apiResponse";
+import { getServerSession } from "next-auth/next";
+import { authOptions } from "../auth/[...nextauth]";
const BASE_URL = process.env.API_ROOT || `http://localhost:${port}`;
-const hasValue = (value) =>
- typeof value === "string" && value.trim().length > 0;
+const forbidden = (res) =>
+ respondError(res, {
+ status: 403,
+ code: "FORBIDDEN",
+ message: "Request not permitted"
+ });
+
+const isValidContainer = (value) =>
+ typeof value === "string" &&
+ value.length >= 3 &&
+ value.length <= 63 &&
+ /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
export default async function ApiProxy(req, res) {
+ res.setHeader("Allow", "GET");
+
+ if (req.method !== "GET") {
+ return respondError(res, {
+ status: 405,
+ code: "METHOD_NOT_ALLOWED",
+ message: "Method not allowed"
+ });
+ }
+
const containerName = req.query.container;
- if (!hasValue(containerName)) {
+ if (typeof containerName === "undefined" || containerName === "") {
return respondError(res, {
status: 400,
code: "MISSING_REQUIRED_QUERY",
@@ -21,10 +43,28 @@ export default async function ApiProxy(req, res) {
});
}
+ if (!isValidContainer(containerName)) {
+ return respondError(res, {
+ status: 400,
+ code: "INVALID_REQUEST",
+ message: "Invalid request"
+ });
+ }
+
+ const session = await getServerSession(req, res, authOptions(req, res));
+ if (
+ typeof session?.user?.id !== "string" ||
+ session.user.id.length === 0 ||
+ session.user.id !== containerName
+ ) {
+ return forbidden(res);
+ }
+
const token = await getToken();
const queryUrl =
- "/api/file/getawaitingsubmissionfromblob?container=" + containerName;
+ "/api/file/getawaitingsubmissionfromblob?container=" +
+ encodeURIComponent(containerName);
try {
const { data } = await axios.get(
diff --git a/pages/api/file/getbloblistproxy.js b/pages/api/file/getbloblistproxy.js
index 6dd29acf..7881099a 100644
--- a/pages/api/file/getbloblistproxy.js
+++ b/pages/api/file/getbloblistproxy.js
@@ -4,13 +4,38 @@ import { consoleLogger } from "../../../actions/core/logger";
import { hashAPIPath } from "../../../actions/core/hash";
import axios from "axios";
import { respondError, respondSuccess } from "../middleware/apiResponse";
+import { getServerSession } from "next-auth/next";
+import { authOptions } from "../auth/[...nextauth]";
const BASE_URL = process.env.API_ROOT || `http://localhost:${port}`;
const hasValue = (value) =>
typeof value === "string" && value.trim().length > 0;
+const forbidden = (res) =>
+ respondError(res, {
+ status: 403,
+ code: "FORBIDDEN",
+ message: "Request not permitted"
+ });
+
+const isValidContainer = (value) =>
+ typeof value === "string" &&
+ value.length >= 3 &&
+ value.length <= 63 &&
+ /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
+
export default async function ApiProxy(req, res) {
+ res.setHeader("Allow", "GET");
+
+ if (req.method !== "GET") {
+ return respondError(res, {
+ status: 405,
+ code: "METHOD_NOT_ALLOWED",
+ message: "Method not allowed"
+ });
+ }
+
const containerName = req.query.container;
const casefolderID = req.query.casefolderID;
@@ -22,6 +47,23 @@ export default async function ApiProxy(req, res) {
});
}
+ if (!isValidContainer(containerName)) {
+ return respondError(res, {
+ status: 400,
+ code: "INVALID_REQUEST",
+ message: "Invalid request"
+ });
+ }
+
+ const session = await getServerSession(req, res, authOptions(req, res));
+ if (
+ typeof session?.user?.id !== "string" ||
+ session.user.id.length === 0 ||
+ session.user.id !== containerName
+ ) {
+ return forbidden(res);
+ }
+
const token = await getToken();
const queryUrl =
diff --git a/pages/api/file/getrepsblob.js b/pages/api/file/getrepsblob.js
index 45dff296..ef58e15e 100644
--- a/pages/api/file/getrepsblob.js
+++ b/pages/api/file/getrepsblob.js
@@ -38,10 +38,23 @@ import middleware from "../middleware/middleware";
import { hashAPIPath } from "../../../actions/core/hash";
import { consoleLogger } from "../../../actions/core/logger";
import { respondError, respondSuccess } from "../middleware/apiResponse";
+import { getServerSession } from "next-auth/next";
+import { authOptions } from "../auth/[...nextauth]";
+import {
+ readAdminSessionCookie,
+ validateAdminSession
+} from "../../../lib/admin/adminAuth";
const ApiProxy = nextConnect();
ApiProxy.use(middleware);
+const forbidden = (res) =>
+ respondError(res, {
+ status: 403,
+ code: "FORBIDDEN",
+ message: "Request not permitted"
+ });
+
ApiProxy.get(async (req, res) => {
const containerName = req.query.container;
const checkHash = req.query.hash;
@@ -59,6 +72,17 @@ ApiProxy.get(async (req, res) => {
});
}
+ const session = await getServerSession(req, res, authOptions(req, res));
+ const isPortalOwner =
+ typeof session?.user?.id === "string" &&
+ session.user.id.length > 0 &&
+ session.user.id === containerName;
+ const isAdministrator = validateAdminSession(readAdminSessionCookie(req));
+
+ if (!isPortalOwner && !isAdministrator) {
+ return forbidden(res);
+ }
+
const hashCandidatePaths = [
"/api/file/getrepsblob?container=" + containerName,
"/api/file/getrepsblob?container=" + encodeURIComponent(containerName)
diff --git a/pages/api/file/getrepsblobproxy.js b/pages/api/file/getrepsblobproxy.js
index 64a02e54..126237e6 100644
--- a/pages/api/file/getrepsblobproxy.js
+++ b/pages/api/file/getrepsblobproxy.js
@@ -1,19 +1,51 @@
+import { BASE_URL } from "../../../actions/core/env";
import { getToken } from "../../../actions/core/token";
import { azureHeaders } from "../../../actions/core/headers";
import { consoleLogger } from "../../../actions/core/logger";
import { hashAPIPath } from "../../../actions/core/hash";
import axios from "axios";
import { respondError, respondSuccess } from "../middleware/apiResponse";
+import { getServerSession } from "next-auth/next";
+import { authOptions } from "../auth/[...nextauth]";
-const BASE_URL = process.env.API_ROOT || `http://localhost:${port}`;
+const isTrustedInternalDestination = () => {
+ try {
+ return (
+ new URL(BASE_URL).origin ===
+ new URL(process.env.NEXTAUTH_URL).origin
+ );
+ } catch {
+ return false;
+ }
+};
-const hasValue = (value) =>
- typeof value === "string" && value.trim().length > 0;
+const forbidden = (res) =>
+ respondError(res, {
+ status: 403,
+ code: "FORBIDDEN",
+ message: "Request not permitted"
+ });
+
+const isValidContainer = (value) =>
+ typeof value === "string" &&
+ value.length >= 3 &&
+ value.length <= 63 &&
+ /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
export default async function ApiProxy(req, res) {
+ res.setHeader("Allow", "GET");
+
+ if (req.method !== "GET") {
+ return respondError(res, {
+ status: 405,
+ code: "METHOD_NOT_ALLOWED",
+ message: "Method not allowed"
+ });
+ }
+
const containerName = req.query.container;
- if (!hasValue(containerName)) {
+ if (typeof containerName === "undefined" || containerName === "") {
return respondError(res, {
status: 400,
code: "MISSING_REQUIRED_QUERY",
@@ -21,15 +53,45 @@ export default async function ApiProxy(req, res) {
});
}
+ if (!isValidContainer(containerName)) {
+ return respondError(res, {
+ status: 400,
+ code: "INVALID_REQUEST",
+ message: "Invalid request"
+ });
+ }
+
+ const session = await getServerSession(req, res, authOptions(req, res));
+ if (
+ typeof session?.user?.id !== "string" ||
+ session.user.id.length === 0 ||
+ session.user.id !== containerName
+ ) {
+ return forbidden(res);
+ }
+
+ if (!isTrustedInternalDestination()) {
+ return forbidden(res);
+ }
+
const token = await getToken();
const queryUrl =
"/api/file/getrepsblob?container=" + encodeURIComponent(containerName);
try {
+ const config = azureHeaders(token.access_token);
+
const { data } = await axios.get(
BASE_URL + queryUrl + hashAPIPath(queryUrl),
- azureHeaders(token.access_token)
+ {
+ ...config,
+ headers: {
+ ...config.headers,
+ Cookie: req.headers.cookie || ""
+ },
+ maxRedirects: 0
+ }
);
return respondSuccess(res, data);
} catch (error) {
diff --git a/pages/api/file/upload.js b/pages/api/file/upload.js
index c4423a08..f7687e43 100644
--- a/pages/api/file/upload.js
+++ b/pages/api/file/upload.js
@@ -1,6 +1,8 @@
import { createBlob, createRepBlob } from "../../../actions/azurestorage";
import { hashAPIPath } from "../../../actions/core/hash";
import { respondError, respondSuccess } from "../middleware/apiResponse";
+import { getServerSession } from "next-auth/next";
+import { authOptions } from "../auth/[...nextauth]";
import nextConnect from "next-connect";
import middleware from "../middleware/middleware";
@@ -8,9 +10,48 @@ import middleware from "../middleware/middleware";
const ApiProxy = nextConnect();
ApiProxy.use(middleware);
+const unauthenticated = (res) =>
+ respondError(res, {
+ status: 401,
+ code: "UNAUTHENTICATED",
+ message: "Authentication required"
+ });
+
+const forbidden = (res) =>
+ respondError(res, {
+ status: 403,
+ code: "FORBIDDEN",
+ message: "Request not permitted"
+ });
+
ApiProxy.post(async (req, res) => {
const getFieldValue = (field) => (Array.isArray(field) ? field[0] : field);
+ const session = await getServerSession(req, res, authOptions(req, res));
+ if (
+ typeof session?.user?.id !== "string" ||
+ session.user.id.length === 0
+ ) {
+ return unauthenticated(res);
+ }
+
+ const appealData = getFieldValue(req.body?.appealData);
+ const containerID = getFieldValue(req.body?.containerID);
+ const casefolderID = getFieldValue(req.body?.casefolderID);
+ const repOrAppealRaw = getFieldValue(req.body?.repOrAppeal);
+ const repOrAppeal =
+ repOrAppealRaw === true ||
+ repOrAppealRaw === "true" ||
+ repOrAppealRaw === "1";
+
+ if (
+ typeof containerID !== "undefined" &&
+ containerID.length > 0 &&
+ session.user.id !== containerID
+ ) {
+ return forbidden(res);
+ }
+
const checkHash = req.query.hash;
if (typeof checkHash === "undefined" || checkHash.length === 0) {
@@ -34,15 +75,6 @@ ApiProxy.post(async (req, res) => {
});
}
- const appealData = getFieldValue(req.body?.appealData);
- const containerID = getFieldValue(req.body?.containerID);
- const casefolderID = getFieldValue(req.body?.casefolderID);
- const repOrAppealRaw = getFieldValue(req.body?.repOrAppeal);
- const repOrAppeal =
- repOrAppealRaw === true ||
- repOrAppealRaw === "true" ||
- repOrAppealRaw === "1";
-
if (
typeof containerID === "undefined" ||
containerID.length === 0 ||
diff --git a/pages/api/file/uploadsinglefile.js b/pages/api/file/uploadsinglefile.js
index a89d1961..8d3e554c 100644
--- a/pages/api/file/uploadsinglefile.js
+++ b/pages/api/file/uploadsinglefile.js
@@ -6,6 +6,8 @@ import { consoleLogger } from "../../../actions/core/logger";
import { hashAPIPath } from "../../../actions/core/hash";
import { respondError, respondSuccess } from "../middleware/apiResponse";
import { fileTypeFromBuffer } from "file-type";
+import { getServerSession } from "next-auth/next";
+import { authOptions } from "../auth/[...nextauth]";
import fs from "fs";
import path from "path";
@@ -36,7 +38,40 @@ function validateFilenameServer(originalFilename) {
const ApiProxy = nextConnect();
ApiProxy.use(middleware);
+const unauthenticated = (res) =>
+ respondError(res, {
+ status: 401,
+ code: "UNAUTHENTICATED",
+ message: "Authentication required"
+ });
+
+const forbidden = (res) =>
+ respondError(res, {
+ status: 403,
+ code: "FORBIDDEN",
+ message: "Request not permitted"
+ });
+
ApiProxy.post(async (req, res) => {
+ const session = await getServerSession(req, res, authOptions(req, res));
+ if (
+ typeof session?.user?.id !== "string" ||
+ session.user.id.length === 0
+ ) {
+ return unauthenticated(res);
+ }
+
+ const containerID = req.body?.containerID?.[0];
+ const casefolderID = req.body?.casefolderID?.[0];
+
+ if (
+ typeof containerID !== "undefined" &&
+ containerID.length > 0 &&
+ session.user.id !== containerID
+ ) {
+ return forbidden(res);
+ }
+
const checkHash = req.query.hash;
if (typeof checkHash === "undefined" || checkHash.length === 0) {
@@ -63,9 +98,6 @@ ApiProxy.post(async (req, res) => {
});
}
- const containerID = req.body?.containerID?.[0];
- const casefolderID = req.body?.casefolderID?.[0];
-
if (
typeof containerID === "undefined" ||
containerID.length === 0 ||
diff --git a/pages/auth/signin.js b/pages/auth/signin.js
index 1015c343..c03c9cb9 100644
--- a/pages/auth/signin.js
+++ b/pages/auth/signin.js
@@ -7,7 +7,7 @@ import CookieBanner from "../../components/cookieBanner";
import Footer from "../../components/footer";
import Header from "../../components/header";
import ServiceBanner from "../../components/servicebanner";
-import { setCookie } from "nookies";
+import { setCookie } from "../../lib/cookies";
const SignIn = (props) => {
let { t, lang } = useTranslation();
diff --git a/pages/error.js b/pages/error.js
index c1de6a39..be5a1f19 100644
--- a/pages/error.js
+++ b/pages/error.js
@@ -2,7 +2,7 @@ import { signOut, useSession } from "next-auth/react";
import useTranslation from "next-translate/useTranslation";
import Head from "next/head";
import Router from "next/router";
-import { destroyCookie } from "nookies";
+import { destroyCookie } from "../lib/cookies";
import CookieBanner from "../components/cookieBanner";
import Footer from "../components/footer";
import Header from "../components/header";
diff --git a/pages/index.js b/pages/index.js
index 16f1b749..d8026ffb 100644
--- a/pages/index.js
+++ b/pages/index.js
@@ -3,7 +3,7 @@ import { getSession } from "next-auth/react";
import useTranslation from "next-translate/useTranslation";
import Head from "next/head";
import { useRouter } from "next/router";
-import { setCookie } from "nookies";
+import { setCookie } from "../lib/cookies";
import { connect } from "react-redux";
import { hashString } from "../actions/core/hash";
import { getIP } from "../actions/core/logger";
diff --git a/pages/myportal/case/[ticketnumber].js b/pages/myportal/case/[ticketnumber].js
index 04859115..9a28f691 100644
--- a/pages/myportal/case/[ticketnumber].js
+++ b/pages/myportal/case/[ticketnumber].js
@@ -304,7 +304,8 @@ export const getServerSideProps = wrapper.getServerSideProps(
break;
case "myRepresentations":
const myRepresentations = await getRepsFromBlob(
- thisSession.user.id
+ thisSession.user.id,
+ { headers: { Cookie: req.headers.cookie || "" } }
);
const myRepresentationsDetails = await getDetails(
diff --git a/pages/myportal/index.js b/pages/myportal/index.js
index dfc737c9..4c0195e0 100644
--- a/pages/myportal/index.js
+++ b/pages/myportal/index.js
@@ -7,10 +7,8 @@ import pLimit from "p-limit";
import { getIP } from "../../actions/core/logger";
import { consoleLogger } from "../../actions/core/logger";
-import {
- getPersonalAccount,
- getPortalLogin
-} from "../../actions/services/accountService";
+import { getPortalLogin } from "../../actions/services/accountService";
+import { getCrmPersonalAccount } from "../../lib/server/getCrmPersonalAccount";
import {
getCase,
getPortalModuleDetails
@@ -257,9 +255,25 @@ export const getServerSideProps = wrapper.getServerSideProps(
}
await createContainerProxy(thisSession.user.id);
- const accountDetails = await getPersonalAccount(loggedInUser);
- if (accountDetails?.errorCode) {
+ let accountDetails;
+
+ try {
+ accountDetails = await getCrmPersonalAccount(loggedInUser);
+ } catch (error) {
+ consoleLogger({
+ name: "MyPortalIndexAccountLookup",
+ reasonCode: "UPSTREAM_FAILURE",
+ message: "myportal index personal account lookup failed",
+ error: error?.message
+ });
+
+ return {
+ redirect: { destination: "/myportal/error", permanent: false }
+ };
+ }
+
+ if (!accountDetails || accountDetails.errorCode) {
return {
redirect: { destination: "/myportal/error", permanent: false }
};
@@ -279,7 +293,9 @@ export const getServerSideProps = wrapper.getServerSideProps(
awaitingSubmissionFromBlob
] = await Promise.all([
isLPA ? getMyLPACases(lpaId) : getMyCases(loggedInUser),
- getRepsFromBlob(thisSession.user.id),
+ getRepsFromBlob(thisSession.user.id, {
+ headers: { Cookie: req.headers.cookie || "" }
+ }),
getWatchedCases(loggedInUser),
getAwaitingSubmissionFromBlob(thisSession.user.id)
]);
diff --git a/pages/myportal/viewall.js b/pages/myportal/viewall.js
index 46aa4cbc..4db131b6 100644
--- a/pages/myportal/viewall.js
+++ b/pages/myportal/viewall.js
@@ -14,10 +14,9 @@ import ServiceBanner from "../../components/myportal/servicebanner";
import { getSession } from "next-auth/react";
import pLimit from "p-limit";
-import {
- getPersonalAccount,
- getPortalLogin
-} from "../../actions/services/accountService";
+import { getPortalLogin } from "../../actions/services/accountService";
+import { getCrmPersonalAccount } from "../../lib/server/getCrmPersonalAccount";
+import { consoleLogger } from "../../actions/core/logger";
import { getPortalModuleDetails } from "../../actions/services/caseService";
@@ -189,7 +188,25 @@ export const getServerSideProps = wrapper.getServerSideProps(
};
}
- const accountDetails = await getPersonalAccount(loggedInUser);
+ let accountDetails;
+
+ try {
+ accountDetails = await getCrmPersonalAccount(loggedInUser);
+ } catch (error) {
+ consoleLogger({
+ name: "MyPortalViewAllAccountLookup",
+ reasonCode: "UPSTREAM_FAILURE",
+ message: "myportal viewall personal account lookup failed",
+ error: error?.message
+ });
+
+ return {
+ redirect: {
+ destination: "/myportal/error",
+ permanent: false
+ }
+ };
+ }
if (!accountDetails || accountDetails.errorCode) {
return {
@@ -354,7 +371,8 @@ export const getServerSideProps = wrapper.getServerSideProps(
case "myRepresentations": {
const myRepresentations = await getRepsFromBlob(
- thisSession.user.id
+ thisSession.user.id,
+ { headers: { Cookie: ctx.req?.headers?.cookie || "" } }
);
// The existing View All component reads
diff --git a/pwe2e/tests/apiTests/api.spec.js b/pwe2e/tests/apiTests/api.spec.js
deleted file mode 100644
index 0e5847bd..00000000
--- a/pwe2e/tests/apiTests/api.spec.js
+++ /dev/null
@@ -1,82 +0,0 @@
-import { test, expect } from "@playwright/test";
-
-// TO DO - build PEDW API playwright harness
-
-// Define a base URL for the mock API
-const BASE_URL = process.env.BASE_URL;
-
-test.describe("User API Validation Suite", () => {
- // 1. GET Request Example
- test("should fetch a list of users and validate headers", async ({
- request,
- }) => {
- const response = await request.get(`${BASE_URL}/users/1`);
-
- // Assert the HTTP status code is 200 OK
- expect(response.ok()).toBeTruthy();
- expect(response.status()).toBe(200);
-
- // Parse the JSON response body
- const responseBody = await response.json();
-
- // Assert specific data fields inside the JSON
- expect(responseBody.id).toBe(1);
- expect(responseBody.name).toBe("Leanne Graham");
- expect(responseBody.email).toBe("Sincere@april.biz");
-
- // Assert response headers
- expect(response.headers()["content-type"]).toContain("application/json");
- });
-
- // 2. POST Request Example
- test("should successfully create a new post", async ({ request }) => {
- const response = await request.post(`${BASE_URL}/posts`, {
- headers: {
- "Content-type": "application/json; charset=UTF-8",
- // 'Authorization': `Bearer ${process.env.API_TOKEN}` <-- Example for CI/CD tokens
- },
- data: {
- title: "Automation Test",
- body: "Testing APIs with Playwright in DevOps pipelines.",
- userId: 99,
- },
- });
-
- // Assert creation status code (201 Created)
- expect(response.status()).toBe(201);
-
- const responseBody = await response.json();
-
- // Assert the API returned our sent data with a new generated ID
- expect(responseBody).toMatchObject({
- title: "Automation Test",
- body: "Testing APIs with Playwright in DevOps pipelines.",
- userId: 99,
- id: 101, // Mock database increments ID to 101
- });
- });
-
- // 3. PUT Request Example (Update)
- test("should update an existing post", async ({ request }) => {
- const response = await request.put(`${BASE_URL}/posts/1`, {
- data: {
- id: 1,
- title: "Updated Title",
- body: "Updated body content",
- userId: 1,
- },
- });
-
- expect(response.ok()).toBeTruthy();
- const responseBody = await response.json();
- expect(responseBody.title).toBe("Updated Title");
- });
-
- // 4. DELETE Request Example
- test("should delete a post", async ({ request }) => {
- const response = await request.delete(`${BASE_URL}/posts/1`);
-
- // Assert successful deletion response status
- expect(response.status()).toBe(200);
- });
-});
diff --git a/pwe2e/tests/loggedin/downloadFile.spec.js b/pwe2e/tests/loggedin/downloadFile.spec.js
deleted file mode 100644
index 5ccc673d..00000000
--- a/pwe2e/tests/loggedin/downloadFile.spec.js
+++ /dev/null
@@ -1,27 +0,0 @@
-import { test, expect } from "@playwright/test";
-import { login } from "../../helpers";
-
-test("Download a file when logged in", async ({ page }) => {
- await login(page);
-
- await page
- .getByRole("textbox", { name: "Use the case reference or DNS" })
- .click();
- await page
- .getByRole("textbox", { name: "Use the case reference or DNS" })
- .fill("gaerwen");
- await page.getByRole("button", { name: "Submit search" }).click();
- // await page
- // .getByRole("link", { name: "DNS3276735 - Gaerwen Wind Farm (test)" })
- // .click();
-
- await page.locator("dd a.govuk-link--no-underline").first().click();
-
- const downloadPromise = page.waitForEvent("download");
-
- await page.locator(".documentLink").first().click();
-
- const download = await downloadPromise;
- await page.getByText("Download complete!").click();
- await page.getByRole("link", { name: "Home" }).click();
-});
diff --git a/pwe2e/tests/loggedin/newappeal.spec.js b/pwe2e/tests/loggedin/newappeal.spec.js
deleted file mode 100644
index 53ecfc51..00000000
--- a/pwe2e/tests/loggedin/newappeal.spec.js
+++ /dev/null
@@ -1,149 +0,0 @@
-import { test, expect } from "@playwright/test";
-import path from "path";
-import { login } from "../../helpers";
-
-const date = new Date();
-date.setDate(date.getDate() - 1); // 👈 subtract 1 day
-
-const day = date.getDate();
-
-const ordinal = (n) => {
- if (n > 3 && n < 21) return "th";
- switch (n % 10) {
- case 1:
- return "st";
- case 2:
- return "nd";
- case 3:
- return "rd";
- default:
- return "th";
- }
-};
-
-const weekday = date.toLocaleDateString("en-GB", { weekday: "long" });
-const month = date.toLocaleDateString("en-GB", { month: "long" });
-
-const finalDate = `${weekday}, ${month} ${day}${ordinal(day)}`;
-
-test("Login and Raise new appeal", async ({ page }) => {
- await login(page);
-
- // create new appeal
- await page.getByRole("link", { name: "Make a new appeal" }).click();
- await page
- .getByRole("textbox", { name: "Appellant or organisation's" })
- .click();
- await page
- .getByRole("textbox", { name: "Appellant or organisation's" })
- .fill("Bob");
- await page.getByText("Appellant", { exact: true }).click();
- await page.getByText("English").click();
- await page.getByText("I confirm that I am making an").click();
- await page.getByRole("button", { name: "Continue" }).click();
- await page
- .getByLabel("Select your Local Planning")
- .selectOption("b9aee444-6ff0-eb11-aac7-00224800be9c");
- await page.getByLabel("Select a case type").selectOption("846040000");
- await page.getByRole("button", { name: "Continue" }).click();
-
- await page.getByRole("button", { name: "Continue" }).click();
-
- const step2 = page.locator('[aria-controls="step-panel-appeal-details"]');
- await step2.click();
-
- await page.getByRole("textbox", { name: "Development description" }).click();
- await page
- .getByRole("textbox", { name: "Development description" })
- .fill("Something in here");
- await page.getByText("No", { exact: true }).click();
- await page
- .getByRole("textbox", { name: "LPA's application reference" })
- .click();
- await page
- .getByRole("textbox", { name: "LPA's application reference" })
- .fill("AB1234");
- await page.getByRole("textbox", { name: "Application form dated" }).click();
-
- await page.getByRole("option", { name: `Choose ${finalDate}` }).click();
- await page.getByLabel("Reason for appeal").selectOption("846040005");
- await page.getByRole("textbox", { name: "Site address line 1" }).click();
- await page
- .getByRole("textbox", { name: "Site address line 1" })
- .fill("1 High Road");
- await page.getByRole("textbox", { name: "Site address line 1" }).press("Tab");
- await page.getByRole("textbox", { name: "Site address line 2" }).press("Tab");
- await page
- .getByRole("textbox", { name: "Site address town" })
- .fill("Big town");
- await page.getByRole("textbox", { name: "Site address town" }).press("Tab");
- await page
- .getByRole("textbox", { name: "Site address county" })
- .fill("Cardiff");
- await page.getByRole("textbox", { name: "Site address county" }).press("Tab");
- await page
- .getByRole("textbox", { name: "Site address postcode" })
- .fill("cf21 3qa");
- await page
- .getByRole("textbox", { name: "Site address postcode" })
- .press("Tab");
- await page
- .getByRole("textbox", { name: "Size of overall appeal site (" })
- .fill("1");
- await page
- .getByRole("textbox", { name: "Size of overall appeal site (" })
- .press("Tab");
- await page
- .getByRole("textbox", { name: "What is the area of floor" })
- .fill("1");
- await page
- .getByRole("textbox", { name: "What is the area of floor" })
- .press("Tab");
- await page.getByRole("button", { name: "Continue" }).click();
- await page.getByText("Certificate A - (for sole").click();
- await page.getByText("(a) None of the land to which").click();
- await page.getByRole("button", { name: "Continue" }).click();
- await page.getByText("No").first().click();
- await page.getByText("No").nth(1).click();
- await page.getByText("No").nth(2).click();
- await page.getByRole("button", { name: "Continue" }).click();
- await page.getByText("No").first().click();
- await page.getByRole("button", { name: "Continue" }).click();
- // await page
- // .getByRole("paragraph")
- // .filter({ hasText: /^$/ })
- // .click();
- await page.locator(".ql-editor").fill("something here");
- await page.getByText("No").nth(1).click();
- await page
- .getByLabel("What procedure would you like")
- .selectOption("846040000");
- await page.getByText("No").nth(3).click();
- await page.getByText("No").nth(4).click();
- await page.getByText("YesNo").nth(2).click();
- await page.getByRole("button", { name: "Continue" }).click();
- // upload files to statement of case
- const files = [
- path.resolve(__dirname, "../../testFiles/file1.pdf"),
- path.resolve(__dirname, "../../testFiles/file2.pdf"),
- ];
-
- const fileInput = page.locator("#pinswg_fileUpload");
-
- await fileInput.setInputFiles(files);
- const uploadedFiles = page.locator("h4", { hasText: "Uploaded files" });
-
- await expect(uploadedFiles).toBeVisible({ timeout: 60000 });
-
- await page.getByRole("button", { name: "Submit" }).click();
- await page
- .getByRole("checkbox", { name: "I wish to download a copy of the form" })
- .check();
- await page
- .getByRole("checkbox", { name: "I confirm that all sections" })
- .check();
- await page.getByText("Submit appeal").click();
- await page.getByRole("link", { name: "Home" }).click();
- await page.goto("/");
- await page.waitForTimeout(20000);
-});
diff --git a/pwe2e/tests/loggedin/raiserep.spec.js b/pwe2e/tests/loggedin/raiserep.spec.js
deleted file mode 100644
index 08aaac1e..00000000
--- a/pwe2e/tests/loggedin/raiserep.spec.js
+++ /dev/null
@@ -1,729 +0,0 @@
-import { test, expect } from "@playwright/test";
-import {
- login,
- loginAgent,
- generatePlanningText,
- loginLPA,
- loginIP,
-} from "../../helpers";
-import path from "path";
-
-const today = new Date();
-
-// Add ordinal (st, nd, rd, th)
-const day = today.getDate();
-const ordinal = (n) => {
- if (n > 3 && n < 21) return "th";
- switch (n % 10) {
- case 1:
- return "st";
- case 2:
- return "nd";
- case 3:
- return "rd";
- default:
- return "th";
- }
-};
-const weekday = today.toLocaleDateString("en-GB", { weekday: "long" });
-const month = today.toLocaleDateString("en-GB", { month: "long" });
-
-const finalDate = `${weekday}, ${month} ${day}${ordinal(day)}`;
-
-const finalCommentsCase = process.env.FINAL_COMMENTS;
-const statementCase = process.env.STATEMENT;
-const questionnaireCase = process.env.QUESTIONNAIRE;
-const consultationCase = process.env.CONSULTATION;
-
-test("Raise Final Comments representation as an Appellant", async ({
- page,
-}) => {
- await login(page);
-
- await page.getByRole("textbox", { name: "Use the case reference" }).click();
- console.log("Value to fill:", finalCommentsCase);
- await page
- .getByRole("textbox", { name: "Use the case reference" })
- .fill(finalCommentsCase);
- await page.getByRole("button", { name: "Submit search" }).click();
- // await page
- // .getByRole("link", { name: "DNS3276735 - Gaerwen Wind Farm (test)" })
- // .click();
-
- await page.locator("dd a.govuk-link--no-underline").first().click();
-
- await page.getByRole("link", { name: "Make representation" }).click();
-
- await page.getByRole("radio", { name: "Appellant" }).check();
-
- await page.getByRole("button", { name: "Continue" }).click();
-
- await page.getByRole("radio", { name: "Final comments" }).check();
- await page.getByRole("button", { name: "Continue" }).click();
- await page.getByRole("paragraph").filter({ hasText: /^$/ }).click();
- await page
- .getByRole("group")
- .locator("div")
- .filter({ hasText: "Please note that all" })
- .locator("div")
- .nth(3)
- .fill("s");
- await page
- .locator("div")
- .filter({ hasText: /^s$/ })
- .nth(2)
- .fill("some text to go here.....");
-
- const files = [
- path.resolve(__dirname, "../../testFiles/file1.pdf"),
- path.resolve(__dirname, "../../testFiles/file2.pdf"),
- ];
-
- const fileInput = page.locator("#representationDocuments");
-
- await fileInput.setInputFiles(files);
- const uploadedFiles = page.locator("h4", { hasText: "Uploaded files" });
-
- await expect(uploadedFiles).toBeVisible({ timeout: 60000 });
-
- await page.getByRole("button", { name: "Continue" }).click();
- await page
- .getByRole("checkbox", { name: "I confirm I have read the" })
- .check();
- await page.getByRole("button", { name: "Continue" }).click();
- await page.getByRole("link", { name: "Continue" }).click();
- await page.goto("/");
-
- await page.waitForTimeout(2000);
-});
-
-test("Raise Final Comments representation as an Interested Party", async ({
- page,
-}) => {
- await loginIP(page);
- //raise rep
-
- await page.getByRole("textbox", { name: "Use the case reference" }).click();
- await page
- .getByRole("textbox", { name: "Use the case reference" })
- .fill(finalCommentsCase);
- await page.getByRole("button", { name: "Submit search" }).click();
-
- await page.locator("dd a.govuk-link--no-underline").first().click();
-
- await page.getByRole("link", { name: "Make representation" }).click();
-
- await page.getByRole("radio", { name: "Interested Party" }).check();
-
- await page.getByRole("button", { name: "Continue" }).click();
- await page.getByRole("radio", { name: "Final comments" }).check();
- await page.getByRole("button", { name: "Continue" }).click();
- await page.getByText("Yes").click();
- await page
- .getByRole("textbox", { name: "Enter the name of the company" })
- .click();
- await page
- .getByRole("textbox", { name: "Enter the name of the company" })
- .fill("Big Company");
- await page.getByRole("paragraph").filter({ hasText: /^$/ }).click();
- await page.locator(".ql-editor").fill(generatePlanningText(5));
-
- const files = [
- path.resolve(__dirname, "../../testFiles/file1.pdf"),
- path.resolve(__dirname, "../../testFiles/file2.pdf"),
- ];
-
- const fileInput = page.locator("#representationDocuments");
-
- await fileInput.setInputFiles(files);
- const uploadedFiles = page.locator("h4", { hasText: "Uploaded files" });
-
- await expect(uploadedFiles).toBeVisible({ timeout: 60000 });
-
- await page.getByRole("button", { name: "Continue" }).click();
- await page
- .getByRole("checkbox", { name: "I confirm I have read the" })
- .check();
- await page.getByRole("button", { name: "Continue" }).click();
- await page.getByRole("link", { name: "Continue" }).click();
- await page.goto("/");
-
- await page.waitForTimeout(2000);
-});
-
-test("Raise Statement representation as an Interested Party", async ({
- page,
-}) => {
- await loginIP(page);
- //raise rep
-
- await page.getByRole("textbox", { name: "Use the case reference" }).click();
- await page
- .getByRole("textbox", { name: "Use the case reference" })
- .fill(statementCase);
- await page.getByRole("button", { name: "Submit search" }).click();
-
- await page.locator("dd a.govuk-link--no-underline").first().click();
-
- await page.getByRole("link", { name: "Make representation" }).click();
-
- await page.getByRole("radio", { name: "Interested Party" }).check();
-
- await page.getByRole("button", { name: "Continue" }).click();
-
- await page.getByRole("radio", { name: "Statement" }).check();
- await page.getByRole("button", { name: "Continue" }).click();
-
- await page.getByText("Yes").click();
- await page
- .getByRole("textbox", { name: "Enter the name of the company" })
- .click();
- await page
- .getByRole("textbox", { name: "Enter the name of the company" })
- .fill("Big Company");
- await page.getByRole("paragraph").filter({ hasText: /^$/ }).click();
- await page.locator(".ql-editor").fill(generatePlanningText(5));
-
- const files = [
- path.resolve(__dirname, "../../testFiles/file1.pdf"),
- path.resolve(__dirname, "../../testFiles/file2.pdf"),
- ];
-
- const fileInput = page.locator("#representationDocuments");
-
- await fileInput.setInputFiles(files);
- const uploadedFiles = page.locator("h4", { hasText: "Uploaded files" });
-
- await expect(uploadedFiles).toBeVisible({ timeout: 60000 });
-
- await page.getByRole("button", { name: "Continue" }).click();
- await page
- .getByRole("checkbox", { name: "I confirm I have read the" })
- .check();
- await page.getByRole("button", { name: "Continue" }).click();
- await page.getByRole("link", { name: "Continue" }).click();
- await page.goto("/");
-
- await page.waitForTimeout(2000);
-});
-
-test("Raise Consultation Response as an Interested Party", async ({ page }) => {
- await loginIP(page);
- //raise rep
-
- await page.getByRole("textbox", { name: "Use the case reference" }).click();
- await page
- .getByRole("textbox", { name: "Use the case reference" })
- .fill(consultationCase);
- await page.getByRole("button", { name: "Submit search" }).click();
-
- await page.locator("dd a.govuk-link--no-underline").first().click();
-
- await page
- .getByRole("link", { name: "Submit a Consultation Response" })
- .click();
-
- await page.getByRole("radio", { name: "Interested Party" }).check();
-
- await page.getByRole("button", { name: "Continue" }).click();
-
- await page.getByRole("radio", { name: "Consultation Response" }).check();
- await page.getByRole("button", { name: "Continue" }).click();
- await page.getByText("Yes").click();
- await page
- .getByRole("textbox", { name: "Enter the name of the company" })
- .click();
- await page
- .getByRole("textbox", { name: "Enter the name of the company" })
- .fill("Big Company");
- await page.getByRole("paragraph").filter({ hasText: /^$/ }).click();
- await page.locator(".ql-editor").fill(generatePlanningText(5));
-
- const files = [
- path.resolve(__dirname, "../../testFiles/file1.pdf"),
- path.resolve(__dirname, "../../testFiles/file2.pdf"),
- ];
-
- const fileInput = page.locator("#representationDocuments");
-
- await fileInput.setInputFiles(files);
- const uploadedFiles = page.locator("h4", { hasText: "Uploaded files" });
-
- await expect(uploadedFiles).toBeVisible({ timeout: 60000 });
-
- await page.getByRole("button", { name: "Continue" }).click();
- await page
- .getByRole("checkbox", { name: "I confirm I have read the" })
- .check();
- await page.getByRole("button", { name: "Continue" }).click();
- await page.getByRole("link", { name: "Continue" }).click();
- await page.goto("/");
-
- await page.waitForTimeout(2000);
-});
-
-test("Raise LIR as an Interested Party", async ({ page }) => {
- await loginIP(page);
- //raise rep
-
- await page.getByRole("textbox", { name: "Use the case reference" }).click();
- await page
- .getByRole("textbox", { name: "Use the case reference" })
- .fill(consultationCase);
- await page.getByRole("button", { name: "Submit search" }).click();
-
- await page.locator("dd a.govuk-link--no-underline").first().click();
-
- await page
- .getByRole("link", { name: "Submit a Consultation Response" })
- .click();
-
- await page.getByRole("radio", { name: "Interested Party" }).check();
-
- await page.getByRole("button", { name: "Continue" }).click();
-
- await page.getByRole("radio", { name: "Local Impact Report" }).check();
- await page.getByRole("button", { name: "Continue" }).click();
-
- await page.getByText("Yes").click();
- await page
- .getByRole("textbox", { name: "Enter the name of the company" })
- .click();
- await page
- .getByRole("textbox", { name: "Enter the name of the company" })
- .fill("Big Company");
-
- const files = [
- path.resolve(__dirname, "../../testFiles/file1.pdf"),
- path.resolve(__dirname, "../../testFiles/file2.pdf"),
- ];
-
- const fileInput = page.locator("#representationDocuments");
-
- await fileInput.setInputFiles(files);
- const uploadedFiles = page.locator("h4", { hasText: "Uploaded files" });
-
- await expect(uploadedFiles).toBeVisible({ timeout: 60000 });
-
- await page.getByRole("button", { name: "Continue" }).click();
- await page
- .getByRole("checkbox", { name: "I confirm I have read the" })
- .check();
- await page.getByRole("button", { name: "Continue" }).click();
- await page.getByRole("link", { name: "Continue" }).click();
- await page.goto("/");
-
- await page.waitForTimeout(2000);
-});
-
-test("Raise MIR as an Interested Party", async ({ page }) => {
- await loginIP(page);
- //raise rep
-
- await page.getByRole("textbox", { name: "Use the case reference" }).click();
- await page
- .getByRole("textbox", { name: "Use the case reference" })
- .fill(consultationCase);
- await page.getByRole("button", { name: "Submit search" }).click();
-
- await page.locator("dd a.govuk-link--no-underline").first().click();
-
- await page
- .getByRole("link", { name: "Submit a Consultation Response" })
- .click();
-
- await page.getByRole("radio", { name: "Interested Party" }).check();
-
- await page.getByRole("button", { name: "Continue" }).click();
-
- await page.getByRole("radio", { name: "Marine Impact Report" }).check();
- await page.getByRole("button", { name: "Continue" }).click();
-
- await page.getByText("Yes").click();
- await page
- .getByRole("textbox", { name: "Enter the name of the company" })
- .click();
- await page
- .getByRole("textbox", { name: "Enter the name of the company" })
- .fill("Big Company");
-
- const files = [
- path.resolve(__dirname, "../../testFiles/file1.pdf"),
- path.resolve(__dirname, "../../testFiles/file2.pdf"),
- ];
-
- const fileInput = page.locator("#representationDocuments");
-
- await fileInput.setInputFiles(files);
- const uploadedFiles = page.locator("h4", { hasText: "Uploaded files" });
-
- await expect(uploadedFiles).toBeVisible({ timeout: 60000 });
-
- await page.getByRole("button", { name: "Continue" }).click();
- await page
- .getByRole("checkbox", { name: "I confirm I have read the" })
- .check();
- await page.getByRole("button", { name: "Continue" }).click();
- await page.getByRole("link", { name: "Continue" }).click();
- await page.goto("/");
-
- await page.waitForTimeout(2000);
-});
-
-test("Raise Final Comments representation as an Agent", async ({ page }) => {
- await loginAgent(page);
- //raise rep
-
- const acceptButton = page.getByRole("button", { name: "Accept cookies" });
-
- if (await acceptButton.isVisible()) {
- await acceptButton.click();
- }
-
- await page.getByRole("textbox", { name: "Use the case reference" }).click();
- await page
- .getByRole("textbox", { name: "Use the case reference" })
- .fill(finalCommentsCase);
- await page.getByRole("button", { name: "Submit search" }).click();
-
- await page.locator("dd a.govuk-link--no-underline").first().click();
-
- await page.getByRole("link", { name: "Make representation" }).click();
-
- await page.getByRole("radio", { name: "Agent" }).check();
-
- await page.getByRole("button", { name: "Continue" }).click();
- await page.getByRole("radio", { name: "Final comments" }).check();
- await page.getByRole("button", { name: "Continue" }).click();
- await page.getByText("Yes").click();
- await page
- .getByRole("textbox", { name: "Enter the name of the company" })
- .click();
- await page
- .getByRole("textbox", { name: "Enter the name of the company" })
- .fill("Big Company");
- await page.getByRole("paragraph").filter({ hasText: /^$/ }).click();
-
- await page.locator(".ql-editor").fill(generatePlanningText(4));
-
- const files = [
- path.resolve(__dirname, "../../testFiles/file1.pdf"),
- path.resolve(__dirname, "../../testFiles/file2.pdf"),
- ];
-
- const fileInput = page.locator("#representationDocuments");
-
- await fileInput.setInputFiles(files);
- const uploadedFiles = page.locator("h4", { hasText: "Uploaded files" });
-
- await expect(uploadedFiles).toBeVisible({ timeout: 60000 });
-
- await page.getByRole("button", { name: "Continue" }).click();
- await page
- .getByRole("checkbox", { name: "I confirm I have read the" })
- .check();
- await page.getByRole("button", { name: "Continue" }).click();
- await page.getByRole("link", { name: "Continue" }).click();
- await page.goto("/");
-
- await page.waitForTimeout(2000);
-});
-
-test("Raise Statement representation as an Agent", async ({ page }) => {
- await loginAgent(page);
- //raise rep
-
- await page.getByRole("textbox", { name: "Use the case reference" }).click();
- await page
- .getByRole("textbox", { name: "Use the case reference" })
- .fill(statementCase);
- await page.getByRole("button", { name: "Submit search" }).click();
-
- await page.locator("dd a.govuk-link--no-underline").first().click();
-
- await page.getByRole("link", { name: "Make representation" }).click();
-
- await page.getByRole("radio", { name: "Agent" }).check();
-
- await page.getByRole("button", { name: "Continue" }).click();
-
- await page.getByRole("radio", { name: "Statement" }).check();
- await page.getByRole("button", { name: "Continue" }).click();
-
- await page.getByText("Yes").click();
- await page
- .getByRole("textbox", { name: "Enter the name of the company" })
- .click();
- await page
- .getByRole("textbox", { name: "Enter the name of the company" })
- .fill("Big Company");
- await page.getByRole("paragraph").filter({ hasText: /^$/ }).click();
- await page.locator(".ql-editor").fill(generatePlanningText(5));
-
- const files = [
- path.resolve(__dirname, "../../testFiles/file1.pdf"),
- path.resolve(__dirname, "../../testFiles/file2.pdf"),
- ];
-
- const fileInput = page.locator("#representationDocuments");
-
- await fileInput.setInputFiles(files);
- const uploadedFiles = page.locator("h4", { hasText: "Uploaded files" });
-
- await expect(uploadedFiles).toBeVisible({ timeout: 60000 });
-
- await page.getByRole("button", { name: "Continue" }).click();
- await page
- .getByRole("checkbox", { name: "I confirm I have read the" })
- .check();
- await page.getByRole("button", { name: "Continue" }).click();
- await page.getByRole("link", { name: "Continue" }).click();
- await page.goto("/");
-
- await page.waitForTimeout(2000);
-});
-
-test("Raise questionnaire as an LPA", async ({ page }) => {
- await loginLPA(page);
-
- await page.getByRole("textbox", { name: "Use the case reference" }).click();
- await page
- .getByRole("textbox", { name: "Use the case reference" })
- .fill(questionnaireCase);
- await page.getByRole("textbox", { name: "Use the case reference," }).click();
- await page
- .getByRole("textbox", { name: "Use the case reference," })
- .fill(questionnaireCase);
- await page.getByRole("button", { name: "Submit Search" }).click();
- await page.getByRole("link", { name: questionnaireCase }).click();
- // await page.getByRole("button", { name: "Submit search" }).click();
-
- //await page.locator("dd a.govuk-link--no-underline").first().click();
-
- await page.getByRole("link", { name: "Make representation" }).click();
-
- await page.getByRole("radio", { name: "Questionnaire" }).check();
- await page.getByRole("button", { name: "Continue" }).click();
- await page.getByRole("combobox").selectOption("Written representations");
- await page.getByText("No").first().click();
- await page.getByText("No").nth(1).click();
- await page.getByText("No").nth(2).click();
- await page.getByText("Yes").nth(2).click();
- await page.getByText("No").nth(3).click();
- await page.getByRole("paragraph").filter({ hasText: /^$/ }).click();
- // await page.locator(".ql-editor").fill(generatePlanningText(2));
- // await page
- // .locator("div")
- // .filter({ hasText: /^w$/ })
- // .nth(2)
- // .fill(generatePlanningText(2));
- await page.getByRole("button", { name: "Continue" }).click();
- await page.locator(".ql-editor").first().fill(generatePlanningText(2));
- await page.locator(".ql-editor").nth(1).fill(generatePlanningText(2));
- await page.locator(".ql-editor").nth(2).fill(generatePlanningText(2));
-
- // // await page.getByRole("paragraph").nth(4).click();
- // await page
- // .locator(".ql-editor.ql-blank")
- // .first()
- // .fill(generatePlanningText(2));
- // await page.getByRole("paragraph").filter({ hasText: /^$/ }).click();
- // await page
- // .locator(".ql-editor.ql-blank")
- // .first()
- // .fill(generatePlanningText(2));
- // await page.locator(".ql-editor.ql-blank").fill("w e");
- // await page
- // .locator("div")
- // .filter({ hasText: /^w e$/ })
- // .nth(2)
- // .fill(generatePlanningText(2));
- // await page.getByRole("paragraph").filter({ hasText: /^$/ }).click();
- // await page
- // .locator("div")
- // .filter({ hasText: /^w e$/ })
- // .nth(2)
- // .fill(generatePlanningText(2));
- await page.getByText("No", { exact: true }).first().click();
- await page.getByRole("button", { name: "Continue" }).click();
- await page.getByText("No").first().click();
- await page.getByText("No").nth(1).click();
- await page.getByText("No").nth(2).click();
- await page.getByText("No").nth(3).click();
- await page.getByText("No").nth(4).click();
- await page.getByText("No").nth(5).click();
- await page
- .locator(
- "div:nth-child(8) > .govuk-form-group > .govuk-fieldset > .govuk-radios > div:nth-child(2) > .govuk-radios__item > .govuk-label",
- )
- .click();
- await page
- .locator(
- "div:nth-child(9) > .govuk-fieldset > .govuk-radios > div:nth-child(2) > .govuk-label",
- )
- .click();
- await page
- .locator(
- "div:nth-child(10) > .govuk-form-group > .govuk-fieldset > .govuk-radios > div:nth-child(2) > .govuk-radios__item > .govuk-label",
- )
- .click();
- await page.getByRole("button", { name: "Continue" }).click();
- await page.getByText("No").nth(2).click();
- await page.getByText("No").nth(3).click();
- await page.getByText("No").nth(5).click();
- await page.getByText("No", { exact: true }).nth(3).click();
- await page.getByText("No", { exact: true }).nth(4).click();
- await page.getByRole("button", { name: "Continue" }).click();
- await page.getByText("Yes").first().click();
- await page.getByText("Yes").nth(1).click();
- await page.getByText("No", { exact: true }).nth(2).click();
- await page.getByText("Yes").nth(2).click();
- await page.getByText("No", { exact: true }).nth(3).click();
- await page.getByText("No", { exact: true }).nth(4).click();
- await page.getByText("No", { exact: true }).nth(5).click();
- await page
- .locator(
- "div:nth-child(9) > .govuk-form-group > .govuk-fieldset > .govuk-radios > div:nth-child(2) > .govuk-radios__item > .govuk-label",
- )
- .click();
- await page
- .locator(
- "div:nth-child(10) > .govuk-form-group > .govuk-fieldset > .govuk-radios > div:nth-child(2) > .govuk-radios__item > .govuk-label",
- )
- .click();
- await page.getByRole("button", { name: "Continue" }).click();
- // await page.getByText("Drag and drop your files here").click();
-
- const files = [
- path.resolve(__dirname, "../../testFiles/file1.pdf"),
- path.resolve(__dirname, "../../testFiles/file2.pdf"),
- ];
-
- const fileInput = page.locator("#representationDocuments");
-
- await fileInput.setInputFiles(files);
- const uploadedFiles = page.locator("h4", { hasText: "Uploaded files" });
-
- await expect(uploadedFiles).toBeVisible({ timeout: 60000 });
-
- await page.getByRole("button", { name: "Continue" }).click();
- await page.getByRole("textbox", { name: "Signed" }).click();
- await page.getByRole("textbox", { name: "Signed" }).fill("Bob Bob");
- await page.getByRole("textbox", { name: "Date" }).click();
- await page.getByRole("option", { name: `Choose ${finalDate}` }).click();
- await page.getByRole("button", { name: "Continue" }).click();
- await page.getByText("I wish to download a copy of").click();
- await page
- .getByRole("checkbox", { name: "I confirm I have read the" })
- .check();
- const downloadPromise = page.waitForEvent("download");
- await page.getByRole("button", { name: "Continue" }).click();
- const download = await downloadPromise;
- await page.getByRole("link", { name: "Continue" }).click();
-
- await page.goto("/");
-
- await page.waitForTimeout(2000);
-});
-
-test("Raise Statement representation as an LPA", async ({ page }) => {
- await loginLPA(page);
- //raise rep
-
- await page.getByRole("textbox", { name: "Use the case reference" }).click();
- await page
- .getByRole("textbox", { name: "Use the case reference" })
- .fill(statementCase);
- await page.getByRole("button", { name: "Submit search" }).click();
-
- await page.locator("dd a.govuk-link--no-underline").first().click();
-
- await page.getByRole("link", { name: "Make representation" }).click();
-
- await page.getByRole("radio", { name: "Statement" }).check();
- await page.getByRole("button", { name: "Continue" }).click();
- await page.getByRole("paragraph").filter({ hasText: /^$/ }).click();
- await page.locator(".ql-editor").fill(generatePlanningText(5));
-
- const files = [
- path.resolve(__dirname, "../../testFiles/file1.pdf"),
- path.resolve(__dirname, "../../testFiles/file2.pdf"),
- ];
-
- const fileInput = page.locator("#representationDocuments");
-
- await fileInput.setInputFiles(files);
- const uploadedFiles = page.locator("h4", { hasText: "Uploaded files" });
-
- await expect(uploadedFiles).toBeVisible({ timeout: 60000 });
-
- await page.getByRole("button", { name: "Continue" }).click();
- await page
- .getByRole("checkbox", { name: "I confirm I have read the" })
- .check();
- await page.getByRole("button", { name: "Continue" }).click();
- await page.getByRole("link", { name: "Continue" }).click();
- await page.goto("/");
-
- await page.waitForTimeout(2000);
-});
-
-test("Raise LIR as an LPA", async ({ page }) => {
- await loginLPA(page);
- //raise rep
-
- await page.getByRole("textbox", { name: "Use the case reference" }).click();
- await page
- .getByRole("textbox", { name: "Use the case reference" })
- .fill(consultationCase);
- await page.getByRole("button", { name: "Submit search" }).click();
-
- await page.locator("dd a.govuk-link--no-underline").first().click();
-
- await page
- .getByRole("link", { name: "Submit a Consultation Response" })
- .click();
-
- await page.getByRole("radio", { name: "Local Impact Report" }).check();
- await page.getByRole("button", { name: "Continue" }).click();
-
- await page.getByRole("paragraph").filter({ hasText: /^$/ }).click();
- await page.locator(".ql-editor").fill(generatePlanningText(5));
- const files = [
- path.resolve(__dirname, "../../testFiles/file1.pdf"),
- path.resolve(__dirname, "../../testFiles/file2.pdf"),
- ];
-
- const fileInput = page.locator("#representationDocuments");
-
- await fileInput.setInputFiles(files);
- const uploadedFiles = page.locator("h4", { hasText: "Uploaded files" });
-
- await expect(uploadedFiles).toBeVisible({ timeout: 60000 });
-
- await page.getByRole("button", { name: "Continue" }).click();
- await page
- .getByRole("checkbox", { name: "I confirm I have read the" })
- .check();
- await page.getByRole("button", { name: "Continue" }).click();
- await page.getByRole("link", { name: "Continue" }).click();
- await page.goto("/");
-
- await page.waitForTimeout(2000);
-});
-
-test("Open Saved Rep as an Interested Party", async ({ page }) => {
- await loginIP(page);
- //raise rep
-
- const firstCaseLink = page
- .locator("#my-representations-card .govuk-link--no-underline")
- .first();
-
- await firstCaseLink.click();
-
- await page.getByRole("button", { name: "Save and exit" }).click();
- await page.goto("/");
-
- await page.waitForTimeout(2000);
-});
diff --git a/pwe2e/tests/loggedin/s78newappeal.spec.js b/pwe2e/tests/loggedin/s78newappeal.spec.js
deleted file mode 100644
index 6f9629ea..00000000
--- a/pwe2e/tests/loggedin/s78newappeal.spec.js
+++ /dev/null
@@ -1,377 +0,0 @@
-import { test, expect } from "@playwright/test";
-import path from "path";
-import * as XLSX from "xlsx";
-
-import {
- login,
- fillYesNoConditional,
- fillQuillEditor,
- toDDMMYYYY,
-} from "../../helpers";
-
-const workbook = XLSX.readFile("./testFiles/newappeals_s78.xlsx");
-const sheetName = workbook.SheetNames[0];
-const data = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], {
- defval: "",
- cellDates: true,
-});
-
-// console.log("sheetName :", sheetName);
-// console.log("Loaded rows:", data);
-
-data.forEach((row, index) => {
- test(`Import new appeal for ${row["Appellant / Organisation"]}`, async ({
- page,
- }) => {
- await login(page);
-
- await page.getByRole("link", { name: "Make a new appeal" }).click();
- await page
- .getByRole("textbox", { name: "Appellant or organisation's" })
- .click();
- await page
- .getByRole("textbox", { name: "Appellant or organisation's" })
- .fill(row["Appellant / Organisation"]);
-
- await page
- .getByRole("radio", { name: row["Appellant / Agent Radio Button"] })
- .click();
-
- await page.locator("#pinswg_appellantfirstname").fill(row["First Name"]);
- await page.locator("#pinswg_appellantlastname").fill(row["Last Name"]);
- await page.locator("#pinswg_appellantaddress").fill(row["Address"]);
- await page
- .locator("#pinswg_appellantemailaddress")
- .fill(row["Email Address"]);
- await page
- .locator("#pinswg_appellantphonenumber")
- .fill(row["Telephone Number"]);
-
- // Excel value: "English" or "Welsh"
- const languageText = row["Language Preference Radio Button"]?.trim();
-
- // Map Excel text to radio button value
- const radioValueLang = languageText === "Welsh" ? "846040001" : "846040000";
-
- // Select the radio by name and value
- await page
- .locator(
- `input[name="pinswg_languagepreference"][value="${radioValueLang}"]`
- )
- .check();
-
- if (row["Appellant / Agent Radio Button"] == "Agent") {
- await page.locator("#pinswg_agentcompanyname").fill(row["Company Name"]);
- await page
- .locator("#pinswg_agentreference")
- .fill(row["Agent's Reference"]);
-
- await page.locator("#pinswg_agentfirstname").fill(row["First Name_1"]);
- await page.locator("#pinswg_agentlastname").fill(row["Last Name_1"]);
- await page.locator("#pinswg_agentaddress").fill(row["Address_1"]);
- await page
- .locator("#pinswg_agentemailaddress")
- .fill(row["Email Address_1"]);
- await page
- .locator("#pinswg_agentphonenumber")
- .fill(row["Telephone Number_1"]);
-
- const agentLanguageText =
- row["Agent Language Preference Radio Button"]?.trim();
- const agentRadioValue =
- agentLanguageText === "Welsh" ? "846040001" : "846040000";
-
- await page
- .locator(
- `input[name="pinswg_agentlanguagepreference"][value="${agentRadioValue}"]`
- )
- .check();
- }
- await page.getByText("I confirm that I am making an").click();
- await page.getByRole("button", { name: "Continue" }).click();
- await page
- .getByLabel("Select your Local Planning")
- .selectOption({ label: row["Select LPA"] });
- await page.getByLabel("Select a case type").selectOption("846040000");
- await page.getByRole("button", { name: "Continue" }).click();
- await page.getByRole("button", { name: "Continue" }).click();
-
- const step2 = page.locator('[aria-controls="step-panel-appeal-details"]');
- await step2.click();
-
- await page
- .getByRole("textbox", { name: "Development description" })
- .click();
- await page
- .getByRole("textbox", { name: "Development description" })
- .fill(row["Development Description"]);
- await page.getByText("No", { exact: true }).click();
- await page
- .getByRole("textbox", { name: "LPA's application reference" })
- .fill(row["LPA's Application Ref Num"]);
-
- await page
- .locator("#pinswg_dateofapplication")
- .fill(toDDMMYYYY(row["App Form Dated"]));
- await page
- .getByLabel("Reason for appeal")
- .selectOption({ label: row["Reason for Appeal"] });
-
- await page.getByRole("textbox", { name: "Site address line 1" }).click();
- await page
- .getByRole("textbox", { name: "Site address line 1" })
- .fill(row["Site Address Line 1"]);
- await page
- .getByRole("textbox", { name: "Site address line 2" })
- .fill(row["Site Address Line 2"]);
- await page
- .getByRole("textbox", { name: "Site address town" })
- .fill(row["Site Address Town"]);
- await page
- .getByRole("textbox", { name: "Site address county" })
- .fill(row["Site Address County"]);
-
- await page
- .getByRole("textbox", { name: "Site address postcode" })
- .fill(row["Site Address Postcode"]);
-
- await page
- .getByRole("textbox", { name: "Size of overall appeal site (" })
- .fill(String(row["Size of Overall Appeal Site"]));
-
- await page
- .getByRole("textbox", { name: "What is the area of floor" })
- .fill(String(row["Floor Space (Sq Metres)"]));
- await page.getByRole("button", { name: "Continue" }).click();
-
- // Ownership Certificate selection and conditional fields
- const ownershipMap = {
- "Certificate A": "846040001",
- "Certificate B": "846040002",
- "Certificate C": "846040003",
- "Certificate D": "846040003", // C and D share same option
- };
-
- const cert = row["Ownership Certificate"]?.trim();
- const value = ownershipMap[cert];
-
- if (!value) throw new Error(`Unknown ownership certificate: ${cert}`);
-
- // Select the certificate radio
- await page
- .locator(`input[name="pinswg_ownershipcertificate"][value="${value}"]`)
- .check();
-
- // Conditional fields for Certificate B
- if (cert === "Certificate B") {
- // Wait for Owner Name input to appear (dynamic rendering)
- const ownerInput = page.locator(
- 'input[id^="pinswg_owners"][id$=".pinswg_owners"]'
- );
- await ownerInput.waitFor({ state: "visible", timeout: 5000 });
- await ownerInput.fill(row["Owner Name"] || "");
-
- // Wait for Date Served input to appear
- const dateServedInput = page.locator(
- ".react-datepicker__input-container input"
- );
- await dateServedInput.waitFor({ state: "visible", timeout: 5000 });
- await dateServedInput.fill(toDDMMYYYY(row["Date Served"]) || "");
- }
-
- // Ownership Certificate selection and conditional fields
- const agHoldingMap = {
- "(a)": "846040002",
- "(b) (i)": "846040001",
- "(b) (ii)": "846040000",
- };
-
- const agriculturalHolding = row["Agricultural Holding"]?.trim();
- const agValue = agHoldingMap[agriculturalHolding];
-
- if (!agValue) throw new Error(`Unknown ownership certificate: ${cert}`);
-
- // Select the certificate radio
- await page
- .locator(`input[name="pinswg_agriculturalholding"][value="${agValue}"]`)
- .check();
-
- // Conditional fields for b (ii)
- if (agriculturalHolding === "(b) (ii)") {
- // Wait for Owner Name input to appear (dynamic rendering)
- const tenantInput = page.locator(
- 'input[id^="pinswg_agriculturaltenantname"][id$=".pinswg_agriculturaltenantname"]'
- );
- await tenantInput.waitFor({ state: "visible", timeout: 5000 });
- await tenantInput.fill(row["Tenant Name"] || "");
-
- // Wait for Date Served input to appear
- const dateServedInput = page.locator(
- ".react-datepicker__input-container input"
- );
- await dateServedInput.waitFor({ state: "visible", timeout: 5000 });
- await dateServedInput.fill(toDDMMYYYY(row["Date Served_1"]) || "");
- }
-
- await page.getByRole("button", { name: "Continue" }).click();
-
- // Site viewable from road
- await fillYesNoConditional(
- page,
- "pinswg_siteviewablefromroad",
- row["See Relevant Parts?"],
- null,
- null
- );
-
- // Inspector needed on site
- await fillYesNoConditional(
- page,
- "pinswg_inspectorneededonsite",
- row["Essential to Enter?"],
- "#pinswg_whyisinspectorneededonsite",
- row["Please Explain (Enter)"]
- );
-
- // Health & safety issues
- await fillYesNoConditional(
- page,
- "pinswg_healthandsafetyissuesonsite",
- row["Any H&S Issues?"],
- "#pinswg_outlinehealthandsafetyissuesonsite",
- row["Set out H&S Issues"]
- );
-
- await page.getByRole("button", { name: "Continue" }).click();
-
- // Step 5 Other Appeals
-
- await fillYesNoConditional(
- page,
- "pinswg_additionalappealsmade", // radio name
- row["Any Other Appeals?"], // "Y" or blank from Excel
- "#pinswg_additionalappealsmadedetails", // Quill editor selector
- row["Other Appeal Details"], // text to fill
- false // flag that it's a Quill editor
- );
-
- await page.getByRole("button", { name: "Continue" }).click();
-
- // Step 6 Submission of Case
-
- // Q.1
- const subnissionOfCaseInput = page.locator(".ql-editor");
- await subnissionOfCaseInput.waitFor({ state: "visible", timeout: 100000 });
- await subnissionOfCaseInput.fill(row["Submit Statement of Case"]);
-
- // Q.2
- const attachSocValue = (row["Attached Separate Case Doc?"] || "")
- .trim()
- .toUpperCase();
-
- const radioValue = attachSocValue === "Y" ? "true" : "false";
-
- // Select the radio
- await page
- .locator(`input[name="pinswg_attachsoc"][value="${radioValue}"]`)
- .check();
-
- // Q.3
- const procedureValue = row["What Procedure?"]?.trim(); // e.g., "Written representation"
-
- // Wait for the dropdown to appear
- const procedureSelect = page.locator("#pinswg_procedure");
- await procedureSelect.waitFor({ state: "visible", timeout: 5000 });
-
- // Select by label (the visible text)
- await procedureSelect.selectOption({ label: procedureValue });
-
- // If not "Written representation", fill the explanation box
- if (
- procedureValue &&
- procedureValue.toLowerCase() !== "written representation"
- ) {
- const explanation =
- row["Procedure Explanation"] ||
- "Default explanation: A hearing/inquiry is required due to case complexity and witnesses.";
-
- const textArea = page.locator("#pinswg_chosenprocedureexplanation");
- await textArea.waitFor({ state: "visible", timeout: 5000 });
- await textArea.fill(explanation);
- }
-
- // Q.4
- await fillYesNoConditional(
- page,
- "pinswg_costappliedforindicator", // radio name
- row["Cost Applied For"], // "Y" or blank from Excel
- ".ql-editor", // Quill editor selector
- row["Cost Application"], // text to fill
- true // flag that it's a Quill editor
- );
-
- // Q.5
- await fillYesNoConditional(
- page,
- "pinswg_s106unilateralsubmitted", // radio name
- row["Submit S106?"] // "Y" or blank from Excel
- );
-
- await page.getByRole("button", { name: "Continue" }).click();
-
- // Step 7 Upload Documents
-
- const files = [
- path.resolve(__dirname, "../../testFiles/file1.pdf"),
- path.resolve(__dirname, "../../testFiles/file2.pdf"),
- ];
-
- const firstInputFiles = [
- path.resolve(__dirname, "../../testFiles/file1.pdf"),
- ];
-
- const fileInputs = [
- "#pinswg_fileUpload",
- "#pinswg_fileUpload1",
- "#pinswg_fileUpload2",
- "#pinswg_fileUpload3",
- "#pinswg_fileUpload4",
- "#pinswg_fileUpload5",
- "#pinswg_fileUpload6",
- "#pinswg_fileUpload7",
- "#pinswg_fileUpload8",
- "#pinswg_fileUpload9",
- "#pinswg_fileUpload10",
- "#pinswg_fileUpload11",
- "#pinswg_fileUpload12",
- "#pinswg_fileUpload13",
- "#pinswg_fileUpload14",
- "#pinswg_fileUpload15",
- ];
-
- for (let i = 0; i < fileInputs.length; i++) {
- const selector = fileInputs[i];
- if (i === 0) {
- // First input gets its specific files
- await page.locator(selector).setInputFiles(firstInputFiles);
- } else {
- // All other inputs get the common files
- await page.locator(selector).setInputFiles(files);
- }
- const uploadedFiles = page
- .locator("h4", { hasText: "Uploaded files" })
- .first();
- await expect(uploadedFiles).toBeVisible({ timeout: 60000 });
- }
-
- await page.getByRole("button", { name: "Submit" }).click();
-
- // Check and Confirm
- await page
- .getByRole("checkbox", { name: "I confirm that all sections" })
- .check();
- await page.getByText("Submit appeal").click();
-
- await page.waitForTimeout(20000);
- });
-});
diff --git a/pwe2e/tests/loggedout/downloadFile.spec.js b/pwe2e/tests/loggedout/downloadFile.spec.js
deleted file mode 100644
index 28d654e3..00000000
--- a/pwe2e/tests/loggedout/downloadFile.spec.js
+++ /dev/null
@@ -1,26 +0,0 @@
-import { test, expect } from "@playwright/test";
-
-test("Download a file", async ({ page }) => {
- await page.goto("/");
- await page.getByRole("button", { name: "Accept cookies" }).click();
- await page
- .getByRole("textbox", { name: "Use the case reference or DNS" })
- .click();
- await page
- .getByRole("textbox", { name: "Use the case reference or DNS" })
- .fill("gaerwen");
- await page.getByRole("button", { name: "Submit search" }).click();
- // await page
- // .getByRole("link", { name: "DNS3276735 - Gaerwen Wind Farm (test)" })
- // .click();
-
- await page.locator("dd a.govuk-link--no-underline").first().click();
-
- const downloadPromise = page.waitForEvent("download");
-
- await page.locator(".documentLink").first().click();
-
- const download = await downloadPromise;
- await page.getByText("Download complete!").click();
- await page.getByRole("link", { name: "Home" }).click();
-});
diff --git a/pwe2e/tests/loggedout/homepageLinks.spec.js b/pwe2e/tests/loggedout/homepageLinks.spec.js
deleted file mode 100644
index 15c945e9..00000000
--- a/pwe2e/tests/loggedout/homepageLinks.spec.js
+++ /dev/null
@@ -1,35 +0,0 @@
-import { test, expect } from "@playwright/test";
-import { handleSearchResults } from "../../helpers/index";
-
-test("Check for DNS applications", async ({ page }) => {
- await page.goto("/");
- await page.getByRole("button", { name: "Accept cookies" }).click();
- await page.getByRole("link", { name: "View all DNS applications" }).click();
-
- async function handleSearchResults(page) {
- const results = page.locator("dd a.govuk-link--no-underline");
-
- await Promise.race([
- results.first().waitFor({ state: "visible", timeout: 15000 }),
- ]);
-
- if ((await results.count()) > 0) {
- await results.first().click({ timeout: 15000 });
- await expect(page.locator("#main-content")).toContainText("Reference:", {
- timeout: 15000,
- });
- return "clicked";
- } else if ((await noResultsMessage.count()) > 0) {
- console.log("ℹ️ No results found. Test passes.");
- return "no-results";
- } else {
- throw new Error(
- "⚠️ Unexpected search page state: neither results nor zero-results message found."
- );
- }
- }
-
- // Handle search results safely
- const outcome = await handleSearchResults(page);
- console.log(`Search outcome for DNS":`, outcome);
-});
diff --git a/pwe2e/tests/loggedout/searches.spec.js b/pwe2e/tests/loggedout/searches.spec.js
deleted file mode 100644
index 4966be7c..00000000
--- a/pwe2e/tests/loggedout/searches.spec.js
+++ /dev/null
@@ -1,208 +0,0 @@
-import { test, expect } from "@playwright/test";
-import * as XLSX from "xlsx";
-import { handleSearchResults } from "../../helpers/index";
-test.use({ headless: true });
-
-test("Basic search", async ({ page }) => {
- await page.goto("/");
- await page.getByRole("button", { name: "Accept cookies" }).click();
- await page
- .getByRole("textbox", { name: "Use the case reference or DNS" })
- .click();
- await page
- .getByRole("textbox", { name: "Use the case reference or DNS" })
- .fill("cas-");
- await page.getByRole("button", { name: "Submit search" }).click();
-
- // Handle search results safely
- const outcome = await handleSearchResults(page);
- console.log(`Search outcome for basic search":`, outcome);
-});
-
-const workbook = XLSX.readFile("./testFiles/appealList.xlsx");
-const sheetName = workbook.SheetNames[0];
-const rawData = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], {
- defval: "",
-});
-
-const data = rawData
- .map((row) => ({
- Values: row["Values"]?.trim(),
- AppealTypes: row["AppealType"]?.trim(),
- }))
- .filter((r) => r.Values && r.AppealTypes);
-
-test.describe("Advanced Search Appeal Types", () => {
- if (data.length === 0) {
- test("No data found in spreadsheet", async () => {
- console.warn("No valid rows found in appealList.xlsx");
- });
- }
-
- data.forEach((row, index) => {
- test(`Advanced search - ${row.AppealTypes} #${index + 1}`, async ({
- page,
- }) => {
- await page.goto("/");
-
- const acceptButton = page.getByRole("button", { name: "Accept cookies" });
- if (await acceptButton.isVisible()) await acceptButton.click();
-
- await page.getByRole("link", { name: "Advanced search" }).click();
- await page.getByLabel("Select a case type").selectOption(row.Values);
- await page.getByRole("button", { name: "Search" }).click();
-
- // Handle search results safely
- const outcome = await handleSearchResults(page);
- console.log(`Search outcome for "${row.AppealTypes}":`, outcome);
- });
- });
-});
-
-const sheetName2 = workbook.SheetNames[1];
-const rawData2 = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName2], {
- defval: "",
-});
-
-const data2 = rawData2
- .map((row) => ({
- Values: row["Values"]?.trim(),
- LPA: row["LPA"]?.trim(),
- }))
- .filter((r) => r.Values && r.LPA);
-
-test.describe("Advanced Search LPA", () => {
- if (data2.length === 0) {
- test("No data found in spreadsheet", async () => {
- console.warn("⚠️ No valid rows found in lpaList.xlsx");
- });
- }
-
- data2.forEach((row, index) => {
- test(`Advanced search LPA - ${row.LPA} #${index + 1}`, async ({ page }) => {
- await page.goto("/");
-
- const acceptButton = page.getByRole("button", { name: "Accept cookies" });
- if (await acceptButton.isVisible()) await acceptButton.click();
-
- await page.getByRole("link", { name: "Advanced search" }).click();
- await page
- .getByLabel("Local Planning Authority")
- .selectOption(row.Values);
- await page.getByRole("button", { name: "Search" }).click();
-
- // Handle search results safely
- const outcome = await handleSearchResults(page);
- console.log(`Search outcome for "${row.LPA}":`, outcome);
- });
- });
-});
-
-const sheetName3 = workbook.SheetNames[2];
-const rawData3 = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName3], {
- defval: "",
-});
-
-const data3 = rawData3
- .map((row) => ({
- Values: row["Values"],
- Status: row["Status"]?.trim(),
- }))
- .filter((r) => r.Values && r.Status);
-
-test.describe("Advanced Search Case Status", () => {
- if (data3.length === 0) {
- test("No data found in spreadsheet", async () => {
- console.warn("⚠️ No valid rows found in lpaList.xlsx");
- });
- }
-
- data3.forEach((row, index) => {
- test(`Advanced search Case Status - ${row.Status} #${index + 1}`, async ({
- page,
- }) => {
- await page.goto("/");
-
- const acceptButton = page.getByRole("button", { name: "Accept cookies" });
- if (await acceptButton.isVisible()) await acceptButton.click();
-
- await page.getByRole("link", { name: "Advanced search" }).click();
- await page.getByLabel("Case Status").selectOption(String(row.Values));
- await page.getByRole("button", { name: "Search" }).click();
-
- // Handle search results safely
- const outcome = await handleSearchResults(page);
- console.log(`Search outcome for "${row.Status}":`, outcome);
- });
- });
-});
-
-test.describe("Address search", () => {
- test("Address search AddressLine1", async ({ page }) => {
- await page.goto("/");
- const acceptButton = page.getByRole("button", { name: "Accept cookies" });
- if (await acceptButton.isVisible()) await acceptButton.click();
- await page.getByRole("link", { name: "Address search" }).click();
- await page.locator("#addressline1").click();
- await page.locator("#addressline1").fill("street");
- await page.getByRole("button", { name: "Search" }).click();
-
- // Handle search results safely
- const outcome = await handleSearchResults(page);
- console.log(`Search outcome for AddressLine1":`, outcome);
- });
- test("Address search Town", async ({ page }) => {
- await page.goto("/");
- const acceptButton = page.getByRole("button", { name: "Accept cookies" });
- if (await acceptButton.isVisible()) await acceptButton.click();
- await page.getByRole("link", { name: "Address search" }).click();
- await page.locator("#town").click();
- await page.locator("#town").fill("Cardiff");
- await page.getByRole("button", { name: "Search" }).click();
-
- // Handle search results safely
- const outcome = await handleSearchResults(page);
- console.log(`Search outcome for Town":`, outcome);
- });
- test("Address search County", async ({ page }) => {
- await page.goto("/");
- const acceptButton = page.getByRole("button", { name: "Accept cookies" });
- if (await acceptButton.isVisible()) await acceptButton.click();
- await page.getByRole("link", { name: "Address search" }).click();
- await page.locator("#county").click();
- await page.locator("#county").fill("Cardiff");
- await page.getByRole("button", { name: "Search" }).click();
-
- // Handle search results safely
- const outcome = await handleSearchResults(page);
- console.log(`Search outcome for County":`, outcome);
- });
- test("Address search Postcode", async ({ page }) => {
- await page.goto("/");
- const acceptButton = page.getByRole("button", { name: "Accept cookies" });
- if (await acceptButton.isVisible()) await acceptButton.click();
- await page.getByRole("link", { name: "Address search" }).click();
- await page.locator("#postcode").click();
- await page.locator("#postcode").fill("cf24");
- await page.getByRole("button", { name: "Search" }).click();
-
- // Handle search results safely
- const outcome = await handleSearchResults(page);
- console.log(`Search outcome for Postcode":`, outcome);
- });
- test("Address search Appellant or Applicant", async ({ page }) => {
- await page.goto("/");
- const acceptButton = page.getByRole("button", { name: "Accept cookies" });
- if (await acceptButton.isVisible()) await acceptButton.click();
- await page.getByRole("link", { name: "Address search" }).click();
- await page.locator("#appellantname").click();
- await page.locator("#appellantname").fill("David");
- await page.locator("#addressline1").click();
- await page.locator("#addressline1").fill("Street");
- await page.getByRole("button", { name: "Search" }).click();
-
- // Handle search results safely
- const outcome = await handleSearchResults(page);
- console.log(`Search outcome for Postcode":`, outcome);
- });
-});
diff --git a/pwe2e/tests/test-1.spec.ts b/pwe2e/tests/test-1.spec.ts
deleted file mode 100644
index b915e038..00000000
--- a/pwe2e/tests/test-1.spec.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import { test, expect } from '@playwright/test';
-
-test('test', async ({ page }) => {
- await page.locator('body').click();
- await page.goto('http://localhost:3000/auth/error?error=Verification
- await page.getByRole('link', { name: 'Home', exact: true }).click();
- await page.goto('http://localhost:3000/myportal');
- await page.goto('http://localhost:3000/myportal/case/CAS-01085-K4R4X0?q=CAS-01085-K4R4X0&adv=false');
- await page.getByRole('link', { name: 'Make representation' }).click();
- await page.getByRole('combobox').selectOption('Questionnaire');
- await page.getByRole('combobox').selectOption('Written representations');
- await page.getByText('No').first().click();
- await page.getByText('No').nth(1).click();
- await page.getByText('No').nth(2).click();
- await page.getByText('Yes').nth(2).click();
- await page.getByText('No').nth(3).click();
- await page.getByRole('paragraph').filter({ hasText: /^$/ }).click();
- await page.locator('.ql-editor').fill('w');
- await page.locator('div').filter({ hasText: /^w$/ }).nth(2).fill('wdwdwdwdwdw ');
- await page.getByRole('button', { name: 'Continue' }).click();
- await page.locator('.ql-editor').first().click();
- await page.locator('.ql-editor').first().fill('wwwqwqeq wefqewr qwerq');
- await page.getByRole('paragraph').nth(4).click();
- await page.locator('.ql-editor.ql-blank').first().fill('qweqwe qwrqrt qwe qweqwqwe');
- await page.getByRole('paragraph').filter({ hasText: /^$/ }).click();
- await page.locator('.ql-editor.ql-blank').first().fill('qweqwe qwrqrt qwe qweqwqweq');
- await page.locator('.ql-editor.ql-blank').fill('w e');
- await page.locator('div').filter({ hasText: /^w e$/ }).nth(2).fill('w eqewrqwe q');
- await page.getByRole('paragraph').filter({ hasText: /^$/ }).click();
- await page.locator('div').filter({ hasText: /^w e$/ }).nth(2).fill('w eqewrqwe qweqwe ');
- await page.getByText('No').nth(1).click();
- await page.getByText('No').nth(2).click();
- await page.getByText('No').nth(3).click();
- await page.getByText('No').nth(4).click();
- await page.getByText('No').nth(5).click();
- await page.locator('div:nth-child(8) > .govuk-form-group > .govuk-fieldset > .govuk-radios > div:nth-child(2) > .govuk-radios__item > .govuk-label').click();
- await page.locator('div:nth-child(9) > .govuk-fieldset > .govuk-radios > div:nth-child(2) > .govuk-label').click();
- await page.locator('div:nth-child(10) > .govuk-form-group > .govuk-fieldset > .govuk-radios > div:nth-child(2) > .govuk-radios__item > .govuk-label').click();
- await page.getByRole('button', { name: 'Continue' }).click();
- await page.getByText('No').nth(2).click();
- await page.getByText('No').nth(3).click();
- await page.getByText('No').nth(5).click();
- await page.getByText('No', { exact: true }).nth(3).click();
- await page.getByText('No', { exact: true }).nth(4).click();
- await page.getByRole('button', { name: 'Continue' }).click();
- await page.getByRole('group', { name: '26. A copy of the applicant’s' }).click();
- await page.getByText('No').nth(4).click();
- await page.getByText('Yes').nth(1).click();
- await page.getByText('No', { exact: true }).nth(2).click();
- await page.getByText('Yes').nth(2).click();
- await page.getByText('No', { exact: true }).nth(3).click();
- await page.getByText('No', { exact: true }).nth(4).click();
- await page.getByText('No', { exact: true }).nth(5).click();
- await page.locator('div:nth-child(9) > .govuk-form-group > .govuk-fieldset > .govuk-radios > div:nth-child(2) > .govuk-radios__item > .govuk-label').click();
- await page.locator('div:nth-child(10) > .govuk-form-group > .govuk-fieldset > .govuk-radios > div:nth-child(2) > .govuk-radios__item > .govuk-label').click();
- await page.getByRole('button', { name: 'Continue' }).click();
- await page.getByText('Drag and drop your files here').click();
- await page.getByRole('button', { name: 'Continue' }).click();
- await page.getByRole('textbox', { name: 'Signed' }).click();
- await page.getByRole('textbox', { name: 'Signed' }).fill('Bob Bob');
- await page.getByRole('textbox', { name: 'Date' }).click();
- await page.getByRole('option', { name: 'Choose Tuesday, April 14th,' }).click();
- await page.getByRole('button', { name: 'Continue' }).click();
- await page.getByText('I wish to download a copy of').click();
- await page.getByRole('checkbox', { name: 'I confirm I have read the' }).check();
- const downloadPromise = page.waitForEvent('download');
- await page.getByRole('button', { name: 'Continue' }).click();
- const download = await downloadPromise;
- await page.getByRole('link', { name: 'Continue' }).click();
- await page.goto('http://localhost:3000/myportal');');
-});
\ No newline at end of file
diff --git a/pwe2e/tests/test-2.spec.ts b/pwe2e/tests/test-2.spec.ts
deleted file mode 100644
index 5b3d48cf..00000000
--- a/pwe2e/tests/test-2.spec.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import { test, expect } from '@playwright/test';
-
-test('test', async ({ page }) => {
- // Recording...
-});
\ No newline at end of file
diff --git a/pwe2e/tests/test-3.spec.ts b/pwe2e/tests/test-3.spec.ts
deleted file mode 100644
index 9f3b9b0e..00000000
--- a/pwe2e/tests/test-3.spec.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { test, expect } from "@playwright/test";
-
-test("test", async ({ page }) => {
- // Recording...
- await page.goto("http://localhost:3000/auth/error?error=Verification");
- await page.getByRole("link", { name: "Home", exact: true }).click();
- await page.goto("http://localhost:3000/myportal");
- await page.getByRole("heading", { name: "Representations awaiting" }).click();
-
- const containerLink = page
- .locator("div", { hasText: "Representations awaiting" })
- .locator("a")
- .first()
- .click();
-
- await page.getByText("CAS-01085-K4R4X0").first().click();
- await page.goto(
- "http://localhost:3000/myportal/representation?case=CAS-01085-K4R4X0&state=edit&created=2026-04-15-12%3A32%3A23_-_LPA_-_Questionnaire_-_CardiffCouncil",
- );
- await page.getByRole("button", { name: "Save and exit" }).click();
- await page.goto("http://localhost:3000/myportal");
-});
diff --git a/styles/sass/patterns/_step-by-step-nav.scss b/styles/sass/patterns/_step-by-step-nav.scss
index 35343fec..d9a21ccb 100644
--- a/styles/sass/patterns/_step-by-step-nav.scss
+++ b/styles/sass/patterns/_step-by-step-nav.scss
@@ -1,6 +1,8 @@
// Based on https://github.com/alphagov/govuk_publishing_components/blob/v22.0.0/app/assets/stylesheets/govuk_publishing_components/components/_step-by-step-nav.scss
// Note - this code for prototype purposes only. It is not production code.
+@use "sass:math";
+
$stroke-width: 2px;
$stroke-width-large: 3px;
$number-circle-size: 26px;
@@ -19,12 +21,12 @@ $top-border: solid 2px govuk-colour("mid-grey");
@mixin step-nav-line-position {
left: 0;
- margin-left: ($number-circle-size / 2) - ($stroke-width / 2);
+ margin-left: math.div($number-circle-size, 2) - math.div($stroke-width, 2);
}
@mixin step-nav-line-position-large {
left: 0;
- margin-left: ($number-circle-size-large / 2) - ($stroke-width-large / 2);
+ margin-left: math.div($number-circle-size-large, 2) - math.div($stroke-width-large, 2);
border-width: $stroke-width-large;
}
@@ -149,8 +151,8 @@ $top-border: solid 2px govuk-colour("mid-grey");
z-index: 6;
bottom: 0;
left: 0;
- margin-left: $number-circle-size / 4;
- width: $number-circle-size / 2;
+ margin-left: math.div($number-circle-size, 4);
+ width: math.div($number-circle-size, 2);
height: 0;
border-bottom: solid $stroke-width govuk-colour("mid-grey");
}
@@ -171,8 +173,8 @@ $top-border: solid 2px govuk-colour("mid-grey");
.app-step-nav--large & {
@include govuk-media-query($from: tablet) {
&:before {
- margin-left: $number-circle-size-large / 4;
- width: $number-circle-size-large / 2;
+ margin-left: math.div($number-circle-size-large, 4);
+ width: math.div($number-circle-size-large, 2);
border-width: $stroke-width-large;
}
@@ -418,9 +420,9 @@ $top-border: solid 2px govuk-colour("mid-grey");
z-index: 5;
top: 0.6em; // position the dot to align with the first row of text in the link
left: -(govuk-spacing(6) + govuk-spacing(3));
- margin-top: -($stroke-width / 2);
- margin-left: ($number-circle-size / 2);
- width: $number-circle-size / 2;
+ margin-top: -(math.div($stroke-width, 2));
+ margin-left: math.div($number-circle-size, 2);
+ width: math.div($number-circle-size, 2);
height: $stroke-width;
background: govuk-colour("black");
}
@@ -429,7 +431,7 @@ $top-border: solid 2px govuk-colour("mid-grey");
@include govuk-media-query($from: tablet) {
&:before {
left: -(govuk-spacing(9));
- margin-left: ($number-circle-size-large / 2);
+ margin-left: math.div($number-circle-size-large, 2);
height: $stroke-width-large;
}
}
diff --git a/styles/sass/patterns/_step-by-step-related.scss b/styles/sass/patterns/_step-by-step-related.scss
index 6431cc66..cd50e391 100644
--- a/styles/sass/patterns/_step-by-step-related.scss
+++ b/styles/sass/patterns/_step-by-step-related.scss
@@ -1,6 +1,8 @@
// Based on https://github.com/alphagov/govuk_publishing_components/blob/v22.0.0/app/assets/stylesheets/govuk_publishing_components/components/_step-by-step-related.scss
// Note - this code for prototype purposes only. It is not production code.
+@use "sass:math";
+
.app-step-nav-related {
@include govuk-text-colour;
border-top: 2px solid govuk-colour("blue");
@@ -32,7 +34,7 @@
}
.app-step-nav-related__pretitle {
- margin-bottom: govuk-spacing(6) / 4;
+ margin-bottom: math.div(govuk-spacing(6), 4);
}
}
diff --git a/styles/sass/styles.scss b/styles/sass/styles.scss
index 20a3ce6c..253da49d 100644
--- a/styles/sass/styles.scss
+++ b/styles/sass/styles.scss
@@ -1,4 +1,4 @@
-@import "node_modules/govuk-frontend/dist/govuk/all";
+@import "govuk-frontend/dist/govuk/all";
// Add extra styles here, or re-organise the Sass files in whichever way makes most sense to you
@import "welshgov/_variables";
diff --git a/tests/phase14/service-behaviour.test.cjs b/tests/phase14/service-behaviour.test.cjs
index 31a3f599..398c9636 100644
--- a/tests/phase14/service-behaviour.test.cjs
+++ b/tests/phase14/service-behaviour.test.cjs
@@ -22,12 +22,20 @@ const loadModule = (relativePath, injected = {}) => {
source +=
'\nif (typeof ApiProxy !== "undefined" && !module.exports.default) module.exports.default = ApiProxy;\n';
+ const respondError = (res, { status, ...error }) =>
+ res.status(status).json({ error });
+ const respondSuccess = (res, data) => res.status(200).json(data);
+
const context = {
module: { exports: {} },
exports: {},
require,
process,
console: { log: () => {}, error: () => {} },
+ getServerSession: injected.getServerSession || injected.getSession,
+ authOptions: injected.authOptions || (() => ({})),
+ respondError,
+ respondSuccess,
...injected
};
@@ -196,28 +204,6 @@ test("gethash_api returns hash for allow-listed deletewatchedcases path", async
});
});
-test("gethash_api returns hash for allow-listed deletemyrepresentations path", async () => {
- const mod = loadModule("pages/api/endpoint/gethash_api.js", {
- hashAPIPath: () => "&hash=delrep",
- getSession: async () => ({ user: { id: "u1" } }),
- nextConnect: createNextConnectMock(),
- middleware: () => {}
- });
-
- const req = {
- query: {
- path: "/api/endpoint/deletemyrepresentations_api?myRepresentationsID=abc"
- }
- };
- const res = createRes();
- await mod.default.handler(req, res);
-
- assert.strictEqual(res.state.statusCode, 200);
- assert.deepStrictEqual(JSON.parse(JSON.stringify(res.state.jsonBody)), {
- hash: "&hash=delrep"
- });
-});
-
test("gethash_api rejects unauthenticated requests with 401", async () => {
const mod = loadModule("pages/api/endpoint/gethash_api.js", {
hashAPIPath: () => "&hash=expected",
diff --git a/tests/phase15/service-behaviour.test.cjs b/tests/phase15/service-behaviour.test.cjs
index 207c55eb..9d5d596d 100644
--- a/tests/phase15/service-behaviour.test.cjs
+++ b/tests/phase15/service-behaviour.test.cjs
@@ -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,
diff --git a/tests/phase21/_shared.cjs b/tests/phase21/_shared.cjs
index 811af4e8..2903a0a2 100644
--- a/tests/phase21/_shared.cjs
+++ b/tests/phase21/_shared.cjs
@@ -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: () => {},
diff --git a/tests/phase21/admin-auth-foundation.test.cjs b/tests/phase21/admin-auth-foundation.test.cjs
new file mode 100644
index 00000000..e4691931
--- /dev/null
+++ b/tests/phase21/admin-auth-foundation.test.cjs
@@ -0,0 +1,437 @@
+const assert = require("assert");
+const crypto = require("crypto");
+const fs = require("fs");
+const path = require("path");
+const vm = require("vm");
+const {
+ createRes,
+ respondErrorMock,
+ respondSuccessMock
+} = require("./_shared.cjs");
+
+const rootDir = path.resolve(__dirname, "..", "..");
+
+const syntheticEnv = {
+ ADMIN_AUTH_SECRET: "synthetic-admin-credential-value-0001",
+ ADMIN_SESSION_SECRET: "synthetic-session-signing-value-0002",
+ NEXTAUTH_URL: "https://admin.test.local"
+};
+
+const fixedNow = () => Date.parse("2026-10-26T12:00:00.000Z");
+const fixedNonce = () => Buffer.alloc(16, 7);
+
+const loadAdminAuthModule = () => {
+ const filePath = path.join(rootDir, "lib", "admin", "adminAuth.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 += `
+module.exports = {
+ ADMIN_SESSION_COOKIE,
+ ADMIN_SESSION_TTL_SECONDS,
+ ADMIN_PASSPHRASE_MAX_LENGTH,
+ validateAdminPassphrase,
+ issueAdminSession,
+ validateAdminSession,
+ createAdminSessionCookie,
+ createClearedAdminSessionCookie,
+ readAdminSessionCookie,
+ hasTrustedSameOrigin,
+ setAdminAuthNoStore
+};`;
+
+ const context = {
+ module: { exports: {} },
+ exports: {},
+ require,
+ process,
+ Buffer,
+ URL,
+ Date,
+ encodeURIComponent,
+ decodeURIComponent,
+ ...crypto
+ };
+
+ vm.runInNewContext(source, context, { filename: filePath });
+ return context.module.exports;
+};
+
+const loadHandler = (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(
+ /export default async function\s+(\w+)\s*\(/,
+ "async function $1("
+ );
+ source += "\nmodule.exports.default = handler;\n";
+
+ const context = {
+ module: { exports: {} },
+ exports: {},
+ require,
+ process,
+ ...injected
+ };
+
+ vm.runInNewContext(source, context, { filename: filePath });
+ return context.module.exports.default;
+};
+
+const tests = [];
+const test = (name, fn) => tests.push({ name, fn });
+
+test("correct administrative credential succeeds", () => {
+ const auth = loadAdminAuthModule();
+ assert.strictEqual(
+ auth.validateAdminPassphrase(syntheticEnv.ADMIN_AUTH_SECRET, {
+ env: syntheticEnv
+ }),
+ true
+ );
+});
+
+test("incorrect administrative credential fails", () => {
+ const auth = loadAdminAuthModule();
+ assert.strictEqual(
+ auth.validateAdminPassphrase("incorrect-synthetic-credential", {
+ env: syntheticEnv
+ }),
+ false
+ );
+ assert.strictEqual(
+ auth.validateAdminPassphrase(
+ "x".repeat(auth.ADMIN_PASSPHRASE_MAX_LENGTH + 1),
+ { env: syntheticEnv }
+ ),
+ false
+ );
+});
+
+test("missing, short, or reused configuration fails closed", () => {
+ const auth = loadAdminAuthModule();
+
+ assert.strictEqual(
+ auth.validateAdminPassphrase("anything", { env: {} }),
+ false
+ );
+ assert.strictEqual(
+ auth.issueAdminSession({
+ env: {
+ ...syntheticEnv,
+ ADMIN_SESSION_SECRET: "short"
+ },
+ now: fixedNow,
+ nonce: fixedNonce
+ }),
+ null
+ );
+ assert.strictEqual(
+ auth.issueAdminSession({
+ env: {
+ ...syntheticEnv,
+ ADMIN_SESSION_SECRET: syntheticEnv.ADMIN_AUTH_SECRET
+ },
+ now: fixedNow,
+ nonce: fixedNonce
+ }),
+ null
+ );
+});
+
+test("session signing and validation succeed with a deterministic clock", () => {
+ const auth = loadAdminAuthModule();
+ const token = auth.issueAdminSession({
+ env: syntheticEnv,
+ now: fixedNow,
+ nonce: fixedNonce
+ });
+
+ assert.match(token, /^v1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/);
+ assert.strictEqual(
+ auth.validateAdminSession(token, { env: syntheticEnv, now: fixedNow }),
+ true
+ );
+});
+
+test("tampered session fails validation", () => {
+ const auth = loadAdminAuthModule();
+ const token = auth.issueAdminSession({
+ env: syntheticEnv,
+ now: fixedNow,
+ nonce: fixedNonce
+ });
+ const tampered = token.slice(0, -1) + (token.endsWith("A") ? "B" : "A");
+
+ assert.strictEqual(
+ auth.validateAdminSession(tampered, {
+ env: syntheticEnv,
+ now: fixedNow
+ }),
+ false
+ );
+});
+
+test("expired session fails validation", () => {
+ const auth = loadAdminAuthModule();
+ const token = auth.issueAdminSession({
+ env: syntheticEnv,
+ now: fixedNow,
+ nonce: fixedNonce
+ });
+ const expiredNow = () =>
+ fixedNow() + (auth.ADMIN_SESSION_TTL_SECONDS + 1) * 1000;
+
+ assert.strictEqual(
+ auth.validateAdminSession(token, {
+ env: syntheticEnv,
+ now: expiredNow
+ }),
+ false
+ );
+});
+
+test("malformed and unsigned sessions fail validation", () => {
+ const auth = loadAdminAuthModule();
+
+ for (const value of [null, "", "unsigned", "v1.payload", "v2.a.b"]){
+ assert.strictEqual(
+ auth.validateAdminSession(value, {
+ env: syntheticEnv,
+ now: fixedNow
+ }),
+ false
+ );
+ }
+});
+
+test("login sets production secure cookie attributes and no-store headers", async () => {
+ const auth = loadAdminAuthModule();
+ const token = auth.issueAdminSession({
+ env: syntheticEnv,
+ now: fixedNow,
+ nonce: fixedNonce
+ });
+ const handler = loadHandler("pages/api/admin/auth/login.js", {
+ validateAdminPassphrase: () => true,
+ issueAdminSession: () => token,
+ hasTrustedSameOrigin: () => true,
+ createAdminSessionCookie: (value) =>
+ auth.createAdminSessionCookie(value, {
+ now: fixedNow,
+ production: true
+ }),
+ setAdminAuthNoStore: auth.setAdminAuthNoStore,
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock
+ });
+ const req = {
+ method: "POST",
+ headers: { origin: syntheticEnv.NEXTAUTH_URL },
+ body: { passphrase: syntheticEnv.ADMIN_AUTH_SECRET }
+ };
+ const res = createRes();
+
+ await handler(req, res);
+
+ const cookie = res.state.headers["set-cookie"];
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.match(cookie, /^pedw_admin_session=/);
+ assert.match(cookie, /Max-Age=1200/);
+ assert.match(cookie, /Expires=/);
+ assert.match(cookie, /Path=\//);
+ assert.match(cookie, /HttpOnly/);
+ assert.match(cookie, /SameSite=Strict/);
+ assert.match(cookie, /Secure/);
+ assert.strictEqual(
+ res.state.headers["cache-control"],
+ "no-store, max-age=0"
+ );
+ assert.strictEqual(res.state.headers.pragma, "no-cache");
+});
+
+test("logout clears the cookie", async () => {
+ const auth = loadAdminAuthModule();
+ const handler = loadHandler("pages/api/admin/auth/logout.js", {
+ hasTrustedSameOrigin: () => true,
+ createClearedAdminSessionCookie: () =>
+ auth.createClearedAdminSessionCookie({ production: true }),
+ setAdminAuthNoStore: auth.setAdminAuthNoStore,
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock
+ });
+ const res = createRes();
+
+ await handler(
+ { method: "POST", headers: { origin: syntheticEnv.NEXTAUTH_URL } },
+ res
+ );
+
+ const cookie = res.state.headers["set-cookie"];
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.match(cookie, /^pedw_admin_session=;/);
+ assert.match(cookie, /Max-Age=0/);
+ assert.match(cookie, /Expires=Thu, 01 Jan 1970 00:00:00 GMT/);
+ assert.match(cookie, /HttpOnly/);
+ assert.match(cookie, /SameSite=Strict/);
+ assert.match(cookie, /Secure/);
+});
+
+test("session-status route reports only authentication state", async () => {
+ const auth = loadAdminAuthModule();
+ const handler = loadHandler("pages/api/admin/auth/session.js", {
+ readAdminSessionCookie: () => "synthetic-token",
+ validateAdminSession: () => true,
+ setAdminAuthNoStore: auth.setAdminAuthNoStore,
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock
+ });
+ const res = createRes();
+
+ await handler({ method: "GET", headers: {} }, res);
+
+ assert.deepStrictEqual(JSON.parse(JSON.stringify(res.state.jsonBody)), {
+ authenticated: true
+ });
+ const serialized = JSON.stringify(res.state.jsonBody);
+ assert.ok(!serialized.includes(syntheticEnv.ADMIN_AUTH_SECRET));
+ assert.ok(!serialized.includes(syntheticEnv.ADMIN_SESSION_SECRET));
+});
+
+test("invalid request methods are rejected", async () => {
+ const auth = loadAdminAuthModule();
+ const shared = {
+ hasTrustedSameOrigin: () => true,
+ validateAdminPassphrase: () => true,
+ issueAdminSession: () => "token",
+ createAdminSessionCookie: () => "cookie",
+ createClearedAdminSessionCookie: () => "cookie",
+ readAdminSessionCookie: () => "token",
+ validateAdminSession: () => true,
+ setAdminAuthNoStore: auth.setAdminAuthNoStore,
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock
+ };
+
+ for (const [route, method] of [
+ ["pages/api/admin/auth/login.js", "GET"],
+ ["pages/api/admin/auth/logout.js", "GET"],
+ ["pages/api/admin/auth/session.js", "POST"]
+ ]) {
+ const handler = loadHandler(route, shared);
+ const res = createRes();
+ await handler({ method, headers: {}, body: {} }, res);
+ assert.strictEqual(res.state.statusCode, 405);
+ assert.strictEqual(res.state.jsonBody.error.code, "METHOD_NOT_ALLOWED");
+ }
+});
+
+test("missing or invalid trusted origin rejects state-changing requests", async () => {
+ const auth = loadAdminAuthModule();
+ assert.strictEqual(
+ auth.hasTrustedSameOrigin(
+ { headers: { origin: syntheticEnv.NEXTAUTH_URL } },
+ { env: syntheticEnv }
+ ),
+ true
+ );
+ const login = loadHandler("pages/api/admin/auth/login.js", {
+ hasTrustedSameOrigin: (req) =>
+ auth.hasTrustedSameOrigin(req, { env: syntheticEnv }),
+ validateAdminPassphrase: () => true,
+ issueAdminSession: () => "token",
+ createAdminSessionCookie: () => "cookie",
+ setAdminAuthNoStore: auth.setAdminAuthNoStore,
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock
+ });
+ const logout = loadHandler("pages/api/admin/auth/logout.js", {
+ hasTrustedSameOrigin: (req) =>
+ auth.hasTrustedSameOrigin(req, { env: syntheticEnv }),
+ createClearedAdminSessionCookie: () => "cookie",
+ setAdminAuthNoStore: auth.setAdminAuthNoStore,
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock
+ });
+
+ for (const handler of [login, logout]) {
+ for (const origin of [undefined, "https://attacker.test", "not-a-url"]) {
+ const res = createRes();
+ await handler(
+ {
+ method: "POST",
+ headers: origin ? { origin } : {},
+ body: { passphrase: syntheticEnv.ADMIN_AUTH_SECRET }
+ },
+ res
+ );
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(res.state.jsonBody.error.code, "FORBIDDEN");
+ }
+ }
+});
+
+test("authentication foundation has no Prisma, CRM, or NextAuth dependency", () => {
+ const files = [
+ "lib/admin/adminAuth.js",
+ "pages/api/admin/auth/login.js",
+ "pages/api/admin/auth/logout.js",
+ "pages/api/admin/auth/session.js"
+ ];
+
+ for (const relativePath of files) {
+ const source = fs.readFileSync(path.join(rootDir, relativePath), "utf8");
+ assert.doesNotMatch(source, /@prisma|Prisma|getPortalLogin|CRM|next-auth/i);
+ }
+});
+
+test("administrative session verification is independent of portal cookies", () => {
+ const auth = loadAdminAuthModule();
+ const token = auth.issueAdminSession({
+ env: syntheticEnv,
+ now: fixedNow,
+ nonce: fixedNonce
+ });
+ const req = {
+ headers: {
+ cookie: `next-auth.session-token=portal-token; ${auth.ADMIN_SESSION_COOKIE}=${encodeURIComponent(
+ token
+ )}`
+ }
+ };
+
+ const extracted = auth.readAdminSessionCookie(req);
+ assert.strictEqual(extracted, token);
+ assert.strictEqual(
+ auth.validateAdminSession(extracted, {
+ env: syntheticEnv,
+ now: fixedNow
+ }),
+ true
+ );
+});
+
+const run = async () => {
+ let passed = 0;
+
+ for (const currentTest of tests) {
+ await currentTest.fn();
+ passed += 1;
+ }
+
+ console.log(
+ `Administrative authentication foundation tests passed (${passed}/${tests.length}).`
+ );
+};
+
+module.exports = run;
+
+if (require.main === module) {
+ run().catch((error) => {
+ console.error(error);
+ process.exit(1);
+ });
+}
\ No newline at end of file
diff --git a/tests/phase21/admin-login-integration.test.cjs b/tests/phase21/admin-login-integration.test.cjs
new file mode 100644
index 00000000..de1cf8ee
--- /dev/null
+++ b/tests/phase21/admin-login-integration.test.cjs
@@ -0,0 +1,284 @@
+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 readSource = (relativePath) =>
+ fs.readFileSync(path.join(rootDir, relativePath), "utf8");
+
+const loadAdminPageLoader = (overrides = {}) => {
+ const filePath = path.join(rootDir, "pages", "admin", "index.js");
+ let source = fs.readFileSync(filePath, "utf8");
+
+ source = source.replace(/import[\s\S]*?from\s+"[^"]+";\n?/g, "");
+ source = source.slice(source.indexOf("export const getServerSideProps"));
+ source = source.replace(
+ /export\s+const\s+getServerSideProps\s*=\s*/,
+ "const getServerSideProps = "
+ );
+ source = source.replace(/const mapDispatchToProps[\s\S]*$/, "");
+ source += "\nmodule.exports = { getServerSideProps };\n";
+
+ const context = {
+ module: { exports: {} },
+ exports: {},
+ wrapper: {
+ getServerSideProps: (factory) => async (ctx) => {
+ const store = {
+ dispatch: () => {},
+ getState: () => ({})
+ };
+ return factory(store)(ctx);
+ }
+ },
+ readAdminSessionCookie: () => "valid-token",
+ validateAdminSession: () => true,
+ fetchAdminStorageData: async () => ({
+ data: [],
+ userData: [],
+ repCompleteCount: 0
+ }),
+ getNewAppeals: async () => ({ value: [] }),
+ getStatusByAppeal: async () => [],
+ getStatusByAppealLPA: async () => [],
+ getSearchDetails: async () => ({}),
+ setSearchResults: () => ({}),
+ setSearchDetails: () => ({}),
+ setCurrentPage: () => ({}),
+ process: {
+ env: {
+ ALLOWED_IPS: "203.0.113.10"
+ }
+ },
+ ...overrides
+ };
+
+ vm.runInNewContext(source, context, { filename: filePath });
+ return context.module.exports;
+};
+
+const loadAdminLoginLoader = (overrides = {}) => {
+ const filePath = path.join(rootDir, "pages", "admin", "login.js");
+ let source = fs.readFileSync(filePath, "utf8");
+
+ source = source.replace(/import[\s\S]*?from\s+"[^"]+";\n?/g, "");
+ source = source.slice(source.indexOf("export const getServerSideProps"));
+ source = source.replace(
+ /export\s+const\s+getServerSideProps\s*=\s*/,
+ "const getServerSideProps = "
+ );
+ source = source.replace(/export default[\s\S]*$/, "");
+ source += "\nmodule.exports = { getServerSideProps };\n";
+
+ const context = {
+ module: { exports: {} },
+ exports: {},
+ readAdminSessionCookie: () => null,
+ validateAdminSession: () => false,
+ ...overrides
+ };
+
+ vm.runInNewContext(source, context, { filename: filePath });
+ return context.module.exports;
+};
+
+const createAdminContext = (ip = "203.0.113.10") => ({
+ query: {},
+ req: {
+ headers: { "x-forwarded-for": ip },
+ socket: { remoteAddress: ip }
+ },
+ res: {}
+});
+
+test("unauthenticated admin access redirects before privileged data loads", async () => {
+ let dataLoads = 0;
+ const mod = loadAdminPageLoader({
+ readAdminSessionCookie: () => null,
+ validateAdminSession: () => false,
+ fetchAdminStorageData: async () => {
+ dataLoads += 1;
+ return { data: [], userData: [], repCompleteCount: 0 };
+ },
+ getNewAppeals: async () => {
+ dataLoads += 1;
+ return { value: [] };
+ }
+ });
+
+ const result = await mod.getServerSideProps(createAdminContext());
+
+ assert.strictEqual(result.redirect.destination, "/admin/login");
+ assert.strictEqual(result.redirect.permanent, false);
+ assert.strictEqual(dataLoads, 0);
+});
+
+test("invalid or expired administrative sessions cannot access admin", async () => {
+ for (const token of ["invalid-token", "expired-token"]) {
+ const mod = loadAdminPageLoader({
+ readAdminSessionCookie: () => token,
+ validateAdminSession: () => false
+ });
+ const result = await mod.getServerSideProps(createAdminContext());
+ assert.strictEqual(result.redirect.destination, "/admin/login");
+ }
+});
+
+test("valid administrative session and allowed IP load existing admin data", async () => {
+ const calls = [];
+ const mod = loadAdminPageLoader({
+ fetchAdminStorageData: async () => {
+ calls.push("storage");
+ return { data: ["storage"], userData: ["user"], repCompleteCount: 1 };
+ },
+ getNewAppeals: async () => {
+ calls.push("appeals");
+ return { value: [] };
+ },
+ getStatusByAppeal: async () => {
+ calls.push("status");
+ return ["status"];
+ },
+ getStatusByAppealLPA: async () => {
+ calls.push("lpa-status");
+ return ["lpa-status"];
+ },
+ getSearchDetails: async () => {
+ calls.push("search-details");
+ return {};
+ }
+ });
+
+ const result = await mod.getServerSideProps(createAdminContext());
+
+ assert.deepStrictEqual(calls, [
+ "storage",
+ "appeals",
+ "status",
+ "lpa-status",
+ "search-details"
+ ]);
+ assert.strictEqual(result.props.repCompleteCount, 1);
+});
+
+test("valid administrative session and disallowed IP retains 403 redirect", async () => {
+ let dataLoads = 0;
+ const mod = loadAdminPageLoader({
+ fetchAdminStorageData: async () => {
+ dataLoads += 1;
+ return { data: [], userData: [], repCompleteCount: 0 };
+ }
+ });
+
+ const result = await mod.getServerSideProps(
+ createAdminContext("198.51.100.25")
+ );
+
+ assert.strictEqual(result.redirect.destination, "/403");
+ assert.strictEqual(dataLoads, 0);
+});
+
+test("missing administrative configuration fails closed at the page boundary", async () => {
+ const mod = loadAdminPageLoader({ validateAdminSession: () => false });
+ const result = await mod.getServerSideProps(createAdminContext());
+ assert.strictEqual(result.redirect.destination, "/admin/login");
+});
+
+test("login page remains available for missing or invalid sessions", async () => {
+ const mod = loadAdminLoginLoader();
+ const result = await mod.getServerSideProps({ req: { headers: {} } });
+
+ assert.deepStrictEqual(JSON.parse(JSON.stringify(result)), { props: {} });
+});
+
+test("login page redirects an already authenticated administrator to admin", async () => {
+ const mod = loadAdminLoginLoader({
+ readAdminSessionCookie: () => "valid-token",
+ validateAdminSession: () => true
+ });
+ const result = await mod.getServerSideProps({ req: { headers: {} } });
+
+ assert.strictEqual(result.redirect.destination, "/admin");
+ assert.strictEqual(result.redirect.permanent, false);
+});
+
+test("login page uses the existing login API and generic error handling", () => {
+ const source = readSource("pages/admin/login.js");
+
+ assert.match(source, /fetch\("\/api\/admin\/auth\/login"/);
+ assert.match(source, /method:\s*"POST"/);
+ assert.match(source, /JSON\.stringify\(\{ passphrase \}\)/);
+ assert.match(source, /type="password"/);
+ assert.match(source, /htmlFor="admin-passphrase"/);
+ assert.match(source, /Sign in failed\. Check the details and try again\./);
+ assert.match(source, /router\.replace\("\/admin"\)/);
+ assert.doesNotMatch(source, /localStorage|sessionStorage/);
+});
+
+test("admin logout uses the existing endpoint and returns to login", () => {
+ const source = readSource("pages/admin/index.js");
+
+ assert.match(source, /fetch\("\/api\/admin\/auth\/logout"/);
+ assert.match(source, /method:\s*"POST"/);
+ assert.match(source, /router\.replace\("\/admin\/login"\)/);
+ assert.match(source, />\s*\{signingOut \? "Signing out\.\.\." : "Sign out"\}/);
+ assert.doesNotMatch(source, /document\.cookie/);
+});
+
+test("admin login integration adds no NextAuth, Prisma, or CRM authentication dependency", () => {
+ for (const relativePath of [
+ "pages/admin/login.js",
+ "lib/admin/adminAuth.js",
+ "pages/api/admin/auth/login.js",
+ "pages/api/admin/auth/logout.js",
+ "pages/api/admin/auth/session.js"
+ ]) {
+ const source = readSource(relativePath);
+ assert.doesNotMatch(source, /next-auth|@prisma|Prisma|getPortalLogin|CRM/i);
+ }
+});
+
+test("existing signing and document service files remain unchanged", () => {
+ const protectedPaths = [
+ "pages/api/endpoint/gethash_api.js",
+ "actions/services/documentDirectService.js"
+ ];
+ const changedPaths = require("child_process")
+ .execFileSync("git", ["diff", "--name-only", "HEAD"], {
+ cwd: rootDir,
+ encoding: "utf8"
+ })
+ .trim()
+ .split("\n")
+ .filter(Boolean);
+
+ for (const protectedPath of protectedPaths) {
+ assert.ok(!changedPaths.includes(protectedPath));
+ }
+});
+
+const run = async () => {
+ let passed = 0;
+
+ for (const currentTest of tests) {
+ await currentTest.fn();
+ passed += 1;
+ }
+
+ console.log(
+ `Administrative login integration tests passed (${passed}/${tests.length}).`
+ );
+};
+
+module.exports = run;
+
+if (require.main === module) {
+ run().catch((error) => {
+ console.error(error);
+ process.exit(1);
+ });
+}
\ No newline at end of file
diff --git a/tests/phase21/endpoint-handler-contract.test.cjs b/tests/phase21/endpoint-handler-contract.test.cjs
index 90a48c71..45078ec2 100644
--- a/tests/phase21/endpoint-handler-contract.test.cjs
+++ b/tests/phase21/endpoint-handler-contract.test.cjs
@@ -9,6 +9,71 @@ const {
const tests = [];
const test = (name, fn) => tests.push({ name, fn });
+test("getCrmPersonalAccount returns the CRM response unchanged", async () => {
+ const contactId = "726158c6-708d-ec11-aad8-00224800be9c";
+ const crmResponse = {
+ contactid: contactId,
+ firstname: "Test",
+ lastname: "User",
+ emailaddress1: "test@example.com"
+ };
+
+ let capturedQueryUrl;
+
+ const mod = loadModule("lib/server/getCrmPersonalAccount.js", {
+ relayGetData: async ({ queryUrl }) => {
+ capturedQueryUrl = queryUrl;
+ return { data: crmResponse };
+ }
+ });
+
+ const result = await mod.getCrmPersonalAccount(contactId);
+
+ assert.deepStrictEqual(result, crmResponse);
+ assert.strictEqual(
+ capturedQueryUrl,
+ "contacts(" +
+ contactId +
+ ")?$select=firstname, lastname, emailaddress1, telephone1, pinswg_companyname, address1_line1,address1_line2,address1_city, address1_county,address1_postalcode,pinswg_typeofinvolvement,pinswg_contact_associatedlpa,pinswg_preferredlanguage&$count=true"
+ );
+});
+
+test("getCrmPersonalAccount preserves the CRM lookup relay policy", async () => {
+ let capturedRelayPolicy;
+
+ const mod = loadModule("lib/server/getCrmPersonalAccount.js", {
+ relayGetData: async ({ relayPolicy }) => {
+ capturedRelayPolicy = relayPolicy;
+ return { data: {} };
+ }
+ });
+
+ await mod.getCrmPersonalAccount("726158c6-708d-ec11-aad8-00224800be9c");
+
+ assert.deepStrictEqual(JSON.parse(JSON.stringify(capturedRelayPolicy)), {
+ method: "GET",
+ timeoutMs: 6000,
+ maxRetries: 1,
+ retryBaseDelayMs: 100,
+ retryMaxDelayMs: 500
+ });
+});
+
+test("getCrmPersonalAccount propagates CRM relay failures", async () => {
+ const relayError = new Error("CRM relay unavailable");
+
+ const mod = loadModule("lib/server/getCrmPersonalAccount.js", {
+ relayGetData: async () => {
+ throw relayError;
+ }
+ });
+
+ await assert.rejects(
+ () => mod.getCrmPersonalAccount("726158c6-708d-ec11-aad8-00224800be9c"),
+ (error) => error === relayError
+ );
+});
+
test("getaccounts returns EMAIL_ADDRESS_REQUIRED when emailAddress missing", async () => {
const mod = loadModule("pages/api/endpoint/getaccounts_api.js", {
respondError: respondErrorMock,
@@ -231,98 +296,6 @@ test("getpreferredlanguage success returns existing data payload contract", asyn
});
});
-test("getlogin returns EMAIL_ADDRESS_REQUIRED when emailAddress missing", async () => {
- const mod = loadModule("pages/api/endpoint/getlogin_api.js", {
- respondError: respondErrorMock,
- respondSuccess: respondSuccessMock,
- relayGet: async () => ({}),
- getToken: async () => ({ access_token: "token" }),
- hashAPIPath: () => "&hash=expected",
- azureHeadersPaged: () => ({}),
- axios: { get: async () => ({ data: { value: [] } }) },
- consoleLogger: () => {}
- });
-
- const req = { query: { pwd: "abc123" } };
- const res = createRes();
- await mod.default(req, res);
-
- assert.strictEqual(res.state.statusCode, 400);
- assert.strictEqual(res.state.jsonBody.error.code, "EMAIL_ADDRESS_REQUIRED");
-});
-
-test("getlogin returns PASSWORD_REQUIRED when pwd missing", async () => {
- const mod = loadModule("pages/api/endpoint/getlogin_api.js", {
- respondError: respondErrorMock,
- respondSuccess: respondSuccessMock,
- relayGet: async () => ({}),
- getToken: async () => ({ access_token: "token" }),
- hashAPIPath: () => "&hash=expected",
- azureHeadersPaged: () => ({}),
- axios: { get: async () => ({ data: { value: [] } }) },
- consoleLogger: () => {}
- });
-
- const req = { query: { emailAddress: "user@test.local" } };
- const res = createRes();
- await mod.default(req, res);
-
- assert.strictEqual(res.state.statusCode, 400);
- assert.strictEqual(res.state.jsonBody.error.code, "PASSWORD_REQUIRED");
-});
-
-test("getlogin catch path returns LOGIN_FETCH_FAILED", async () => {
- const mod = loadModule("pages/api/endpoint/getlogin_api.js", {
- respondError: respondErrorMock,
- respondSuccess: respondSuccessMock,
- relayGet: async ({ res, errorResponse }) =>
- respondErrorMock(res, errorResponse),
- getToken: async () => ({ access_token: "token" }),
- hashAPIPath: () => "&hash=expected",
- azureHeadersPaged: () => ({}),
- axios: {
- get: async () => {
- throw new Error("relay failed");
- }
- },
- consoleLogger: () => {}
- });
-
- const req = { query: { emailAddress: "user@test.local", pwd: "abc123" } };
- const res = createRes();
- await mod.default(req, res);
-
- assert.strictEqual(res.state.statusCode, 400);
- assert.strictEqual(res.state.jsonBody.error.code, "LOGIN_FETCH_FAILED");
-});
-
-test("getlogin passes strict relayPolicy overrides to relayGet", async () => {
- let capturedRelayPolicy = null;
-
- const mod = loadModule("pages/api/endpoint/getlogin_api.js", {
- respondError: respondErrorMock,
- respondSuccess: respondSuccessMock,
- relayGet: async ({ relayPolicy, res }) => {
- capturedRelayPolicy = relayPolicy;
- return respondSuccessMock(res, { value: [] });
- },
- azureHeadersPaged: () => ({})
- });
-
- const req = { query: { emailAddress: "user@test.local", pwd: "abc123" } };
- const res = createRes();
- await mod.default(req, res);
-
- assert.strictEqual(res.state.statusCode, 200);
- assert.deepStrictEqual(JSON.parse(JSON.stringify(capturedRelayPolicy)), {
- method: "GET",
- timeoutMs: 5000,
- maxRetries: 0,
- retryBaseDelayMs: 0,
- retryMaxDelayMs: 0
- });
-});
-
test("getportallogin returns HASH_REQUIRED when hash missing", async () => {
const mod = loadModule("pages/api/endpoint/getportallogin_api.js", {
respondError: respondErrorMock,
@@ -923,35 +896,75 @@ test("createaccount catch path returns ACCOUNT_CREATE_FAILED", async () => {
assert.strictEqual(res.state.jsonBody.error.code, "ACCOUNT_CREATE_FAILED");
});
-test("updateaccount returns CONTACT_ID_REQUIRED when contactId missing", async () => {
+test("updateaccount returns INVALID_CONTACT_ID when contactId missing", async () => {
const mod = loadModule("pages/api/endpoint/updateaccount_api.js", {
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
- getToken: async () => ({ access_token: "token" }),
- hashAPIPath: () => "&hash=expected",
- axios: async () => ({ data: { contactid: "c1" } }),
- consoleLogger: () => {}
+ updateCrmContact: async () => ({ contactid: "c1" }),
+ consoleLogger: () => {},
+ getServerSession: async () => ({
+ user: { email: "owner@example.com" }
+ }),
+ authOptions: () => ({}),
+ getToken: async () => ({
+ access_token: "test-token"
+ }),
+ escapeODataString: (value) => value,
+ azureHeaders: (token) => ({
+ headers: { Authorization: `Bearer ${token}` }
+ }),
+ relayGetData: async () => ({
+ data: {
+ value: [
+ {
+ contactid: "00000000-0000-0000-0000-000000000001"
+ }
+ ]
+ }
+ })
});
- const req = { query: {}, body: { firstname: "A" } };
+ const req = { method: "POST", query: {}, body: { firstname: "A" } };
const res = createRes();
await mod.default(req, res);
assert.strictEqual(res.state.statusCode, 400);
- assert.strictEqual(res.state.jsonBody.error.code, "CONTACT_ID_REQUIRED");
+ assert.strictEqual(res.state.jsonBody.error.code, "INVALID_CONTACT_ID");
});
test("updateaccount returns ACCOUNT_UPDATE_PAYLOAD_REQUIRED when body missing", async () => {
const mod = loadModule("pages/api/endpoint/updateaccount_api.js", {
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
- getToken: async () => ({ access_token: "token" }),
- hashAPIPath: () => "&hash=expected",
- axios: async () => ({ data: { contactid: "c1" } }),
- consoleLogger: () => {}
+ updateCrmContact: async () => ({ contactid: "c1" }),
+ consoleLogger: () => {},
+ getServerSession: async () => ({
+ user: { email: "owner@example.com" }
+ }),
+ authOptions: () => ({}),
+ getToken: async () => ({
+ access_token: "test-token"
+ }),
+ escapeODataString: (value) => value,
+ azureHeaders: (token) => ({
+ headers: { Authorization: `Bearer ${token}` }
+ }),
+ relayGetData: async () => ({
+ data: {
+ value: [
+ {
+ contactid: "00000000-0000-0000-0000-000000000001"
+ }
+ ]
+ }
+ })
});
- const req = { query: { contactId: "c1" }, body: undefined };
+ const req = {
+ method: "POST",
+ query: { contactId: "00000000-0000-0000-0000-000000000001" },
+ body: undefined
+ };
const res = createRes();
await mod.default(req, res);
@@ -966,15 +979,37 @@ test("updateaccount catch path returns ACCOUNT_UPDATE_FAILED", async () => {
const mod = loadModule("pages/api/endpoint/updateaccount_api.js", {
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
- getToken: async () => ({ access_token: "token" }),
- hashAPIPath: () => "&hash=expected",
- axios: async () => {
+ updateCrmContact: async () => {
throw new Error("relay failed");
},
- consoleLogger: () => {}
+ consoleLogger: () => {},
+ getServerSession: async () => ({
+ user: { email: "owner@example.com" }
+ }),
+ authOptions: () => ({}),
+ getToken: async () => ({
+ access_token: "test-token"
+ }),
+ escapeODataString: (value) => value,
+ azureHeaders: (token) => ({
+ headers: { Authorization: `Bearer ${token}` }
+ }),
+ relayGetData: async () => ({
+ data: {
+ value: [
+ {
+ contactid: "00000000-0000-0000-0000-000000000001"
+ }
+ ]
+ }
+ })
});
- const req = { query: { contactId: "c1" }, body: { firstname: "A" } };
+ const req = {
+ method: "POST",
+ query: { contactId: "00000000-0000-0000-0000-000000000001" },
+ body: { firstname: "A" }
+ };
const res = createRes();
await mod.default(req, res);
@@ -982,66 +1017,238 @@ test("updateaccount catch path returns ACCOUNT_UPDATE_FAILED", async () => {
assert.strictEqual(res.state.jsonBody.error.code, "ACCOUNT_UPDATE_FAILED");
});
-test("updatepassword returns CONTACT_ID_REQUIRED when contactId missing", async () => {
- const mod = loadModule("pages/api/endpoint/updatepassword_api.js", {
+test("updateaccount rejects a different CRM contact before updating", async () => {
+ let updateCalls = 0;
+
+ const mod = loadModule("pages/api/endpoint/updateaccount_api.js", {
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
- getToken: async () => ({ access_token: "token" }),
- hashAPIPath: () => "&hash=expected",
- axios: async () => ({ data: { contactid: "c1" } }),
- consoleLogger: () => {}
+ consoleLogger: () => {},
+
+ getServerSession: async () => ({
+ user: { email: "owner@example.com" }
+ }),
+ authOptions: () => ({}),
+
+ getToken: async () => ({
+ access_token: "test-token"
+ }),
+ escapeODataString: (value) => value,
+ azureHeaders: (token) => ({
+ headers: { Authorization: `Bearer ${token}` }
+ }),
+
+ relayGetData: async () => ({
+ data: {
+ value: [
+ {
+ contactid: "00000000-0000-0000-0000-000000000001"
+ }
+ ]
+ }
+ }),
+
+ updateCrmContact: async () => {
+ updateCalls++;
+ return {};
+ }
});
- const req = { query: {}, body: { pinswg_password: "abc" } };
+ const req = {
+ method: "POST",
+ query: {
+ contactId: "00000000-0000-0000-0000-000000000002"
+ },
+ body: {
+ firstname: "Unauthorised Update"
+ }
+ };
+
const res = createRes();
+
await mod.default(req, res);
- assert.strictEqual(res.state.statusCode, 400);
- assert.strictEqual(res.state.jsonBody.error.code, "CONTACT_ID_REQUIRED");
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(
+ res.state.jsonBody.error.code,
+ "CONTACT_OWNERSHIP_MISMATCH"
+ );
+ assert.strictEqual(updateCalls, 0);
});
-test("updatepassword returns PASSWORD_UPDATE_PAYLOAD_REQUIRED when body missing", async () => {
- const mod = loadModule("pages/api/endpoint/updatepassword_api.js", {
+test("updateaccount rejects unresolved CRM identity before updating", async () => {
+ let updateCalls = 0;
+
+ const mod = loadModule("pages/api/endpoint/updateaccount_api.js", {
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
- getToken: async () => ({ access_token: "token" }),
- hashAPIPath: () => "&hash=expected",
- axios: async () => ({ data: { contactid: "c1" } }),
- consoleLogger: () => {}
+ consoleLogger: () => {},
+
+ getServerSession: async () => ({
+ user: { email: "owner@example.com" }
+ }),
+ authOptions: () => ({}),
+
+ getToken: async () => ({
+ access_token: "test-token"
+ }),
+ escapeODataString: (value) => value,
+ azureHeaders: (token) => ({
+ headers: { Authorization: `Bearer ${token}` }
+ }),
+
+ relayGetData: async () => ({
+ data: {
+ value: []
+ }
+ }),
+
+ updateCrmContact: async () => {
+ updateCalls++;
+ return {};
+ }
});
- const req = { query: { contactId: "c1" }, body: undefined };
+ const req = {
+ method: "POST",
+ query: {
+ contactId: "00000000-0000-0000-0000-000000000001"
+ },
+ body: {
+ firstname: "Unauthorised Update"
+ }
+ };
+
const res = createRes();
+
+ await mod.default(req, res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(
+ res.state.jsonBody.error.code,
+ "CONTACT_IDENTITY_NOT_RESOLVED"
+ );
+ assert.strictEqual(updateCalls, 0);
+});
+
+test("updateaccount strips prohibited CRM fields before updating", async () => {
+ const contactId = "00000000-0000-0000-0000-000000000001";
+ let capturedContactId;
+ let capturedPayload;
+ let updateCalls = 0;
+
+ const mod = loadModule("pages/api/endpoint/updateaccount_api.js", {
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock,
+ consoleLogger: () => {},
+
+ getServerSession: async () => ({
+ user: { email: "owner@example.com" }
+ }),
+ authOptions: () => ({}),
+
+ getToken: async () => ({
+ access_token: "test-token"
+ }),
+ escapeODataString: (value) => value,
+ azureHeaders: (token) => ({
+ headers: { Authorization: `Bearer ${token}` }
+ }),
+
+ relayGetData: async () => ({
+ data: {
+ value: [{ contactid: contactId }]
+ }
+ }),
+
+ updateCrmContact: async (id, payload) => {
+ updateCalls++;
+ capturedContactId = id;
+ capturedPayload = payload;
+ return { contactid: id };
+ }
+ });
+
+ const req = {
+ method: "POST",
+ query: { contactId },
+ body: {
+ firstname: "Robert",
+ telephone1: "01234567890",
+ emailaddress1: "attacker@example.com",
+ statuscode: 2,
+ contactid: "00000000-0000-0000-0000-000000000002"
+ }
+ };
+
+ const res = createRes();
+
+ await mod.default(req, res);
+
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.strictEqual(updateCalls, 1);
+ assert.strictEqual(capturedContactId, contactId);
+
+ assert.deepStrictEqual(JSON.parse(JSON.stringify(capturedPayload)), {
+ firstname: "Robert",
+ telephone1: "01234567890"
+ });
+});
+
+test("updateaccount rejects payload containing only prohibited fields", async () => {
+ const contactId = "00000000-0000-0000-0000-000000000001";
+ let updateCalls = 0;
+
+ const mod = loadModule("pages/api/endpoint/updateaccount_api.js", {
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock,
+ consoleLogger: () => {},
+
+ getServerSession: async () => ({
+ user: { email: "owner@example.com" }
+ }),
+ authOptions: () => ({}),
+
+ getToken: async () => ({
+ access_token: "test-token"
+ }),
+ escapeODataString: (value) => value,
+ azureHeaders: (token) => ({
+ headers: { Authorization: `Bearer ${token}` }
+ }),
+
+ relayGetData: async () => ({
+ data: {
+ value: [{ contactid: contactId }]
+ }
+ }),
+
+ updateCrmContact: async () => {
+ updateCalls++;
+ return {};
+ }
+ });
+
+ const req = {
+ method: "POST",
+ query: { contactId },
+ body: {
+ emailaddress1: "attacker@example.com",
+ statuscode: 2,
+ contactid: "00000000-0000-0000-0000-000000000002"
+ }
+ };
+
+ const res = createRes();
+
await mod.default(req, res);
assert.strictEqual(res.state.statusCode, 400);
assert.strictEqual(
res.state.jsonBody.error.code,
- "PASSWORD_UPDATE_PAYLOAD_REQUIRED"
+ "NO_ALLOWED_ACCOUNT_FIELDS"
);
-});
-
-test("updatepassword catch path returns PASSWORD_UPDATE_FAILED", async () => {
- const mod = loadModule("pages/api/endpoint/updatepassword_api.js", {
- respondError: respondErrorMock,
- respondSuccess: respondSuccessMock,
- getToken: async () => ({ access_token: "token" }),
- hashAPIPath: () => "&hash=expected",
- axios: async () => {
- throw new Error("relay failed");
- },
- consoleLogger: () => {}
- });
-
- const req = {
- query: { contactId: "c1" },
- body: { pinswg_password: "abc" }
- };
- const res = createRes();
- await mod.default(req, res);
-
- assert.strictEqual(res.state.statusCode, 400);
- assert.strictEqual(res.state.jsonBody.error.code, "PASSWORD_UPDATE_FAILED");
+ assert.strictEqual(updateCalls, 0);
});
test("getbasicsearch returns SEARCH_STRING_REQUIRED when searchString missing", async () => {
@@ -1215,7 +1422,7 @@ test("getadvancedsearchpaged returns SEARCH_STRING_REQUIRED when searchstring mi
respondSuccess: respondSuccessMock,
relayGet: async () => ({}),
azureHeadersPagedCustom: () => ({}),
- _: { has: () => false }
+ hasOwn: (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)
});
const req = {
@@ -1238,7 +1445,7 @@ test("getadvancedsearchpaged returns ORDER_BY_REQUIRED when orderby missing", as
respondSuccess: respondSuccessMock,
relayGet: async () => ({}),
azureHeadersPagedCustom: () => ({}),
- _: { has: () => false }
+ hasOwn: (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)
});
const req = {
@@ -1262,7 +1469,7 @@ test("getadvancedsearchpaged catch path returns ADVANCED_SEARCH_PAGED_FETCH_FAIL
relayGet: async ({ res, errorResponse }) =>
respondErrorMock(res, errorResponse),
azureHeadersPagedCustom: () => ({}),
- _: { has: () => false }
+ hasOwn: (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)
});
const req = {
@@ -2912,10 +3119,16 @@ test("createwatchedcases returns WATCHED_CASE_BINDINGS_REQUIRED when bindings mi
getToken: async () => ({ access_token: "token" }),
hashAPIPath: () => "&hash=expected",
axios: async () => ({ data: {} }),
- consoleLogger: () => {}
+ consoleLogger: () => {},
+ getServerSession: async () => ({
+ user: {
+ email: "test@example.com"
+ }
+ }),
+ authOptions: () => ({})
});
- const req = { body: {} };
+ const req = { method: "POST", body: {} };
const res = createRes();
await mod.default(req, res);
@@ -2933,10 +3146,17 @@ test("createwatchedcases returns INVALID_BINDING_FORMAT when bindings invalid",
getToken: async () => ({ access_token: "token" }),
hashAPIPath: () => "&hash=expected",
axios: async () => ({ data: {} }),
- consoleLogger: () => {}
+ consoleLogger: () => {},
+ getServerSession: async () => ({
+ user: {
+ email: "test@example.com"
+ }
+ }),
+ authOptions: () => ({})
});
const req = {
+ method: "POST",
body: {
"pinswg_WatchedCase@odata.bind": "/incidents",
"pinswg_Contact@odata.bind": "/contacts"
@@ -2958,13 +3178,22 @@ test("createwatchedcases catch path returns WATCHED_CASE_UPSERT_FAILED", async (
},
hashAPIPath: () => "&hash=expected",
axios: async () => ({ data: {} }),
- consoleLogger: () => {}
+ consoleLogger: () => {},
+ getServerSession: async () => ({
+ user: {
+ email: "test@example.com"
+ }
+ }),
+ authOptions: () => ({})
});
const req = {
+ method: "POST",
body: {
- "pinswg_WatchedCase@odata.bind": "/incidents(incident-id)",
- "pinswg_Contact@odata.bind": "/contacts(contact-id)"
+ "pinswg_WatchedCase@odata.bind":
+ "/incidents(11111111-1111-1111-1111-111111111111)",
+ "pinswg_Contact@odata.bind":
+ "/contacts(22222222-2222-2222-2222-222222222222)"
}
};
const res = createRes();
@@ -2977,48 +3206,841 @@ test("createwatchedcases catch path returns WATCHED_CASE_UPSERT_FAILED", async (
);
});
-test("deletewatchedcases returns WATCHED_CASE_ID_REQUIRED when watchedCaseID missing", async () => {
- const mod = loadModule("pages/api/endpoint/deletewatchedcases_api.js", {
+test("createwatchedcases rejects unauthenticated requests before CRM access", async () => {
+ let tokenCalls = 0;
+ let relayCalls = 0;
+ let writeCalls = 0;
+
+ const mod = loadModule("pages/api/endpoint/createwatchedcases_api.js", {
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
- getToken: async () => ({ access_token: "token" }),
+ getServerSession: async () => null,
+ authOptions: () => ({}),
+ getToken: async () => {
+ tokenCalls += 1;
+ return { access_token: "token" };
+ },
+ relayGetData: async () => {
+ relayCalls += 1;
+ return { data: { value: [] } };
+ },
hashAPIPath: () => "&hash=expected",
- axios: async () => ({ data: {} }),
- consoleLogger: () => {}
+ axios: async () => {
+ writeCalls += 1;
+ return { data: {} };
+ },
+ consoleLogger: () => {},
+ authOptions: () => ({})
});
- const req = { query: {} };
+ const req = {
+ method: "POST",
+ body: {
+ "pinswg_WatchedCase@odata.bind":
+ "/incidents(11111111-1111-1111-1111-111111111111)",
+ "pinswg_Contact@odata.bind":
+ "/contacts(22222222-2222-2222-2222-222222222222)"
+ }
+ };
+
const res = createRes();
await mod.default(req, res);
- assert.strictEqual(res.state.statusCode, 400);
- assert.strictEqual(
- res.state.jsonBody.error.code,
- "WATCHED_CASE_ID_REQUIRED"
- );
+ assert.strictEqual(res.state.statusCode, 401);
+ assert.strictEqual(res.state.jsonBody.error.code, "UNAUTHENTICATED");
+ assert.strictEqual(tokenCalls, 0);
+ assert.strictEqual(relayCalls, 0);
+ assert.strictEqual(writeCalls, 0);
});
-test("deletewatchedcases catch path returns WATCHED_CASE_DELETE_FAILED", async () => {
- const mod = loadModule("pages/api/endpoint/deletewatchedcases_api.js", {
+test("createwatchedcases rejects another contact before CRM write", async () => {
+ let writeCalls = 0;
+
+ const ownContactID = "22222222-2222-2222-2222-222222222222";
+ const otherContactID = "33333333-3333-3333-3333-333333333333";
+
+ const mod = loadModule("pages/api/endpoint/createwatchedcases_api.js", {
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
+ getServerSession: async () => ({
+ user: { email: "test@example.com" }
+ }),
+ authOptions: () => ({}),
getToken: async () => ({ access_token: "token" }),
+ azureHeaders: () => ({
+ headers: { Authorization: "Bearer token" }
+ }),
+ escapeODataString: (value) => value.replace(/'/g, "''"),
+ relayGetData: async ({ queryUrl }) => {
+ if (queryUrl.startsWith("contacts?")) {
+ return {
+ data: {
+ value: [{ contactid: ownContactID }]
+ }
+ };
+ }
+
+ return { data: { value: [] } };
+ },
hashAPIPath: () => "&hash=expected",
axios: async () => {
- throw new Error("delete failed");
+ writeCalls += 1;
+ return { data: {} };
},
consoleLogger: () => {}
});
- const req = { query: { watchedCaseID: "w1" } };
+ const req = {
+ method: "POST",
+ body: {
+ "pinswg_WatchedCase@odata.bind":
+ "/incidents(11111111-1111-1111-1111-111111111111)",
+ "pinswg_Contact@odata.bind": `/contacts(${otherContactID})`
+ }
+ };
+
+ const res = createRes();
+ await mod.default(req, res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(
+ res.state.jsonBody.error.code,
+ "CONTACT_OWNERSHIP_MISMATCH"
+ );
+ assert.strictEqual(writeCalls, 0);
+});
+
+test("createwatchedcases rejects malformed GUID bindings before CRM access", async () => {
+ let tokenCalls = 0;
+ let relayCalls = 0;
+ let writeCalls = 0;
+
+ const mod = loadModule("pages/api/endpoint/createwatchedcases_api.js", {
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock,
+ getServerSession: async () => ({
+ user: { email: "test@example.com" }
+ }),
+ authOptions: () => ({}),
+ getToken: async () => {
+ tokenCalls += 1;
+ return { access_token: "token" };
+ },
+ relayGetData: async () => {
+ relayCalls += 1;
+ return { data: { value: [] } };
+ },
+ hashAPIPath: () => "&hash=expected",
+ axios: async () => {
+ writeCalls += 1;
+ return { data: {} };
+ },
+ consoleLogger: () => {}
+ });
+
+ const req = {
+ method: "POST",
+ body: {
+ "pinswg_WatchedCase@odata.bind": "/incidents(not-a-valid-guid)",
+ "pinswg_Contact@odata.bind":
+ "/contacts(22222222-2222-2222-2222-222222222222)"
+ }
+ };
+
const res = createRes();
await mod.default(req, res);
assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "INVALID_BINDING_FORMAT");
+ assert.strictEqual(tokenCalls, 0);
+ assert.strictEqual(relayCalls, 0);
+ assert.strictEqual(writeCalls, 0);
+});
+
+test("createwatchedcases rejects existing watchlist with mismatched ownership", async () => {
+ let writeCalls = 0;
+
+ const ownContactID = "22222222-2222-2222-2222-222222222222";
+ const otherContactID = "33333333-3333-3333-3333-333333333333";
+ const caseID = "11111111-1111-1111-1111-111111111111";
+
+ const mod = loadModule("pages/api/endpoint/createwatchedcases_api.js", {
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock,
+ getServerSession: async () => ({
+ user: { email: "test@example.com" }
+ }),
+ authOptions: () => ({}),
+ getToken: async () => ({ access_token: "token" }),
+ azureHeaders: () => ({
+ headers: { Authorization: "Bearer token" }
+ }),
+ escapeODataString: (value) => value.replace(/'/g, "''"),
+ relayGetData: async ({ queryUrl }) => {
+ if (queryUrl.startsWith("contacts?")) {
+ return {
+ data: { value: [{ contactid: ownContactID }] }
+ };
+ }
+
+ if (queryUrl.startsWith("pinswg_watchlists?")) {
+ return {
+ data: {
+ value: [
+ {
+ pinswg_watchlistid:
+ "44444444-4444-4444-4444-444444444444",
+ _pinswg_contact_value: otherContactID,
+ _pinswg_watchedcase_value: caseID
+ }
+ ]
+ }
+ };
+ }
+
+ throw new Error("Unexpected CRM query");
+ },
+ hashAPIPath: () => "&hash=expected",
+ axios: async () => {
+ writeCalls += 1;
+ return { data: {} };
+ },
+ consoleLogger: () => {}
+ });
+
+ const req = {
+ method: "POST",
+ body: {
+ "pinswg_WatchedCase@odata.bind": `/incidents(${caseID})`,
+ "pinswg_Contact@odata.bind": `/contacts(${ownContactID})`
+ }
+ };
+
+ const res = createRes();
+ await mod.default(req, res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(
+ res.state.jsonBody.error.code,
+ "WATCHLIST_OWNERSHIP_MISMATCH"
+ );
+ assert.strictEqual(writeCalls, 0);
+});
+
+test("createwatchedcases allows multiple existing watchlists for the same contact and case", async () => {
+ const writes = [];
+
+ const contactID = "22222222-2222-2222-2222-222222222222";
+ const caseID = "11111111-1111-1111-1111-111111111111";
+
+ const mod = loadModule("pages/api/endpoint/createwatchedcases_api.js", {
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock,
+ getServerSession: async () => ({
+ user: { email: "test@example.com" }
+ }),
+ authOptions: () => ({}),
+ getToken: async () => ({ access_token: "token" }),
+ azureHeaders: () => ({
+ headers: { Authorization: "Bearer token" }
+ }),
+ escapeODataString: (value) => value.replace(/'/g, "''"),
+ relayGetData: async ({ queryUrl }) => {
+ if (queryUrl.startsWith("contacts?")) {
+ return {
+ data: { value: [{ contactid: contactID }] }
+ };
+ }
+
+ if (queryUrl.startsWith("pinswg_watchlists?")) {
+ return {
+ data: {
+ value: [
+ {
+ pinswg_watchlistid:
+ "44444444-4444-4444-4444-444444444444",
+ _pinswg_contact_value: contactID,
+ _pinswg_watchedcase_value: caseID
+ },
+ {
+ pinswg_watchlistid:
+ "55555555-5555-5555-5555-555555555555",
+ _pinswg_contact_value: contactID,
+ _pinswg_watchedcase_value: caseID
+ }
+ ]
+ }
+ };
+ }
+
+ throw new Error("Unexpected CRM query");
+ },
+ hashAPIPath: () => "&hash=expected",
+ axios: async (config) => {
+ writes.push(config);
+ return { data: {} };
+ },
+ consoleLogger: () => {}
+ });
+
+ const req = {
+ method: "POST",
+ body: {
+ "pinswg_WatchedCase@odata.bind": `/incidents(${caseID})`,
+ "pinswg_Contact@odata.bind": `/contacts(${contactID})`
+ }
+ };
+
+ const res = createRes();
+ await mod.default(req, res);
+
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.strictEqual(writes.length, 1);
+ assert.strictEqual(writes[0].method, "patch");
+
+ assert.ok(
+ writes[0].url.includes(
+ "pinswg_watchlists(44444444-4444-4444-4444-444444444444)"
+ )
+ );
+});
+
+test("createwatchedcases creates a watched case for the authenticated contact", async () => {
+ const contactID = "22222222-2222-2222-2222-222222222222";
+ const caseID = "11111111-1111-1111-1111-111111111111";
+ const writes = [];
+
+ const mod = loadModule("pages/api/endpoint/createwatchedcases_api.js", {
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock,
+ getServerSession: async () => ({
+ user: { email: "test@example.com" }
+ }),
+ authOptions: () => ({}),
+ getToken: async () => ({ access_token: "token" }),
+ azureHeaders: () => ({
+ headers: { Authorization: "Bearer token" }
+ }),
+ escapeODataString: (value) => value.replace(/'/g, "''"),
+ relayGetData: async ({ queryUrl }) => {
+ if (queryUrl.startsWith("contacts?")) {
+ return {
+ data: { value: [{ contactid: contactID }] }
+ };
+ }
+
+ if (queryUrl.startsWith("pinswg_watchlists?")) {
+ return { data: { value: [] } };
+ }
+
+ throw new Error("Unexpected CRM query");
+ },
+ hashAPIPath: () => "&hash=expected",
+ axios: async (config) => {
+ writes.push(config);
+ return { data: { created: true } };
+ },
+ consoleLogger: () => {}
+ });
+
+ const body = {
+ "pinswg_WatchedCase@odata.bind": `/incidents(${caseID})`,
+ "pinswg_Contact@odata.bind": `/contacts(${contactID})`,
+ pinswg_emailnotifications: true
+ };
+
+ const res = createRes();
+
+ await mod.default(
+ {
+ method: "POST",
+ body
+ },
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.strictEqual(writes.length, 1);
+ assert.strictEqual(writes[0].method, "post");
+ assert.ok(writes[0].url.includes("pinswg_watchlists"));
+
+ const writtenData = JSON.parse(writes[0].data);
+
+ assert.strictEqual(
+ writtenData["pinswg_Contact@odata.bind"],
+ `/contacts(${contactID})`
+ );
+ assert.strictEqual(
+ writtenData["pinswg_WatchedCase@odata.bind"],
+ `/incidents(${caseID})`
+ );
+ assert.strictEqual(writtenData.pinswg_emailnotifications, true);
+});
+
+test("createwatchedcases updates a verified watchlist preserving representation fields", async () => {
+ const contactID = "22222222-2222-2222-2222-222222222222";
+ const caseID = "11111111-1111-1111-1111-111111111111";
+ const watchlistID = "44444444-4444-4444-4444-444444444444";
+ const writes = [];
+
+ const mod = loadModule("pages/api/endpoint/createwatchedcases_api.js", {
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock,
+ getServerSession: async () => ({
+ user: { email: "test@example.com" }
+ }),
+ authOptions: () => ({}),
+ getToken: async () => ({ access_token: "token" }),
+ azureHeaders: () => ({
+ headers: { Authorization: "Bearer token" }
+ }),
+ escapeODataString: (value) => value.replace(/'/g, "''"),
+ relayGetData: async ({ queryUrl }) => {
+ if (queryUrl.startsWith("contacts?")) {
+ return {
+ data: { value: [{ contactid: contactID }] }
+ };
+ }
+
+ if (queryUrl.startsWith("pinswg_watchlists?")) {
+ return {
+ data: {
+ value: [
+ {
+ pinswg_watchlistid: watchlistID,
+ _pinswg_contact_value: contactID,
+ _pinswg_watchedcase_value: caseID
+ }
+ ]
+ }
+ };
+ }
+
+ throw new Error("Unexpected CRM query");
+ },
+ hashAPIPath: () => "&hash=expected",
+ axios: async (config) => {
+ writes.push(config);
+ return { data: { updated: true } };
+ },
+ consoleLogger: () => {}
+ });
+
+ const body = {
+ "pinswg_WatchedCase@odata.bind": `/incidents(${caseID})`,
+ "pinswg_Contact@odata.bind": `/contacts(${contactID})`,
+ pinswg_emailnotifications: true,
+ pinswg_representationsubmitted: true,
+ pinswg_representationtype: 1
+ };
+
+ const res = createRes();
+
+ await mod.default({ method: "POST", body }, res);
+
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.strictEqual(writes.length, 1);
+ assert.strictEqual(writes[0].method, "patch");
+ assert.ok(writes[0].url.includes(`pinswg_watchlists(${watchlistID})`));
+
+ const writtenData = JSON.parse(writes[0].data);
+
+ assert.strictEqual(writtenData.pinswg_emailnotifications, true);
+ assert.strictEqual(writtenData.pinswg_representationsubmitted, true);
+ assert.strictEqual(writtenData.pinswg_representationtype, 1);
+ assert.strictEqual(
+ writtenData["pinswg_Contact@odata.bind"],
+ `/contacts(${contactID})`
+ );
+});
+
+test("createwatchedcases preserves previous representations when submitting another", async () => {
+ const contactID = "22222222-2222-2222-2222-222222222222";
+ const caseID = "11111111-1111-1111-1111-111111111111";
+ const writes = [];
+
+ const existingRecords = [
+ {
+ pinswg_watchlistid: "44444444-4444-4444-4444-444444444444",
+ _pinswg_contact_value: contactID,
+ _pinswg_watchedcase_value: caseID,
+ pinswg_representationsubmitted: "2025-01-07T10:00:00Z",
+ pinswg_representationtype: 1
+ },
+ {
+ pinswg_watchlistid: "55555555-5555-5555-5555-555555555555",
+ _pinswg_contact_value: contactID,
+ _pinswg_watchedcase_value: caseID,
+ pinswg_representationsubmitted: "2025-01-09T14:00:00Z",
+ pinswg_representationtype: 2
+ }
+ ];
+
+ const mod = loadModule("pages/api/endpoint/createwatchedcases_api.js", {
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock,
+ getServerSession: async () => ({
+ user: { email: "test@example.com" }
+ }),
+ authOptions: () => ({}),
+ getToken: async () => ({ access_token: "token" }),
+ azureHeaders: () => ({
+ headers: { Authorization: "Bearer token" }
+ }),
+ escapeODataString: (value) => value.replace(/'/g, "''"),
+ relayGetData: async ({ queryUrl }) => {
+ if (queryUrl.startsWith("contacts?")) {
+ return {
+ data: { value: [{ contactid: contactID }] }
+ };
+ }
+
+ if (queryUrl.startsWith("pinswg_watchlists?")) {
+ assert.ok(queryUrl.includes("pinswg_representationsubmitted"));
+
+ return {
+ data: { value: existingRecords }
+ };
+ }
+
+ throw new Error("Unexpected CRM query");
+ },
+ hashAPIPath: () => "&hash=expected",
+ axios: async (config) => {
+ writes.push(config);
+ return { data: { created: true } };
+ },
+ consoleLogger: () => {}
+ });
+
+ const submissionDate = "2025-01-14T09:30:00Z";
+
+ const body = {
+ "pinswg_WatchedCase@odata.bind": `/incidents(${caseID})`,
+ "pinswg_Contact@odata.bind": `/contacts(${contactID})`,
+ pinswg_representationsubmitted: submissionDate,
+ pinswg_representationtype: 3
+ };
+
+ const res = createRes();
+
+ await mod.default({ method: "POST", body }, res);
+
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.strictEqual(writes.length, 1);
+
+ // A new submission must not PATCH a historical representation.
+ assert.strictEqual(writes[0].method, "post");
+ assert.ok(writes[0].url.includes("pinswg_watchlists"));
+ assert.ok(
+ !writes[0].url.includes(
+ "pinswg_watchlists(44444444-4444-4444-4444-444444444444)"
+ )
+ );
+
+ const writtenData = JSON.parse(writes[0].data);
+
+ assert.strictEqual(
+ writtenData.pinswg_representationsubmitted,
+ submissionDate
+ );
+ assert.strictEqual(writtenData.pinswg_representationtype, 3);
+ assert.strictEqual(
+ writtenData["pinswg_Contact@odata.bind"],
+ `/contacts(${contactID})`
+ );
+
+ // Neither historical submission was modified.
+ assert.strictEqual(
+ existingRecords[0].pinswg_representationsubmitted,
+ "2025-01-07T10:00:00Z"
+ );
+ assert.strictEqual(
+ existingRecords[1].pinswg_representationsubmitted,
+ "2025-01-09T14:00:00Z"
+ );
+});
+
+const WATCHED_CASE_ID = "11111111-1111-1111-1111-111111111111";
+const CONTACT_ID = "22222222-2222-2222-2222-222222222222";
+const OTHER_CONTACT_ID = "33333333-3333-3333-3333-333333333333";
+
+const createDeleteWatchedCasesFixture = (overrides = {}) => {
+ const calls = {
+ session: [],
+ token: 0,
+ relay: [],
+ delete: []
+ };
+ const session = Object.prototype.hasOwnProperty.call(overrides, "session")
+ ? overrides.session
+ : { user: { email: "user.o'neill@test.local" } };
+ const contacts = Object.prototype.hasOwnProperty.call(overrides, "contacts")
+ ? overrides.contacts
+ : [{ contactid: CONTACT_ID }];
+ const watchlist = Object.prototype.hasOwnProperty.call(
+ overrides,
+ "watchlist"
+ )
+ ? overrides.watchlist
+ : {
+ pinswg_watchlistid: WATCHED_CASE_ID,
+ _pinswg_contact_value: CONTACT_ID
+ };
+
+ const mod = loadModule("pages/api/endpoint/deletewatchedcases_api.js", {
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock,
+ getServerSession: async (...args) => {
+ calls.session.push(args);
+ return session;
+ },
+ authOptions: (req, res) => ({ req, res }),
+ getToken: async () => {
+ calls.token += 1;
+ return { access_token: "token" };
+ },
+ relayGetData: async (options) => {
+ calls.relay.push(options);
+
+ if (options.queryUrl.startsWith("contacts?")) {
+ if (overrides.contactLookupError) {
+ throw overrides.contactLookupError;
+ }
+ return { data: { value: contacts } };
+ }
+
+ if (overrides.watchlistLookupError) {
+ throw overrides.watchlistLookupError;
+ }
+ return { data: watchlist };
+ },
+ escapeODataString: (value) => value.trim().replace(/'/g, "''"),
+ azureHeaders: (accessToken) => ({
+ headers: { Authorization: `Bearer ${accessToken}` }
+ }),
+ hashAPIPath: () => "&hash=expected",
+ axios: async (config) => {
+ calls.delete.push(config);
+ if (overrides.deleteError) throw overrides.deleteError;
+ return { data: { removed: true } };
+ },
+ consoleLogger: () => {}
+ });
+
+ return { mod, calls };
+};
+
+const invokeDeleteWatchedCase = async (fixture, request = {}) => {
+ const req = {
+ method: "DELETE",
+ query: { watchedCaseID: WATCHED_CASE_ID },
+ ...request
+ };
+ const res = createRes();
+ await fixture.mod.default(req, res);
+ return { req, res };
+};
+
+test("deletewatchedcases rejects missing watchedCaseID without CRM access", async () => {
+ const fixture = createDeleteWatchedCasesFixture();
+ const { res } = await invokeDeleteWatchedCase(fixture, { query: {} });
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(
+ res.state.jsonBody.error.code,
+ "INVALID_WATCHED_CASE_ID"
+ );
+ assert.strictEqual(fixture.calls.session.length, 0);
+ assert.strictEqual(fixture.calls.token, 0);
+ assert.strictEqual(fixture.calls.delete.length, 0);
+});
+
+test("deletewatchedcases rejects malformed and array watchedCaseID values", async () => {
+ for (const watchedCaseID of [
+ "not-a-guid",
+ ` ${WATCHED_CASE_ID} `,
+ [WATCHED_CASE_ID]
+ ]) {
+ const fixture = createDeleteWatchedCasesFixture();
+ const { res } = await invokeDeleteWatchedCase(fixture, {
+ query: { watchedCaseID }
+ });
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(
+ res.state.jsonBody.error.code,
+ "INVALID_WATCHED_CASE_ID"
+ );
+ assert.strictEqual(fixture.calls.token, 0);
+ assert.strictEqual(fixture.calls.delete.length, 0);
+ }
+});
+
+test("deletewatchedcases rejects non-DELETE methods without CRM access", async () => {
+ const fixture = createDeleteWatchedCasesFixture();
+ const { res } = await invokeDeleteWatchedCase(fixture, { method: "GET" });
+
+ assert.strictEqual(res.state.statusCode, 405);
+ assert.strictEqual(res.state.jsonBody.error.code, "METHOD_NOT_ALLOWED");
+ assert.strictEqual(fixture.calls.session.length, 0);
+ assert.strictEqual(fixture.calls.token, 0);
+ assert.strictEqual(fixture.calls.delete.length, 0);
+});
+
+test("deletewatchedcases rejects missing session without CRM access", async () => {
+ const fixture = createDeleteWatchedCasesFixture({ session: null });
+ const { req, res } = await invokeDeleteWatchedCase(fixture);
+
+ assert.strictEqual(res.state.statusCode, 401);
+ assert.strictEqual(res.state.jsonBody.error.code, "UNAUTHENTICATED");
+ assert.strictEqual(fixture.calls.session[0][0], req);
+ assert.strictEqual(fixture.calls.session[0][1], res);
+ assert.strictEqual(fixture.calls.token, 0);
+ assert.strictEqual(fixture.calls.delete.length, 0);
+});
+
+test("deletewatchedcases rejects session without email", async () => {
+ const fixture = createDeleteWatchedCasesFixture({
+ session: { user: { id: "application-user" } }
+ });
+ const { res } = await invokeDeleteWatchedCase(fixture);
+
+ assert.strictEqual(res.state.statusCode, 401);
+ assert.strictEqual(res.state.jsonBody.error.code, "UNAUTHENTICATED");
+ assert.strictEqual(fixture.calls.token, 0);
+ assert.strictEqual(fixture.calls.delete.length, 0);
+});
+
+test("deletewatchedcases denies zero active CRM contacts", async () => {
+ const fixture = createDeleteWatchedCasesFixture({ contacts: [] });
+ const { res } = await invokeDeleteWatchedCase(fixture);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(
+ res.state.jsonBody.error.code,
+ "CONTACT_IDENTITY_NOT_RESOLVED"
+ );
+ assert.strictEqual(fixture.calls.delete.length, 0);
+});
+
+test("deletewatchedcases denies multiple active CRM contacts", async () => {
+ const fixture = createDeleteWatchedCasesFixture({
+ contacts: [{ contactid: CONTACT_ID }, { contactid: OTHER_CONTACT_ID }]
+ });
+ const { res } = await invokeDeleteWatchedCase(fixture);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(
+ res.state.jsonBody.error.code,
+ "CONTACT_IDENTITY_NOT_RESOLVED"
+ );
+ assert.strictEqual(fixture.calls.delete.length, 0);
+});
+
+test("deletewatchedcases fails closed when CRM contact lookup fails", async () => {
+ const fixture = createDeleteWatchedCasesFixture({
+ contactLookupError: new Error("CRM unavailable")
+ });
+ const { res } = await invokeDeleteWatchedCase(fixture);
+
+ assert.strictEqual(res.state.statusCode, 500);
assert.strictEqual(
res.state.jsonBody.error.code,
"WATCHED_CASE_DELETE_FAILED"
);
+ assert.strictEqual(fixture.calls.delete.length, 0);
+});
+
+test("deletewatchedcases returns 404 for unknown watchlist", async () => {
+ const lookupError = new Error("not found");
+ lookupError.response = { status: 404 };
+ const fixture = createDeleteWatchedCasesFixture({
+ watchlistLookupError: lookupError
+ });
+ const { res } = await invokeDeleteWatchedCase(fixture);
+
+ assert.strictEqual(res.state.statusCode, 404);
+ assert.strictEqual(res.state.jsonBody.error.code, "WATCHED_CASE_NOT_FOUND");
+ assert.strictEqual(fixture.calls.delete.length, 0);
+});
+
+test("deletewatchedcases returns 404 for non-owned watchlist", async () => {
+ const fixture = createDeleteWatchedCasesFixture({
+ watchlist: {
+ pinswg_watchlistid: WATCHED_CASE_ID,
+ _pinswg_contact_value: OTHER_CONTACT_ID
+ }
+ });
+ const { res } = await invokeDeleteWatchedCase(fixture);
+
+ assert.strictEqual(res.state.statusCode, 404);
+ assert.strictEqual(res.state.jsonBody.error.code, "WATCHED_CASE_NOT_FOUND");
+ assert.strictEqual(fixture.calls.delete.length, 0);
+});
+
+test("deletewatchedcases deletes exactly once for the authenticated CRM contact", async () => {
+ const fixture = createDeleteWatchedCasesFixture();
+ const { req, res } = await invokeDeleteWatchedCase(fixture);
+
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.deepStrictEqual(JSON.parse(JSON.stringify(res.state.jsonBody)), {
+ removed: true
+ });
+ assert.strictEqual(fixture.calls.relay.length, 2);
+ assert.strictEqual(
+ fixture.calls.relay[0].queryUrl,
+ "contacts?$filter=emailaddress1 eq 'user.o''neill@test.local' and statuscode eq 1&$select=contactid"
+ );
+ assert.strictEqual(
+ fixture.calls.relay[1].queryUrl,
+ `pinswg_watchlists(${WATCHED_CASE_ID})?$select=pinswg_watchlistid,_pinswg_contact_value`
+ );
+ assert.strictEqual(fixture.calls.delete.length, 1);
+ assert.strictEqual(fixture.calls.delete[0].method, "delete");
+ assert.match(
+ fixture.calls.delete[0].url,
+ new RegExp(`pinswg_watchlists\\(${WATCHED_CASE_ID}\\)&hash=expected$`)
+ );
+ assert.strictEqual(fixture.calls.session[0][0], req);
+});
+
+test("deletewatchedcases ignores client-supplied contact and email identity", async () => {
+ const fixture = createDeleteWatchedCasesFixture({
+ watchlist: {
+ pinswg_watchlistid: WATCHED_CASE_ID,
+ _pinswg_contact_value: OTHER_CONTACT_ID
+ }
+ });
+ const { res } = await invokeDeleteWatchedCase(fixture, {
+ query: {
+ watchedCaseID: WATCHED_CASE_ID,
+ contactid: OTHER_CONTACT_ID,
+ email: "other@test.local"
+ },
+ body: { contactid: OTHER_CONTACT_ID, email: "other@test.local" }
+ });
+
+ assert.strictEqual(res.state.statusCode, 404);
+ assert.match(fixture.calls.relay[0].queryUrl, /user\.o''neill@test\.local/);
+ assert.doesNotMatch(fixture.calls.relay[0].queryUrl, /other@test\.local/);
+ assert.strictEqual(fixture.calls.delete.length, 0);
+});
+
+test("deletewatchedcases does not let a valid HMAC override ownership", async () => {
+ const fixture = createDeleteWatchedCasesFixture({
+ watchlist: {
+ pinswg_watchlistid: WATCHED_CASE_ID,
+ _pinswg_contact_value: OTHER_CONTACT_ID
+ }
+ });
+ const { res } = await invokeDeleteWatchedCase(fixture, {
+ query: { watchedCaseID: WATCHED_CASE_ID, hash: "valid-signature" }
+ });
+
+ assert.strictEqual(res.state.statusCode, 404);
+ assert.strictEqual(res.state.jsonBody.error.code, "WATCHED_CASE_NOT_FOUND");
+ assert.strictEqual(fixture.calls.delete.length, 0);
});
test("deletewatchedcasesproxy returns WATCHED_CASE_ID_REQUIRED when watchedCaseID missing", async () => {
@@ -3073,56 +4095,6 @@ test("deletewatchedcasesproxy catch path returns WATCHED_CASE_PROXY_DELETE_FAILE
);
});
-test("deletemyrepresentations returns MY_REPRESENTATION_ID_REQUIRED when myRepresentationsID missing", async () => {
- const mod = loadModule(
- "pages/api/endpoint/deletemyrepresentations_api.js",
- {
- respondError: respondErrorMock,
- respondSuccess: respondSuccessMock,
- getToken: async () => ({ access_token: "token" }),
- hashAPIPath: () => "&hash=expected",
- axios: async () => ({ data: {} }),
- consoleLogger: () => {}
- }
- );
-
- const req = { query: {} };
- const res = createRes();
- await mod.default(req, res);
-
- assert.strictEqual(res.state.statusCode, 400);
- assert.strictEqual(
- res.state.jsonBody.error.code,
- "MY_REPRESENTATION_ID_REQUIRED"
- );
-});
-
-test("deletemyrepresentations catch path returns MY_REPRESENTATION_DELETE_FAILED", async () => {
- const mod = loadModule(
- "pages/api/endpoint/deletemyrepresentations_api.js",
- {
- respondError: respondErrorMock,
- respondSuccess: respondSuccessMock,
- getToken: async () => ({ access_token: "token" }),
- hashAPIPath: () => "&hash=expected",
- axios: async () => {
- throw new Error("delete failed");
- },
- consoleLogger: () => {}
- }
- );
-
- const req = { query: { myRepresentationsID: "r1" } };
- const res = createRes();
- await mod.default(req, res);
-
- assert.strictEqual(res.state.statusCode, 400);
- assert.strictEqual(
- res.state.jsonBody.error.code,
- "MY_REPRESENTATION_DELETE_FAILED"
- );
-});
-
test("deleteawaitingsubmissions returns INCIDENT_ID_REQUIRED when incidentID missing", async () => {
const mod = loadModule(
"pages/api/endpoint/deleteawaitingsubmissions_api.js",
@@ -3809,76 +4781,6 @@ test("getappealpdfdocuments catch path returns APPEAL_PDF_DOCUMENTS_FETCH_FAILED
);
});
-test("createcase returns CASE_PAYLOAD_REQUIRED when body missing", async () => {
- const mod = loadModule("pages/api/endpoint/createcase_api.js", {
- respondError: respondErrorMock,
- respondSuccess: respondSuccessMock,
- getToken: async () => ({ access_token: "token" }),
- getCaseBlob: async () => {},
- hashAPIPath: () => "&hash=expected",
- axios: async () => ({ data: { ticketnumber: "CAS-1" } }),
- consoleLogger: () => {}
- });
-
- const req = { query: {}, body: undefined };
- const res = createRes();
- await mod.default(req, res);
-
- assert.strictEqual(res.state.statusCode, 400);
- assert.strictEqual(res.state.jsonBody.error.code, "CASE_PAYLOAD_REQUIRED");
-});
-
-test("createcase returns CONTACT_ID_REQUIRED when contactid missing", async () => {
- const mod = loadModule("pages/api/endpoint/createcase_api.js", {
- respondError: respondErrorMock,
- respondSuccess: respondSuccessMock,
- getToken: async () => ({ access_token: "token" }),
- getCaseBlob: async () => {},
- hashAPIPath: () => "&hash=expected",
- axios: async () => ({ data: { ticketnumber: "CAS-1" } }),
- consoleLogger: () => {}
- });
-
- const req = {
- query: { appealTypeId: "a1", containername: "c1", lpaID: "l1" },
- body: { title: "x" }
- };
- const res = createRes();
- await mod.default(req, res);
-
- assert.strictEqual(res.state.statusCode, 400);
- assert.strictEqual(res.state.jsonBody.error.code, "CONTACT_ID_REQUIRED");
-});
-
-test("createcase catch path returns CASE_CREATE_FAILED", async () => {
- const mod = loadModule("pages/api/endpoint/createcase_api.js", {
- respondError: respondErrorMock,
- respondSuccess: respondSuccessMock,
- getToken: async () => ({ access_token: "token" }),
- getCaseBlob: async () => {},
- hashAPIPath: () => "&hash=expected",
- axios: async () => {
- throw new Error("create failed");
- },
- consoleLogger: () => {}
- });
-
- const req = {
- query: {
- contactid: "c1",
- appealTypeId: "a1",
- containername: "container",
- lpaID: "l1"
- },
- body: { title: "x" }
- };
- const res = createRes();
- await mod.default(req, res);
-
- assert.strictEqual(res.state.statusCode, 400);
- assert.strictEqual(res.state.jsonBody.error.code, "CASE_CREATE_FAILED");
-});
-
test("updatecase returns CASE_UPDATE_PAYLOAD_REQUIRED when body missing", async () => {
const mod = loadModule("pages/api/endpoint/updatecase_api.js", {
respondError: respondErrorMock,
@@ -4021,7 +4923,8 @@ test("gethash returns UNAUTHENTICATED when session missing", async () => {
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
hashAPIPath: () => "&hash=expected",
- getSession: async () => null,
+ getServerSession: async () => null,
+ authOptions: () => ({}),
nextConnect: () => {
const handler = { registeredGet: null };
handler.get = (cb) => {
@@ -4045,7 +4948,10 @@ test("gethash returns INVALID_HASH_PATH when path is invalid", async () => {
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
hashAPIPath: () => "&hash=expected",
- getSession: async () => ({ user: { email: "user@test.local" } }),
+ getServerSession: async () => ({
+ user: { email: "user@test.local" }
+ }),
+ authOptions: () => ({}),
nextConnect: () => {
const handler = { registeredGet: null };
handler.get = (cb) => {
@@ -4178,10 +5084,20 @@ test("getToken catch path returns TOKEN_FETCH_FAILED", async () => {
test("getsipsmedia returns success contract", async () => {
const mod = loadModule("pages/api/endpoint/getsipsmedia_api.js", {
- respondSuccess: respondSuccessMock
+ respondError: respondErrorMock,
+ relayGet: async ({ res }) =>
+ respondSuccessMock(res, {
+ "@odata.count": 4,
+ value: []
+ })
});
- const req = { query: {} };
+ const req = {
+ method: "GET",
+ query: {
+ caseid: "11111111-1111-4111-8111-111111111111"
+ }
+ };
const res = createRes();
await mod.default(req, res);
@@ -4189,9 +5105,8 @@ test("getsipsmedia returns success contract", async () => {
assert.strictEqual(res.state.jsonBody["@odata.count"], 4);
});
-test("getsipsmedia returns METHOD_NOT_ALLOWED for non-GET methods", async () => {
+test("getsipsmedia returns CASE_ID_REQUIRED when caseid missing", async () => {
const mod = loadModule("pages/api/endpoint/getsipsmedia_api.js", {
- respondSuccess: respondSuccessMock,
respondError: respondErrorMock
});
@@ -4199,8 +5114,8 @@ test("getsipsmedia returns METHOD_NOT_ALLOWED for non-GET methods", async () =>
const res = createRes();
await mod.default(req, res);
- assert.strictEqual(res.state.statusCode, 405);
- assert.strictEqual(res.state.jsonBody.error.code, "METHOD_NOT_ALLOWED");
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "CASE_ID_REQUIRED");
});
test("getappealtypesfornewappeal returns METHOD_NOT_ALLOWED for non-GET methods", async () => {
@@ -4221,13 +5136,25 @@ test("getappealtypesfornewappeal returns METHOD_NOT_ALLOWED for non-GET methods"
});
const run = async () => {
+ const filter = process.env.PEDW_TEST_FILTER;
+
+ const selectedTests = filter
+ ? tests.filter((currentTest) => currentTest.name.includes(filter))
+ : tests;
+
+ if (selectedTests.length === 0) {
+ throw new Error(`No tests match filter: ${filter}`);
+ }
+
let passed = 0;
- for (const currentTest of tests) {
+
+ for (const currentTest of selectedTests) {
await currentTest.fn();
passed += 1;
}
+
console.log(
- `Phase 21 endpoint-handler contract tests passed (${passed}/${tests.length}).`
+ `Phase 21 endpoint-handler contract tests passed (${passed}/${selectedTests.length}).`
);
};
diff --git a/tests/phase21/file-handler-contract.test.cjs b/tests/phase21/file-handler-contract.test.cjs
index 3d976800..53fcc5cc 100644
--- a/tests/phase21/file-handler-contract.test.cjs
+++ b/tests/phase21/file-handler-contract.test.cjs
@@ -1,4 +1,6 @@
const assert = require("assert");
+const fs = require("fs");
+const path = require("path");
const {
loadModule,
createRes,
@@ -14,6 +16,8 @@ test("upload handler returns HASH_REQUIRED for missing hash", async () => {
const mod = loadModule("pages/api/file/upload.js", {
nextConnect: createNextConnectMock(),
middleware: () => {},
+ getServerSession: async () => ({ user: { id: "c1" } }),
+ authOptions: () => ({}),
hashAPIPath: () => "?hash=expected",
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
@@ -33,6 +37,8 @@ test("upload handler returns INVALID_HASH for wrong hash", async () => {
const mod = loadModule("pages/api/file/upload.js", {
nextConnect: createNextConnectMock(),
middleware: () => {},
+ getServerSession: async () => ({ user: { id: "c1" } }),
+ authOptions: () => ({}),
hashAPIPath: () => "?hash=expected",
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
@@ -55,6 +61,8 @@ test("upload handler accepts alternate canonical hash candidate", async () => {
const mod = loadModule("pages/api/file/upload.js", {
nextConnect: createNextConnectMock(),
middleware: () => {},
+ getServerSession: async () => ({ user: { id: "c1" } }),
+ authOptions: () => ({}),
hashAPIPath: (queryPath) =>
queryPath === "/api/file/upload?"
? "?hash=expected"
@@ -83,10 +91,166 @@ test("upload handler accepts alternate canonical hash candidate", async () => {
});
});
+const loadUploadAuthorization = (overrides = {}) => {
+ const calls = {
+ session: [],
+ options: [],
+ createBlob: [],
+ createRepBlob: [],
+ hash: []
+ };
+ const options = { id: "pedw-upload-options" };
+ const mod = loadModule("pages/api/file/upload.js", {
+ nextConnect: createNextConnectMock(),
+ middleware: () => {},
+ authOptions: (req, res) => {
+ calls.options.push([req, res]);
+ return options;
+ },
+ getServerSession: async (...args) => {
+ calls.session.push(args);
+ return { user: { id: "user-container" } };
+ },
+ hashAPIPath: (queryPath) => {
+ calls.hash.push(queryPath);
+ return "?hash=expected";
+ },
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock,
+ createBlob: async (...args) => {
+ calls.createBlob.push(args);
+ return { id: "appeal-blob" };
+ },
+ createRepBlob: async (...args) => {
+ calls.createRepBlob.push(args);
+ return { id: "representation-blob" };
+ },
+ ...overrides
+ });
+
+ return { mod, calls, options };
+};
+
+const uploadAuthorizationRequest = (overrides = {}) => ({
+ query: { hash: "expected" },
+ body: {
+ appealData: [JSON.stringify({ key: "value" })],
+ containerID: ["user-container"],
+ casefolderID: ["CASE-1"],
+ repOrAppeal: ["false"]
+ },
+ files: {},
+ ...overrides
+});
+
+const assertNoUploadWrites = (calls) => {
+ assert.strictEqual(calls.createBlob.length, 0);
+ assert.strictEqual(calls.createRepBlob.length, 0);
+};
+
+test("upload rejects a missing NextAuth session before HMAC or Azure write", async () => {
+ const loaded = loadUploadAuthorization({
+ getServerSession: async () => null
+ });
+ const res = createRes();
+
+ await loaded.mod.default.handler(uploadAuthorizationRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 401);
+ assert.strictEqual(res.state.jsonBody.error.code, "UNAUTHENTICATED");
+ assert.strictEqual(loaded.calls.hash.length, 0);
+ assertNoUploadWrites(loaded.calls);
+});
+
+test("upload rejects an unusable NextAuth session before HMAC or Azure write", async () => {
+ const loaded = loadUploadAuthorization({
+ getServerSession: async () => ({ user: {} })
+ });
+ const res = createRes();
+
+ await loaded.mod.default.handler(uploadAuthorizationRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 401);
+ assert.strictEqual(res.state.jsonBody.error.code, "UNAUTHENTICATED");
+ assert.strictEqual(loaded.calls.hash.length, 0);
+ assertNoUploadWrites(loaded.calls);
+});
+
+test("upload passes the request, response and PEDW options to getServerSession", async () => {
+ const loaded = loadUploadAuthorization();
+ const req = uploadAuthorizationRequest();
+ const res = createRes();
+
+ await loaded.mod.default.handler(req, res);
+
+ assert.deepStrictEqual(loaded.calls.options, [[req, res]]);
+ assert.strictEqual(loaded.calls.session.length, 1);
+ assert.strictEqual(loaded.calls.session[0][0], req);
+ assert.strictEqual(loaded.calls.session[0][1], res);
+ assert.strictEqual(loaded.calls.session[0][2], loaded.options);
+});
+
+test("upload forbids another user's container before HMAC or Azure write", async () => {
+ const loaded = loadUploadAuthorization();
+ const req = uploadAuthorizationRequest();
+ req.body.containerID = ["other-container"];
+ const res = createRes();
+
+ await loaded.mod.default.handler(req, res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(res.state.jsonBody.error.code, "FORBIDDEN");
+ assert.strictEqual(loaded.calls.hash.length, 0);
+ assertNoUploadWrites(loaded.calls);
+});
+
+test("upload rejects invalid HMAC for the owning user without Azure write", async () => {
+ const loaded = loadUploadAuthorization({
+ hashAPIPath: () => "?hash=different"
+ });
+ const res = createRes();
+
+ await loaded.mod.default.handler(uploadAuthorizationRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "INVALID_HASH");
+ assertNoUploadWrites(loaded.calls);
+});
+
+test("upload requires HMAC for the authenticated owning user", async () => {
+ const loaded = loadUploadAuthorization();
+ const req = uploadAuthorizationRequest({ query: {} });
+ const res = createRes();
+
+ await loaded.mod.default.handler(req, res);
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "HASH_REQUIRED");
+ assertNoUploadWrites(loaded.calls);
+});
+
+test("upload preserves the authorised owner success contract and helper arguments", async () => {
+ const loaded = loadUploadAuthorization();
+ const res = createRes();
+
+ await loaded.mod.default.handler(uploadAuthorizationRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.deepStrictEqual(JSON.parse(JSON.stringify(res.state.jsonBody)), {
+ data: { id: "appeal-blob" }
+ });
+ assert.deepStrictEqual(loaded.calls.createBlob, [
+ [JSON.stringify({ key: "value" }), "user-container", "CASE-1"]
+ ]);
+ assert.strictEqual(loaded.calls.createRepBlob.length, 0);
+});
+
test("deleteblob handler returns MISSING_REQUIRED_QUERY when blobname missing", async () => {
const mod = loadModule("pages/api/file/deleteblob.js", {
nextConnect: createNextConnectMock(),
middleware: () => {},
+ getServerSession: async () => ({ user: { id: "container-1" } }),
+ authOptions: () => ({}),
hashAPIPath: () => "&hash=expected",
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
@@ -94,7 +258,11 @@ test("deleteblob handler returns MISSING_REQUIRED_QUERY when blobname missing",
});
const req = {
- query: { container: "c1", casefolderID: "f1", hash: "expected" }
+ query: {
+ container: "container-1",
+ casefolderID: "f1",
+ hash: "expected"
+ }
};
const res = createRes();
await mod.default.handler(req, res);
@@ -108,8 +276,10 @@ test("deleteblob handler accepts encoded hash variant and normalizes prefixed pa
const mod = loadModule("pages/api/file/deleteblob.js", {
nextConnect: createNextConnectMock(),
middleware: () => {},
+ getServerSession: async () => ({ user: { id: "container-1" } }),
+ authOptions: () => ({}),
hashAPIPath: (queryPath) =>
- queryPath.includes("/api/file/deleteblob?container=c1")
+ queryPath.includes("/api/file/deleteblob?container=container-1")
? "&hash=expected"
: "&hash=other",
respondError: respondErrorMock,
@@ -122,7 +292,7 @@ test("deleteblob handler accepts encoded hash variant and normalizes prefixed pa
const req = {
query: {
- container: "c1",
+ container: "container-1",
casefolderID: "TMP-LFE1C",
blobname:
"TMP-LFE1C/files/2026-03-18_-_Site_Location_Plan_-_test document 021.xlsx",
@@ -143,6 +313,8 @@ test("deleteblob handler dependency failure returns DELETE_BLOB_FAILED", async (
const mod = loadModule("pages/api/file/deleteblob.js", {
nextConnect: createNextConnectMock(),
middleware: () => {},
+ getServerSession: async () => ({ user: { id: "container-1" } }),
+ authOptions: () => ({}),
hashAPIPath: () => "&hash=expected",
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
@@ -153,7 +325,7 @@ test("deleteblob handler dependency failure returns DELETE_BLOB_FAILED", async (
const req = {
query: {
- container: "c1",
+ container: "container-1",
casefolderID: "f1",
blobname: "doc.pdf",
hash: "expected"
@@ -171,6 +343,8 @@ test("deleteblobcase handler accepts encoded hash variant", async () => {
const mod = loadModule("pages/api/file/deleteblobcase.js", {
nextConnect: createNextConnectMock(),
middleware: () => {},
+ getServerSession: async () => ({ user: { id: "c1" } }),
+ authOptions: () => ({}),
hashAPIPath: (queryPath) =>
queryPath.includes("casefolderID=CASE%2FSUB")
? "&hash=expected"
@@ -201,6 +375,8 @@ test("deleteblobcase handler dependency failure returns DELETE_BLOB_CASE_FAILED"
const mod = loadModule("pages/api/file/deleteblobcase.js", {
nextConnect: createNextConnectMock(),
middleware: () => {},
+ getServerSession: async () => ({ user: { id: "c1" } }),
+ authOptions: () => ({}),
hashAPIPath: () => "&hash=expected",
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
@@ -231,6 +407,8 @@ test("deleteblobrep handler accepts encoded hash variant", async () => {
const mod = loadModule("pages/api/file/deleteblobrep.js", {
nextConnect: createNextConnectMock(),
middleware: () => {},
+ getServerSession: async () => ({ user: { id: "c1" } }),
+ authOptions: () => ({}),
hashAPIPath: (queryPath) =>
queryPath.includes("repfile=Rep%20Name")
? "&hash=expected"
@@ -262,6 +440,8 @@ test("deleteblobrep handler dependency failure returns DELETE_BLOB_REP_FAILED",
const mod = loadModule("pages/api/file/deleteblobrep.js", {
nextConnect: createNextConnectMock(),
middleware: () => {},
+ getServerSession: async () => ({ user: { id: "c1" } }),
+ authOptions: () => ({}),
hashAPIPath: () => "&hash=expected",
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
@@ -285,6 +465,776 @@ test("deleteblobrep handler dependency failure returns DELETE_BLOB_REP_FAILED",
assert.strictEqual(res.state.jsonBody.error.code, "DELETE_BLOB_REP_FAILED");
});
+const ordinaryDeletionCases = [
+ {
+ name: "deleteblobcase",
+ route: "pages/api/file/deleteblobcase.js",
+ query: {
+ container: "user-container",
+ casefolderID: "CASE-1",
+ hash: "expected"
+ },
+ dependency: "deleteBlobCase"
+ },
+ {
+ name: "deleteblobrep",
+ route: "pages/api/file/deleteblobrep.js",
+ query: {
+ container: "user-container",
+ casefolderID: "CASE-1",
+ repfile: "representation.json",
+ hash: "expected"
+ },
+ dependency: "deleteBlobRep"
+ }
+];
+
+for (const deletionCase of ordinaryDeletionCases) {
+ test(`${deletionCase.name} forbids a missing NextAuth session before deletion`, async () => {
+ let deletionCalls = 0;
+ const mod = loadModule(deletionCase.route, {
+ nextConnect: createNextConnectMock(),
+ middleware: () => {},
+ getServerSession: async () => null,
+ authOptions: () => ({}),
+ hashAPIPath: () => "&hash=expected",
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock,
+ [deletionCase.dependency]: async () => {
+ deletionCalls += 1;
+ }
+ });
+ const res = createRes();
+
+ await mod.default.handler({ query: deletionCase.query }, res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(res.state.jsonBody.error.code, "FORBIDDEN");
+ assert.strictEqual(deletionCalls, 0);
+ });
+
+ test(`${deletionCase.name} forbids a session without user id before deletion`, async () => {
+ let deletionCalls = 0;
+ const mod = loadModule(deletionCase.route, {
+ nextConnect: createNextConnectMock(),
+ middleware: () => {},
+ getServerSession: async () => ({ user: {} }),
+ authOptions: () => ({}),
+ hashAPIPath: () => "&hash=expected",
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock,
+ [deletionCase.dependency]: async () => {
+ deletionCalls += 1;
+ }
+ });
+ const res = createRes();
+
+ await mod.default.handler({ query: deletionCase.query }, res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(deletionCalls, 0);
+ });
+
+ test(`${deletionCase.name} forbids cross-container deletion before HMAC or Azure deletion`, async () => {
+ let hashCalls = 0;
+ let deletionCalls = 0;
+ const mod = loadModule(deletionCase.route, {
+ nextConnect: createNextConnectMock(),
+ middleware: () => {},
+ getServerSession: async () => ({ user: { id: "different-user" } }),
+ authOptions: () => ({}),
+ hashAPIPath: () => {
+ hashCalls += 1;
+ return "&hash=expected";
+ },
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock,
+ [deletionCase.dependency]: async () => {
+ deletionCalls += 1;
+ }
+ });
+ const res = createRes();
+
+ await mod.default.handler({ query: deletionCase.query }, res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(hashCalls, 0);
+ assert.strictEqual(deletionCalls, 0);
+ });
+
+ test(`${deletionCase.name} passes the request, response and PEDW options to getServerSession`, async () => {
+ const sessionCalls = [];
+ const optionCalls = [];
+ const options = { id: `${deletionCase.name}-options` };
+ const mod = loadModule(deletionCase.route, {
+ nextConnect: createNextConnectMock(),
+ middleware: () => {},
+ authOptions: (req, res) => {
+ optionCalls.push([req, res]);
+ return options;
+ },
+ getServerSession: async (...args) => {
+ sessionCalls.push(args);
+ return { user: { id: "user-container" } };
+ },
+ hashAPIPath: () => "&hash=expected",
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock,
+ [deletionCase.dependency]: async () => ({ deleted: true })
+ });
+ const req = {
+ query: deletionCase.query,
+ body: { parsed: ["multipart"] }
+ };
+ const res = createRes();
+
+ await mod.default.handler(req, res);
+
+ assert.deepStrictEqual(optionCalls, [[req, res]]);
+ assert.strictEqual(sessionCalls.length, 1);
+ assert.strictEqual(sessionCalls[0][0], req);
+ assert.strictEqual(sessionCalls[0][1], res);
+ assert.strictEqual(sessionCalls[0][2], options);
+ assert.strictEqual(res.state.statusCode, 200);
+ });
+
+ test(`${deletionCase.name} rejects invalid HMAC for the owning user without deletion`, async () => {
+ let deletionCalls = 0;
+ const mod = loadModule(deletionCase.route, {
+ nextConnect: createNextConnectMock(),
+ middleware: () => {},
+ getServerSession: async () => ({ user: { id: "user-container" } }),
+ authOptions: () => ({}),
+ hashAPIPath: () => "&hash=different",
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock,
+ [deletionCase.dependency]: async () => {
+ deletionCalls += 1;
+ }
+ });
+ const res = createRes();
+
+ await mod.default.handler({ query: deletionCase.query }, res);
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "INVALID_HASH");
+ assert.strictEqual(deletionCalls, 0);
+ });
+
+ test(`${deletionCase.name} preserves valid same-user deletion`, async () => {
+ const deletionCalls = [];
+ const mod = loadModule(deletionCase.route, {
+ nextConnect: createNextConnectMock(),
+ middleware: () => {},
+ getServerSession: async () => ({ user: { id: "user-container" } }),
+ authOptions: () => ({}),
+ hashAPIPath: () => "&hash=expected",
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock,
+ [deletionCase.dependency]: async (...args) => {
+ deletionCalls.push(args);
+ return { deleted: true };
+ }
+ });
+ const res = createRes();
+
+ await mod.default.handler({ query: deletionCase.query }, res);
+
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.strictEqual(deletionCalls.length, 1);
+ assert.strictEqual(deletionCalls[0][0], "user-container");
+ });
+}
+
+const loadAdminDeletion = (overrides = {}) => {
+ let deletionCalls = 0;
+ const mod = loadModule("pages/api/admin/deleteblobrep.js", {
+ deleteBlobRep: async () => {
+ deletionCalls += 1;
+ return { deleted: true };
+ },
+ readAdminSessionCookie: () => "admin-token",
+ validateAdminSession: () => true,
+ hasTrustedSameOrigin: () => true,
+ setAdminAuthNoStore: () => {},
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock,
+ ...overrides
+ });
+
+ return { mod, getDeletionCalls: () => deletionCalls };
+};
+
+const validAdminDeletionRequest = () => ({
+ method: "POST",
+ headers: { origin: "https://portal.example.test" },
+ body: {
+ container: "ck-user-container",
+ casefolderID: "CASE-1",
+ repfile: "representation.json"
+ }
+});
+
+test("admin representation deletion forbids a missing administrative session", async () => {
+ const loaded = loadAdminDeletion({
+ readAdminSessionCookie: () => null,
+ validateAdminSession: () => false
+ });
+ const res = createRes();
+
+ await loaded.mod.default(validAdminDeletionRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(res.state.jsonBody.error.code, "FORBIDDEN");
+ assert.strictEqual(loaded.getDeletionCalls(), 0);
+});
+
+test("admin representation deletion forbids an invalid or expired administrative session", async () => {
+ const loaded = loadAdminDeletion({ validateAdminSession: () => false });
+ const res = createRes();
+
+ await loaded.mod.default(validAdminDeletionRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(loaded.getDeletionCalls(), 0);
+});
+
+for (const originCase of ["missing", "cross-origin"]) {
+ test(`admin representation deletion forbids ${originCase} Origin`, async () => {
+ const loaded = loadAdminDeletion({ hasTrustedSameOrigin: () => false });
+ const req = validAdminDeletionRequest();
+ if (originCase === "missing") delete req.headers.origin;
+ if (originCase === "cross-origin") {
+ req.headers.origin = "https://attacker.example";
+ }
+ const res = createRes();
+
+ await loaded.mod.default(req, res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(loaded.getDeletionCalls(), 0);
+ });
+}
+
+test("ordinary user HMAC cannot authorize administrative representation deletion", async () => {
+ const loaded = loadAdminDeletion({
+ readAdminSessionCookie: () => null,
+ validateAdminSession: () => false
+ });
+ const req = validAdminDeletionRequest();
+ req.body.hash = "ordinary-user-hmac";
+ const res = createRes();
+
+ await loaded.mod.default(req, res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(loaded.getDeletionCalls(), 0);
+});
+
+test("admin representation deletion rejects malformed paths without deletion", async () => {
+ for (const malformedBody of [
+ { casefolderID: "../CASE-1" },
+ { repfile: "folder/representation.json" },
+ { repfile: ".." }
+ ]) {
+ const loaded = loadAdminDeletion();
+ const req = validAdminDeletionRequest();
+ req.body = { ...req.body, ...malformedBody };
+ const res = createRes();
+
+ await loaded.mod.default(req, res);
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "INVALID_REQUEST");
+ assert.strictEqual(loaded.getDeletionCalls(), 0);
+ }
+});
+
+test("valid administrative session and origin authorize cross-container representation deletion", async () => {
+ const deletionCalls = [];
+ const loaded = loadAdminDeletion({
+ deleteBlobRep: async (...args) => {
+ deletionCalls.push(args);
+ return { deleted: args[1] };
+ }
+ });
+ const res = createRes();
+
+ await loaded.mod.default(validAdminDeletionRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.deepStrictEqual(JSON.parse(JSON.stringify(deletionCalls)), [
+ ["ck-user-container", "CASE-1/representation.json"]
+ ]);
+});
+
+test("admin storage caller uses dedicated POST deletion while ordinary caller remains signed GET", () => {
+ const rootDir = path.resolve(__dirname, "..", "..");
+ const adminSource = fs.readFileSync(
+ path.join(rootDir, "components/admin/tabs/storage.js"),
+ "utf8"
+ );
+ const ordinarySource = fs.readFileSync(
+ path.join(rootDir, "actions/services/documentDirectService.js"),
+ "utf8"
+ );
+
+ assert.match(adminSource, /fetch\("\/api\/admin\/deleteblobrep"/);
+ assert.match(adminSource, /method:\s*"POST"/);
+ assert.doesNotMatch(adminSource, /deleteMyRepresentationsFromBlob/);
+ assert.match(
+ ordinarySource,
+ /buildFileQuery\("\/api\/file\/deleteblobrep"[\s\S]*getSignedFileJson\(queryUrl\)/
+ );
+});
+
+const loadAdminCaseDeletion = (overrides = {}) => {
+ const calls = {
+ noStore: 0,
+ readSession: 0,
+ validateSession: 0,
+ origin: 0,
+ deletion: []
+ };
+ const payload = { deleted: "TMP-CASE-1" };
+ const mod = loadModule("pages/api/admin/deleteblobcase.js", {
+ deleteBlobCase: async (...args) => {
+ calls.deletion.push(args);
+ return payload;
+ },
+ readAdminSessionCookie: () => {
+ calls.readSession += 1;
+ return "admin-token";
+ },
+ validateAdminSession: () => {
+ calls.validateSession += 1;
+ return true;
+ },
+ hasTrustedSameOrigin: () => {
+ calls.origin += 1;
+ return true;
+ },
+ setAdminAuthNoStore: () => {
+ calls.noStore += 1;
+ },
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock,
+ ...overrides
+ });
+
+ return { mod, calls, payload };
+};
+
+const validAdminCaseDeletionRequest = (overrides = {}) => ({
+ method: "POST",
+ headers: {
+ origin: "https://portal.example.test",
+ cookie: "pedw_admin_session=admin-token"
+ },
+ body: {
+ container: "selected-user-container",
+ casefolderID: "TMP-CASE-1"
+ },
+ ...overrides
+});
+
+for (const method of ["GET", "DELETE"]) {
+ test(`admin case deletion rejects ${method} with 405 before authorization or deletion`, async () => {
+ const loaded = loadAdminCaseDeletion();
+ const res = createRes();
+
+ await loaded.mod.default(
+ validAdminCaseDeletionRequest({ method }),
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 405);
+ assert.strictEqual(res.state.headers.allow, "POST");
+ assert.strictEqual(res.state.jsonBody.error.code, "METHOD_NOT_ALLOWED");
+ assert.strictEqual(loaded.calls.noStore, 1);
+ assert.strictEqual(loaded.calls.readSession, 0);
+ assert.strictEqual(loaded.calls.deletion.length, 0);
+ });
+}
+
+for (const sessionCase of [
+ { name: "missing", token: null },
+ { name: "invalid", token: "invalid-token" },
+ { name: "expired", token: "expired-token" }
+]) {
+ test(`admin case deletion rejects ${sessionCase.name} administrative session before deletion`, async () => {
+ const loaded = loadAdminCaseDeletion({
+ readAdminSessionCookie: () => sessionCase.token,
+ validateAdminSession: () => false
+ });
+ const res = createRes();
+
+ await loaded.mod.default(validAdminCaseDeletionRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(res.state.jsonBody.error.code, "FORBIDDEN");
+ assert.strictEqual(loaded.calls.origin, 0);
+ assert.strictEqual(loaded.calls.deletion.length, 0);
+ });
+}
+
+for (const originCase of [
+ { name: "missing", headers: { cookie: "pedw_admin_session=admin-token" } },
+ {
+ name: "cross-origin",
+ headers: {
+ origin: "https://attacker.example.test",
+ cookie: "pedw_admin_session=admin-token"
+ }
+ }
+]) {
+ test(`admin case deletion rejects ${originCase.name} Origin before deletion`, async () => {
+ const loaded = loadAdminCaseDeletion({
+ hasTrustedSameOrigin: () => false
+ });
+ const res = createRes();
+
+ await loaded.mod.default(
+ validAdminCaseDeletionRequest({ headers: originCase.headers }),
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(loaded.calls.deletion.length, 0);
+ });
+}
+
+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 traversal segment", body: { casefolderID: ".." } },
+ {
+ name: "case identifier control character",
+ body: { casefolderID: "TMP\u0000CASE" }
+ }
+]) {
+ test(`admin case deletion rejects ${inputCase.name} without deletion`, async () => {
+ const loaded = loadAdminCaseDeletion();
+ const request = validAdminCaseDeletionRequest();
+ const res = createRes();
+
+ request.body = { ...request.body, ...inputCase.body };
+ Object.keys(request.body).forEach((key) => {
+ if (typeof request.body[key] === "undefined")
+ delete request.body[key];
+ });
+ await loaded.mod.default(request, res);
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "INVALID_REQUEST");
+ assert.strictEqual(loaded.calls.deletion.length, 0);
+ });
+}
+
+test("valid administrator can delete a cross-container case prefix with the existing helper", async () => {
+ const loaded = loadAdminCaseDeletion();
+ const request = validAdminCaseDeletionRequest();
+ const res = createRes();
+
+ await loaded.mod.default(request, res);
+
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.deepStrictEqual(loaded.calls.deletion, [
+ [request.body.container, request.body.casefolderID]
+ ]);
+ assert.deepStrictEqual(JSON.parse(JSON.stringify(res.state.jsonBody)), {
+ data: loaded.payload
+ });
+});
+
+test("admin case deletion dependency failure returns DELETE_BLOB_CASE_FAILED", async () => {
+ const loaded = loadAdminCaseDeletion({
+ deleteBlobCase: async (...args) => {
+ loaded.calls.deletion.push(args);
+ throw new Error("delete case failed");
+ }
+ });
+ const res = createRes();
+
+ await loaded.mod.default(validAdminCaseDeletionRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(
+ res.state.jsonBody.error.code,
+ "DELETE_BLOB_CASE_FAILED"
+ );
+ assert.strictEqual(loaded.calls.deletion.length, 1);
+});
+
+test("admin storage case deletion uses dedicated POST route while ordinary callers remain signed GET", () => {
+ const rootDir = path.resolve(__dirname, "..", "..");
+ const adminSource = fs.readFileSync(
+ path.join(rootDir, "components/admin/tabs/storage.js"),
+ "utf8"
+ );
+ const ordinarySource = fs.readFileSync(
+ path.join(rootDir, "actions/services/documentDirectService.js"),
+ "utf8"
+ );
+
+ assert.match(adminSource, /fetch\(\s*"\/api\/admin\/deleteblobcase"/);
+ assert.match(
+ adminSource,
+ /"\/api\/admin\/deleteblobcase"[\s\S]*method:\s*"POST"[\s\S]*container:\s*c\.container[\s\S]*casefolderID:\s*folder\.folderPath/
+ );
+ assert.match(adminSource, /if \(!response\.ok\)/);
+ assert.doesNotMatch(adminSource, /deleteAwaitingSubmissionsFromBlob/);
+ assert.match(
+ ordinarySource,
+ /buildFileQuery\("\/api\/file\/deleteblobcase"[\s\S]*getSignedFileJson\(queryUrl\)/
+ );
+});
+
+const loadAdminRepJsonEdit = (overrides = {}) => {
+ let azureClientConstructions = 0;
+ const storageCalls = [];
+ const sourceJson = {
+ containerID: "ck-user-container",
+ ticketnumber: "CASE-1",
+ repComplete: true,
+ representationType: "Support",
+ nested: { retained: true }
+ };
+ const uploaded = {};
+
+ class DefaultAzureCredentialMock {}
+
+ class BlobServiceClientMock {
+ constructor(url, credential) {
+ azureClientConstructions += 1;
+ storageCalls.push(["construct", url, credential]);
+ }
+
+ getContainerClient(container) {
+ storageCalls.push(["container", container]);
+ return {
+ getBlockBlobClient(blobName) {
+ storageCalls.push(["blob", blobName]);
+ return {
+ async download(offset) {
+ storageCalls.push(["download", offset]);
+ const { Readable } = require("stream");
+ return {
+ readableStreamBody: Readable.from([
+ JSON.stringify(sourceJson)
+ ])
+ };
+ },
+ async upload(content, length, options) {
+ uploaded.content = content;
+ uploaded.length = length;
+ uploaded.options = options;
+ storageCalls.push(["upload"]);
+ },
+ async setTags(tags) {
+ uploaded.tags = tags;
+ storageCalls.push(["tags"]);
+ },
+ async setMetadata(metadata) {
+ uploaded.metadata = metadata;
+ storageCalls.push(["metadata"]);
+ }
+ };
+ }
+ };
+ }
+ }
+
+ const mod = loadModule("pages/api/admin/editRepJson.js", {
+ Buffer,
+ DefaultAzureCredential: DefaultAzureCredentialMock,
+ BlobServiceClient: BlobServiceClientMock,
+ consoleLogger: () => {},
+ readAdminSessionCookie: () => "admin-token",
+ validateAdminSession: () => true,
+ hasTrustedSameOrigin: () => true,
+ setAdminAuthNoStore: () => {},
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock,
+ ...overrides
+ });
+
+ return {
+ mod,
+ getAzureClientConstructions: () => azureClientConstructions,
+ storageCalls,
+ sourceJson,
+ uploaded
+ };
+};
+
+const validAdminRepJsonEditRequest = () => ({
+ method: "POST",
+ headers: { origin: "https://portal.example.test" },
+ body: {
+ container: "ck-user-container",
+ blobName: "CASE-1/representation-1/representation_rep.json"
+ }
+});
+
+test("admin representation JSON edit forbids a missing administrative session before Azure access", async () => {
+ const loaded = loadAdminRepJsonEdit({
+ readAdminSessionCookie: () => null,
+ validateAdminSession: () => false
+ });
+ const res = createRes();
+
+ await loaded.mod.default(validAdminRepJsonEditRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(res.state.jsonBody.error.code, "FORBIDDEN");
+ assert.strictEqual(loaded.getAzureClientConstructions(), 0);
+});
+
+test("admin representation JSON edit forbids an invalid administrative session before Azure access", async () => {
+ const loaded = loadAdminRepJsonEdit({ validateAdminSession: () => false });
+ const res = createRes();
+
+ await loaded.mod.default(validAdminRepJsonEditRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(loaded.getAzureClientConstructions(), 0);
+});
+
+test("admin representation JSON edit forbids cross-origin requests before Azure access", async () => {
+ const loaded = loadAdminRepJsonEdit({ hasTrustedSameOrigin: () => false });
+ const req = validAdminRepJsonEditRequest();
+ req.headers.origin = "https://attacker.example";
+ const res = createRes();
+
+ await loaded.mod.default(req, res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(loaded.getAzureClientConstructions(), 0);
+});
+
+test("admin representation JSON edit rejects unsupported methods before Azure access", async () => {
+ const loaded = loadAdminRepJsonEdit();
+ const req = validAdminRepJsonEditRequest();
+ req.method = "GET";
+ const res = createRes();
+
+ await loaded.mod.default(req, res);
+
+ assert.strictEqual(res.state.statusCode, 405);
+ assert.strictEqual(res.state.jsonBody.error.code, "METHOD_NOT_ALLOWED");
+ assert.strictEqual(res.state.headers.allow, "POST");
+ assert.strictEqual(loaded.getAzureClientConstructions(), 0);
+});
+
+test("admin representation JSON edit rejects malformed identifiers before Azure access", async () => {
+ for (const malformedBody of [
+ { container: "UPPERCASE" },
+ { container: "ab" },
+ { blobName: "../representation_rep.json" },
+ { blobName: "CASE-1//representation_rep.json" },
+ { blobName: "CASE-1\\representation_rep.json" },
+ { blobName: " representation_rep.json" }
+ ]) {
+ const loaded = loadAdminRepJsonEdit();
+ const req = validAdminRepJsonEditRequest();
+ req.body = { ...req.body, ...malformedBody };
+ const res = createRes();
+
+ await loaded.mod.default(req, res);
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "INVALID_REQUEST");
+ assert.strictEqual(loaded.getAzureClientConstructions(), 0);
+ }
+});
+
+test("valid administrative representation JSON edit preserves the existing mutation contract", async () => {
+ const loaded = loadAdminRepJsonEdit();
+ const res = createRes();
+
+ await loaded.mod.default(validAdminRepJsonEditRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.deepStrictEqual(JSON.parse(JSON.stringify(res.state.jsonBody)), {
+ message: "repComplete removed successfully"
+ });
+ assert.strictEqual(loaded.getAzureClientConstructions(), 1);
+ assert.deepStrictEqual(loaded.storageCalls.slice(1, 4), [
+ ["container", "ck-user-container"],
+ ["blob", "CASE-1/representation-1/representation_rep.json"],
+ ["download", 0]
+ ]);
+
+ 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.representationType,
+ loaded.sourceJson.representationType
+ );
+ assert.deepStrictEqual(
+ JSON.parse(JSON.stringify(updatedJson.nested)),
+ loaded.sourceJson.nested
+ );
+ assert.strictEqual(
+ loaded.uploaded.length,
+ Buffer.byteLength(loaded.uploaded.content)
+ );
+ assert.deepStrictEqual(
+ JSON.parse(JSON.stringify(loaded.uploaded.options)),
+ { blobHTTPHeaders: { blobContentType: "application/json" } }
+ );
+ assert.deepStrictEqual(JSON.parse(JSON.stringify(loaded.uploaded.tags)), {
+ containerid: "ck-user-container",
+ caseID: "CASE-1",
+ blobType: "Representation"
+ });
+ assert.deepStrictEqual(
+ JSON.parse(JSON.stringify(loaded.uploaded.metadata)),
+ JSON.parse(JSON.stringify(loaded.uploaded.tags))
+ );
+});
+
+test("retired file representation JSON endpoint cannot mutate storage", async () => {
+ let storageCalls = 0;
+ const mod = loadModule("pages/api/file/editRepJson.js", {
+ BlobServiceClient: class {
+ constructor() {
+ storageCalls += 1;
+ }
+ },
+ respondError: respondErrorMock
+ });
+ const res = createRes();
+
+ await mod.default(validAdminRepJsonEditRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 410);
+ assert.strictEqual(res.state.jsonBody.error.code, "ENDPOINT_RETIRED");
+ assert.strictEqual(storageCalls, 0);
+});
+
+test("admin storage caller uses the protected representation JSON edit endpoint", () => {
+ const rootDir = path.resolve(__dirname, "..", "..");
+ const adminSource = fs.readFileSync(
+ path.join(rootDir, "components/admin/tabs/storage.js"),
+ "utf8"
+ );
+
+ assert.match(adminSource, /fetch\(\s*"\/api\/admin\/editRepJson"/);
+ assert.doesNotMatch(adminSource, /fetch\(\s*"\/api\/file\/editRepJson"/);
+});
+
test("deleteawaitingsubmissionfromblob accepts legacy deleteblob hash variant", async () => {
let deletedPath = null;
const mod = loadModule(
@@ -292,8 +1242,10 @@ test("deleteawaitingsubmissionfromblob accepts legacy deleteblob hash variant",
{
nextConnect: createNextConnectMock(),
middleware: () => {},
+ getServerSession: async () => ({ user: { id: "container-1" } }),
+ authOptions: () => ({}),
hashAPIPath: (queryPath) =>
- queryPath.includes("/api/file/deleteblob?container=c1")
+ queryPath.includes("/api/file/deleteblob?container=container-1")
? "&hash=expected"
: "&hash=other",
respondError: respondErrorMock,
@@ -307,7 +1259,7 @@ test("deleteawaitingsubmissionfromblob accepts legacy deleteblob hash variant",
const req = {
query: {
- container: "c1",
+ container: "container-1",
casefolderID: "CASE-1",
blobname: "CASE-1/files/doc.pdf",
hash: "expected"
@@ -326,6 +1278,8 @@ test("deleteawaitingsubmissionfromblob dependency failure returns DELETE_AWAITIN
{
nextConnect: createNextConnectMock(),
middleware: () => {},
+ getServerSession: async () => ({ user: { id: "container-1" } }),
+ authOptions: () => ({}),
hashAPIPath: () => "&hash=expected",
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
@@ -337,7 +1291,7 @@ test("deleteawaitingsubmissionfromblob dependency failure returns DELETE_AWAITIN
const req = {
query: {
- container: "c1",
+ container: "container-1",
casefolderID: "CASE-1",
blobname: "doc.pdf",
hash: "expected"
@@ -353,6 +1307,245 @@ test("deleteawaitingsubmissionfromblob dependency failure returns DELETE_AWAITIN
);
});
+const ownerBoundBlobDeletionCases = [
+ {
+ name: "deleteblob",
+ route: "pages/api/file/deleteblob.js"
+ },
+ {
+ name: "deleteawaitingsubmissionfromblob",
+ route: "pages/api/file/deleteawaitingsubmissionfromblob.js"
+ }
+];
+
+const loadOwnerBoundBlobDeletion = (
+ deletionCase,
+ { session, ...overrides } = {}
+) => {
+ const calls = {
+ options: [],
+ session: [],
+ hash: [],
+ deletion: []
+ };
+ const options = { id: `${deletionCase.name}-options` };
+ const resolvedSession =
+ typeof session === "undefined"
+ ? { user: { id: "owner-container" } }
+ : session;
+ const mod = loadModule(deletionCase.route, {
+ nextConnect: createNextConnectMock(),
+ middleware: () => {},
+ 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";
+ },
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock,
+ deleteBlob: async (...args) => {
+ calls.deletion.push(args);
+ return { deleted: true };
+ },
+ ...overrides
+ });
+
+ return { mod, calls, options };
+};
+
+const ownerBoundBlobDeletionRequest = (overrides = {}) => ({
+ query: {
+ container: "owner-container",
+ casefolderID: "CASE-1",
+ blobname: "document.pdf",
+ hash: "expected"
+ },
+ ...overrides
+});
+
+const assertNoOwnerBoundBlobDeletion = (calls) => {
+ assert.strictEqual(calls.hash.length, 0);
+ assert.strictEqual(calls.deletion.length, 0);
+};
+
+for (const deletionCase of ownerBoundBlobDeletionCases) {
+ for (const sessionCase of [
+ { name: "missing session", session: null },
+ { name: "session without user id", session: { user: {} } },
+ { name: "session with empty user id", session: { user: { id: "" } } },
+ {
+ name: "session with non-string user id",
+ session: { user: { id: 123 } }
+ }
+ ]) {
+ test(`${deletionCase.name} rejects ${sessionCase.name} before HMAC or Azure deletion`, async () => {
+ const loaded = loadOwnerBoundBlobDeletion(deletionCase, {
+ session: sessionCase.session
+ });
+ const res = createRes();
+
+ await loaded.mod.default.handler(
+ ownerBoundBlobDeletionRequest(),
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(res.state.jsonBody.error.code, "FORBIDDEN");
+ assertNoOwnerBoundBlobDeletion(loaded.calls);
+ });
+ }
+
+ test(`${deletionCase.name} rejects cross-container deletion before HMAC or Azure deletion`, async () => {
+ const loaded = loadOwnerBoundBlobDeletion(deletionCase, {
+ session: { user: { id: "different-container" } }
+ });
+ const res = createRes();
+
+ await loaded.mod.default.handler(ownerBoundBlobDeletionRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(res.state.jsonBody.error.code, "FORBIDDEN");
+ assertNoOwnerBoundBlobDeletion(loaded.calls);
+ });
+
+ test(`${deletionCase.name} rejects an invalid container before authentication or deletion`, async () => {
+ const loaded = loadOwnerBoundBlobDeletion(deletionCase);
+ const res = createRes();
+
+ await loaded.mod.default.handler(
+ ownerBoundBlobDeletionRequest({
+ query: {
+ container: "Invalid_Container",
+ casefolderID: "CASE-1",
+ blobname: "document.pdf",
+ hash: "expected"
+ }
+ }),
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "INVALID_REQUEST");
+ assert.strictEqual(loaded.calls.options.length, 0);
+ assert.strictEqual(loaded.calls.session.length, 0);
+ assertNoOwnerBoundBlobDeletion(loaded.calls);
+ });
+
+ test(`${deletionCase.name} rejects a missing blob name before authentication or deletion`, async () => {
+ const loaded = loadOwnerBoundBlobDeletion(deletionCase);
+ const res = createRes();
+
+ await loaded.mod.default.handler(
+ ownerBoundBlobDeletionRequest({
+ query: {
+ container: "owner-container",
+ casefolderID: "CASE-1",
+ hash: "expected"
+ }
+ }),
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(
+ res.state.jsonBody.error.code,
+ "MISSING_REQUIRED_QUERY"
+ );
+ assert.strictEqual(loaded.calls.options.length, 0);
+ assert.strictEqual(loaded.calls.session.length, 0);
+ assertNoOwnerBoundBlobDeletion(loaded.calls);
+ });
+
+ test(`${deletionCase.name} rejects malformed folder and blob parameters before authentication or deletion`, async () => {
+ const loaded = loadOwnerBoundBlobDeletion(deletionCase);
+
+ for (const query of [
+ {
+ container: "owner-container",
+ casefolderID: ["CASE-1"],
+ blobname: "document.pdf",
+ hash: "expected"
+ },
+ {
+ container: "owner-container",
+ casefolderID: "CASE-1",
+ blobname: ["document.pdf"],
+ hash: "expected"
+ },
+ {
+ container: "owner-container",
+ casefolderID: " ",
+ blobname: "document.pdf",
+ hash: "expected"
+ },
+ {
+ container: "owner-container",
+ casefolderID: "CASE-1",
+ blobname: " ",
+ hash: "expected"
+ }
+ ]) {
+ const res = createRes();
+
+ await loaded.mod.default.handler(
+ ownerBoundBlobDeletionRequest({ query }),
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(
+ res.state.jsonBody.error.code,
+ "MISSING_REQUIRED_QUERY"
+ );
+ }
+
+ assert.strictEqual(loaded.calls.options.length, 0);
+ assert.strictEqual(loaded.calls.session.length, 0);
+ assertNoOwnerBoundBlobDeletion(loaded.calls);
+ });
+
+ test(`${deletionCase.name} rejects an invalid HMAC after owner authentication and before deletion`, async () => {
+ const loaded = loadOwnerBoundBlobDeletion(deletionCase, {
+ hashAPIPath: () => "&hash=different"
+ });
+ const res = createRes();
+
+ await loaded.mod.default.handler(ownerBoundBlobDeletionRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "INVALID_HASH");
+ assert.strictEqual(loaded.calls.deletion.length, 0);
+ });
+
+ test(`${deletionCase.name} preserves owner deletion and request-aware session arguments`, async () => {
+ const loaded = loadOwnerBoundBlobDeletion(deletionCase);
+ const req = ownerBoundBlobDeletionRequest();
+ const res = createRes();
+
+ await loaded.mod.default.handler(req, res);
+
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.deepStrictEqual(loaded.calls.options, [[req, res]]);
+ assert.deepStrictEqual(loaded.calls.session, [
+ [req, res, loaded.options]
+ ]);
+ assert.strictEqual(loaded.calls.hash.length, 1);
+ assert.deepStrictEqual(loaded.calls.deletion, [
+ ["owner-container", "CASE-1/files/document.pdf"]
+ ]);
+ assert.deepStrictEqual(JSON.parse(JSON.stringify(res.state.jsonBody)), {
+ data: { deleted: true }
+ });
+ });
+}
+
test("getrepsblob handler success returns representations payload", async () => {
const mod = loadModule("pages/api/file/getrepsblob.js", {
nextConnect: createNextConnectMock(),
@@ -361,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" }
],
@@ -383,6 +1580,243 @@ test("getrepsblob handler success returns representations payload", async () =>
});
});
+test("getrepsblob handler rejects missing HMAC before Azure access", async () => {
+ let azureCalls = 0;
+ const mod = loadModule("pages/api/file/getrepsblob.js", {
+ nextConnect: createNextConnectMock(),
+ middleware: () => {},
+ hashAPIPath: () => "&hash=expected",
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock,
+ consoleLogger: () => {},
+ getRepsBlobs: async () => {
+ azureCalls += 1;
+ return [];
+ },
+ downloadAllRepsFiles: async () => {
+ azureCalls += 1;
+ return {};
+ }
+ });
+ const res = createRes();
+
+ await mod.default.handler({ query: { container: "c1" } }, res);
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "MISSING_REQUIRED_QUERY");
+ assert.strictEqual(azureCalls, 0);
+});
+
+test("getrepsblob handler rejects invalid HMAC before Azure access", async () => {
+ let azureCalls = 0;
+ const mod = loadModule("pages/api/file/getrepsblob.js", {
+ nextConnect: createNextConnectMock(),
+ middleware: () => {},
+ hashAPIPath: () => "&hash=expected",
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock,
+ consoleLogger: () => {},
+ getServerSession: async () => ({ user: { id: "c1" } }),
+ authOptions: () => ({}),
+ readAdminSessionCookie: () => null,
+ validateAdminSession: () => false,
+ getRepsBlobs: async () => {
+ azureCalls += 1;
+ return [];
+ },
+ downloadAllRepsFiles: async () => {
+ azureCalls += 1;
+ return {};
+ }
+ });
+ const res = createRes();
+
+ await mod.default.handler(
+ { query: { container: "c1", hash: "wrong" } },
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "INVALID_HASH");
+ assert.strictEqual(azureCalls, 0);
+});
+
+test("general hash endpoint does not authorize getrepsblob signing", async () => {
+ let hashCalls = 0;
+ const mod = loadModule("pages/api/endpoint/gethash_api.js", {
+ nextConnect: createNextConnectMock(),
+ getServerSession: async () => ({ user: { id: "user-container" } }),
+ authOptions: () => ({}),
+ hashAPIPath: () => {
+ hashCalls += 1;
+ return "&hash=unexpected";
+ },
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock
+ });
+ const res = createRes();
+
+ await mod.default.handler(
+ {
+ query: {
+ path: "/api/file/getrepsblob?container=user-container"
+ }
+ },
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "INVALID_HASH_PATH");
+ assert.strictEqual(hashCalls, 0);
+});
+
+const loadAppealCompletionSigning = ({ session, ...overrides } = {}) => {
+ const calls = { options: [], session: [], hash: [] };
+ const options = { id: "appeal-completion-signing-options" };
+ const resolvedSession =
+ typeof session === "undefined"
+ ? { user: { id: "owner-container" } }
+ : session;
+ const mod = loadModule("pages/api/endpoint/gethash_api.js", {
+ nextConnect: createNextConnectMock(),
+ 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=completion-capability";
+ },
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock,
+ URL,
+ ...overrides
+ });
+
+ return { mod, calls, options };
+};
+
+const appealCompletionSigningRequest = (pathValue) => ({
+ query: {
+ path:
+ pathValue ||
+ "/api/file/createappealcompletemessage_api?container=owner-container&tempcaseref=TMP-CASE-1"
+ }
+});
+
+for (const sessionCase of [
+ {
+ 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: "" } } },
+ {
+ name: "session with non-string user id",
+ session: { user: { id: 123 } }
+ },
+ {
+ name: "foreign-container session",
+ session: { user: { id: "foreign-container" } }
+ }
+]) {
+ test(`gethash rejects appeal completion signing for ${sessionCase.name} before HMAC generation`, async () => {
+ const loaded = loadAppealCompletionSigning({
+ session: sessionCase.session
+ });
+ const res = createRes();
+
+ await loaded.mod.default.handler(appealCompletionSigningRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, sessionCase.status || 403);
+ assert.strictEqual(
+ res.state.jsonBody.error.code,
+ sessionCase.code || "FORBIDDEN"
+ );
+ assert.strictEqual(loaded.calls.hash.length, 0);
+ });
+}
+
+for (const pathCase of [
+ {
+ name: "missing container",
+ path: "/api/file/createappealcompletemessage_api?tempcaseref=TMP-CASE-1"
+ },
+ {
+ name: "invalid container",
+ path: "/api/file/createappealcompletemessage_api?container=Invalid_Container&tempcaseref=TMP-CASE-1"
+ },
+ {
+ name: "missing draft reference",
+ path: "/api/file/createappealcompletemessage_api?container=owner-container"
+ },
+ {
+ name: "malformed draft reference",
+ path: "/api/file/createappealcompletemessage_api?container=owner-container&tempcaseref=..%2Fforeign"
+ },
+ {
+ name: "duplicate container binding",
+ path: "/api/file/createappealcompletemessage_api?container=owner-container&container=foreign-container&tempcaseref=TMP-CASE-1"
+ },
+ {
+ name: "duplicate draft binding",
+ path: "/api/file/createappealcompletemessage_api?container=owner-container&tempcaseref=TMP-CASE-1&tempcaseref=TMP-CASE-2"
+ },
+ {
+ name: "completion route lookalike",
+ path: "/api/file/createappealcompletemessage_api-foreign?container=owner-container&tempcaseref=TMP-CASE-1"
+ }
+]) {
+ test(`gethash rejects appeal completion signing with ${pathCase.name} before HMAC generation`, async () => {
+ const loaded = loadAppealCompletionSigning();
+ const res = createRes();
+
+ await loaded.mod.default.handler(
+ appealCompletionSigningRequest(pathCase.path),
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "INVALID_HASH_PATH");
+ assert.strictEqual(loaded.calls.hash.length, 0);
+ });
+}
+
+test("gethash issues the existing appeal completion capability only to the owning session", async () => {
+ const loaded = loadAppealCompletionSigning();
+ const req = appealCompletionSigningRequest();
+ const res = createRes();
+
+ await loaded.mod.default.handler(req, res);
+
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.deepStrictEqual(loaded.calls.options, [[req, res]]);
+ assert.deepStrictEqual(loaded.calls.session, [[req, res, loaded.options]]);
+ assert.deepStrictEqual(loaded.calls.hash, [req.query.path]);
+ assert.deepStrictEqual(JSON.parse(JSON.stringify(res.state.jsonBody)), {
+ hash: "&hash=completion-capability"
+ });
+});
+
+test("gethash preserves unrelated allow-listed signing without applying completion ownership", async () => {
+ const loaded = loadAppealCompletionSigning({
+ session: { user: { email: "user@test.local" } }
+ });
+ const req = appealCompletionSigningRequest("/api/file/upload");
+ const res = createRes();
+
+ await loaded.mod.default.handler(req, res);
+
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.deepStrictEqual(loaded.calls.hash, [req.query.path]);
+});
+
test("getrepsblob handler dependency failure returns GET_REPS_BLOB_FAILED", async () => {
const mod = loadModule("pages/api/file/getrepsblob.js", {
nextConnect: createNextConnectMock(),
@@ -391,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");
},
@@ -418,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" }] })
});
@@ -438,6 +1880,8 @@ test("uploadsinglefile handler returns HASH_REQUIRED when hash missing", async (
const mod = loadModule("pages/api/file/uploadsinglefile.js", {
nextConnect: createNextConnectMock(),
middleware: () => {},
+ getServerSession: async () => ({ user: { id: "c1" } }),
+ authOptions: () => ({}),
hashAPIPath: () => "?hash=expected",
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
@@ -459,6 +1903,8 @@ test("uploadsinglefile handler dependency failure returns UPLOAD_SINGLE_FILE_FAI
const mod = loadModule("pages/api/file/uploadsinglefile.js", {
nextConnect: createNextConnectMock(),
middleware: () => {},
+ getServerSession: async () => ({ user: { id: "c1" } }),
+ authOptions: () => ({}),
hashAPIPath: () => "?hash=expected",
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
@@ -467,13 +1913,24 @@ test("uploadsinglefile handler dependency failure returns UPLOAD_SINGLE_FILE_FAI
throw new Error("upload failed");
},
fileTypeFromBuffer: async () => ({ mime: "application/pdf" }),
- fs: { readFileSync: () => Buffer.from("x") }
+ fs: { readFileSync: () => Buffer.from("x") },
+ path: { basename: (value) => value }
});
const req = {
query: { hash: "expected" },
body: { containerID: ["c1"], casefolderID: ["f1"] },
- files: {}
+ files: {
+ document: [
+ {
+ fieldName: "document.pdf",
+ originalFilename: "document.pdf",
+ path: "/tmp/document.pdf",
+ size: 1,
+ headers: { "content-type": "application/pdf" }
+ }
+ ]
+ }
};
const res = createRes();
await mod.default.handler(req, res);
@@ -485,179 +1942,2003 @@ test("uploadsinglefile handler dependency failure returns UPLOAD_SINGLE_FILE_FAI
);
});
-test("createrepcompletemessage handler accepts encoded hash variant", async () => {
- const mod = loadModule("pages/api/file/createrepcompletemessage_api.js", {
+const loadSingleFileUploadAuthorization = (overrides = {}) => {
+ const calls = {
+ session: [],
+ options: [],
+ upload: [],
+ hash: [],
+ fileReads: 0,
+ typeChecks: 0
+ };
+ const options = { id: "pedw-request-options" };
+ const mod = loadModule("pages/api/file/uploadsinglefile.js", {
nextConnect: createNextConnectMock(),
middleware: () => {},
- hashAPIPath: (queryPath) =>
- queryPath.includes("repid=rep%201")
- ? "&hash=expected"
- : "&hash=other",
+ authOptions: (req, res) => {
+ calls.options.push([req, res]);
+ return options;
+ },
+ getServerSession: async (...args) => {
+ calls.session.push(args);
+ return { user: { id: "user-container" } };
+ },
+ hashAPIPath: (queryPath) => {
+ calls.hash.push(queryPath);
+ return "?hash=expected";
+ },
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
consoleLogger: () => {},
- createRepCompleteMessage: async () => ({ ok: true })
+ uploadSingleFile: async (...args) => {
+ calls.upload.push(args);
+ return [{ file: "document.pdf" }];
+ },
+ fileTypeFromBuffer: async () => {
+ calls.typeChecks += 1;
+ return { mime: "application/pdf" };
+ },
+ fs: {
+ readFileSync: () => {
+ calls.fileReads += 1;
+ return Buffer.from("synthetic-pdf");
+ }
+ },
+ path: { basename: (value) => value },
+ ...overrides
});
+ return { mod, calls, options };
+};
+
+const singleFileUploadAuthorizationRequest = (overrides = {}) => ({
+ query: { hash: "expected" },
+ body: {
+ containerID: ["user-container"],
+ casefolderID: ["CASE-1"]
+ },
+ files: {
+ document: [
+ {
+ fieldName: "document.pdf",
+ originalFilename: "document.pdf",
+ path: "/tmp/document.pdf",
+ size: 1,
+ headers: { "content-type": "application/pdf" }
+ }
+ ]
+ },
+ ...overrides
+});
+
+const assertNoSingleFileWork = (calls, { noHash = false } = {}) => {
+ assert.strictEqual(calls.upload.length, 0);
+ assert.strictEqual(calls.fileReads, 0);
+ assert.strictEqual(calls.typeChecks, 0);
+ if (noHash) assert.strictEqual(calls.hash.length, 0);
+};
+
+test("uploadsinglefile rejects a missing NextAuth session before HMAC, file processing or Azure write", async () => {
+ const loaded = loadSingleFileUploadAuthorization({
+ getServerSession: async () => null
+ });
+ const res = createRes();
+
+ await loaded.mod.default.handler(
+ singleFileUploadAuthorizationRequest(),
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 401);
+ assert.strictEqual(res.state.jsonBody.error.code, "UNAUTHENTICATED");
+ assertNoSingleFileWork(loaded.calls, { noHash: true });
+});
+
+test("uploadsinglefile rejects an unusable NextAuth session before HMAC, file processing or Azure write", async () => {
+ const loaded = loadSingleFileUploadAuthorization({
+ getServerSession: async () => ({ user: { id: "" } })
+ });
+ const res = createRes();
+
+ await loaded.mod.default.handler(
+ singleFileUploadAuthorizationRequest(),
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 401);
+ assert.strictEqual(res.state.jsonBody.error.code, "UNAUTHENTICATED");
+ assertNoSingleFileWork(loaded.calls, { noHash: true });
+});
+
+test("uploadsinglefile passes the multipart request, response and PEDW request-scoped options to getServerSession", async () => {
+ const loaded = loadSingleFileUploadAuthorization();
+ const req = singleFileUploadAuthorizationRequest();
+ const res = createRes();
+
+ await loaded.mod.default.handler(req, res);
+
+ assert.strictEqual(loaded.calls.options.length, 1);
+ assert.strictEqual(loaded.calls.options[0][0], req);
+ assert.strictEqual(loaded.calls.options[0][1], res);
+ assert.strictEqual(loaded.calls.session.length, 1);
+ assert.strictEqual(loaded.calls.session[0][0], req);
+ assert.strictEqual(loaded.calls.session[0][1], res);
+ assert.strictEqual(loaded.calls.session[0][2], loaded.options);
+});
+
+test("installed getServerSession resolves a database session cookie without treating multipart body as a session update", async () => {
+ const { getServerSession } = require("next-auth/next");
+ const adapterCalls = [];
+ const callbackCalls = [];
+ const expires = new Date(Date.now() + 30 * 60 * 1000);
const req = {
- query: {
- container: "c1",
- tempcaseref: "TMP/1",
- repid: "rep 1",
- hash: "expected"
+ method: "POST",
+ body: {
+ containerID: ["user-container"],
+ casefolderID: ["CASE-1"]
+ },
+ headers: { host: "localhost:3000" },
+ cookies: { "next-auth.session-token": "session-token" }
+ };
+ const responseHeaders = {};
+ const res = {
+ getHeader(name) {
+ return responseHeaders[name.toLowerCase()];
+ },
+ setHeader(name, value) {
+ responseHeaders[name.toLowerCase()] = value;
+ }
+ };
+ const user = {
+ id: "user-container",
+ name: "Owner",
+ email: "owner@example.test",
+ image: null
+ };
+ const session = {
+ sessionToken: "session-token",
+ userId: user.id,
+ expires
+ };
+ const options = {
+ secret: "test-secret",
+ session: {
+ strategy: "database",
+ maxAge: 30 * 60,
+ updateAge: 5 * 60
+ },
+ cookies: {
+ sessionToken: {
+ name: "next-auth.session-token",
+ options: {
+ httpOnly: true,
+ sameSite: "lax",
+ path: "/",
+ secure: false
+ }
+ }
+ },
+ adapter: {
+ async getSessionAndUser(sessionToken) {
+ adapterCalls.push(["getSessionAndUser", sessionToken]);
+ return { session, user };
+ },
+ async updateSession(updatedSession) {
+ adapterCalls.push(["updateSession", updatedSession]);
+ return updatedSession;
+ },
+ async deleteSession(sessionToken) {
+ adapterCalls.push(["deleteSession", sessionToken]);
+ }
+ },
+ callbacks: {
+ async session(callbackArguments) {
+ callbackCalls.push(callbackArguments);
+ return callbackArguments;
+ }
}
};
- const res = createRes();
- await mod.default.handler(req, res);
- assert.strictEqual(res.state.statusCode, 200);
- assert.deepStrictEqual(JSON.parse(JSON.stringify(res.state.jsonBody)), {
- ok: true
+ const resolvedSession = await getServerSession(req, res, options);
+
+ assert.deepStrictEqual(adapterCalls[0], [
+ "getSessionAndUser",
+ "session-token"
+ ]);
+ assert.strictEqual(callbackCalls.length, 1);
+ assert.strictEqual(callbackCalls[0].user.id, "user-container");
+ assert.strictEqual(callbackCalls[0].newSession, undefined);
+ assert.strictEqual(resolvedSession.user.id, "user-container");
+ assert.deepStrictEqual(req.body, {
+ containerID: ["user-container"],
+ casefolderID: ["CASE-1"]
});
});
-test("createrepcompletemessage handler dependency failure returns CREATE_REP_COMPLETE_MESSAGE_FAILED", async () => {
+test("uploadsinglefile forbids another user's container before HMAC, file processing or Azure write", async () => {
+ const loaded = loadSingleFileUploadAuthorization();
+ const req = singleFileUploadAuthorizationRequest();
+ req.body.containerID = ["other-container"];
+ const res = createRes();
+
+ await loaded.mod.default.handler(req, res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(res.state.jsonBody.error.code, "FORBIDDEN");
+ assertNoSingleFileWork(loaded.calls, { noHash: true });
+});
+
+test("uploadsinglefile rejects invalid HMAC for the owning user before file processing or Azure write", async () => {
+ const loaded = loadSingleFileUploadAuthorization({
+ hashAPIPath: () => "?hash=different"
+ });
+ const res = createRes();
+
+ await loaded.mod.default.handler(
+ singleFileUploadAuthorizationRequest(),
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "INVALID_HASH");
+ assertNoSingleFileWork(loaded.calls);
+});
+
+test("uploadsinglefile requires HMAC for the authenticated owning user", async () => {
+ const loaded = loadSingleFileUploadAuthorization();
+ const req = singleFileUploadAuthorizationRequest({ query: {} });
+ const res = createRes();
+
+ await loaded.mod.default.handler(req, res);
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "HASH_REQUIRED");
+ assertNoSingleFileWork(loaded.calls);
+});
+
+test("uploadsinglefile preserves multipart owner success response and exact Azure helper arguments", async () => {
+ const loaded = loadSingleFileUploadAuthorization();
+ const res = createRes();
+
+ await loaded.mod.default.handler(
+ singleFileUploadAuthorizationRequest(),
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.deepStrictEqual(JSON.parse(JSON.stringify(res.state.jsonBody)), {
+ data: [{ file: "document.pdf" }],
+ invalidFiles: []
+ });
+ assert.strictEqual(loaded.calls.upload.length, 1);
+ assert.strictEqual(loaded.calls.upload[0][1], "user-container");
+ assert.strictEqual(loaded.calls.upload[0][2], "CASE-1");
+ assert.deepStrictEqual(
+ JSON.parse(JSON.stringify(loaded.calls.upload[0][0])),
+ {
+ document: [
+ {
+ fieldName: "document.pdf",
+ originalFilename: "document.pdf",
+ path: "/tmp/document.pdf",
+ size: 1,
+ headers: { "content-type": "application/pdf" },
+ contentType: "application/pdf"
+ }
+ ]
+ }
+ );
+ assert.strictEqual(loaded.calls.fileReads, 1);
+ assert.strictEqual(loaded.calls.typeChecks, 1);
+});
+
+const loadOrdinaryRepCompletion = (overrides = {}) => {
+ const calls = { hash: [], queue: [] };
+ const payload = { messageId: "ordinary-message" };
const mod = loadModule("pages/api/file/createrepcompletemessage_api.js", {
- nextConnect: createNextConnectMock(),
- middleware: () => {},
- hashAPIPath: () => "&hash=expected",
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
+ getSession: async () => ({ user: { id: "user-container" } }),
+ hashAPIPath: (queryPath) => {
+ calls.hash.push(queryPath);
+ return "&hash=expected";
+ },
+ createRepCompleteMessage: async (...args) => {
+ calls.queue.push(args);
+ return payload;
+ },
consoleLogger: () => {},
- createRepCompleteMessage: async () => {
+ ...overrides
+ });
+
+ return { mod, calls, payload };
+};
+
+const ordinaryRepCompletionRequest = (overrides = {}) => ({
+ method: "GET",
+ headers: {},
+ query: {
+ container: "user-container",
+ tempcaseref: "CAS-12345-A1B2C3",
+ repid: "2026-03-18-10:20:30_-_APP_-_Statement_-_Jones_Rob",
+ hash: "expected"
+ },
+ ...overrides
+});
+
+const assertNoCompletionWork = (calls, { noHash = false } = {}) => {
+ assert.strictEqual(calls.queue.length, 0);
+ if (noHash) assert.strictEqual(calls.hash.length, 0);
+};
+
+test("createrepcompletemessage rejects unsupported methods before authorization work", async () => {
+ const loaded = loadOrdinaryRepCompletion();
+ const res = createRes();
+
+ await loaded.mod.default(
+ ordinaryRepCompletionRequest({ method: "POST" }),
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 405);
+ assert.strictEqual(res.state.headers.allow, "GET");
+ assert.strictEqual(res.state.jsonBody.error.code, "METHOD_NOT_ALLOWED");
+ assertNoCompletionWork(loaded.calls, { noHash: true });
+});
+
+for (const inputCase of [
+ { name: "missing container", query: { container: undefined } },
+ {
+ 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: "missing representation identifier", query: { repid: undefined } },
+ {
+ 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();
+ const request = ordinaryRepCompletionRequest();
+ const res = createRes();
+
+ request.query = { ...request.query, ...inputCase.query };
+ Object.keys(request.query).forEach((key) => {
+ if (typeof request.query[key] === "undefined")
+ delete request.query[key];
+ });
+ await loaded.mod.default(request, res);
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assertNoCompletionWork(loaded.calls, { noHash: true });
+ });
+}
+
+for (const sessionCase of [
+ { name: "missing NextAuth session", session: null },
+ { name: "session without user id", session: { user: {} } },
+ { name: "session with empty user id", session: { user: { id: "" } } },
+ { name: "session with non-string user id", session: { user: { id: 123 } } }
+]) {
+ test(`createrepcompletemessage rejects ${sessionCase.name} before HMAC processing`, async () => {
+ const loaded = loadOrdinaryRepCompletion({
+ getSession: async () => sessionCase.session
+ });
+ const res = createRes();
+
+ await loaded.mod.default(ordinaryRepCompletionRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assertNoCompletionWork(loaded.calls, { noHash: true });
+ });
+}
+
+test("createrepcompletemessage rejects cross-container ownership before HMAC processing", async () => {
+ const loaded = loadOrdinaryRepCompletion({
+ getSession: async () => ({ user: { id: "different-container" } })
+ });
+ const res = createRes();
+
+ await loaded.mod.default(ordinaryRepCompletionRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assertNoCompletionWork(loaded.calls, { noHash: true });
+});
+
+test("administrative cookie alone cannot authorize ordinary representation completion", async () => {
+ const loaded = loadOrdinaryRepCompletion({ getSession: async () => null });
+ const res = createRes();
+
+ await loaded.mod.default(
+ ordinaryRepCompletionRequest({
+ headers: { cookie: "pedw_admin_session=valid-admin-token" }
+ }),
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assertNoCompletionWork(loaded.calls, { noHash: true });
+});
+
+test("previously valid HMAC cannot bypass a missing current ordinary session", async () => {
+ const loaded = loadOrdinaryRepCompletion({ getSession: async () => null });
+ const res = createRes();
+
+ await loaded.mod.default(ordinaryRepCompletionRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assertNoCompletionWork(loaded.calls, { noHash: true });
+});
+
+for (const hashCase of [
+ { name: "missing HMAC", hash: undefined },
+ { name: "invalid HMAC", hash: "wrong" }
+]) {
+ test(`createrepcompletemessage rejects ${hashCase.name} without queue work`, async () => {
+ const loaded = loadOrdinaryRepCompletion();
+ const request = ordinaryRepCompletionRequest();
+ const res = createRes();
+
+ if (typeof hashCase.hash === "undefined") delete request.query.hash;
+ else request.query.hash = hashCase.hash;
+ await loaded.mod.default(request, res);
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assertNoCompletionWork(loaded.calls);
+ });
+}
+
+test("createrepcompletemessage accepts punctuation and preserves exact identifiers and response", async () => {
+ const loaded = loadOrdinaryRepCompletion();
+ const request = ordinaryRepCompletionRequest();
+ const res = createRes();
+
+ await loaded.mod.default(request, res);
+
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.deepStrictEqual(loaded.calls.queue, [
+ [
+ request.query.container,
+ request.query.tempcaseref,
+ request.query.repid
+ ]
+ ]);
+ assert.deepStrictEqual(
+ JSON.parse(JSON.stringify(res.state.jsonBody)),
+ loaded.payload
+ );
+});
+
+test("createrepcompletemessage preserves encoded HMAC compatibility", async () => {
+ const loaded = loadOrdinaryRepCompletion({
+ hashAPIPath: (queryPath) => {
+ loaded.calls.hash.push(queryPath);
+ return queryPath.includes("repid=rep%20name%20%26%20notes.json")
+ ? "&hash=expected"
+ : "&hash=other";
+ }
+ });
+ const request = ordinaryRepCompletionRequest();
+ request.query.repid = "rep name & notes.json";
+ const res = createRes();
+
+ await loaded.mod.default(request, res);
+
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.strictEqual(loaded.calls.queue.length, 1);
+ assert.strictEqual(loaded.calls.hash.length, 2);
+});
+
+test("createrepcompletemessage dependency failure returns CREATE_REP_COMPLETE_MESSAGE_FAILED", async () => {
+ const loaded = loadOrdinaryRepCompletion({
+ createRepCompleteMessage: async (...args) => {
+ loaded.calls.queue.push(args);
throw new Error("rep message failed");
}
});
-
- const req = {
- query: {
- container: "c1",
- tempcaseref: "TMP1",
- repid: "rep1",
- hash: "expected"
- }
- };
const res = createRes();
- await mod.default.handler(req, res);
+
+ await loaded.mod.default(ordinaryRepCompletionRequest(), res);
assert.strictEqual(res.state.statusCode, 400);
assert.strictEqual(
res.state.jsonBody.error.code,
"CREATE_REP_COMPLETE_MESSAGE_FAILED"
);
+ assert.strictEqual(loaded.calls.queue.length, 1);
});
-test("getbloblistproxy success returns proxied payload", async () => {
+const loadAdminRepCompletion = (overrides = {}) => {
+ 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,
+ respondSuccess: respondSuccessMock,
+ setAdminAuthNoStore: () => {
+ calls.noStore += 1;
+ },
+ readAdminSessionCookie: () => {
+ calls.readSession += 1;
+ return "admin-token";
+ },
+ validateAdminSession: () => {
+ calls.validate += 1;
+ return true;
+ },
+ hasTrustedSameOrigin: () => {
+ calls.origin += 1;
+ return true;
+ },
+ createRepCompleteMessage: async (...args) => {
+ calls.queue.push(args);
+ return payload;
+ },
+ consoleLogger: () => {},
+ ...overrides
+ });
+
+ return { mod, calls, payload };
+};
+
+const adminRepCompletionRequest = (overrides = {}) => ({
+ method: "POST",
+ headers: {
+ origin: "https://portal.example.test",
+ cookie: "pedw_admin_session=admin-token"
+ },
+ body: {
+ container: "selected-user-container",
+ tempcaseref: "CAS-12345-A1B2C3",
+ repid: "2026-03-18-10:20:30_-_IP_-_Statement_-_Smith_Alex_rep.json"
+ },
+ ...overrides
+});
+
+test("admin representation completion rejects unsupported methods before authentication", async () => {
+ const loaded = loadAdminRepCompletion();
+ const res = createRes();
+
+ await loaded.mod.default(adminRepCompletionRequest({ method: "GET" }), res);
+
+ assert.strictEqual(res.state.statusCode, 405);
+ assert.strictEqual(res.state.headers.allow, "POST");
+ assert.strictEqual(loaded.calls.noStore, 1);
+ assert.strictEqual(loaded.calls.readSession, 0);
+ assertNoCompletionWork(loaded.calls);
+});
+
+for (const sessionCase of [
+ { name: "missing administrative session", token: null },
+ { name: "invalid administrative session", token: "invalid-token" },
+ { name: "expired administrative session", token: "expired-token" }
+]) {
+ test(`admin representation completion rejects ${sessionCase.name}`, async () => {
+ const loaded = loadAdminRepCompletion({
+ readAdminSessionCookie: () => sessionCase.token,
+ validateAdminSession: () => false
+ });
+ const res = createRes();
+
+ await loaded.mod.default(adminRepCompletionRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(loaded.calls.origin, 0);
+ assertNoCompletionWork(loaded.calls);
+ });
+}
+
+for (const originCase of [
+ {
+ name: "missing Origin",
+ headers: { cookie: "pedw_admin_session=admin-token" }
+ },
+ {
+ name: "cross-origin request",
+ headers: {
+ origin: "https://attacker.example.test",
+ cookie: "pedw_admin_session=admin-token"
+ }
+ }
+]) {
+ test(`admin representation completion rejects ${originCase.name}`, async () => {
+ const loaded = loadAdminRepCompletion({
+ hasTrustedSameOrigin: () => false
+ });
+ const res = createRes();
+
+ await loaded.mod.default(
+ adminRepCompletionRequest({ headers: originCase.headers }),
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assertNoCompletionWork(loaded.calls);
+ });
+}
+
+for (const inputCase of [
+ { name: "missing container", body: { container: undefined } },
+ { name: "malformed container", body: { container: "Invalid_Container" } },
+ { name: "missing case reference", body: { tempcaseref: undefined } },
+ { name: "unsafe case-reference segment", body: { tempcaseref: "CAS/123" } },
+ { name: "missing representation identifier", body: { repid: undefined } },
+ { name: "unsafe representation segment", body: { repid: "../rep.json" } }
+]) {
+ test(`admin representation completion rejects ${inputCase.name} without queue work`, async () => {
+ const loaded = loadAdminRepCompletion();
+ const request = adminRepCompletionRequest();
+ const res = createRes();
+
+ request.body = { ...request.body, ...inputCase.body };
+ Object.keys(request.body).forEach((key) => {
+ if (typeof request.body[key] === "undefined")
+ delete request.body[key];
+ });
+ await loaded.mod.default(request, res);
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assertNoCompletionWork(loaded.calls);
+ });
+}
+
+test("ordinary NextAuth session alone cannot authorize admin representation completion", async () => {
+ const loaded = loadAdminRepCompletion({
+ readAdminSessionCookie: () => null,
+ validateAdminSession: () => false,
+ getSession: async () => ({ user: { id: "selected-user-container" } })
+ });
+ const res = createRes();
+
+ await loaded.mod.default(adminRepCompletionRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assertNoCompletionWork(loaded.calls);
+});
+
+test("admin representation completion preserves cross-container identifiers and response", async () => {
+ const loaded = loadAdminRepCompletion();
+ const request = adminRepCompletionRequest();
+ const res = createRes();
+
+ await loaded.mod.default(request, res);
+
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.deepStrictEqual(loaded.calls.queue, [
+ [request.body.container, request.body.tempcaseref, request.body.repid]
+ ]);
+ assert.deepStrictEqual(
+ JSON.parse(JSON.stringify(res.state.jsonBody)),
+ loaded.payload
+ );
+});
+
+test("admin representation completion accepts legitimate filename punctuation", async () => {
+ const loaded = loadAdminRepCompletion();
+ const request = adminRepCompletionRequest();
+ request.body.repid = "rep name_-_notes.v2 (final)!.json";
+ const res = createRes();
+
+ await loaded.mod.default(request, res);
+
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.strictEqual(loaded.calls.queue.length, 1);
+});
+
+const loadBlobListProxy = ({ session, ...overrides } = {}) => {
+ const calls = {
+ session: [],
+ options: [],
+ token: 0,
+ hash: [],
+ headers: [],
+ axios: []
+ };
+ const options = { id: "pedw-blob-list-options" };
+ const payload = { value: [{ id: "blob-1" }] };
+ const resolvedSession =
+ typeof session === "undefined"
+ ? { user: { id: "user-container" } }
+ : session;
const mod = loadModule("pages/api/file/getbloblistproxy.js", {
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
- getToken: async () => ({ access_token: "tok" }),
- azureHeaders: () => ({ headers: { Authorization: "Bearer tok" } }),
- hashAPIPath: () => "&hash=abc",
+ authOptions: (req, res) => {
+ calls.options.push([req, res]);
+ return options;
+ },
+ getServerSession: async (...args) => {
+ calls.session.push(args);
+ return resolvedSession;
+ },
+ getToken: async () => {
+ calls.token += 1;
+ return { access_token: "synthetic-token" };
+ },
+ azureHeaders: (accessToken) => {
+ calls.headers.push(accessToken);
+ return {
+ headers: { Authorization: "Bearer synthetic-token" }
+ };
+ },
+ hashAPIPath: (queryPath) => {
+ calls.hash.push(queryPath);
+ return "&hash=synthetic-hash";
+ },
consoleLogger: () => {},
process: { env: { API_ROOT: "http://example.com" } },
axios: {
- get: async () => ({ data: { value: [{ id: "b1" }] } })
- }
+ get: async (...args) => {
+ calls.axios.push(args);
+ return { data: payload };
+ }
+ },
+ ...overrides
});
- const req = {
- query: { container: "cont/1", casefolderID: "CASE/1" }
- };
+ return { mod, calls, options, payload };
+};
+
+const blobListProxyRequest = (overrides = {}) => ({
+ method: "GET",
+ query: { container: "user-container", casefolderID: "CASE/1" },
+ headers: {},
+ ...overrides
+});
+
+const assertNoBlobListProxyWork = (calls) => {
+ assert.strictEqual(calls.token, 0);
+ assert.strictEqual(calls.hash.length, 0);
+ assert.strictEqual(calls.headers.length, 0);
+ assert.strictEqual(calls.axios.length, 0);
+};
+
+test("getbloblistproxy rejects unsupported methods before authentication or proxy work", async () => {
+ const loaded = loadBlobListProxy();
const res = createRes();
- await mod.default(req, res);
- assert.strictEqual(res.state.statusCode, 200);
- assert.deepStrictEqual(JSON.parse(JSON.stringify(res.state.jsonBody)), {
- value: [{ id: "b1" }]
+ await loaded.mod.default(blobListProxyRequest({ method: "POST" }), res);
+
+ assert.strictEqual(res.state.statusCode, 405);
+ assert.strictEqual(res.state.jsonBody.error.code, "METHOD_NOT_ALLOWED");
+ assert.strictEqual(loaded.calls.options.length, 0);
+ assert.strictEqual(loaded.calls.session.length, 0);
+ assertNoBlobListProxyWork(loaded.calls);
+});
+
+test("getbloblistproxy rejects a missing container before authentication or proxy work", async () => {
+ const loaded = loadBlobListProxy();
+ const res = createRes();
+
+ await loaded.mod.default(
+ blobListProxyRequest({ query: { casefolderID: "CASE/1" } }),
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "MISSING_REQUIRED_QUERY");
+ assert.strictEqual(loaded.calls.options.length, 0);
+ assert.strictEqual(loaded.calls.session.length, 0);
+ assertNoBlobListProxyWork(loaded.calls);
+});
+
+test("getbloblistproxy rejects a malformed container before authentication or proxy work", async () => {
+ const loaded = loadBlobListProxy();
+ const res = createRes();
+
+ await loaded.mod.default(
+ blobListProxyRequest({
+ query: { container: "Invalid_Container", casefolderID: "CASE/1" }
+ }),
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "INVALID_REQUEST");
+ assert.strictEqual(loaded.calls.options.length, 0);
+ assert.strictEqual(loaded.calls.session.length, 0);
+ assertNoBlobListProxyWork(loaded.calls);
+});
+
+test("getbloblistproxy rejects a missing casefolderID before authentication or proxy work", async () => {
+ const loaded = loadBlobListProxy();
+ const res = createRes();
+
+ await loaded.mod.default(
+ blobListProxyRequest({ query: { container: "user-container" } }),
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "MISSING_REQUIRED_QUERY");
+ assert.strictEqual(loaded.calls.options.length, 0);
+ assert.strictEqual(loaded.calls.session.length, 0);
+ assertNoBlobListProxyWork(loaded.calls);
+});
+
+for (const sessionCase of [
+ { name: "missing session", session: null },
+ { name: "session without user id", session: { user: {} } },
+ { name: "session with empty user id", session: { user: { id: "" } } },
+ { name: "session with non-string user id", session: { user: { id: 123 } } }
+]) {
+ test(`getbloblistproxy rejects ${sessionCase.name} before proxy work`, async () => {
+ const loaded = loadBlobListProxy({ session: sessionCase.session });
+ const res = createRes();
+
+ await loaded.mod.default(blobListProxyRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(res.state.jsonBody.error.code, "FORBIDDEN");
+ assertNoBlobListProxyWork(loaded.calls);
});
+}
+
+test("getbloblistproxy rejects cross-container access before proxy work", async () => {
+ const loaded = loadBlobListProxy({
+ session: { user: { id: "different-container" } }
+ });
+ const res = createRes();
+
+ await loaded.mod.default(blobListProxyRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(res.state.jsonBody.error.code, "FORBIDDEN");
+ assertNoBlobListProxyWork(loaded.calls);
+});
+
+test("getbloblistproxy preserves signed path, bearer header and response for owning user", async () => {
+ const loaded = loadBlobListProxy();
+ const req = blobListProxyRequest();
+ const res = createRes();
+
+ await loaded.mod.default(req, res);
+
+ const expectedPath =
+ "/api/file/getbloblist?container=user-container&casefolderID=CASE%2F1";
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.deepStrictEqual(loaded.calls.options, [[req, res]]);
+ assert.deepStrictEqual(loaded.calls.session, [[req, res, loaded.options]]);
+ assert.strictEqual(loaded.calls.token, 1);
+ assert.deepStrictEqual(loaded.calls.hash, [expectedPath]);
+ assert.deepStrictEqual(loaded.calls.headers, ["synthetic-token"]);
+ assert.strictEqual(loaded.calls.axios.length, 1);
+ assert.strictEqual(
+ loaded.calls.axios[0][0],
+ `http://example.com${expectedPath}&hash=synthetic-hash`
+ );
+ assert.deepStrictEqual(loaded.calls.axios[0][1], {
+ headers: { Authorization: "Bearer synthetic-token" }
+ });
+ assert.deepStrictEqual(
+ JSON.parse(JSON.stringify(res.state.jsonBody)),
+ loaded.payload
+ );
});
test("getbloblistproxy dependency failure returns GET_BLOB_LIST_PROXY_FAILED", async () => {
- const mod = loadModule("pages/api/file/getbloblistproxy.js", {
- respondError: respondErrorMock,
- respondSuccess: respondSuccessMock,
- getToken: async () => ({ access_token: "tok" }),
- azureHeaders: () => ({ headers: {} }),
- hashAPIPath: () => "&hash=abc",
- consoleLogger: () => {},
- process: { env: { API_ROOT: "http://example.com" } },
+ const loaded = loadBlobListProxy({
axios: {
- get: async () => {
+ get: async (...args) => {
+ loaded.calls.axios.push(args);
throw new Error("proxy failed");
}
}
});
- const req = {
- query: { container: "c1", casefolderID: "f1" }
- };
const res = createRes();
- await mod.default(req, res);
+ await loaded.mod.default(blobListProxyRequest(), res);
assert.strictEqual(res.state.statusCode, 400);
assert.strictEqual(
res.state.jsonBody.error.code,
"GET_BLOB_LIST_PROXY_FAILED"
);
+ assert.strictEqual(loaded.calls.token, 1);
+ assert.strictEqual(loaded.calls.hash.length, 1);
+ assert.strictEqual(loaded.calls.headers.length, 1);
+ assert.strictEqual(loaded.calls.axios.length, 1);
});
-test("getrepsblobproxy success returns proxied payload", async () => {
+const loadOrdinaryRepsProxy = (overrides = {}) => {
+ const calls = { session: [], options: [], token: 0, hash: [], axios: [] };
+ const options = { id: "pedw-representation-options" };
+ const payload = { "@odata.count": 1, value: [{ id: "r1" }] };
const mod = loadModule("pages/api/file/getrepsblobproxy.js", {
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
- getToken: async () => ({ access_token: "tok" }),
- azureHeaders: () => ({ headers: {} }),
- hashAPIPath: () => "&hash=abc",
+ authOptions: (req, res) => {
+ calls.options.push([req, res]);
+ return options;
+ },
+ getServerSession: async (...args) => {
+ calls.session.push(args);
+ return { user: { id: "user-container" } };
+ },
+ getToken: async () => {
+ calls.token += 1;
+ return { access_token: "tok" };
+ },
+ azureHeaders: () => ({ headers: { Authorization: "Bearer tok" } }),
+ hashAPIPath: (queryPath) => {
+ calls.hash.push(queryPath);
+ 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 () => ({ data: { value: [{ id: "r1" }] } })
- }
+ get: async (...args) => {
+ calls.axios.push(args);
+ return { data: payload };
+ }
+ },
+ ...overrides
});
- const req = {
- query: { container: "c1" }
- };
- const res = createRes();
- await mod.default(req, res);
+ return { mod, calls, options, payload };
+};
- assert.strictEqual(res.state.statusCode, 200);
- assert.deepStrictEqual(JSON.parse(JSON.stringify(res.state.jsonBody)), {
- value: [{ id: "r1" }]
- });
+const ordinaryRepsRequest = (overrides = {}) => ({
+ method: "GET",
+ query: { container: "user-container" },
+ headers: {},
+ ...overrides
});
-test("getawaitingsubmissionfromblobproxy dependency failure returns GET_AWAITING_SUBMISSION_PROXY_FAILED", async () => {
+const assertNoProxyWork = (calls) => {
+ assert.strictEqual(calls.token, 0);
+ assert.strictEqual(calls.hash.length, 0);
+ assert.strictEqual(calls.axios.length, 0);
+};
+
+for (const sessionCase of [
+ { name: "missing session", session: null },
+ { name: "session without user id", session: { user: {} } },
+ { name: "session with empty user id", session: { user: { id: "" } } },
+ { name: "session with non-string user id", session: { user: { id: 123 } } }
+]) {
+ test(`getrepsblobproxy rejects ${sessionCase.name} before proxy work`, async () => {
+ const loaded = loadOrdinaryRepsProxy({
+ getServerSession: async () => sessionCase.session
+ });
+ const res = createRes();
+
+ await loaded.mod.default(ordinaryRepsRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(res.state.jsonBody.error.code, "FORBIDDEN");
+ assertNoProxyWork(loaded.calls);
+ });
+}
+
+test("getrepsblobproxy rejects cross-container access before proxy work", async () => {
+ const loaded = loadOrdinaryRepsProxy({
+ getServerSession: async () => ({ user: { id: "different-container" } })
+ });
+ const res = createRes();
+
+ await loaded.mod.default(ordinaryRepsRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(res.state.jsonBody.error.code, "FORBIDDEN");
+ assertNoProxyWork(loaded.calls);
+});
+
+test("administrative cookie alone cannot authorize getrepsblobproxy", async () => {
+ const loaded = loadOrdinaryRepsProxy({
+ getServerSession: async () => null
+ });
+ const res = createRes();
+
+ await loaded.mod.default(
+ ordinaryRepsRequest({
+ headers: { cookie: "pedw_admin_session=valid-admin-token" }
+ }),
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assertNoProxyWork(loaded.calls);
+});
+
+test("getrepsblobproxy rejects unsupported methods before proxy work", async () => {
+ const loaded = loadOrdinaryRepsProxy();
+ const res = createRes();
+
+ await loaded.mod.default(ordinaryRepsRequest({ method: "POST" }), res);
+
+ assert.strictEqual(res.state.statusCode, 405);
+ assert.strictEqual(res.state.jsonBody.error.code, "METHOD_NOT_ALLOWED");
+ assertNoProxyWork(loaded.calls);
+});
+
+for (const containerCase of [
+ { name: "missing container", query: {} },
+ { name: "empty container", query: { container: "" } },
+ { name: "null container", query: { container: null } },
+ { name: "non-string container", query: { container: ["user-container"] } },
+ { name: "malformed container", query: { container: "Invalid_Container" } }
+]) {
+ test(`getrepsblobproxy rejects ${containerCase.name} before proxy work`, async () => {
+ const loaded = loadOrdinaryRepsProxy();
+ const res = createRes();
+
+ await loaded.mod.default(
+ ordinaryRepsRequest({ query: containerCase.query }),
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assertNoProxyWork(loaded.calls);
+ });
+}
+
+test("getrepsblobproxy preserves signed path and response for owning user", async () => {
+ const loaded = loadOrdinaryRepsProxy();
+ const req = ordinaryRepsRequest({
+ headers: { cookie: "next-auth.session-token=test-session" }
+ });
+ const res = createRes();
+
+ await loaded.mod.default(req, res);
+
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.deepStrictEqual(loaded.calls.options, [[req, res]]);
+ assert.deepStrictEqual(loaded.calls.session, [[req, res, loaded.options]]);
+ assert.strictEqual(loaded.calls.token, 1);
+ assert.deepStrictEqual(loaded.calls.hash, [
+ "/api/file/getrepsblob?container=user-container"
+ ]);
+ assert.strictEqual(
+ 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
+ );
+});
+
+test("getrepsblobproxy dependency failure returns GET_REPS_BLOB_PROXY_FAILED", async () => {
+ const loaded = loadOrdinaryRepsProxy({
+ axios: {
+ get: async (...args) => {
+ loaded.calls.axios.push(args);
+ throw new Error("representation proxy failed");
+ }
+ }
+ });
+ const res = createRes();
+
+ await loaded.mod.default(ordinaryRepsRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(
+ res.state.jsonBody.error.code,
+ "GET_REPS_BLOB_PROXY_FAILED"
+ );
+ assert.strictEqual(loaded.calls.token, 1);
+ assert.strictEqual(loaded.calls.hash.length, 1);
+ assert.strictEqual(loaded.calls.axios.length, 1);
+});
+
+const loadAdminRepsProxy = (overrides = {}) => {
+ const calls = { token: 0, hash: [], axios: [] };
+ const payload = { "@odata.count": 1, value: [{ id: "admin-r1" }] };
+ 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,
+ setAdminAuthNoStore: () => {},
+ getToken: async () => {
+ calls.token += 1;
+ return { access_token: "tok" };
+ },
+ azureHeaders: () => ({ headers: { Authorization: "Bearer tok" } }),
+ hashAPIPath: (queryPath) => {
+ calls.hash.push(queryPath);
+ return "&hash=abc";
+ },
+ consoleLogger: () => {},
+ 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);
+ return { data: payload };
+ }
+ },
+ ...overrides
+ });
+
+ return { mod, calls, payload };
+};
+
+const adminRepsRequest = (overrides = {}) => ({
+ method: "POST",
+ headers: { origin: "https://portal.example.test" },
+ body: { container: "selected-user-container" },
+ ...overrides
+});
+
+for (const adminSessionCase of [
+ {
+ name: "missing administrative session",
+ overrides: {
+ readAdminSessionCookie: () => null,
+ validateAdminSession: () => false
+ }
+ },
+ {
+ name: "invalid administrative session",
+ overrides: { validateAdminSession: () => false }
+ },
+ {
+ name: "expired administrative session",
+ overrides: { validateAdminSession: () => false }
+ }
+]) {
+ test(`admin getrepsblobproxy rejects ${adminSessionCase.name} before proxy work`, async () => {
+ const loaded = loadAdminRepsProxy(adminSessionCase.overrides);
+ 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);
+ });
+}
+
+for (const originCase of ["missing Origin", "cross-origin request"]) {
+ test(`admin getrepsblobproxy rejects ${originCase} before proxy work`, async () => {
+ const loaded = loadAdminRepsProxy({
+ hasTrustedSameOrigin: () => false
+ });
+ const req = adminRepsRequest();
+ if (originCase === "missing Origin") delete req.headers.origin;
+ if (originCase === "cross-origin request") {
+ req.headers.origin = "https://attacker.example";
+ }
+ const res = createRes();
+
+ await loaded.mod.default(req, res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assertNoProxyWork(loaded.calls);
+ });
+}
+
+for (const containerCase of [
+ { name: "missing container", body: {} },
+ { name: "malformed container", body: { container: "Invalid_Container" } }
+]) {
+ test(`admin getrepsblobproxy rejects ${containerCase.name} before proxy work`, async () => {
+ const loaded = loadAdminRepsProxy();
+ const res = createRes();
+
+ await loaded.mod.default(
+ adminRepsRequest({ body: containerCase.body }),
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "INVALID_REQUEST");
+ assertNoProxyWork(loaded.calls);
+ });
+}
+
+test("admin getrepsblobproxy rejects unsupported methods before proxy work", async () => {
+ const loaded = loadAdminRepsProxy();
+ const res = createRes();
+
+ await loaded.mod.default(adminRepsRequest({ method: "GET" }), res);
+
+ assert.strictEqual(res.state.statusCode, 405);
+ assert.strictEqual(res.state.jsonBody.error.code, "METHOD_NOT_ALLOWED");
+ assertNoProxyWork(loaded.calls);
+});
+
+test("ordinary NextAuth session alone cannot authorize admin getrepsblobproxy", async () => {
+ const loaded = loadAdminRepsProxy({
+ readAdminSessionCookie: () => null,
+ validateAdminSession: () => false,
+ getSession: async () => ({ user: { id: "selected-user-container" } })
+ });
+ const res = createRes();
+
+ await loaded.mod.default(adminRepsRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assertNoProxyWork(loaded.calls);
+});
+
+test("admin getrepsblobproxy preserves cross-container signed path and response", async () => {
+ const loaded = loadAdminRepsProxy();
+ const res = createRes();
+
+ await loaded.mod.default(adminRepsRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.strictEqual(loaded.calls.token, 1);
+ assert.deepStrictEqual(loaded.calls.hash, [
+ "/api/file/getrepsblob?container=selected-user-container"
+ ]);
+ assert.strictEqual(
+ 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
+ );
+});
+
+test("admin storage refresh uses dedicated POST proxy while ordinary callers remain unchanged", () => {
+ const rootDir = path.resolve(__dirname, "..", "..");
+ const adminSource = fs.readFileSync(
+ path.join(rootDir, "components/admin/tabs/storage.js"),
+ "utf8"
+ );
+ const topThreeSource = fs.readFileSync(
+ path.join(rootDir, "components/myportal/topthree_reps.js"),
+ "utf8"
+ );
+ const viewAllSource = fs.readFileSync(
+ path.join(rootDir, "components/myportal/viewall.js"),
+ "utf8"
+ );
+
+ assert.match(adminSource, /fetch\("\/api\/admin\/getrepsblobproxy"/);
+ assert.match(
+ adminSource,
+ /fetch\("\/api\/admin\/getrepsblobproxy"[\s\S]*method:\s*"POST"[\s\S]*JSON\.stringify\(\{ container: containerID \}\)/
+ );
+ assert.doesNotMatch(adminSource, /getRepsFromBlobProxy/);
+ assert.match(topThreeSource, /getRepsFromBlobProxy\(containerID\)/);
+ 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(
+ path.join(rootDir, "components/admin/tabs/storage.js"),
+ "utf8"
+ );
+ const ordinarySource = fs.readFileSync(
+ path.join(
+ rootDir,
+ "components/case/representation/representationComplete.js"
+ ),
+ "utf8"
+ );
+
+ assert.match(
+ adminSource,
+ /fetch\(\s*"\/api\/admin\/createrepcompletemessage",\s*\{\s*method:\s*"POST"/
+ );
+ assert.match(adminSource, /container:\s*c\.container/);
+ assert.match(
+ adminSource,
+ /tempcaseref:\s*folder\.repJsonBlob\.name\.split\(\s*"\/"\s*\)\[0\]/
+ );
+ assert.match(
+ adminSource,
+ /repid:\s*folder\.repJsonBlob\.name\.split\(\s*"\/"\s*\)\[1\]/
+ );
+ assert.match(adminSource, /if \(!response\.ok\)/);
+ assert.doesNotMatch(adminSource, /sendRepCompleteMessage/);
+ assert.match(ordinarySource, /sendRepCompleteMessage\(/);
+});
+
+const loadAwaitingSubmissionProxy = (overrides = {}) => {
+ const calls = { session: [], options: [], token: 0, hash: [], axios: [] };
+ const options = { id: "pedw-awaiting-submission-options" };
+ const payload = {
+ "@odata.count": 1,
+ value: [{ pinswg_name: "TMP-SYNTHETIC" }],
+ case: [{ ticketnumber: "TMP-SYNTHETIC" }]
+ };
const mod = loadModule(
"pages/api/file/getawaitingsubmissionfromblobproxy.js",
{
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
- getToken: async () => ({ access_token: "tok" }),
- azureHeaders: () => ({ headers: {} }),
- hashAPIPath: () => "&hash=abc",
+ authOptions: (req, res) => {
+ calls.options.push([req, res]);
+ return options;
+ },
+ getServerSession: async (...args) => {
+ calls.session.push(args);
+ return { user: { id: "user-container" } };
+ },
+ getToken: async () => {
+ calls.token += 1;
+ return { access_token: "tok" };
+ },
+ azureHeaders: () => ({
+ headers: { Authorization: "Bearer tok" }
+ }),
+ hashAPIPath: (queryPath) => {
+ calls.hash.push(queryPath);
+ return "&hash=abc";
+ },
consoleLogger: () => {},
process: { env: { API_ROOT: "http://example.com" } },
axios: {
- get: async () => {
- throw new Error("awaiting failed");
+ get: async (...args) => {
+ calls.axios.push(args);
+ return { data: payload };
}
- }
+ },
+ ...overrides
}
);
- const req = {
- query: { container: "c1" }
- };
+ return { mod, calls, options, payload };
+};
+
+const awaitingSubmissionRequest = (overrides = {}) => ({
+ method: "GET",
+ query: { container: "user-container" },
+ headers: {},
+ ...overrides
+});
+
+for (const sessionCase of [
+ { name: "missing session", session: null },
+ { name: "session without user id", session: { user: {} } },
+ { name: "session with empty user id", session: { user: { id: "" } } },
+ { name: "session with non-string user id", session: { user: { id: 123 } } }
+]) {
+ test(`getawaitingsubmissionfromblobproxy rejects ${sessionCase.name} before proxy work`, async () => {
+ const loaded = loadAwaitingSubmissionProxy({
+ getServerSession: async () => sessionCase.session
+ });
+ const res = createRes();
+
+ await loaded.mod.default(awaitingSubmissionRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(res.state.jsonBody.error.code, "FORBIDDEN");
+ assertNoProxyWork(loaded.calls);
+ });
+}
+
+test("getawaitingsubmissionfromblobproxy rejects cross-container access before proxy work", async () => {
+ const loaded = loadAwaitingSubmissionProxy({
+ getServerSession: async () => ({ user: { id: "different-container" } })
+ });
const res = createRes();
- await mod.default(req, res);
+
+ await loaded.mod.default(awaitingSubmissionRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(res.state.jsonBody.error.code, "FORBIDDEN");
+ assertNoProxyWork(loaded.calls);
+});
+
+test("getawaitingsubmissionfromblobproxy rejects unsupported methods before proxy work", async () => {
+ const loaded = loadAwaitingSubmissionProxy();
+ const res = createRes();
+
+ await loaded.mod.default(
+ awaitingSubmissionRequest({ method: "POST" }),
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 405);
+ assert.strictEqual(res.state.jsonBody.error.code, "METHOD_NOT_ALLOWED");
+ assertNoProxyWork(loaded.calls);
+});
+
+for (const containerCase of [
+ { name: "missing container", query: {} },
+ { name: "empty container", query: { container: "" } },
+ { name: "null container", query: { container: null } },
+ { name: "non-string container", query: { container: ["user-container"] } },
+ { name: "malformed container", query: { container: "Invalid_Container" } }
+]) {
+ test(`getawaitingsubmissionfromblobproxy rejects ${containerCase.name} before proxy work`, async () => {
+ const loaded = loadAwaitingSubmissionProxy();
+ const res = createRes();
+
+ await loaded.mod.default(
+ awaitingSubmissionRequest({ query: containerCase.query }),
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assertNoProxyWork(loaded.calls);
+ });
+}
+
+test("getawaitingsubmissionfromblobproxy preserves signed path and response for owning user", async () => {
+ const loaded = loadAwaitingSubmissionProxy();
+ const req = awaitingSubmissionRequest();
+ const res = createRes();
+
+ await loaded.mod.default(req, res);
+
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.deepStrictEqual(loaded.calls.options, [[req, res]]);
+ assert.deepStrictEqual(loaded.calls.session, [[req, res, loaded.options]]);
+ assert.strictEqual(loaded.calls.token, 1);
+ assert.deepStrictEqual(loaded.calls.hash, [
+ "/api/file/getawaitingsubmissionfromblob?container=user-container"
+ ]);
+ assert.strictEqual(
+ loaded.calls.axios[0][0],
+ "http://example.com/api/file/getawaitingsubmissionfromblob?container=user-container&hash=abc"
+ );
+ assert.deepStrictEqual(
+ JSON.parse(JSON.stringify(res.state.jsonBody)),
+ loaded.payload
+ );
+});
+
+test("getawaitingsubmissionfromblobproxy dependency failure returns GET_AWAITING_SUBMISSION_PROXY_FAILED", async () => {
+ const loaded = loadAwaitingSubmissionProxy({
+ axios: {
+ get: async (...args) => {
+ loaded.calls.axios.push(args);
+ throw new Error("awaiting failed");
+ }
+ }
+ });
+ const res = createRes();
+
+ await loaded.mod.default(awaitingSubmissionRequest(), res);
assert.strictEqual(res.state.statusCode, 400);
assert.strictEqual(
res.state.jsonBody.error.code,
"GET_AWAITING_SUBMISSION_PROXY_FAILED"
);
+ assert.strictEqual(loaded.calls.token, 1);
+ assert.strictEqual(loaded.calls.hash.length, 1);
+ assert.strictEqual(loaded.calls.axios.length, 1);
+});
+
+const loadAppealCompletionProxy = ({ session, ...overrides } = {}) => {
+ const calls = {
+ options: [],
+ session: [],
+ token: 0,
+ hash: [],
+ headers: [],
+ axios: []
+ };
+ const options = { id: "appeal-completion-proxy-options" };
+ const payload = { status: "success" };
+ const resolvedSession =
+ typeof session === "undefined"
+ ? { user: { id: "owner-container" } }
+ : session;
+ const mod = loadModule(
+ "pages/api/file/createappealcompletemessageproxy_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;
+ },
+ getToken: async () => {
+ calls.token += 1;
+ return { access_token: "synthetic-token" };
+ },
+ azureHeaders: (token) => {
+ calls.headers.push(token);
+ return { headers: { Authorization: `Bearer ${token}` } };
+ },
+ hashAPIPath: (queryPath) => {
+ calls.hash.push(queryPath);
+ return "&hash=synthetic-hash";
+ },
+ consoleLogger: () => {},
+ process: { env: { API_ROOT: "http://example.com" } },
+ axios: {
+ get: async (...args) => {
+ calls.axios.push(args);
+ return { data: payload };
+ }
+ },
+ ...overrides
+ }
+ );
+
+ return { mod, calls, options, payload };
+};
+
+const appealCompletionProxyRequest = (overrides = {}) => ({
+ query: {
+ container: "owner-container",
+ tempcaseref: "TMP-CASE-1"
+ },
+ headers: { cookie: "next-auth.session-token=synthetic-session" },
+ ...overrides
+});
+
+const assertNoAppealCompletionProxyWork = (calls) => {
+ assert.strictEqual(calls.token, 0);
+ assert.strictEqual(calls.hash.length, 0);
+ assert.strictEqual(calls.headers.length, 0);
+ assert.strictEqual(calls.axios.length, 0);
+};
+
+for (const sessionCase of [
+ { name: "missing session", session: null },
+ { name: "session without user id", session: { user: {} } },
+ { name: "session with empty user id", session: { user: { id: "" } } },
+ {
+ name: "session with non-string user id",
+ session: { user: { id: 123 } }
+ },
+ {
+ name: "cross-container session",
+ session: { user: { id: "foreign-container" } }
+ }
+]) {
+ test(`createappealcompletemessageproxy rejects ${sessionCase.name} before token, signing or submission`, async () => {
+ const loaded = loadAppealCompletionProxy({
+ session: sessionCase.session
+ });
+ const res = createRes();
+
+ await loaded.mod.default.handler(appealCompletionProxyRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(res.state.jsonBody.error.code, "FORBIDDEN");
+ assertNoAppealCompletionProxyWork(loaded.calls);
+ });
+}
+
+for (const inputCase of [
+ {
+ name: "invalid container",
+ query: { container: "Invalid_Container", tempcaseref: "TMP-CASE-1" }
+ },
+ {
+ name: "missing temporary case reference",
+ query: { container: "owner-container" },
+ code: "MISSING_REQUIRED_QUERY"
+ },
+ {
+ name: "malformed temporary case reference",
+ query: { container: "owner-container", tempcaseref: "../foreign" }
+ },
+ {
+ name: "array temporary case reference",
+ query: { container: "owner-container", tempcaseref: ["TMP-CASE-1"] },
+ code: "MISSING_REQUIRED_QUERY"
+ }
+]) {
+ test(`createappealcompletemessageproxy rejects ${inputCase.name} before authentication or submission`, async () => {
+ const loaded = loadAppealCompletionProxy();
+ const res = createRes();
+
+ await loaded.mod.default.handler(
+ appealCompletionProxyRequest({ query: inputCase.query }),
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(
+ res.state.jsonBody.error.code,
+ inputCase.code || "INVALID_REQUEST"
+ );
+ assert.strictEqual(loaded.calls.options.length, 0);
+ assert.strictEqual(loaded.calls.session.length, 0);
+ assertNoAppealCompletionProxyWork(loaded.calls);
+ });
+}
+
+test("createappealcompletemessageproxy preserves owner submission and forwards the authenticated cookie", async () => {
+ const loaded = loadAppealCompletionProxy();
+ const req = appealCompletionProxyRequest();
+ const res = createRes();
+
+ await loaded.mod.default.handler(req, res);
+
+ const expectedPath =
+ "/api/file/createappealcompletemessage_api?container=owner-container&tempcaseref=TMP-CASE-1";
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.deepStrictEqual(loaded.calls.options, [[req, res]]);
+ assert.deepStrictEqual(loaded.calls.session, [[req, res, loaded.options]]);
+ assert.strictEqual(loaded.calls.token, 1);
+ assert.deepStrictEqual(loaded.calls.hash, [expectedPath]);
+ assert.deepStrictEqual(loaded.calls.headers, ["synthetic-token"]);
+ assert.strictEqual(loaded.calls.axios.length, 1);
+ assert.strictEqual(
+ loaded.calls.axios[0][0],
+ `http://example.com${expectedPath}&hash=synthetic-hash`
+ );
+ assert.deepStrictEqual(
+ JSON.parse(JSON.stringify(loaded.calls.axios[0][1])),
+ {
+ headers: {
+ Authorization: "Bearer synthetic-token",
+ cookie: "next-auth.session-token=synthetic-session"
+ }
+ }
+ );
+ assert.deepStrictEqual(
+ JSON.parse(JSON.stringify(res.state.jsonBody)),
+ loaded.payload
+ );
+});
+
+const loadAppealCompletionDirect = ({ session, ...overrides } = {}) => {
+ const calls = {
+ options: [],
+ session: [],
+ hash: [],
+ progress: [],
+ download: [],
+ createBlob: [],
+ caseBlob: [],
+ account: [],
+ queue: []
+ };
+ const options = { id: "appeal-completion-direct-options" };
+ const resolvedSession =
+ typeof session === "undefined"
+ ? { user: { id: "owner-container" } }
+ : session;
+ const progress = {
+ pinswg_siteaddressline1: "Line 1",
+ pinswg_siteaddressline2: "",
+ pinswg_siteaddresstown: "Town",
+ pinswg_siteaddresscounty: "County",
+ pinswg_siteaddresspostcode: "CF1 1AA",
+ pinswg_lpaapplicationreference: "LPA-1",
+ pinswg_developmentdescription: "Description",
+ pinswg_name: "draft-name"
+ };
+ const caseObject = {
+ "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 {};
+ },
+ 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 };
+};
+
+const appealCompletionDirectRequest = (overrides = {}) => ({
+ query: {
+ container: "owner-container",
+ tempcaseref: "TMP-CASE-1",
+ inv: "846040001",
+ hash: "expected"
+ },
+ ...overrides
+});
+
+const assertNoAppealCompletionEffects = (calls) => {
+ assert.strictEqual(calls.progress.length, 0);
+ assert.strictEqual(calls.download.length, 0);
+ assert.strictEqual(calls.createBlob.length, 0);
+ assert.strictEqual(calls.caseBlob.length, 0);
+ assert.strictEqual(calls.account.length, 0);
+ assert.strictEqual(calls.queue.length, 0);
+};
+
+for (const sessionCase of [
+ { name: "missing session", session: null },
+ { name: "session without user id", session: { user: {} } },
+ { name: "session with empty user id", session: { user: { id: "" } } },
+ {
+ name: "session with non-string user id",
+ session: { user: { id: 123 } }
+ },
+ {
+ name: "cross-container session",
+ session: { user: { id: "foreign-container" } }
+ }
+]) {
+ test(`createappealcompletemessage_api blocks direct bypass with ${sessionCase.name} before HMAC or side effects`, async () => {
+ const loaded = loadAppealCompletionDirect({
+ session: sessionCase.session
+ });
+ const res = createRes();
+
+ await loaded.mod.default.handler(appealCompletionDirectRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(res.state.jsonBody.error.code, "FORBIDDEN");
+ assert.strictEqual(loaded.calls.hash.length, 0);
+ assertNoAppealCompletionEffects(loaded.calls);
+ });
+}
+
+for (const inputCase of [
+ {
+ name: "invalid container",
+ query: {
+ container: "Invalid_Container",
+ tempcaseref: "TMP-CASE-1",
+ hash: "expected"
+ }
+ },
+ {
+ name: "missing temporary case reference",
+ query: { container: "owner-container", hash: "expected" },
+ code: "MISSING_REQUIRED_QUERY"
+ },
+ {
+ name: "malformed temporary case reference",
+ query: {
+ container: "owner-container",
+ tempcaseref: "../foreign",
+ hash: "expected"
+ }
+ }
+]) {
+ test(`createappealcompletemessage_api rejects ${inputCase.name} before authentication or side effects`, async () => {
+ const loaded = loadAppealCompletionDirect();
+ const res = createRes();
+
+ await loaded.mod.default.handler(
+ appealCompletionDirectRequest({ query: inputCase.query }),
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(
+ res.state.jsonBody.error.code,
+ inputCase.code || "INVALID_REQUEST"
+ );
+ assert.strictEqual(loaded.calls.options.length, 0);
+ assert.strictEqual(loaded.calls.session.length, 0);
+ assert.strictEqual(loaded.calls.hash.length, 0);
+ assertNoAppealCompletionEffects(loaded.calls);
+ });
+}
+
+for (const hashCase of [
+ { name: "missing HMAC", hash: undefined },
+ { name: "invalid HMAC", hash: "wrong" }
+]) {
+ test(`createappealcompletemessage_api rejects ${hashCase.name} after owner authentication and before side effects`, async () => {
+ const loaded = loadAppealCompletionDirect();
+ const request = appealCompletionDirectRequest();
+ const res = createRes();
+
+ if (typeof hashCase.hash === "undefined") delete request.query.hash;
+ else request.query.hash = hashCase.hash;
+ await loaded.mod.default.handler(request, res);
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assertNoAppealCompletionEffects(loaded.calls);
+ });
+}
+
+for (const resourceCase of [
+ {
+ name: "another container",
+ query: {
+ container: "other-container",
+ tempcaseref: "TMP-CASE-1",
+ inv: "846040001",
+ hash: "expected"
+ },
+ session: { user: { id: "other-container" } }
+ },
+ {
+ name: "another draft folder",
+ query: {
+ container: "owner-container",
+ tempcaseref: "TMP-CASE-2",
+ inv: "846040001",
+ hash: "expected"
+ }
+ }
+]) {
+ test(`createappealcompletemessage_api rejects an HMAC issued for ${resourceCase.name}`, async () => {
+ const loaded = loadAppealCompletionDirect({
+ session: resourceCase.session,
+ hashAPIPath: (queryPath) => {
+ loaded.calls.hash.push(queryPath);
+ return queryPath ===
+ "/api/file/createappealcompletemessage_api?container=owner-container&tempcaseref=TMP-CASE-1"
+ ? "&hash=expected"
+ : "&hash=other";
+ }
+ });
+ const res = createRes();
+
+ await loaded.mod.default.handler(
+ appealCompletionDirectRequest({ query: resourceCase.query }),
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "INVALID_HASH");
+ assertNoAppealCompletionEffects(loaded.calls);
+ });
+}
+
+test("createappealcompletemessage_api rejects a capability for another operation", async () => {
+ const loaded = loadAppealCompletionDirect({
+ hashAPIPath: (queryPath) => {
+ loaded.calls.hash.push(queryPath);
+ return queryPath.startsWith("/api/file/deleteblob?")
+ ? "&hash=expected"
+ : "&hash=other";
+ }
+ });
+ const res = createRes();
+
+ await loaded.mod.default.handler(appealCompletionDirectRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "INVALID_HASH");
+ assertNoAppealCompletionEffects(loaded.calls);
+});
+
+test("createappealcompletemessage_api preserves owner payloads and downstream completion calls", async () => {
+ const loaded = loadAppealCompletionDirect();
+ const req = appealCompletionDirectRequest();
+ const res = createRes();
+
+ await loaded.mod.default.handler(req, res);
+
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.deepStrictEqual(loaded.calls.options, [[req, res]]);
+ assert.deepStrictEqual(loaded.calls.session, [[req, res, loaded.options]]);
+ assert.deepStrictEqual(loaded.calls.progress, [
+ ["owner-container", "TMP-CASE-1"]
+ ]);
+ 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"]
+ ]);
+ const savedProgress = JSON.parse(loaded.calls.createBlob[0][0]);
+ assert.strictEqual(savedProgress.appealComplete, "TMP-CASE-1");
+ assert.strictEqual(Object.hasOwn(savedProgress, "pinswg_name"), false);
+ assert.deepStrictEqual(loaded.calls.createBlob[0].slice(1), [
+ "owner-container",
+ "TMP-CASE-1"
+ ]);
+ assert.strictEqual(loaded.calls.caseBlob.length, 1);
+ assert.deepStrictEqual(JSON.parse(JSON.stringify(loaded.calls.account)), [
+ [
+ "00000000-0000-0000-0000-000000000001",
+ { pinswg_typeofinvolvement: 846040001 }
+ ]
+ ]);
+ assert.deepStrictEqual(loaded.calls.queue, [
+ ["owner-container", "TMP-CASE-1"]
+ ]);
+ assert.deepStrictEqual(JSON.parse(JSON.stringify(res.state.jsonBody)), {
+ status: "success"
+ });
});
test("createappealcompletemessageproxy dependency failure returns CREATE_APPEAL_COMPLETE_MESSAGE_PROXY_FAILED", async () => {
@@ -666,6 +3947,8 @@ test("createappealcompletemessageproxy dependency failure returns CREATE_APPEAL_
{
nextConnect: createNextConnectMock(),
middleware: () => {},
+ getServerSession: async () => ({ user: { id: "container-1" } }),
+ authOptions: () => ({}),
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
getToken: async () => ({ access_token: "tok" }),
@@ -682,7 +3965,8 @@ test("createappealcompletemessageproxy dependency failure returns CREATE_APPEAL_
);
const req = {
- query: { container: "c1", tempcaseref: "TMP1" }
+ query: { container: "container-1", tempcaseref: "TMP1" },
+ headers: { cookie: "next-auth.session-token=synthetic" }
};
const res = createRes();
await mod.default.handler(req, res);
@@ -700,6 +3984,8 @@ test("createappealcompletemessage_api accepts encoded hash variant and returns s
{
nextConnect: createNextConnectMock(),
middleware: () => {},
+ getServerSession: async () => ({ user: { id: "container-1" } }),
+ authOptions: () => ({}),
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
hashAPIPath: (queryPath) =>
@@ -729,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 === "" }
}
@@ -737,7 +4023,7 @@ test("createappealcompletemessage_api accepts encoded hash variant and returns s
const req = {
query: {
- container: "cont/1",
+ container: "container-1",
tempcaseref: "TMP/1",
inv: "846040001",
hash: "expected"
@@ -758,6 +4044,8 @@ test("createappealcompletemessage_api dependency failure returns CREATE_APPEAL_C
{
nextConnect: createNextConnectMock(),
middleware: () => {},
+ getServerSession: async () => ({ user: { id: "owner-container" } }),
+ authOptions: () => ({}),
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
hashAPIPath: () => "&hash=expected",
@@ -771,7 +4059,7 @@ test("createappealcompletemessage_api dependency failure returns CREATE_APPEAL_C
const req = {
query: {
- container: "c1",
+ container: "owner-container",
tempcaseref: "TMP1",
hash: "expected"
}
@@ -820,6 +4108,7 @@ test("createrepinvolvement dependency failure returns CREATE_REP_INVOLVEMENT_FAI
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
getToken: async () => ({ access_token: "tok" }),
+ getPersonalAccount: async () => ({}),
hashAPIPath: () => "?hash=abc",
consoleLogger: () => {},
process: {
@@ -1125,6 +4414,8 @@ test("upload handler success returns data payload with 200", async () => {
const mod = loadModule("pages/api/file/upload.js", {
nextConnect: createNextConnectMock(),
middleware: () => {},
+ getServerSession: async () => ({ user: { id: "c1" } }),
+ authOptions: () => ({}),
hashAPIPath: () => "?hash=expected",
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
@@ -1223,10 +4514,182 @@ test("downloadblob handler success sets attachment header and returns body", asy
assert.strictEqual(res.state.sentBody.toString(), "file-content");
});
+const loadDownloadBlobCapability = (overrides = {}) => {
+ const calls = { hash: [], download: [] };
+ const mod = loadModule("pages/api/file/downloadblob.js", {
+ nextConnect: createNextConnectMock(),
+ middleware: () => {},
+ hashAPIPath: (queryPath) => {
+ calls.hash.push(queryPath);
+ return queryPath ===
+ "/api/file/downloadblob?container=selected-container&casefolderID=CASE%2F1&blobname=document.pdf"
+ ? "&hash=valid-capability"
+ : "&hash=other-capability";
+ },
+ respondError: respondErrorMock,
+ downloadFile: async (...args) => {
+ calls.download.push(args);
+ return Buffer.from("private-draft-content");
+ },
+ ...overrides
+ });
+
+ return { mod, calls };
+};
+
+const downloadBlobCapabilityRequest = (overrides = {}) => ({
+ query: {
+ container: "selected-container",
+ casefolderID: "CASE/1",
+ blobname: "document.pdf",
+ hash: "valid-capability"
+ },
+ ...overrides
+});
+
+test("downloadblob preserves anonymous access with a valid exact-resource capability", async () => {
+ const loaded = loadDownloadBlobCapability();
+ const res = createRes();
+
+ await loaded.mod.default.handler(downloadBlobCapabilityRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.deepStrictEqual(loaded.calls.download, [
+ ["selected-container", "CASE/1/files/document.pdf"]
+ ]);
+ assert.strictEqual(
+ res.state.headers["content-disposition"],
+ "attachment; filename=document.pdf"
+ );
+ assert.strictEqual(res.state.sentBody.toString(), "private-draft-content");
+});
+
+test("downloadblob rejects a missing capability before Azure download", async () => {
+ const loaded = loadDownloadBlobCapability();
+ const res = createRes();
+
+ await loaded.mod.default.handler(
+ downloadBlobCapabilityRequest({
+ query: {
+ container: "selected-container",
+ casefolderID: "CASE/1",
+ blobname: "document.pdf"
+ }
+ }),
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "MISSING_REQUIRED_QUERY");
+ assert.strictEqual(loaded.calls.hash.length, 0);
+ assert.strictEqual(loaded.calls.download.length, 0);
+});
+
+test("downloadblob rejects an invalid capability before Azure download", async () => {
+ const loaded = loadDownloadBlobCapability();
+ const res = createRes();
+
+ await loaded.mod.default.handler(
+ downloadBlobCapabilityRequest({
+ query: {
+ container: "selected-container",
+ casefolderID: "CASE/1",
+ blobname: "document.pdf",
+ hash: "invalid-capability"
+ }
+ }),
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "INVALID_HASH");
+ assert.strictEqual(loaded.calls.download.length, 0);
+});
+
+for (const capabilityCase of [
+ {
+ name: "different blob",
+ query: {
+ container: "selected-container",
+ casefolderID: "CASE/1",
+ blobname: "other-document.pdf",
+ hash: "valid-capability"
+ }
+ },
+ {
+ name: "different folder",
+ query: {
+ container: "selected-container",
+ casefolderID: "CASE/2",
+ blobname: "document.pdf",
+ hash: "valid-capability"
+ }
+ },
+ {
+ name: "different container",
+ query: {
+ container: "other-container",
+ casefolderID: "CASE/1",
+ blobname: "document.pdf",
+ hash: "valid-capability"
+ }
+ }
+]) {
+ test(`downloadblob rejects a capability issued for a ${capabilityCase.name}`, async () => {
+ const loaded = loadDownloadBlobCapability();
+ const res = createRes();
+
+ await loaded.mod.default.handler(
+ downloadBlobCapabilityRequest({ query: capabilityCase.query }),
+ res
+ );
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "INVALID_HASH");
+ assert.strictEqual(loaded.calls.download.length, 0);
+ });
+}
+
+test("downloadblob rejects a delete-operation capability before Azure download", async () => {
+ const loaded = loadDownloadBlobCapability({
+ hashAPIPath: (queryPath) => {
+ loaded.calls.hash.push(queryPath);
+ return queryPath.startsWith("/api/file/deleteblob?")
+ ? "&hash=valid-capability"
+ : "&hash=other-capability";
+ }
+ });
+ const res = createRes();
+
+ await loaded.mod.default.handler(downloadBlobCapabilityRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "INVALID_HASH");
+ assert.strictEqual(loaded.calls.download.length, 0);
+});
+
+test("downloadblob preserves dependency failure contract for a valid capability", async () => {
+ const loaded = loadDownloadBlobCapability({
+ downloadFile: async (...args) => {
+ loaded.calls.download.push(args);
+ throw new Error("download failed");
+ }
+ });
+ const res = createRes();
+
+ await loaded.mod.default.handler(downloadBlobCapabilityRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "DOWNLOAD_BLOB_FAILED");
+ assert.strictEqual(loaded.calls.download.length, 1);
+});
+
test("upload handler dependency failure returns UPLOAD_FAILED", async () => {
const mod = loadModule("pages/api/file/upload.js", {
nextConnect: createNextConnectMock(),
middleware: () => {},
+ getServerSession: async () => ({ user: { id: "c1" } }),
+ authOptions: () => ({}),
hashAPIPath: () => "?hash=expected",
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
@@ -1442,77 +4905,823 @@ test("generateappealpdfcopy catch path returns APPEAL_PDF_COPY_GENERATION_FAILED
);
});
-test("generatepdf catch path returns GENERATE_PDF_FAILED", async () => {
+const PDF_OWNER_CONTAINER = "owner-container";
+const PDF_CASE_FOLDER = "CASE-1";
+
+const loadGeneratePdf = (overrides = {}) => {
const { Readable } = require("stream");
+ const calls = {
+ session: [],
+ options: [],
+ hash: [],
+ render: [],
+ create: []
+ };
+ const options = { id: "generate-pdf-options" };
const mod = loadModule("pages/api/file/generatepdf.js", {
Buffer,
respondError: respondErrorMock,
respondSuccess: respondSuccessMock,
- hashAPIPath: () => "&hash=expected",
+ authOptions: (req, res) => {
+ calls.options.push([req, res]);
+ return options;
+ },
+ getServerSession: async (...args) => {
+ calls.session.push(args);
+ return { user: { id: PDF_OWNER_CONTAINER } };
+ },
+ hashAPIPath: (queryPath) => {
+ calls.hash.push(queryPath);
+ return queryPath.includes("?")
+ ? "&hash=expected"
+ : "?hash=expected";
+ },
consoleLogger: () => {},
ReactPDF: {
- renderToStream: async () => Readable.from(["pdf"])
+ renderToStream: async (...args) => {
+ calls.render.push(args);
+ return Readable.from(["pdf"]);
+ }
},
- createRepPDFBlob: async () => {
- throw new Error("pdf write failed");
+ createRepPDFBlob: async (...args) => {
+ calls.create.push(args);
+ return { id: "representation-pdf" };
},
- other_pdf: () => ({ type: "other" })
+ other_pdf: () => ({ type: "other" }),
+ ...overrides
});
- const req = {
+ return { mod, calls, options };
+};
+
+const generatePdfRequest = (overrides = {}) => ({
+ method: "POST",
+ query: { hash: "expected" },
+ body: {
+ representationType: "Other",
+ repfile_name: "rep-file",
+ containerID: PDF_OWNER_CONTAINER,
+ caseRef: PDF_CASE_FOLDER
+ },
+ ...overrides
+});
+
+const loadGenerateAppealPdf = (overrides = {}) => {
+ const { Readable } = require("stream");
+ const calls = {
+ session: [],
+ options: [],
+ hash: [],
+ temp: [],
+ progress: [],
+ download: [],
+ pickLists: [],
+ render: [],
+ create: []
+ };
+ const options = { id: "generate-appeal-pdf-options" };
+ const mod = loadModule("pages/api/file/generateappealpdf.js", {
+ Buffer,
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock,
+ authOptions: (req, res) => {
+ calls.options.push([req, res]);
+ return options;
+ },
+ getServerSession: async (...args) => {
+ calls.session.push(args);
+ return { user: { id: PDF_OWNER_CONTAINER } };
+ },
+ hashAPIPath: (queryPath) => {
+ calls.hash.push(queryPath);
+ return "&hash=expected";
+ },
+ getTempCaseBlob: async (...args) => {
+ calls.temp.push(args);
+ return { ticketnumber: PDF_CASE_FOLDER };
+ },
+ getProgressBlobs: async (...args) => {
+ calls.progress.push(args);
+ return { path: `${PDF_CASE_FOLDER}/progress.json` };
+ },
+ downloadProgressFile: async (...args) => {
+ calls.download.push(args);
+ return {
+ pinswg_name: PDF_CASE_FOLDER,
+ pinswg_appealcasetype: "846040000"
+ };
+ },
+ getPickLists: async (...args) => {
+ calls.pickLists.push(args);
+ return {};
+ },
+ planningappeals78_pdf: () => ({ type: "planning" }),
+ other_pdf: () => ({ type: "other" }),
+ ReactPDF: {
+ renderToStream: async (...args) => {
+ calls.render.push(args);
+ return Readable.from(["pdf"]);
+ }
+ },
+ createAppealPDFBlob: async (...args) => {
+ calls.create.push(args);
+ return { id: "appeal-pdf" };
+ },
+ ...overrides
+ });
+
+ return { mod, calls, options };
+};
+
+const generateAppealPdfRequest = (overrides = {}) => ({
+ method: "POST",
+ query: { hash: "expected", appealType: "846040000" },
+ body: {
+ containerID: PDF_OWNER_CONTAINER,
+ casefolderID: PDF_CASE_FOLDER,
+ filesList: []
+ },
+ ...overrides
+});
+
+const assertNoGeneratePdfWork = (calls) => {
+ assert.strictEqual(calls.render.length, 0);
+ assert.strictEqual(calls.create.length, 0);
+};
+
+const assertNoGenerateAppealPdfWork = (calls) => {
+ assert.strictEqual(calls.temp.length, 0);
+ assert.strictEqual(calls.progress.length, 0);
+ assert.strictEqual(calls.download.length, 0);
+ assert.strictEqual(calls.pickLists.length, 0);
+ assert.strictEqual(calls.render.length, 0);
+ assert.strictEqual(calls.create.length, 0);
+};
+
+for (const endpoint of [
+ {
+ name: "generatepdf",
+ load: loadGeneratePdf,
+ request: generatePdfRequest,
+ assertNoWork: assertNoGeneratePdfWork
+ },
+ {
+ name: "generateappealpdf",
+ load: loadGenerateAppealPdf,
+ request: generateAppealPdfRequest,
+ assertNoWork: assertNoGenerateAppealPdfWork
+ }
+]) {
+ for (const sessionCase of [
+ { name: "missing session", session: null },
+ { name: "missing session user id", session: { user: {} } },
+ { name: "empty session user id", session: { user: { id: "" } } },
+ {
+ name: "non-string session user id",
+ session: { user: { id: 123 } }
+ }
+ ]) {
+ test(`${endpoint.name} rejects ${sessionCase.name} before privileged work`, async () => {
+ const loaded = endpoint.load({
+ getServerSession: async () => sessionCase.session
+ });
+ const res = createRes();
+
+ await loaded.mod.default(endpoint.request(), res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(res.state.jsonBody.error.code, "FORBIDDEN");
+ endpoint.assertNoWork(loaded.calls);
+ });
+ }
+
+ test(`${endpoint.name} rejects another user's container before privileged work`, async () => {
+ const loaded = endpoint.load({
+ getServerSession: async () => ({
+ user: { id: "different-container" }
+ })
+ });
+ const res = createRes();
+
+ await loaded.mod.default(endpoint.request(), res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(res.state.jsonBody.error.code, "FORBIDDEN");
+ endpoint.assertNoWork(loaded.calls);
+ });
+
+ test(`${endpoint.name} ignores a client-provided user identity`, async () => {
+ const loaded = endpoint.load({
+ getServerSession: async () => ({
+ user: { id: "different-container" }
+ })
+ });
+ const req = endpoint.request();
+ req.body.userID = PDF_OWNER_CONTAINER;
+ const res = createRes();
+
+ await loaded.mod.default(req, res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ endpoint.assertNoWork(loaded.calls);
+ });
+
+ test(`${endpoint.name} passes req, res and request-scoped auth options to getServerSession`, async () => {
+ const loaded = endpoint.load();
+ const req = endpoint.request();
+ const res = createRes();
+
+ await loaded.mod.default(req, res);
+
+ assert.deepStrictEqual(loaded.calls.options, [[req, res]]);
+ assert.deepStrictEqual(loaded.calls.session, [
+ [req, res, loaded.options]
+ ]);
+ });
+}
+
+for (const containerCase of [
+ { name: "missing", value: undefined },
+ { name: "invalid", value: "Invalid_Container" },
+ { name: "ambiguous", value: [PDF_OWNER_CONTAINER] }
+]) {
+ test(`generatepdf rejects ${containerCase.name} container before privileged work`, async () => {
+ const loaded = loadGeneratePdf();
+ const req = generatePdfRequest();
+ if (typeof containerCase.value === "undefined") {
+ delete req.body.containerID;
+ } else {
+ req.body.containerID = containerCase.value;
+ }
+ const res = createRes();
+
+ await loaded.mod.default(req, res);
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assertNoGeneratePdfWork(loaded.calls);
+ });
+
+ test(`generateappealpdf rejects ${containerCase.name} container before privileged work`, async () => {
+ const loaded = loadGenerateAppealPdf();
+ const req = generateAppealPdfRequest();
+ if (typeof containerCase.value === "undefined") {
+ delete req.body.containerID;
+ } else {
+ req.body.containerID = containerCase.value;
+ }
+ const res = createRes();
+
+ await loaded.mod.default(req, res);
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assertNoGenerateAppealPdfWork(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 () => {
+ for (const value of [undefined, "../CASE-1", [PDF_CASE_FOLDER]]) {
+ const loaded = loadGenerateAppealPdf();
+ const req = generateAppealPdfRequest();
+ if (typeof value === "undefined") {
+ delete req.body.casefolderID;
+ } else {
+ req.body.casefolderID = value;
+ }
+ const res = createRes();
+ await loaded.mod.default(req, res);
+ assert.strictEqual(res.state.statusCode, 400);
+ assertNoGenerateAppealPdfWork(loaded.calls);
+ }
+});
+
+for (const endpoint of [
+ {
+ name: "generatepdf",
+ load: loadGeneratePdf,
+ request: generatePdfRequest,
+ assertNoWork: assertNoGeneratePdfWork
+ },
+ {
+ name: "generateappealpdf",
+ load: loadGenerateAppealPdf,
+ request: generateAppealPdfRequest,
+ assertNoWork: assertNoGenerateAppealPdfWork
+ }
+]) {
+ test(`${endpoint.name} rejects a query/body container ambiguity`, async () => {
+ const loaded = endpoint.load();
+ const req = endpoint.request();
+ req.query.containerID = PDF_OWNER_CONTAINER;
+ const res = createRes();
+ await loaded.mod.default(req, res);
+ assert.strictEqual(res.state.statusCode, 400);
+ endpoint.assertNoWork(loaded.calls);
+ });
+
+ test(`${endpoint.name} rejects missing HMAC before privileged work`, async () => {
+ const loaded = endpoint.load();
+ const req = endpoint.request();
+ delete req.query.hash;
+ const res = createRes();
+ await loaded.mod.default(req, res);
+ assert.strictEqual(res.state.statusCode, 400);
+ endpoint.assertNoWork(loaded.calls);
+ });
+
+ test(`${endpoint.name} rejects invalid HMAC before privileged work`, async () => {
+ const loaded = endpoint.load();
+ const req = endpoint.request();
+ req.query.hash = "wrong";
+ const res = createRes();
+ await loaded.mod.default(req, res);
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "INVALID_HASH");
+ endpoint.assertNoWork(loaded.calls);
+ });
+
+ test(`${endpoint.name} rejects a valid HMAC for an unauthorised container`, async () => {
+ const loaded = endpoint.load({
+ getServerSession: async () => ({
+ user: { id: "different-container" }
+ })
+ });
+ const res = createRes();
+ await loaded.mod.default(endpoint.request(), res);
+ assert.strictEqual(res.state.statusCode, 403);
+ endpoint.assertNoWork(loaded.calls);
+ });
+}
+
+test("generatepdf owner success writes the PDF to the authorised container", async () => {
+ const loaded = loadGeneratePdf();
+ const res = createRes();
+
+ await loaded.mod.default(generatePdfRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.strictEqual(loaded.calls.render.length, 1);
+ 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(loaded.calls.create[0][3], "rep-file");
+ 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();
+
+ await loaded.mod.default(generateAppealPdfRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.strictEqual(loaded.calls.temp[0][0], PDF_OWNER_CONTAINER);
+ assert.strictEqual(loaded.calls.progress[0][0], PDF_OWNER_CONTAINER);
+ assert.strictEqual(loaded.calls.download[0][0], PDF_OWNER_CONTAINER);
+ 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 catch path returns GENERATE_PDF_FAILED for an authorised owner", async () => {
+ const loaded = loadGeneratePdf({
+ createRepPDFBlob: async (...args) => {
+ loaded.calls.create.push(args);
+ throw new Error("pdf write failed");
+ }
+ });
+ const req = generatePdfRequest({
query: { hash: "expected", download: "true" },
body: {
representationType: "Other",
repfile_name: "rep-file",
- containerID: "c1",
- casefolderID: "f1",
- caseRef: "CAS-1"
+ containerID: PDF_OWNER_CONTAINER,
+ caseRef: PDF_CASE_FOLDER
}
- };
+ });
const res = createRes();
- await mod.default(req, res);
+ await loaded.mod.default(req, res);
assert.strictEqual(res.state.statusCode, 400);
assert.strictEqual(res.state.jsonBody.error.code, "GENERATE_PDF_FAILED");
+ assert.strictEqual(loaded.calls.render.length, 1);
+ assert.strictEqual(loaded.calls.create.length, 1);
});
-test("generateappealpdf catch path returns GENERATE_APPEAL_PDF_FAILED", async () => {
- const mod = loadModule("pages/api/file/generateappealpdf.js", {
- respondError: respondErrorMock,
- respondSuccess: respondSuccessMock,
- hashAPIPath: () => "&hash=expected",
- getTempCaseBlob: async () => ({ ticketnumber: "CAS-1" }),
- getProgressBlobs: async () => ({ path: "CAS-1/progress.json" }),
+test("generateappealpdf catch path returns GENERATE_APPEAL_PDF_FAILED for an authorised owner", async () => {
+ const loaded = loadGenerateAppealPdf({
downloadProgressFile: async () => {
+ loaded.calls.download.push([
+ PDF_OWNER_CONTAINER,
+ `${PDF_CASE_FOLDER}/progress.json`,
+ PDF_CASE_FOLDER
+ ]);
throw new Error("progress failed");
- },
- getPickLists: async () => ({}),
- planningappeals78_pdf: () => ({ type: "planning" }),
- other_pdf: () => ({ type: "other" }),
- ReactPDF: {
- renderToStream: async () => {
- throw new Error("render failed");
- }
}
});
- const req = {
- query: { hash: "expected", appealType: "846040000" },
- body: {
- containerID: "c1",
- casefolderID: "f1",
- caseRef: "CAS-1",
- filesList: []
- }
- };
const res = createRes();
- await mod.default(req, res);
+ await loaded.mod.default(generateAppealPdfRequest(), res);
assert.strictEqual(res.state.statusCode, 400);
assert.strictEqual(
res.state.jsonBody.error.code,
"GENERATE_APPEAL_PDF_FAILED"
);
+ assert.strictEqual(loaded.calls.temp.length, 1);
+ assert.strictEqual(loaded.calls.progress.length, 1);
+ assert.strictEqual(loaded.calls.download.length, 1);
+ assert.strictEqual(loaded.calls.render.length, 0);
+ assert.strictEqual(loaded.calls.create.length, 0);
+});
+
+const CASE_OWNER_CONTAINER = "case-owner-container";
+const GENERATED_CASE_REFERENCE = "TMP-CASE-04E";
+
+const loadCreateCase = (overrides = {}) => {
+ const calls = {
+ session: [],
+ options: [],
+ token: 0,
+ reference: 0,
+ caseBlob: [],
+ appealBlob: []
+ };
+ const options = { id: "create-case-options" };
+ const mod = loadModule("pages/api/file/createcase_api.js", {
+ respondError: respondErrorMock,
+ respondSuccess: respondSuccessMock,
+ authOptions: (req, res) => {
+ calls.options.push([req, res]);
+ return options;
+ },
+ getServerSession: async (...args) => {
+ calls.session.push(args);
+ return { user: { id: CASE_OWNER_CONTAINER } };
+ },
+ getToken: async () => {
+ calls.token += 1;
+ return { access_token: "synthetic-token" };
+ },
+ getTempCaseRef: () => {
+ calls.reference += 1;
+ return GENERATED_CASE_REFERENCE;
+ },
+ uuidv4: () => "00000000-0000-4000-8000-00000000004e",
+ getCaseBlob: async (...args) => {
+ calls.caseBlob.push(args);
+ return `${GENERATED_CASE_REFERENCE}/${GENERATED_CASE_REFERENCE}_case.json`;
+ },
+ createBlob: async (...args) => {
+ calls.appealBlob.push(args);
+ return GENERATED_CASE_REFERENCE;
+ },
+ _: { isEmpty: (value) => !value || Object.keys(value).length === 0 },
+ ...overrides
+ });
+
+ return { mod, calls, options };
+};
+
+const createCaseRequest = (overrides = {}) => ({
+ method: "POST",
+ query: {
+ contactid: "00000000-0000-4000-8000-000000000001",
+ appealTypeId: "846040000",
+ containername: CASE_OWNER_CONTAINER,
+ lpaID: "00000000-0000-4000-8000-000000000002"
+ },
+ body: {
+ pinswg_lpaname: "Synthetic LPA",
+ createdon: "2026-11-04T00:00:00.000Z"
+ },
+ ...overrides
+});
+
+const assertNoCreateCaseSideEffects = (calls) => {
+ assert.strictEqual(calls.token, 0);
+ assert.strictEqual(calls.reference, 0);
+ assert.strictEqual(calls.caseBlob.length, 0);
+ assert.strictEqual(calls.appealBlob.length, 0);
+};
+
+for (const sessionCase of [
+ { name: "missing session", session: null },
+ { name: "missing session user ID", session: { user: {} } },
+ { name: "empty session user ID", session: { user: { id: "" } } },
+ {
+ name: "non-string session user ID",
+ session: { user: { id: 123 } }
+ }
+]) {
+ test(`createcase_api rejects ${sessionCase.name} before private draft creation`, async () => {
+ const loaded = loadCreateCase({
+ getServerSession: async () => sessionCase.session
+ });
+ const res = createRes();
+
+ await loaded.mod.default(createCaseRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(res.state.jsonBody.error.code, "FORBIDDEN");
+ assertNoCreateCaseSideEffects(loaded.calls);
+ });
+}
+
+test("createcase_api rejects a foreign destination container before private draft creation", async () => {
+ const loaded = loadCreateCase({
+ getServerSession: async () => ({ user: { id: "different-container" } })
+ });
+ const res = createRes();
+
+ await loaded.mod.default(createCaseRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assert.strictEqual(res.state.jsonBody.error.code, "FORBIDDEN");
+ assertNoCreateCaseSideEffects(loaded.calls);
+});
+
+test("createcase_api does not trust a caller-supplied identity", async () => {
+ const loaded = loadCreateCase({
+ getServerSession: async () => ({ user: { id: "different-container" } })
+ });
+ const req = createCaseRequest();
+ req.body.userID = CASE_OWNER_CONTAINER;
+ const res = createRes();
+
+ await loaded.mod.default(req, res);
+
+ assert.strictEqual(res.state.statusCode, 403);
+ assertNoCreateCaseSideEffects(loaded.calls);
+});
+
+test("createcase_api passes req, res and request-scoped options to getServerSession", async () => {
+ const loaded = loadCreateCase();
+ const req = createCaseRequest();
+ const res = createRes();
+
+ await loaded.mod.default(req, res);
+
+ assert.deepStrictEqual(loaded.calls.options, [[req, res]]);
+ assert.deepStrictEqual(loaded.calls.session, [[req, res, loaded.options]]);
+});
+
+for (const containerCase of [
+ { name: "missing", value: undefined },
+ { name: "invalid", value: "Invalid_Container" },
+ { name: "array-valued", value: [CASE_OWNER_CONTAINER] }
+]) {
+ test(`createcase_api rejects a ${containerCase.name} container before private draft creation`, async () => {
+ const loaded = loadCreateCase();
+ const req = createCaseRequest();
+ if (typeof containerCase.value === "undefined") {
+ delete req.query.containername;
+ } else {
+ req.query.containername = containerCase.value;
+ }
+ const res = createRes();
+
+ await loaded.mod.default(req, res);
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assertNoCreateCaseSideEffects(loaded.calls);
+ });
+}
+
+test("createcase_api rejects malformed JSON before private draft creation", async () => {
+ const loaded = loadCreateCase();
+ const res = createRes();
+
+ await loaded.mod.default(createCaseRequest({ body: "{" }), res);
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "INVALID_REQUEST");
+ assertNoCreateCaseSideEffects(loaded.calls);
+});
+
+test("createcase_api rejects ambiguous destination identifiers before private draft creation", async () => {
+ for (const request of [
+ createCaseRequest({
+ query: {
+ ...createCaseRequest().query,
+ containerID: CASE_OWNER_CONTAINER
+ }
+ }),
+ createCaseRequest({
+ body: {
+ ...createCaseRequest().body,
+ containername: CASE_OWNER_CONTAINER
+ }
+ })
+ ]) {
+ const loaded = loadCreateCase();
+ const res = createRes();
+
+ await loaded.mod.default(request, res);
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "INVALID_REQUEST");
+ assertNoCreateCaseSideEffects(loaded.calls);
+ }
+});
+
+test("createcase_api rejects an invalid generated folder before token acquisition and Blob writes", async () => {
+ const loaded = loadCreateCase({ getTempCaseRef: () => "../foreign-case" });
+ const res = createRes();
+
+ await loaded.mod.default(createCaseRequest(), res);
+
+ assert.strictEqual(res.state.statusCode, 400);
+ assert.strictEqual(res.state.jsonBody.error.code, "INVALID_REQUEST");
+ assert.strictEqual(loaded.calls.token, 0);
+ assert.strictEqual(loaded.calls.caseBlob.length, 0);
+ assert.strictEqual(loaded.calls.appealBlob.length, 0);
+});
+
+test("createcase_api creates both draft JSON blobs in the authenticated owner's container", async () => {
+ const loaded = loadCreateCase();
+ const req = createCaseRequest();
+ const res = createRes();
+
+ await loaded.mod.default(req, res);
+
+ assert.strictEqual(res.state.statusCode, 200);
+ assert.strictEqual(loaded.calls.token, 1);
+ assert.strictEqual(loaded.calls.reference, 1);
+ 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.appealBlob[0][1], CASE_OWNER_CONTAINER);
+ assert.deepStrictEqual(
+ JSON.parse(JSON.stringify(loaded.calls.caseBlob[0][2])),
+ JSON.parse(JSON.stringify(res.state.jsonBody))
+ );
+ 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"
+ });
+ assert.strictEqual(
+ res.state.jsonBody.ticketnumber,
+ GENERATED_CASE_REFERENCE
+ );
+ assert.strictEqual(res.state.jsonBody.title, GENERATED_CASE_REFERENCE);
+ assert.strictEqual(
+ res.state.jsonBody.incidentid,
+ "00000000-0000-4000-8000-00000000004e"
+ );
+});
+
+test("createcase_api preserves the existing propagated token dependency failure for an authorised owner", async () => {
+ const loaded = loadCreateCase({
+ getToken: async () => {
+ loaded.calls.token += 1;
+ throw new Error("token failure");
+ }
+ });
+ const res = createRes();
+
+ await assert.rejects(
+ loaded.mod.default(createCaseRequest(), res),
+ /token failure/
+ );
+
+ assert.strictEqual(loaded.calls.token, 1);
+ assert.strictEqual(loaded.calls.caseBlob.length, 0);
+ 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 () => {
diff --git a/tests/phase22/api-grouping-facade-myportal-reads.test.cjs b/tests/phase22/api-grouping-facade-myportal-reads.test.cjs
index a9464293..0f334d5b 100644
--- a/tests/phase22/api-grouping-facade-myportal-reads.test.cjs
+++ b/tests/phase22/api-grouping-facade-myportal-reads.test.cjs
@@ -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\)/
diff --git a/tests/phase22/auth-redirect-safety.test.cjs b/tests/phase22/auth-redirect-safety.test.cjs
index 95c92c4f..4416c311 100644
--- a/tests/phase22/auth-redirect-safety.test.cjs
+++ b/tests/phase22/auth-redirect-safety.test.cjs
@@ -19,6 +19,7 @@ const loadAuthInternals = ({ adapterFactory = () => ({}) } = {}) => {
let source = fs.readFileSync(filePath, "utf8");
source = source.replace(/import[\s\S]*?from\s+"[^"]+";\n?/g, "");
+ source = source.replace("export const authOptions", "const authOptions");
source = source.replace(
/export default NextAuthPEDW;\s*$/,
"module.exports = { appendParamsAndPathToNewUrl, resolveRequestLocale, authOptions, NextAuthPEDW };"
diff --git a/tests/phase22/breadcrumbs-route-map-structure.test.cjs b/tests/phase22/breadcrumbs-route-map-structure.test.cjs
index 4dfd31a3..f416dca4 100644
--- a/tests/phase22/breadcrumbs-route-map-structure.test.cjs
+++ b/tests/phase22/breadcrumbs-route-map-structure.test.cjs
@@ -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 () => {
diff --git a/tests/phase22/client-utils-behaviour.test.cjs b/tests/phase22/client-utils-behaviour.test.cjs
index 310c58fc..217957de 100644
--- a/tests/phase22/client-utils-behaviour.test.cjs
+++ b/tests/phase22/client-utils-behaviour.test.cjs
@@ -219,6 +219,83 @@ test("clients/fileRouteBuilder builds query with optional encoding and suffix he
);
});
+const loadUpdateLinks = () => {
+ const filePath = path.join(rootDir, "components", "utils", "index.js");
+ const source = fs.readFileSync(filePath, "utf8");
+
+ const start = source.indexOf("export const updateLinks =");
+ const end = source.indexOf("\nexport const whichRepType", start);
+
+ assert.ok(start >= 0, "updateLinks export not found");
+ assert.ok(end > start, "updateLinks boundary not found");
+
+ const implementation = source
+ .slice(start, end)
+ .replace("export const updateLinks =", "const updateLinks =");
+
+ const context = { module: { exports: {} } };
+
+ vm.runInNewContext(
+ `${implementation}\nmodule.exports = updateLinks;`,
+ context,
+ { filename: filePath }
+ );
+
+ return context.module.exports;
+};
+
+test("updateLinks removes Quill video iframe", () => {
+ const updateLinks = loadUpdateLinks();
+
+ const input =
+ '
Before
After
';
+
+ assert.strictEqual(updateLinks(input), "
Before
After
");
+});
+
+test("updateLinks removes HTML video elements", () => {
+ const updateLinks = loadUpdateLinks();
+
+ const input =
+ '
Before
After
';
+
+ assert.strictEqual(updateLinks(input), "
Before
After
");
+});
+
+test("updateLinks converts plain URLs", () => {
+ const updateLinks = loadUpdateLinks();
+
+ assert.strictEqual(
+ updateLinks("
Visit https://example.com.
"),
+ '
Visit https://example.com.
'
+ );
+});
+
+test("updateLinks preserves existing anchors", () => {
+ const updateLinks = loadUpdateLinks();
+
+ const input = '
Existing link
';
+
+ assert.strictEqual(updateLinks(input), input);
+});
+
+test("updateLinks preserves standard rich-text formatting", () => {
+ const updateLinks = loadUpdateLinks();
+
+ const input = "
Bold and italic
";
+
+ assert.strictEqual(updateLinks(input), input);
+});
+
+test("updateLinks removes empty Quill paragraphs", () => {
+ const updateLinks = loadUpdateLinks();
+
+ assert.strictEqual(
+ updateLinks("
Content
"),
+ "
Content
"
+ );
+});
+
const run = async () => {
let passed = 0;
diff --git a/tests/phase22/email-provider-contract.test.cjs b/tests/phase22/email-provider-contract.test.cjs
new file mode 100644
index 00000000..b8d000b2
--- /dev/null
+++ b/tests/phase22/email-provider-contract.test.cjs
@@ -0,0 +1,113 @@
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const path = require("node:path");
+const test = require("node:test");
+const vm = require("node:vm");
+
+const root = path.resolve(__dirname, "../..");
+
+const source = fs.readFileSync(
+ path.join(root, "lib/auth/email-provider.js"),
+ "utf8"
+);
+
+const EmailProvider = vm.runInNewContext(
+ source.replace("export default EmailProvider;", "") + "\nEmailProvider;",
+ {}
+);
+
+const OriginalEmailProvider = require("next-auth/providers/email").default;
+
+const customSender = async () => {};
+
+const options = {
+ maxAge: 2 * 60 * 60,
+ sendVerificationRequest: customSender
+};
+
+const normalize = (provider) => {
+ const { options: userOptions, ...defaults } = provider;
+
+ return {
+ ...defaults,
+ ...userOptions
+ };
+};
+
+test("local provider preserves NextAuth email provider defaults", () => {
+ const original = OriginalEmailProvider(options);
+ const replacement = EmailProvider(options);
+
+ for (const property of ["id", "type", "name", "server", "from", "maxAge"]) {
+ assert.deepEqual(
+ JSON.parse(JSON.stringify(replacement[property])),
+ JSON.parse(JSON.stringify(original[property])),
+ `Mismatch in ${property}`
+ );
+ }
+});
+
+test("local provider preserves the user options contract", () => {
+ const provider = EmailProvider(options);
+
+ assert.equal(provider.options.maxAge, 7200);
+ assert.equal(provider.options.sendVerificationRequest, customSender);
+});
+
+test("normalized provider retains two-hour token expiry", () => {
+ const original = normalize(OriginalEmailProvider(options));
+ const replacement = normalize(EmailProvider(options));
+
+ assert.equal(original.maxAge, 7200);
+ assert.equal(replacement.maxAge, original.maxAge);
+});
+
+test("normalized provider uses the custom verification sender", () => {
+ const provider = normalize(EmailProvider(options));
+
+ assert.equal(provider.sendVerificationRequest, customSender);
+});
+
+test("provider retains NextAuth email identity", () => {
+ const provider = normalize(EmailProvider(options));
+
+ assert.equal(provider.id, "email");
+ assert.equal(provider.type, "email");
+ assert.equal(provider.name, "Email");
+});
+
+test("default sender fails explicitly without PEDW override", async () => {
+ const provider = EmailProvider();
+
+ await assert.rejects(
+ provider.sendVerificationRequest(),
+ /requires a custom GOV\.UK Notify verification sender/
+ );
+});
+
+test("local provider does not import Nodemailer", () => {
+ assert.doesNotMatch(
+ source,
+ /(?:require\s*\(|from\s+|import\s*\()\s*["']nodemailer/
+ );
+});
+
+test("authentication handler imports the local provider", () => {
+ const authSource = fs.readFileSync(
+ path.join(root, "pages/api/auth/[...nextauth].js"),
+ "utf8"
+ );
+
+ assert.match(
+ authSource,
+ /import EmailProvider from ["']\.\.\/\.\.\/\.\.\/lib\/auth\/email-provider["']/
+ );
+
+ assert.doesNotMatch(authSource, /from ["']next-auth\/providers\/email["']/);
+
+ assert.match(authSource, /EmailProvider\s*\(\s*\{/);
+
+ assert.match(authSource, /async sendVerificationRequest\s*\(/);
+
+ assert.match(authSource, /notifyClient\.sendEmail\s*\(/);
+});
diff --git a/tests/phase22/i18n-route-parity.test.cjs b/tests/phase22/i18n-route-parity.test.cjs
index 683ab513..7778ea82 100644
--- a/tests/phase22/i18n-route-parity.test.cjs
+++ b/tests/phase22/i18n-route-parity.test.cjs
@@ -6,7 +6,6 @@ const test = (name, fn) => tests.push({ name, fn });
const loadRewrites = async () => {
const configPath = path.join(__dirname, "..", "..", "next.config.js");
- // eslint-disable-next-line global-require, import/no-dynamic-require
const nextConfig = require(configPath);
return nextConfig.rewrites();
};
diff --git a/tests/phase22/myportal-index-loader-guards.test.cjs b/tests/phase22/myportal-index-loader-guards.test.cjs
new file mode 100644
index 00000000..1cbc4ef9
--- /dev/null
+++ b/tests/phase22/myportal-index-loader-guards.test.cjs
@@ -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);
+ });
+}
diff --git a/tests/phase22/myportal-viewall-loader-guards.test.cjs b/tests/phase22/myportal-viewall-loader-guards.test.cjs
new file mode 100644
index 00000000..20b16af6
--- /dev/null
+++ b/tests/phase22/myportal-viewall-loader-guards.test.cjs
@@ -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);
+ });
+}
diff --git a/tests/phase22/portal-service-behaviour.test.cjs b/tests/phase22/portal-service-behaviour.test.cjs
index 2c847fd6..bbae655b 100644
--- a/tests/phase22/portal-service-behaviour.test.cjs
+++ b/tests/phase22/portal-service-behaviour.test.cjs
@@ -43,39 +43,6 @@ test("portal/sendCaseCompleteMessage appends signed hash suffix to inv query", a
);
});
-test("portal/deleteMyRepresentations uses signed delete request with headers", async () => {
- const axios = createAxiosMock();
- const logger = createLoggerMock();
-
- const requestCalls = [];
- const requestJson = async (config) => {
- requestCalls.push(config);
- return { deleted: true };
- };
-
- const portal = loadServiceModule("portalDirectService.js", {
- axios,
- BASE_URL: "",
- consoleLogger: logger.consoleLogger,
- buildHashedQueryUrl: async (queryUrl) => `${queryUrl}&hash=xyz`,
- requestJson
- });
-
- const result = await portal.deleteMyRepresentations("rep-1");
-
- assert.deepStrictEqual(normalize(result), { deleted: true });
- assert.strictEqual(requestCalls.length, 1);
- assert.strictEqual(requestCalls[0].method, "delete");
- assert.strictEqual(
- requestCalls[0].url,
- "/api/endpoint/deletemyrepresentations_api?myRepresentationsID=rep-1&hash=xyz"
- );
- assert.strictEqual(
- requestCalls[0].headers["Content-Type"],
- "application/json"
- );
-});
-
test("portal/createWatchedCases posts to harmonized route helper URL", async () => {
const axios = createAxiosMock();
const logger = createLoggerMock();
diff --git a/tests/phase22/representation-list-ownership.test.cjs b/tests/phase22/representation-list-ownership.test.cjs
new file mode 100644
index 00000000..82eb7ce4
--- /dev/null
+++ b/tests/phase22/representation-list-ownership.test.cjs
@@ -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);
+ });
+}
diff --git a/tests/phase7/service-behaviour.test.cjs b/tests/phase7/service-behaviour.test.cjs
index dbe91bb3..e53a3071 100644
--- a/tests/phase7/service-behaviour.test.cjs
+++ b/tests/phase7/service-behaviour.test.cjs
@@ -65,73 +65,91 @@ test("document/getAwaitingSubmissionFromBlob logs and returns undefined on failu
assert.strictEqual(logger.calls.length, 1);
});
-test("portal/deleteMyRepresentations appends hash and returns data", async () => {
+test("document/getRepsFromBlob forwards cookies only to trusted origin without redirects", async () => {
const axios = createAxiosMock();
const logger = createLoggerMock();
- const signCalls = [];
- axios.getHandler = async (url) => {
- if (url.startsWith("/api/endpoint/gethash_api?path=")) {
- signCalls.push(url);
- return { data: { hash: "&hash=portal123" } };
- }
-
- throw new Error("Unexpected get url: " + url);
- };
-
- axios.requestHandler = async () => ({ data: { removed: true } });
-
- const portal = loadServiceModule("portalDirectService.js", {
- axios,
- BASE_URL: "",
- consoleLogger: logger.consoleLogger,
- hashAPIPath: () => "&hash=fallback"
+ axios.getHandler = async () => ({
+ data: { value: ["representation"] }
});
- const result = await portal.deleteMyRepresentations("rep-1");
+ const document = loadServiceModule("documentDirectService.js", {
+ axios,
+ BASE_URL: "http://example.local",
+ consoleLogger: logger.consoleLogger,
+ hashAPIPath: () => "&hash=abc123"
+ });
- assert.deepStrictEqual(normalize(result), { removed: true });
- assert.strictEqual(
- signCalls[0],
- "/api/endpoint/gethash_api?path=%2Fapi%2Fendpoint%2Fdeletemyrepresentations_api%3FmyRepresentationsID%3Drep-1"
- );
+ 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,
- "/api/endpoint/gethash_api?path=%2Fapi%2Fendpoint%2Fdeletemyrepresentations_api%3FmyRepresentationsID%3Drep-1"
+ "http://example.local/api/file/getrepsblob?container=container-1&hash=abc123"
);
assert.strictEqual(
- axios.calls[1].config.url,
- "/api/endpoint/deletemyrepresentations_api?myRepresentationsID=rep-1&hash=portal123"
+ axios.calls[0].config.headers.Cookie,
+ "next-auth.session-token=test-session"
);
- assert.strictEqual(axios.calls[1].config.method, "delete");
+ assert.strictEqual(axios.calls[0].config.maxRedirects, 0);
+ assert.strictEqual(logger.calls.length, 0);
});
-test("portal/deleteMyRepresentations logs and returns undefined on failure", async () => {
+test("document/getRepsFromBlob rejects untrusted origin before HTTP request", async () => {
const axios = createAxiosMock();
const logger = createLoggerMock();
- axios.getHandler = async (url) => {
- if (url.startsWith("/api/endpoint/gethash_api?path=")) {
- return { data: { hash: "&hash=portal-fail" } };
- }
-
- throw new Error("Unexpected get url: " + url);
- };
-
- axios.requestHandler = async () =>
- Promise.reject(createAxiosError(401, "Unauthorized"));
-
- const portal = loadServiceModule("portalDirectService.js", {
+ const document = loadServiceModule("documentDirectService.js", {
axios,
- BASE_URL: "",
+ BASE_URL: "https://untrusted.example",
consoleLogger: logger.consoleLogger,
- hashAPIPath: () => "&hash=fallback"
+ hashAPIPath: () => "&hash=abc123"
});
- const result = await portal.deleteMyRepresentations("rep-2");
+ await assert.rejects(
+ document.getRepsFromBlob("container-1", {
+ headers: {
+ Cookie: "next-auth.session-token=test-session"
+ }
+ }),
+ /Untrusted representation request destination/
+ );
- assert.strictEqual(result, undefined);
- assert.strictEqual(logger.calls.length, 1);
+ 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 () => {
@@ -162,11 +180,11 @@ test("portal/deleteWatchedCases uses signer hash and returns data", async () =>
assert.deepStrictEqual(normalize(result), { removed: true });
assert.strictEqual(
signCalls[0],
- "/api/endpoint/gethash_api?path=%2Fapi%2Fendpoint%2Fdeletewatchedcases_api%3FwatchedCaseID%3Dwatch-1"
+ "/api/endpoint/gethash_api?path=%2Fapi%2Fsubscriptions%2Fdelete-watched-case%3FwatchedCaseID%3Dwatch-1"
);
assert.strictEqual(
axios.calls[1].config.url,
- "/api/endpoint/deletewatchedcases_api?watchedCaseID=watch-1&hash=watch123"
+ "/api/subscriptions/delete-watched-case?watchedCaseID=watch-1&hash=watch123"
);
});
diff --git a/tests/phase8/service-behaviour.test.cjs b/tests/phase8/service-behaviour.test.cjs
index eb677911..77e109bb 100644
--- a/tests/phase8/service-behaviour.test.cjs
+++ b/tests/phase8/service-behaviour.test.cjs
@@ -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: () => {}
diff --git a/tests/security/cookie-compatibility.test.cjs b/tests/security/cookie-compatibility.test.cjs
new file mode 100644
index 00000000..d330320c
--- /dev/null
+++ b/tests/security/cookie-compatibility.test.cjs
@@ -0,0 +1,331 @@
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const path = require("node:path");
+const test = require("node:test");
+const vm = require("node:vm");
+
+const rootDir = path.resolve(__dirname, "..", "..");
+const normalize = (value) => JSON.parse(JSON.stringify(value));
+
+const loadLocalCookieCompatibility = () => {
+ const filePath = path.join(rootDir, "lib", "cookies.js");
+ let source = fs.readFileSync(filePath, "utf8");
+
+ source = source.replace(
+ 'import * as cookie from "cookie";',
+ 'const cookie = require("cookie");'
+ );
+ source = source.replace(
+ 'import setCookieParser from "set-cookie-parser";',
+ 'const setCookieParser = require("set-cookie-parser");'
+ );
+ source = source.replace(/export const\s+/g, "const ");
+ source += "\nmodule.exports = { parseCookies, setCookie, destroyCookie };\n";
+
+ const context = {
+ module: { exports: {} },
+ exports: {},
+ require,
+ console,
+ document: global.document,
+ window: global.window
+ };
+
+ vm.runInNewContext(source, context, { filename: filePath });
+ return context.module.exports;
+};
+
+const loadCookieImplementation = () => {
+ return loadLocalCookieCompatibility();
+};
+
+const withBrowserDocument = async (initialCookies, callback) => {
+ const previousDocument = global.document;
+ const previousWindow = global.window;
+ const cookieJar = new Map(Object.entries(initialCookies));
+ const writes = [];
+
+ const documentMock = {};
+ Object.defineProperty(documentMock, "cookie", {
+ configurable: true,
+ get() {
+ return Array.from(cookieJar.entries())
+ .map(([name, value]) => `${name}=${value}`)
+ .join("; ");
+ },
+ set(serializedCookie) {
+ writes.push(serializedCookie);
+ const [nameValue, ...attributes] = serializedCookie.split(";");
+ const separatorIndex = nameValue.indexOf("=");
+ const name = nameValue.slice(0, separatorIndex);
+ const value = nameValue.slice(separatorIndex + 1);
+ const maxAge = attributes
+ .map((attribute) => attribute.trim())
+ .find((attribute) =>
+ attribute.toLowerCase().startsWith("max-age=")
+ );
+
+ if (maxAge && Number(maxAge.split("=")[1]) < 0) {
+ cookieJar.delete(name);
+ return;
+ }
+
+ cookieJar.set(name, value);
+ }
+ });
+
+ global.window = {};
+ global.document = documentMock;
+
+ try {
+ await callback({ cookieJar, writes });
+ } finally {
+ if (previousWindow === undefined) {
+ delete global.window;
+ } else {
+ global.window = previousWindow;
+ }
+
+ if (previousDocument === undefined) {
+ delete global.document;
+ } else {
+ global.document = previousDocument;
+ }
+ }
+};
+
+const createResponse = (initialHeader) => {
+ let setCookieHeader = initialHeader;
+ const calls = [];
+
+ return {
+ response: {
+ finished: false,
+ getHeader(name) {
+ assert.strictEqual(name, "Set-Cookie");
+ return setCookieHeader;
+ },
+ setHeader(name, value) {
+ calls.push({ name, value });
+ setCookieHeader = value;
+ }
+ },
+ calls,
+ getSetCookieHeader: () => setCookieHeader
+ };
+};
+
+test("browser parsing preserves characterized nookies behavior", async () => {
+ await withBrowserDocument(
+ {
+ first: "one",
+ encoded: "two%20words",
+ equals: "a%3Db",
+ spaces: "hello%20world",
+ special: "%21%40%23%24%25%5E%26*%28%29",
+ malformed: "%E0%A4%A"
+ },
+ () => {
+ const { parseCookies } = loadCookieImplementation();
+
+ assert.deepStrictEqual(parseCookies(), {
+ first: "one",
+ encoded: "two words",
+ equals: "a=b",
+ spaces: "hello world",
+ special: "!@#$%^&*()",
+ malformed: "%E0%A4%A"
+ });
+ }
+ );
+
+ await withBrowserDocument({}, () => {
+ const { parseCookies } = loadCookieImplementation();
+ assert.deepStrictEqual(parseCookies(), {});
+ });
+});
+
+test("parseCookies returns an empty object without a browser document", () => {
+ const { parseCookies } = loadCookieImplementation();
+
+ assert.deepStrictEqual(normalize(parseCookies()), {});
+ assert.deepStrictEqual(normalize(parseCookies(null)), {});
+ assert.deepStrictEqual(normalize(parseCookies({})), {});
+});
+
+test("browser writes preserve encoding and supported options", async () => {
+ await withBrowserDocument({}, ({ writes }) => {
+ const { setCookie } = loadCookieImplementation();
+ const expires = new Date("2030-01-02T03:04:05.000Z");
+
+ assert.deepStrictEqual(
+ normalize(setCookie(null, "basic", "value")),
+ {}
+ );
+ setCookie(null, "pathCookie", "value", { path: "/" });
+ setCookie(null, "expiresCookie", "value", { expires });
+ setCookie(null, "maxAgeCookie", "value", { maxAge: 60 });
+ setCookie(null, "encodedCookie", "hello world=a&b");
+
+ assert.deepStrictEqual(writes, [
+ "basic=value",
+ "pathCookie=value; Path=/",
+ "expiresCookie=value; Expires=Wed, 02 Jan 2030 03:04:05 GMT",
+ "maxAgeCookie=value; Max-Age=60",
+ "encodedCookie=hello%20world%3Da%26b"
+ ]);
+ });
+});
+
+test("browser writes reject httpOnly cookies", async () => {
+ await withBrowserDocument({}, () => {
+ const { setCookie } = loadCookieImplementation();
+
+ assert.throws(
+ () => setCookie(null, "protected", "value", { httpOnly: true }),
+ /Can not set a httpOnly cookie in the browser\./
+ );
+ });
+});
+
+test("browser deletion preserves path and uses an empty value with negative maxAge", async () => {
+ await withBrowserDocument(
+ {
+ pedwWatchCase: "case-1",
+ pinsUser: "contact-1",
+ pedw_locale: "cy"
+ },
+ ({ cookieJar, writes }) => {
+ const { destroyCookie } = loadCookieImplementation();
+
+ for (const name of ["pedwWatchCase", "pinsUser", "pedw_locale"]) {
+ assert.deepStrictEqual(
+ normalize(destroyCookie(null, name, { path: "/" })),
+ {}
+ );
+ }
+
+ assert.deepStrictEqual(writes, [
+ "pedwWatchCase=; Max-Age=-1; Path=/",
+ "pinsUser=; Max-Age=-1; Path=/",
+ "pedw_locale=; Max-Age=-1; Path=/"
+ ]);
+ assert.strictEqual(cookieJar.has("pedwWatchCase"), false);
+ assert.strictEqual(cookieJar.has("pinsUser"), false);
+ assert.strictEqual(cookieJar.has("pedw_locale"), false);
+ }
+ );
+});
+
+test("server parsing uses ctx.req.headers.cookie", () => {
+ const { parseCookies } = loadCookieImplementation();
+
+ assert.deepStrictEqual(
+ parseCookies({
+ req: {
+ headers: {
+ cookie: "first=one; encoded=two%20words; equals=a%3Db"
+ }
+ }
+ }),
+ {
+ first: "one",
+ encoded: "two words",
+ equals: "a=b"
+ }
+ );
+});
+
+test("server writes a Set-Cookie header and preserves unrelated cookies", () => {
+ const { setCookie } = loadCookieImplementation();
+ const responseState = createResponse([
+ "unrelated=keep; Path=/; SameSite=Lax",
+ "other=value; HttpOnly; Path=/; SameSite=Strict"
+ ]);
+
+ assert.deepStrictEqual(
+ normalize(
+ setCookie(
+ { res: responseState.response },
+ "target",
+ "new value",
+ { path: "/" }
+ )
+ ),
+ {}
+ );
+
+ assert.deepStrictEqual(normalize(responseState.getSetCookieHeader()), [
+ "unrelated=keep; Path=/; SameSite=Lax",
+ "other=value; Path=/; HttpOnly; SameSite=Strict",
+ "target=new%20value; Path=/"
+ ]);
+ assert.strictEqual(responseState.calls.length, 1);
+});
+
+test("server deduplicates an exactly matching cookie and keeps cookies with changed values or paths", () => {
+ const { setCookie } = loadCookieImplementation();
+ const responseState = createResponse([
+ "target=new; Path=/; SameSite=Lax",
+ "target=old; Path=/; SameSite=Lax",
+ "target=keep-a; Path=/a; SameSite=Lax",
+ "target=keep-b; Path=/b; SameSite=Lax"
+ ]);
+
+ setCookie({ res: responseState.response }, "target", "new", {
+ path: "/",
+ sameSite: "lax"
+ });
+
+ assert.deepStrictEqual(normalize(responseState.getSetCookieHeader()), [
+ "target=old; Path=/; SameSite=Lax",
+ "target=keep-a; Path=/a; SameSite=Lax",
+ "target=keep-b; Path=/b; SameSite=Lax",
+ "target=new; Path=/; SameSite=Lax"
+ ]);
+});
+
+test("server does not write after the response has finished", () => {
+ const { setCookie } = loadCookieImplementation();
+ const responseState = createResponse();
+ responseState.response.finished = true;
+ const warnings = [];
+ const originalWarn = console.warn;
+ console.warn = (message) => warnings.push(message);
+
+ try {
+ assert.deepStrictEqual(
+ normalize(
+ setCookie(
+ { res: responseState.response },
+ "target",
+ "value"
+ )
+ ),
+ {}
+ );
+ } finally {
+ console.warn = originalWarn;
+ }
+
+ assert.deepStrictEqual(responseState.calls, []);
+ assert.deepStrictEqual(warnings, [
+ 'Not setting "target" cookie. Response has finished.',
+ "You should set cookie before res.send()"
+ ]);
+});
+
+test("server no-op behavior is preserved for null, empty, and undefined contexts", () => {
+ const { setCookie, destroyCookie } = loadCookieImplementation();
+
+ assert.deepStrictEqual(normalize(setCookie(null, "target", "value")), {});
+ assert.deepStrictEqual(normalize(setCookie({}, "target", "value")), {});
+ assert.deepStrictEqual(
+ normalize(setCookie(undefined, "target", "value")),
+ {}
+ );
+ assert.deepStrictEqual(
+ normalize(destroyCookie({}, "pedwWatchCase", { path: "/" })),
+ {}
+ );
+});
\ No newline at end of file
diff --git a/tests/serviceHarness.cjs b/tests/serviceHarness.cjs
index aea3882b..a489b5ce 100644
--- a/tests/serviceHarness.cjs
+++ b/tests/serviceHarness.cjs
@@ -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: () => {},
diff --git a/tsconfig.json b/tsconfig.json
index 8a5672e6..8f6d8664 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -15,7 +15,7 @@
"moduleResolution": "Node16",
"resolveJsonModule": true,
"isolatedModules": true,
- "jsx": "preserve"
+ "jsx": "react-jsx"
},
"include": [
"next-env.d.ts",