๐Ÿ“ฆ EqualifyEverything / equalify-iris

๐Ÿ“„ anonymous-token.test.ts ยท 645 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645import { test, afterEach } from "node:test";
import assert from "node:assert/strict";
import express from "express";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { AddressInfo } from "node:net";
import { Store } from "../src/store/db.ts";
import {
  makeAuthMiddleware,
  __clearTokenCache,
  __seedRejectedCredential,
  __rejectedCredentialUntil,
} from "../src/auth/middleware.ts";
import type { AuthedRequest } from "../src/auth/middleware.ts";
import { meRouter } from "../src/routes/me.ts";
import { sessionsRouter } from "../src/routes/sessions.ts";
import { uploadRateLimit } from "../src/util/requestLimits.ts";
import { anonymousToken, anonymousTokenWarning, normalizeTrustProxy } from "../src/config.ts";
import type { IrisConfig, RateLimitConfig } from "../src/config.ts";

// `github.anonymous_token` (#456): a deployment can serve callers who send NO credential
// as one shared identity, so a visitor can try the demo without a GitHub account.
//
// Everything worth pinning here is a property that cannot be seen from a response body,
// because the whole point of the feature is that an anonymous request looks like an
// ordinary successful one:
//
//   * WHICH missing-credential shape it answers for. A request with no header is served;
//     a request with a BAD header is still refused. Serving that second one would move a
//     client that was trying to be someone into a shared account's session space, and
//     every response on the way would be a 200.
//   * That the session LIST is closed to anonymous callers. Ownership is `github_user_id`
//     and nothing else, so one shared credential makes "this user's sessions" mean "every
//     anonymous visitor's sessions" โ€” a stranger's document, listed to whoever asks next.
//   * That the shared identity is not one rate-limit bucket. Every anonymous caller
//     resolves to the same user id, so keying uploads on the user would put the whole
//     internet in a single `upload_per_minute`, and it would look like a working
//     deployment that is mysteriously always at its limit.
//   * That the credential from config is VALIDATED like any other, rather than trusted
//     because an operator typed it.
//
// And the default: with the key unset, none of the above is reachable and a token is
// required on every call.
//
// Each of those is pinned by a test that was MEASURED red, not assumed to be: removing the
// `req.anonymous` guard from the session list returns 200 with `ses_anon_one` in the body โ€”
// a session owned by the shared identity, so in a real deployment whatever the previous
// visitor uploaded. Broadening the served shape from `!header` to `!match` serves
// `Basic โ€ฆ`; dropping the flag from `/v1/me` or from `userKey` reddens one test each, and
// never setting it at all reddens two.

const ANON_TOKEN = "gho_anon_demo";
const ANON_USER = { id: 4242, login: "iris-demo-bot" };
const USER_TOKEN = "gho_real_person";
const REAL_USER = { id: 909, login: "a-real-person" };
// A token GitHub cannot answer ABOUT, as distinct from one it rejects. Both leave the
// anonymous identity unresolved and both must leave a signed-in caller working, but only
// one of them is a final answer โ€” see `isRejectedCredential` in auth/github.ts, and
// `rejectedCredentials` in auth/middleware.ts for what is done with it.
const UNANSWERABLE_TOKEN = "gho_github_is_having_a_day";

// A GitHub that knows exactly two tokens, so "the anonymous credential was validated" and
// "the caller's own token was validated" are distinguishable, and anything else 401s.
async function mockGitHub(): Promise<{
  base: string;
  close: () => void;
  calls: () => number;
  // Start accepting a token this mock was rejecting, as the shared identity. For the case
  // that cannot be tested with a static mock: GitHub answering `Bad credentials` for a
  // credential that is actually fine, and then recovering.
  recover: (token: string) => void;
}> {
  const app = express();
  const state = { calls: 0 };
  const recovered = new Set<string>();
  app.get("/user", (req, res) => {
    state.calls++;
    const auth = req.header("authorization") ?? "";
    if (auth === `Bearer ${ANON_TOKEN}`) return void res.json(ANON_USER);
    if (auth === `Bearer ${USER_TOKEN}`) return void res.json(REAL_USER);
    // Deliberately a 5xx and not a 401: a status that says "ask again later".
    if (auth === `Bearer ${UNANSWERABLE_TOKEN}`) return void res.status(502).json({ message: "Bad gateway" });
    for (const t of recovered) if (auth === `Bearer ${t}`) return void res.json(ANON_USER);
    res.status(401).json({ message: "Bad credentials" });
  });
  const server = app.listen(0);
  await new Promise((r) => server.once("listening", r));
  return {
    base: `http://127.0.0.1:${(server.address() as AddressInfo).port}`,
    close: () => server.close(),
    calls: () => state.calls,
    recover: (token: string) => recovered.add(token),
  };
}

