PEP-315: «Дать: чтение» после истёкших полных прав не возвращает запись
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 51с
peppa/build build: success за 34с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1569с
peppa-ci / ci (pull_request) Successful in 28m8s

Приёмка 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>
This commit is contained in:
peppa-bot 2026-11-27 12:20:45 +05:00
parent fd0db12629
commit cb604d7a41
5 changed files with 119 additions and 5 deletions

4
.peppa/memory/pep-315.md Normal file
View File

@ -0,0 +1,4 @@
# Память: PEP-315
## Грабли
- Строка `connection_grants` остаётся после конца срока и после снятия «без дела»: читая «прошлую выдачу», проверяй `grantState(row, now) === "active"`, иначе вернёшь права, которых уже нет (PEP-315: «Дать: чтение» возвращало запись).

File diff suppressed because one or more lines are too long

View File

@ -580,7 +580,7 @@ FORGE SHALL закреплять ключ SSH-сервера: отпечаток
- **THEN** подключение в FORGE отозвано и токены стёрты
### Requirement: Кнопки выдачи под запросом доступа
Под сообщением о запросе доступа агента (Telegram и «Агенты просят доступ» в вебе) владелец проекта SHALL видеть «Дать: чтение», «Дать: полные права» и «Отказать». После выбора прав SHALL выбираться срок: 1 час, 1 день, 7 дней или до отзыва; по умолчанию — 1 день. Разрешение SHALL выдаваться проекту запроса на выбранный срок, прежнее разрешение проекта SHALL только расширяться по правам. Если подходящего подключения нет, владелец SHALL получать ссылку на карточку запроса с шагами подключения, где тоже выбираются права и срок. Нажимать кнопки SHALL только владелец; решение SHALL доходить до агента.
Под сообщением о запросе доступа агента (Telegram и «Агенты просят доступ» в вебе) владелец проекта SHALL видеть «Дать: чтение», «Дать: полные права» и «Отказать». После выбора прав SHALL выбираться срок: 1 час, 1 день, 7 дней или до отзыва; по умолчанию — 1 день. Разрешение SHALL выдаваться проекту запроса на выбранный срок, действующее разрешение проекта SHALL только расширяться по правам; разрешение, срок которого вышел или которое снято без дела, SHALL NOT добавлять новому ни прав, ни операций. Если подходящего подключения нет, владелец SHALL получать ссылку на карточку запроса с шагами подключения, где тоже выбираются права и срок. Нажимать кнопки SHALL только владелец; решение SHALL доходить до агента.
#### Scenario: Чтение на 1 день кнопкой в Telegram
- **GIVEN** у «anna» подключение «CRM» и открытый запрос агента проекта «SHOP» к нему
@ -606,6 +606,12 @@ FORGE SHALL закреплять ключ SSH-сервера: отпечаток
- **WHEN** «anna» вставляет ключ, выбирает «полные права» и «7 дней» и нажимает «Подключить и разрешить»
- **THEN** проекту выдано чтение и запись «Stripe» на 7 дней
#### Scenario: Чтение после истёкших полных прав
- **GIVEN** проекту «SHOP» были выданы полные права «CRM» на 1 час, срок вышел
- **WHEN** агент просит доступ снова, и «anna» нажимает «Дать: чтение», затем «1 день»
- **THEN** проекту выдано только чтение «CRM» на 1 день
- **AND** запрос агента на изменение данных получает отказ
### Requirement: Истёкший доступ — новый запрос
Отказ шлюза из-за истёкшего срока или снятого без дела разрешения SHALL подсказывать агенту попросить доступ снова через `request_access` с названием сервиса.

View File

@ -10,7 +10,7 @@ import { lookup as dnsLookup } from "node:dns/promises";
import { logEvent } from "./audit.ts";
import { addMasterMessage } from "./chats.ts";
import { catalogService, CONNECTION_CATALOG, type CatalogService } from "./connection-catalog.ts";
import { agentConnections, createConnection, DEFAULT_GRANT_TERM, GRANT_RIGHTS, GRANT_TERM_TEXT, GRANT_TERMS, grantConnection, isBlockedAddress, isGrantTerm, listConnections, parseBaseUrl, type ConnectionInput, type ConnectionView, type GrantMode, type GrantRights, type GrantTerm } from "./connections.ts";
import { agentConnections, createConnection, DEFAULT_GRANT_TERM, GRANT_RIGHTS, GRANT_TERM_TEXT, GRANT_TERMS, grantConnection, grantState, isBlockedAddress, isGrantTerm, listConnections, parseBaseUrl, type ConnectionInput, type ConnectionView, type GrantMode, type GrantRights, type GrantTerm } from "./connections.ts";
import { PeppaError } from "./errors.ts";
import { deliverToUser } from "./notifications.ts";
import { guardUntrusted } from "./untrusted.ts";
@ -372,9 +372,14 @@ export interface AccessGrantChoice {
type Given = { rights: GrantRights; term: GrantTerm };
const given = (r: AccessRequestView, c: AccessGrantChoice = {}): Given => ({ rights: c.rights === "full" || c.rights === "read" ? c.rights : r.mode === "write" ? "full" : "read", term: isGrantTerm(c.term) ? c.term : DEFAULT_GRANT_TERM });
/** Grant to the request's project (any of its agents) on the chosen term. An existing grant only widens its modes. */
/**
* Grant to the request's project (any of its agents) on the chosen term. A grant that works now only
* widens its modes. PEP-315: a grant whose term is over or that was revoked for no use gives nothing
* to the new one — «Дать: чтение» after expired full rights is reading only.
*/
async function grantFor(db: Db, userId: number, r: AccessRequestView, connectionId: number, g: Given): Promise<void> {
const [prev] = (await db.select().from(connectionGrants).where(and(eq(connectionGrants.connectionId, connectionId), eq(connectionGrants.projectId, r.projectId)))).filter((x) => x.agentId == null);
const [row] = (await db.select().from(connectionGrants).where(and(eq(connectionGrants.connectionId, connectionId), eq(connectionGrants.projectId, r.projectId)))).filter((x) => x.agentId == null);
const prev = row && grantState(row, new Date()) === "active" ? row : undefined;
await grantConnection(db, userId, connectionId, {
projectId: r.projectId,
agentId: null,

View File

@ -0,0 +1,99 @@
// 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);
});
});