File size: 23,047 Bytes
5cb63c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
645
646
647
648
649
650
// Plugin HTTP routing tests cover route matching, gateway auth decisions, and upgrade dispatch.
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import type { Duplex } from "node:stream";
import { afterEach, describe, expect, it, vi } from "vitest";
import { PluginInstance } from "../../plugins/plugin-instance.js";
import { createEmptyPluginRegistry } from "../../plugins/registry.js";
import { setActivePluginRegistry } from "../../plugins/runtime.js";
import { getPluginRuntimeGatewayRequestScope } from "../../plugins/runtime/gateway-request-scope.js";
import { makeMockHttpResponse } from "../test-http-response.js";
import { createGatewayTestRegistry } from "./__tests__/test-utils.js";
import {
  createGatewayPluginUpgradeHandler,
  createGatewayPluginRequestHandler,
  isPluginAuthenticatedRoutePath,
  isRegisteredPluginHttpRoutePath,
  shouldEnforceGatewayAuthForPluginPath,
} from "./plugins-http.js";

type PluginHandlerLog = Parameters<typeof createGatewayPluginRequestHandler>[0]["log"];

const CANVAS_WS_PATH = "/__openclaw__/canvas/ws";

function createPluginLog(): PluginHandlerLog {
  return { warn: vi.fn() } as unknown as PluginHandlerLog;
}

function createRoute(params: {
  path: string;
  pluginId?: string;
  auth?: "gateway" | "plugin";
  match?: "exact" | "prefix";
  handler?: (req: IncomingMessage, res: ServerResponse) => boolean | void | Promise<boolean | void>;
  handleUpgrade?: (
    req: IncomingMessage,
    socket: Duplex,
    head: Buffer,
  ) => boolean | void | Promise<boolean | void>;
}) {
  return {
    pluginId: params.pluginId ?? "route",
    path: params.path,
    auth: params.auth ?? "plugin",
    match: params.match ?? "exact",
    handler: params.handler ?? (() => {}),
    handleUpgrade: params.handleUpgrade,
    source: params.pluginId ?? "route",
  };
}

function createMockUpgradeSocket() {
  const socket = {
    chunks: [] as string[],
    destroyed: false,
    write(chunk: string) {
      socket.chunks.push(chunk);
    },
    end(chunk: string, callback: () => void) {
      socket.write(chunk);
      callback();
    },
    destroy() {
      socket.destroyed = true;
    },
  } as unknown as Duplex & { chunks: string[]; destroyed: boolean };
  return socket;
}

function buildRepeatedEncodedSlash(depth: number): string {
  let encodedSlash = "%2f";
  for (let i = 1; i < depth; i++) {
    encodedSlash = encodedSlash.replace(/%/g, "%25");
  }
  return encodedSlash;
}

function createSecurePluginRouteHandler(params: {
  exactPluginHandler: () => boolean | Promise<boolean>;
  prefixGatewayHandler: () => boolean | Promise<boolean>;
}) {
  return createGatewayPluginRequestHandler({
    registry: createGatewayTestRegistry({
      httpRoutes: [
        createRoute({
          path: "/plugin/secure/report",
          match: "exact",
          auth: "plugin",
          handler: params.exactPluginHandler,
        }),
        createRoute({
          path: "/plugin/secure",
          match: "prefix",
          auth: "gateway",
          handler: params.prefixGatewayHandler,
        }),
      ],
    }),
    log: createPluginLog(),
  });
}

async function invokeSecureGatewayRoute(params: {
  gatewayAuthSatisfied: boolean;
  gatewayRequestOperatorScopes?: readonly string[];
}) {
  const exactPluginHandler = vi.fn(async () => false);
  const prefixGatewayHandler = vi.fn(async () => true);
  const handler = createSecurePluginRouteHandler({
    exactPluginHandler,
    prefixGatewayHandler,
  });
  const { res } = makeMockHttpResponse();
  const handled = await handler(
    { url: "/plugin/secure/report" } as IncomingMessage,
    res,
    undefined,
    {
      gatewayAuthSatisfied: params.gatewayAuthSatisfied,
      gatewayRequestOperatorScopes: params.gatewayRequestOperatorScopes,
    },
  );
  return { handled, exactPluginHandler, prefixGatewayHandler };
}