function cfg(apiBase: string, dir: string, anonToken?: string): IrisConfig {
  return {
    server: { port: 0, base_url: "http://localhost:0" },
    storage: { data_dir: dir, agents_dir: "agents", database: join(dir, "iris.sqlite") },
    github: {
      client_id: "Iv1.test",
      client_secret: "s",
      upstream_repo: "https://github.com/o/r",
      api_base_url: apiBase,
      oauth_base_url: "https://github.com",
      anonymous_token: anonToken,
    },
    providers: { default: "openrouter", openrouter: { api_key: "k", default_model: "anthropic/claude-sonnet-4.6" } },
    defaults: { max_review_iterations: 3, extraction_concurrency: 5, max_concurrent_runs: 2, recheck_sample_size: 1 },
  };
}

// The real auth middleware in front of the real `/v1/me` and `/v1/sessions` routers, so
// each request below runs the branch under test rather than a re-implementation of it.
async function harness(anonToken?: string) {
  __clearTokenCache();
  const dir = mkdtempSync(join(tmpdir(), "iris-anon-"));
  const gh = await mockGitHub();
  const config = cfg(gh.base, dir, anonToken);
  const store = new Store(join(dir, "iris.sqlite"));
  const app = express();
  const auth = makeAuthMiddleware(store, config);
  app.use("/v1/me", auth, meRouter(config));
  app.use("/v1/sessions", auth, sessionsRouter(config, store));
  const server = app.listen(0);
  await new Promise((r) => server.once("listening", r));
  const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
  return {
    store,
    ghCalls: gh.calls,
    ghRecover: gh.recover,
    // No `headers` key at all when nothing is passed: an empty object would still be a
    // request with no Authorization header, but being explicit is what this suite is about.
    fetch: (path: string, headers?: Record<string, string>) =>
      fetch(`${base}${path}`, headers ? { headers } : undefined),
    close: () => {
      server.close();
      gh.close();
      // The database goes with the temp directory, as in test/token-cache.test.ts: the
      // handle is process-local and the file is about to not exist.
      rmSync(dir, { recursive: true, force: true });
    },
  };
}

afterEach(() => {
  __clearTokenCache();
});

test("with no anonymous_token, a request without a credential is still refused", async () => {
  const h = await harness(undefined);
  try {
    const res = await h.fetch("/v1/me");
    assert.equal(res.status, 401);
    const body = (await res.json()) as { error: { code: string; message: string } };
    assert.equal(body.error.code, "unauthorized");
    assert.match(body.error.message, /Missing or malformed Authorization header/);
    // And nothing was asked of GitHub: there was no credential to validate, so the
    // refusal costs no outbound call.
    assert.equal(h.ghCalls(), 0);
  } finally {
    h.close();
  }
});

test("a whitespace-only anonymous_token is not a credential, end to end", async () => {
  // The shape an unset `${IRIS_ANONYMOUS_TOKEN}` and a blank YAML value both arrive as. Its own
  // test rather than an assertion inside the unit test above, because what is at stake is which
  // deployment an operator actually gets: the config helper agreeing with itself proves nothing
  // if the middleware asks a different question.
  const h = await harness("   ");
  try {
    assert.equal(await h.fetch("/v1/me").then((r) => r.status), 401);
    assert.equal(h.ghCalls(), 0, "a blank credential must not be sent to GitHub for validation");
  } finally {
    h.close();
  }
});

