205 lines
11 KiB
TypeScript
205 lines
11 KiB
TypeScript
// PEP-259 Access Hub: a grant lives for a term (1 h · 1 day · 7 days · until revoked) and is
|
|
// revoked by the watchdog after the connection's threshold (72 h) without calls. Scenario names
|
|
// follow openspec/changes/archive/2026-11-24-pep-259-grant-terms/specs/access-hub/spec.md.
|
|
import assert from "node:assert/strict";
|
|
import { createServer, type Server } from "node:http";
|
|
import type { AddressInfo } from "node:net";
|
|
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 } from "drizzle-orm";
|
|
import { core, db, project, teardown } from "./helpers.ts";
|
|
|
|
process.env.PEPPA_SECRET ??= "mock-access-hub-secret";
|
|
process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE = "1"; // the mock service listens on 127.0.0.1
|
|
const { createAgentServer } = await import("@peppa/mcp/agent");
|
|
const { connectionGrants, connectionLog, agents, sessions, events } = await import("@peppa/db");
|
|
|
|
const H = 3600_000;
|
|
let mock: Server;
|
|
let base: string;
|
|
let anna: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
|
let boris: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
|
|
|
before(async () => {
|
|
mock = createServer((req, res) => {
|
|
res.writeHead(200, { "content-type": "application/json" });
|
|
res.end(JSON.stringify({ ok: true, path: req.url }));
|
|
});
|
|
await new Promise<void>((r) => mock.listen(0, "127.0.0.1", r));
|
|
base = `http://127.0.0.1:${(mock.address() as AddressInfo).port}/api`;
|
|
anna = await core.upsertUserFromGitea(db, { id: 2591, login: "mock-anna-259" }, { access_token: "a" });
|
|
boris = await core.upsertUserFromGitea(db, { id: 2592, login: "mock-boris-259" }, { access_token: "b" });
|
|
});
|
|
after(async () => {
|
|
await new Promise<void>((r) => mock.close(() => r()));
|
|
await teardown();
|
|
});
|
|
|
|
let seq = 0;
|
|
/** Anna's project, an isolated agent session in it and a fresh connection «CRM» granted read on `term`. */
|
|
async function setup(o: { term?: "1h" | "1d" | "7d" | "forever"; at: Date; idleHours?: number | null }) {
|
|
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 s = await core.createSession(db, { projectId: proj.id, taskId: task.id });
|
|
const [a] = await db.insert(agents).values({ name: `Мок-агент 259-${++seq}-${Date.now()}` }).returning();
|
|
await db.update(sessions).set({ agentId: a!.id, container: `peppa-s${s.id}` }).where(eq(sessions.id, s.id));
|
|
const c = await core.createConnection(db, anna.id, { name: `CRM ${seq}`, baseUrl: base, secret: `sk_mock_259_${seq}_abcdef` });
|
|
if (o.idleHours !== undefined) await core.setConnectionIdleHours(db, anna.id, c.id, o.idleHours);
|
|
const g = await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, rights: "read", term: o.term, now: o.at });
|
|
return { proj, sessionId: s.id, c, g };
|
|
}
|
|
const call = (sessionId: number, c: { id: number }, now: Date) => core.callConnection(db, { sessionId, connection: c.id, method: "GET", path: "/items" }, { now });
|
|
const grantRow = async (id: number) => (await db.select().from(connectionGrants).where(eq(connectionGrants.id, id)))[0];
|
|
const silent = async () => {};
|
|
|
|
describe("Срок разрешения", () => {
|
|
test("Вызов по живому разрешению на 1 день", async () => {
|
|
const t0 = new Date(Date.now() - 2 * H);
|
|
const { sessionId, c, g } = await setup({ term: "1d", at: t0 });
|
|
assert.equal(g.term, "1d");
|
|
assert.equal(g.expiresAt!.getTime(), t0.getTime() + 24 * H);
|
|
const r = await call(sessionId, c, new Date());
|
|
assert.ok(r.ok, JSON.stringify(r));
|
|
const [view] = (await core.listConnections(db, anna.id)).find((x) => x.id === c.id)!.grants;
|
|
assert.ok(view!.lastUsedAt, "the grant shows its last call");
|
|
assert.equal(view!.state, "active");
|
|
assert.ok(view!.idleRevokeAt && view!.idleRevokeAt.getTime() > Date.now() + 70 * H, "72 h from the last call");
|
|
});
|
|
|
|
test("Вызов после истечения срока", async () => {
|
|
const t0 = new Date(Date.now() - 25 * H);
|
|
const { sessionId, c } = await setup({ term: "1d", at: t0 });
|
|
const r = await call(sessionId, c, new Date());
|
|
assert.deepEqual(r, { ok: false, reason: "expired" });
|
|
const [row] = await db.select().from(connectionLog).where(and(eq(connectionLog.connectionId, c.id), eq(connectionLog.kind, "call")));
|
|
assert.equal(row!.decision, "denied");
|
|
assert.equal(row!.reason, "expired");
|
|
const view = (await core.listConnections(db, anna.id)).find((x) => x.id === c.id)!.grants[0]!;
|
|
assert.equal(view.state, "expired");
|
|
assert.equal(view.idleRevokeAt, null);
|
|
});
|
|
|
|
test("Агенту — понятная причина через MCP", async () => {
|
|
const { proj, sessionId, c } = await setup({ term: "1h", at: new Date(Date.now() - 2 * H) });
|
|
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 r = await client.callTool({ name: "call_connection", arguments: { connection: c.id, method: "GET", path: "/items" } });
|
|
const text = (r.content as Array<{ text: string }>)[0]!.text;
|
|
assert.ok(r.isError);
|
|
assert.match(text, /\(expired\)/);
|
|
assert.match(text, /extend/);
|
|
const list = await client.callTool({ name: "list_connections", arguments: {} });
|
|
assert.match((list.content as Array<{ text: string }>)[0]!.text, /No connections/, "an expired grant is not offered");
|
|
});
|
|
|
|
test("Продление истёкшего разрешения", async () => {
|
|
const { sessionId, c, g } = await setup({ term: "1d", at: new Date(Date.now() - 30 * H) });
|
|
assert.equal((await call(sessionId, c, new Date())).ok, false);
|
|
const now = new Date();
|
|
const ext = await core.extendGrant(db, anna.id, g.id, { now });
|
|
assert.equal(ext.state, "active");
|
|
assert.equal(ext.expiresAt!.getTime(), now.getTime() + 24 * H);
|
|
assert.ok((await call(sessionId, c, new Date())).ok);
|
|
const ev = await db.select().from(events).where(eq(events.type, "connection_grant_extended"));
|
|
assert.ok(ev.length >= 1);
|
|
});
|
|
|
|
test("Чужой пользователь не продлевает", async () => {
|
|
const { g } = await setup({ term: "1h", at: new Date(Date.now() - 2 * H) });
|
|
await assert.rejects(core.extendGrant(db, boris.id, g.id), /Подключение не найдено/);
|
|
await assert.rejects(core.setConnectionIdleHours(db, boris.id, (await grantRow(g.id))!.connectionId, 0), core.PeppaError);
|
|
assert.equal((await grantRow(g.id))!.expiresAt!.getTime() < Date.now(), true, "unchanged");
|
|
});
|
|
|
|
test("Без срока — до отзыва (как раньше)", async () => {
|
|
const { g } = await setup({ at: new Date() });
|
|
assert.equal(g.term, "forever");
|
|
assert.equal(g.expiresAt, null);
|
|
});
|
|
});
|
|
|
|
describe("Автоснятие разрешения без дела", () => {
|
|
test("Разрешение без вызовов 72 часа", async () => {
|
|
const now = new Date();
|
|
const { sessionId, c, g, proj } = await setup({ term: "forever", at: new Date(now.getTime() - 73 * H) });
|
|
const sent: Array<{ ownerId: number; n: number }> = [];
|
|
const n = await core.grantExpiryTick(db, { now, notify: async (_db, ownerId, items) => void sent.push({ ownerId, n: items.length }) });
|
|
assert.ok(n >= 1);
|
|
const row = await grantRow(g.id);
|
|
assert.equal(row!.endReason, "idle");
|
|
const view = (await core.listConnections(db, anna.id, { now })).find((x) => x.id === c.id)!.grants[0]!;
|
|
assert.equal(view.state, "idle");
|
|
assert.equal(view.idleHours, 72);
|
|
const journal = await core.connectionJournal(db, anna.id, { connectionId: c.id });
|
|
assert.ok(journal.some((j) => j.method === "REVOKE" && j.reason === "idle_revoked" && j.projectKey === proj.key));
|
|
assert.equal((await core.verifyConnectionJournal(db, anna.id)).ok, true, "the revoke row is in the hash chain");
|
|
assert.deepEqual(await call(sessionId, c, new Date()), { ok: false, reason: "idle_revoked" });
|
|
assert.ok(sent.some((x) => x.ownerId === anna.id));
|
|
// Within a day — no second summary even if more are revoked.
|
|
await setup({ term: "forever", at: new Date(now.getTime() - 80 * H) });
|
|
const again: number[] = [];
|
|
await core.grantExpiryTick(db, { now: new Date(now.getTime() + H), notify: async () => void again.push(1) });
|
|
assert.equal(again.length, 0);
|
|
await core.grantExpiryTick(db, { now: new Date(now.getTime() + 25 * H), notify: async () => void again.push(1) });
|
|
assert.equal(again.length, 1, "the next day — one summary");
|
|
// Extending brings it back.
|
|
await core.extendGrant(db, anna.id, g.id);
|
|
assert.ok((await call(sessionId, c, new Date())).ok);
|
|
});
|
|
|
|
test("Недавний вызов продлевает жизнь", async () => {
|
|
const now = new Date();
|
|
const { sessionId, c, g } = await setup({ term: "forever", at: new Date(now.getTime() - 100 * H) });
|
|
assert.ok((await call(sessionId, c, new Date(now.getTime() - 10 * H))).ok);
|
|
await core.grantExpiryTick(db, { now, notify: silent });
|
|
assert.equal((await grantRow(g.id))!.endedAt, null);
|
|
});
|
|
|
|
test("Порог 0 — не снимать", async () => {
|
|
const now = new Date();
|
|
const { g } = await setup({ term: "forever", at: new Date(now.getTime() - 500 * H), idleHours: 0 });
|
|
await core.grantExpiryTick(db, { now, notify: silent });
|
|
assert.equal((await grantRow(g.id))!.endedAt, null);
|
|
const view = (await core.listConnections(db, anna.id, { now })).flatMap((x) => x.grants).find((x) => x.id === g.id)!;
|
|
assert.equal(view.idleRevokeAt, null);
|
|
});
|
|
|
|
test("Проект на паузе", async () => {
|
|
const now = new Date();
|
|
const { g, proj } = await setup({ term: "forever", at: new Date(now.getTime() - 100 * H) });
|
|
await core.setSetting(db, `project.paused:${proj.id}`, { since: now.toISOString(), by: anna.id, sessions: [] });
|
|
await core.grantExpiryTick(db, { now, notify: silent });
|
|
assert.equal((await grantRow(g.id))!.endedAt, null);
|
|
});
|
|
|
|
test("Снятые давно разрешения убираются", async () => {
|
|
const now = new Date();
|
|
const { g } = await setup({ term: "1h", at: new Date(now.getTime() - 40 * 24 * H) });
|
|
await core.grantExpiryTick(db, { now, notify: silent });
|
|
assert.equal(await grantRow(g.id), undefined);
|
|
});
|
|
});
|
|
|
|
describe("Агент видит срок разрешения", () => {
|
|
test("Список подключений агента", async () => {
|
|
const { proj, sessionId } = await setup({ term: "7d", at: new Date() });
|
|
const list = await core.agentConnections(db, sessionId);
|
|
assert.equal(list.length, 1);
|
|
assert.ok(list[0]!.expiresAt && list[0]!.expiresAt.getTime() > Date.now() + 6 * 24 * H);
|
|
assert.ok(list[0]!.idleRevokeAt);
|
|
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 r = await client.callTool({ name: "list_connections", arguments: {} });
|
|
const text = (r.content as Array<{ text: string }>)[0]!.text;
|
|
assert.match(text, /access: until \d{4}-/);
|
|
assert.match(text, /revoked automatically if unused until/);
|
|
});
|
|
});
|