← All repositories

crossmate

A collaborative crossword app for iPhone and iPad

git clone https://code.inqk.net/crossmate.git


Tests/Workers/push-worker.test.mjs (25087B)

1import test from "node:test";
2import assert from "node:assert/strict";
3import { createHmac } from "node:crypto";
4import {
5  parseAuthenticatorData,
6  PushRegistry,
7  validateAppAttestExtensions
8} from "../../Workers/push-worker.js";
9import { StubStorage } from "./helpers.mjs";
10
11function makeRegistry(env = {}) {
12  const storage = new StubStorage();
13  return { registry: new PushRegistry({ storage }, env), storage };
14}
15
16function attestRequest(ip) {
17  return new Request("https://push.example/attest/register", {
18    method: "POST",
19    headers: { "CF-Connecting-IP": ip }
20  });
21}
22
23const appAttestKeyBytes = Buffer.from([
24  0xfb, 0xff, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05,
25  0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
26  0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
27  0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d
28]);
29const standardAppAttestKeyID = appAttestKeyBytes.toString("base64");
30const urlSafeAppAttestKeyID = appAttestKeyBytes.toString("base64url");
31
32function attestedAuthenticatorData({ flags = 0x40, extensions = new Uint8Array() } = {}) {
33  const rpIDHash = Buffer.alloc(32);
34  const signCount = Buffer.alloc(4);
35  const aaguid = Buffer.alloc(16);
36  const credentialID = Buffer.alloc(32, 7);
37  // A P-256 COSE key: { 1: 2, 3: -7, -1: 1, -2: x, -3: y }.
38  const coseKey = Buffer.concat([
39    Buffer.from([0xa5, 0x01, 0x02, 0x03, 0x26, 0x20, 0x01, 0x21, 0x58, 0x20]),
40    Buffer.alloc(32, 1),
41    Buffer.from([0x22, 0x58, 0x20]),
42    Buffer.alloc(32, 2)
43  ]);
44  const credentialLength = Buffer.from([0x00, credentialID.length]);
45  return Buffer.concat([
46    rpIDHash,
47    Buffer.from([flags]),
48    signCount,
49    aaguid,
50    credentialLength,
51    credentialID,
52    coseKey,
53    extensions
54  ]);
55}
56
57test("App Attest extensions follow, rather than extend, the COSE key despite a clear ED flag", () => {
58  // { "apple_bundle_version_01": "886", "apple_validation_category_01": h'02000000' }
59  const extensions = Buffer.from([
60    0xa2,
61    0x77, ...Buffer.from("apple_bundle_version_01"), 0x63, 0x38, 0x38, 0x36,
62    0x78, 0x1c, ...Buffer.from("apple_validation_category_01"), 0x44, 0x02, 0x00, 0x00, 0x00
63  ]);
64  const data = attestedAuthenticatorData({ extensions });
65  const parsed = parseAuthenticatorData(data, { requireAttestedCredential: true });
66
67  assert.equal(parsed.cosePublicKey.length, 77);
68  assert.equal(parsed.extensions.apple_bundle_version_01, "886");
69  assert.deepEqual(parsed.extensions.apple_validation_category_01, Buffer.from([2, 0, 0, 0]));
70  assert.doesNotThrow(() => validateAppAttestExtensions(parsed.extensions));
71});
72
73test("App Attest rejects malformed and invalid app extensions", () => {
74  assert.throws(
75    () => parseAuthenticatorData(attestedAuthenticatorData({ extensions: Buffer.from([0xf6]) }), {
76      requireAttestedCredential: true
77    }),
78    /invalid authenticator extensions/
79  );
80  assert.throws(
81    () => validateAppAttestExtensions({
82      apple_validation_category_01: new Uint8Array([3, 0, 0, 0]),
83      apple_bundle_version_01: "886"
84    }),
85    /unexpected App Attest launch category/
86  );
87});
88
89function challengeRequest(keyID, deviceID = "device-1") {
90  return new Request("https://push.example/attest/challenge", {
91    method: "POST",
92    headers: {
93      "Content-Type": "application/json",
94      "CF-Connecting-IP": "203.0.113.9"
95    },
96    body: JSON.stringify({ deviceID, keyID })
97  });
98}
99
100test("challenge accepts standard and URL-safe App Attest key IDs", async () => {
101  assert.match(standardAppAttestKeyID, /[+/]/);
102  assert.match(standardAppAttestKeyID, /=+$/);
103  const standard = makeRegistry();
104  const standardResponse = await standard.registry.fetch(challengeRequest(standardAppAttestKeyID));
105  assert.equal(standardResponse.status, 200);
106
107  const urlSafe = makeRegistry();
108  const urlSafeResponse = await urlSafe.registry.fetch(challengeRequest(urlSafeAppAttestKeyID));
109  assert.equal(urlSafeResponse.status, 200);
110});
111
112test("registration accepts both App Attest key-ID alphabets before attestation verification", async () => {
113  for (const keyID of [standardAppAttestKeyID, urlSafeAppAttestKeyID]) {
114    const { registry } = makeRegistry();
115    const response = await registry.handleAttestationRegister(
116      attestRequest("203.0.113.9"),
117      JSON.stringify({
118        deviceID: "device-1",
119        keyID,
120        challenge: "unknown-challenge",
121        attestationObject: "AA"
122      })
123    );
124    assert.equal(response.status, 401);
125    assert.equal(await response.text(), "Unknown App Attest challenge");
126  }
127});
128
129test("App Attest key-ID storage uses one URL-safe canonical component", () => {
130  const { registry } = makeRegistry();
131  const expected = `appattest-key:device-1:${urlSafeAppAttestKeyID}`;
132  assert.equal(registry.appAttestRegistrationKey("device-1", standardAppAttestKeyID), expected);
133  assert.equal(registry.appAttestRegistrationKey("device-1", urlSafeAppAttestKeyID), expected);
134});
135
136test("registration retry succeeds after its first response was lost", async () => {
137  const { registry, storage } = makeRegistry();
138  const registrationKey = registry.appAttestRegistrationKey("device-1", standardAppAttestKeyID);
139  await storage.put(registrationKey, { publicKeySPKI: "already-verified" });
140
141  const response = await registry.handleAttestationRegister(
142    attestRequest("203.0.113.9"),
143    JSON.stringify({
144      deviceID: "device-1",
145      keyID: standardAppAttestKeyID,
146      challenge: "already-consumed",
147      attestationObject: "AA"
148    })
149  );
150
151  assert.equal(response.status, 204);
152});
153
154test("pre-885 registration storage migrates to the canonical key on lookup", async () => {
155  const { registry, storage } = makeRegistry();
156  const legacyKey = `appattest-key:device-1:${standardAppAttestKeyID}`;
157  const canonicalKey = `appattest-key:device-1:${urlSafeAppAttestKeyID}`;
158  const registration = { publicKeySPKI: "legacy-record" };
159  await storage.put(legacyKey, registration);
160
161  const loaded = await registry.loadAppAttestRegistration(
162    "device-1",
163    standardAppAttestKeyID,
164    urlSafeAppAttestKeyID
165  );
166
167  assert.deepEqual(loaded, registration);
168  assert.equal(storage.map.has(legacyKey), false);
169  assert.deepEqual(await storage.get(canonicalKey), registration);
170});
171
172test("challenge rejects empty, oversized, malformed, and storage-smuggling key IDs", async () => {
173  const invalidKeyIDs = [
174    "",
175    "A".repeat(257),
176    "not:base64",
177    "+_8=",
178    "AA=A",
179    "A",
180    `${standardAppAttestKeyID}:forged`
181  ];
182  for (const keyID of invalidKeyIDs) {
183    const { registry } = makeRegistry();
184    const response = await registry.fetch(challengeRequest(keyID));
185    assert.equal(response.status, 400, `expected rejection for ${JSON.stringify(keyID.slice(0, 20))}`);
186  }
187});
188
189test("rate limit config uses table defaults", () => {
190  const { registry } = makeRegistry();
191  assert.deepEqual(registry.rateLimitConfig("PUBLISH_CRED"), { limit: 60, windowSeconds: 60 });
192  assert.deepEqual(registry.rateLimitConfig("APP_ATTEST_REGISTER_IP"), { limit: 30, windowSeconds: 60 * 60 });
193});
194
195test("rate limit config honours env overrides and rejects junk", () => {
196  const { registry } = makeRegistry({
197    PUBLISH_CRED_LIMIT: "5",
198    PUBLISH_CRED_WINDOW_SECONDS: "120",
199    PUBLISH_ADDRESS_LIMIT: "not-a-number"
200  });
201  assert.deepEqual(registry.rateLimitConfig("PUBLISH_CRED"), { limit: 5, windowSeconds: 120 });
202  // A malformed override falls back to the table default rather than NaN.
203  assert.equal(registry.rateLimitConfig("PUBLISH_ADDRESS").limit, 30);
204});
205
206test("requests beyond the limit are rejected with a retry hint", async () => {
207  const { registry } = makeRegistry();
208  const config = registry.rateLimitConfig("PUBLISH_CRED");
209  for (let i = 0; i < config.limit; i++) {
210    const result = await registry.checkRateLimit("publish:cred", "cred-a", config);
211    assert.equal(result.ok, true, `call ${i + 1} should be allowed`);
212  }
213  const over = await registry.checkRateLimit("publish:cred", "cred-a", config);
214  assert.equal(over.ok, false);
215  assert.ok(over.retryAfterSeconds >= 1);
216});
217
218test("the window slides: aged entries free quota again", async () => {
219  const { registry, storage } = makeRegistry({ PUBLISH_CRED_LIMIT: "2" });
220  const config = registry.rateLimitConfig("PUBLISH_CRED");
221  await registry.checkRateLimit("publish:cred", "cred-a", config);
222  await registry.checkRateLimit("publish:cred", "cred-a", config);
223  assert.equal((await registry.checkRateLimit("publish:cred", "cred-a", config)).ok, false);
224
225  storage.age(storage.keys("rate:")[0], config.windowSeconds * 1000 + 1000);
226  assert.equal((await registry.checkRateLimit("publish:cred", "cred-a", config)).ok, true);
227});
228
229test("identities have independent buckets", async () => {
230  const { registry } = makeRegistry({ PUBLISH_CRED_LIMIT: "1" });
231  const config = registry.rateLimitConfig("PUBLISH_CRED");
232  assert.equal((await registry.checkRateLimit("publish:cred", "cred-a", config)).ok, true);
233  assert.equal((await registry.checkRateLimit("publish:cred", "cred-a", config)).ok, false);
234  assert.equal((await registry.checkRateLimit("publish:cred", "cred-b", config)).ok, true);
235});
236
237test("attestation gate returns a 429 response once the device limit is hit", async () => {
238  const { registry } = makeRegistry({ APP_ATTEST_REGISTER_DEVICE_LIMIT: "2" });
239  const request = attestRequest("203.0.113.9");
240  assert.equal(await registry.checkAttestationRateLimit(request, "register", "device-1"), null);
241  assert.equal(await registry.checkAttestationRateLimit(request, "register", "device-1"), null);
242  const limited = await registry.checkAttestationRateLimit(request, "register", "device-1");
243  assert.equal(limited.status, 429);
244  assert.ok(Number(limited.headers.get("Retry-After")) >= 1);
245});
246
247test("first write arms the sweep alarm at the horizon; later writes leave it", async () => {
248  const { registry, storage } = makeRegistry();
249  const config = registry.rateLimitConfig("PUBLISH_CRED");
250  const before = Date.now();
251  await registry.checkRateLimit("publish:cred", "cred-a", config);
252  const horizon = registry.rateSweepHorizonMillis();
253  // The default horizon is the largest table window: the 1h attest buckets.
254  assert.equal(horizon, 60 * 60 * 1000);
255  assert.ok(storage.alarmAt >= before + horizon);
256
257  const armedAt = storage.alarmAt;
258  await registry.checkRateLimit("publish:cred", "cred-b", config);
259  assert.equal(storage.alarmAt, armedAt, "arm-if-unarmed must not reschedule");
260});
261
262test("an env window override raises the sweep horizon", () => {
263  const { registry } = makeRegistry({ APP_ATTEST_REGISTER_IP_WINDOW_SECONDS: "7200" });
264  assert.equal(registry.rateSweepHorizonMillis(), 7200 * 1000);
265});
266
267test("sweep prunes only stale rate keys and re-arms while live ones remain", async () => {
268  const { registry, storage } = makeRegistry();
269  const config = registry.rateLimitConfig("PUBLISH_CRED");
270  await registry.checkRateLimit("publish:cred", "cred-a", config);
271  await registry.checkRateLimit("publish:cred", "cred-b", config);
272  const [staleKey, freshKey] = storage.keys("rate:");
273  storage.age(staleKey, registry.rateSweepHorizonMillis() + 60 * 1000);
274  await storage.put("gamecred:keep-me", { secret: "s" });
275
276  await registry.alarm();
277  assert.equal(storage.map.has(staleKey), false);
278  assert.equal(storage.map.has(freshKey), true);
279  assert.equal(storage.map.has("gamecred:keep-me"), true, "sweep must stay inside the rate: prefix");
280  assert.ok(storage.alarmAt > Date.now(), "alarm re-arms while live keys remain");
281});
282
283test("sweep goes quiet once every rate key has expired", async () => {
284  const { registry, storage } = makeRegistry();
285  const config = registry.rateLimitConfig("PUBLISH_CRED");
286  await registry.checkRateLimit("publish:cred", "cred-a", config);
287  storage.age(storage.keys("rate:")[0], registry.rateSweepHorizonMillis() + 60 * 1000);
288  storage.alarmAt = null;
289
290  await registry.alarm();
291  assert.deepEqual(storage.keys("rate:"), []);
292  assert.equal(storage.alarmAt, null, "no live keys, no re-arm");
293});
294
295// --- Game-binding registration (H4): a credID-scoped address registration
296// must prove possession of that game's secret, exactly like a publish.
297
298const gameSecret = Buffer.alloc(32, 7).toString("base64url");
299const otherSecret = Buffer.alloc(32, 9).toString("base64url");
300
301function gameSignature(secret, credID, { bodyHash = "hash", timestamp = "1000", nonce = "nonce" } = {}) {
302  const payload = ["crossmate-push-game-v1", credID, bodyHash, timestamp, nonce].join("\n");
303  return createHmac("sha256", Buffer.from(secret, "base64url")).update(payload).digest("base64url");
304}
305
306function registerRequest(signature) {
307  const headers = {
308    "X-Crossmate-Body-SHA256": "hash",
309    "X-Crossmate-Timestamp": "1000",
310    "X-Crossmate-Nonce": "nonce"
311  };
312  if (signature) headers["X-Crossmate-Game-Signature"] = signature;
313  return new Request("https://push.example/register", { method: "POST", headers });
314}
315
316function registerBody(addresses, deviceID = "device1") {
317  return JSON.stringify({
318    deviceID,
319    token: "apns-token",
320    environment: "production",
321    addresses
322  });
323}
324
325async function registerGameCred(registry, credID, secret = gameSecret) {
326  const response = await registry.handleGameRegister(credID, JSON.stringify({ secret }));
327  assert.ok(response.status === 201 || response.status === 204);
328}
329
330test("a correctly signed game binding registers under its credID", async () => {
331  const { registry, storage } = makeRegistry();
332  await registerGameCred(registry, "cred-1");
333
334  const response = await registry.handleRegister(
335    registerRequest(gameSignature(gameSecret, "cred-1")),
336    registerBody([{ address: "addr-a", credID: "cred-1" }]),
337    { deviceID: "device1" }
338  );
339
340  assert.equal(response.status, 204);
341  assert.deepEqual(storage.keys("addr:"), ["addr:cred-1:addr-a:device1"]);
342});
343
344test("an App-Attest-only game binding (no game signature) is not stored", async () => {
345  const { registry, storage } = makeRegistry();
346  await registerGameCred(registry, "cred-1");
347
348  // A departed participant (or anyone who learned the credID) has a valid
349  // App Attest enrollment of their own but not the game secret.
350  const response = await registry.handleRegister(
351    registerRequest(null),
352    registerBody([
353      { address: "addr-account" },
354      { address: "addr-a", credID: "cred-1" }
355    ]),
356    { deviceID: "device1" }
357  );
358
359  // The account-scoped binding still lands (legacy batched clients), but the
360  // unproven game binding is dropped.
361  assert.equal(response.status, 204);
362  assert.deepEqual(storage.keys("addr:"), ["addr:addr-account:device1"]);
363});
364
365test("a game binding signed with the wrong secret is not stored", async () => {
366  const { registry, storage } = makeRegistry();
367  await registerGameCred(registry, "cred-1");
368
369  const response = await registry.handleRegister(
370    registerRequest(gameSignature(otherSecret, "cred-1")),
371    registerBody([{ address: "addr-a", credID: "cred-1" }]),
372    { deviceID: "device1" }
373  );
374
375  assert.equal(response.status, 204);
376  assert.deepEqual(storage.keys("addr:"), []);
377});
378
379test("a game binding naming an unknown credID is not stored", async () => {
380  const { registry, storage } = makeRegistry();
381
382  const response = await registry.handleRegister(
383    registerRequest(gameSignature(gameSecret, "cred-unregistered")),
384    registerBody([{ address: "addr-a", credID: "cred-unregistered" }]),
385    { deviceID: "device1" }
386  );
387
388  assert.equal(response.status, 204);
389  assert.deepEqual(storage.keys("addr:"), []);
390});
391
392test("mixed credIDs in one request drop every game binding", async () => {
393  const { registry, storage } = makeRegistry();
394  await registerGameCred(registry, "cred-1");
395  await registerGameCred(registry, "cred-2", otherSecret);
396
397  // One request carries one signature, so it can prove at most one credID;
398  // a batch that names two proves neither.
399  const response = await registry.handleRegister(
400    registerRequest(gameSignature(gameSecret, "cred-1")),
401    registerBody([
402      { address: "addr-a", credID: "cred-1" },
403      { address: "addr-b", credID: "cred-2" }
404    ]),
405    { deviceID: "device1" }
406  );
407
408  assert.equal(response.status, 204);
409  assert.deepEqual(storage.keys("addr:"), []);
410});
411
412test("after rotation, the old credential cannot bind under the new credID", async () => {
413  const { registry, storage } = makeRegistry();
414  // The room before rotation…
415  await registerGameCred(registry, "cred-old");
416  // …and the replacement a remaining participant registered after someone left.
417  await registerGameCred(registry, "cred-new", otherSecret);
418
419  // The departed participant holds the complete old credential but signs for
420  // the new credID with the old secret — the only credential it has.
421  const response = await registry.handleRegister(
422    registerRequest(gameSignature(gameSecret, "cred-new")),
423    registerBody([{ address: "addr-a", credID: "cred-new" }], "device-departed"),
424    { deviceID: "device-departed" }
425  );
426  assert.equal(response.status, 204);
427  assert.deepEqual(storage.keys("addr:"), [], "old secret must not subscribe to the rotated room");
428
429  // A current participant holding the new secret registers fine.
430  const ok = await registry.handleRegister(
431    registerRequest(gameSignature(otherSecret, "cred-new")),
432    registerBody([{ address: "addr-a", credID: "cred-new" }], "device-current"),
433    { deviceID: "device-current" }
434  );
435  assert.equal(ok.status, 204);
436  assert.deepEqual(storage.keys("addr:"), ["addr:cred-new:addr-a:device-current"]);
437});
438
439// --- Ingress and fanout bounds (M3): request bodies, lists, strings, and
440// APNs payloads are all refused before the work they would otherwise buy.
441
442test("an oversized request body is refused before auth", async () => {
443  const { registry } = makeRegistry({ MAX_BODY_BYTES: "1024" });
444  const response = await registry.fetch(new Request("https://push.example/publish", {
445    method: "POST",
446    body: "x".repeat(2048)
447  }));
448  assert.equal(response.status, 413);
449});
450
451test("a body exactly at the limit passes the size gate", async () => {
452  const { registry } = makeRegistry({ MAX_BODY_BYTES: "1024" });
453  const response = await registry.fetch(new Request("https://push.example/publish", {
454    method: "POST",
455    body: "x".repeat(1024)
456  }));
457  // Past the size gate; refused by auth, not by size.
458  assert.equal(response.status, 401);
459});
460
461test("the body cap also covers the pre-auth attestation routes", async () => {
462  const { registry } = makeRegistry({ MAX_BODY_BYTES: "1024" });
463  const response = await registry.fetch(new Request("https://push.example/attest/challenge", {
464    method: "POST",
465    body: "x".repeat(2048)
466  }));
467  assert.equal(response.status, 413);
468});
469
470test("register refuses oversized address and mutedKinds lists", async () => {
471  const { registry } = makeRegistry({ MAX_ADDRESS_COUNT: "2" });
472  const tooMany = await registry.handleRegister(
473    registerRequest(null),
474    registerBody([{ address: "a1" }, { address: "a2" }, { address: "a3" }]),
475    { deviceID: "device1" }
476  );
477  assert.equal(tooMany.status, 400);
478
479  const mutedOverflow = await registry.handleRegister(
480    registerRequest(null),
481    JSON.stringify({
482      deviceID: "device1",
483      token: "apns-token",
484      environment: "production",
485      addresses: [{ address: "a1" }],
486      mutedKinds: Array.from({ length: 33 }, (_, i) => `kind${i}`)
487    }),
488    { deviceID: "device1" }
489  );
490  assert.equal(mutedOverflow.status, 400);
491});
492
493test("register refuses a malformed token and skips malformed addresses", async () => {
494  const { registry, storage } = makeRegistry();
495  const badToken = await registry.handleRegister(
496    registerRequest(null),
497    JSON.stringify({
498      deviceID: "device1",
499      token: "x".repeat(200),
500      environment: "production",
501      addresses: [{ address: "a1" }]
502    }),
503    { deviceID: "device1" }
504  );
505  assert.equal(badToken.status, 400);
506
507  // An address that could forge a `:`-separated storage-key segment is
508  // dropped; the well-formed sibling in the same request still registers.
509  const mixed = await registry.handleRegister(
510    registerRequest(null),
511    registerBody([{ address: "addr:forged" }, { address: "addr-ok" }]),
512    { deviceID: "device1" }
513  );
514  assert.equal(mixed.status, 204);
515  assert.deepEqual(storage.keys("addr:"), ["addr:addr-ok:device1"]);
516});
517
518test("a game's registration set is capped at write time", async () => {
519  const { registry, storage } = makeRegistry({ MAX_REGISTRATIONS_PER_CRED: "2" });
520  await registerGameCred(registry, "cred-1");
521  for (const device of ["device1", "device2"]) {
522    const response = await registry.handleRegister(
523      registerRequest(gameSignature(gameSecret, "cred-1")),
524      registerBody([{ address: `addr-${device}`, credID: "cred-1" }], device),
525      { deviceID: device }
526    );
527    assert.equal(response.status, 204);
528  }
529
530  const over = await registry.handleRegister(
531    registerRequest(gameSignature(gameSecret, "cred-1")),
532    registerBody([{ address: "addr-device3", credID: "cred-1" }], "device3"),
533    { deviceID: "device3" }
534  );
535  assert.equal(over.status, 400);
536  assert.equal(storage.keys("addr:cred-1:").length, 2);
537
538  // Re-registering an existing binding is an overwrite, not growth.
539  const again = await registry.handleRegister(
540    registerRequest(gameSignature(gameSecret, "cred-1")),
541    registerBody([{ address: "addr-device1", credID: "cred-1" }], "device1"),
542    { deviceID: "device1" }
543  );
544  assert.equal(again.status, 204);
545});
546
547test("game credential registration bounds credID and secret", async () => {
548  const { registry } = makeRegistry();
549  const badCredID = await registry.handleGameRegister(
550    "cred:forged",
551    JSON.stringify({ secret: gameSecret })
552  );
553  assert.equal(badCredID.status, 400);
554
555  const hugeSecret = await registry.handleGameRegister(
556    "cred-1",
557    JSON.stringify({ secret: "A".repeat(1000) })
558  );
559  assert.equal(hugeSecret.status, 400);
560});
561
562function publishRequest() {
563  return new Request("https://push.example/publish", { method: "POST" });
564}
565
566function publishBody(overrides = {}) {
567  return JSON.stringify({
568    kind: "win",
569    addressees: [{ address: "addr-a" }],
570    ...overrides
571  });
572}
573
574test("a bounded publish with no registered targets succeeds cheaply", async () => {
575  const { registry } = makeRegistry();
576  const response = await registry.handlePublish(
577    publishRequest(),
578    publishBody(),
579    { deviceID: "device1" }
580  );
581  assert.equal(response.status, 200);
582  assert.deepEqual(await response.json(), { delivered: 0, removed: 0, muted: 0, failed: 0 });
583});
584
585test("publish refuses oversized addressee lists and fields", async () => {
586  const { registry } = makeRegistry({ MAX_ADDRESS_COUNT: "2" });
587  const tooMany = await registry.handlePublish(
588    publishRequest(),
589    publishBody({ addressees: [{ address: "a1" }, { address: "a2" }, { address: "a3" }] }),
590    { deviceID: "device1" }
591  );
592  assert.equal(tooMany.status, 400);
593
594  const hugeEnc = await registry.handlePublish(
595    publishRequest(),
596    publishBody({ addressees: [{ address: "a1", enc: "A".repeat(5000) }] }),
597    { deviceID: "device1" }
598  );
599  assert.equal(hugeEnc.status, 400);
600
601  const hugeBody = await registry.handlePublish(
602    publishRequest(),
603    publishBody({ alertBody: "x".repeat(1000) }),
604    { deviceID: "device1" }
605  );
606  assert.equal(hugeBody.status, 400);
607
608  const badCollapse = await registry.handlePublish(
609    publishRequest(),
610    publishBody({ collapseID: "c".repeat(65) }),
611    { deviceID: "device1" }
612  );
613  assert.equal(badCollapse.status, 400);
614
615  const badAddress = await registry.handlePublish(
616    publishRequest(),
617    publishBody({ addressees: [{ address: "addr:forged" }] }),
618    { deviceID: "device1" }
619  );
620  assert.equal(badAddress.status, 400);
621});
622
623test("a publish whose APNs payload cannot fit is refused before any fanout", async () => {
624  const { registry } = makeRegistry();
625  // Each field is within its own cap, but the assembled APNs payload
626  // (aps + kind + title + enc as JSON) exceeds the 4 KB APNs ceiling.
627  const response = await registry.handlePublish(
628    publishRequest(),
629    publishBody({
630      title: "t".repeat(400),
631      alertBody: "b".repeat(500),
632      addressees: [{ address: "a1", enc: "A".repeat(4000) }]
633    }),
634    { deviceID: "device1" }
635  );
636  assert.equal(response.status, 413);
637
638  // The same shape with a small enc fits and proceeds.
639  const fits = await registry.handlePublish(
640    publishRequest(),
641    publishBody({
642      title: "t".repeat(400),
643      alertBody: "b".repeat(500),
644      addressees: [{ address: "a1", enc: "A".repeat(500) }]
645    }),
646    { deviceID: "device1" }
647  );
648  assert.equal(fits.status, 200);
649});
650
651test("broadcast fanout is capped even for an over-cap room", async () => {
652  const { registry, storage } = makeRegistry({ MAX_BROADCAST_TARGETS: "2" });
653  for (let index = 0; index < 4; index += 1) {
654    await storage.put(`addr:cred-1:addr-${index}:device-${index}`, {
655      token: "t",
656      environment: "production"
657    });
658  }
659  const targets = await registry.resolveBroadcastTargets(
660    "cred-1", null, null, "body", undefined, undefined
661  );
662  assert.equal(targets.length, 2);
663});