test("with anonymous_token set, a request with no credential is served and says so", async () => {
  const h = await harness(ANON_TOKEN);
  try {
    const res = await h.fetch("/v1/me");
    assert.equal(res.status, 200);
    const body = (await res.json()) as { github_login: string; github_user_id: number; anonymous?: boolean };
    // The identity is the configured credential's, and `anonymous: true` is the only
    // thing in the body that says the caller is not that person: without it a demo page
    // would greet a visitor who never signed in as `iris-demo-bot`.
    assert.equal(body.github_login, ANON_USER.login);
    assert.equal(body.github_user_id, ANON_USER.id);
    assert.equal(body.anonymous, true);
    // Validated through GitHub like any other token, not trusted because it came from
    // config โ€” one `GET /user`, and the second request is served from the same cache a
    // user's token uses.
    assert.equal(h.ghCalls(), 1);
    assert.equal(await h.fetch("/v1/me").then((r) => r.status), 200);
    assert.equal(h.ghCalls(), 1);
  } finally {
    h.close();
  }
});

test("a signed-in caller is unchanged, and carries no anonymous flag", async () => {
  const h = await harness(ANON_TOKEN);
  try {
    const res = await h.fetch("/v1/me", { authorization: `Bearer ${USER_TOKEN}` });
    assert.equal(res.status, 200);
    const body = (await res.json()) as { github_login: string; anonymous?: boolean };
    assert.equal(body.github_login, REAL_USER.login);
    // Absent, not `false`. The key means "this response is not about a person", so it
    // appears only in the mode it describes.
    assert.equal("anonymous" in body, false);
  } finally {
    h.close();
  }
});

// The two shapes below are two tests and not one, because they fail through different
// mechanisms and a single test stops at its first failed assertion. `Bearer <expired>`
// MATCHES the header pattern and dies in validation; `Basic โ€ฆ` never matches and dies at
// the guard. Widening either one leaves the other's assertion unrun and unreported, which
// is the state where a reader edits the first test to match the new behaviour and only
// discovers the second on a later run.

test("a credential GitHub rejects is refused, not downgraded to the shared identity", async () => {
  const h = await harness(ANON_TOKEN);
  try {
    // The tempting behaviour โ€” fall back to the anonymous credential โ€” would serve this
    // caller 200 under a bot account, so its uploads would land somewhere it cannot list
    // and its feedback would be filed as someone else. The failure it needs to see is its
    // own expired token.
    const rejected = await h.fetch("/v1/me", { authorization: "Bearer gho_expired" });
    assert.equal(rejected.status, 401);
    assert.match(((await rejected.json()) as { error: { message: string } }).error.message, /Token validation failed/);
    // And the deployment is still serving anonymous callers, so the 401 above is about
    // this request rather than the mode being off.
    assert.equal(await h.fetch("/v1/me").then((r) => r.status), 200);
  } finally {
    h.close();
  }
});

test("a header that is not a usable Bearer is refused, not read as a missing one", async () => {
  const h = await harness(ANON_TOKEN);
  try {
    // Present but not a Bearer at all: still a client trying to authenticate, so still a
    // 401 rather than a silent downgrade.
    const wrongScheme = await h.fetch("/v1/me", { authorization: "Basic dXNlcjpwYXNz" });
    assert.equal(wrongScheme.status, 401);
    assert.match(
      ((await wrongScheme.json()) as { error: { message: string } }).error.message,
      /Missing or malformed Authorization header/,
    );

    // An empty Bearer, the shape closest to "no header", must land on the same side of the
    // line: the guard is `!header`, not "no token in the header", so a caller who sends the
    // scheme and nothing else is refused rather than served.
    assert.equal(await h.fetch("/v1/me", { authorization: "Bearer " }).then((r) => r.status), 401);

    assert.equal(await h.fetch("/v1/me").then((r) => r.status), 200);
  } finally {
    h.close();
  }
});

