@exulu/backend 5.1.2 → 5.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-37MKZIH2.js → chunk-PU3LGCBR.js} +281 -33
- package/dist/{convert-exulu-tools-to-ai-sdk-tools-BNDHJH7B.js → convert-exulu-tools-to-ai-sdk-tools-77FLVHEA.js} +3 -1
- package/dist/index.cjs +2800 -376
- package/dist/index.js +2412 -285
- package/ee/agentic-retrieval/pipeline/config.test.ts +42 -0
- package/ee/agentic-retrieval/pipeline/config.ts +36 -0
- package/ee/agentic-retrieval/pipeline/index.test.ts +3 -3
- package/ee/agentic-retrieval/pipeline/index.ts +43 -1
- package/ee/agentic-retrieval/pipeline/micro-call.test.ts +58 -0
- package/ee/agentic-retrieval/pipeline/micro-call.ts +20 -3
- package/ee/agentic-retrieval/pipeline/near-duplicates.test.ts +50 -0
- package/ee/agentic-retrieval/pipeline/near-duplicates.ts +74 -0
- package/ee/agentic-retrieval/pipeline/prefilter.test.ts +32 -0
- package/ee/agentic-retrieval/pipeline/prefilter.ts +13 -1
- package/ee/agentic-retrieval/pipeline/rerank.test.ts +79 -0
- package/ee/agentic-retrieval/pipeline/rerank.ts +61 -6
- package/ee/claim-check/agent-config.ts +26 -0
- package/ee/claim-check/concurrency.test.ts +33 -0
- package/ee/claim-check/concurrency.ts +30 -0
- package/ee/claim-check/evidence.test.ts +198 -0
- package/ee/claim-check/evidence.ts +162 -0
- package/ee/claim-check/prompts/decompose.ts +52 -0
- package/ee/claim-check/prompts/disambiguate.ts +58 -0
- package/ee/claim-check/prompts/select-disambiguate.ts +17 -0
- package/ee/claim-check/prompts/select.ts +55 -0
- package/ee/claim-check/prompts/shared.test.ts +193 -0
- package/ee/claim-check/prompts/shared.ts +89 -0
- package/ee/claim-check/prompts/verify.ts +56 -0
- package/ee/claim-check/rate-limit.test.ts +40 -0
- package/ee/claim-check/rate-limit.ts +82 -0
- package/ee/claim-check/routes.test.ts +1188 -0
- package/ee/claim-check/routes.ts +682 -0
- package/ee/claim-check/run.test.ts +1317 -0
- package/ee/claim-check/run.ts +710 -0
- package/ee/claim-check/score.test.ts +108 -0
- package/ee/claim-check/score.ts +75 -0
- package/ee/claim-check/second-chance.test.ts +89 -0
- package/ee/claim-check/second-chance.ts +80 -0
- package/ee/claim-check/split.test.ts +179 -0
- package/ee/claim-check/split.ts +220 -0
- package/ee/claim-check/stages/decompose.test.ts +129 -0
- package/ee/claim-check/stages/decompose.ts +64 -0
- package/ee/claim-check/stages/disambiguate.test.ts +130 -0
- package/ee/claim-check/stages/disambiguate.ts +74 -0
- package/ee/claim-check/stages/select-disambiguate.test.ts +137 -0
- package/ee/claim-check/stages/select-disambiguate.ts +90 -0
- package/ee/claim-check/stages/select.test.ts +155 -0
- package/ee/claim-check/stages/select.ts +94 -0
- package/ee/claim-check/stages/usage.ts +11 -0
- package/ee/claim-check/stages/verify.test.ts +154 -0
- package/ee/claim-check/stages/verify.ts +78 -0
- package/ee/claim-check/types.ts +178 -0
- package/ee/entitlements.ts +3 -0
- package/ee/invoke-skills/create-sandbox.ts +18 -1
- package/ee/python/requirements.txt +3 -0
- package/ee/schemas.ts +71 -0
- package/ee/workers.ts +13 -0
- package/package.json +1 -1
|
@@ -0,0 +1,1188 @@
|
|
|
1
|
+
// ee/claim-check/routes.test.ts
|
|
2
|
+
import express from "express";
|
|
3
|
+
import request from "supertest";
|
|
4
|
+
import {
|
|
5
|
+
registerClaimCheckRoutes,
|
|
6
|
+
CLAIM_CHECK_PATH,
|
|
7
|
+
CLAIM_CHECK_SESSION_PATH,
|
|
8
|
+
CLAIM_CHECK_TIMEOUT_MS,
|
|
9
|
+
resolveClaimCheckTimeoutMs,
|
|
10
|
+
type ClaimCheckRouteDeps,
|
|
11
|
+
} from "./routes";
|
|
12
|
+
import { claimCheckRateLimiter } from "./rate-limit";
|
|
13
|
+
import { PUBLIC_SURFACE_HEADER } from "@SRC/exulu/public-surface";
|
|
14
|
+
|
|
15
|
+
const RESULT = {
|
|
16
|
+
status: "ok" as const,
|
|
17
|
+
score: { claims: 2, supported: 2, contradicted: 0, unsupported: 0, unsupportedShare: 0, label: "ok" as const },
|
|
18
|
+
sentences: [],
|
|
19
|
+
claims: [],
|
|
20
|
+
usage: { calls: 3, inputTokens: 10, outputTokens: 2 },
|
|
21
|
+
timings: { totalMs: 5 },
|
|
22
|
+
limits: { truncated: false, sentencesSkipped: 0 },
|
|
23
|
+
notes: [],
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const BODY = {
|
|
27
|
+
question: "Womit arbeitet die FST-2XT?",
|
|
28
|
+
answer: "Die FST-2XT arbeitet mit 230 Volt.",
|
|
29
|
+
sources: [{ id: "s1", content: "Die FST-2XT arbeitet mit 230 Volt." }],
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
function buildApp(overrides: Partial<ClaimCheckRouteDeps> = {}) {
|
|
33
|
+
const runCheck = jest.fn().mockResolvedValue(RESULT);
|
|
34
|
+
const deps: ClaimCheckRouteDeps = {
|
|
35
|
+
authenticate: async () => ({ user: { id: 7, type: "user" } as any }),
|
|
36
|
+
checkApiKeyScope: () => ({ allowed: true, code: 200, reason: "" }),
|
|
37
|
+
checkRecordAccess: async () => true,
|
|
38
|
+
getAgent: async () => ({ id: "agent-1", model: "agent-model", tools: [] }) as any,
|
|
39
|
+
resolveModel: async ({ modelId }: any) => ({ languageModel: { modelId } }) as any,
|
|
40
|
+
runCheck,
|
|
41
|
+
isLicensed: () => true,
|
|
42
|
+
limiter: claimCheckRateLimiter({ perMinute: 100, perHour: 1000, maxInFlight: 10 }),
|
|
43
|
+
isExternalUser: () => false,
|
|
44
|
+
externalRateLimitExceeded: () => false,
|
|
45
|
+
platformDefaultModel: async () => "platform-model",
|
|
46
|
+
saveClaimCheck: jest.fn().mockResolvedValue(undefined),
|
|
47
|
+
listClaimChecks: jest.fn().mockResolvedValue({}),
|
|
48
|
+
// Nothing stored unless a test says otherwise, so every existing
|
|
49
|
+
// assertion still exercises the engine path.
|
|
50
|
+
findClaimCheck: jest.fn().mockResolvedValue(undefined),
|
|
51
|
+
...overrides,
|
|
52
|
+
};
|
|
53
|
+
const app = express();
|
|
54
|
+
app.use(express.json({ limit: "20mb" }));
|
|
55
|
+
registerClaimCheckRoutes(app, deps);
|
|
56
|
+
return { app, deps, runCheck: deps.runCheck as jest.Mock };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function post(app: ReturnType<typeof express>, body: unknown) {
|
|
60
|
+
return request(app).post(CLAIM_CHECK_PATH).send(body);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
describe(`POST ${CLAIM_CHECK_PATH}`, () => {
|
|
64
|
+
it("returns the engine's result for a valid request", async () => {
|
|
65
|
+
const { app, runCheck } = buildApp();
|
|
66
|
+
const res = await request(app).post(CLAIM_CHECK_PATH).send(BODY);
|
|
67
|
+
expect(res.status).toBe(200);
|
|
68
|
+
expect(res.body.score.label).toBe("ok");
|
|
69
|
+
expect(runCheck).toHaveBeenCalledTimes(1);
|
|
70
|
+
expect(runCheck.mock.calls[0][0].question).toBe(BODY.question);
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it("404s when the deployment is not licensed, without running anything", async () => {
|
|
74
|
+
const authenticate = jest.fn(async () => ({ user: { id: 7, type: "user" } as any }));
|
|
75
|
+
const checkApiKeyScope = jest.fn(() => ({ allowed: true, code: 200, reason: "" }));
|
|
76
|
+
const checkRecordAccess = jest.fn(async () => true);
|
|
77
|
+
const getAgent = jest.fn(async () => ({ id: "agent-1", model: "agent-model", tools: [] }) as any);
|
|
78
|
+
const { app, runCheck } = buildApp({
|
|
79
|
+
isLicensed: () => false,
|
|
80
|
+
authenticate,
|
|
81
|
+
checkApiKeyScope,
|
|
82
|
+
checkRecordAccess,
|
|
83
|
+
getAgent,
|
|
84
|
+
});
|
|
85
|
+
const res = await request(app).post(CLAIM_CHECK_PATH).send({ ...BODY, agent: "agent-1" });
|
|
86
|
+
expect(res.status).toBe(404);
|
|
87
|
+
expect(runCheck).not.toHaveBeenCalled();
|
|
88
|
+
// The licence check must run before anything else touches auth, scope or RBAC.
|
|
89
|
+
expect(authenticate).not.toHaveBeenCalled();
|
|
90
|
+
expect(checkApiKeyScope).not.toHaveBeenCalled();
|
|
91
|
+
expect(checkRecordAccess).not.toHaveBeenCalled();
|
|
92
|
+
expect(getAgent).not.toHaveBeenCalled();
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it("401s when authentication fails", async () => {
|
|
96
|
+
const { app } = buildApp({
|
|
97
|
+
authenticate: async () => ({ error: true, code: 401, message: "no key" }),
|
|
98
|
+
});
|
|
99
|
+
const res = await request(app).post(CLAIM_CHECK_PATH).send(BODY);
|
|
100
|
+
expect(res.status).toBe(401);
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
it("400s on a missing question, a missing answer and a non-array sources field", async () => {
|
|
104
|
+
const { app } = buildApp();
|
|
105
|
+
expect((await request(app).post(CLAIM_CHECK_PATH).send({ answer: "a", sources: [] })).status).toBe(400);
|
|
106
|
+
expect((await request(app).post(CLAIM_CHECK_PATH).send({ question: "q", sources: [] })).status).toBe(400);
|
|
107
|
+
expect((await request(app).post(CLAIM_CHECK_PATH).send({ question: "q", answer: "a", sources: "nope" })).status).toBe(400);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it("413s when the answer or the evidence exceeds the payload caps", async () => {
|
|
111
|
+
const { app, runCheck } = buildApp();
|
|
112
|
+
const huge = "a".repeat(200_001);
|
|
113
|
+
const tooLongAnswer = await request(app).post(CLAIM_CHECK_PATH).send({ ...BODY, answer: huge });
|
|
114
|
+
expect(tooLongAnswer.status).toBe(413);
|
|
115
|
+
|
|
116
|
+
const tooMuchEvidence = await request(app)
|
|
117
|
+
.post(CLAIM_CHECK_PATH)
|
|
118
|
+
.send({ ...BODY, sources: [{ id: "s1", content: "b".repeat(2_000_001) }] });
|
|
119
|
+
expect(tooMuchEvidence.status).toBe(413);
|
|
120
|
+
expect(runCheck).not.toHaveBeenCalled();
|
|
121
|
+
|
|
122
|
+
const tooManySources = await request(app)
|
|
123
|
+
.post(CLAIM_CHECK_PATH)
|
|
124
|
+
.send({ ...BODY, sources: Array.from({ length: 201 }, (_, i) => ({ id: `s${i}`, content: "x" })) });
|
|
125
|
+
expect(tooManySources.status).toBe(413);
|
|
126
|
+
expect(runCheck).not.toHaveBeenCalled();
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
it("429s when the limiter refuses, and releases the slot after a completed check", async () => {
|
|
130
|
+
const limiter = claimCheckRateLimiter({ perMinute: 1, perHour: 10, maxInFlight: 10 });
|
|
131
|
+
const { app } = buildApp({ limiter });
|
|
132
|
+
expect((await request(app).post(CLAIM_CHECK_PATH).send(BODY)).status).toBe(200);
|
|
133
|
+
const second = await request(app).post(CLAIM_CHECK_PATH).send(BODY);
|
|
134
|
+
expect(second.status).toBe(429);
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
it("resolves a super admin's chosen model WITHOUT rbacBypass (rbacBypass is inert in this codebase — the real gate against a non-admin naming an arbitrary model is the super-admin check, see the 403 test below)", async () => {
|
|
138
|
+
const resolveModel = jest.fn(async ({ modelId }: any) => ({ languageModel: { modelId } }) as any);
|
|
139
|
+
const { app } = buildApp({
|
|
140
|
+
resolveModel,
|
|
141
|
+
authenticate: async () => ({ user: { id: 7, type: "user", super_admin: true } as any }),
|
|
142
|
+
});
|
|
143
|
+
const res = await request(app).post(CLAIM_CHECK_PATH).send({ ...BODY, model: "caller-choice" });
|
|
144
|
+
expect(res.status).toBe(200);
|
|
145
|
+
expect(resolveModel).toHaveBeenCalledWith(expect.objectContaining({ modelId: "caller-choice" }));
|
|
146
|
+
expect(resolveModel.mock.calls[0][0].rbacBypass).toBeUndefined();
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
it("honours a super-admin caller's model override end to end", async () => {
|
|
150
|
+
const { app, runCheck } = buildApp({
|
|
151
|
+
authenticate: async () => ({ user: { id: 7, type: "user", super_admin: true } as any }),
|
|
152
|
+
});
|
|
153
|
+
const res = await request(app).post(CLAIM_CHECK_PATH).send({ ...BODY, model: "caller-choice" });
|
|
154
|
+
expect(res.status).toBe(200);
|
|
155
|
+
expect(runCheck).toHaveBeenCalledTimes(1);
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
it("403s a non-admin caller's `model` override, without resolving a model or running anything", async () => {
|
|
159
|
+
const resolveModel = jest.fn(async ({ modelId }: any) => ({ languageModel: { modelId } }) as any);
|
|
160
|
+
const { app, runCheck } = buildApp({ resolveModel });
|
|
161
|
+
const res = await request(app).post(CLAIM_CHECK_PATH).send({ ...BODY, model: "caller-choice" });
|
|
162
|
+
expect(res.status).toBe(403);
|
|
163
|
+
expect(String(res.body.detail)).toContain("super-admin");
|
|
164
|
+
expect(resolveModel).not.toHaveBeenCalled();
|
|
165
|
+
expect(runCheck).not.toHaveBeenCalled();
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
// Finding 1: a request may TIGHTEN a cap, never loosen one. Without the
|
|
169
|
+
// clamp, these three numbers would reach the engine verbatim and buy an
|
|
170
|
+
// authenticated non-admin thousands of provider calls and up to 5,000 full
|
|
171
|
+
// retrievals per request, repeatable at the limiter's 30/min.
|
|
172
|
+
it("clamps request-supplied caps down to the configured values instead of honouring them", async () => {
|
|
173
|
+
const { app, runCheck } = buildApp();
|
|
174
|
+
const res = await request(app)
|
|
175
|
+
.post(CLAIM_CHECK_PATH)
|
|
176
|
+
.send({ ...BODY, options: { caps: { maxSentences: 5000, maxClaims: 5000, maxReRetrievals: 5000 } } });
|
|
177
|
+
|
|
178
|
+
expect(res.status).toBe(200);
|
|
179
|
+
// With no agent named, `configured` is the engine default
|
|
180
|
+
// (CLAIM_CHECK_DEFAULTS.caps, via the claim_check config schema).
|
|
181
|
+
expect(runCheck.mock.calls[0][0].options.caps).toEqual({
|
|
182
|
+
maxSentences: 120,
|
|
183
|
+
maxClaims: 200,
|
|
184
|
+
maxReRetrievals: 10,
|
|
185
|
+
});
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
it("honours a request cap that is lower than the configured one", async () => {
|
|
189
|
+
const { app, runCheck } = buildApp();
|
|
190
|
+
const res = await request(app)
|
|
191
|
+
.post(CLAIM_CHECK_PATH)
|
|
192
|
+
.send({ ...BODY, options: { caps: { maxSentences: 5, maxClaims: 7, maxReRetrievals: 0 } } });
|
|
193
|
+
|
|
194
|
+
expect(res.status).toBe(200);
|
|
195
|
+
expect(runCheck.mock.calls[0][0].options.caps).toEqual({
|
|
196
|
+
maxSentences: 5,
|
|
197
|
+
maxClaims: 7,
|
|
198
|
+
maxReRetrievals: 0,
|
|
199
|
+
});
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
// R33: the module ceilings are gone. They were meant to stop a REQUEST
|
|
203
|
+
// demanding more work, but they also clamped the operator's own configured
|
|
204
|
+
// value — which is why a 44,000-character NEWLIFT answer (568 sentences
|
|
205
|
+
// after list segmentation) was 21% checked with no configuration path to
|
|
206
|
+
// raise it. An operator configuring their own agent is trusted; they pay
|
|
207
|
+
// for it.
|
|
208
|
+
it("honours a configured cap above the engine default for an agent-scoped call", async () => {
|
|
209
|
+
const agentWithRaisedCaps = {
|
|
210
|
+
id: "agent-1",
|
|
211
|
+
model: "agent-model",
|
|
212
|
+
tools: [
|
|
213
|
+
{
|
|
214
|
+
id: "agentic_context_search",
|
|
215
|
+
config: [
|
|
216
|
+
{
|
|
217
|
+
name: "claim_check",
|
|
218
|
+
type: "json",
|
|
219
|
+
variable: '{"enabled":true,"caps":{"maxSentences":600,"maxClaims":900,"maxReRetrievals":40}}',
|
|
220
|
+
},
|
|
221
|
+
],
|
|
222
|
+
},
|
|
223
|
+
],
|
|
224
|
+
};
|
|
225
|
+
const { app, runCheck } = buildApp({ getAgent: async () => agentWithRaisedCaps as any });
|
|
226
|
+
const res = await request(app).post(CLAIM_CHECK_PATH).send({ ...BODY, agent: "agent-1" });
|
|
227
|
+
|
|
228
|
+
expect(res.status).toBe(200);
|
|
229
|
+
expect(runCheck.mock.calls[0][0].options.caps).toEqual({
|
|
230
|
+
maxSentences: 600,
|
|
231
|
+
maxClaims: 900,
|
|
232
|
+
maxReRetrievals: 40,
|
|
233
|
+
});
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
it("still refuses to let a request loosen a cap the operator configured above the default", async () => {
|
|
237
|
+
const agentWithRaisedCaps = {
|
|
238
|
+
id: "agent-1",
|
|
239
|
+
model: "agent-model",
|
|
240
|
+
tools: [
|
|
241
|
+
{
|
|
242
|
+
id: "agentic_context_search",
|
|
243
|
+
config: [
|
|
244
|
+
{ name: "claim_check", type: "json", variable: '{"enabled":true,"caps":{"maxSentences":600}}' },
|
|
245
|
+
],
|
|
246
|
+
},
|
|
247
|
+
],
|
|
248
|
+
};
|
|
249
|
+
const { app, runCheck } = buildApp({ getAgent: async () => agentWithRaisedCaps as any });
|
|
250
|
+
const res = await request(app)
|
|
251
|
+
.post(CLAIM_CHECK_PATH)
|
|
252
|
+
.send({ ...BODY, agent: "agent-1", options: { caps: { maxSentences: 5000, maxClaims: 5000 } } });
|
|
253
|
+
|
|
254
|
+
expect(res.status).toBe(200);
|
|
255
|
+
expect(runCheck.mock.calls[0][0].options.caps).toEqual({
|
|
256
|
+
maxSentences: 600,
|
|
257
|
+
maxClaims: 200,
|
|
258
|
+
maxReRetrievals: 10,
|
|
259
|
+
});
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
// Finding 1: paper fidelity and voting multiply the call count, so they are
|
|
263
|
+
// gated like `model` is — our own benchmark runs with an admin key.
|
|
264
|
+
it("403s a non-admin caller asking for paper fidelity, without running anything", async () => {
|
|
265
|
+
const { app, runCheck } = buildApp();
|
|
266
|
+
const res = await request(app)
|
|
267
|
+
.post(CLAIM_CHECK_PATH)
|
|
268
|
+
.send({ ...BODY, options: { fidelity: "paper" } });
|
|
269
|
+
|
|
270
|
+
expect(res.status).toBe(403);
|
|
271
|
+
expect(String(res.body.detail)).toContain("super-admin");
|
|
272
|
+
expect(String(res.body.detail)).toContain("claim_check.fidelity");
|
|
273
|
+
expect(runCheck).not.toHaveBeenCalled();
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
it("403s a non-admin caller asking for more than one completion, without running anything", async () => {
|
|
277
|
+
const { app, runCheck } = buildApp();
|
|
278
|
+
const res = await request(app)
|
|
279
|
+
.post(CLAIM_CHECK_PATH)
|
|
280
|
+
.send({ ...BODY, options: { completions: 3 } });
|
|
281
|
+
|
|
282
|
+
expect(res.status).toBe(403);
|
|
283
|
+
expect(runCheck).not.toHaveBeenCalled();
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
it("lets a super admin ask for paper fidelity with voting", async () => {
|
|
287
|
+
const { app, runCheck } = buildApp({
|
|
288
|
+
authenticate: async () => ({ user: { id: 7, type: "user", super_admin: true } as any }),
|
|
289
|
+
});
|
|
290
|
+
const res = await request(app)
|
|
291
|
+
.post(CLAIM_CHECK_PATH)
|
|
292
|
+
.send({ ...BODY, options: { fidelity: "paper", completions: 3 } });
|
|
293
|
+
|
|
294
|
+
expect(res.status).toBe(200);
|
|
295
|
+
expect(runCheck.mock.calls[0][0].options.fidelity).toBe("paper");
|
|
296
|
+
expect(runCheck.mock.calls[0][0].options.completions).toBe(3);
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
it("falls back through claim_check.model, utility_model and the agent model", async () => {
|
|
300
|
+
const resolveModel = jest.fn(async ({ modelId }: any) => ({ languageModel: { modelId } }) as any);
|
|
301
|
+
const agentWith = (config: Record<string, string>) => ({
|
|
302
|
+
id: "agent-1",
|
|
303
|
+
model: "agent-model",
|
|
304
|
+
tools: [
|
|
305
|
+
{
|
|
306
|
+
id: "agentic_context_search",
|
|
307
|
+
config: Object.entries(config).map(([name, variable]) => ({ name, variable, type: "json" })),
|
|
308
|
+
},
|
|
309
|
+
],
|
|
310
|
+
});
|
|
311
|
+
|
|
312
|
+
const withClaimModel = buildApp({
|
|
313
|
+
resolveModel,
|
|
314
|
+
getAgent: async () => agentWith({ claim_check: '{"enabled":true,"model":"claim-model"}' }) as any,
|
|
315
|
+
});
|
|
316
|
+
await request(withClaimModel.app).post(CLAIM_CHECK_PATH).send({ ...BODY, agent: "agent-1" });
|
|
317
|
+
expect(resolveModel.mock.calls[0][0].modelId).toBe("claim-model");
|
|
318
|
+
|
|
319
|
+
resolveModel.mockClear();
|
|
320
|
+
const withUtilityModel = buildApp({
|
|
321
|
+
resolveModel,
|
|
322
|
+
getAgent: async () =>
|
|
323
|
+
agentWith({ claim_check: '{"enabled":true}', utility_model: "utility-model" }) as any,
|
|
324
|
+
});
|
|
325
|
+
await request(withUtilityModel.app).post(CLAIM_CHECK_PATH).send({ ...BODY, agent: "agent-1" });
|
|
326
|
+
expect(resolveModel.mock.calls[0][0].modelId).toBe("utility-model");
|
|
327
|
+
|
|
328
|
+
resolveModel.mockClear();
|
|
329
|
+
const withAgentModel = buildApp({
|
|
330
|
+
resolveModel,
|
|
331
|
+
// claim_check must be enabled for the agent to be usable at all, but it
|
|
332
|
+
// names no model, so resolution falls through to the agent's own model.
|
|
333
|
+
getAgent: async () => agentWith({ claim_check: '{"enabled":true}' }) as any,
|
|
334
|
+
});
|
|
335
|
+
await request(withAgentModel.app).post(CLAIM_CHECK_PATH).send({ ...BODY, agent: "agent-1" });
|
|
336
|
+
expect(resolveModel.mock.calls[0][0].modelId).toBe("agent-model");
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
it("400s naming the missing configuration when no model resolves at all", async () => {
|
|
340
|
+
const { app, runCheck } = buildApp({
|
|
341
|
+
getAgent: async () => undefined,
|
|
342
|
+
platformDefaultModel: async () => "",
|
|
343
|
+
});
|
|
344
|
+
const res = await request(app).post(CLAIM_CHECK_PATH).send(BODY);
|
|
345
|
+
expect(res.status).toBe(400);
|
|
346
|
+
// Finding 12: the message used to name a platform setting
|
|
347
|
+
// `claim_check.default_model` that does not exist in the codebase.
|
|
348
|
+
expect(String(res.body.detail)).toContain("CLAIM_CHECK_DEFAULT_MODEL");
|
|
349
|
+
expect(runCheck).not.toHaveBeenCalled();
|
|
350
|
+
});
|
|
351
|
+
|
|
352
|
+
it("403s when the API key is not scoped to the named agent", async () => {
|
|
353
|
+
const { app, runCheck } = buildApp({
|
|
354
|
+
checkApiKeyScope: () => ({ allowed: false, code: 403, reason: "key is scoped to another agent" }),
|
|
355
|
+
});
|
|
356
|
+
const res = await request(app).post(CLAIM_CHECK_PATH).send({ ...BODY, agent: "agent-1" });
|
|
357
|
+
expect(res.status).toBe(403);
|
|
358
|
+
expect(runCheck).not.toHaveBeenCalled();
|
|
359
|
+
});
|
|
360
|
+
|
|
361
|
+
it("403s when the caller cannot read the named agent", async () => {
|
|
362
|
+
const { app } = buildApp({ checkRecordAccess: async () => false });
|
|
363
|
+
const res = await request(app).post(CLAIM_CHECK_PATH).send({ ...BODY, agent: "agent-1" });
|
|
364
|
+
expect(res.status).toBe(403);
|
|
365
|
+
});
|
|
366
|
+
|
|
367
|
+
// Finding 8: cfg.claimCheck.enabled and showToExternalUsers were parsed and
|
|
368
|
+
// read nowhere, and the external limiter was missing entirely.
|
|
369
|
+
it("403s when the named agent has claim check disabled, without running anything", async () => {
|
|
370
|
+
const { app, runCheck } = buildApp({
|
|
371
|
+
getAgent: async () =>
|
|
372
|
+
({
|
|
373
|
+
id: "agent-1",
|
|
374
|
+
model: "agent-model",
|
|
375
|
+
tools: [
|
|
376
|
+
{
|
|
377
|
+
id: "agentic_context_search",
|
|
378
|
+
config: [{ name: "claim_check", type: "json", variable: '{"enabled":false}' }],
|
|
379
|
+
},
|
|
380
|
+
],
|
|
381
|
+
}) as any,
|
|
382
|
+
});
|
|
383
|
+
const res = await request(app).post(CLAIM_CHECK_PATH).send({ ...BODY, agent: "agent-1" });
|
|
384
|
+
expect(res.status).toBe(403);
|
|
385
|
+
expect(String(res.body.detail)).toContain("claim_check.enabled");
|
|
386
|
+
expect(runCheck).not.toHaveBeenCalled();
|
|
387
|
+
});
|
|
388
|
+
|
|
389
|
+
it("403s an external caller when the agent does not show claim check to external users", async () => {
|
|
390
|
+
const agentWithClaimCheck = (variable: string) =>
|
|
391
|
+
({
|
|
392
|
+
id: "agent-1",
|
|
393
|
+
model: "agent-model",
|
|
394
|
+
tools: [{ id: "agentic_context_search", config: [{ name: "claim_check", type: "json", variable }] }],
|
|
395
|
+
}) as any;
|
|
396
|
+
const external = {
|
|
397
|
+
authenticate: async () => ({ user: { id: 9, type: "user", role: { name: "external" } } as any }),
|
|
398
|
+
};
|
|
399
|
+
|
|
400
|
+
const hidden = buildApp({ ...external, getAgent: async () => agentWithClaimCheck('{"enabled":true}') });
|
|
401
|
+
const res = await request(hidden.app).post(CLAIM_CHECK_PATH).send({ ...BODY, agent: "agent-1" });
|
|
402
|
+
expect(res.status).toBe(403);
|
|
403
|
+
expect(String(res.body.detail)).toContain("showToExternalUsers");
|
|
404
|
+
expect(hidden.runCheck).not.toHaveBeenCalled();
|
|
405
|
+
|
|
406
|
+
// With the flag on, the same external caller is served.
|
|
407
|
+
const shown = buildApp({
|
|
408
|
+
...external,
|
|
409
|
+
getAgent: async () => agentWithClaimCheck('{"enabled":true,"showToExternalUsers":true}'),
|
|
410
|
+
});
|
|
411
|
+
const allowed = await request(shown.app).post(CLAIM_CHECK_PATH).send({ ...BODY, agent: "agent-1" });
|
|
412
|
+
expect(allowed.status).toBe(200);
|
|
413
|
+
expect(shown.runCheck).toHaveBeenCalledTimes(1);
|
|
414
|
+
});
|
|
415
|
+
|
|
416
|
+
// Fix round 1, Important 1: a signed-in INTERNAL user (no external role) on
|
|
417
|
+
// the public surface renders in guest mode, so must be refused the same way
|
|
418
|
+
// an external role is — the chat's finish-part fragment applies the same rule.
|
|
419
|
+
it("403s a signed-in internal user on the public surface when the agent does not show claim check to external users", async () => {
|
|
420
|
+
const agentWithClaimCheck = (variable: string) =>
|
|
421
|
+
({
|
|
422
|
+
id: "agent-1",
|
|
423
|
+
model: "agent-model",
|
|
424
|
+
tools: [{ id: "agentic_context_search", config: [{ name: "claim_check", type: "json", variable }] }],
|
|
425
|
+
}) as any;
|
|
426
|
+
// Internal: id set, no external role — would pass isExternalOrAnonymousUser.
|
|
427
|
+
const internalOnPublicSurface = {
|
|
428
|
+
authenticate: async () => ({ user: { id: 9, type: "user" } as any }),
|
|
429
|
+
};
|
|
430
|
+
|
|
431
|
+
const hidden = buildApp({ ...internalOnPublicSurface, getAgent: async () => agentWithClaimCheck('{"enabled":true}') });
|
|
432
|
+
const res = await request(hidden.app)
|
|
433
|
+
.post(CLAIM_CHECK_PATH)
|
|
434
|
+
.set(PUBLIC_SURFACE_HEADER, "1")
|
|
435
|
+
.send({ ...BODY, agent: "agent-1" });
|
|
436
|
+
expect(res.status).toBe(403);
|
|
437
|
+
expect(String(res.body.detail)).toContain("showToExternalUsers");
|
|
438
|
+
expect(hidden.runCheck).not.toHaveBeenCalled();
|
|
439
|
+
|
|
440
|
+
// With the flag on, the same signed-in internal user on the public
|
|
441
|
+
// surface is served.
|
|
442
|
+
const shown = buildApp({
|
|
443
|
+
...internalOnPublicSurface,
|
|
444
|
+
getAgent: async () => agentWithClaimCheck('{"enabled":true,"showToExternalUsers":true}'),
|
|
445
|
+
});
|
|
446
|
+
const allowed = await request(shown.app)
|
|
447
|
+
.post(CLAIM_CHECK_PATH)
|
|
448
|
+
.set(PUBLIC_SURFACE_HEADER, "1")
|
|
449
|
+
.send({ ...BODY, agent: "agent-1" });
|
|
450
|
+
expect(allowed.status).toBe(200);
|
|
451
|
+
expect(shown.runCheck).toHaveBeenCalledTimes(1);
|
|
452
|
+
|
|
453
|
+
// And off the public surface, the same user is unaffected.
|
|
454
|
+
const normal = buildApp({ ...internalOnPublicSurface, getAgent: async () => agentWithClaimCheck('{"enabled":true}') });
|
|
455
|
+
const notPublic = await request(normal.app).post(CLAIM_CHECK_PATH).send({ ...BODY, agent: "agent-1" });
|
|
456
|
+
expect(notPublic.status).toBe(200);
|
|
457
|
+
expect(normal.runCheck).toHaveBeenCalledTimes(1);
|
|
458
|
+
});
|
|
459
|
+
|
|
460
|
+
it("429s an external caller over the external rate-limit budget, before any model work", async () => {
|
|
461
|
+
const resolveModel = jest.fn(async ({ modelId }: any) => ({ languageModel: { modelId } }) as any);
|
|
462
|
+
const externalRateLimitExceeded = jest.fn(() => true);
|
|
463
|
+
const { app, runCheck } = buildApp({
|
|
464
|
+
resolveModel,
|
|
465
|
+
isExternalUser: () => true,
|
|
466
|
+
externalRateLimitExceeded,
|
|
467
|
+
});
|
|
468
|
+
const res = await request(app).post(CLAIM_CHECK_PATH).send(BODY);
|
|
469
|
+
expect(res.status).toBe(429);
|
|
470
|
+
expect(externalRateLimitExceeded).toHaveBeenCalledWith("7");
|
|
471
|
+
expect(resolveModel).not.toHaveBeenCalled();
|
|
472
|
+
expect(runCheck).not.toHaveBeenCalled();
|
|
473
|
+
});
|
|
474
|
+
|
|
475
|
+
it("does not consult the external budget for an internal caller", async () => {
|
|
476
|
+
const externalRateLimitExceeded = jest.fn(() => true);
|
|
477
|
+
const { app } = buildApp({ isExternalUser: () => false, externalRateLimitExceeded });
|
|
478
|
+
const res = await request(app).post(CLAIM_CHECK_PATH).send(BODY);
|
|
479
|
+
expect(res.status).toBe(200);
|
|
480
|
+
expect(externalRateLimitExceeded).not.toHaveBeenCalled();
|
|
481
|
+
});
|
|
482
|
+
|
|
483
|
+
// Finding 14: an unusable locale used to reach new Intl.Segmenter inside the
|
|
484
|
+
// engine and throw into its outer catch, so garbage yielded 200 plus an
|
|
485
|
+
// empty partial result instead of a 400.
|
|
486
|
+
it("400s an unusable locale at the edge, without running the engine", async () => {
|
|
487
|
+
const { app, runCheck } = buildApp();
|
|
488
|
+
const res = await request(app).post(CLAIM_CHECK_PATH).send({ ...BODY, locale: "💥not-a-locale💥" });
|
|
489
|
+
expect(res.status).toBe(400);
|
|
490
|
+
expect(String(res.body.detail)).toContain("locale");
|
|
491
|
+
expect(runCheck).not.toHaveBeenCalled();
|
|
492
|
+
|
|
493
|
+
const ok = await request(app).post(CLAIM_CHECK_PATH).send({ ...BODY, locale: "de" });
|
|
494
|
+
expect(ok.status).toBe(200);
|
|
495
|
+
});
|
|
496
|
+
|
|
497
|
+
// Finding 14: warn above alert labels everything "alert", which reads as a
|
|
498
|
+
// hallucination finding. It is refused, not applied.
|
|
499
|
+
it("400s when the resolved thresholds have warn above alert", async () => {
|
|
500
|
+
const { app, runCheck } = buildApp();
|
|
501
|
+
const res = await request(app)
|
|
502
|
+
.post(CLAIM_CHECK_PATH)
|
|
503
|
+
.send({ ...BODY, options: { thresholds: { warn: 0.5, alert: 0.3 } } });
|
|
504
|
+
expect(res.status).toBe(400);
|
|
505
|
+
expect(String(res.body.detail)).toContain("thresholds.warn");
|
|
506
|
+
expect(runCheck).not.toHaveBeenCalled();
|
|
507
|
+
|
|
508
|
+
// Equal values are fine: everything at or above alert is "alert".
|
|
509
|
+
const equal = await request(app)
|
|
510
|
+
.post(CLAIM_CHECK_PATH)
|
|
511
|
+
.send({ ...BODY, options: { thresholds: { warn: 0.3, alert: 0.3 } } });
|
|
512
|
+
expect(equal.status).toBe(200);
|
|
513
|
+
});
|
|
514
|
+
|
|
515
|
+
it("400s when a request warn exceeds the agent's configured alert", async () => {
|
|
516
|
+
const { app } = buildApp({
|
|
517
|
+
getAgent: async () =>
|
|
518
|
+
({
|
|
519
|
+
id: "agent-1",
|
|
520
|
+
model: "agent-model",
|
|
521
|
+
tools: [
|
|
522
|
+
{
|
|
523
|
+
id: "agentic_context_search",
|
|
524
|
+
config: [
|
|
525
|
+
{
|
|
526
|
+
name: "claim_check",
|
|
527
|
+
type: "json",
|
|
528
|
+
variable: '{"enabled":true,"showToExternalUsers":true,"thresholds":{"warn":0.1,"alert":0.2}}',
|
|
529
|
+
},
|
|
530
|
+
],
|
|
531
|
+
},
|
|
532
|
+
],
|
|
533
|
+
}) as any,
|
|
534
|
+
});
|
|
535
|
+
const res = await request(app)
|
|
536
|
+
.post(CLAIM_CHECK_PATH)
|
|
537
|
+
.send({ ...BODY, agent: "agent-1", options: { thresholds: { warn: 0.4 } } });
|
|
538
|
+
expect(res.status).toBe(400);
|
|
539
|
+
});
|
|
540
|
+
|
|
541
|
+
// Finding 14: a malformed agent id makes the lookup throw rather than return
|
|
542
|
+
// undefined, which surfaced as a 500 outside any try/catch.
|
|
543
|
+
it("404s a malformed agent id instead of 500ing", async () => {
|
|
544
|
+
const warnSpy = jest.spyOn(console, "warn").mockImplementation(() => {});
|
|
545
|
+
const { app, runCheck } = buildApp({
|
|
546
|
+
getAgent: async () => {
|
|
547
|
+
throw new Error('invalid input syntax for type uuid: "not-a-uuid"');
|
|
548
|
+
},
|
|
549
|
+
});
|
|
550
|
+
const res = await request(app).post(CLAIM_CHECK_PATH).send({ ...BODY, agent: "not-a-uuid" });
|
|
551
|
+
expect(res.status).toBe(404);
|
|
552
|
+
expect(String(res.body.detail)).toContain("not found");
|
|
553
|
+
expect(runCheck).not.toHaveBeenCalled();
|
|
554
|
+
warnSpy.mockRestore();
|
|
555
|
+
});
|
|
556
|
+
|
|
557
|
+
it("passes a partial engine result through with 200", async () => {
|
|
558
|
+
const { app } = buildApp({
|
|
559
|
+
runCheck: jest.fn().mockResolvedValue({ ...RESULT, status: "partial", notes: ["selection aborted"] }),
|
|
560
|
+
});
|
|
561
|
+
const res = await request(app).post(CLAIM_CHECK_PATH).send(BODY);
|
|
562
|
+
expect(res.status).toBe(200);
|
|
563
|
+
expect(res.body.status).toBe("partial");
|
|
564
|
+
expect(res.body.notes).toEqual(["selection aborted"]);
|
|
565
|
+
});
|
|
566
|
+
|
|
567
|
+
// Finding 7: spec §4 mandates a 60 s request timeout, and there was none
|
|
568
|
+
// anywhere in the module — a hung provider held one of the twenty global
|
|
569
|
+
// in-flight slots until the transport gave up, and twenty such requests
|
|
570
|
+
// 429 the endpoint deployment-wide.
|
|
571
|
+
it("504s a check that outlives the deadline, releases the slot and aborts the engine's signal", async () => {
|
|
572
|
+
const warnSpy = jest.spyOn(console, "warn").mockImplementation(() => {});
|
|
573
|
+
// Only setTimeout/clearTimeout are faked: faking setImmediate, nextTick or
|
|
574
|
+
// queueMicrotask stalls Node's HTTP server and supertest never connects.
|
|
575
|
+
jest.useFakeTimers({
|
|
576
|
+
doNotFake: [
|
|
577
|
+
"Date", "hrtime", "nextTick", "performance", "queueMicrotask",
|
|
578
|
+
"requestAnimationFrame", "cancelAnimationFrame", "requestIdleCallback",
|
|
579
|
+
"cancelIdleCallback", "setImmediate", "clearImmediate", "setInterval", "clearInterval",
|
|
580
|
+
],
|
|
581
|
+
});
|
|
582
|
+
try {
|
|
583
|
+
let reached!: () => void;
|
|
584
|
+
const started = new Promise<void>((resolve) => {
|
|
585
|
+
reached = resolve;
|
|
586
|
+
});
|
|
587
|
+
let signal: AbortSignal | undefined;
|
|
588
|
+
const runCheck = jest.fn((args: any) => {
|
|
589
|
+
signal = args.signal;
|
|
590
|
+
reached();
|
|
591
|
+
return new Promise(() => {}) as Promise<any>;
|
|
592
|
+
});
|
|
593
|
+
const limiter = claimCheckRateLimiter({ perMinute: 100, perHour: 1000, maxInFlight: 1 });
|
|
594
|
+
const { app } = buildApp({ runCheck, limiter });
|
|
595
|
+
|
|
596
|
+
// .end() dispatches immediately and delivers the response through a
|
|
597
|
+
// callback; superagent's promise form is lazy AND defers through
|
|
598
|
+
// setTimeout, so it would never settle while the clock is faked.
|
|
599
|
+
const pending = new Promise<{ status: number; body: any }>((resolve, reject) => {
|
|
600
|
+
request(app)
|
|
601
|
+
.post(CLAIM_CHECK_PATH)
|
|
602
|
+
.send(BODY)
|
|
603
|
+
.end((err, r) => (err ? reject(err) : resolve(r)));
|
|
604
|
+
});
|
|
605
|
+
await started;
|
|
606
|
+
expect(signal!.aborted).toBe(false);
|
|
607
|
+
|
|
608
|
+
await jest.advanceTimersByTimeAsync(CLAIM_CHECK_TIMEOUT_MS);
|
|
609
|
+
// Back to real timers before reading the response: superagent defers its
|
|
610
|
+
// own callbacks through setTimeout, which would never fire while faked.
|
|
611
|
+
jest.useRealTimers();
|
|
612
|
+
const res = await pending;
|
|
613
|
+
|
|
614
|
+
expect(res.status).toBe(504);
|
|
615
|
+
expect(String(res.body.detail)).toContain("60 seconds");
|
|
616
|
+
// The engine's provider calls are cancelled, not left running.
|
|
617
|
+
expect(signal!.aborted).toBe(true);
|
|
618
|
+
// The in-flight slot was released on the timeout path too: maxInFlight
|
|
619
|
+
// is 1, so an unreleased slot would make the next take() fail. (A second
|
|
620
|
+
// HTTP request cannot test this here — this app's runCheck never
|
|
621
|
+
// settles, so the request would simply hang.)
|
|
622
|
+
expect(limiter.take("7").ok).toBe(true);
|
|
623
|
+
} finally {
|
|
624
|
+
jest.useRealTimers();
|
|
625
|
+
warnSpy.mockRestore();
|
|
626
|
+
}
|
|
627
|
+
});
|
|
628
|
+
|
|
629
|
+
// Fix round 2, parked item 6: this used to `await` supertest's PROMISE form
|
|
630
|
+
// while setTimeout was faked. Superagent defers its own callbacks through
|
|
631
|
+
// setTimeout, so settling that promise depended on a faked timer nobody
|
|
632
|
+
// advanced — it passed only because of how node happened to schedule the
|
|
633
|
+
// response, and flaked under load. A known flake in the suite that proves
|
|
634
|
+
// the 429/413/403 gates on the most expensive endpoint in the product
|
|
635
|
+
// trains people to re-run it, which is how a real failure gets re-run away.
|
|
636
|
+
//
|
|
637
|
+
// The fix removes the dependency instead of hiding it: dispatch with
|
|
638
|
+
// `.end()` (immediate, callback-delivered), wait on a signal the HANDLER
|
|
639
|
+
// raises — limiter.release(), which runs in its `finally` immediately after
|
|
640
|
+
// `clearTimeout(deadline)` — and only then read the timer count. Nothing in
|
|
641
|
+
// the test waits for a faked timer, so there is nothing left to race.
|
|
642
|
+
// Request delivery itself needs no timers (it is socket I/O, which fake
|
|
643
|
+
// timers do not touch); the 504 test above already relies on that.
|
|
644
|
+
it("does not time out a check that finishes in time, and clears its timer", async () => {
|
|
645
|
+
const inner = claimCheckRateLimiter({ perMinute: 100, perHour: 1000, maxInFlight: 10 });
|
|
646
|
+
let handlerFinished!: () => void;
|
|
647
|
+
const released = new Promise<void>((resolve) => (handlerFinished = resolve));
|
|
648
|
+
const limiter = {
|
|
649
|
+
...inner,
|
|
650
|
+
release: () => {
|
|
651
|
+
inner.release();
|
|
652
|
+
handlerFinished();
|
|
653
|
+
},
|
|
654
|
+
};
|
|
655
|
+
|
|
656
|
+
jest.useFakeTimers({
|
|
657
|
+
doNotFake: [
|
|
658
|
+
"Date", "hrtime", "nextTick", "performance", "queueMicrotask",
|
|
659
|
+
"requestAnimationFrame", "cancelAnimationFrame", "requestIdleCallback",
|
|
660
|
+
"cancelIdleCallback", "setImmediate", "clearImmediate", "setInterval", "clearInterval",
|
|
661
|
+
],
|
|
662
|
+
});
|
|
663
|
+
try {
|
|
664
|
+
const { app } = buildApp({ limiter });
|
|
665
|
+
const pending = new Promise<{ status: number }>((resolve, reject) => {
|
|
666
|
+
request(app)
|
|
667
|
+
.post(CLAIM_CHECK_PATH)
|
|
668
|
+
.send(BODY)
|
|
669
|
+
.end((err, r) => (err ? reject(err) : resolve(r)));
|
|
670
|
+
});
|
|
671
|
+
|
|
672
|
+
// The handler has run to completion: its finally block cleared the
|
|
673
|
+
// deadline and then released the slot, which is what resolves this.
|
|
674
|
+
await released;
|
|
675
|
+
// ...so no deadline timer is left behind. (Read while timers are still
|
|
676
|
+
// faked — getTimerCount only sees the fake clock.)
|
|
677
|
+
expect(jest.getTimerCount()).toBe(0);
|
|
678
|
+
|
|
679
|
+
// Back to real timers before reading the response: superagent defers
|
|
680
|
+
// its own callbacks through setTimeout, which would never fire while
|
|
681
|
+
// faked.
|
|
682
|
+
jest.useRealTimers();
|
|
683
|
+
expect((await pending).status).toBe(200);
|
|
684
|
+
} finally {
|
|
685
|
+
jest.useRealTimers();
|
|
686
|
+
}
|
|
687
|
+
});
|
|
688
|
+
|
|
689
|
+
// Finding 2: the docs tell a tenant who wants full coverage of a long
|
|
690
|
+
// answer to raise claim_check.caps.maxSentences, but the 60s deadline was a
|
|
691
|
+
// hard constant — raising the cap without raising this just moves the
|
|
692
|
+
// 504 later, after more calls were spent. The deadline now reads
|
|
693
|
+
// CLAIM_CHECK_TIMEOUT_MS so an operator can size both together.
|
|
694
|
+
it("races the deadline from CLAIM_CHECK_TIMEOUT_MS instead of the hardcoded 60s default", async () => {
|
|
695
|
+
const warnSpy = jest.spyOn(console, "warn").mockImplementation(() => {});
|
|
696
|
+
const originalEnv = process.env.CLAIM_CHECK_TIMEOUT_MS;
|
|
697
|
+
process.env.CLAIM_CHECK_TIMEOUT_MS = "500";
|
|
698
|
+
jest.useFakeTimers({
|
|
699
|
+
doNotFake: [
|
|
700
|
+
"Date", "hrtime", "nextTick", "performance", "queueMicrotask",
|
|
701
|
+
"requestAnimationFrame", "cancelAnimationFrame", "requestIdleCallback",
|
|
702
|
+
"cancelIdleCallback", "setImmediate", "clearImmediate", "setInterval", "clearInterval",
|
|
703
|
+
],
|
|
704
|
+
});
|
|
705
|
+
try {
|
|
706
|
+
let signal: AbortSignal | undefined;
|
|
707
|
+
const runCheck = jest.fn((args: any) => {
|
|
708
|
+
signal = args.signal;
|
|
709
|
+
return new Promise(() => {}) as Promise<any>;
|
|
710
|
+
});
|
|
711
|
+
const limiter = claimCheckRateLimiter({ perMinute: 100, perHour: 1000, maxInFlight: 1 });
|
|
712
|
+
const { app } = buildApp({ runCheck, limiter });
|
|
713
|
+
|
|
714
|
+
const pending = new Promise<{ status: number; body: any }>((resolve, reject) => {
|
|
715
|
+
request(app)
|
|
716
|
+
.post(CLAIM_CHECK_PATH)
|
|
717
|
+
.send(BODY)
|
|
718
|
+
.end((err, r) => (err ? reject(err) : resolve(r)));
|
|
719
|
+
});
|
|
720
|
+
|
|
721
|
+
// The env-configured 500ms deadline has not elapsed yet — this would
|
|
722
|
+
// still be well inside the hardcoded 60,000ms default too, so it only
|
|
723
|
+
// proves the request is still pending, not which deadline is active.
|
|
724
|
+
await jest.advanceTimersByTimeAsync(400);
|
|
725
|
+
expect(signal?.aborted).toBeFalsy();
|
|
726
|
+
|
|
727
|
+
// Crossing 500ms (but nowhere near 60,000ms) must trigger the timeout:
|
|
728
|
+
// this is the assertion that fails if the module ignores the env var
|
|
729
|
+
// and keeps racing the 60s constant.
|
|
730
|
+
await jest.advanceTimersByTimeAsync(100);
|
|
731
|
+
jest.useRealTimers();
|
|
732
|
+
const res = await pending;
|
|
733
|
+
|
|
734
|
+
expect(res.status).toBe(504);
|
|
735
|
+
expect(String(res.body.detail)).toContain("0.5 seconds");
|
|
736
|
+
expect(signal!.aborted).toBe(true);
|
|
737
|
+
} finally {
|
|
738
|
+
jest.useRealTimers();
|
|
739
|
+
if (originalEnv === undefined) delete process.env.CLAIM_CHECK_TIMEOUT_MS;
|
|
740
|
+
else process.env.CLAIM_CHECK_TIMEOUT_MS = originalEnv;
|
|
741
|
+
warnSpy.mockRestore();
|
|
742
|
+
}
|
|
743
|
+
});
|
|
744
|
+
|
|
745
|
+
it("500s and releases the limiter slot when the engine throws", async () => {
|
|
746
|
+
const errorSpy = jest.spyOn(console, "error").mockImplementation(() => {});
|
|
747
|
+
const limiter = claimCheckRateLimiter({ perMinute: 2, perHour: 10, maxInFlight: 1 });
|
|
748
|
+
const { app } = buildApp({ limiter, runCheck: jest.fn().mockRejectedValue(new Error("engine exploded")) });
|
|
749
|
+
expect((await request(app).post(CLAIM_CHECK_PATH).send(BODY)).status).toBe(500);
|
|
750
|
+
// The slot was released, so the next request is not blocked by maxInFlight.
|
|
751
|
+
const second = await request(app).post(CLAIM_CHECK_PATH).send(BODY);
|
|
752
|
+
expect(second.status).toBe(500);
|
|
753
|
+
errorSpy.mockRestore();
|
|
754
|
+
});
|
|
755
|
+
});
|
|
756
|
+
|
|
757
|
+
// Stage 4, Task B2: `content` is the only required field on a source. `id`
|
|
758
|
+
// becomes optional and positional, `type` is accepted but dropped before the
|
|
759
|
+
// engine sees it, and two sources naming the same id are a 400, not a merge.
|
|
760
|
+
describe("source normalisation", () => {
|
|
761
|
+
it("accepts a source with only content, and assigns it a positional id", async () => {
|
|
762
|
+
const runCheck = jest.fn().mockResolvedValue(RESULT);
|
|
763
|
+
const { app } = buildApp({ runCheck });
|
|
764
|
+
await post(app, { question: "q", answer: "a", sources: [{ content: "230 Volt." }] }).expect(200);
|
|
765
|
+
expect(runCheck.mock.calls[0][0].sources).toEqual([{ id: "s1", content: "230 Volt." }]);
|
|
766
|
+
});
|
|
767
|
+
|
|
768
|
+
it("accepts a `type` on the request without passing it to the engine", async () => {
|
|
769
|
+
const runCheck = jest.fn().mockResolvedValue(RESULT);
|
|
770
|
+
const { app } = buildApp({ runCheck });
|
|
771
|
+
await post(app, {
|
|
772
|
+
question: "q", answer: "a",
|
|
773
|
+
sources: [{ id: "memory:m_7", name: "Sprache", type: "memory", content: "Deutsch." }],
|
|
774
|
+
}).expect(200);
|
|
775
|
+
expect(runCheck.mock.calls[0][0].sources).toEqual([{ id: "memory:m_7", name: "Sprache", content: "Deutsch." }]);
|
|
776
|
+
});
|
|
777
|
+
|
|
778
|
+
it("does not let a generated id collide with one the caller supplied", async () => {
|
|
779
|
+
const runCheck = jest.fn().mockResolvedValue(RESULT);
|
|
780
|
+
const { app } = buildApp({ runCheck });
|
|
781
|
+
await post(app, { question: "q", answer: "a", sources: [{ content: "first" }, { id: "s1", content: "second" }] }).expect(200);
|
|
782
|
+
const ids = runCheck.mock.calls[0][0].sources.map((s: { id: string }) => s.id);
|
|
783
|
+
expect(new Set(ids).size).toBe(2);
|
|
784
|
+
expect(ids).toContain("s1");
|
|
785
|
+
});
|
|
786
|
+
|
|
787
|
+
// Review Focus 5
|
|
788
|
+
it("rejects two sources that supply the same id rather than merging them", async () => {
|
|
789
|
+
const { app } = buildApp({});
|
|
790
|
+
const res = await post(app, {
|
|
791
|
+
question: "q", answer: "a",
|
|
792
|
+
sources: [{ id: "doc", content: "one" }, { id: "doc", content: "two" }],
|
|
793
|
+
}).expect(400);
|
|
794
|
+
expect(res.body.detail).toMatch(/duplicate source id/i);
|
|
795
|
+
});
|
|
796
|
+
|
|
797
|
+
// Fix round 1: `type` is purely informational (spec §2, no trust tiers) and
|
|
798
|
+
// the pre-change schema didn't know about it at all — zod's default object
|
|
799
|
+
// parsing silently stripped it and answered 200. Rejecting a mislabeled
|
|
800
|
+
// value here would turn that pre-existing 200 into a 400 over a field
|
|
801
|
+
// nothing downstream reads, which is a tightening this loosening-only task
|
|
802
|
+
// must not introduce. So an unrecognised value falls back to `undefined`
|
|
803
|
+
// (schema's `.catch`), not a validation error.
|
|
804
|
+
it("ignores an unknown source type instead of rejecting the request", async () => {
|
|
805
|
+
const runCheck = jest.fn().mockResolvedValue(RESULT);
|
|
806
|
+
const { app } = buildApp({ runCheck });
|
|
807
|
+
await post(app, { question: "q", answer: "a", sources: [{ content: "x", type: "guesswork" }] }).expect(200);
|
|
808
|
+
expect(runCheck.mock.calls[0][0].sources).toEqual([{ id: "s1", content: "x" }]);
|
|
809
|
+
});
|
|
810
|
+
|
|
811
|
+
it("still accepts the Stage 1 shape, id and all", async () => {
|
|
812
|
+
const runCheck = jest.fn().mockResolvedValue(RESULT);
|
|
813
|
+
const { app } = buildApp({ runCheck });
|
|
814
|
+
await post(app, { question: "q", answer: "a", sources: [{ id: "i1", name: "h.pdf", content: "x" }] }).expect(200);
|
|
815
|
+
expect(runCheck.mock.calls[0][0].sources[0].id).toBe("i1");
|
|
816
|
+
});
|
|
817
|
+
});
|
|
818
|
+
|
|
819
|
+
describe("resolveClaimCheckTimeoutMs", () => {
|
|
820
|
+
const originalEnv = process.env.CLAIM_CHECK_TIMEOUT_MS;
|
|
821
|
+
|
|
822
|
+
afterEach(() => {
|
|
823
|
+
if (originalEnv === undefined) delete process.env.CLAIM_CHECK_TIMEOUT_MS;
|
|
824
|
+
else process.env.CLAIM_CHECK_TIMEOUT_MS = originalEnv;
|
|
825
|
+
});
|
|
826
|
+
|
|
827
|
+
it("falls back to the 60s default when the env var is unset", () => {
|
|
828
|
+
delete process.env.CLAIM_CHECK_TIMEOUT_MS;
|
|
829
|
+
expect(resolveClaimCheckTimeoutMs()).toBe(CLAIM_CHECK_TIMEOUT_MS);
|
|
830
|
+
});
|
|
831
|
+
|
|
832
|
+
it("reads a valid positive value from the env var", () => {
|
|
833
|
+
process.env.CLAIM_CHECK_TIMEOUT_MS = "120000";
|
|
834
|
+
expect(resolveClaimCheckTimeoutMs()).toBe(120_000);
|
|
835
|
+
});
|
|
836
|
+
|
|
837
|
+
// The deadline must never be disabled: a cap raise without a matching
|
|
838
|
+
// deadline raise is strictly worse than the default's own "partial"
|
|
839
|
+
// degradation, so garbage input has to land back on a real, finite
|
|
840
|
+
// deadline rather than NaN (which never fires) or a negative/zero value
|
|
841
|
+
// (which fires immediately or not at all).
|
|
842
|
+
it.each([
|
|
843
|
+
["non-numeric", "not-a-number"],
|
|
844
|
+
["empty string", ""],
|
|
845
|
+
["zero", "0"],
|
|
846
|
+
["negative", "-5000"],
|
|
847
|
+
["a numeric prefix followed by garbage", "5000ms"],
|
|
848
|
+
])("falls back to the default for a %s value", (_label, raw) => {
|
|
849
|
+
process.env.CLAIM_CHECK_TIMEOUT_MS = raw;
|
|
850
|
+
expect(resolveClaimCheckTimeoutMs()).toBe(CLAIM_CHECK_TIMEOUT_MS);
|
|
851
|
+
});
|
|
852
|
+
});
|
|
853
|
+
|
|
854
|
+
describe("persistence", () => {
|
|
855
|
+
it("stores the result when the request names a session and a message", async () => {
|
|
856
|
+
const saveClaimCheck = jest.fn().mockResolvedValue(undefined);
|
|
857
|
+
const { app } = buildApp({ saveClaimCheck });
|
|
858
|
+
const res = await request(app)
|
|
859
|
+
.post(CLAIM_CHECK_PATH)
|
|
860
|
+
.send({ ...BODY, session: "11111111-1111-4111-8111-111111111111", messageId: "msg_1" });
|
|
861
|
+
expect(res.status).toBe(200);
|
|
862
|
+
expect(saveClaimCheck).toHaveBeenCalledTimes(1);
|
|
863
|
+
expect(saveClaimCheck.mock.calls[0][0]).toEqual(
|
|
864
|
+
expect.objectContaining({ session: "11111111-1111-4111-8111-111111111111", messageId: "msg_1", userId: 7 }),
|
|
865
|
+
);
|
|
866
|
+
});
|
|
867
|
+
|
|
868
|
+
it("does not store anything when the request names no session", async () => {
|
|
869
|
+
const saveClaimCheck = jest.fn();
|
|
870
|
+
const { app } = buildApp({ saveClaimCheck });
|
|
871
|
+
expect((await request(app).post(CLAIM_CHECK_PATH).send(BODY)).status).toBe(200);
|
|
872
|
+
expect(saveClaimCheck).not.toHaveBeenCalled();
|
|
873
|
+
});
|
|
874
|
+
|
|
875
|
+
it("still answers 200 when the write fails — a lost panel must not fail the check", async () => {
|
|
876
|
+
const warn = jest.spyOn(console, "warn").mockImplementation(() => {});
|
|
877
|
+
try {
|
|
878
|
+
const { app } = buildApp({ saveClaimCheck: jest.fn().mockRejectedValue(new Error("db down")) });
|
|
879
|
+
const res = await request(app)
|
|
880
|
+
.post(CLAIM_CHECK_PATH)
|
|
881
|
+
.send({ ...BODY, session: "11111111-1111-4111-8111-111111111111", messageId: "msg_1" });
|
|
882
|
+
expect(res.status).toBe(200);
|
|
883
|
+
expect(res.body.score.label).toBe("ok");
|
|
884
|
+
} finally {
|
|
885
|
+
warn.mockRestore();
|
|
886
|
+
}
|
|
887
|
+
});
|
|
888
|
+
|
|
889
|
+
// Review Focus 3
|
|
890
|
+
it("calls saveClaimCheck again, with the same key, for a repeated check on the same message", async () => {
|
|
891
|
+
const saveClaimCheck = jest.fn().mockResolvedValue(undefined);
|
|
892
|
+
const { app } = buildApp({ saveClaimCheck });
|
|
893
|
+
const body = { ...BODY, session: "11111111-1111-4111-8111-111111111111", messageId: "msg_1" };
|
|
894
|
+
await request(app).post(CLAIM_CHECK_PATH).send(body);
|
|
895
|
+
await request(app).post(CLAIM_CHECK_PATH).send(body);
|
|
896
|
+
expect(saveClaimCheck).toHaveBeenCalledTimes(2);
|
|
897
|
+
// This only proves the handler calls the dep again with the same
|
|
898
|
+
// (session, messageId) key on a repeat — it says nothing about whether
|
|
899
|
+
// the row is actually replaced rather than duplicated. That guarantee is
|
|
900
|
+
// the dep's own contract (upsert by (session, message_id, user), never a
|
|
901
|
+
// delete) and is proven against a real query builder in
|
|
902
|
+
// src/exulu/claim-check/store.test.ts, not here.
|
|
903
|
+
expect(saveClaimCheck.mock.calls[1][0].messageId).toBe("msg_1");
|
|
904
|
+
});
|
|
905
|
+
|
|
906
|
+
it("does not store anything when the named session is not a uuid", async () => {
|
|
907
|
+
const saveClaimCheck = jest.fn();
|
|
908
|
+
const { app } = buildApp({ saveClaimCheck });
|
|
909
|
+
const res = await request(app)
|
|
910
|
+
.post(CLAIM_CHECK_PATH)
|
|
911
|
+
.send({ ...BODY, session: "not-a-uuid", messageId: "msg_1" });
|
|
912
|
+
expect(res.status).toBe(200);
|
|
913
|
+
expect(saveClaimCheck).not.toHaveBeenCalled();
|
|
914
|
+
});
|
|
915
|
+
});
|
|
916
|
+
|
|
917
|
+
// Fix round 2, Important 5: §5.2's Redis result cache was deferred from stage
|
|
918
|
+
// 1 because "nothing fires a check repeatedly until the chat surface exists" —
|
|
919
|
+
// a rationale this branch expires. The stored row was never consulted, so a
|
|
920
|
+
// double-fire, a user-initiated re-check or a retry after a transport hiccup
|
|
921
|
+
// paid ~8 provider calls again for a verdict already on disk.
|
|
922
|
+
describe("stored-result lookup", () => {
|
|
923
|
+
const SESSION = "11111111-1111-4111-8111-111111111111";
|
|
924
|
+
const stored = { ...BODY, session: SESSION, messageId: "msg_1" };
|
|
925
|
+
|
|
926
|
+
it("returns the stored check and never runs the engine", async () => {
|
|
927
|
+
const findClaimCheck = jest.fn().mockResolvedValue(RESULT);
|
|
928
|
+
const saveClaimCheck = jest.fn();
|
|
929
|
+
const { app, runCheck } = buildApp({ findClaimCheck, saveClaimCheck });
|
|
930
|
+
const res = await request(app).post(CLAIM_CHECK_PATH).send(stored);
|
|
931
|
+
|
|
932
|
+
expect(res.status).toBe(200);
|
|
933
|
+
expect(res.body).toEqual(RESULT);
|
|
934
|
+
expect(runCheck).not.toHaveBeenCalled();
|
|
935
|
+
// Nothing new to persist, and re-saving would touch updatedAt for no gain.
|
|
936
|
+
expect(saveClaimCheck).not.toHaveBeenCalled();
|
|
937
|
+
expect(findClaimCheck.mock.calls[0][0]).toEqual({ session: SESSION, messageId: "msg_1", userId: 7 });
|
|
938
|
+
});
|
|
939
|
+
|
|
940
|
+
it("serves a response byte-identical to the engine's", async () => {
|
|
941
|
+
const live = await request(buildApp().app).post(CLAIM_CHECK_PATH).send(stored);
|
|
942
|
+
const cached = await request(buildApp({ findClaimCheck: jest.fn().mockResolvedValue(RESULT) }).app)
|
|
943
|
+
.post(CLAIM_CHECK_PATH)
|
|
944
|
+
.send(stored);
|
|
945
|
+
expect(cached.status).toBe(live.status);
|
|
946
|
+
expect(cached.body).toEqual(live.body);
|
|
947
|
+
});
|
|
948
|
+
|
|
949
|
+
it("runs the check when nothing is stored for this message", async () => {
|
|
950
|
+
const { app, runCheck } = buildApp({ findClaimCheck: jest.fn().mockResolvedValue(undefined) });
|
|
951
|
+
expect((await request(app).post(CLAIM_CHECK_PATH).send(stored)).status).toBe(200);
|
|
952
|
+
expect(runCheck).toHaveBeenCalledTimes(1);
|
|
953
|
+
});
|
|
954
|
+
|
|
955
|
+
it("falls through to running the check when the lookup fails", async () => {
|
|
956
|
+
const warn = jest.spyOn(console, "warn").mockImplementation(() => {});
|
|
957
|
+
try {
|
|
958
|
+
const { app, runCheck } = buildApp({
|
|
959
|
+
findClaimCheck: jest.fn().mockRejectedValue(new Error("db down")),
|
|
960
|
+
});
|
|
961
|
+
const res = await request(app).post(CLAIM_CHECK_PATH).send(stored);
|
|
962
|
+
expect(res.status).toBe(200);
|
|
963
|
+
expect(res.body.score.label).toBe("ok");
|
|
964
|
+
expect(runCheck).toHaveBeenCalledTimes(1);
|
|
965
|
+
} finally {
|
|
966
|
+
warn.mockRestore();
|
|
967
|
+
}
|
|
968
|
+
});
|
|
969
|
+
|
|
970
|
+
it("does not look anything up when the request names no session and message", async () => {
|
|
971
|
+
const findClaimCheck = jest.fn();
|
|
972
|
+
const { app, runCheck } = buildApp({ findClaimCheck });
|
|
973
|
+
expect((await request(app).post(CLAIM_CHECK_PATH).send(BODY)).status).toBe(200);
|
|
974
|
+
expect(findClaimCheck).not.toHaveBeenCalled();
|
|
975
|
+
expect(runCheck).toHaveBeenCalledTimes(1);
|
|
976
|
+
});
|
|
977
|
+
|
|
978
|
+
it("does not look anything up for a session id that is not a uuid", async () => {
|
|
979
|
+
const findClaimCheck = jest.fn();
|
|
980
|
+
const { app } = buildApp({ findClaimCheck });
|
|
981
|
+
const res = await request(app)
|
|
982
|
+
.post(CLAIM_CHECK_PATH)
|
|
983
|
+
.send({ ...BODY, session: "not-a-uuid", messageId: "msg_1" });
|
|
984
|
+
expect(res.status).toBe(200);
|
|
985
|
+
expect(findClaimCheck).not.toHaveBeenCalled();
|
|
986
|
+
});
|
|
987
|
+
|
|
988
|
+
// The lookup sits AFTER every gate: a stored row must not become a way to
|
|
989
|
+
// read a verdict for an agent whose admin has since turned the check off,
|
|
990
|
+
// or one the caller may not use.
|
|
991
|
+
it("still 403s for an agent with the check disabled, stored row or not", async () => {
|
|
992
|
+
const findClaimCheck = jest.fn().mockResolvedValue(RESULT);
|
|
993
|
+
const { app } = buildApp({
|
|
994
|
+
findClaimCheck,
|
|
995
|
+
getAgent: async () => ({ id: "agent-1", model: "m", tools: [] }) as any,
|
|
996
|
+
});
|
|
997
|
+
const res = await request(app).post(CLAIM_CHECK_PATH).send({ ...stored, agent: "agent-1" });
|
|
998
|
+
expect(res.status).toBe(403);
|
|
999
|
+
expect(findClaimCheck).not.toHaveBeenCalled();
|
|
1000
|
+
});
|
|
1001
|
+
|
|
1002
|
+
it("is skipped entirely when the dep is not wired", async () => {
|
|
1003
|
+
const { app, runCheck } = buildApp({ findClaimCheck: undefined });
|
|
1004
|
+
expect((await request(app).post(CLAIM_CHECK_PATH).send(stored)).status).toBe(200);
|
|
1005
|
+
expect(runCheck).toHaveBeenCalledTimes(1);
|
|
1006
|
+
});
|
|
1007
|
+
});
|
|
1008
|
+
|
|
1009
|
+
// Fix round 2, Minor 2 and Minor 3, and parked item 2.
|
|
1010
|
+
describe("persistence edge cases", () => {
|
|
1011
|
+
const SESSION = "11111111-1111-4111-8111-111111111111";
|
|
1012
|
+
const stored = { ...BODY, session: SESSION, messageId: "msg_1" };
|
|
1013
|
+
|
|
1014
|
+
// M2: completedResult used to be set AFTER res.json. If the client has gone
|
|
1015
|
+
// away and the send throws, the check had been paid for and was then
|
|
1016
|
+
// discarded — the one case where persisting matters most.
|
|
1017
|
+
it("persists the result even when sending the response throws", async () => {
|
|
1018
|
+
const saveClaimCheck = jest.fn().mockResolvedValue(undefined);
|
|
1019
|
+
const errorSpy = jest.spyOn(console, "error").mockImplementation(() => {});
|
|
1020
|
+
try {
|
|
1021
|
+
const { deps } = buildApp({ saveClaimCheck });
|
|
1022
|
+
const app = express();
|
|
1023
|
+
app.use(express.json());
|
|
1024
|
+
// One throwing res.json, as a client that disconnected mid-send looks
|
|
1025
|
+
// to the handler; the handler's own error path may still answer.
|
|
1026
|
+
app.use((_req, res, next) => {
|
|
1027
|
+
const original = res.json.bind(res);
|
|
1028
|
+
let thrown = false;
|
|
1029
|
+
res.json = ((body: unknown) => {
|
|
1030
|
+
if (!thrown) {
|
|
1031
|
+
thrown = true;
|
|
1032
|
+
throw new Error("client has gone away");
|
|
1033
|
+
}
|
|
1034
|
+
return original(body as never);
|
|
1035
|
+
}) as never;
|
|
1036
|
+
next();
|
|
1037
|
+
});
|
|
1038
|
+
registerClaimCheckRoutes(app, deps);
|
|
1039
|
+
|
|
1040
|
+
await request(app).post(CLAIM_CHECK_PATH).send(stored);
|
|
1041
|
+
expect(saveClaimCheck).toHaveBeenCalledTimes(1);
|
|
1042
|
+
expect(saveClaimCheck.mock.calls[0][0].result).toEqual(RESULT);
|
|
1043
|
+
} finally {
|
|
1044
|
+
errorSpy.mockRestore();
|
|
1045
|
+
}
|
|
1046
|
+
});
|
|
1047
|
+
|
|
1048
|
+
// M3: the GET 500s loudly on an unwired dep while this path skipped in
|
|
1049
|
+
// silence, so a dropped wiring showed up only as a panel that never
|
|
1050
|
+
// survived a reload.
|
|
1051
|
+
it("logs an error when saveClaimCheck is missing but a session and message were named", async () => {
|
|
1052
|
+
const errorSpy = jest.spyOn(console, "error").mockImplementation(() => {});
|
|
1053
|
+
try {
|
|
1054
|
+
const { app } = buildApp({ saveClaimCheck: undefined });
|
|
1055
|
+
expect((await request(app).post(CLAIM_CHECK_PATH).send(stored)).status).toBe(200);
|
|
1056
|
+
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("saveClaimCheck is not wired"));
|
|
1057
|
+
} finally {
|
|
1058
|
+
errorSpy.mockRestore();
|
|
1059
|
+
}
|
|
1060
|
+
});
|
|
1061
|
+
|
|
1062
|
+
it("stays silent about the missing dep when no session was named", async () => {
|
|
1063
|
+
const errorSpy = jest.spyOn(console, "error").mockImplementation(() => {});
|
|
1064
|
+
try {
|
|
1065
|
+
const { app } = buildApp({ saveClaimCheck: undefined });
|
|
1066
|
+
expect((await request(app).post(CLAIM_CHECK_PATH).send(BODY)).status).toBe(200);
|
|
1067
|
+
expect(errorSpy).not.toHaveBeenCalled();
|
|
1068
|
+
} finally {
|
|
1069
|
+
errorSpy.mockRestore();
|
|
1070
|
+
}
|
|
1071
|
+
});
|
|
1072
|
+
});
|
|
1073
|
+
|
|
1074
|
+
// Parked item 2: auth.code describes the authentication ATTEMPT. When a
|
|
1075
|
+
// principal comes back whose id cannot key a row, that attempt may have
|
|
1076
|
+
// "succeeded" — and echoing its code answered a 200 (or a future branch's 0)
|
|
1077
|
+
// with an "Unauthorized." body.
|
|
1078
|
+
describe("a principal with an unusable id is always 401", () => {
|
|
1079
|
+
const SESSION = "11111111-1111-4111-8111-111111111111";
|
|
1080
|
+
|
|
1081
|
+
it.each([
|
|
1082
|
+
["a successful attempt (code 200)", { user: { id: "not-a-number" } as any, code: 200 }],
|
|
1083
|
+
["an attempt that left the code unset", { user: { id: "not-a-number" } as any }],
|
|
1084
|
+
["a code of 0", { user: { id: "not-a-number" } as any, code: 0 }],
|
|
1085
|
+
])("POST answers 401 for %s", async (_label, auth) => {
|
|
1086
|
+
const { app, runCheck } = buildApp({ authenticate: async () => auth });
|
|
1087
|
+
expect((await request(app).post(CLAIM_CHECK_PATH).send(BODY)).status).toBe(401);
|
|
1088
|
+
expect(runCheck).not.toHaveBeenCalled();
|
|
1089
|
+
});
|
|
1090
|
+
|
|
1091
|
+
it.each([
|
|
1092
|
+
["a successful attempt (code 200)", { user: { id: "not-a-number" } as any, code: 200 }],
|
|
1093
|
+
["an attempt that left the code unset", { user: { id: "not-a-number" } as any }],
|
|
1094
|
+
["a code of 0", { user: { id: "not-a-number" } as any, code: 0 }],
|
|
1095
|
+
])("GET answers 401 for %s", async (_label, auth) => {
|
|
1096
|
+
const listClaimChecks = jest.fn();
|
|
1097
|
+
const { app } = buildApp({ authenticate: async () => auth, listClaimChecks });
|
|
1098
|
+
expect((await request(app).get(`/claims/check/${SESSION}`)).status).toBe(401);
|
|
1099
|
+
expect(listClaimChecks).not.toHaveBeenCalled();
|
|
1100
|
+
});
|
|
1101
|
+
|
|
1102
|
+
it("still passes a genuine auth failure's own code through", async () => {
|
|
1103
|
+
const { app } = buildApp({
|
|
1104
|
+
authenticate: async () => ({ error: true, code: 403, message: "key disabled" }),
|
|
1105
|
+
});
|
|
1106
|
+
expect((await request(app).post(CLAIM_CHECK_PATH).send(BODY)).status).toBe(403);
|
|
1107
|
+
expect((await request(app).get(`/claims/check/${SESSION}`)).status).toBe(403);
|
|
1108
|
+
});
|
|
1109
|
+
});
|
|
1110
|
+
|
|
1111
|
+
describe(`GET ${CLAIM_CHECK_SESSION_PATH}`, () => {
|
|
1112
|
+
it("returns stored checks keyed by message id", async () => {
|
|
1113
|
+
const listClaimChecks = jest.fn().mockResolvedValue({ msg_1: RESULT });
|
|
1114
|
+
const { app } = buildApp({ listClaimChecks });
|
|
1115
|
+
const res = await request(app).get("/claims/check/11111111-1111-4111-8111-111111111111");
|
|
1116
|
+
expect(res.status).toBe(200);
|
|
1117
|
+
expect(res.body.checks.msg_1.score.label).toBe("ok");
|
|
1118
|
+
expect(listClaimChecks.mock.calls[0][0]).toEqual(
|
|
1119
|
+
expect.objectContaining({ session: "11111111-1111-4111-8111-111111111111", userId: 7 }),
|
|
1120
|
+
);
|
|
1121
|
+
});
|
|
1122
|
+
|
|
1123
|
+
it("404s when the deployment is not licensed", async () => {
|
|
1124
|
+
const { app } = buildApp({ isLicensed: () => false });
|
|
1125
|
+
expect((await request(app).get("/claims/check/11111111-1111-4111-8111-111111111111")).status).toBe(404);
|
|
1126
|
+
});
|
|
1127
|
+
|
|
1128
|
+
it("401s when authentication fails", async () => {
|
|
1129
|
+
const { app } = buildApp({ authenticate: async () => ({ error: true, code: 401, message: "no key" }) });
|
|
1130
|
+
expect((await request(app).get("/claims/check/11111111-1111-4111-8111-111111111111")).status).toBe(401);
|
|
1131
|
+
});
|
|
1132
|
+
|
|
1133
|
+
// Review Focus 4
|
|
1134
|
+
it("400s on a session id that is not a uuid, without touching the database or authenticating", async () => {
|
|
1135
|
+
const listClaimChecks = jest.fn();
|
|
1136
|
+
const authenticate = jest.fn();
|
|
1137
|
+
const { app } = buildApp({ listClaimChecks, authenticate });
|
|
1138
|
+
expect((await request(app).get("/claims/check/not-a-uuid")).status).toBe(400);
|
|
1139
|
+
expect(listClaimChecks).not.toHaveBeenCalled();
|
|
1140
|
+
// Pins the ordering: the uuid shape is checked before anything that
|
|
1141
|
+
// would touch auth or the database, so a junk path segment never reaches
|
|
1142
|
+
// either.
|
|
1143
|
+
expect(authenticate).not.toHaveBeenCalled();
|
|
1144
|
+
});
|
|
1145
|
+
|
|
1146
|
+
// Review Focus 4
|
|
1147
|
+
it("scopes the lookup to the caller, so another tenant's checks cannot be read", async () => {
|
|
1148
|
+
const listClaimChecks = jest.fn().mockResolvedValue({});
|
|
1149
|
+
const { app } = buildApp({
|
|
1150
|
+
listClaimChecks,
|
|
1151
|
+
authenticate: async () => ({ user: { id: 99, type: "user" } as any }),
|
|
1152
|
+
});
|
|
1153
|
+
await request(app).get("/claims/check/11111111-1111-4111-8111-111111111111");
|
|
1154
|
+
expect(listClaimChecks.mock.calls[0][0].userId).toBe(99);
|
|
1155
|
+
});
|
|
1156
|
+
|
|
1157
|
+
it("returns an empty object for a session with no checks", async () => {
|
|
1158
|
+
const { app } = buildApp({ listClaimChecks: jest.fn().mockResolvedValue({}) });
|
|
1159
|
+
const res = await request(app).get("/claims/check/11111111-1111-4111-8111-111111111111");
|
|
1160
|
+
expect(res.status).toBe(200);
|
|
1161
|
+
expect(res.body.checks).toEqual({});
|
|
1162
|
+
});
|
|
1163
|
+
|
|
1164
|
+
it("500s when the stored-check lookup throws", async () => {
|
|
1165
|
+
const errorSpy = jest.spyOn(console, "error").mockImplementation(() => {});
|
|
1166
|
+
try {
|
|
1167
|
+
const { app } = buildApp({ listClaimChecks: jest.fn().mockRejectedValue(new Error("db down")) });
|
|
1168
|
+
const res = await request(app).get("/claims/check/11111111-1111-4111-8111-111111111111");
|
|
1169
|
+
expect(res.status).toBe(500);
|
|
1170
|
+
} finally {
|
|
1171
|
+
errorSpy.mockRestore();
|
|
1172
|
+
}
|
|
1173
|
+
});
|
|
1174
|
+
|
|
1175
|
+
// A missing dep is a deployment wiring defect, not "nothing stored" — a
|
|
1176
|
+
// silent 200 {checks:{}} here would make a future regression that drops
|
|
1177
|
+
// the wiring read as an empty, legitimate result instead of failing loudly.
|
|
1178
|
+
it("500s when listClaimChecks is not wired, instead of silently answering empty", async () => {
|
|
1179
|
+
const errorSpy = jest.spyOn(console, "error").mockImplementation(() => {});
|
|
1180
|
+
try {
|
|
1181
|
+
const { app } = buildApp({ listClaimChecks: undefined });
|
|
1182
|
+
const res = await request(app).get("/claims/check/11111111-1111-4111-8111-111111111111");
|
|
1183
|
+
expect(res.status).toBe(500);
|
|
1184
|
+
} finally {
|
|
1185
|
+
errorSpy.mockRestore();
|
|
1186
|
+
}
|
|
1187
|
+
});
|
|
1188
|
+
});
|