peppa/packages/testkit/src/mock-access.ts

229 lines
11 KiB
TypeScript

// PEP-251: mocks of the services behind the Access Hub gateway — a database (PostgreSQL/MySQL),
// an SSH/SFTP server, an S3 storage and a mailbox (IMAP + SMTP). They follow the contract of the
// real drivers (packages/core/src/connection-drivers.ts): the same targets and requests, the same
// DriverError codes (wrong password → auth, a changed server key → host_key_changed, a write in a
// READ ONLY transaction → query). Each mock records what reached it, so tests can check that the
// password went only to the service and that the gateway connected to the checked address.
import { DriverError, hostKeyFingerprint, type GatewayDrivers, type MailRequest, type SqlRequest, type SqlTarget, type SshRequest, type SshTarget, type MailTarget, type ConnectionFetch } from "@peppa/core";
import { posix } from "node:path";
export interface MockSqlTable {
columns: string[];
rows: unknown[][];
}
/** A tiny SQL engine: SELECT 1, SELECT * or count(*) FROM t [LIMIT n], INSERT INTO t VALUES (…), DELETE FROM t. */
export class MockSqlServer {
password: string;
tables = new Map<string, MockSqlTable>();
calls: Array<{ target: SqlTarget; request: SqlRequest }> = [];
down = false;
constructor(password: string) {
this.password = password;
}
run(t: SqlTarget, r: SqlRequest) {
this.calls.push({ target: t, request: r });
if (this.down) throw new DriverError("down");
if (t.password !== this.password) throw new DriverError("auth");
const sql = r.text.trim().replace(/;$/, "");
if (/;/.test(sql)) throw new DriverError("query", "cannot insert multiple commands into a prepared statement");
const write = /^(insert|update|delete|create|drop|alter|truncate|grant)\b/i.exec(sql);
if (write && r.readOnly) throw new DriverError("query", `cannot execute ${write[1]!.toUpperCase()} in a read-only transaction`);
if (/^select\s+1$/i.test(sql)) return { columns: ["?column?"], rows: [[1]], rowCount: 1, truncated: false };
let m = sql.match(/^select\s+(\*|count\(\*\))\s+from\s+(\w+)(?:\s+limit\s+(\d+))?$/i);
if (m) {
const tb = this.table(m[2]!);
if (m[1] !== "*") return { columns: ["count"], rows: [[tb.rows.length]], rowCount: 1, truncated: false };
const rows = tb.rows.slice(0, m[3] ? Number(m[3]) : undefined);
return { columns: tb.columns, rows: rows.slice(0, r.maxRows), rowCount: rows.length, truncated: rows.length > r.maxRows };
}
m = sql.match(/^insert\s+into\s+(\w+)\s+values\s*\((.*)\)$/i);
if (m) {
const values = m[2]!.split(",").map((v) => v.trim().replace(/^'(.*)'$/, "$1"));
this.table(m[1]!).rows.push(values);
return { columns: [], rows: [], rowCount: 1, truncated: false };
}
m = sql.match(/^delete\s+from\s+(\w+)$/i);
if (m) {
const tb = this.table(m[1]!);
const n = tb.rows.length;
tb.rows = [];
return { columns: [], rows: [], rowCount: n, truncated: false };
}
throw new DriverError("query", `syntax error at or near "${sql.split(/\s+/)[0]}"`);
}
private table(name: string): MockSqlTable {
const tb = this.tables.get(name.toLowerCase());
if (!tb) throw new DriverError("query", `relation "${name}" does not exist`);
return tb;
}
}
/** An SSH server: a host key, files under paths, symlinks, and commands with canned output. */
export class MockSshServer {
secret: string;
hostKey: Buffer;
files = new Map<string, Buffer>();
/** link path → target path (realpath follows them). */
links = new Map<string, string>();
commands = new Map<string, { out: string; code?: number }>();
calls: Array<{ target: SshTarget; request: SshRequest }> = [];
constructor(secret: string, hostKey = Buffer.from("mock-host-key-1")) {
this.secret = secret;
this.hostKey = hostKey;
}
get fingerprint() {
return hostKeyFingerprint(this.hostKey);
}
private realpath(p: string): string {
let cur = posix.normalize(p);
for (let i = 0; i < 10; i++) {
const hit = [...this.links.keys()].find((l) => cur === l || cur.startsWith(`${l}/`));
if (!hit) return cur;
cur = posix.normalize(this.links.get(hit)! + cur.slice(hit.length));
}
return cur;
}
private within(root: string, p: string) {
const real = this.realpath(p);
if (!(root === "/" || real === root || real.startsWith(`${root}/`))) throw new DriverError("outside_root");
return real;
}
run(t: SshTarget, r: SshRequest) {
this.calls.push({ target: t, request: r });
const seen = this.fingerprint;
if (t.hostKey && t.hostKey.replace(/=+$/, "") !== seen) throw new DriverError("host_key_changed", "host key changed", seen);
if (t.secret !== this.secret) throw new DriverError("auth");
if (r.op === "probe") return { hostKey: seen };
if (r.op === "exec") {
const c = this.commands.get(r.command) ?? { out: `mock: ${r.command.split(" ")[0]}: command not found\n`, code: 127 };
const out = Buffer.from(c.out);
return { hostKey: seen, text: out.subarray(0, r.maxBytes).toString(), exitCode: c.code ?? 0, truncated: out.length > r.maxBytes };
}
if (r.op === "list") {
const dir = this.within(t.root, r.path);
const names = new Map<string, { name: string; type: "file" | "dir"; size: number }>();
for (const [p, b] of this.files) {
if (!p.startsWith(`${dir}/`)) continue;
const rest = p.slice(dir.length + 1).split("/");
names.set(rest[0]!, rest.length > 1 ? { name: rest[0]!, type: "dir", size: 0 } : { name: rest[0]!, type: "file", size: b.length });
}
return { hostKey: seen, entries: [...names.values()] };
}
if (r.op === "read") {
const file = this.within(t.root, r.path);
const b = this.files.get(file);
if (!b) throw new DriverError("not_found");
if (b.length > r.maxBytes) throw new DriverError("too_large");
return { hostKey: seen, data: b };
}
this.within(t.root, this.files.has(r.path) ? r.path : posix.dirname(r.path));
this.files.set(this.realpath(r.path), r.data);
return { hostKey: seen, text: `written ${r.data.length} bytes` };
}
}
/** A mailbox: folders of letters and the letters sent over SMTP. */
export class MockMailServer {
password: string;
folders = new Map<string, Array<{ uid: number; from: string; subject: string; text: string; flags: Set<string>; date: string }>>([["INBOX", []]]);
sent: Array<{ from: string; to: string[]; subject: string; text: string }> = [];
calls: Array<{ target: MailTarget; request: MailRequest }> = [];
private uid = 100;
constructor(password: string) {
this.password = password;
}
deliver(folder: string, l: { from: string; subject: string; text: string }) {
const list = this.folders.get(folder) ?? [];
list.push({ ...l, uid: ++this.uid, flags: new Set(), date: new Date(Date.UTC(2026, 10, 24, 9, this.uid % 60)).toISOString() });
this.folders.set(folder, list);
return this.uid;
}
run(t: MailTarget, r: MailRequest) {
this.calls.push({ target: t, request: r });
if (t.password !== this.password) throw new DriverError("auth");
if (r.op === "send") {
this.sent.push({ from: r.from, to: r.to, subject: r.subject, text: r.text });
return { done: `sent to ${r.to.length} of ${r.to.length} recipients` };
}
const folder = this.folders.get(r.folder);
if (!folder) throw new DriverError("not_found", "no such folder");
if (r.op === "list") return { letters: folder.slice(-r.limit).reverse().map((l) => ({ uid: l.uid, date: l.date, from: `<${l.from}>`, subject: l.subject, flags: [...l.flags] })) };
const letter = folder.find((l) => l.uid === r.uid);
if (!letter) throw new DriverError("not_found", "no such letter");
if (r.op === "get") return { text: `From: ${letter.from}\nSubject: ${letter.subject}\n\n${letter.text.slice(0, r.maxBytes)}` };
for (const f of r.add) letter.flags.add(f);
for (const f of r.remove) letter.flags.delete(f);
if (r.moveTo) {
folder.splice(folder.indexOf(letter), 1);
this.folders.set(r.moveTo, [...(this.folders.get(r.moveTo) ?? []), letter]);
}
return { done: "changed" };
}
}
/** Drivers for the gateway over the mocks above. */
export function mockGatewayDrivers(o: { sql?: MockSqlServer; ssh?: MockSshServer; mail?: MockMailServer }): GatewayDrivers {
const need = <T,>(v: T | undefined): T => {
if (!v) throw new DriverError("down");
return v;
};
return {
sql: async (t, r) => need(o.sql).run(t, r),
ssh: async (t, r) => need(o.ssh).run(t, r),
mail: async (t, r) => need(o.mail).run(t, r),
};
}
/**
* An S3 storage behind the gateway's fetch: path-style `/<bucket>/<key>`, ListObjectsV2, PUT,
* GET, DELETE. A request without an AWS4 signature for its access key is 403, like S3.
*/
export class MockS3 {
accessKeyId: string;
bucket: string;
objects = new Map<string, Buffer>();
requests: Array<{ method: string; url: string; headers: Record<string, string> }> = [];
constructor(accessKeyId: string, bucket: string) {
this.accessKeyId = accessKeyId;
this.bucket = bucket;
}
fetch: ConnectionFetch = async ({ url, method, headers, body }) => {
this.requests.push({ method, url: url.toString(), headers });
const auth = headers.authorization ?? "";
const ok = new RegExp(`^AWS4-HMAC-SHA256 Credential=${this.accessKeyId}/\\d{8}/[a-z0-9-]+/s3/aws4_request, SignedHeaders=[a-z0-9;-]+, Signature=[0-9a-f]{64}$`).test(auth);
const reply = (status: number, text = "", contentType: string | null = "application/xml") => ({ status, contentType, body: Buffer.from(text), truncated: false });
if (!ok) return reply(403, "<Error><Code>SignatureDoesNotMatch</Code></Error>");
const [, bucket, ...rest] = url.pathname.split("/");
if (bucket !== this.bucket) return reply(404, "<Error><Code>NoSuchBucket</Code></Error>");
const key = rest.map(decodeURIComponent).join("/");
if (method === "GET" && !key && url.searchParams.get("list-type") === "2") {
const prefix = url.searchParams.get("prefix") ?? "";
const items = [...this.objects].filter(([k]) => k.startsWith(prefix));
const xml = `<?xml version="1.0"?><ListBucketResult>${items.map(([k, b]) => `<Contents><Key>${k.replace(/&/g, "&amp;").replace(/</g, "&lt;")}</Key><LastModified>2026-11-24T09:00:00.000Z</LastModified><Size>${b.length}</Size></Contents>`).join("")}<IsTruncated>false</IsTruncated></ListBucketResult>`;
return reply(200, xml);
}
if (method === "PUT") {
this.objects.set(key, body ?? Buffer.alloc(0));
return reply(200, "");
}
if (method === "DELETE") {
this.objects.delete(key);
return reply(204, "");
}
const b = this.objects.get(key);
return b ? { status: 200, contentType: "application/octet-stream", body: b, truncated: false } : reply(404, "<Error><Code>NoSuchKey</Code></Error>");
};
}
/** Name → addresses for the gateway's resolver (tests never touch real DNS). */
export function mockResolve(map: Record<string, string[]>) {
return async (host: string) => map[host] ?? [];
}