peppa/packages/testkit/test/access-requests.test.ts

198 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PEP-250 Access Hub: an agent asks the owner for access itself; the owner connects the key once
// or refuses; the decision reaches the agent. Scenario names follow
// openspec/changes/pep-250-access-requests/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 { and, eq, like } from "drizzle-orm";
import { stripAsIs } from "@peppa/shared/i18n";
import { core, db, project, runner, teardown, type TestProject } from "./helpers.ts";
process.env.PEPPA_SECRET ??= "mock-access-requests-secret";
process.env.PEPPA_CONNECTIONS_UNISOLATED = "on"; // mock agents run without a container
process.env.PEPPA_WEB_URL = "https://forge.mock.test";
const { createAgentServer } = await import("@peppa/mcp/agent");
const { accessRequests, chatMessages, sessions, tasks, telegramOutbox, users } = await import("@peppa/db");
let anna: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
let boris: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
const ANNA_CHAT = 2_500_001;
before(async () => {
anna = await core.upsertUserFromGitea(db, { id: 2501, login: "mock-anna-250" }, { access_token: "a" });
boris = await core.upsertUserFromGitea(db, { id: 2502, login: "mock-boris-250" }, { access_token: "b" });
await db.update(users).set({ telegramChatId: ANNA_CHAT, telegramUserId: ANNA_CHAT }).where(eq(users.id, anna.id));
});
after(teardown);
/** A project of anna with a live mock agent on its story. */
async function story(turns: number): Promise<{ tp: TestProject; proj: Awaited<ReturnType<typeof core.getProject>>; sessionId: number; taskId: number }> {
const tp = await project({ turns: Array.from({ length: turns }, () => [{ say: "Работаю." }]) });
const proj = await core.getProject(db, tp.key);
await core.setProjectOwner(db, proj.id, anna.id);
const sessionId = await tp.start();
await tp.waitLog("turn 0", (e) => e.ev === "prompt");
const taskId = (await tp.task()).id;
await db.update(tasks).set({ status: "in_progress" }).where(eq(tasks.id, taskId));
return { tp, proj, sessionId, taskId };
}
async function mcpAgent(sessionId: number, key: string) {
const [a, b] = InMemoryTransport.createLinkedPair();
await createAgentServer(db, { defaultKey: key, sessionId, lockProject: true }).connect(a);
const client = new Client({ name: "mock-agent", version: "0" });
await client.connect(b);
return 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 };
};
}
/** anna's Telegram messages about access requests. */
const annaHeard = async (id: number) => db.select().from(telegramOutbox).where(and(like(telegramOutbox.dedupeKey, `access-request:${id}:%`)));
const stopAll = async (projectId: number) => {
for (const s of await core.listSessions(db, { active: true, projectId })) await runner.stopSession(db, s.id);
};
const said = (tp: TestProject, text: string) => tp.log().some((e) => JSON.stringify(e).includes(text));
describe("Агент запрашивает доступ к сервису", () => {
let s: Awaited<ReturnType<typeof story>>;
let call: Awaited<ReturnType<typeof mcpAgent>>;
let requestId: number;
before(async () => {
s = await story(4);
call = await mcpAgent(s.sessionId, s.proj.key);
});
after(async () => stopAll(s.proj.id));
test("Запрос доходит до владельца", async () => {
const r = await call("request_access", { service: "stripe", purpose: "проверить оплату заказа", mode: "read" });
assert.equal(r.isError, false, r.text);
assert.match(r.text, /Requested: #\d+ Stripe \(read\)/);
requestId = Number(r.text.match(/#(\d+)/)![1]);
const open = await core.ownerAccessRequests(db, anna.id);
const mine = open.find((x) => x.id === requestId)!;
assert.ok(mine, "anna sees it in «Агенты просят доступ»");
assert.equal(mine.service, "Stripe");
assert.equal(mine.taskKey, s.tp.taskKey);
assert.equal(mine.purpose, "проверить оплату заказа");
assert.equal(mine.mode, "read");
const tg = await annaHeard(requestId);
assert.equal(tg.length, 1, "one Telegram message");
const text = stripAsIs(String(tg[0]!.params.text));
assert.match(text, /просит доступ: Stripe — только читать/);
assert.match(text, /Зачем: проверить оплату заказа/);
const markup = JSON.stringify(tg[0]!.params.reply_markup);
assert.ok(markup.includes(`ar:${requestId}:no`), "a «Отказать» button");
assert.ok(markup.includes(`https://forge.mock.test/connections/requests/${requestId}`), "a link to the card");
const [master] = await db.select().from(chatMessages).where(eq(chatMessages.dedupeKey, `master:access-request:${requestId}`));
assert.equal(master?.url, `/connections/requests/${requestId}`, "the master chat has it with the link");
});
test("Повтор не создаёт второй запрос", async () => {
const r = await call("request_access", { service: "Stripe", purpose: "создать возврат", mode: "write" });
assert.match(r.text, /already exists \(#\d+\)/);
const rows = await db.select().from(accessRequests).where(and(eq(accessRequests.projectId, s.proj.id), eq(accessRequests.serviceKey, "stripe")));
assert.equal(rows.length, 1);
assert.equal(rows[0]!.repeats, 1);
assert.equal(rows[0]!.mode, "write", "write widens the request");
assert.equal((await annaHeard(requestId)).length, 1, "no second message");
const list = await call("list_requests");
assert.match(list.text, /Stripe \(write\) — open/);
});
test("Чужой не видит запрос", async () => {
assert.equal(await core.accessRequestForUser(db, boris.id, requestId), null);
await assert.rejects(runner.denyAccessRequestAndTell(db, boris.id, requestId, "нет"), /Запрос не найден/);
await assert.rejects(core.connectAndGrantAccess(db, boris.id, requestId, { secret: "sk_test_mock_boris_123456" }), /Запрос не найден/);
assert.equal((await core.ownerAccessRequests(db, boris.id)).length, 0);
assert.equal((await core.getAccessRequest(db, requestId))!.status, "open");
});
test("Подключить и разрешить", async () => {
const out = await runner.connectAndGrantAccessRequest(db, anna.id, requestId, { secret: "sk_test_mock_STRIPE_250_123456" });
assert.equal(out.request.status, "granted");
assert.equal(out.connection.catalogId, "stripe");
const grant = out.connection.grants.length ? out.connection.grants : (await core.listConnections(db, anna.id)).find((c) => c.id === out.connection.id)!.grants;
assert.equal(grant[0]!.projectId, s.proj.id);
assert.equal(grant[0]!.readMode, "auto");
assert.equal(grant[0]!.writeMode, "auto", "the request asked to write");
await s.tp.waitLog("the live agent is told", (e) => JSON.stringify(e).includes("Доступ выдан"));
const conns = await core.agentConnections(db, s.sessionId);
assert.ok(conns.some((c) => c.catalogId === "stripe" && c.readMode === "auto"), "the agent now has it");
// Asking again for what it has: refused with a hint to call it.
const again = await call("request_access", { service: "stripe", purpose: "ещё раз" });
assert.equal(again.isError, true);
assert.match(again.text, /already have this access: call_connection\("stripe"/);
});
test("Вызов без разрешения", async () => {
const crm = await core.createConnection(db, anna.id, { name: "CRM 250", baseUrl: "https://crm250.example.com/api", secret: "sk_test_mock_CRM_250_123456" });
await core.grantConnection(db, anna.id, crm.id, { projectId: s.proj.id, readMode: "auto", writeMode: "off" });
const r = await call("call_connection", { connection: crm.slug, method: "POST", path: "/orders", body: "{}" });
assert.equal(r.isError, true);
assert.match(r.text, /write_denied/);
assert.match(r.text, /Access requested from the owner \(request #\d+\)/);
const [req] = await db.select().from(accessRequests).where(and(eq(accessRequests.projectId, s.proj.id), eq(accessRequests.serviceKey, "https://crm250.example.com"), eq(accessRequests.status, "open")));
assert.ok(req, "the refusal became a request");
assert.equal(req.mode, "write");
assert.match(req.purpose, /POST \/orders/);
// The owner allows it from the existing connection: write widens the grant, read stays.
await runner.grantAccessRequestFromExisting(db, anna.id, req.id, crm.id);
const g = (await core.listConnections(db, anna.id)).find((c) => c.id === crm.id)!.grants.find((x) => x.projectId === s.proj.id)!;
assert.equal(g.readMode, "auto");
assert.equal(g.writeMode, "auto");
});
test("Ключ внешнего сервиса для агента — запрос доступа, а не секрет проекта", async () => {
const r = await call("declare_needs", { needs: [{ title: "Ключ SendGrid", why: "отправить тестовое письмо", secret: "SENDGRID_API_KEY", use: "agent" }] });
assert.equal(r.isError, false, r.text);
assert.match(r.text, /access request #\d+ \(SendGrid\) sent to the owner/);
assert.equal((await core.productNeeds(db, s.proj.id)).length, 0, "nothing in the product's list");
});
});
describe("Отказ и адреса", () => {
test("Отказ с причиной: остановленный агент получает её с новым запуском", async () => {
const s = await story(3);
const { request } = await core.requestAccess(db, { sessionId: s.sessionId, service: "github", purpose: "прочитать задачи репозитория" });
await stopAll(s.proj.id);
await db.update(sessions).set({ status: "done" }).where(eq(sessions.id, s.sessionId));
const r = await runner.denyAccessRequestAndTell(db, anna.id, request.id, "используйте тестовые данные");
assert.equal(r.status, "denied");
assert.equal(r.reason, "используйте тестовые данные");
await s.tp.waitLog("a new agent got the reason", (e) => JSON.stringify(e).includes("используйте тестовые данные"));
assert.ok(said(s.tp, "отказал в доступе к GitHub"));
assert.equal((await s.tp.task()).status, "in_progress");
await assert.rejects(runner.denyAccessRequestAndTell(db, anna.id, request.id, "ещё раз"), /уже есть решение/);
await stopAll(s.proj.id);
});
test("Адрес внутрь отклоняется", async () => {
const was = process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE;
delete process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE;
try {
const tp = await project({ turns: [] });
const proj = await core.getProject(db, tp.key);
await core.setProjectOwner(db, proj.id, anna.id);
const sess = await core.createSession(db, { projectId: proj.id, taskId: (await tp.task()).id });
for (const host of ["https://127.0.0.1/admin", "localhost", "http://10.0.0.5", "https://[::1]/", "https://intranet.local", "https://user:pw@api.example.com"]) {
await assert.rejects(core.requestAccess(db, { sessionId: sess.id, host, purpose: "x y z" }), (e: Error) => /адрес|Адрес/.test(e.message), host);
}
// A name that resolves inside is refused like the gateway refuses it.
await assert.rejects(core.requestAccess(db, { sessionId: sess.id, host: "https://sneaky.example.com", purpose: "x y z" }, { lookup: async () => ["192.168.1.10"] }), /недоступен/);
const ok = await core.requestAccess(db, { sessionId: sess.id, host: "api.example.com/v1/items?x=1", purpose: "x y z" }, { lookup: async () => ["93.184.216.34"] });
assert.equal(ok.request.host, "https://api.example.com", "only the origin is kept");
assert.equal((await db.select().from(accessRequests).where(eq(accessRequests.projectId, proj.id))).length, 1, "nothing stored for the refused ones");
// An address of a catalog service becomes its card.
const card = await core.requestAccess(db, { sessionId: sess.id, host: "https://api.stripe.com", purpose: "x y z" }, { lookup: async () => ["93.184.216.35"] });
assert.equal(card.request.catalogId, "stripe");
} finally {
if (was !== undefined) process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE = was;
}
});
});