security: preserve representation history in watched-case upsert

This commit is contained in:
2026-11-05 12:48:45 +00:00
parent 706083b6f0
commit 0a115a8808
2 changed files with 749 additions and 37 deletions
@@ -2912,10 +2912,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 +2939,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 +2971,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,6 +2999,561 @@ test("createwatchedcases catch path returns WATCHED_CASE_UPSERT_FAILED", async (
);
});
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,
getServerSession: async () => null,
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: () => {},
authOptions: () => ({})
});
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, 401);
assert.strictEqual(res.state.jsonBody.error.code, "UNAUTHENTICATED");
assert.strictEqual(tokenCalls, 0);
assert.strictEqual(relayCalls, 0);
assert.strictEqual(writeCalls, 0);
});
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 () => {
writeCalls += 1;
return { data: {} };
},
consoleLogger: () => {}
});
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";