async function invokeRouteAndCollectRuntimeScopes(params: {
  path: string;
  auth: "gateway" | "plugin";
  gatewayAuthSatisfied: boolean;
  gatewayRequestOperatorScopes?: readonly string[];
}) {
  let observedScopes: string[] | undefined;
  const handler = createGatewayPluginRequestHandler({
    registry: createGatewayTestRegistry({
      httpRoutes: [
        createRoute({
          path: params.path,
          auth: params.auth,
          handler: async () => {
            observedScopes =
              getPluginRuntimeGatewayRequestScope()?.client?.connect?.scopes?.slice() ?? [];
            return true;
          },
        }),
      ],
    }),
    log: createPluginLog(),
  });

  const response = makeMockHttpResponse();
  const handled = await handler({ url: params.path } as IncomingMessage, response.res, undefined, {
    gatewayAuthSatisfied: params.gatewayAuthSatisfied,
    gatewayRequestOperatorScopes: params.gatewayRequestOperatorScopes,
  });
  return { handled, observedScopes, ...response };
}

async function invokeCanvasGatewayUpgrade(params: { gatewayAuthSatisfied: boolean }) {
  const routeUpgradeHandler = vi.fn(async () => true);
  const handler = createGatewayPluginUpgradeHandler({
    registry: createGatewayTestRegistry({
      httpRoutes: [
        createRoute({
          path: CANVAS_WS_PATH,
          auth: "gateway",
          handleUpgrade: routeUpgradeHandler,
        }),
      ],
    }),
    log: createPluginLog(),
  });
  const socket = createMockUpgradeSocket();
  const handled = await handler(
    { url: CANVAS_WS_PATH } as IncomingMessage,
    socket,
    Buffer.alloc(0),
    undefined,
    {
      gatewayAuthSatisfied: params.gatewayAuthSatisfied,
      ...(params.gatewayAuthSatisfied ? { gatewayRequestOperatorScopes: ["operator.read"] } : {}),
    },
  );
  return { handled, routeUpgradeHandler, socket };
}

