Compare commits

..

No commits in common. "main" and "task/pep-261" have entirely different histories.

10 changed files with 8 additions and 202 deletions

View File

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

View File

@ -1,5 +0,0 @@
# Память: PEP-316
## Грабли
- Гонку двух процессов за базу тест в одном процессе не ловит: `node:sqlite` синхронный, два вызова идут по очереди. Нужен настоящий второй процесс — `packages/testkit/src/mock-db-writer.ts` держит блокировку записи (PEP-313 «починил» гонку тестом в одном процессе, на проде она осталась).
- Транзакция, начатая как читающая (`BEGIN`), получает «database is locked» на первой записи сразу, без ожидания `busy_timeout`. Поэтому `db.transaction` всегда `BEGIN IMMEDIATE` (PEP-316).

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 NOT добавлять новому ни прав, ни операций. Если подходящего подключения нет, владелец SHALL получать ссылку на карточку запроса с шагами подключения, где тоже выбираются права и срок. Нажимать кнопки SHALL только владелец; решение SHALL доходить до агента.
Под сообщением о запросе доступа агента (Telegram и «Агенты просят доступ» в вебе) владелец проекта SHALL видеть «Дать: чтение», «Дать: полные права» и «Отказать». После выбора прав SHALL выбираться срок: 1 час, 1 день, 7 дней или до отзыва; по умолчанию — 1 день. Разрешение SHALL выдаваться проекту запроса на выбранный срок, прежнее разрешение проекта SHALL только расширяться по правам. Если подходящего подключения нет, владелец SHALL получать ссылку на карточку запроса с шагами подключения, где тоже выбираются права и срок. Нажимать кнопки SHALL только владелец; решение SHALL доходить до агента.
#### Scenario: Чтение на 1 день кнопкой в Telegram
- **GIVEN** у «anna» подключение «CRM» и открытый запрос агента проекта «SHOP» к нему
@ -606,12 +606,6 @@ 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, grantState, 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, 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,14 +372,9 @@ 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. 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.
*/
/** Grant to the request's project (any of its agents) on the chosen term. An existing grant only widens its modes. */
async function grantFor(db: Db, userId: number, r: AccessRequestView, connectionId: number, g: Given): Promise<void> {
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;
const [prev] = (await db.select().from(connectionGrants).where(and(eq(connectionGrants.connectionId, connectionId), eq(connectionGrants.projectId, r.projectId)))).filter((x) => x.agentId == null);
await grantConnection(db, userId, connectionId, {
projectId: r.projectId,
agentId: null,

View File

@ -72,7 +72,7 @@ export function summarizeChecks(configured: string[], runs: RunLike[], sha: stri
/** Stores a CI result (one row per project/commit/check). `changed` — the state is new. */
export async function upsertCheckRun(db: Db, project: Project, taskId: number | null, r: CheckReport): Promise<{ run: CheckRun; changed: boolean }> {
// PEP-313: one transaction (it takes the write lock first — PEP-316, db/client.ts). The CI step's report (web) and the
// PEP-313: one transaction (the write lock is taken first). The CI step's report (web) and the
// watchdog's poll write the same check of the same commit at the same moment: read apart from the
// write, both saw no row, the second insert failed on the unique index, and the report with the
// log was lost with a 500 (27.11.2026). In turn each sees what the other stored.

View File

@ -112,13 +112,7 @@ export class SqliteClient {
throw e;
}
};
// PEP-316: every transaction takes the write lock first. Many processes write to this file, and
// SQLite refuses a transaction that began as a reader (plain BEGIN) at its first write — at
// once, busy_timeout does not wait for it — whenever another process is writing: «database is
// locked» (27.11.2026, a CI report lost). drizzle asks for `deferred` unless told otherwise,
// so `deferred` is immediate here too: a transaction waits for its turn and then sees
// what the others stored.
return { deferred: run("BEGIN IMMEDIATE"), immediate: run("BEGIN IMMEDIATE"), exclusive: run("BEGIN EXCLUSIVE") };
return { deferred: run("BEGIN"), immediate: run("BEGIN IMMEDIATE"), exclusive: run("BEGIN EXCLUSIVE") };
}
/** Changes committed by other connections since the last call (PRAGMA data_version). */
dataVersion(): number {

View File

@ -1,14 +0,0 @@
// PEP-316: a second process that holds SQLite's write lock for a while — like the watchdog or an
// agent's hook writing at the moment the web is inside a transaction. Tests only.
// Usage: node mock-db-writer.ts <db file> <hold ms> — prints «locked» once the lock is held.
import { DatabaseSync } from "node:sqlite";
const [file, hold] = process.argv.slice(2);
const db = new DatabaseSync(file!);
db.exec("PRAGMA busy_timeout = 5000");
db.exec("BEGIN IMMEDIATE");
db.exec("UPDATE projects SET name = name");
process.stdout.write("locked\n");
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, Number(hold) || 300);
db.exec("COMMIT");
db.close();

View File

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

View File

@ -1,55 +0,0 @@
// PEP-316: транзакция берёт блокировку записи первой.
// 27.11.2026 11:27, «Ошибки из прода» №22 «database is locked»: отчёт шага проверки (веб) пришёл
// в момент, когда в базу писал другой процесс. Транзакция начиналась как читающая (BEGIN), а
// читающей транзакции SQLite не даёт ждать блокировку записи: отказ сразу, busy_timeout не
// работает. Второй процесс здесь настоящий (mock-db-writer): в одном процессе гонку не поймать.
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { after, describe, test } from "node:test";
import { eq, sql } from "drizzle-orm";
import { core, db, project, teardown } from "./helpers.ts";
const { checkRuns, projects } = await import("@peppa/db");
const WRITER = resolve(fileURLToPath(import.meta.url), "../../src/mock-db-writer.ts");
const HOLD_MS = 600;
after(teardown);
/** Another process takes the write lock and keeps it for `holdMs`; resolves once the lock is held. */
function otherWriter(holdMs: number): Promise<{ done: Promise<number | null> }> {
const child = spawn(process.execPath, [WRITER, process.env.PEPPA_DB!, String(holdMs)], { stdio: ["ignore", "pipe", "inherit"] });
const done = new Promise<number | null>((r) => child.on("exit", (code) => r(code)));
return new Promise((ok, fail) => {
child.stdout.once("data", () => ok({ done }));
child.once("error", fail);
void done.then((code) => fail(new Error(`mock-db-writer exited with ${code} before taking the lock`)));
});
}
describe("PEP-316: транзакция берёт блокировку записи первой", () => {
test("Отчёт проверки приходит, пока пишет другой процесс: отчёт ждёт и сохраняется", async () => {
const p = await core.getProject(db, (await project({ turns: [] })).key);
const sha = "e".repeat(40);
const other = await otherWriter(HOLD_MS);
const t0 = Date.now();
const r = await core.upsertCheckRun(db, p, null, { sha, check: "test", state: "failure", logTail: "✖ упал один тест", source: "report" });
assert.ok(Date.now() - t0 >= HOLD_MS / 3, "the report waited for the other writer instead of failing");
assert.equal(r.run.logTail, "✖ упал один тест", "the log of the report is kept");
assert.equal(await other.done, 0, "the other writer committed");
assert.equal(db.select().from(checkRuns).where(eq(checkRuns.sha, sha)).all().length, 1);
});
test("Любая транзакция «прочитал — записал» ждёт чужую запись, а не падает", async () => {
const p = await core.getProject(db, (await project({ turns: [] })).key);
const other = await otherWriter(HOLD_MS);
const name = db.transaction((tx) => {
const row = tx.select().from(projects).where(eq(projects.id, p.id)).get()!;
tx.update(projects).set({ name: sql`${projects.name} || ' ✓'` }).where(eq(projects.id, p.id)).run();
return row.name;
});
assert.equal(await other.done, 0);
assert.equal((await core.getProject(db, p.key)).name, `${name} ✓`);
});
});