test("the session list refuses an anonymous caller and still serves a signed-in one", async () => {
  const h = await harness(ANON_TOKEN);
  try {
    // Two sessions that exist: one owned by the shared anonymous identity, one by a real
    // user. Written through the store rather than by upload, because what is under test is
    // who may READ the list.
    h.store.upsertUser({ github_user_id: ANON_USER.id, github_login: ANON_USER.login }, 1);
    h.store.upsertUser({ github_user_id: REAL_USER.id, github_login: REAL_USER.login }, 1);
    h.store.createSession({ session_id: "ses_anon_one", github_user_id: ANON_USER.id, image_count: 1, iterations_max: 1 });
    h.store.createSession({ session_id: "ses_real_one", github_user_id: REAL_USER.id, image_count: 1, iterations_max: 1 });

    const refused = await h.fetch("/v1/sessions");
    assert.equal(refused.status, 403);
    const body = (await refused.json()) as { error: { code: string; message: string } };
    assert.equal(body.error.code, "anonymous_session_list");
    // The message has to name the remedy, because a client that just uploaded has the one
    // thing that still works and no way to guess it from a bare 403. Both remedies are
    // asserted, one per caller who can land here: the session id for a visitor, and the
    // account for whoever holds the shared credential (see the test below).
    assert.match(body.error.message, /session id returned by POST \/v1\/sessions/);
    assert.match(body.error.message, /sign in with a different one/);

    // The refusal is about the caller, not the route: the same deployment lists a
    // signed-in user's own sessions, and lists only theirs.
    const listed = await h.fetch("/v1/sessions", { authorization: `Bearer ${USER_TOKEN}` });
    assert.equal(listed.status, 200);
    const page = (await listed.json()) as { sessions: { session_id: string }[] };
    assert.deepEqual(
      page.sessions.map((s) => s.session_id),
      ["ses_real_one"],
    );

    // And what an anonymous caller keeps: the session it holds the id of. This is the
    // narrowing the mode trades for โ€” reachability by id, which is `ses_` + a ULID rather
    // than an owner check.
    assert.equal(await h.fetch("/v1/sessions/ses_anon_one").then((r) => r.status), 200);
  } finally {
    h.close();
  }
});

test("the shared account's own token gets the same refusal, not the list", async () => {
  // Round 1 of #458 found this: the flag was keyed on the missing HEADER, so the one caller
  // who can reach the shared identity another way โ€” by presenting its token normally โ€” was
  // served the page the 403 exists to prevent. Measured before the fix: `200` and
  // `{"sessions":[{"session_id":"ses_anon_one",โ€ฆ}]}`, a visitor's document listed by id to
  // whoever holds that account's token, from anywhere, with no access to the server.
  //
  // Docs tell the operator to use a token "of your own", so the caller is not hypothetical:
  // it is the operator signing in to their own deployment.
  const h = await harness(ANON_TOKEN);
  try {
    h.store.upsertUser({ github_user_id: ANON_USER.id, github_login: ANON_USER.login }, 1);
    h.store.createSession({
      session_id: "ses_anon_one",
      github_user_id: ANON_USER.id,
      image_count: 1,
      iterations_max: 1,
    });

    const res = await h.fetch("/v1/sessions", { authorization: `Bearer ${ANON_TOKEN}` });
    assert.equal(res.status, 403);
    const body = (await res.json()) as { error: { code: string; message: string } };
    assert.equal(body.error.code, "anonymous_session_list");
    // And the message has to be usable by THIS caller. "Sign in with GitHub" was the only
    // advice before, which is no advice at all for someone who is signed in.
    assert.match(body.error.message, /github\.anonymous_token/);

    // `/v1/me` agrees, because one flag decides both. A client that trusted `anonymous`
    // to mean "no credential was sent" would be wrong; it means "this is the shared
    // identity", which is the thing every downstream owner check is keyed on.
    const me = (await h.fetch("/v1/me", { authorization: `Bearer ${ANON_TOKEN}` }).then((r) => r.json())) as {
      anonymous?: boolean;
    };
    assert.equal(me.anonymous, true);
  } finally {
    h.close();
  }
});