describe("createGatewayPluginRequestHandler", () => {
  afterEach(() => {
    setActivePluginRegistry(createEmptyPluginRegistry());
  });

  it("fences an identity-preserved route after its plugin instance retires", async () => {
    const instance = new PluginInstance("identity-route");
    const routeHandler = instance.adopt(vi.fn(async () => true));
    const log = createPluginLog();
    const handler = createGatewayPluginRequestHandler({
      registry: createGatewayTestRegistry({
        httpRoutes: [createRoute({ path: "/identity", handler: routeHandler })],
      }),
      log,
    });
    await instance.dispose();

    const { res } = makeMockHttpResponse();
    await expect(handler({ url: "/identity" } as IncomingMessage, res)).resolves.toBe(true);
    expect(routeHandler).not.toHaveBeenCalled();
    expect(log.warn).toHaveBeenCalledWith(
      expect.stringContaining("Plugin identity-route was reloaded or disabled"),
    );
  });

  it("keeps unauthenticated plugin routes off operator runtime scopes", async () => {
    const { handled, observedScopes, res } = await invokeRouteAndCollectRuntimeScopes({
      path: "/hook",
      auth: "plugin",
      gatewayAuthSatisfied: false,
    });

    expect(handled).toBe(true);
    expect(res.statusCode).toBe(200);
    expect(observedScopes).toStrictEqual([]);
  });

  it("preserves gateway-authenticated plugin route runtime scopes from request auth", async () => {
    const { handled, observedScopes, res } = await invokeRouteAndCollectRuntimeScopes({
      path: "/secure-hook",
      auth: "gateway",
      gatewayAuthSatisfied: true,
      gatewayRequestOperatorScopes: ["operator.read"],
    });

    expect(handled).toBe(true);
    expect(res.statusCode).toBe(200);
    expect(observedScopes).toEqual(["operator.read"]);
  });

  it("returns false when no routes are registered", async () => {
    const log = createPluginLog();
    const handler = createGatewayPluginRequestHandler({
      registry: createGatewayTestRegistry(),
      log,
    });
    const { res } = makeMockHttpResponse();
    const handled = await handler({} as IncomingMessage, res);
    expect(handled).toBe(false);
  });

  it("handles exact route matches", async () => {
    const routeHandler = vi.fn(async (_req, res: ServerResponse) => {
      res.statusCode = 200;
    });
    const handler = createGatewayPluginRequestHandler({
      registry: createGatewayTestRegistry({
        httpRoutes: [createRoute({ path: "/demo", handler: routeHandler })],
      }),
      log: createPluginLog(),
    });

    const { res } = makeMockHttpResponse();
    const handled = await handler({ url: "/demo" } as IncomingMessage, res);
    expect(handled).toBe(true);
    expect(routeHandler).toHaveBeenCalledTimes(1);
  });

  it("prefers exact matches before prefix matches", async () => {
    const exactHandler = vi.fn(async (_req, res: ServerResponse) => {
      res.statusCode = 200;
    });
    const prefixHandler = vi.fn(async () => true);
    const handler = createGatewayPluginRequestHandler({
      registry: createGatewayTestRegistry({
        httpRoutes: [
          createRoute({ path: "/api", match: "prefix", handler: prefixHandler }),
          createRoute({ path: "/api/demo", match: "exact", handler: exactHandler }),
        ],
      }),
      log: createPluginLog(),
    });

    const { res } = makeMockHttpResponse();
    const handled = await handler({ url: "/api/demo" } as IncomingMessage, res);
    expect(handled).toBe(true);
    expect(exactHandler).toHaveBeenCalledTimes(1);
    expect(prefixHandler).not.toHaveBeenCalled();
  });

  it("supports route fallthrough when handler returns false", async () => {
    const first = vi.fn(async () => false);
    const second = vi.fn(async () => true);
    const handler = createGatewayPluginRequestHandler({
      registry: createGatewayTestRegistry({
        httpRoutes: [
          createRoute({ path: "/hook", match: "exact", handler: first }),
          createRoute({ path: "/hook", match: "prefix", handler: second }),
        ],
      }),
      log: createPluginLog(),
    });

    const { res } = makeMockHttpResponse();
    const handled = await handler({ url: "/hook" } as IncomingMessage, res);
    expect(handled).toBe(true);
    expect(first).toHaveBeenCalledTimes(1);
    expect(second).toHaveBeenCalledTimes(1);
  });

  it("fails closed when a matched gateway route reaches dispatch without auth", async () => {
    const { handled, exactPluginHandler, prefixGatewayHandler } = await invokeSecureGatewayRoute({
      gatewayAuthSatisfied: false,
    });
    expect(handled).toBe(false);
    expect(exactPluginHandler).not.toHaveBeenCalled();
    expect(prefixGatewayHandler).not.toHaveBeenCalled();
  });

  it("keeps hosted-media bearer query strings out of route-auth logs", async () => {
    const warn = vi.fn();
    const log = { warn } as unknown as PluginHandlerLog;
    const handler = createGatewayPluginRequestHandler({
      registry: createGatewayTestRegistry({
        httpRoutes: [createRoute({ path: "/webhooks/sms", auth: "gateway" })],
      }),
      log,
    });
    const tokenParam = `__openclaw_mms_token_${"a".repeat(24)}`;
    const { res } = makeMockHttpResponse();

    const handled = await handler(
      {
        url: `/webhooks/sms?upstream-token=proxy-secret&${tokenParam}=media-secret`,
      } as IncomingMessage,
      res,
      undefined,
      { gatewayAuthSatisfied: false },
    );

    expect(handled).toBe(false);
    expect(warn).toHaveBeenCalledWith(
      "plugin http route blocked without gateway auth (/webhooks/sms)",
    );
    expect(JSON.stringify(warn.mock.calls)).not.toContain("proxy-secret");
    expect(JSON.stringify(warn.mock.calls)).not.toContain("media-secret");
  });

  it("allows gateway route fallthrough only after gateway auth succeeds", async () => {
    const { handled, exactPluginHandler, prefixGatewayHandler } = await invokeSecureGatewayRoute({
      gatewayAuthSatisfied: true,
      gatewayRequestOperatorScopes: ["operator.write"],
    });
    expect(handled).toBe(true);
    expect(exactPluginHandler).toHaveBeenCalledTimes(1);
    expect(prefixGatewayHandler).toHaveBeenCalledTimes(1);
  });

  it("fails closed when gateway route dispatch lacks caller scopes", async () => {
    const { handled, exactPluginHandler, prefixGatewayHandler } = await invokeSecureGatewayRoute({
      gatewayAuthSatisfied: true,
    });
    expect(handled).toBe(false);
    expect(exactPluginHandler).not.toHaveBeenCalled();
    expect(prefixGatewayHandler).not.toHaveBeenCalled();
  });

  it("matches canonicalized route variants", async () => {
    const routeHandler = vi.fn(async (_req, res: ServerResponse) => {
      res.statusCode = 200;
    });
    const handler = createGatewayPluginRequestHandler({
      registry: createGatewayTestRegistry({
        httpRoutes: [createRoute({ path: "/api/demo", handler: routeHandler })],
      }),
      log: createPluginLog(),
    });

    const { res } = makeMockHttpResponse();
    const handled = await handler({ url: "/API//demo" } as IncomingMessage, res);
    expect(handled).toBe(true);
    expect(routeHandler).toHaveBeenCalledTimes(1);
  });

  it("uses the explicit registry when no route registry resolver is provided", async () => {
    const explicitRouteHandler = vi.fn(async (_req, res: ServerResponse) => {
      res.statusCode = 200;
      return true;
    });
    const explicitRegistry = createGatewayTestRegistry({
      httpRoutes: [createRoute({ path: "/demo", auth: "plugin", handler: explicitRouteHandler })],
    });

    const handler = createGatewayPluginRequestHandler({
      registry: explicitRegistry,
      log: createPluginLog(),
    });

    const { res } = makeMockHttpResponse();
    const handled = await handler({ url: "/demo" } as IncomingMessage, res);
    expect(handled).toBe(true);
    expect(explicitRouteHandler).toHaveBeenCalledTimes(1);
  });

  it("logs and responds with 500 when a route throws", async () => {
    const log = createPluginLog();
    const handler = createGatewayPluginRequestHandler({
      registry: createGatewayTestRegistry({
        httpRoutes: [
          createRoute({
            path: "/boom",
            handler: async () => {
              throw new Error("boom");
            },
          }),
        ],
      }),
      log,
    });

    const { res, setHeader, end } = makeMockHttpResponse();
    const handled = await handler({ url: "/boom" } as IncomingMessage, res);
    expect(handled).toBe(true);
    expect(log.warn).toHaveBeenCalledWith("plugin http route failed (route): Error: boom");
    expect(res.statusCode).toBe(500);
    expect(setHeader).toHaveBeenCalledWith("Content-Type", "text/plain; charset=utf-8");
    expect(end).toHaveBeenCalledWith("Internal Server Error");
  });

  it("aborts an incomplete unframed response when the plugin route throws", async () => {
    const log = createPluginLog();
    const handler = createGatewayPluginRequestHandler({
      registry: createGatewayTestRegistry({
        httpRoutes: [
          createRoute({
            path: "/partial",
            handler: async (_req, res) => {
              res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
              res.write("partial");
              throw new Error("boom");
            },
          }),
        ],
      }),
      log,
    });
    const server = createServer((req, res) => {
      void (async () => {
        const handled = await handler(req, res);
        if (!handled) {
          res.statusCode = 404;
          res.end("not found");
        }
      })();
    });

    await new Promise<void>((resolve, reject) => {
      server.once("error", reject);
      server.listen(0, "127.0.0.1", () => resolve());
    });

    const address = server.address();
    if (!address || typeof address === "string") {
      throw new Error("server did not bind to a TCP port");
    }
    try {
      await expect(
        fetch(`http://127.0.0.1:${address.port}/partial`, {
          signal: AbortSignal.timeout(1_000),
        }).then(async (response) => await response.text()),
      ).rejects.toMatchObject({ name: "TypeError" });
      expect(log.warn).toHaveBeenCalledWith("plugin http route failed (route): Error: boom");
    } finally {
      server.closeAllConnections();
      await new Promise<void>((resolve) => {
        server.close(() => resolve());
      });
    }
  });

  it.each([
    {
      label: "setHeader",
      setContentLength: (res: ServerResponse) => res.setHeader("Content-Length", "10"),
    },
    {
      label: "writeHead",
      setContentLength: (res: ServerResponse) => res.writeHead(200, { "Content-Length": "10" }),
    },
  ])(
    "closes an incomplete plugin $label fixed-length response after its route throws",
    async ({ setContentLength }) => {
      const log = createPluginLog();
      const handler = createGatewayPluginRequestHandler({
        registry: createGatewayTestRegistry({
          httpRoutes: [
            createRoute({
              path: "/incomplete",
              handler: async (_req, res) => {
                setContentLength(res);
                res.write("partial");
                throw new Error("boom");
              },
            }),
          ],
        }),
        log,
      });
      const server = createServer((req, res) => {
        void handler(req, res);
      });

      await new Promise<void>((resolve, reject) => {
        server.once("error", reject);
        server.listen(0, "127.0.0.1", () => resolve());
      });
      const address = server.address();
      if (!address || typeof address === "string") {
        throw new Error("server did not bind to a TCP port");
      }

      try {
        await expect(
          fetch(`http://127.0.0.1:${address.port}/incomplete`, {
            signal: AbortSignal.timeout(500),
          }).then(async (response) => await response.text()),
        ).rejects.toMatchObject({ name: "TypeError" });
      } finally {
        server.closeAllConnections();
        await new Promise<void>((resolve) => {
          server.close(() => resolve());
        });
      }
    },
  );

  it("does not end a response the plugin already destroyed before throwing", async () => {
    const log = createPluginLog();
    const handler = createGatewayPluginRequestHandler({
      registry: createGatewayTestRegistry({
        httpRoutes: [
          createRoute({
            path: "/destroyed",
            handler: async (_req, res) => {
              Object.defineProperty(res, "headersSent", { value: true, configurable: true });
              res.destroy();
              throw new Error("boom");
            },
          }),
        ],
      }),
      log,
    });
    const { res, end } = makeMockHttpResponse();

    const handled = await handler({ url: "/destroyed" } as IncomingMessage, res);

    expect(handled).toBe(true);
    expect(res.destroyed).toBe(true);
    expect(end).not.toHaveBeenCalled();
    expect(log.warn).toHaveBeenCalledWith("plugin http route failed (route): Error: boom");
  });
});

