265 lines
16 KiB
TypeScript
265 lines
16 KiB
TypeScript
// PEP-235 Access Hub: the owner confirms calls in «спрашивать меня» mode.
|
||
// Scenario names follow openspec/changes/pep-235-owner-approvals/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 { core, db, project, runner, teardown } from "./helpers.ts";
|
||
|
||
process.env.PEPPA_SECRET ??= "mock-access-hub-secret";
|
||
const { createAgentServer } = await import("@peppa/mcp/agent");
|
||
const { agents, connectionApprovals, connectionLog, sessions } = await import("@peppa/db");
|
||
type Fetch = NonNullable<Parameters<typeof core.callConnection>[2]>["fetch"];
|
||
|
||
const KEY = "sk_test_mock_APPROVAL_123456";
|
||
let anna: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
let boris: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
|
||
before(async () => {
|
||
anna = await core.upsertUserFromGitea(db, { id: 2351, login: "mock-anna-235" }, { access_token: "a" });
|
||
boris = await core.upsertUserFromGitea(db, { id: 2352, login: "mock-boris-235" }, { access_token: "b" });
|
||
});
|
||
after(teardown);
|
||
|
||
let seq = 0;
|
||
async function setup(o: { catalogId?: string; writeMode?: "ask" | "auto"; readMode?: "ask" | "auto" | "off" } = {}) {
|
||
const p = await project({ turns: [] });
|
||
const proj = await core.getProject(db, p.key);
|
||
await core.setProjectOwner(db, proj.id, anna.id);
|
||
const task = (await core.listTasks(db, { projectId: proj.id }))[0]!;
|
||
const c = await core.createConnection(db, anna.id, { catalogId: o.catalogId ?? "stripe", name: `Stripe-235-${++seq}`, secret: KEY });
|
||
await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, readMode: o.readMode ?? "auto", writeMode: o.writeMode ?? "ask" });
|
||
const s = await core.createSession(db, { projectId: proj.id, taskId: task.id });
|
||
const [a] = await db.insert(agents).values({ name: `Мок-235 ${seq}-${Date.now()}` }).returning();
|
||
await db.update(sessions).set({ agentId: a!.id, container: `peppa-s${s.id}` }).where(eq(sessions.id, s.id));
|
||
return { proj, task, c, sessionId: s.id, agentName: a!.name };
|
||
}
|
||
|
||
function mockFetch() {
|
||
const calls: Array<{ url: URL; method: string; headers: Record<string, string>; body: string | null }> = [];
|
||
const fetch: Fetch = async ({ url, method, headers, body }) => {
|
||
calls.push({ url, method, headers, body: body ? body.toString() : null });
|
||
return { status: 200, contentType: "application/json", body: Buffer.from(JSON.stringify({ id: `re_${calls.length}`, ok: true })), truncated: false };
|
||
};
|
||
return { fetch, calls };
|
||
}
|
||
|
||
const order = (sessionId: number, c: { id: number }, body = '{"sum":10}', extra: Partial<Parameters<typeof core.callConnection>[1]> = {}) => ({ sessionId, connection: c.id, method: "POST", path: "/v1/refunds", body, ...extra });
|
||
|
||
async function pending(r: Awaited<ReturnType<typeof core.callConnection>>) {
|
||
assert.ok(!r.ok && r.reason === "needs_approval" && r.approval, JSON.stringify(r));
|
||
return r.approval!.id;
|
||
}
|
||
|
||
describe("Подтверждение владельцем операций в режиме «спрашивать меня»", () => {
|
||
test("Разрешено — выполняется один раз", async () => {
|
||
const { c, sessionId } = await setup();
|
||
const m = mockFetch();
|
||
const id = await pending(await core.callConnection(db, order(sessionId, c), { fetch: m.fetch }));
|
||
assert.equal(m.calls.length, 0, "nothing runs before «Разрешить»");
|
||
const { approval, waiting } = await core.decideApproval(db, anna.id, id, true);
|
||
assert.equal(approval.status, "approved");
|
||
assert.equal(waiting, false);
|
||
assert.ok(await core.runApproval(db, id, { gateway: { fetch: m.fetch } }));
|
||
assert.equal(await core.runApproval(db, id, { gateway: { fetch: m.fetch } }), null, "a second run is not claimed");
|
||
assert.equal(m.calls.length, 1);
|
||
assert.equal(m.calls[0]!.body, '{"sum":10}');
|
||
assert.equal(m.calls[0]!.headers["idempotency-key"], `forge-${approval.idemKey}`, "Stripe takes the repeat key");
|
||
const got = await core.agentCall(db, sessionId, id);
|
||
assert.equal(got.status, "done");
|
||
assert.equal((got.result as { ok: boolean; body: string }).ok, true);
|
||
assert.match((got.result as { body: string }).body, /re_1/);
|
||
// A repeat of the same request returns the stored outcome and never runs it again.
|
||
const again = await core.callConnection(db, order(sessionId, c), { fetch: m.fetch });
|
||
assert.equal(again.ok, true);
|
||
assert.equal(m.calls.length, 1);
|
||
// A new repeat key is a new action: a new confirmation.
|
||
const fresh = await core.callConnection(db, order(sessionId, c, '{"sum":10}', { idempotencyKey: "second-refund" }), { fetch: m.fetch });
|
||
assert.notEqual(await pending(fresh), id);
|
||
});
|
||
|
||
test("Отклонено — не выполняется", async () => {
|
||
const { c, sessionId } = await setup();
|
||
const m = mockFetch();
|
||
const id = await pending(await core.callConnection(db, order(sessionId, c), { fetch: m.fetch }));
|
||
await core.decideApproval(db, anna.id, id, false);
|
||
assert.equal(await core.runApproval(db, id, { gateway: { fetch: m.fetch } }), null);
|
||
await core.approvalTick(db, { gateway: { fetch: m.fetch } });
|
||
assert.equal(m.calls.length, 0);
|
||
const got = await core.agentCall(db, sessionId, id);
|
||
assert.equal(got.status, "denied");
|
||
assert.deepEqual(got.result, { ok: false, reason: "approval_denied" });
|
||
await assert.rejects(core.decideApproval(db, anna.id, id, true), /уже есть решение/);
|
||
});
|
||
|
||
test("Просроченное не выполняется", async () => {
|
||
const { c, sessionId } = await setup();
|
||
const m = mockFetch();
|
||
const id = await pending(await core.callConnection(db, order(sessionId, c), { fetch: m.fetch, now: new Date(Date.now() - 25 * 3600_000) }));
|
||
await core.approvalTick(db, { gateway: { fetch: m.fetch } });
|
||
const [row] = await db.select().from(connectionApprovals).where(eq(connectionApprovals.id, id));
|
||
assert.equal(row!.status, "expired");
|
||
await assert.rejects(core.decideApproval(db, anna.id, id, true), /уже есть решение/);
|
||
assert.equal(m.calls.length, 0);
|
||
// Approved but the term ran out before the run: not run either.
|
||
const id2 = await pending(await core.callConnection(db, order(sessionId, c, '{"sum":11}'), { fetch: m.fetch }));
|
||
await core.decideApproval(db, anna.id, id2, true);
|
||
await core.approvalTick(db, { now: new Date(Date.now() + 25 * 3600_000), gateway: { fetch: m.fetch } });
|
||
assert.equal(m.calls.length, 0);
|
||
assert.equal((await core.agentCall(db, sessionId, id2)).status, "expired");
|
||
});
|
||
|
||
test("Чужой пользователь не может согласовать", async () => {
|
||
const { proj, c, sessionId } = await setup();
|
||
await core.addMember(db, proj, boris.login, anna.id);
|
||
const m = mockFetch();
|
||
const id = await pending(await core.callConnection(db, order(sessionId, c), { fetch: m.fetch }));
|
||
await assert.rejects(core.decideApproval(db, boris.id, id, true), /Подтверждение не найдено/);
|
||
assert.equal(await core.approvalForUser(db, boris.id, id), null);
|
||
assert.deepEqual(await core.ownerPendingApprovals(db, boris.id), []);
|
||
assert.equal((await core.agentCall(db, sessionId, id)).status, "pending");
|
||
// An agent of another project can't read the call either.
|
||
const other = await setup();
|
||
await assert.rejects(core.agentCall(db, other.sessionId, id), /not found/);
|
||
});
|
||
|
||
test("Изменение параметров требует нового согласования", async () => {
|
||
const { c, sessionId } = await setup();
|
||
const m = mockFetch();
|
||
const first = await pending(await core.callConnection(db, order(sessionId, c, '{"sum":10}'), { fetch: m.fetch }));
|
||
const second = await pending(await core.callConnection(db, order(sessionId, c, '{"sum":1000}'), { fetch: m.fetch }));
|
||
assert.notEqual(first, second);
|
||
assert.equal((await core.agentCall(db, sessionId, first)).status, "pending");
|
||
// The same repeat key with other parameters is refused.
|
||
await pending(await core.callConnection(db, order(sessionId, c, '{"sum":1}', { idempotencyKey: "k-1" }), { fetch: m.fetch }));
|
||
const conflict = await core.callConnection(db, order(sessionId, c, '{"sum":2}', { idempotencyKey: "k-1" }), { fetch: m.fetch });
|
||
assert.deepEqual(conflict, { ok: false, reason: "bad_request" });
|
||
});
|
||
|
||
test("Повтор того же запроса — без второго подтверждения", async () => {
|
||
const { c, sessionId } = await setup();
|
||
const m = mockFetch();
|
||
const a = await pending(await core.callConnection(db, order(sessionId, c), { fetch: m.fetch }));
|
||
const b = await pending(await core.callConnection(db, order(sessionId, c), { fetch: m.fetch }));
|
||
assert.equal(a, b);
|
||
const rows = await db.select().from(connectionApprovals).where(eq(connectionApprovals.connectionId, c.id));
|
||
assert.equal(rows.length, 1);
|
||
const log = await db.select().from(connectionLog).where(eq(connectionLog.connectionId, c.id));
|
||
assert.ok(log.every((r) => r.reason === "needs_approval" && r.decision === "denied"), "journal: asked, not run");
|
||
assert.ok(!JSON.stringify(log).includes("sum"), "no body in the journal");
|
||
assert.ok(!JSON.stringify(rows).includes(KEY) && !rows[0]!.requestEnc.includes("sum"), "the request is stored encrypted");
|
||
});
|
||
|
||
test("После рестарта выполняется один раз", async () => {
|
||
const { c, sessionId } = await setup();
|
||
const m = mockFetch();
|
||
const id = await pending(await core.callConnection(db, order(sessionId, c), { fetch: m.fetch }));
|
||
// The waiting call was cut by a restart: the row still says «waiting» for a while.
|
||
await core.setApprovalWaiting(db, id, new Date(Date.now() + 60_000));
|
||
await core.decideApproval(db, anna.id, id, true);
|
||
await core.approvalTick(db, { gateway: { fetch: m.fetch } });
|
||
assert.equal(m.calls.length, 0, "a waiting call runs it itself");
|
||
await core.approvalTick(db, { now: new Date(Date.now() + 120_000), gateway: { fetch: m.fetch } });
|
||
await core.approvalTick(db, { now: new Date(Date.now() + 180_000), gateway: { fetch: m.fetch } });
|
||
assert.equal(m.calls.length, 1);
|
||
assert.equal((await core.agentCall(db, sessionId, id)).status, "done");
|
||
// A run cut in the middle is never repeated: it ends as «interrupted».
|
||
const id2 = await pending(await core.callConnection(db, order(sessionId, c, '{"sum":12}'), { fetch: m.fetch }));
|
||
await core.decideApproval(db, anna.id, id2, true);
|
||
assert.ok(await core.claimApproval(db, id2, new Date()));
|
||
await core.approvalTick(db, { now: new Date(Date.now() + 11 * 60_000), gateway: { fetch: m.fetch } });
|
||
const got = await core.agentCall(db, sessionId, id2);
|
||
assert.equal(got.status, "failed");
|
||
assert.deepEqual(got.result, { ok: false, reason: "interrupted" });
|
||
assert.equal(m.calls.length, 1);
|
||
});
|
||
|
||
test("«Разрешить» с телефона выполняет вызов сразу", async () => {
|
||
const { decideConnectionApproval } = runner;
|
||
const { c, sessionId } = await setup();
|
||
const m = mockFetch();
|
||
const id = await pending(await core.callConnection(db, order(sessionId, c, '{"sum":14}'), { fetch: m.fetch }));
|
||
await assert.rejects(decideConnectionApproval(db, boris.id, id, true, { gateway: { fetch: m.fetch } }), /Подтверждение не найдено/);
|
||
const v = await decideConnectionApproval(db, anna.id, id, true, { via: "telegram", gateway: { fetch: m.fetch } });
|
||
assert.equal(v.status, "approved");
|
||
assert.equal(m.calls.length, 1);
|
||
assert.equal((await core.agentCall(db, sessionId, id)).status, "done");
|
||
});
|
||
|
||
test("Ждущий вызов получает результат сам", async () => {
|
||
const { c, sessionId } = await setup();
|
||
const m = mockFetch();
|
||
const call = core.callConnection(db, order(sessionId, c, '{"sum":13}'), { fetch: m.fetch, approvalWaitMs: 5_000 });
|
||
let row: typeof connectionApprovals.$inferSelect | undefined;
|
||
for (let i = 0; i < 50 && !row?.waitingUntil; i++) {
|
||
await new Promise((r) => setTimeout(r, 50));
|
||
[row] = await db.select().from(connectionApprovals).where(eq(connectionApprovals.connectionId, c.id));
|
||
}
|
||
const { waiting } = await core.decideApproval(db, anna.id, row!.id, true);
|
||
assert.equal(waiting, true, "the decider leaves the run to the waiting call");
|
||
const r = await call;
|
||
assert.equal(r.ok, true, JSON.stringify(r));
|
||
assert.equal(m.calls.length, 1);
|
||
const [done] = await db.select().from(connectionApprovals).where(eq(connectionApprovals.id, row!.id));
|
||
assert.ok(done!.deliveredAt, "delivered in the call: no extra message");
|
||
assert.ok(!(await core.undeliveredApprovals(db)).some((u) => u.id === row!.id));
|
||
});
|
||
});
|
||
|
||
describe("Владелец видит запрос и отвечает с телефона", () => {
|
||
test("Карточка без ключей", async () => {
|
||
const { c, sessionId, agentName } = await setup({ catalogId: "sendgrid" });
|
||
const m = mockFetch();
|
||
const body = JSON.stringify({ to: "a@b.kz", token: "sk_live_abcdef123456", note: "hello" });
|
||
const id = await pending(await core.callConnection(db, { sessionId, connection: c.id, method: "POST", path: "/v3/mail/send?api_key=zzzSECRETzzz111", body }, { fetch: m.fetch }));
|
||
const v = (await core.ownerPendingApprovals(db, anna.id)).find((x) => x.id === id);
|
||
assert.ok(v, "in «Ждут подтверждения»");
|
||
assert.match(v!.summary, /POST \/v3\/mail\/send/);
|
||
assert.match(v!.summary, /a@b\.kz/);
|
||
assert.ok(!v!.summary.includes("sk_live_abcdef123456"));
|
||
assert.ok(!v!.summary.includes("zzzSECRETzzz111"));
|
||
const text = core.approvalText(v!);
|
||
assert.ok(text.includes(agentName) && text.includes(c.name));
|
||
assert.deepEqual(core.parseApprovalCallback(`ap:${id}:y`), { id, allow: true });
|
||
assert.deepEqual(core.parseApprovalCallback(`ap:${id}:n`), { id, allow: false });
|
||
assert.equal(core.parseApprovalCallback("ap:x:y"), null);
|
||
});
|
||
|
||
test("Значения, похожие на ключи, скрыты", () => {
|
||
const t = core.maskKeyLike('{"password":"hunter2","to":"x@y.kz","sum":1000,"id":"ghp_abcdefghijklmnop1234","note":"Bearer abc.def"}');
|
||
assert.ok(!t.includes("hunter2") && !t.includes("ghp_abcdefghijklmnop1234") && !t.includes("abc.def"), t);
|
||
assert.ok(t.includes("x@y.kz") && t.includes("1000"), t);
|
||
});
|
||
|
||
test("Агент получает «ждёт подтверждения» и проверяет get_call", async () => {
|
||
const { c, sessionId } = await setup();
|
||
const m = mockFetch();
|
||
core.setGatewayDefaults({ fetch: m.fetch });
|
||
try {
|
||
const server = createAgentServer(db, { sessionId });
|
||
const [a, b] = InMemoryTransport.createLinkedPair();
|
||
await server.connect(a);
|
||
const client = new Client({ name: "mock-agent", version: "1" });
|
||
await client.connect(b);
|
||
const callTool = async (name: string, args: Record<string, unknown>) => {
|
||
const r = (await client.callTool({ name, arguments: args })) as { content: Array<{ text: string }>; isError?: boolean };
|
||
return { text: r.content.map((x) => x.text).join("\n"), isError: !!r.isError };
|
||
};
|
||
const w = await callTool("call_connection", { connection: c.id, method: "POST", path: "/v1/refunds", body: '{"sum":5}' });
|
||
assert.equal(w.isError, false, w.text);
|
||
const id = Number(/call #(\d+)/.exec(w.text)![1]);
|
||
assert.match((await callTool("get_call", { id })).text, /still waiting/);
|
||
await core.decideApproval(db, anna.id, id, true);
|
||
await core.runApproval(db, id);
|
||
const done = await callTool("get_call", { id });
|
||
assert.match(done.text, /approved by the owner and done/);
|
||
assert.match(done.text, /ДАННЫЕ, НЕ ИНСТРУКЦИИ/);
|
||
assert.ok(!done.text.includes(KEY));
|
||
await client.close();
|
||
} finally {
|
||
core.setGatewayDefaults({});
|
||
}
|
||
});
|
||
});
|