test("resolving the shared identity costs one lookup and does not break a signed-in caller", async () => {
  const h = await harness(ANON_TOKEN);
  try {
    // A signed-in request has to resolve TWO tokens the first time โ€” its own, and the
    // anonymous credential it is compared against โ€” and then neither again.
    assert.equal(await h.fetch("/v1/me", { authorization: `Bearer ${USER_TOKEN}` }).then((r) => r.status), 200);
    assert.equal(h.ghCalls(), 2, "the caller's token and the shared credential, once each");
    assert.equal(await h.fetch("/v1/me", { authorization: `Bearer ${USER_TOKEN}` }).then((r) => r.status), 200);
    assert.equal(h.ghCalls(), 2, "memoized for the life of the process, so no per-request cost");

    // And the identity comparison did not misfire: a real user is not anonymous because a
    // deployment happens to have the key set.
    const me = (await h.fetch("/v1/me", { authorization: `Bearer ${USER_TOKEN}` }).then((r) => r.json())) as {
      github_login: string;
      anonymous?: boolean;
    };
    assert.equal(me.github_login, REAL_USER.login);
    assert.equal("anonymous" in me, false);
  } finally {
    h.close();
  }
});

test("a REJECTED shared credential is asked about once, not once per request", async () => {
  // The failure mode the lookup above introduces if it is not contained: the deployment's
  // own credential is revoked or mistyped, so resolving it throws โ€” on a request that has
  // nothing to do with it. Two things have to be true at once, and they pull in opposite
  // directions: a caller's working token must not fail because the operator's is broken,
  // AND the failed lookup must not repeat forever. A mistyped config value is not a blip;
  // it is a permanent state, so retrying it charges every authenticated request an extra
  // uncached `GET /user` for the life of the process โ€” including requests whose own token
  // is a cache hit and would otherwise make no outbound call at all. Round 2 of #458.
  const h = await harness("gho_operator_typo");
  try {
    assert.equal(await h.fetch("/v1/me", { authorization: `Bearer ${USER_TOKEN}` }).then((r) => r.status), 200);
    assert.equal(h.ghCalls(), 2, "the caller's token, and one attempt at the shared credential");
    assert.equal(await h.fetch("/v1/me", { authorization: `Bearer ${USER_TOKEN}` }).then((r) => r.status), 200);
    assert.equal(h.ghCalls(), 2, "asked GitHub again about a credential it had already rejected");
    // Latching is only safe because a rejected credential cannot serve an anonymous
    // request either โ€” so while the flag is set, nothing new can reach the shared identity
    // for the guard to have protected. That is this assertion, not a separate concern.
    assert.equal(await h.fetch("/v1/me").then((r) => r.status), 401);
    // The guard is off rather than misapplied: the signed-in caller is still not anonymous.
    const me = (await h.fetch("/v1/me", { authorization: `Bearer ${USER_TOKEN}` }).then((r) => r.json())) as {
      anonymous?: boolean;
    };
    assert.equal("anonymous" in me, false);
  } finally {
    h.close();
  }
});

test("an ANONYMOUS request does not re-ask about a rejected credential either", async () => {
  // Round 3 of #458: the first version of this cache was consulted only on the signed-in
  // branch, so the identical cost stayed on the half an OUTSIDE caller drives. A request
  // with no header goes straight into `resolveUserId`, and a failure writes nothing to the
  // positive cache, so with a mistyped config value every unauthenticated request paid an
  // uncached `GET /user` โ€” with no timeout โ€” before its 401.
  const h = await harness("gho_operator_typo");
  try {
    const first = await h.fetch("/v1/me");
    assert.equal(first.status, 401);
    assert.equal(h.ghCalls(), 1, "the one lookup that learns the credential is rejected");
    const second = await h.fetch("/v1/me");
    assert.equal(h.ghCalls(), 1, "asked GitHub again about a credential it had already rejected");
    // The saving must not be observable. A cached rejection and a fresh one are the same
    // answer to the caller, down to the body โ€” otherwise this becomes a way to ask whether
    // the deployment has spoken to GitHub lately.
    assert.equal(second.status, first.status);
    assert.deepEqual(await second.json(), await first.json());
  } finally {
    h.close();
  }
});