describe("createGatewayPluginUpgradeHandler", () => {
  afterEach(() => {
    setActivePluginRegistry(createEmptyPluginRegistry());
  });

  it("claims and rejects matched gateway upgrades when auth was not satisfied", async () => {
    const { handled, routeUpgradeHandler, socket } = await invokeCanvasGatewayUpgrade({
      gatewayAuthSatisfied: false,
    });

    expect(handled).toBe(true);
    expect(routeUpgradeHandler).not.toHaveBeenCalled();
    expect(socket.destroyed).toBe(true);
    expect(socket.chunks.join("")).toContain("HTTP/1.1 401 Unauthorized");
  });

  it("dispatches gateway upgrades after gateway auth succeeds", async () => {
    const { handled, routeUpgradeHandler, socket } = await invokeCanvasGatewayUpgrade({
      gatewayAuthSatisfied: true,
    });

    expect(handled).toBe(true);
    expect(routeUpgradeHandler).toHaveBeenCalledTimes(1);
    expect(socket.destroyed).toBe(false);
    expect(socket.chunks).toStrictEqual([]);
  });
});

describe("plugin HTTP route auth checks", () => {
  const deeplyEncodedChannelPath =
    "/api%2525252fchannels%2525252fnostr%2525252fdefault%2525252fprofile";
  const decodeOverflowPublicPath = `/googlechat${buildRepeatedEncodedSlash(40)}public`;

  it("detects registered route paths", () => {
    const registry = createGatewayTestRegistry({
      httpRoutes: [createRoute({ path: "/demo" })],
    });
    expect(isRegisteredPluginHttpRoutePath(registry, "/demo")).toBe(true);
    expect(isRegisteredPluginHttpRoutePath(registry, "/missing")).toBe(false);
  });

  it("matches canonicalized variants of registered route paths", () => {
    const registry = createGatewayTestRegistry({
      httpRoutes: [createRoute({ path: "/api/demo" })],
    });
    expect(isRegisteredPluginHttpRoutePath(registry, "/api//demo")).toBe(true);
    expect(isRegisteredPluginHttpRoutePath(registry, "/API/demo")).toBe(true);
    expect(isRegisteredPluginHttpRoutePath(registry, "/api/%2564emo")).toBe(true);
  });

  it("enforces auth for protected and gateway-auth routes", () => {
    const registry = createGatewayTestRegistry({
      httpRoutes: [
        createRoute({ path: "/googlechat", match: "prefix", auth: "plugin" }),
        createRoute({ path: "/api/demo", auth: "gateway" }),
      ],
    });
    expect(shouldEnforceGatewayAuthForPluginPath(registry, "/api//demo")).toBe(true);
    expect(shouldEnforceGatewayAuthForPluginPath(registry, "/googlechat/public")).toBe(false);
    expect(shouldEnforceGatewayAuthForPluginPath(registry, "/api/channels/status")).toBe(true);
    expect(shouldEnforceGatewayAuthForPluginPath(registry, deeplyEncodedChannelPath)).toBe(true);
    expect(shouldEnforceGatewayAuthForPluginPath(registry, decodeOverflowPublicPath)).toBe(true);
    expect(shouldEnforceGatewayAuthForPluginPath(registry, "/not-plugin")).toBe(false);
  });

  it("enforces auth when any overlapping matched route requires gateway auth", () => {
    const registry = createGatewayTestRegistry({
      httpRoutes: [
        createRoute({ path: "/plugin/secure/report", match: "exact", auth: "plugin" }),
        createRoute({ path: "/plugin/secure", match: "prefix", auth: "gateway" }),
      ],
    });
    expect(shouldEnforceGatewayAuthForPluginPath(registry, "/plugin/secure/report")).toBe(true);
  });

  it("recognizes only existing, unambiguous plugin-authenticated routes", () => {
    const registry = createGatewayTestRegistry({
      httpRoutes: [
        createRoute({ path: "/googlechat", match: "prefix", auth: "plugin" }),
        createRoute({ path: "/plugin/secure", match: "prefix", auth: "gateway" }),
        createRoute({ path: "/plugin/secure/report", auth: "plugin" }),
      ],
    });

    expect(isPluginAuthenticatedRoutePath(registry, "/googlechat")).toBe(true);
    expect(isPluginAuthenticatedRoutePath(registry, "/googlechat/events")).toBe(true);
    expect(isPluginAuthenticatedRoutePath(registry, "/missing")).toBe(false);
    expect(isPluginAuthenticatedRoutePath(registry, "/api/channels/status")).toBe(false);
    expect(isPluginAuthenticatedRoutePath(registry, "/plugin/secure/report")).toBe(false);
    expect(isPluginAuthenticatedRoutePath(registry, decodeOverflowPublicPath)).toBe(false);
  });
});