341 lines
24 KiB
TypeScript
341 lines
24 KiB
TypeScript
// PEP-251 Access Hub: databases, SSH/SFTP, S3 and mailboxes through the gateway — on mocks of
|
||
// each service (src/mock-access.ts). Scenario names follow
|
||
// openspec/changes/pep-251-access-hub-protocols/specs/access-hub/spec.md.
|
||
import assert from "node:assert/strict";
|
||
import { after, before, describe, test } from "node:test";
|
||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
||
import { eq } from "drizzle-orm";
|
||
import { stripAsIs } from "@peppa/shared/i18n";
|
||
import { core, db, project, teardown } from "./helpers.ts";
|
||
import { MockMailServer, MockS3, MockSqlServer, MockSshServer, mockGatewayDrivers, mockResolve } from "../src/mock-access.ts";
|
||
|
||
process.env.PEPPA_SECRET ??= "mock-access-hub-secret";
|
||
delete process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE; // internal addresses must be refused here
|
||
const { createAgentServer } = await import("@peppa/mcp/agent");
|
||
const { connections, connectionLog, agents, sessions, events } = await import("@peppa/db");
|
||
|
||
const PG_PASSWORD = "mock-pg-Pa55word-xyz";
|
||
const SSH_PASSWORD = "mock-ssh-Pa55word-abc";
|
||
const S3_SECRET = "mockS3SecretKey/abcdefghijklmnop";
|
||
const MAIL_PASSWORD = "mock-mail-Pa55word-q";
|
||
|
||
const PUBLIC = "93.184.216.34";
|
||
const resolve = mockResolve({ "db.example.com": [PUBLIC], "srv.example.com": [PUBLIC], "s3.example.com": [PUBLIC], "mail.example.com": [PUBLIC], "rebind.example.com": ["10.0.0.7"], "own.forge.example": ["10.1.2.3"] });
|
||
|
||
const pg = new MockSqlServer(PG_PASSWORD);
|
||
pg.tables.set("orders", { columns: ["id", "total"], rows: Array.from({ length: 250 }, (_, i) => [i + 1, (i + 1) * 100]) });
|
||
const ssh = new MockSshServer(SSH_PASSWORD);
|
||
ssh.files.set("/var/www/logs/app.log", Buffer.from("started\nok\n"));
|
||
ssh.files.set("/etc/passwd", Buffer.from("root:x:0:0"));
|
||
ssh.links.set("/var/www/escape", "/etc");
|
||
ssh.commands.set("uptime", { out: " 10:00 up 3 days\n" });
|
||
ssh.commands.set("echo-secret", { out: `password is ${SSH_PASSWORD}\n` });
|
||
const s3 = new MockS3("MOCKAKIA1234567", "shop-files");
|
||
const mail = new MockMailServer(MAIL_PASSWORD);
|
||
const drivers = mockGatewayDrivers({ sql: pg, ssh, mail });
|
||
const opts = { drivers, resolve, fetch: s3.fetch };
|
||
core.setGatewayDefaults(opts);
|
||
|
||
let anna: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
let boris: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
let asel: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
|
||
before(async () => {
|
||
anna = await core.upsertUserFromGitea(db, { id: 2511, login: "mock-anna" }, { access_token: "a" });
|
||
boris = await core.upsertUserFromGitea(db, { id: 2512, login: "mock-boris" }, { access_token: "b" });
|
||
asel = await core.upsertUserFromGitea(db, { id: 2513, login: "mock-asel" }, { access_token: "c" });
|
||
await core.setPlatformAdmins(db, ["mock-asel"]);
|
||
});
|
||
after(async () => {
|
||
core.setGatewayDefaults({});
|
||
await teardown();
|
||
});
|
||
|
||
async function ownedProject(ownerId: number) {
|
||
const p = await project({ turns: [] });
|
||
const proj = await core.getProject(db, p.key);
|
||
await core.setProjectOwner(db, proj.id, ownerId);
|
||
const task = (await core.listTasks(db, { projectId: proj.id }))[0]!;
|
||
return { proj, task };
|
||
}
|
||
|
||
let agentSeq = 0;
|
||
async function agentSession(projectId: number, taskId: number) {
|
||
const s = await core.createSession(db, { projectId, taskId });
|
||
const [a] = await db.insert(agents).values({ name: `Мок-агент п${++agentSeq}-${Date.now()}` }).returning();
|
||
await db.update(sessions).set({ agentId: a!.id, container: `peppa-s${s.id}` }).where(eq(sessions.id, s.id));
|
||
return s.id;
|
||
}
|
||
|
||
const use = (sessionId: number, connection: string | number, operation: string, args: Record<string, unknown> = {}) => core.useConnection(db, { sessionId, connection, operation, args });
|
||
|
||
async function setup(name: string, protocol: "postgres" | "mysql" | "ssh" | "s3" | "mail", config: Record<string, unknown>, secret: string, modes: { readMode?: "auto" | "ask" | "off"; writeMode?: "auto" | "ask" | "off" } = {}) {
|
||
const c = await core.createConnection(db, anna.id, { name, protocol, config, secret });
|
||
const { proj, task } = await ownedProject(anna.id);
|
||
await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, readMode: modes.readMode ?? "auto", writeMode: modes.writeMode ?? "ask" });
|
||
const sessionId = await agentSession(proj.id, task.id);
|
||
return { c, proj, task, sessionId };
|
||
}
|
||
|
||
const PG = { host: "db.example.com", port: 5432, database: "shop", user: "reader" };
|
||
const SSH = { host: "srv.example.com", user: "deploy", root: "/var/www" };
|
||
const S3 = { endpoint: "https://s3.example.com", region: "eu-central-1", bucket: "shop-files", prefix: "app", accessKeyId: "MOCKAKIA1234567" };
|
||
const MAIL = { imapHost: "mail.example.com", smtpHost: "mail.example.com", user: "shop@example.com" };
|
||
|
||
async function journal(connectionId: number) {
|
||
return db.select().from(connectionLog).where(eq(connectionLog.connectionId, connectionId));
|
||
}
|
||
|
||
describe("База данных через шлюз", () => {
|
||
test("Агент читает таблицу, не зная пароля", async () => {
|
||
const { c, sessionId } = await setup("Магазин БД", "postgres", PG, PG_PASSWORD);
|
||
assert.equal(c.protocol, "postgres");
|
||
assert.equal(c.baseUrl, "postgres://reader@db.example.com:5432/shop");
|
||
assert.ok(!JSON.stringify(await core.listConnections(db, anna.id)).includes(PG_PASSWORD));
|
||
const [row] = await db.select().from(connections).where(eq(connections.id, c.id));
|
||
assert.ok(!row!.secretEnc!.includes(PG_PASSWORD) && !JSON.stringify(row!.config).includes(PG_PASSWORD));
|
||
|
||
const r = await use(sessionId, "Магазин БД", "query", { sql: "select * from orders" });
|
||
assert.equal(r.ok, true, JSON.stringify(r));
|
||
assert.ok(r.ok && /^rows: 250 · page 1 of 3/.test(r.text));
|
||
assert.ok(r.ok && r.text.split("\n")[1] === "id\ttotal");
|
||
const call = pg.calls.at(-1)!;
|
||
assert.equal(call.request.readOnly, true);
|
||
assert.equal(call.target.address, PUBLIC, "connects to the checked address");
|
||
assert.equal(call.target.host, "db.example.com", "the name only verifies the certificate");
|
||
assert.equal(call.target.password, PG_PASSWORD);
|
||
const p3 = await use(sessionId, c.slug, "query", { sql: "select * from orders", page: 3 });
|
||
assert.ok(p3.ok && /page 3 of 3/.test(p3.text) && p3.text.split("\n").length === 52);
|
||
});
|
||
|
||
test("Запись в базу ждёт подтверждения владельца", async () => {
|
||
const { c, sessionId } = await setup("Магазин БД запись", "postgres", PG, PG_PASSWORD);
|
||
const before = pg.calls.length;
|
||
assert.deepEqual(await use(sessionId, c.id, "execute", { sql: "insert into orders values (999, 1)" }), { ok: false, reason: "needs_approval" });
|
||
assert.equal(pg.calls.length, before, "the database is not touched");
|
||
// Write through `query` is refused before the database too.
|
||
assert.deepEqual(await use(sessionId, c.id, "query", { sql: "delete from orders" }), { ok: false, reason: "not_read_query" });
|
||
assert.deepEqual(await use(sessionId, c.id, "query", { sql: "select 1; drop table orders" }), { ok: false, reason: "bad_request" });
|
||
const rows = await journal(c.id);
|
||
assert.ok(rows.some((r) => r.method === "EXECUTE" && r.reason === "needs_approval"));
|
||
assert.ok(!JSON.stringify(rows).includes("insert into") && !JSON.stringify(rows).includes("orders"), "no SQL text in the journal");
|
||
});
|
||
|
||
test("Запись с разрешением «сразу» выполняется", async () => {
|
||
const { c, sessionId } = await setup("Магазин MySQL", "mysql", { ...PG, port: "" }, PG_PASSWORD, { writeMode: "auto" });
|
||
assert.equal(c.baseUrl, "mysql://reader@db.example.com:3306/shop");
|
||
const r = await use(sessionId, c.id, "execute", { sql: "insert into orders values (1000, 5);" });
|
||
assert.ok(r.ok && /rows affected: 1/.test(r.text), JSON.stringify(r));
|
||
assert.equal(pg.calls.at(-1)!.request.readOnly, false);
|
||
});
|
||
|
||
test("Ошибка базы возвращается агенту, пароль — нет", async () => {
|
||
const { c, sessionId } = await setup("Магазин БД ошибка", "postgres", PG, PG_PASSWORD);
|
||
const r = await use(sessionId, c.id, "query", { sql: "select * from nope" });
|
||
assert.equal(r.ok, false);
|
||
assert.ok(!r.ok && r.reason === "query_error" && /relation "nope" does not exist/.test(r.message ?? ""));
|
||
// Wrong stored password: the owner's check says «ключ не подходит».
|
||
await core.replaceConnectionSecret(db, anna.id, c.id, "wrong-password");
|
||
const check = await core.checkConnection(db, anna.id, c.id);
|
||
assert.equal(check.status, "bad_key");
|
||
await core.replaceConnectionSecret(db, anna.id, c.id, PG_PASSWORD);
|
||
assert.equal((await core.checkConnection(db, anna.id, c.id)).status, "ok");
|
||
});
|
||
});
|
||
|
||
describe("Изоляция и адреса", () => {
|
||
test("Чужое подключение недоступно другому пользователю", async () => {
|
||
const { c } = await setup("Анна БД", "postgres", PG, PG_PASSWORD);
|
||
assert.ok(!(await core.listConnections(db, boris.id)).some((x) => x.id === c.id));
|
||
assert.ok(!(await core.listConnections(db, asel.id)).some((x) => x.id === c.id), "superadmin does not see it either");
|
||
const { proj, task } = await ownedProject(boris.id);
|
||
const borisSession = await agentSession(proj.id, task.id);
|
||
assert.deepEqual(await use(borisSession, c.id, "query", { sql: "select 1" }), { ok: false, reason: "unknown_connection" });
|
||
await assert.rejects(core.grantConnection(db, boris.id, c.id, { projectId: proj.id, readMode: "auto" }), /Подключение не найдено/);
|
||
await assert.rejects(core.resetHostKey(db, boris.id, c.id), /Подключение не найдено/);
|
||
});
|
||
|
||
test("Внутренний адрес отклоняется", async () => {
|
||
await assert.rejects(core.createConnection(db, anna.id, { name: "Локальная БД", protocol: "postgres", config: { ...PG, host: "10.0.0.5" }, secret: PG_PASSWORD }), /адрес в интернете/);
|
||
await assert.rejects(core.createConnection(db, anna.id, { name: "Локальная БД 2", protocol: "ssh", config: { ...SSH, host: "localhost" }, secret: SSH_PASSWORD }), /адрес в интернете/);
|
||
// A public name that resolves to an internal address at call time (DNS rebinding).
|
||
const { c, sessionId } = await setup("Подменённая БД", "postgres", { ...PG, host: "rebind.example.com" }, PG_PASSWORD);
|
||
const before = pg.calls.length;
|
||
assert.deepEqual(await use(sessionId, c.id, "query", { sql: "select 1" }), { ok: false, reason: "blocked_address" });
|
||
assert.equal(pg.calls.length, before, "nothing connected");
|
||
assert.ok((await journal(c.id)).some((r) => r.kind === "result" && r.decision === "denied" && r.reason === "blocked_address"));
|
||
});
|
||
|
||
test("Свой сервер FORGE с внутренним адресом — только по разрешению администратора", async () => {
|
||
await assert.rejects(core.setInternalHosts(db, anna, ["own.forge.example"]), /только администратор/);
|
||
await assert.rejects(core.createConnection(db, anna.id, { name: "Своя БД IP", protocol: "postgres", config: { ...PG, host: "10.1.2.3" }, secret: PG_PASSWORD }), /адрес в интернете/);
|
||
// The name looks public, so it is saved; it resolves to an internal address — refused until the superadmin allows it.
|
||
const { c, sessionId } = await setup("Своя БД", "postgres", { ...PG, host: "own.forge.example" }, PG_PASSWORD);
|
||
assert.deepEqual(await use(sessionId, c.id, "query", { sql: "select 1" }), { ok: false, reason: "blocked_address" });
|
||
await core.setInternalHosts(db, asel, ["own.forge.example", "10.1.2.3"]);
|
||
assert.equal((await core.createConnection(db, anna.id, { name: "Своя БД IP", protocol: "postgres", config: { ...PG, host: "10.1.2.3" }, secret: PG_PASSWORD })).protocol, "postgres");
|
||
const r = await use(sessionId, c.id, "query", { sql: "select 1" });
|
||
assert.equal(r.ok, true, JSON.stringify(r));
|
||
assert.equal(pg.calls.at(-1)!.target.address, "10.1.2.3");
|
||
await core.setInternalHosts(db, asel, []);
|
||
assert.deepEqual(await use(sessionId, c.id, "query", { sql: "select 1" }), { ok: false, reason: "blocked_address" });
|
||
});
|
||
|
||
test("Агент без изоляции получает отказ", async () => {
|
||
const { c, sessionId } = await setup("БД без изоляции", "postgres", PG, PG_PASSWORD);
|
||
await db.update(sessions).set({ container: null }).where(eq(sessions.id, sessionId));
|
||
assert.deepEqual(await use(sessionId, c.id, "query", { sql: "select 1" }), { ok: false, reason: "not_isolated" });
|
||
});
|
||
});
|
||
|
||
describe("SSH и SFTP через шлюз", () => {
|
||
test("Агент выполняет команду на сервере, не зная пароля", async () => {
|
||
const { c, sessionId } = await setup("Сервер", "ssh", SSH, SSH_PASSWORD, { writeMode: "auto" });
|
||
const r = await use(sessionId, c.id, "exec", { command: "uptime" });
|
||
assert.ok(r.ok && /^exit code: 0\n 10:00 up 3 days/.test(r.text), JSON.stringify(r));
|
||
assert.equal(ssh.calls.at(-1)!.target.address, PUBLIC);
|
||
// First contact pins the server key.
|
||
const [row] = await db.select().from(connections).where(eq(connections.id, c.id));
|
||
assert.equal((row!.config as { hostKey: string }).hostKey, ssh.fingerprint);
|
||
// The password never reaches the agent even if the server prints it.
|
||
const echo = await use(sessionId, c.id, "exec", { command: "echo-secret" });
|
||
assert.ok(echo.ok && !echo.text.includes(SSH_PASSWORD) && echo.text.includes("••••"));
|
||
const rows = await journal(c.id);
|
||
assert.ok(rows.some((x) => x.method === "EXEC") && !JSON.stringify(rows).includes("uptime"), "no command text in the journal");
|
||
});
|
||
|
||
test("Файлы — только внутри разрешённой папки", async () => {
|
||
const { c, sessionId } = await setup("Сервер файлы", "ssh", SSH, SSH_PASSWORD, { writeMode: "auto" });
|
||
const read = await use(sessionId, c.id, "sftp_read", { path: "logs/app.log" });
|
||
assert.ok(read.ok && read.text === "started\nok\n", JSON.stringify(read));
|
||
assert.deepEqual(await use(sessionId, c.id, "sftp_read", { path: "../../etc/passwd" }), { ok: false, reason: "outside_root" });
|
||
// An absolute path is taken inside the folder too: /var/www/etc/passwd, not the system file.
|
||
assert.deepEqual(await use(sessionId, c.id, "sftp_read", { path: "/etc/passwd" }), { ok: false, reason: "not_found" });
|
||
assert.equal((ssh.calls.at(-1)!.request as { path: string }).path, "/var/www/etc/passwd");
|
||
// A symlink inside the folder that points out of it.
|
||
assert.deepEqual(await use(sessionId, c.id, "sftp_read", { path: "escape/passwd" }), { ok: false, reason: "outside_root" });
|
||
const write = await use(sessionId, c.id, "sftp_write", { path: "logs/note.txt", content: "hello" });
|
||
assert.equal(write.ok, true);
|
||
assert.equal(ssh.files.get("/var/www/logs/note.txt")?.toString(), "hello");
|
||
const list = await use(sessionId, c.id, "sftp_list", { path: "logs" });
|
||
assert.ok(list.ok && /file\t11\tapp\.log/.test(list.text));
|
||
assert.ok((await journal(c.id)).some((x) => x.method === "SFTP_READ" && x.path === "/logs/app.log"));
|
||
});
|
||
|
||
test("Смена ключа сервера — отказ и сообщение владельцу", async () => {
|
||
const { c, sessionId } = await setup("Сервер ключ", "ssh", SSH, SSH_PASSWORD, { writeMode: "auto" });
|
||
assert.equal((await use(sessionId, c.id, "exec", { command: "uptime" })).ok, true);
|
||
const old = ssh.hostKey;
|
||
ssh.hostKey = Buffer.from("mock-host-key-EVIL");
|
||
try {
|
||
const before = ssh.calls.length;
|
||
assert.deepEqual(await use(sessionId, c.id, "exec", { command: "uptime" }), { ok: false, reason: "host_key_changed" });
|
||
assert.equal(ssh.calls.length, before + 1);
|
||
assert.equal(await core.tellHostKeyChanged(db, { id: c.id, name: c.name, ownerId: anna.id }, ssh.fingerprint), false, "one message per new key");
|
||
const feed = await core.masterFeed(db, anna);
|
||
assert.ok(feed.some((m) => /Ключ сервера подключения «Сервер ключ» изменился/.test(stripAsIs(m.text))));
|
||
assert.equal((await core.checkConnection(db, anna.id, c.id)).status, "host_key");
|
||
// The owner checked the server and accepts the new key.
|
||
await core.resetHostKey(db, anna.id, c.id);
|
||
assert.equal((await use(sessionId, c.id, "exec", { command: "uptime" })).ok, true);
|
||
const [row] = await db.select().from(connections).where(eq(connections.id, c.id));
|
||
assert.equal((row!.config as { hostKey: string }).hostKey, ssh.fingerprint);
|
||
const ev = await db.select().from(events).where(eq(events.type, "connection_host_key_changed"));
|
||
assert.ok(ev.length >= 1);
|
||
} finally {
|
||
ssh.hostKey = old;
|
||
}
|
||
});
|
||
|
||
test("Известный отпечаток задаётся при подключении", async () => {
|
||
await assert.rejects(core.createConnection(db, anna.id, { name: "Сервер плохой отпечаток", protocol: "ssh", config: { ...SSH, hostKey: "md5:aa" }, secret: SSH_PASSWORD }), /SHA256/);
|
||
const { c, sessionId } = await setup("Сервер с отпечатком", "ssh", { ...SSH, hostKey: "SHA256:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" }, SSH_PASSWORD, { writeMode: "auto" });
|
||
assert.deepEqual(await use(sessionId, c.id, "exec", { command: "uptime" }), { ok: false, reason: "host_key_changed" });
|
||
});
|
||
});
|
||
|
||
describe("S3 через шлюз", () => {
|
||
test("Список, запись, чтение и удаление в пределах папки", async () => {
|
||
const { c, sessionId } = await setup("Файлы", "s3", S3, S3_SECRET, { writeMode: "auto" });
|
||
assert.equal(c.baseUrl, "https://s3.example.com/shop-files/app/");
|
||
assert.equal((await use(sessionId, c.id, "put", { key: "reports/1.csv", content: "a,b\n1,2\n", content_type: "text/csv" })).ok, true);
|
||
assert.equal(s3.objects.get("app/reports/1.csv")?.toString(), "a,b\n1,2\n");
|
||
s3.objects.set("other/secret.txt", Buffer.from("not yours"));
|
||
const list = await use(sessionId, c.id, "list");
|
||
assert.ok(list.ok && /\treports\/1\.csv$/.test(list.text) && !list.text.includes("secret"), JSON.stringify(list));
|
||
const get = await use(sessionId, c.id, "get", { key: "reports/1.csv" });
|
||
assert.ok(get.ok && get.text === "a,b\n1,2\n");
|
||
assert.deepEqual(await use(sessionId, c.id, "get", { key: "../other/secret.txt" }), { ok: false, reason: "bad_path" });
|
||
assert.equal((await use(sessionId, c.id, "delete", { key: "reports/1.csv" })).ok, true);
|
||
assert.ok(!s3.objects.has("app/reports/1.csv"));
|
||
for (const r of s3.requests) {
|
||
assert.ok(!JSON.stringify(r).includes(S3_SECRET), "the secret key is never sent, only the signature");
|
||
assert.match(r.headers.authorization ?? "", /^AWS4-HMAC-SHA256 Credential=MOCKAKIA1234567\//);
|
||
}
|
||
assert.equal((await core.checkConnection(db, anna.id, c.id)).status, "ok");
|
||
});
|
||
|
||
test("Подпись S3 совпадает с образцом AWS", () => {
|
||
// AWS SigV4 sample keys, «GET Object» without the Range header; the signature was checked
|
||
// once against the AWS SDK signer (@smithy/signature-v4) — a regression guard.
|
||
const r = core.signS3({ endpoint: "https://s3.amazonaws.com", region: "us-east-1", bucket: "examplebucket", prefix: "", accessKeyId: "AKIAIOSFODNN7EXAMPLE" }, "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", { method: "GET", key: "test.txt" }, new Date("2013-05-24T00:00:00Z"));
|
||
assert.equal(r.url.toString(), "https://s3.amazonaws.com/examplebucket/test.txt");
|
||
assert.match(r.headers.authorization!, /Credential=AKIAIOSFODNN7EXAMPLE\/20130524\/us-east-1\/s3\/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=0fcb291c4b47980ad34dd9a29532ceae67b48e45de3d6054873b430740567ec2$/);
|
||
});
|
||
});
|
||
|
||
describe("Почта через шлюз", () => {
|
||
test("Чтение писем и отправка по подтверждению", async () => {
|
||
const uid = mail.deliver("INBOX", { from: "client@example.kz", subject: "Где мой заказ?", text: "Заказ 15 не пришёл" });
|
||
const { c, sessionId } = await setup("Почта магазина", "mail", MAIL, MAIL_PASSWORD);
|
||
const list = await use(sessionId, c.id, "read");
|
||
assert.ok(list.ok && list.text.includes("Где мой заказ?"), JSON.stringify(list));
|
||
const one = await use(sessionId, c.id, "read", { uid });
|
||
assert.ok(one.ok && one.text.includes("Заказ 15 не пришёл"));
|
||
assert.deepEqual(await use(sessionId, c.id, "send", { to: "client@example.kz", subject: "Ответ", text: "Заказ в пути" }), { ok: false, reason: "needs_approval" });
|
||
assert.equal(mail.sent.length, 0);
|
||
assert.equal(mail.calls.at(-1)!.target.imap.address, PUBLIC);
|
||
});
|
||
|
||
test("Отправка и пометки с разрешением «сразу»", async () => {
|
||
const uid = mail.deliver("INBOX", { from: "client2@example.kz", subject: "Спасибо", text: "Всё пришло" });
|
||
const { c, sessionId } = await setup("Почта отправка", "mail", MAIL, MAIL_PASSWORD, { writeMode: "auto" });
|
||
const sent = await use(sessionId, c.id, "send", { to: "client2@example.kz", subject: "Пожалуйста", text: "Рады помочь" });
|
||
assert.equal(sent.ok, true, JSON.stringify(sent));
|
||
assert.deepEqual(mail.sent.at(-1), { from: "shop@example.com", to: ["client2@example.kz"], subject: "Пожалуйста", text: "Рады помочь" });
|
||
assert.deepEqual(await use(sessionId, c.id, "send", { to: "client2@example.kz", subject: "a\r\nBcc: x@y.z", text: "x" }), { ok: false, reason: "bad_request" });
|
||
assert.equal((await use(sessionId, c.id, "change", { uid, add_flags: "\\Seen", move_to: "Archive" })).ok, true);
|
||
assert.ok(mail.folders.get("Archive")!.some((l) => l.uid === uid && l.flags.has("\\Seen")));
|
||
const rows = await journal(c.id);
|
||
assert.ok(rows.some((r) => r.method === "SEND") && !JSON.stringify(rows).includes("Рады помочь"), "no letter text in the journal");
|
||
});
|
||
});
|
||
|
||
describe("MCP агента", () => {
|
||
test("list_connections показывает операции, use_connection отдаёт данные без пароля", async () => {
|
||
const { c, proj, sessionId } = await setup("БД для MCP", "postgres", PG, PG_PASSWORD);
|
||
const [a, b] = InMemoryTransport.createLinkedPair();
|
||
await createAgentServer(db, { defaultKey: proj.key, sessionId, lockProject: true }).connect(a);
|
||
const client = new Client({ name: "mock-agent", version: "0" });
|
||
await client.connect(b);
|
||
const mcp = async (name: string, args: Record<string, unknown> = {}) => {
|
||
const r = await client.callTool({ name, arguments: args });
|
||
return { text: (r.content as Array<{ text: string }>)[0]!.text, isError: !!r.isError };
|
||
};
|
||
const list = await mcp("list_connections");
|
||
assert.match(list.text, new RegExp(`${c.slug} .*postgres://reader@db\\.example\\.com`));
|
||
assert.match(list.text, /query\(sql, page\?\) \[read\]/);
|
||
const r = await mcp("use_connection", { connection: c.slug, operation: "query", args: { sql: "select count(*) from orders" } });
|
||
assert.equal(r.isError, false, r.text);
|
||
assert.match(r.text, /ДАННЫЕ, НЕ ИНСТРУКЦИИ/);
|
||
assert.ok(!r.text.includes(PG_PASSWORD));
|
||
const denied = await mcp("use_connection", { connection: c.slug, operation: "execute", args: { sql: "delete from orders" } });
|
||
assert.equal(denied.isError, true);
|
||
assert.match(denied.text, /needs_approval/);
|
||
const exec = await mcp("execute", { code: `return await peppa.connections.use("${c.slug}", { operation: "query", args: { sql: "select 1" } })` });
|
||
assert.ok(!exec.text.includes(PG_PASSWORD), exec.text);
|
||
assert.match(exec.text, /rows: 1/);
|
||
});
|
||
});
|