test("a rejection is cached for a bounded window, not for the life of the process", async () => {
  // Why this is a TTL and not a flag that latches: GitHub's auth can answer `Bad
  // credentials` for a token that is fine, and a latch would then 401 every anonymous
  // caller until a human restarted the service โ€” trading a per-request lookup for an
  // outage. Recovery has to need no restart, so the expiry is the mechanism and this is the
  // test of it.
  //
  // Seeded rather than waited for: the TTL is five minutes. Same device as the positive
  // cache's expiry test (test/token-cache.test.ts seeds a stale entry rather than sleeping).
  const BROKEN = "gho_transiently_rejected";
  const h = await harness(BROKEN);
  try {
    assert.equal(await h.fetch("/v1/me").then((r) => r.status), 401);
    assert.equal(h.ghCalls(), 1);
    assert.notEqual(__rejectedCredentialUntil(BROKEN), undefined, "the rejection was not recorded at all");
    // GitHub starts answering for it again โ€” the credential was never actually bad.
    h.ghRecover(BROKEN);
    // Still inside the window: the cached rejection stands, and nothing is asked.
    assert.equal(await h.fetch("/v1/me").then((r) => r.status), 401);
    assert.equal(h.ghCalls(), 1);
    // Now the window has passed.
    __seedRejectedCredential(BROKEN, Date.now() - 1);
    const res = await h.fetch("/v1/me");
    assert.equal(res.status, 200, "a recovered credential stayed refused past its window");
    assert.equal(h.ghCalls(), 2, "the expired entry did not cause a re-ask");
    const body = (await res.json()) as { github_login: string; anonymous?: boolean };
    assert.equal(body.github_login, ANON_USER.login);
    // And the guard is armed again on the same request, not one later: this response is the
    // one that re-resolves the shared identity.
    assert.equal(body.anonymous, true);
    // The expired entry is dropped on read rather than accumulating.
    assert.equal(__rejectedCredentialUntil(BROKEN), undefined, "an expired entry was left in the map");
  } finally {
    h.close();
  }
});

test("serving a cached rejection does not push its own expiry out", async () => {
  // Round 4 of #458, and the defect the TTL was introduced to prevent, reintroduced by the
  // mechanism that answers it. The cached refusal is raised as `userLookupError(401)` so the
  // reply comes from one place โ€” but that error is indistinguishable from a fresh rejection
  // to the `catch` that RECORDS rejections, so every anonymous request served from the cache
  // rewrote the expiry to `now + TTL_MS`. Any deployment seeing an anonymous request more
  // often than once per TTL โ€” which is every deployment that turned the mode on for a reason
  // โ€” never reaches the expiry, so a TTL under traffic was exactly the process-lifetime latch
  // it replaced: one spurious `Bad credentials` would 401 anonymous callers until a restart,
  // and hold the round-1 session-list guard off for that whole time.
  //
  // The window test above cannot see it, because forcing the expiry with a seed OVERWRITES a
  // slid entry. So this asserts the stored instant itself, and pins it to a known value
  // first: a renewal then moves it by the whole TTL rather than by however many milliseconds
  // the two requests happen to be apart, which would be a race against the clock.
  const BROKEN = "gho_transiently_rejected";
  const h = await harness(BROKEN);
  try {
    assert.equal(await h.fetch("/v1/me").then((r) => r.status), 401);
    assert.equal(h.ghCalls(), 1);
    const until = Date.now() + 1_000;
    __seedRejectedCredential(BROKEN, until);

    assert.equal(await h.fetch("/v1/me").then((r) => r.status), 401);
    assert.equal(h.ghCalls(), 1, "the cached answer was served, so GitHub was not asked");
    assert.equal(
      __rejectedCredentialUntil(BROKEN),
      until,
      "an anonymous request served FROM the cache extended it, so the window never closes under traffic",
    );
  } finally {
    h.close();
  }
});

