mirror of
https://github.com/Termix-SSH/Termix.git
synced 2026-10-30 15:15:24 +00:00
feat: move opkssh and warpgate into plugins (C3)
This commit is contained in:
1 parent
925da4a661
commit
98d367d7e2
336 files changed
+22380
-4746
No files matched your search
@@ -0,0 +1,110 @@
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
binaryName,
|
||||
binarySpec,
|
||||
DEFAULT_VERSION,
|
||||
} from "../../src/backend/binary.js";
|
||||
import {
|
||||
parseProviders,
|
||||
validateRedirectUris,
|
||||
} from "../../src/backend/config.js";
|
||||
import {
|
||||
normalizeSelectOpParam,
|
||||
rewriteOpksshHtml,
|
||||
} from "../../src/backend/html.js";
|
||||
|
||||
describe("config", () => {
|
||||
it("reads providers and strips the issuer scheme", () => {
|
||||
expect(
|
||||
parseProviders(`providers:
|
||||
- alias: google
|
||||
issuer: https://accounts.google.com
|
||||
redirect_uris:
|
||||
- http://localhost:3000/login-callback
|
||||
- alias: broken
|
||||
`),
|
||||
).toEqual([
|
||||
{
|
||||
alias: "google",
|
||||
issuer: "accounts.google.com",
|
||||
redirectUris: ["http://localhost:3000/login-callback"],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("accepts localhost redirect_uris only, naming the public callback", () => {
|
||||
const callback = "https://termix.test/plugin-api/opkssh/callback";
|
||||
expect(
|
||||
validateRedirectUris(
|
||||
[
|
||||
{
|
||||
alias: "a",
|
||||
issuer: "x",
|
||||
redirectUris: ["http://127.0.0.1:10001/login-callback"],
|
||||
},
|
||||
],
|
||||
callback,
|
||||
),
|
||||
).toEqual({ ok: true });
|
||||
const refused = validateRedirectUris(
|
||||
[{ alias: "a", issuer: "x", redirectUris: [callback] }],
|
||||
callback,
|
||||
);
|
||||
expect(refused.ok).toBe(false);
|
||||
expect(refused.ok === false && refused.message).toContain(callback);
|
||||
});
|
||||
});
|
||||
|
||||
describe("html", () => {
|
||||
it("sends the page's links through the proxied path", () => {
|
||||
const html = rewriteOpksshHtml(
|
||||
'<html><head></head><body><a href="/select?op=google">g</a><form action="http://localhost:4567/login"></form></body></html>',
|
||||
"/plugin-api/opkssh/chooser/req-1",
|
||||
);
|
||||
expect(html).toContain(
|
||||
'href="/plugin-api/opkssh/chooser/req-1/select?op=google"',
|
||||
);
|
||||
expect(html).toContain('action="/plugin-api/opkssh/chooser/req-1/login"');
|
||||
expect(html).toContain('<base href="/plugin-api/opkssh/chooser/req-1/">');
|
||||
});
|
||||
|
||||
it("maps a provider alias to the name OPKSSH's chooser uses", () => {
|
||||
const providers = [{ alias: "work", issuer: "accounts.google.com" }];
|
||||
expect(normalizeSelectOpParam("work", providers)).toBe("google");
|
||||
expect(normalizeSelectOpParam("google", providers)).toBe("google");
|
||||
expect(normalizeSelectOpParam("other", providers)).toBe("other");
|
||||
});
|
||||
});
|
||||
|
||||
describe("binary", () => {
|
||||
it("names the release asset per platform", () => {
|
||||
expect(binaryName("linux", "x64")).toBe("opkssh-linux-amd64");
|
||||
expect(binaryName("darwin", "arm64")).toBe("opkssh-osx-arm64");
|
||||
expect(binaryName("win32", "x64")).toBe("opkssh-windows-amd64.exe");
|
||||
});
|
||||
|
||||
it("pins the default release and checks the Docker copy first", () => {
|
||||
const spec = binarySpec({}, "linux", "x64", "/app");
|
||||
expect(spec).toMatchObject({
|
||||
name: "opkssh-linux-amd64",
|
||||
version: DEFAULT_VERSION,
|
||||
url: `https://github.com/openpubkey/opkssh/releases/download/${DEFAULT_VERSION}/opkssh-linux-amd64`,
|
||||
prebuilt: [path.join("/app", "opkssh-bundled", "opkssh-linux-amd64")],
|
||||
});
|
||||
expect(spec.sha256).toMatch(/^[0-9a-f]{64}$/);
|
||||
expect(
|
||||
binarySpec({ OPKSSH_BUNDLED_DIR: "/srv/opk" }, "linux", "x64").prebuilt,
|
||||
).toEqual([path.join("/srv/opk", "opkssh-linux-amd64")]);
|
||||
});
|
||||
|
||||
it("needs a checksum for any other release", () => {
|
||||
expect(() => binarySpec({ OPKSSH_VERSION: "v9" }, "linux", "x64")).toThrow(
|
||||
/no trusted SHA-256/,
|
||||
);
|
||||
const sha = "a".repeat(64);
|
||||
expect(
|
||||
binarySpec({ OPKSSH_VERSION: "v9", OPKSSH_SHA256: sha }, "linux", "x64"),
|
||||
).toMatchObject({ version: "v9", sha256: sha });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,193 @@
|
||||
import http from "node:http";
|
||||
import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import express, { type Router } from "express";
|
||||
import {
|
||||
createFakeProcess,
|
||||
createMockCtx,
|
||||
createTestDb,
|
||||
type FakeProcess,
|
||||
type MockPluginContext,
|
||||
type TestDb,
|
||||
} from "@termix/plugin-sdk/testing";
|
||||
import type {
|
||||
PluginHostSummary,
|
||||
PluginSshAuthProvider,
|
||||
} from "@termix/plugin-sdk/backend";
|
||||
import type { PluginManifest } from "@termix/plugin-sdk/manifest";
|
||||
import manifestJson from "../../manifest.json";
|
||||
|
||||
export const pluginDir = fileURLToPath(new URL("../..", import.meta.url));
|
||||
export const manifest = manifestJson as unknown as PluginManifest;
|
||||
|
||||
/** Core's 2.8 opkssh_tokens, as db/index.ts created it. */
|
||||
export const LEGACY_DDL = `
|
||||
CREATE TABLE IF NOT EXISTS opkssh_tokens (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
host_id INTEGER NOT NULL,
|
||||
ssh_cert TEXT NOT NULL,
|
||||
private_key TEXT NOT NULL,
|
||||
email TEXT,
|
||||
sub TEXT,
|
||||
issuer TEXT,
|
||||
audience TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
expires_at TEXT NOT NULL,
|
||||
last_used TEXT,
|
||||
UNIQUE(user_id, host_id),
|
||||
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (host_id) REFERENCES ssh_data (id) ON DELETE CASCADE
|
||||
);
|
||||
`;
|
||||
|
||||
export const PROVIDERS_CONFIG = `providers:
|
||||
- alias: google
|
||||
issuer: https://accounts.google.com
|
||||
client_id: abc
|
||||
scopes: openid email
|
||||
`;
|
||||
|
||||
/** A fake terminal socket that records what it was sent. */
|
||||
export function fakeSocket() {
|
||||
const sent: Array<Record<string, unknown>> = [];
|
||||
const closers: Array<() => void> = [];
|
||||
return {
|
||||
sent,
|
||||
socket: {
|
||||
send: (data: string) => sent.push(JSON.parse(data)),
|
||||
on: (_event: "close", listener: () => void) => closers.push(listener),
|
||||
},
|
||||
close: () => closers.forEach((listener) => listener()),
|
||||
};
|
||||
}
|
||||
|
||||
export interface TestServer {
|
||||
db: TestDb;
|
||||
mock: MockPluginContext;
|
||||
dataDir: string;
|
||||
processes: FakeProcess[];
|
||||
provider: () => PluginSshAuthProvider;
|
||||
request: (
|
||||
method: string,
|
||||
path: string,
|
||||
options?: { user?: string; headers?: Record<string, string> },
|
||||
// Route bodies vary per test; asserting on them is the point.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
) => Promise<{ status: number; body: any; location: string | null }>;
|
||||
close: () => Promise<void>;
|
||||
}
|
||||
|
||||
export async function startServer(
|
||||
options: {
|
||||
capabilities?: string[];
|
||||
hosts?: PluginHostSummary[];
|
||||
settings?: Record<string, unknown>;
|
||||
before?: (sqlite: TestDb["sqlite"]) => void;
|
||||
} = {},
|
||||
): Promise<TestServer> {
|
||||
const db = await createTestDb(pluginDir, { before: options.before });
|
||||
db.sqlite
|
||||
.prepare("INSERT OR IGNORE INTO users (id) VALUES (?)")
|
||||
.run("user-1");
|
||||
db.sqlite.prepare("INSERT OR IGNORE INTO ssh_data (id) VALUES (?)").run(7);
|
||||
const dataDir = await fs.mkdtemp(path.join(os.tmpdir(), "opkssh-"));
|
||||
const processes: FakeProcess[] = [];
|
||||
|
||||
let router: Router | null = null;
|
||||
const mock = createMockCtx({
|
||||
pluginId: manifest.id,
|
||||
manifest,
|
||||
capabilities: options.capabilities ?? manifest.capabilities,
|
||||
db: db.database,
|
||||
router: () => (router = express.Router()),
|
||||
hosts: options.hosts ?? [
|
||||
{
|
||||
id: 7,
|
||||
userId: "user-1",
|
||||
name: "box",
|
||||
ip: "10.0.0.7",
|
||||
port: 22,
|
||||
username: "root",
|
||||
} as PluginHostSummary,
|
||||
],
|
||||
settings: options.settings,
|
||||
baseUrl: "https://termix.test",
|
||||
process: {
|
||||
run: () => {
|
||||
const child = createFakeProcess();
|
||||
processes.push(child);
|
||||
return child;
|
||||
},
|
||||
ensureBinary: async (spec) => `/opt/${spec.name}`,
|
||||
},
|
||||
});
|
||||
// The plugin's data folder, somewhere the test can write.
|
||||
(mock.ctx as unknown as { files: unknown }).files = {
|
||||
dataDir: async () => dataDir,
|
||||
};
|
||||
|
||||
const { activate } = await import("../../src/backend/index.js");
|
||||
await activate(mock.ctx);
|
||||
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => {
|
||||
mock.setActor(req.header("x-test-user") || undefined);
|
||||
next();
|
||||
});
|
||||
app.use((req, res, next) => router!(req, res, next));
|
||||
|
||||
const server = http.createServer(app);
|
||||
await new Promise<void>((resolve) => server.listen(0, resolve));
|
||||
const { port } = server.address() as AddressInfo;
|
||||
|
||||
return {
|
||||
db,
|
||||
mock,
|
||||
dataDir,
|
||||
processes,
|
||||
provider: () =>
|
||||
mock.auth.sshAuthProviders.find(
|
||||
(provider) => provider.type === "opkssh",
|
||||
)!,
|
||||
async request(method, requestPath, { user = "user-1", headers = {} } = {}) {
|
||||
const response = await fetch(`http://127.0.0.1:${port}${requestPath}`, {
|
||||
method,
|
||||
redirect: "manual",
|
||||
headers: { ...(user ? { "x-test-user": user } : {}), ...headers },
|
||||
});
|
||||
const text = await response.text();
|
||||
let parsed: unknown = null;
|
||||
try {
|
||||
parsed = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
parsed = text;
|
||||
}
|
||||
return {
|
||||
status: response.status,
|
||||
body: parsed,
|
||||
location: response.headers.get("location"),
|
||||
};
|
||||
},
|
||||
async close() {
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
db.close();
|
||||
await fs.rm(dataDir, { recursive: true, force: true });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export const env = (hostId = 7) => ({
|
||||
client: {},
|
||||
userId: "user-1",
|
||||
hostId,
|
||||
purpose: "terminal",
|
||||
interactive: true,
|
||||
log: () => {},
|
||||
});
|
||||
|
||||
export const HOST = { id: 7, ip: "10.0.0.7", port: 22, username: "root" };
|
||||
@@ -0,0 +1,341 @@
|
||||
import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { PluginCapabilityError } from "@termix/plugin-sdk/backend";
|
||||
import { createMockCtx, createTestDb } from "@termix/plugin-sdk/testing";
|
||||
import {
|
||||
HOST,
|
||||
LEGACY_DDL,
|
||||
PROVIDERS_CONFIG,
|
||||
env,
|
||||
fakeSocket,
|
||||
manifest,
|
||||
pluginDir,
|
||||
startServer,
|
||||
type TestServer,
|
||||
} from "./helpers.js";
|
||||
|
||||
const certs = vi.hoisted(() => ({ applyCertificateAuth: vi.fn() }));
|
||||
vi.mock("@termix/plugin-sdk/ssh-certs", () => certs);
|
||||
|
||||
const KEY = `-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
b3BlbnNzaC1rZXktdjEAAAAA
|
||||
-----END OPENSSH PRIVATE KEY-----`;
|
||||
const CERT = "ssh-ed25519-cert-v01@openssh.com AAAAC3NzaC1lZDI1NTE5";
|
||||
|
||||
let server: TestServer | null = null;
|
||||
|
||||
beforeEach(() => {
|
||||
certs.applyCertificateAuth.mockReset();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await server?.close();
|
||||
server = null;
|
||||
});
|
||||
|
||||
async function writeConfig(content = PROVIDERS_CONFIG) {
|
||||
await fs.writeFile(path.join(server!.dataDir, "config.yml"), content);
|
||||
}
|
||||
|
||||
/** Starts a sign-in and returns its request id and what the socket saw. */
|
||||
async function startSignIn(origin = "https://termix.test") {
|
||||
const socket = fakeSocket();
|
||||
await server!.provider().startInteraction!({
|
||||
userId: "user-1",
|
||||
hostId: 7,
|
||||
host: { name: "box", ip: "10.0.0.7", username: "root" },
|
||||
socket: socket.socket,
|
||||
requestOrigin: origin,
|
||||
payload: {},
|
||||
});
|
||||
return socket;
|
||||
}
|
||||
|
||||
describe("adopting opkssh_tokens", () => {
|
||||
it("keeps the 2.8 rows and the unique index", async () => {
|
||||
const db = await createTestDb(pluginDir, {
|
||||
before: (sqlite) => {
|
||||
sqlite.exec("INSERT INTO users (id) VALUES ('user-1')");
|
||||
sqlite.exec("INSERT INTO ssh_data (id) VALUES (7)");
|
||||
sqlite.exec(LEGACY_DDL);
|
||||
sqlite
|
||||
.prepare(
|
||||
"INSERT INTO opkssh_tokens (user_id, host_id, ssh_cert, private_key, expires_at) VALUES (?, ?, ?, ?, ?)",
|
||||
)
|
||||
.run("user-1", 7, "cert", "key", "2099-01-01T00:00:00.000Z");
|
||||
},
|
||||
});
|
||||
const rows = db.sqlite.prepare("SELECT * FROM p_opkssh_tokens").all();
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(() =>
|
||||
db.sqlite
|
||||
.prepare(
|
||||
"INSERT INTO p_opkssh_tokens (user_id, host_id, ssh_cert, private_key, expires_at) VALUES (?, ?, ?, ?, ?)",
|
||||
)
|
||||
.run("user-1", 7, "c", "k", "2099-01-01T00:00:00.000Z"),
|
||||
).toThrow(/UNIQUE/);
|
||||
expect(
|
||||
db.sqlite
|
||||
.prepare("SELECT name FROM sqlite_master WHERE name = 'opkssh_tokens'")
|
||||
.get(),
|
||||
).toBeUndefined();
|
||||
db.close();
|
||||
});
|
||||
|
||||
it("creates the table on a fresh install", async () => {
|
||||
const db = await createTestDb(pluginDir);
|
||||
expect(
|
||||
db.sqlite
|
||||
.prepare(
|
||||
"SELECT name FROM sqlite_master WHERE name = 'p_opkssh_tokens'",
|
||||
)
|
||||
.get(),
|
||||
).toBeTruthy();
|
||||
db.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe("activate", () => {
|
||||
it("registers the opkssh auth type and its routes", async () => {
|
||||
server = await startServer();
|
||||
expect(server.provider()).toMatchObject({
|
||||
type: "opkssh",
|
||||
interaction: "opkssh",
|
||||
supportsBackground: false,
|
||||
});
|
||||
expect(server.mock.httpRouters).toHaveLength(1);
|
||||
expect(server.mock.binaries[0]?.name).toMatch(/^opkssh-/);
|
||||
});
|
||||
|
||||
it.each(["db:own", "auth:provide", "network:serve"])(
|
||||
"fails closed without %s",
|
||||
async (capability) => {
|
||||
const mock = createMockCtx({
|
||||
pluginId: manifest.id,
|
||||
manifest,
|
||||
capabilities: manifest.capabilities.filter((c) => c !== capability),
|
||||
db: (await createTestDb(pluginDir)).database,
|
||||
});
|
||||
const { activate } = await import("../../src/backend/index.js");
|
||||
await expect(activate(mock.ctx)).rejects.toThrow(PluginCapabilityError);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("the opkssh provider", () => {
|
||||
it("asks for a sign-in without a cached certificate", async () => {
|
||||
server = await startServer();
|
||||
const outcome = await server.provider().prepare({}, HOST, env());
|
||||
expect(outcome).toMatchObject({
|
||||
status: "interaction-required",
|
||||
interaction: "opkssh",
|
||||
flag: "requiresOPKSSHAuth",
|
||||
});
|
||||
});
|
||||
|
||||
it("connects with the certificate a sign-in stored", async () => {
|
||||
server = await startServer();
|
||||
await writeConfig();
|
||||
await startSignIn();
|
||||
server.processes[0].emitStdout(`${KEY}\n${CERT}\n`);
|
||||
await vi.waitFor(() =>
|
||||
expect(
|
||||
server!.db.sqlite.prepare("SELECT * FROM p_opkssh_tokens").all(),
|
||||
).toHaveLength(1),
|
||||
);
|
||||
|
||||
const config: Record<string, unknown> = {};
|
||||
const outcome = await server.provider().prepare(config, HOST, env());
|
||||
expect(outcome).toEqual({ status: "ready" });
|
||||
expect(certs.applyCertificateAuth).toHaveBeenCalledWith(
|
||||
config,
|
||||
{},
|
||||
{ privateKey: KEY, certificate: CERT },
|
||||
"root",
|
||||
);
|
||||
const row = server.db.sqlite
|
||||
.prepare("SELECT ssh_cert FROM p_opkssh_tokens")
|
||||
.get() as { ssh_cert: string };
|
||||
expect(row.ssh_cert).not.toContain("cert-v01");
|
||||
});
|
||||
|
||||
it("treats a 2.8 row it cannot unseal as expired", async () => {
|
||||
server = await startServer({
|
||||
before: (sqlite) => {
|
||||
sqlite.exec("INSERT INTO users (id) VALUES ('user-1')");
|
||||
sqlite.exec("INSERT INTO ssh_data (id) VALUES (7)");
|
||||
sqlite.exec(LEGACY_DDL);
|
||||
sqlite
|
||||
.prepare(
|
||||
"INSERT INTO opkssh_tokens (user_id, host_id, ssh_cert, private_key, expires_at) VALUES (?, ?, ?, ?, ?)",
|
||||
)
|
||||
.run("user-1", 7, "v2:old", "v2:old", "2099-01-01T00:00:00.000Z");
|
||||
},
|
||||
});
|
||||
const outcome = await server.provider().prepare({}, HOST, env());
|
||||
expect(outcome.status).toBe("interaction-required");
|
||||
expect(
|
||||
server.db.sqlite.prepare("SELECT * FROM p_opkssh_tokens").all(),
|
||||
).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("forgets the certificate when the server refuses it", async () => {
|
||||
server = await startServer();
|
||||
await writeConfig();
|
||||
await startSignIn();
|
||||
server.processes[0].emitStdout(`${KEY}\n${CERT}\n`);
|
||||
await vi.waitFor(() =>
|
||||
expect(
|
||||
server!.db.sqlite.prepare("SELECT * FROM p_opkssh_tokens").all(),
|
||||
).toHaveLength(1),
|
||||
);
|
||||
const followUp = server.provider().onAuthFailed!(HOST, env(), {
|
||||
error: new Error("All configured authentication methods failed"),
|
||||
retries: 0,
|
||||
canRetry: true,
|
||||
methodNotAvailable: false,
|
||||
});
|
||||
expect(followUp).toMatchObject({ status: "interaction-required" });
|
||||
await vi.waitFor(() =>
|
||||
expect(
|
||||
server!.db.sqlite.prepare("SELECT * FROM p_opkssh_tokens").all(),
|
||||
).toHaveLength(0),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the browser sign-in", () => {
|
||||
it("runs opkssh with the plugin's config and the public callback", async () => {
|
||||
server = await startServer();
|
||||
await writeConfig();
|
||||
const socket = await startSignIn();
|
||||
const run = server.mock.processRuns[0];
|
||||
expect(run.file).toMatch(/opkssh-/);
|
||||
expect(run.args).toContain(
|
||||
`--config-path=${path.join(server.dataDir, "config.yml")}`,
|
||||
);
|
||||
expect(run.args).toContain(
|
||||
"--remote-redirect-uri=https://termix.test/plugin-api/opkssh/callback",
|
||||
);
|
||||
|
||||
server.processes[0].emitStderr(
|
||||
"Opening browser to http://localhost:4567/chooser\n",
|
||||
);
|
||||
const status = socket.sent.find((m) => m.type === "opkssh_status");
|
||||
expect(status).toMatchObject({
|
||||
stage: "chooser",
|
||||
url: expect.stringMatching(
|
||||
/^https:\/\/termix\.test\/plugin-api\/opkssh\/chooser\/[\w-]+$/,
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the old callback for an install upgraded from 2.8", async () => {
|
||||
server = await startServer({ settings: { legacyCallback: true } });
|
||||
await writeConfig();
|
||||
await startSignIn();
|
||||
expect(server.mock.processRuns[0].args).toContain(
|
||||
"--remote-redirect-uri=https://termix.test/host/opkssh-callback",
|
||||
);
|
||||
});
|
||||
|
||||
it("writes a template and reports a missing config", async () => {
|
||||
server = await startServer();
|
||||
const socket = await startSignIn();
|
||||
expect(socket.sent[0]).toMatchObject({ type: "opkssh_config_error" });
|
||||
expect(
|
||||
await fs.readFile(path.join(server.dataDir, "config.yml"), "utf8"),
|
||||
).toContain("OPKSSH Configuration");
|
||||
expect(server.mock.processRuns).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("refuses redirect_uris that are not localhost", async () => {
|
||||
server = await startServer();
|
||||
await writeConfig(
|
||||
`${PROVIDERS_CONFIG} redirect_uris:\n - https://termix.example/host/opkssh-callback\n`,
|
||||
);
|
||||
const socket = await startSignIn();
|
||||
expect(socket.sent[0]).toMatchObject({ type: "opkssh_config_error" });
|
||||
expect(String(socket.sent[0].error)).toMatch(/must only contain localhost/);
|
||||
});
|
||||
|
||||
it("kills the process when the terminal goes away", async () => {
|
||||
server = await startServer();
|
||||
await writeConfig();
|
||||
const socket = await startSignIn();
|
||||
socket.close();
|
||||
await vi.waitFor(() =>
|
||||
expect(server!.processes[0].killed).toContain("SIGTERM"),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("routes", () => {
|
||||
it("reports and forgets a cached certificate", async () => {
|
||||
server = await startServer();
|
||||
expect((await server.request("GET", "/token/7")).body).toEqual({
|
||||
exists: false,
|
||||
});
|
||||
await writeConfig();
|
||||
await startSignIn();
|
||||
server.processes[0].emitStdout(`${KEY}\n${CERT}\n`);
|
||||
await vi.waitFor(async () =>
|
||||
expect((await server!.request("GET", "/token/7")).body.exists).toBe(true),
|
||||
);
|
||||
expect((await server.request("DELETE", "/token/7")).status).toBe(200);
|
||||
expect((await server.request("GET", "/token/7")).body.exists).toBe(false);
|
||||
});
|
||||
|
||||
it("refuses a host the user cannot reach, and anonymous callers", async () => {
|
||||
server = await startServer();
|
||||
expect((await server.request("GET", "/token/99")).status).toBe(404);
|
||||
expect((await server.request("GET", "/token/7", { user: "" })).status).toBe(
|
||||
401,
|
||||
);
|
||||
});
|
||||
|
||||
it("forwards the identity provider's callback to the sign-in it belongs to", async () => {
|
||||
server = await startServer();
|
||||
await writeConfig();
|
||||
const socket = await startSignIn();
|
||||
server.processes[0].emitStderr(
|
||||
"Opening browser to http://localhost:4567/chooser\n",
|
||||
);
|
||||
const requestId = String(
|
||||
socket.sent.find((m) => m.type === "opkssh_status")?.requestId,
|
||||
);
|
||||
const cookie = { cookie: `opkssh_request_id=${requestId}` };
|
||||
|
||||
// OPKSSH's callback listener is not up yet.
|
||||
expect(
|
||||
(
|
||||
await server.request("GET", "/callback?code=x", {
|
||||
user: "",
|
||||
headers: cookie,
|
||||
})
|
||||
).status,
|
||||
).toBe(503);
|
||||
|
||||
server.processes[0].emitStderr("listening on http://127.0.0.1:5555/\n");
|
||||
const forwarded = await server.request("GET", "/callback?code=x&state=s", {
|
||||
user: "",
|
||||
headers: cookie,
|
||||
});
|
||||
expect(forwarded.status).toBe(302);
|
||||
expect(forwarded.location).toBe(
|
||||
`/plugin-api/opkssh/callback/${requestId}?code=x&state=s`,
|
||||
);
|
||||
|
||||
expect(
|
||||
(await server.request("GET", "/callback?code=x", { user: "" })).status,
|
||||
).toBe(401);
|
||||
});
|
||||
|
||||
it("answers an unknown sign-in with a not-found page", async () => {
|
||||
server = await startServer();
|
||||
const response = await server.request("GET", "/chooser/nope", { user: "" });
|
||||
expect(response.status).toBe(404);
|
||||
expect(String(response.body)).toContain("Session Not Found");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import {
|
||||
renderWithApp,
|
||||
type RenderedPluginApp,
|
||||
} from "@termix/plugin-sdk/testing";
|
||||
import type { PluginManifest } from "@termix/plugin-sdk/manifest";
|
||||
import * as plugin from "../../src/frontend/index";
|
||||
import { OpksshOverlay } from "../../src/frontend/OpksshOverlay";
|
||||
import { redirectUri } from "../../src/frontend/RedirectUriSetting";
|
||||
import manifestJson from "../../manifest.json";
|
||||
import locales from "../../locales/en.json";
|
||||
|
||||
vi.mock("@termix/plugin-sdk/frontend", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@termix/plugin-sdk/frontend")>()),
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
const manifest = manifestJson as unknown as PluginManifest;
|
||||
|
||||
let rendered: RenderedPluginApp | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
await rendered?.deactivate();
|
||||
rendered = null;
|
||||
});
|
||||
|
||||
describe("opkssh activate", () => {
|
||||
it("registers the auth editor, the terminal overlay and the settings field", async () => {
|
||||
rendered = await renderWithApp(plugin, { manifest, locales });
|
||||
expect(rendered.registered.settingsComponents()).toEqual(["redirectUri"]);
|
||||
expect(rendered.registered.slot("terminal.overlay")).toEqual([
|
||||
"opkssh.signIn",
|
||||
]);
|
||||
await rendered.deactivate();
|
||||
expect(rendered.registered.settingsComponents()).toEqual([]);
|
||||
expect(rendered.registered.slot("terminal.overlay")).toEqual([]);
|
||||
rendered = null;
|
||||
});
|
||||
});
|
||||
|
||||
describe("redirectUri", () => {
|
||||
it("names the plugin callback, or the 2.8 one", () => {
|
||||
expect(redirectUri(false, "https://t.example/app/")).toBe(
|
||||
"https://t.example/app/plugin-api/opkssh/callback",
|
||||
);
|
||||
expect(redirectUri(true, "https://t.example/")).toBe(
|
||||
"https://t.example/host/opkssh-callback",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("OpksshOverlay", () => {
|
||||
function setup() {
|
||||
let listener: (message: {
|
||||
type: string;
|
||||
[key: string]: unknown;
|
||||
}) => void = () => {};
|
||||
const props = {
|
||||
host: { id: 7 },
|
||||
subscribe: vi.fn((next: typeof listener) => {
|
||||
listener = next;
|
||||
return () => {};
|
||||
}),
|
||||
holdConnectTimeout: vi.fn(),
|
||||
fail: vi.fn(),
|
||||
disconnect: vi.fn(),
|
||||
send: vi.fn(),
|
||||
connectPayload: vi.fn(() => ({ hostId: 7, cols: 80, rows: 24 })),
|
||||
};
|
||||
render(<OpksshOverlay {...props} />);
|
||||
const emit = (message: { type: string; [key: string]: unknown }) =>
|
||||
act(() => listener(message));
|
||||
return { props, emit };
|
||||
}
|
||||
|
||||
it("starts the sign-in once, then reports a second request as a failure", () => {
|
||||
const { props, emit } = setup();
|
||||
emit({ type: "opkssh_auth_required", hostId: 7 });
|
||||
expect(props.send).toHaveBeenCalledWith("opkssh_start_auth", { hostId: 7 });
|
||||
expect(props.holdConnectTimeout).toHaveBeenCalledWith(true);
|
||||
|
||||
emit({ type: "opkssh_auth_required", hostId: 7 });
|
||||
expect(props.fail).toHaveBeenCalledWith("errors.authFailed");
|
||||
});
|
||||
|
||||
it("shows the chooser, cancels it, and reconnects once signed in", () => {
|
||||
const { props, emit } = setup();
|
||||
emit({ type: "opkssh_auth_required", hostId: 7 });
|
||||
emit({
|
||||
type: "opkssh_status",
|
||||
stage: "chooser",
|
||||
requestId: "req-1",
|
||||
url: "https://termix.test/plugin-api/opkssh/chooser/req-1",
|
||||
providers: [{ alias: "google", issuer: "accounts.google.com" }],
|
||||
});
|
||||
expect(screen.getByText("dialog.title")).toBeTruthy();
|
||||
|
||||
emit({ type: "opkssh_completed", requestId: "req-1" });
|
||||
expect(props.send).toHaveBeenCalledWith("opkssh_auth_completed", {
|
||||
hostId: 7,
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
});
|
||||
expect(screen.queryByText("dialog.title")).toBeNull();
|
||||
|
||||
emit({
|
||||
type: "opkssh_status",
|
||||
stage: "chooser",
|
||||
requestId: "req-2",
|
||||
url: "https://termix.test/plugin-api/opkssh/chooser/req-2",
|
||||
});
|
||||
fireEvent.click(screen.getByText("common.cancel"));
|
||||
expect(props.send).toHaveBeenCalledWith("opkssh_cancel", {
|
||||
requestId: "req-2",
|
||||
});
|
||||
});
|
||||
|
||||
it("shows a config error", () => {
|
||||
const { emit } = setup();
|
||||
emit({
|
||||
type: "opkssh_config_error",
|
||||
requestId: "",
|
||||
error: "OPKSSH configuration not found.",
|
||||
});
|
||||
expect(screen.getByText("OPKSSH configuration not found.")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user