Приёмка PEP-261, 27.11.2026: агенту дали полные права на срок, срок вышел; на новый запрос владелец нажал «Дать: чтение» — проект снова получил чтение и запись, а сообщение говорило «чтение». `grantFor` расширял права по строке прошлой выдачи и не смотрел, действует ли она. На живом сервере выдач ещё не было. - core/access-requests.ts: прошлая выдача расширяет новую, только пока она действует (`grantState` = active); права и операции истёкшей или снятой «без дела» не возвращаются. - Тест access-regrant.test.ts: истёкшие полные права и права, снятые «без дела» → «Дать: чтение» даёт только чтение (оба случая падали до исправления: writeMode auto вместо off); действующая выдача по-прежнему только расширяется. - Спека access-hub: уточнение требования и сценарий «Чтение после истёкших полных прав». Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
100 lines
6.4 KiB
TypeScript
100 lines
6.4 KiB
TypeScript
// PEP-315: права истёкшей или снятой выдачи не возвращаются с новой.
|
||
// 27.11.2026, приёмка PEP-261: агенту дали полные права на срок, срок вышел; на новый запрос владелец
|
||
// нажал «Дать: чтение» — и проект снова получил запись. grantFor расширял права по строке прошлой
|
||
// выдачи и не смотрел, действует ли она. Mock service on 127.0.0.1; no agent process.
|
||
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 { eq } from "drizzle-orm";
|
||
import { core, db, project, runner, teardown } from "./helpers.ts";
|
||
|
||
process.env.PEPPA_SECRET ??= "mock-access-regrant-secret";
|
||
process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE = "1"; // the mock service listens on 127.0.0.1
|
||
const { agents, connectionGrants, sessions } = await import("@peppa/db");
|
||
|
||
const H = 3600_000;
|
||
let mock: Server;
|
||
let origin: string;
|
||
let anna: 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));
|
||
origin = `http://127.0.0.1:${(mock.address() as AddressInfo).port}`;
|
||
anna = await core.upsertUserFromGitea(db, { id: 3151, login: "mock-anna-315" }, { access_token: "a" });
|
||
});
|
||
after(async () => {
|
||
await new Promise<void>((r) => mock.close(() => r()));
|
||
await teardown();
|
||
});
|
||
|
||
let seq = 0;
|
||
/** Anna's project with an isolated agent session (no live process: the decision is only logged). */
|
||
async function setup() {
|
||
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: `Мок-агент 315-${++seq}-${Date.now()}` }).returning();
|
||
await db.update(sessions).set({ agentId: a!.id, container: `peppa-s${s.id}`, status: "done" }).where(eq(sessions.id, s.id));
|
||
return { proj, sessionId: s.id };
|
||
}
|
||
const crm = (n: string) => core.createConnection(db, anna.id, { name: `CRM ${n}`, baseUrl: `${origin}/api`, secret: `sk_mock_315_${n}_abcdef` });
|
||
const ask = (sessionId: number, mode: "read" | "write") => core.requestAccess(db, { sessionId, purpose: "посмотреть заказы клиента", host: origin, mode });
|
||
const grantOf = async (connectionId: number, projectId: number) => (await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, connectionId))).find((g) => g.projectId === projectId && g.agentId == null)!;
|
||
const read = (sessionId: number, connection: number) => core.callConnection(db, { sessionId, connection, method: "GET", path: "/items" });
|
||
const write = (sessionId: number, connection: number) => core.callConnection(db, { sessionId, connection, method: "POST", path: "/items", body: "{}" });
|
||
|
||
describe("PEP-315: прошлая выдача расширяет новую, только пока она действует", () => {
|
||
test("Полные права истекли — «Дать: чтение» даёт только чтение", async () => {
|
||
const { proj, sessionId } = await setup();
|
||
const c = await crm("expired");
|
||
await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, rights: "full", term: "1h", operations: ["POST /items"], now: new Date(Date.now() - 2 * H) });
|
||
assert.deepEqual(await write(sessionId, c.id), { ok: false, reason: "expired" }, "the old grant is over");
|
||
|
||
// The agent asks again, for reading; the owner answers «Дать: чтение», 1 day.
|
||
const { request } = await ask(sessionId, "read");
|
||
const done = await runner.grantAccessRequestByButton(db, anna.id, request.id, { rights: "read", term: "1d" });
|
||
assert.equal(done.status, "granted");
|
||
const g = await grantOf(c.id, proj.id);
|
||
assert.equal(g.readMode, "auto");
|
||
assert.equal(g.writeMode, "off", "the owner gave reading only — writing of the expired grant does not come back");
|
||
assert.deepEqual(g.operations, [], "operations of the expired grant do not come back either");
|
||
assert.ok((await read(sessionId, c.id)).ok, "reading works");
|
||
assert.equal((await write(sessionId, c.id)).ok, false, "writing is refused");
|
||
});
|
||
|
||
test("Права сняты «без дела» — новая выдача их не возвращает", async () => {
|
||
const { proj, sessionId } = await setup();
|
||
const c = await crm("idle");
|
||
await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, rights: "full", term: "forever" });
|
||
const old = await grantOf(c.id, proj.id);
|
||
await db.update(connectionGrants).set({ endedAt: new Date(), endReason: "idle" }).where(eq(connectionGrants.id, old.id));
|
||
assert.deepEqual(await write(sessionId, c.id), { ok: false, reason: "idle_revoked" });
|
||
|
||
const { request } = await ask(sessionId, "read");
|
||
await runner.grantAccessRequestFromExisting(db, anna.id, request.id, c.id, { rights: "read", term: "7d" });
|
||
const g = await grantOf(c.id, proj.id);
|
||
assert.equal(g.writeMode, "off", "reading only");
|
||
assert.equal(g.endedAt, null, "the grant works again");
|
||
assert.equal((await write(sessionId, c.id)).ok, false, "writing is refused");
|
||
});
|
||
|
||
test("Действующая выдача по-прежнему только расширяется", async () => {
|
||
const { proj, sessionId } = await setup();
|
||
const c = await crm("active");
|
||
// The request is open; meanwhile the owner gives full rights in «Подключениях» and then answers the old request with «Дать: чтение».
|
||
const { request } = await ask(sessionId, "read");
|
||
await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, rights: "full", term: "forever" });
|
||
await runner.grantAccessRequestByButton(db, anna.id, request.id, { rights: "read", term: "1d" });
|
||
const g = await grantOf(c.id, proj.id);
|
||
assert.equal(g.writeMode, "auto", "the button does not take away what works now");
|
||
assert.ok((await write(sessionId, c.id)).ok);
|
||
});
|
||
});
|