test("a CALLER's rejected token is never recorded as a rejected credential", async () => {
  // The bound on the negative cache. It has no ceiling and no eviction sweep, which is only
  // safe because nothing a caller sends can create an entry โ€” a map keyed on whatever
  // arrives in a header is the unbounded one `MAX_ENTRIES` exists to prevent, and distinct
  // bearer strings are free to produce. Two shapes have to be checked, because the guard is
  // `servedAnonymously` rather than a comparison against the configured value: an ordinary
  // bad token, and a caller presenting the deployment's OWN credential.
  const h = await harness(ANON_TOKEN);
  try {
    assert.equal(await h.fetch("/v1/me", { authorization: "Bearer gho_not_a_real_token" }).then((r) => r.status), 401);
    assert.equal(__rejectedCredentialUntil("gho_not_a_real_token"), undefined, "a caller's token entered the map");
    // The deployment's own credential, presented by a caller, resolves fine here โ€” the point
    // is that this path cannot write to the map even when the token IS the configured one.
    assert.equal(await h.fetch("/v1/me", { authorization: `Bearer ${ANON_TOKEN}` }).then((r) => r.status), 200);
    assert.equal(__rejectedCredentialUntil(ANON_TOKEN), undefined);
  } finally {
    h.close();
  }
});

test("a shared credential GitHub cannot answer about is retried, not latched off", async () => {
  // The other half, and the reason the memoization above is keyed on 401 alone. A 502 (or a
  // 5xx, a 403 rate limit, a thrown fetch) says GitHub could not answer, not that the
  // answer is no โ€” and the credential behind it may be perfectly good, still serving
  // anonymous sessions the moment GitHub recovers. Latching there would switch the guard
  // off for the rest of the process over a blip, which is the session list this PR exists
  // to close. So this one pays the repeated lookup, on purpose.
  const h = await harness(UNANSWERABLE_TOKEN);
  try {
    assert.equal(await h.fetch("/v1/me", { authorization: `Bearer ${USER_TOKEN}` }).then((r) => r.status), 200);
    assert.equal(h.ghCalls(), 2, "the caller's token, and one attempt at the shared credential");
    assert.equal(await h.fetch("/v1/me", { authorization: `Bearer ${USER_TOKEN}` }).then((r) => r.status), 200);
    assert.equal(h.ghCalls(), 3, "gave up on a credential GitHub had merely failed to answer about");
  } finally {
    h.close();
  }
});

