Repository navigation
Expand file tree
/
Copy pathsmeCoverageRunApi.test.ts
More file actions
370 lines (318 loc) · 13.2 KB
/
Copy pathsmeCoverageRunApi.test.ts
File metadata and controls
370 lines (318 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
import { describe, expect, it, vi } from "vitest";
import type { SessionCredentials } from "../domain/types";
import { SmeCoverageRunError, type SmeCoverageRunResult } from "../utilities/smeCoverage/runner";
import { handleSmeCoverageRunRequest } from "./smeCoverageRunApi";
const credentials: SessionCredentials = {
instanceType: "enterprise",
baseUrl: "https://soedemo.stackenterprise.co",
apiKey: "enterprise-api-key-secret",
accessToken: "enterprise-access-token-secret",
authSource: "manual-enterprise-token",
};
const credentialsWithEveryString: SessionCredentials = {
...credentials,
pat: "personal-access-token-secret",
oauthClientId: "oauth-client-id-secret",
oauthScopes: ["scope-one-secret", "scope-two-secret"],
accessTokenExpiresAt: "2027-07-31T00:00:00.000Z",
};
const result: SmeCoverageRunResult = {
utilityId: "sme-coverage-analyzer",
utilityTitle: "SME Coverage Analyzer",
datasets: [],
messages: [],
warnings: [],
decisionPack: {
summary: {
tagsAnalyzed: 0,
tagsWithSmes: 0,
immediateGaps: 0,
criticalUnderCoverage: 0,
lightCoverage: 0,
unknownRows: 0,
},
evidence: [],
overview: "No SME coverage data was returned.",
assessment: "No assessment is available.",
findings: {
immediateGaps: [],
criticalUnderCoverage: [],
lightCoverage: [],
},
methodology: {
activityQuestionMinimum: 1,
activityPageViewThresholdExclusive: 25,
activeTagMedianPageViews: null,
coveredActiveSampleSize: 0,
p75PageViewsPerSme: null,
p90PageViewsPerSme: null,
percentileSampleSufficient: false,
ratioFormula: "pageViews / smeCount",
roundingRule: "Nearest whole page view for display; unrounded for calculation",
},
warnings: [],
snapshot: {
instanceHost: "soedemo.stackenterprise.co",
generatedAt: "2026-07-31T00:00:00.000Z",
scopeLabel: "All-time demand · Current SME coverage",
collectionLabel: "All available data collected",
completeness: "Complete",
},
},
};
const exhaustiveScopeError =
"SME Coverage Analyzer accepts credentials only; its scope is all available history.";
async function responseBody(response: Response) {
return response.json();
}
describe("handleSmeCoverageRunRequest", () => {
it("passes only cloned credentials to the runner", async () => {
const runSmeCoverageAnalysis = vi.fn().mockResolvedValue(result);
const response = await handleSmeCoverageRunRequest({ credentials }, { runSmeCoverageAnalysis });
expect(response.status).toBe(200);
await expect(responseBody(response)).resolves.toEqual({ ok: true, result });
expect(runSmeCoverageAnalysis).toHaveBeenCalledOnce();
expect(runSmeCoverageAnalysis).toHaveBeenCalledWith(credentials);
});
it.each([
["pageSize", { pageSize: 100 }],
["maxPagesPerDataset", { maxPagesPerDataset: 20 }],
["runPreset", { runPreset: "deep-audit" }],
["scope", { scope: {} }],
["startDate", { startDate: "2026-07-01" }],
["endDate", { endDate: "2026-07-31" }],
["an extra scope key", { dataset: "questions" }],
])("rejects obsolete or extra %s before running", async (_label, extraProperty) => {
const runSmeCoverageAnalysis = vi.fn();
const response = await handleSmeCoverageRunRequest(
{ credentials, ...extraProperty },
{ runSmeCoverageAnalysis },
);
expect(response.status).toBe(400);
await expect(responseBody(response)).resolves.toEqual({
ok: false,
kind: "validation",
error: exhaustiveScopeError,
});
expect(runSmeCoverageAnalysis).not.toHaveBeenCalled();
});
it.each([
["missing credentials", {}],
["malformed OAuth scopes", { credentials: { ...credentials, oauthScopes: {} } }],
])("returns a validation response for %s", async (_label, payload) => {
const runSmeCoverageAnalysis = vi.fn();
const response = await handleSmeCoverageRunRequest(payload, { runSmeCoverageAnalysis });
expect(response.status).toBe(400);
await expect(responseBody(response)).resolves.toMatchObject({ ok: false, kind: "validation" });
expect(runSmeCoverageAnalysis).not.toHaveBeenCalled();
});
it.each([
["validation", 400],
["unsupported", 422],
["collection", 502],
] as const)("maps a %s runner error to HTTP %i", async (kind, status) => {
const runSmeCoverageAnalysis = vi.fn().mockRejectedValue(new SmeCoverageRunError(kind, `${kind} failed`));
const response = await handleSmeCoverageRunRequest({ credentials }, { runSmeCoverageAnalysis });
expect(response.status).toBe(status);
await expect(responseBody(response)).resolves.toEqual({ ok: false, kind, error: `${kind} failed` });
});
it("does not expose unexpected runner details or stages", async () => {
const sensitiveDetail = "database-password=internal-secret";
const runSmeCoverageAnalysis = vi.fn().mockRejectedValue(
new SmeCoverageRunError("unexpected", sensitiveDetail, `stage-${sensitiveDetail}`),
);
const response = await handleSmeCoverageRunRequest({ credentials }, { runSmeCoverageAnalysis });
const body = await responseBody(response);
expect(response.status).toBe(500);
expect(body).toEqual({
ok: false,
kind: "unexpected",
error: "SME Coverage Analyzer failed unexpectedly.",
});
expect(JSON.stringify(body)).not.toContain(sensitiveDetail);
});
it("includes a non-empty collection stage", async () => {
const runSmeCoverageAnalysis = vi.fn().mockRejectedValue(
new SmeCoverageRunError("collection", "Questions failed", "questions"),
);
const response = await handleSmeCoverageRunRequest({ credentials }, { runSmeCoverageAnalysis });
expect(response.status).toBe(502);
await expect(responseBody(response)).resolves.toEqual({
ok: false,
kind: "collection",
stage: "questions",
error: "Questions failed",
});
});
it.each([
["complete", result],
[
"partial",
{
...result,
warnings: [{ code: "capped", message: "Partial sample" }],
decisionPack: {
...result.decisionPack,
snapshot: { ...result.decisionPack.snapshot, completeness: "Partial" as const },
},
},
],
[
"empty",
{
...result,
datasets: [],
messages: [],
warnings: [],
decisionPack: {
...result.decisionPack,
snapshot: { ...result.decisionPack.snapshot, completeness: "Empty" as const },
},
},
],
])("returns a %s result pack unchanged", async (_label, successfulResult) => {
const runSmeCoverageAnalysis = vi.fn().mockResolvedValue(successfulResult);
const response = await handleSmeCoverageRunRequest({ credentials }, { runSmeCoverageAnalysis });
expect(response.status).toBe(200);
await expect(responseBody(response)).resolves.toEqual({ ok: true, result: successfulResult });
});
it("never returns submitted credential values", async () => {
const runSmeCoverageAnalysis = vi.fn().mockRejectedValue(
new SmeCoverageRunError("collection", "Questions failed", "questions"),
);
const response = await handleSmeCoverageRunRequest({ credentials }, { runSmeCoverageAnalysis });
const body = JSON.stringify(await responseBody(response));
expect(body).not.toContain("enterprise-api-key-secret");
expect(body).not.toContain("enterprise-access-token-secret");
expect(body).not.toContain("credentials");
});
it("redacts every submitted credential string from mapped runner errors", async () => {
const submittedValues = [
credentialsWithEveryString.instanceType,
credentialsWithEveryString.baseUrl,
credentialsWithEveryString.apiKey,
credentialsWithEveryString.accessToken,
credentialsWithEveryString.pat,
credentialsWithEveryString.authSource,
credentialsWithEveryString.oauthClientId,
...(credentialsWithEveryString.oauthScopes ?? []),
credentialsWithEveryString.accessTokenExpiresAt,
].filter((value): value is string => typeof value === "string" && value.length > 0);
const runSmeCoverageAnalysis = vi.fn().mockRejectedValue(
new SmeCoverageRunError("collection", submittedValues.join(" | "), "questions"),
);
const response = await handleSmeCoverageRunRequest(
{ credentials: credentialsWithEveryString },
{ runSmeCoverageAnalysis },
);
const body = JSON.stringify(await responseBody(response));
expect(response.status).toBe(502);
expect(body).toContain("[REDACTED]");
for (const value of submittedValues) {
expect(body).not.toContain(value);
}
});
it("redacts the pre-run credential snapshot after a runner mutation attempt", async () => {
const submittedCredentials: SessionCredentials = {
...credentialsWithEveryString,
oauthScopes: [...(credentialsWithEveryString.oauthScopes ?? []), "\t\t"],
};
const submittedValues = [
submittedCredentials.instanceType,
submittedCredentials.baseUrl,
submittedCredentials.apiKey,
submittedCredentials.accessToken,
submittedCredentials.pat,
submittedCredentials.authSource,
submittedCredentials.oauthClientId,
...(submittedCredentials.oauthScopes ?? []),
submittedCredentials.accessTokenExpiresAt,
].filter((value): value is string => typeof value === "string" && value.length > 0);
let runnerCredentialsFrozen = false;
let runnerScopesFrozen = false;
const runSmeCoverageAnalysis = vi.fn().mockImplementation((runnerCredentials: SessionCredentials) => {
runnerCredentialsFrozen = Object.isFrozen(runnerCredentials);
runnerScopesFrozen = Object.isFrozen(runnerCredentials.oauthScopes);
for (const mutate of [
() => { runnerCredentials.apiKey = ""; },
() => { runnerCredentials.accessToken = ""; },
() => { runnerCredentials.pat = ""; },
() => { runnerCredentials.oauthClientId = ""; },
() => { runnerCredentials.accessTokenExpiresAt = ""; },
() => { runnerCredentials.oauthScopes?.splice(0); },
]) {
try {
mutate();
} catch {
// A hostile dependency may cast away readonly types; frozen values reject every mutation.
}
}
return Promise.reject(new SmeCoverageRunError("collection", submittedValues.join(" | "), "questions"));
});
const response = await handleSmeCoverageRunRequest(
{ credentials: submittedCredentials },
{ runSmeCoverageAnalysis },
);
const body = JSON.stringify(await responseBody(response));
expect(response.status).toBe(502);
expect(runnerCredentialsFrozen).toBe(true);
expect(runnerScopesFrozen).toBe(true);
expect(body).toContain("[REDACTED]");
for (const value of submittedValues) {
expect(body).not.toContain(value);
}
expect(body).not.toContain("\\t\\t");
});
it("uses a generic message for unknown errors", async () => {
const runSmeCoverageAnalysis = vi.fn().mockRejectedValue(new Error("enterprise-api-key-secret"));
const response = await handleSmeCoverageRunRequest({ credentials }, { runSmeCoverageAnalysis });
expect(response.status).toBe(500);
await expect(responseBody(response)).resolves.toEqual({
ok: false,
kind: "unexpected",
error: "SME Coverage Analyzer failed unexpectedly.",
});
});
it("rejects inherited credentials before running", async () => {
const runSmeCoverageAnalysis = vi.fn();
const payload = Object.create({ credentials });
const response = await handleSmeCoverageRunRequest(payload, { runSmeCoverageAnalysis });
expect(response.status).toBe(400);
expect(runSmeCoverageAnalysis).not.toHaveBeenCalled();
});
it("rejects credentials with inherited required fields before running", async () => {
const runSmeCoverageAnalysis = vi.fn();
const inheritedCredentials = Object.create(credentials);
const response = await handleSmeCoverageRunRequest(
{ credentials: inheritedCredentials },
{ runSmeCoverageAnalysis },
);
expect(response.status).toBe(400);
expect(runSmeCoverageAnalysis).not.toHaveBeenCalled();
});
it("does not use inherited optional payload fields", async () => {
const runSmeCoverageAnalysis = vi.fn().mockResolvedValue(result);
const payload = Object.assign(Object.create({ pageSize: 50, maxPagesPerDataset: 1 }), { credentials });
const response = await handleSmeCoverageRunRequest(payload, { runSmeCoverageAnalysis });
expect(response.status).toBe(200);
expect(runSmeCoverageAnalysis).toHaveBeenCalledWith(credentials);
});
it.each([
["a non-enumerable unapproved property", () => {
const payload = { credentials };
Object.defineProperty(payload, "hidden", { value: true });
return payload;
}],
["a symbol property", () => ({ credentials, [Symbol("hidden")]: true })],
])("rejects %s before running", async (_label, createPayload) => {
const runSmeCoverageAnalysis = vi.fn();
const response = await handleSmeCoverageRunRequest(createPayload(), { runSmeCoverageAnalysis });
expect(response.status).toBe(400);
await expect(responseBody(response)).resolves.toEqual({
ok: false,
kind: "validation",
error: exhaustiveScopeError,
});
expect(runSmeCoverageAnalysis).not.toHaveBeenCalled();
});
});