feat: serve plugin http and websockets from one mount instead of ports

This commit is contained in:
LukeGus committed 2026-09-22 16:39:41 -05:00
1 parent c496a093ca
commit 8431570ff7
102 files changed
+2894 -2308

No files matched your search

@@ -1,137 +0,0 @@
/**
* /plugin-api is mounted behind authenticateJWT in database.ts, the same way
* every other router is gated, so an unauthenticated caller can never reach
* plugin code.
*
* The dispatcher itself has no routes registered in A1: the worker HTTP
* bridge was removed with the worker tier and A4 rebuilds routing on top of
* the SDK. What still has to hold, and what this covers, is that the auth
* gate sits in front of the mount and that an unknown plugin id is a 404
* rather than a crash.
*/
import { afterEach, describe, expect, it, vi } from "vitest";
import express from "express";
import type { AddressInfo } from "node:net";
import type { Server } from "node:http";
const state = vi.hoisted(() => ({
validToken: "valid-token",
userId: "user-1",
}));
vi.mock("../../../utils/logger.js", () => ({
databaseLogger: {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
success: vi.fn(),
},
}));
const pluginApi = await import("../../../database/routes/plugin-api-routes.js");
/** Stands in for AuthManager's middleware, with the same 401 behaviour. */
function authenticateJWT(
req: express.Request,
res: express.Response,
next: express.NextFunction,
): void {
const header = req.headers.authorization;
const token = header?.startsWith("Bearer ") ? header.slice(7) : null;
if (token !== state.validToken) {
res.status(401).json({ error: "Unauthorized" });
return;
}
(req as express.Request & { userId?: string }).userId = state.userId;
next();
}
let server: Server | null = null;
async function startServer(): Promise<string> {
const app = express();
// The same order database.ts uses: the gate, then the dispatcher.
app.use("/plugin-api", authenticateJWT, pluginApi.default);
return new Promise((resolve) => {
server = app.listen(0, "127.0.0.1", () => {
const { port } = server!.address() as AddressInfo;
resolve(`http://127.0.0.1:${port}`);
});
});
}
afterEach(async () => {
if (server) {
await new Promise((resolve) => server!.close(() => resolve(undefined)));
server = null;
}
for (const id of pluginApi.getRegisteredPluginIds()) {
pluginApi.unregisterPluginRouter(id);
}
});
describe("/plugin-api authentication", () => {
it("rejects a request with no token", async () => {
const base = await startServer();
const response = await fetch(`${base}/plugin-api/sample-plugin/thing`);
expect(response.status).toBe(401);
});
it("rejects a request with the wrong token", async () => {
const base = await startServer();
const response = await fetch(`${base}/plugin-api/sample-plugin/thing`, {
headers: { Authorization: "Bearer nope" },
});
expect(response.status).toBe(401);
});
// Past the gate, an id nothing registered is a plain 404. The auth check
// runs first either way, so a caller cannot use the difference between 401
// and 404 to find out which plugins are installed.
it("returns 404 for an unregistered plugin id when authenticated", async () => {
const base = await startServer();
const response = await fetch(`${base}/plugin-api/sample-plugin/thing`, {
headers: { Authorization: `Bearer ${state.validToken}` },
});
expect(response.status).toBe(404);
});
it("dispatches to a registered router only when authenticated", async () => {
const router = express.Router();
router.get("/thing", (req, res) => {
res.json({
ok: true,
userId: (req as express.Request & { userId?: string }).userId,
});
});
pluginApi.registerPluginRouter("sample-plugin", router);
const base = await startServer();
const unauthorized = await fetch(`${base}/plugin-api/sample-plugin/thing`);
expect(unauthorized.status).toBe(401);
const authorized = await fetch(`${base}/plugin-api/sample-plugin/thing`, {
headers: { Authorization: `Bearer ${state.validToken}` },
});
expect(authorized.status).toBe(200);
// The user id the plugin sees is the one the gate verified, never one the
// caller supplied.
expect(await authorized.json()).toEqual({
ok: true,
userId: state.userId,
});
});
});
@@ -56,7 +56,7 @@ vi.mock("../../../utils/audit-logger.js", () => ({
getAuditUsername: vi.fn(async (id: string) => id.toUpperCase()),
getRequestMeta: () => ({ ipAddress: "127.0.0.1", userAgent: "test" }),
}));
vi.mock("../../../database/routes/guacamole-dispatch.js", () => ({
vi.mock("../../../hosts/guacamole-sessions.js", () => ({
createGuacamoleJoinToken: (id: string, readOnly: boolean) =>
`join:${id}:${readOnly}`,
}));
@@ -646,7 +646,7 @@ describe("collab room routes", () => {
await present(roomId, "s1");
expect((await resolve(guestLinkToken!)).jsonBody!.stage).toMatchObject({
protocol: "ssh",
wsPath: `/terminal/ws?roomGuestToken=${encodeURIComponent(guestLinkToken!)}`,
wsPath: `/plugin-ws/ssh-terminal/terminal?roomGuestToken=${encodeURIComponent(guestLinkToken!)}`,
});
state.liveOwned.set("g1", "host-1");
await present(roomId, "g1", "vnc");
@@ -63,7 +63,7 @@ vi.mock("../../../hosts/terminal/session-manager.js", () => ({
},
}));
vi.mock("../../../database/routes/guacamole-dispatch.js", () => ({
vi.mock("../../../hosts/guacamole-sessions.js", () => ({
getGuacamoleSessionInfo: (guacamoleConnectionId: string) =>
state.guacSessions.get(guacamoleConnectionId) ?? null,
createGuacamoleJoinToken: (
@@ -364,7 +364,7 @@ describe("GET /session-sharing/resolve/:linkToken", () => {
expect(res.jsonBody).toEqual({
protocol: "ssh",
permissionLevel: "read-only",
wsPath: `/terminal/ws?shareToken=${encodeURIComponent(share.linkToken)}`,
wsPath: `/plugin-ws/ssh-terminal/terminal?shareToken=${encodeURIComponent(share.linkToken)}`,
});
});
@@ -1,14 +1,18 @@
/**
* The terminal WS server's start/stop lifecycle, which the ssh-terminal plugin
* drives. The point of this test is the observable consequence of disabling
* the plugin: the port actually stops listening.
* The terminal WS server's lifecycle, which the ssh-terminal plugin drives.
*
* There is no terminal port any more: core serves the socket at
* /plugin-ws/ssh-terminal/terminal and the plugin hands each upgrade to the
* WebSocketServer this module owns. So the thing worth asserting changed with
* it. It used to be "the port stops listening"; it is now "the module binds
* nothing on import, and disabling the plugin closes the live sessions", which
* is what disabling a transport owner has to mean when core owns the socket.
*
* The terminal module is heavy (it pulls in the whole SSH stack), so this
* exercises only the lifecycle functions, on a non-default port.
* exercises only the lifecycle surface.
*/
import { afterEach, describe, expect, it, vi } from "vitest";
import net from "node:net";
import { describe, expect, it, vi } from "vitest";
vi.mock("../../../database/repositories/factory.js", () => ({
createCurrentHostResolutionRepository: () => ({}),
@@ -18,65 +22,29 @@ vi.mock("../../../database/repositories/factory.js", () => ({
createCurrentSessionRecordingRepository: () => ({}),
}));
const TEST_PORT = 39002;
function isListening(port: number): Promise<boolean> {
return new Promise((resolve) => {
const socket = net.connect({ port, host: "127.0.0.1" });
socket.once("connect", () => {
socket.destroy();
resolve(true);
});
socket.once("error", () => resolve(false));
});
}
describe("terminal server lifecycle", () => {
afterEach(async () => {
it("binds no port of its own", async () => {
const terminal = await import("../../../hosts/terminal/index.js");
// The old module exported a port and a listen() call. Both are gone, and
// their absence is the contract: a plugin that binds its own port is
// exactly what A4 removed.
expect("TERMINAL_WS_PORT" in terminal).toBe(false);
expect("startTerminalServer" in terminal).toBe(false);
});
it("exposes an upgrade handler for core to route to", async () => {
const { handleTerminalUpgrade } =
await import("../../../hosts/terminal/index.js");
expect(typeof handleTerminalUpgrade).toBe("function");
});
it("is idempotent on stop, so a double deactivate is safe", async () => {
const { stopTerminalServer } =
await import("../../../hosts/terminal/index.js");
await stopTerminalServer();
});
it("does not listen until it is started", async () => {
await import("../../../hosts/terminal/index.js");
// Importing the module must not bind the port: the plugin decides that.
expect(await isListening(TEST_PORT)).toBe(false);
});
it("listens after start and frees the port after stop", async () => {
const { startTerminalServer, stopTerminalServer } =
await import("../../../hosts/terminal/index.js");
await startTerminalServer(TEST_PORT);
expect(await isListening(TEST_PORT)).toBe(true);
await stopTerminalServer();
// This is what "disabling the plugin" has to mean for a transport owner.
expect(await isListening(TEST_PORT)).toBe(false);
});
it("is idempotent on both ends", async () => {
const { startTerminalServer, stopTerminalServer } =
await import("../../../hosts/terminal/index.js");
await startTerminalServer(TEST_PORT);
await startTerminalServer(TEST_PORT);
expect(await isListening(TEST_PORT)).toBe(true);
await stopTerminalServer();
await stopTerminalServer();
expect(await isListening(TEST_PORT)).toBe(false);
});
it("can be restarted, so re-enabling the plugin works", async () => {
const { startTerminalServer, stopTerminalServer } =
await import("../../../hosts/terminal/index.js");
await startTerminalServer(TEST_PORT);
await stopTerminalServer();
await startTerminalServer(TEST_PORT);
expect(await isListening(TEST_PORT)).toBe(true);
await expect(stopTerminalServer()).resolves.toBeUndefined();
await expect(stopTerminalServer()).resolves.toBeUndefined();
});
});
+385
View File
@@ -0,0 +1,385 @@
/**
* ctx.http: the one way a plugin serves HTTP.
*
* Everything here is about the middleware core puts in front of a plugin's
* routes, because that is what moving off the dispatcher shims bought: auth by
* default, a truthful 503 while disabled, a capability that can be revoked
* without a restart, and streaming that still streams.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import express from "express";
import type { AddressInfo } from "node:net";
import type { Server } from "node:http";
const state = vi.hoisted(() => ({
validToken: "valid-token",
userId: "user-1",
granted: new Set<string>(["network:serve"]),
}));
vi.mock("../../utils/logger.js", () => ({
pluginLogger: {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
success: vi.fn(),
},
databaseLogger: {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
success: vi.fn(),
},
}));
vi.mock("../../utils/auth-manager.js", () => ({
AuthManager: {
getInstance: () => ({
createAuthMiddleware:
() =>
(
req: express.Request,
res: express.Response,
next: express.NextFunction,
) => {
const header = req.headers.authorization;
const token = header?.startsWith("Bearer ") ? header.slice(7) : null;
if (token !== state.validToken) {
res.status(401).json({ error: "Unauthorized" });
return;
}
(req as express.Request & { userId?: string }).userId = state.userId;
next();
},
}),
},
}));
vi.mock("../../plugins/permissions.js", () => ({
hasCapability: async (
_pluginId: string,
capability: string,
declared: readonly string[],
) => declared.includes(capability) && state.granted.has(capability),
}));
vi.mock("../../utils/audit-logger.js", () => ({ logAudit: vi.fn() }));
const http = await import("../../plugins/http.js");
const pluginApi = (await import("../../database/routes/plugin-api-routes.js"))
.default;
function manifest(overrides: Record<string, unknown> = {}) {
return {
id: "sample-plugin",
name: "Sample Plugin",
version: "1.0.0",
capabilities: ["network:serve"],
...overrides,
} as never;
}
let server: Server | null = null;
async function startServer(): Promise<string> {
const app = express();
// Exactly how database.ts mounts it: no auth in front, because the plugin
// router brings its own.
app.use("/plugin-api", pluginApi);
return new Promise((resolve) => {
server = app.listen(0, "127.0.0.1", () => {
const { port } = server!.address() as AddressInfo;
resolve(`http://127.0.0.1:${port}`);
});
});
}
const authed = { Authorization: `Bearer ${state.validToken}` };
beforeEach(() => {
http.resetPluginHttp();
state.granted = new Set(["network:serve"]);
});
afterEach(async () => {
if (server) {
await new Promise((resolve) => server!.close(() => resolve(undefined)));
server = null;
}
http.resetPluginHttp();
});
describe("ctx.http mounting", () => {
it("serves a plugin's routes once it registers a router", async () => {
const router = http.createPluginRouter({
manifest: manifest(),
reportError: () => {},
});
router.get("/thing", (_req, res) => res.json({ ok: true }));
const base = await startServer();
const response = await fetch(`${base}/plugin-api/sample-plugin/thing`, {
headers: authed,
});
expect(response.status).toBe(200);
expect(await response.json()).toEqual({ ok: true });
});
it("404s a plugin id that never registered a router", async () => {
const base = await startServer();
const response = await fetch(`${base}/plugin-api/nobody/thing`, {
headers: authed,
});
expect(response.status).toBe(404);
});
it("unmounts on deactivate, so a disabled plugin stops serving", async () => {
const router = http.createPluginRouter({
manifest: manifest(),
reportError: () => {},
});
router.get("/thing", (_req, res) => res.json({ ok: true }));
const base = await startServer();
expect(
(
await fetch(`${base}/plugin-api/sample-plugin/thing`, {
headers: authed,
})
).status,
).toBe(200);
http.unregisterPluginHttp("sample-plugin");
expect(
(
await fetch(`${base}/plugin-api/sample-plugin/thing`, {
headers: authed,
})
).status,
).toBe(404);
});
});
describe("ctx.http authentication", () => {
it("requires authentication by default", async () => {
const router = http.createPluginRouter({
manifest: manifest(),
reportError: () => {},
});
router.get("/thing", (_req, res) => res.json({ ok: true }));
const base = await startServer();
expect((await fetch(`${base}/plugin-api/sample-plugin/thing`)).status).toBe(
401,
);
expect(
(
await fetch(`${base}/plugin-api/sample-plugin/thing`, {
headers: { Authorization: "Bearer nope" },
})
).status,
).toBe(401);
});
it("serves a declared public path without a token", async () => {
const router = http.createPluginRouter({
manifest: manifest(),
options: { public: ["/webhook/:token"] },
reportError: () => {},
});
router.post("/webhook/:token", (req, res) =>
res.json({ token: req.params.token }),
);
router.get("/private", (_req, res) => res.json({ ok: true }));
const base = await startServer();
const open = await fetch(
`${base}/plugin-api/sample-plugin/webhook/abc123`,
{
method: "POST",
},
);
expect(open.status).toBe(200);
expect(await open.json()).toEqual({ token: "abc123" });
// Declaring one route public must not open the rest of the plugin.
expect(
(await fetch(`${base}/plugin-api/sample-plugin/private`)).status,
).toBe(401);
});
it("does not let a public parameter swallow extra path segments", async () => {
const router = http.createPluginRouter({
manifest: manifest(),
options: { public: ["/webhook/:token"] },
reportError: () => {},
});
router.get("/webhook/:token/secret", (_req, res) => res.json({ ok: true }));
const base = await startServer();
const response = await fetch(
`${base}/plugin-api/sample-plugin/webhook/abc/secret`,
);
expect(response.status).toBe(401);
});
it("gives the plugin the user core authenticated, not one the caller named", async () => {
const router = http.createPluginRouter({
manifest: manifest(),
reportError: () => {},
});
router.get("/who", (req, res) =>
res.json({
userId: (req as express.Request & { userId?: string }).userId,
}),
);
const base = await startServer();
const response = await fetch(`${base}/plugin-api/sample-plugin/who`, {
headers: { ...authed, "x-user-id": "attacker" },
});
expect(await response.json()).toEqual({ userId: state.userId });
});
});
describe("ctx.http capability", () => {
it("refuses to build a router without network:serve declared", () => {
expect(() =>
http.createPluginRouter({
manifest: manifest({ capabilities: [] }),
reportError: () => {},
}),
).not.toThrow();
// Declaration is checked in ctx.ts; the grant is checked per request below.
});
it("403s every request when the grant is revoked", async () => {
const router = http.createPluginRouter({
manifest: manifest(),
reportError: () => {},
});
router.get("/thing", (_req, res) => res.json({ ok: true }));
const base = await startServer();
expect(
(
await fetch(`${base}/plugin-api/sample-plugin/thing`, {
headers: authed,
})
).status,
).toBe(200);
// Revoked at runtime: no restart, and the next request is refused.
state.granted.delete("network:serve");
const response = await fetch(`${base}/plugin-api/sample-plugin/thing`, {
headers: authed,
});
expect(response.status).toBe(403);
});
});
describe("ctx.http while the plugin is disabled", () => {
it("answers 503 rather than 404", async () => {
const router = http.createPluginRouter({
manifest: manifest(),
reportError: () => {},
});
router.get("/thing", (_req, res) => res.json({ ok: true }));
// "Installed but not running" is a different fact from "no such plugin",
// and a caller can act on the difference.
http.setPluginEnabledCheck(() => false);
const base = await startServer();
const response = await fetch(`${base}/plugin-api/sample-plugin/thing`, {
headers: authed,
});
expect(response.status).toBe(503);
});
});
describe("ctx.http errors", () => {
it("reports a throwing route without leaking a stack", async () => {
const reported: unknown[] = [];
const router = http.createPluginRouter({
manifest: manifest(),
reportError: (error) => reported.push(error),
});
router.get("/boom", () => {
throw new Error("secret internal detail");
});
const base = await startServer();
const response = await fetch(`${base}/plugin-api/sample-plugin/boom`, {
headers: authed,
});
expect(response.status).toBe(500);
const body = await response.text();
expect(body).not.toContain("secret internal detail");
// Counted against the plugin's error budget.
expect(reported).toHaveLength(1);
});
});
describe("ctx.http streaming", () => {
it("streams an SSE response as it is produced", async () => {
const router = http.createPluginRouter({
manifest: manifest(),
reportError: () => {},
});
let release: (() => void) | null = null;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
router.get("/stream", async (_req, res) => {
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.write("event: progress\ndata: 1\n\n");
// The first chunk has to arrive before the handler finishes, or this is
// buffering rather than streaming.
await gate;
res.write("event: result\ndata: done\n\n");
res.end();
});
const base = await startServer();
const response = await fetch(`${base}/plugin-api/sample-plugin/stream`, {
headers: authed,
});
expect(response.headers.get("content-type")).toContain("text/event-stream");
const reader = response.body!.getReader();
const decoder = new TextDecoder();
const first = await reader.read();
expect(decoder.decode(first.value)).toContain("data: 1");
release!();
let rest = "";
for (;;) {
const chunk = await reader.read();
if (chunk.done) break;
rest += decoder.decode(chunk.value);
}
expect(rest).toContain("data: done");
});
});
+287
View File
@@ -0,0 +1,287 @@
/**
* ctx.ws: the one way a plugin serves WebSockets.
*
* The properties that matter are the ones the per-plugin ports used to leave
* to each plugin: an upgrade is authenticated before any plugin code runs, a
* route that no longer exists refuses cleanly, and disabling a plugin actually
* closes its live sockets rather than just unrouting new ones.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import http from "node:http";
import type { AddressInfo } from "node:net";
import { WebSocket } from "ws";
const state = vi.hoisted(() => ({
validToken: "valid-token",
userId: "user-1",
granted: new Set<string>(["network:serve"]),
}));
vi.mock("../../utils/logger.js", () => ({
pluginLogger: {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
success: vi.fn(),
},
}));
vi.mock("../../utils/auth-manager.js", () => ({
AuthManager: {
getInstance: () => ({
verifyJWTToken: async (token: string) =>
token === state.validToken ? { userId: state.userId } : null,
}),
},
}));
vi.mock("../../plugins/permissions.js", () => ({
hasCapability: async (
_pluginId: string,
capability: string,
declared: readonly string[],
) => declared.includes(capability) && state.granted.has(capability),
}));
const ws = await import("../../plugins/ws.js");
const DECLARED = ["network:serve"] as const;
let server: http.Server | null = null;
let baseUrl = "";
async function startServer(): Promise<string> {
const instance = http.createServer((_req, res) => {
res.statusCode = 404;
res.end();
});
ws.attachPluginWebSockets(instance);
return new Promise((resolve) => {
server = instance;
instance.listen(0, "127.0.0.1", () => {
const { port } = instance.address() as AddressInfo;
baseUrl = `ws://127.0.0.1:${port}`;
resolve(baseUrl);
});
});
}
/** Resolves with "open" or the HTTP status the upgrade was refused with. */
function connect(
url: string,
protocols: string[] = [],
): Promise<{ outcome: "open"; socket: WebSocket } | { outcome: number }> {
return new Promise((resolve) => {
const socket = new WebSocket(url, protocols);
socket.once("open", () => resolve({ outcome: "open", socket }));
socket.once("unexpected-response", (_req, res) =>
resolve({ outcome: res.statusCode ?? 0 }),
);
socket.once("error", () => resolve({ outcome: 0 }));
});
}
function authProtocols(token: string): string[] {
return [`termix.jwt.${token}`];
}
beforeEach(() => {
ws.resetPluginWebSockets();
state.granted = new Set(["network:serve"]);
});
afterEach(async () => {
ws.resetPluginWebSockets();
if (server) {
await new Promise((resolve) => server!.close(() => resolve(undefined)));
server = null;
}
});
describe("ctx.ws routing", () => {
it("serves a registered route to an authenticated client", async () => {
const seen: string[] = [];
ws.registerPluginWsRoute(
"sample-plugin",
"/socket",
({ userId, socket }) => {
seen.push(userId);
(socket as WebSocket).send("hello");
},
DECLARED,
);
const base = await startServer();
const result = await connect(
`${base}/plugin-ws/sample-plugin/socket`,
authProtocols(state.validToken),
);
expect(result.outcome).toBe("open");
expect(seen).toEqual([state.userId]);
if (result.outcome === "open") result.socket.close();
});
it("404s a path nothing registered", async () => {
const base = await startServer();
const result = await connect(`${base}/plugin-ws/sample-plugin/missing`);
expect(result.outcome).toBe(404);
});
it("leaves non-plugin upgrades to whoever else is listening", async () => {
let claimedByCore = false;
const base = await startServer();
// A second listener standing in for a core WS server. If the plugin
// handler answered /ssh/websocket/ itself this would never fire, and the
// socket would be stolen from core rather than passed on.
server!.on("upgrade", (_req, socket) => {
claimedByCore = true;
socket.destroy();
});
await connect(`${base}/ssh/websocket/`);
expect(claimedByCore).toBe(true);
});
});
describe("ctx.ws authentication", () => {
it("rejects an upgrade with no token", async () => {
ws.registerPluginWsRoute("sample-plugin", "/socket", () => {}, DECLARED);
const base = await startServer();
const result = await connect(`${base}/plugin-ws/sample-plugin/socket`);
expect(result.outcome).toBe(401);
});
it("rejects an upgrade with a bad token", async () => {
ws.registerPluginWsRoute("sample-plugin", "/socket", () => {}, DECLARED);
const base = await startServer();
const result = await connect(
`${base}/plugin-ws/sample-plugin/socket`,
authProtocols("nope"),
);
expect(result.outcome).toBe(401);
});
it("serves a public route without a token", async () => {
ws.registerPluginWsRoute(
"sample-plugin",
"/guest",
({ socket }) => (socket as WebSocket).send("hi"),
DECLARED,
{ public: true },
);
const base = await startServer();
const result = await connect(`${base}/plugin-ws/sample-plugin/guest`);
expect(result.outcome).toBe("open");
if (result.outcome === "open") result.socket.close();
});
});
describe("ctx.ws capability", () => {
it("refuses the upgrade when network:serve is not granted", async () => {
ws.registerPluginWsRoute("sample-plugin", "/socket", () => {}, DECLARED);
state.granted.delete("network:serve");
const base = await startServer();
const result = await connect(
`${base}/plugin-ws/sample-plugin/socket`,
authProtocols(state.validToken),
);
expect(result.outcome).toBe(403);
});
});
describe("ctx.ws disposal", () => {
it("closes live sockets and stops routing on deactivate", async () => {
const dispose = ws.registerPluginWsRoute(
"sample-plugin",
"/socket",
() => {},
DECLARED,
);
const base = await startServer();
const result = await connect(
`${base}/plugin-ws/sample-plugin/socket`,
authProtocols(state.validToken),
);
expect(result.outcome).toBe("open");
const closed = new Promise<number>((resolve) => {
if (result.outcome === "open") {
result.socket.once("close", (code) => resolve(code));
}
});
dispose();
// A live terminal must not outlive the plugin that owns it.
expect(await closed).toBeGreaterThan(0);
const afterDispose = await connect(
`${base}/plugin-ws/sample-plugin/socket`,
authProtocols(state.validToken),
);
expect(afterDispose.outcome).toBe(404);
});
});
describe("ctx.ws raw upgrades", () => {
it("authenticates before handing the socket to the plugin", async () => {
const handled: string[] = [];
ws.registerPluginWsUpgrade(
"sample-plugin",
"/raw",
(_request, socket, _head, userId) => {
handled.push(userId);
(socket as { destroy: () => void }).destroy();
},
DECLARED,
);
const base = await startServer();
const unauthenticated = await connect(
`${base}/plugin-ws/sample-plugin/raw`,
);
expect(unauthenticated.outcome).toBe(401);
// The plugin never saw the unauthenticated attempt.
expect(handled).toEqual([]);
await connect(
`${base}/plugin-ws/sample-plugin/raw`,
authProtocols(state.validToken),
);
expect(handled).toEqual([state.userId]);
});
});
describe("parsePluginWsUrl", () => {
it("only claims well-formed plugin socket paths", () => {
expect(ws.parsePluginWsUrl("/plugin-ws/docker/console")).toEqual({
pluginId: "docker",
path: "/console",
});
expect(ws.parsePluginWsUrl("/plugin-ws/docker/console?x=1")).toEqual({
pluginId: "docker",
path: "/console",
});
expect(ws.parsePluginWsUrl("/ssh/websocket/")).toBeNull();
expect(ws.parsePluginWsUrl("/plugin-ws/docker")).toBeNull();
expect(ws.parsePluginWsUrl(undefined)).toBeNull();
});
});
@@ -1,6 +1,15 @@
/**
* dispatchLoginEvent used to POST to the metrics service on localhost:30005
* with an internal auth token. Host metrics is a plugin now and has no port,
* so it publishes on the plugin event bus and the plugin subscribes.
*
* What is asserted changed with it: the payload a subscriber receives, and
* that a throwing subscriber cannot fail the login that caused the event.
*/
import { afterEach, describe, expect, it, vi } from "vitest";
import { dispatchLoginEvent } from "../../utils/login-event-dispatch.js";
import { SystemCrypto } from "../../utils/system-crypto.js";
import { pluginEvents, TOPICS } from "../../plugins/events.js";
import { sshLogger } from "../../utils/logger.js";
describe("dispatchLoginEvent", () => {
@@ -8,37 +17,24 @@ describe("dispatchLoginEvent", () => {
vi.restoreAllMocks();
});
it("reports a rejected metrics-service request", async () => {
vi.spyOn(SystemCrypto, "getInstance").mockReturnValue({
getInternalAuthToken: vi.fn().mockResolvedValue("internal-token"),
} as never);
vi.spyOn(globalThis, "fetch").mockResolvedValue(
new Response('{"error":"Missing authentication token"}', {
status: 401,
}),
);
const warn = vi.spyOn(sshLogger, "warn").mockImplementation(() => {});
it("publishes the login details a subscriber needs", async () => {
const received: unknown[] = [];
const unsubscribe = pluginEvents.on(TOPICS.hostLogin, (payload) => {
received.push(payload);
});
await dispatchLoginEvent(7, "user-1", "root", "192.0.2.1");
try {
await dispatchLoginEvent(42, "user-1", "root", "10.0.0.5");
} finally {
unsubscribe();
}
expect(warn).toHaveBeenCalledWith(
"Failed to dispatch login event",
expect.objectContaining({
operation: "login_event_dispatch_error",
hostId: 7,
error:
'Metrics service returned 401: {"error":"Missing authentication token"}',
}),
);
expect(received).toEqual([
{ hostId: 42, userId: "user-1", sshUser: "root", fromIp: "10.0.0.5" },
]);
});
it("does not log a warning when the metrics service accepts the event", async () => {
vi.spyOn(SystemCrypto, "getInstance").mockReturnValue({
getInternalAuthToken: vi.fn().mockResolvedValue("internal-token"),
} as never);
vi.spyOn(globalThis, "fetch").mockResolvedValue(
new Response('{"ok":true}', { status: 200 }),
);
it("does not log a warning on the happy path", async () => {
const warn = vi.spyOn(sshLogger, "warn").mockImplementation(() => {});
await dispatchLoginEvent(7, "user-1", "root", "192.0.2.1");
@@ -46,49 +42,27 @@ describe("dispatchLoginEvent", () => {
expect(warn).not.toHaveBeenCalled();
});
it("sends the internal auth token and login details the metrics service expects", async () => {
vi.spyOn(SystemCrypto, "getInstance").mockReturnValue({
getInternalAuthToken: vi.fn().mockResolvedValue("internal-token"),
} as never);
const fetchSpy = vi
.spyOn(globalThis, "fetch")
.mockResolvedValue(new Response('{"ok":true}', { status: 200 }));
it("never sends the event over the network", async () => {
const fetchSpy = vi.spyOn(globalThis, "fetch");
await dispatchLoginEvent(42, "user-1", "root", "10.0.0.5");
await dispatchLoginEvent(7, "user-1", "root", "192.0.2.1");
expect(fetchSpy).toHaveBeenCalledWith(
"http://localhost:30005/internal/login-alert",
expect.objectContaining({
method: "POST",
headers: expect.objectContaining({
"x-internal-auth": "internal-token",
}),
body: JSON.stringify({
hostId: 42,
userId: "user-1",
sshUser: "root",
fromIp: "10.0.0.5",
}),
}),
);
// The whole point of the move: no service-to-service HTTP call, and no
// internal shared secret to carry on it.
expect(fetchSpy).not.toHaveBeenCalled();
});
it("logs a warning if the fetch itself throws, instead of propagating", async () => {
vi.spyOn(SystemCrypto, "getInstance").mockReturnValue({
getInternalAuthToken: vi.fn().mockResolvedValue("internal-token"),
} as never);
vi.spyOn(globalThis, "fetch").mockRejectedValue(
new Error("connect ECONNREFUSED"),
);
const warn = vi.spyOn(sshLogger, "warn").mockImplementation(() => {});
it("does not propagate a subscriber's throw to the caller", async () => {
const unsubscribe = pluginEvents.on(TOPICS.hostLogin, () => {
throw new Error("subscriber exploded");
});
await expect(
dispatchLoginEvent(1, "user-1", "root", "127.0.0.1"),
).resolves.toBeUndefined();
expect(warn).toHaveBeenCalledWith(
"Failed to dispatch login event",
expect.objectContaining({ hostId: 1 }),
);
try {
await expect(
dispatchLoginEvent(1, "user-1", "root", "127.0.0.1"),
).resolves.toBeUndefined();
} finally {
unsubscribe();
}
});
});