// The rate-limit key, driven through `uploadRateLimit` with the auth result stubbed: what
// is under test is which bucket a request lands in, and reaching the real upload route
// would mean standing up multer and a pipeline to assert something decided before either.
//
// Two addresses from one process, which needs `trust proxy` โ€” the same device
// test/request-limits.test.ts uses for the forged-header case, and the only way to have
// two callers in one test file.
//
// Stubbing the auth result means these two cannot see whether a real request arrives at the
// limiter with the flag already on. That it does is an ordering fact, checked by reading
// rather than asserted here: `uploadBudget` is mounted inside the sessions router
// (src/routes/sessions.ts:274), and src/index.ts:144 mounts that router behind `auth`. The
// `/v1` general limiter is the one that runs first, which is why it has no anonymous
// branch at all.
async function serveUploadLimit(
  limits: Partial<RateLimitConfig>,
  stub: (req: AuthedRequest) => void,
): Promise<{ as: (ip: string) => Promise<number>; close: () => void }> {
  const app = express();
  app.set("trust proxy", normalizeTrustProxy(1));
  const config = {
    server: { port: 0, base_url: "http://localhost:0", rate_limits: limits },
  } as unknown as IrisConfig;
  app.use(
    "/upload",
    (req, _res, next) => {
      stub(req as AuthedRequest);
      next();
    },
    uploadRateLimit(config),
    (_req, res) => void res.json({ ok: true }),
  );
  const server = app.listen(0);
  await new Promise((r) => server.once("listening", r));
  const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/upload`;
  return {
    as: (ip: string) => fetch(url, { method: "POST", headers: { "x-forwarded-for": ip } }).then((r) => r.status),
    close: () => server.close(),
  };
}

test("anonymous uploads are counted per address, not against the shared identity", async () => {
  // Every anonymous caller is `iris-demo-bot` as far as the store is concerned. Keyed on
  // that user id, one upload per minute would be one upload per minute for the whole
  // internet โ€” and the symptom is a deployment that looks healthy and is permanently at
  // its limit for everyone but the first visitor.
  const anon = await serveUploadLimit({ upload_per_minute: 1 }, (req) => {
    req.user = { github_user_id: ANON_USER.id, github_login: ANON_USER.login, max_review_iterations: 1 } as AuthedRequest["user"];
    req.anonymous = true;
  });
  try {
    assert.equal(await anon.as("10.0.0.1"), 200);
    assert.equal(await anon.as("10.0.0.2"), 200, "a second visitor must not be paying for the first");
    assert.equal(await anon.as("10.0.0.1"), 429, "and each address still has a budget of its own");
  } finally {
    anon.close();
  }
});

test("a signed-in user's uploads are still counted per user, across addresses", async () => {
  // The other axis, and the reason the branch is on `anonymous` rather than on "is there a
  // user": per-user keying is what makes Iris usable from a campus NAT, so switching
  // uploads to per-address wholesale would be a regression that this file's other test
  // could not see. One user, two addresses, one budget.
  const signedIn = await serveUploadLimit({ upload_per_minute: 1 }, (req) => {
    req.user = { github_user_id: REAL_USER.id, github_login: REAL_USER.login, max_review_iterations: 1 } as AuthedRequest["user"];
  });
  try {
    assert.equal(await signedIn.as("10.0.0.1"), 200);
    assert.equal(await signedIn.as("10.0.0.2"), 429, "the same user from a second address shares one bucket");
  } finally {
    signedIn.close();
  }
});

test("one rule decides whether the key is set, so the warning cannot contradict the behaviour", () => {
  // `${IRIS_ANONYMOUS_TOKEN}` unset expands to `""`, not to a missing key (`expandEnv`), and a
  // YAML value can be whitespace. Both mean OFF, and both have to mean off in the same way in
  // two places: the middleware decides whether to serve an anonymous request, and the boot log
  // tells the operator which deployment they have. Split rules here would print "anonymous
  // access is on" over a service that 401s every anonymous call โ€” a bug hunt in the wrong half.
  const off = (v: string | undefined) => ({ github: { anonymous_token: v } }) as unknown as IrisConfig;
  assert.equal(anonymousToken(off(undefined)), undefined);
  assert.equal(anonymousToken(off("")), undefined);
  assert.equal(anonymousToken(off("   ")), undefined);
  // And a real value survives, trimmed โ€” a token pasted with a trailing newline still works.
  assert.equal(anonymousToken(off(` ${ANON_TOKEN}\n`)), ANON_TOKEN);
});

test("the boot warning fires only when the key is set, and never prints the credential", () => {
  assert.equal(anonymousTokenWarning(undefined), undefined);
  assert.equal(anonymousTokenWarning(""), undefined);
  const warning = anonymousTokenWarning(ANON_TOKEN) ?? "";
  // The four consequences an operator cannot see from outside, each named. Asserted
  // because this string is the only place the deployment states its own policy, and a
  // warning that says "anonymous access is on" without saying what that costs is the
  // version of this that would have shipped.
  assert.match(warning, /GET \/v1\/sessions refuses them/);
  assert.match(warning, /rate limited by address/);
  assert.match(warning, /filed under this credential's account/);
  // The fourth is the one an operator acts on when CHOOSING the account, and it is the
  // only consequence that lands on them rather than on a visitor: this token's own
  // account gets the same 403. Round 1 of #458 is what added it โ€” before the fix the
  // account was exempt, and being exempt is what made the token a session list for
  // every visitor. So the warning has to ask for a dedicated account and say why.
  assert.match(warning, /this credential's own account gets it too/);
  assert.match(warning, /no person needs/, "asked for nothing of the operator");
  assert.match(warning, /lists every visitor's/, "named the requirement without its reason");
  // A boot log gets pasted into issues. This is the one config value that is a live
  // GitHub token for a real account, so no part of it appears here.
  assert.equal(warning.includes(ANON_TOKEN), false);
  assert.equal(warning.includes(ANON_TOKEN.slice(0, 8)), false);
});