From 79d75e52347cd6039d3246a55940175e5ddbd087 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Tue, 17 Nov 2026 12:59:53 +0500 Subject: [PATCH] PEP-191: archive change Co-Authored-By: Claude Sonnet 5.5 --- AGENTS.md | 1 + .../changes/pep-191-protect-main/design.md | 7 + .../changes/pep-191-protect-main/proposal.md | 9 ++ .../specs/branch-protection/spec.md | 28 ++++ .../changes/pep-191-protect-main/tasks.md | 5 + packages/cli/src/index.ts | 21 ++- packages/core/src/gitea.ts | 39 ++++++ packages/runner/src/branch-protection.ts | 84 ++++++++++++ packages/runner/src/ci.ts | 4 + packages/runner/src/index.ts | 1 + packages/runner/src/provision.ts | 12 ++ packages/runner/src/transfer.ts | 3 + packages/runner/src/watchdog.ts | 3 + packages/shared/src/i18n/en/runner.ts | 2 + packages/shared/src/i18n/kk/runner.ts | 2 + packages/testkit/src/mock-gitea.ts | 53 ++++++++ .../testkit/test/branch-protection.test.ts | 125 ++++++++++++++++++ packages/testkit/test/helpers.ts | 1 + 18 files changed, 399 insertions(+), 1 deletion(-) create mode 100644 openspec/changes/pep-191-protect-main/design.md create mode 100644 openspec/changes/pep-191-protect-main/proposal.md create mode 100644 openspec/changes/pep-191-protect-main/specs/branch-protection/spec.md create mode 100644 openspec/changes/pep-191-protect-main/tasks.md create mode 100644 packages/runner/src/branch-protection.ts create mode 100644 packages/testkit/test/branch-protection.test.ts diff --git a/AGENTS.md b/AGENTS.md index 186fe185..799005d6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -73,6 +73,7 @@ - **Свой Telegram-бот (PEP-85)**: `users.telegram_bot_token_enc` (в `encryptedColumns`) + `telegram_bot_username` (миграция 0016). core/telegram.ts: `verifyBotToken`, `setUserBot`/`clearUserBot`, `userBots`; `acceptPairing(…, { botUserId })` — свой бот привязывает только владельца, общий не привязывает того, у кого есть свой; `getOffset`/`claimUpdate` принимают `botUserId` (ключ обновления `userId·2^36 + update_id`). apps/bot: `syncOwnBots` (раз в `userBotsIntervalMs`), `ownPollLoop`, обработка внутри `via.run(bot)`, объект `api` маршрутизирует вызов: бот текущего обновления → бот владельца `chat_id` → общий. Группы и каналы — только общий бот. Веб «Настройки → Telegram»: три шага. Тест `own-bot.test.ts` — два `MockTelegram` (`userApi` в опциях бота) - **Удаление проекта (PEP-163)**: `projects.deleted_at`/`deleted_by` (миграция 0021). Владелец — «⋯ Настройки проекта → Удалить проект» (`deleteProjectAction` → `deleteProject` в runner/project-trash.ts: `markProjectDeleted` + остановка сессий). Удалённый скрыт: `userProjectIds`, `listProjects(db)` (диспетчеры, intake) его не отдают, `projectForUser` пускает только суперадмина; он видит его в «Проектах других» («удалён, ещё N дн.») и жмёт «Вернуть проект» (`restoreProject`). `projectTrashTick` в вачдоге после `PEPPA_PROJECT_TRASH_DAYS` (7) делает `DELETE` строки (FK каскадные); репозиторий в Gitea и рабочая копия остаются. Платформенный проект не удаляется. Тест `project-trash.test.ts` - **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member +- **Защита основной ветки (PEP-191)**: `runner/branch-protection.ts` — push и merge в основную ветку только `peppa-bot` (белый список Gitea, без deploy-ключей, одобрений 0; `GiteaClient.protectBranch`, идемпотентно). Ставят `provisionProject`, `transferProject`, `connectCi` (`peppa ci connect`), `branchProtectionTick` (вачдог раз в сутки, `PEPPA_BRANCH_PROTECT=off`); клиенты по очереди — владелец, потом бот (нужен admin). Сбой не ломает проект: суперадмину одно сообщение (`branch.protect.failed:`). CLI `peppa project protect `. Запись в main не от бота — отказ 403 (`saveAgentsMd` откатывается на бота). Мок: `MockGitea.protections`, `protectionDown`. Тест `branch-protection.test.ts` - **Перенос репозитория проекта (PEP-4)**: `peppa project transfer ` (админ, от имени peppa-bot; `transferProject` в runner/transfer.ts): `POST /repos/{o}/{r}/transfer` → `projects.gitea_owner` → `origin` рабочей копии → `setupCi` (репо вне пространства бота получает свой раннер `repo---`, секрет, вебхук) → событие `repo_transferred` (чат проекта). Повторный запуск доводит до конца (репозиторий уже на месте — чинит только сторону Пеппы); цель — организация, где бот может создавать репозитории, иначе Gitea оставляет перенос ожидающим и команда падает. Откат — та же команда обратно - **Видимость репозиториев (PEP-15/64)**: новые проекты по умолчанию публичные (веб, MCP `create_project`, CLI `project create … --private` — приватный), подключаемый существующий репо не меняется. Сменить — `setProjectVisibility` (runner/share.ts; PATCH repo `private` клиентом владельца, иначе peppa-bot; сбрасывает кэш `describeRepo`): веб «⋯ Настройки проекта» → «Репозиторий» и MCP `set_project_visibility` — только владелец; CLI `peppa project visibility public|private` — админ, без проверки владельца - **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (сервис `bugsink` в `infra/docker-compose.yml`, `scripts/bugsink-up.sh`, база — SQLite `/data/db.sqlite3` в томе `peppa-bugsink-data` (PEP-63; перенос из Postgres — `scripts/bugsink-migrate-to-sqlite.sh`: dumpdata → migrate → loaddata → сверка строк; `peppa-postgres` только под профилем `legacy` до недели после переноса, откат — `infra/bugsink-legacy-pg.yml`), `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `-web`/`-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i::backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage` diff --git a/openspec/changes/pep-191-protect-main/design.md b/openspec/changes/pep-191-protect-main/design.md new file mode 100644 index 00000000..04a9af86 --- /dev/null +++ b/openspec/changes/pep-191-protect-main/design.md @@ -0,0 +1,7 @@ +## Решения +- Модуль `runner/branch-protection.ts`: `ensureBranchProtection` (пробует клиентов по очереди: владелец → peppa-bot; нужен admin), `branchProtectionState`, `branchProtectionTick` (раз в сутки, `PEPPA_BRANCH_PROTECT=off` выключает). +- Сбой: `alertAdmins` один раз на «период поломки» (`settings` `branch.protect.failed:`, снимается при успехе); `platformDelay` не берём — у него причины привязаны к задачам. +- Белый список — `GITEA_BOT_USER` (как в `ci.ts`), по умолчанию `peppa-bot`. +- `saveAgentsMd` уже перебирает клиентов: владелец получает 403 на защищённой main, запись идёт от peppa-bot (проверено тестом). +- Теги `deploy-*` не защищаем; `scripts/push-template.sh` и `git push` агентов идут от бота (credential helper). +- Мок не может запретить настоящий `git push` по пути; отказ моделируется на contents API и merge. diff --git a/openspec/changes/pep-191-protect-main/proposal.md b/openspec/changes/pep-191-protect-main/proposal.md new file mode 100644 index 00000000..bda549f3 --- /dev/null +++ b/openspec/changes/pep-191-protect-main/proposal.md @@ -0,0 +1,9 @@ +## Why +Код в основную ветку проекта должен попадать только через Peppa FACTORY (агенты, «Принять», автомерж) и её проверки. Защита main включена вручную в 28 существующих репозиториях; новые проекты её не получали. + +## What Changes +- `GiteaClient.getBranchProtection` / `protectBranch` — правило ветки: push и merge только `peppa-bot`, без deploy-ключей, без обязательных одобрений; идемпотентно (POST или PATCH). +- Защита ставится при создании и подключении проекта (`provisionProject`), переносе (`transferProject`), `peppa ci connect`, и сверяется раз в сутки в вачдоге. +- Сбой установки не ломает проект: суперадмину одно сообщение, пока не заработает. +- CLI `peppa project protect `. +- `mock-gitea`: branch_protections, отказ push/merge вне белого списка. diff --git a/openspec/changes/pep-191-protect-main/specs/branch-protection/spec.md b/openspec/changes/pep-191-protect-main/specs/branch-protection/spec.md new file mode 100644 index 00000000..7551301d --- /dev/null +++ b/openspec/changes/pep-191-protect-main/specs/branch-protection/spec.md @@ -0,0 +1,28 @@ +## ADDED Requirements +### Requirement: Основная ветка проекта защищена +Основная ветка каждого проекта SHALL быть защищена в Gitea: пишет и мержит только peppa-bot. + +#### Scenario: Новый проект +- **GIVEN** пользователь создаёт проект +- **WHEN** создание проекта завершено +- **THEN** у main есть правило с белым списком push и merge «peppa-bot» + +#### Scenario: Подключённый репозиторий +- **GIVEN** существующий репозиторий с кодом +- **WHEN** пользователь подключает его как проект +- **THEN** main получает такое же правило + +#### Scenario: Другой пользователь +- **GIVEN** main защищена +- **WHEN** владелец пытается записать файл в main или смержить PR +- **THEN** Gitea отвечает отказом, а peppa-bot мержит PR + +#### Scenario: Защита не поставилась +- **GIVEN** Gitea не принимает правило +- **WHEN** создаётся проект +- **THEN** проект создан, суперадмин получает одно сообщение, повторные попытки молчат + +#### Scenario: Правило изменили руками +- **GIVEN** в белый список добавлен посторонний +- **WHEN** срабатывает суточная проверка вачдога +- **THEN** правило возвращено к белому списку из peppa-bot diff --git a/openspec/changes/pep-191-protect-main/tasks.md b/openspec/changes/pep-191-protect-main/tasks.md new file mode 100644 index 00000000..57a11756 --- /dev/null +++ b/openspec/changes/pep-191-protect-main/tasks.md @@ -0,0 +1,5 @@ +- [x] 1. GiteaClient.getBranchProtection / protectBranch +- [x] 2. runner/branch-protection.ts, provision, transfer, ci connect, вачдог +- [x] 3. CLI `peppa project protect` +- [x] 4. mock-gitea: branch_protections, отказ вне белого списка +- [x] 5. Тесты branch-protection.test.ts, словарь и переводы diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index a489ee0d..df4c1e9a 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -74,7 +74,7 @@ import { promoteRunner, queueTaskOnRunner, renameRunner, startFreeRunner, runner import { checkPlatformChannel, describeChannel, getPlatformChannel, parseChatId, platformDigestTick, setPlatformChannel, PLATFORM_CHANNEL_EVENTS, type PlatformChannelPatch } from "@peppa/core"; import { setSharedPool, sharedPool, createHost, deleteHost, findHost, HOST_STATUS_RU, listHosts, setHostDisabled, updateHost } from "@peppa/core"; import { getProjectRunnerSettings, getSystemRunnerSettings, getTaskRunnerSettings, resolveRunnerSettings, runnerStories, setProjectRunnerSettings, setSystemRunnerSettings, setTaskRunnerSettings, type RunnerSettingsPatch } from "@peppa/core"; -import { connectErrorTrackingFromEnv, pauseProject, resumeProject } from "@peppa/runner"; +import { branchProtectionState, connectErrorTrackingFromEnv, ensureBranchProtection, pauseProject, resumeProject } from "@peppa/runner"; import { logoutAllUsers, showWelcomeToEveryone } from "@peppa/core"; import { installCrashReporting } from "@peppa/core"; import { answerAndDeliver, connectCi, importIssues, deployProd, listReleases, platformReleaseOffers, setPlatformReleaseOffers, recordRelease, type ReleaseStatus, provisionProject, setProjectVisibility, transferProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner"; @@ -93,6 +93,7 @@ const USAGE = `peppa — Peppa software factory CLI peppa project visibility public|private (repo visibility in Gitea: owner's client, then peppa-bot) peppa project pause|resume (PEP-174: agents stop, nothing is sent; resume continues them) peppa project transfer (PEP-4: move the repo to another Gitea namespace as peppa-bot; fixes origin, CI runner, secret, webhook) + peppa project protect (PEP-191: default branch protected, only peppa-bot writes) peppa project errors (PEP-58/91: connect to Bugsink — -web and -api, webhook, goal «Стабильность») peppa project import-issues (PEP-46: open Gitea issues of the repo → backlog stories, linked back) peppa project list @@ -348,6 +349,24 @@ async function main(): Promise { if (failed) process.exitCode = 1; break; } + case "project protect": { + // PEP-191: puts the default branch under protection (only the bot writes) and shows who may. + const keys = opts.all ? (await listProjects(db)).map((p) => p.key) : args[0] ? [args[0]] : []; + if (!keys.length) throw new PeppaError("usage: peppa project protect "); + let bad = 0; + for (const key of keys) { + const p = await getProject(db, key); + let st = await branchProtectionState(db, p); + if (!st?.protected) { + await ensureBranchProtection(db, p, { log: (l) => console.log(`… ${l}`) }); + st = await branchProtectionState(db, p); + } + if (!st?.protected) bad++; + console.log(`${p.key.padEnd(8)} ${p.giteaOwner}/${p.giteaRepo}@${p.defaultBranch} ${st?.protected ? "защищена" : "НЕ защищена"} push: ${st?.pushUsers.join(",") || "—"} merge: ${st?.mergeUsers.join(",") || "—"}`); + } + if (bad) process.exitCode = 1; + break; + } case "project transfer": { const [key, owner] = args; if (!key || !owner) throw new PeppaError("usage: peppa project transfer "); diff --git a/packages/core/src/gitea.ts b/packages/core/src/gitea.ts index 249256ce..91983f8a 100644 --- a/packages/core/src/gitea.ts +++ b/packages/core/src/gitea.ts @@ -70,6 +70,16 @@ export interface GiteaIssue { user?: { login: string }; pull_request?: unknown; } +export interface GiteaBranchProtection { + rule_name?: string; + branch_name?: string; + enable_push: boolean; + enable_push_whitelist: boolean; + push_whitelist_usernames: string[] | null; + push_whitelist_deploy_keys?: boolean; + enable_merge_whitelist: boolean; + merge_whitelist_usernames: string[] | null; +} export interface GiteaHook { id: number; type: string; @@ -313,6 +323,35 @@ export class GiteaClient { return this.request<{ commit: { sha: string; html_url: string } }>(o.sha ? "PUT" : "POST", `${this.repoPath(owner, repo)}/contents/${path.split("/").map(encodeURIComponent).join("/")}`, body); } + /** PEP-191: the protection rule of `branch`, null when there is none. */ + async getBranchProtection(owner: string, repo: string, branch: string): Promise { + try { + return await this.request("GET", `${this.repoPath(owner, repo)}/branch_protections/${encodeURIComponent(branch)}`); + } catch (e) { + if (e instanceof GiteaError && e.status === 404) return null; + throw e; + } + } + + /** + * PEP-191: only `users` push to and merge into `branch` (deploy keys do not push; no approvals + * required — Peppa merges after green checks). Creates the rule or updates the existing one. + */ + async protectBranch(owner: string, repo: string, branch: string, o: { users: string[] }): Promise { + const body = { + rule_name: branch, + enable_push: true, + enable_push_whitelist: true, + push_whitelist_usernames: o.users, + push_whitelist_deploy_keys: false, + enable_merge_whitelist: true, + merge_whitelist_usernames: o.users, + required_approvals: 0, + }; + if (await this.getBranchProtection(owner, repo, branch)) return this.request("PATCH", `${this.repoPath(owner, repo)}/branch_protections/${encodeURIComponent(branch)}`, body); + return this.request("POST", `${this.repoPath(owner, repo)}/branch_protections`, body); + } + setActionsSecret(owner: string, repo: string, name: string, data: string) { return this.request("PUT", `${this.repoPath(owner, repo)}/actions/secrets/${encodeURIComponent(name)}`, { data }); } diff --git a/packages/runner/src/branch-protection.ts b/packages/runner/src/branch-protection.ts new file mode 100644 index 00000000..b8344ca7 --- /dev/null +++ b/packages/runner/src/branch-protection.ts @@ -0,0 +1,84 @@ +// PEP-191: the default branch of every project is protected in Gitea — only peppa-bot pushes to it +// and merges into it, so code reaches `main` through Peppa (agents, «Принять», auto-merge) and +// through its checks, never around them. Tags (`deploy-*`) are not protected. +import { m } from "@peppa/shared/i18n"; +import { alertAdmins, deleteSetting, getSetting, listProjects, setSetting, type GiteaClient, type Project } from "@peppa/core"; +import type { Db } from "@peppa/db"; +import { repoAdmins } from "./share.ts"; + +const botLogin = () => process.env.GITEA_BOT_USER ?? "peppa-bot"; +const DAY_MS = 24 * 3600_000; + +export interface BranchProtectionState { + branch: string; + /** The rule exists and only the bot is on both whitelists. */ + protected: boolean; + /** Logins allowed to push (empty when push is open to everyone with write access). */ + pushUsers: string[]; + mergeUsers: string[]; +} + +const same = (a: string[], b: string[]) => a.length === b.length && a.every((x) => b.includes(x)); + +/** Reads the rule with the first client that can see it; null when no client could ask. */ +export async function branchProtectionState(db: Db, project: Project, clients?: GiteaClient[]): Promise { + for (const c of clients ?? (await repoAdmins(db, project))) { + try { + const r = await c.getBranchProtection(project.giteaOwner, project.giteaRepo, project.defaultBranch); + const pushUsers = r?.enable_push && r.enable_push_whitelist ? (r.push_whitelist_usernames ?? []) : []; + const mergeUsers = r?.enable_merge_whitelist ? (r.merge_whitelist_usernames ?? []) : []; + const ok = !!r && r.enable_push_whitelist && r.enable_merge_whitelist && !r.push_whitelist_deploy_keys && same(pushUsers, [botLogin()]) && same(mergeUsers, [botLogin()]); + return { branch: project.defaultBranch, protected: ok, pushUsers, mergeUsers }; + } catch {} + } + return null; +} + +/** + * Sets (or repairs) the protection with the first client that has admin rights. Never throws: + * when no client can, the superadmin hears about it once (until it works again) and `false` is + * returned — the caller goes on (a project without protection still works). + */ +export async function ensureBranchProtection(db: Db, project: Project, o: { clients?: GiteaClient[]; log?: (line: string) => void } = {}): Promise { + const repo = `${project.giteaOwner}/${project.giteaRepo}`; + const failKey = `branch.protect.failed:${project.id}`; + let last: unknown = null; + try { + for (const c of o.clients ?? (await repoAdmins(db, project))) { + try { + await c.protectBranch(project.giteaOwner, project.giteaRepo, project.defaultBranch, { users: [botLogin()] }); + await deleteSetting(db, failKey); + return true; + } catch (e) { + last = e; + } + } + } catch (e) { + last = e; + } + const reason = (last as Error | null)?.message ?? m("нет доступа к коду проекта"); + o.log?.(`branch protection ${repo}: ${reason}`); + try { + if (!(await getSetting(db, failKey))) { + const at = Date.now(); + await setSetting(db, failKey, { at, reason: reason.slice(0, 300) }); + // glossary-ignore: сообщение читает администратор платформы + await alertAdmins(db, `protect:${project.id}:${at}`, m("Основная ветка проекта {key} не защищена: {reason}. Peppa FACTORY повторит проверку сама; сразу — peppa project protect {key}.", { key: project.key, reason }), o.log ?? (() => {})); + } + } catch {} + return false; +} + +/** Watchdog: once a day every project's rule is checked and put back if someone changed it. */ +export async function branchProtectionTick(db: Db, opts: { now?: Date; log?: (line: string) => void } = {}): Promise { + if (process.env.PEPPA_BRANCH_PROTECT === "off") return; + const now = (opts.now ?? new Date()).getTime(); + const last = await getSetting(db, "branch.protect.last"); + if (last != null && now - last < DAY_MS) return; + await setSetting(db, "branch.protect.last", now); + for (const p of await listProjects(db)) { + const st = await branchProtectionState(db, p); + if (st?.protected) continue; + await ensureBranchProtection(db, p, { log: opts.log }); + } +} diff --git a/packages/runner/src/ci.ts b/packages/runner/src/ci.ts index 14e328be..1a165be3 100644 --- a/packages/runner/src/ci.ts +++ b/packages/runner/src/ci.ts @@ -9,6 +9,7 @@ import { dirname, join } from "node:path"; import { giteaForBot, PeppaError, projectHookSecret, type GiteaClient, type Project } from "@peppa/core"; import type { Db } from "@peppa/db"; import { loadEnv } from "@peppa/shared"; +import { ensureBranchProtection } from "./branch-protection.ts"; import { repoAdmins } from "./share.ts"; import { git, run, templateRepoUrl } from "./git.ts"; @@ -87,6 +88,9 @@ export async function connectCi(db: Db, project: Project, o: { templateUrl?: str const log = o.log ?? (() => {}); log("runner + secret"); const setup = await setupCi(db, project); + // PEP-191: the same command also puts the default branch protection back. + log("protect branch"); + await ensureBranchProtection(db, project, { log }); const bot = giteaForBot(); const repo = await bot.getRepo(project.giteaOwner, project.giteaRepo); if (!repo) throw new PeppaError(m("Код проекта {repo} не найден", { repo: `${project.giteaOwner}/${project.giteaRepo}` })); diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts index e4720c3c..aa03482a 100644 --- a/packages/runner/src/index.ts +++ b/packages/runner/src/index.ts @@ -29,6 +29,7 @@ export * from "./project-subscription.ts"; export * from "./subscription-request.ts"; export * from "./intake.ts"; export * from "./project-trash.ts"; +export * from "./branch-protection.ts"; export * from "./story-refine.ts"; export * from "./terminal.ts"; export * from "./claude-print.ts"; diff --git a/packages/runner/src/provision.ts b/packages/runner/src/provision.ts index ce1898e9..3f36f623 100644 --- a/packages/runner/src/provision.ts +++ b/packages/runner/src/provision.ts @@ -9,6 +9,7 @@ import { createProject, NEW_PROJECT_AUTONOMY, NEW_PROJECT_PUBLISH, setPublishMod import { projects, type Db } from "@peppa/db"; import { loadEnv } from "@peppa/shared"; import { eq, or } from "drizzle-orm"; +import { ensureBranchProtection } from "./branch-protection.ts"; import { setupCi } from "./ci.ts"; import { credentialHelper, git, run, templateRepoUrl } from "./git.ts"; @@ -177,6 +178,17 @@ export async function provisionProject(db: Db, o: ProvisionOptions): Promise { + try { + return giteaForBot(); + } catch { + return null; // no bot token (tests, a half-set machine): protect with the owner's client alone + } + })(); + await ensureBranchProtection(db, project, { clients: bot ? [o.gitea, bot] : [o.gitea], log }); // 7. CI (PEP-57): runner, Actions secret, webhook. Best effort — `peppa ci connect` redoes it. log("ci"); const ci = await setupCi(db, project).then(() => true, (e) => (log(`ci: ${(e as Error).message}`), false)); diff --git a/packages/runner/src/transfer.ts b/packages/runner/src/transfer.ts index b1f40abf..e2e58f1a 100644 --- a/packages/runner/src/transfer.ts +++ b/packages/runner/src/transfer.ts @@ -7,6 +7,7 @@ import { existsSync } from "node:fs"; import { eq } from "drizzle-orm"; import { GiteaError, giteaForBot, logEvent, PeppaError, type Project } from "@peppa/core"; import { projects, type Db } from "@peppa/db"; +import { ensureBranchProtection } from "./branch-protection.ts"; import { setupCi } from "./ci.ts"; import { git } from "./git.ts"; import { forgetRepoInfo } from "./share.ts"; @@ -66,6 +67,8 @@ export async function transferProject(db: Db, project: Project, newOwner: string log("origin"); await git(project.workspacePath, "remote", "set-url", "origin", dest.clone_url); } + log("protect branch"); + await ensureBranchProtection(db, updated, { clients: [bot], log }); log("ci"); const ciError = await setupCi(db, updated).then( () => null, diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts index 9f54fa2d..a2161ade 100644 --- a/packages/runner/src/watchdog.ts +++ b/packages/runner/src/watchdog.ts @@ -3,6 +3,7 @@ import { asIs, m } from "@peppa/shared/i18n"; import { runnerTick } from "./runners.ts"; import { projectTrashTick } from "./project-trash.ts"; +import { branchProtectionTick } from "./branch-protection.ts"; import { createHash } from "node:crypto"; import { backupDb, @@ -124,6 +125,8 @@ async function tickInner(db: Db, opts: WatchdogOptions): Promise { // PEP-84: «продакт» and «аналитик» refine new stories before the dispatcher sees them. // PEP-163: deleted projects leave for good after their week. await projectTrashTick(db, { now: opts.now, log }).catch(failed(db, log, "project trash")); + // PEP-191: once a day the protection of every project's default branch is checked. + await branchProtectionTick(db, { now: opts.now, log }).catch(failed(db, log, "branch protection")); await intakeTick(db, { now: opts.now, log }).catch(failed(db, log, "intake")); // PEP-115: a comment on a backlog story — the analyst reworks the story. await storyRefineTick(db, { now: opts.now, log }).catch(failed(db, log, "story refine")); diff --git a/packages/shared/src/i18n/en/runner.ts b/packages/shared/src/i18n/en/runner.ts index 38cde86c..4c72e7eb 100644 --- a/packages/shared/src/i18n/en/runner.ts +++ b/packages/shared/src/i18n/en/runner.ts @@ -257,6 +257,8 @@ export const runner: Dict = { 'Slug "{slug}" уже занят': 'Slug "{slug}" is already taken', 'Ключ "{key}" уже занят': 'Key "{key}" is already taken', "Рабочая копия {path} уже существует": "Working copy {path} already exists", + "Основная ветка проекта {key} не защищена: {reason}. Peppa FACTORY повторит проверку сама; сразу — peppa project protect {key}.": "The default branch of project {key} is not protected: {reason}. Peppa FACTORY will check again by itself; to do it now — peppa project protect {key}.", + "нет доступа к коду проекта": "no access to the project's code", "Нет прав администратора на {repo}": "No admin rights on {repo}", "Код проекта {repo} уже есть — подключите его как существующий": "The project code {repo} already exists — connect it as an existing one", "Не удалось подготовить проект: {error}": "Could not prepare the project: {error}", diff --git a/packages/shared/src/i18n/kk/runner.ts b/packages/shared/src/i18n/kk/runner.ts index 3dae05cd..301b5d27 100644 --- a/packages/shared/src/i18n/kk/runner.ts +++ b/packages/shared/src/i18n/kk/runner.ts @@ -198,6 +198,8 @@ export const runner: Dict = { "Slug \"{slug}\" уже занят": "Slug \"{slug}\" бос емес", "Ключ \"{key}\" уже занят": "\"{key}\" кілті бос емес", "Рабочая копия {path} уже существует": "{path} жұмыс көшірмесі бұрыннан бар", + "Основная ветка проекта {key} не защищена: {reason}. Peppa FACTORY повторит проверку сама; сразу — peppa project protect {key}.": "{key} жобасының негізгі тармағы қорғалмаған: {reason}. Peppa FACTORY тексеруді өзі қайталайды; дәл қазір — peppa project protect {key}.", + "нет доступа к коду проекта": "жоба кодына қол жетімділік жоқ", "Нет прав администратора на {repo}": "{repo} үшін әкімші құқықтары жоқ", "Код проекта {repo} уже есть — подключите его как существующий": "{repo} жоба коды бұрыннан бар — оны бар код ретінде қосыңыз", "Не удалось подготовить проект: {error}": "Жобаны дайындау мүмкін болмады: {error}", diff --git a/packages/testkit/src/mock-gitea.ts b/packages/testkit/src/mock-gitea.ts index 4dce78b2..a4d76cc8 100644 --- a/packages/testkit/src/mock-gitea.ts +++ b/packages/testkit/src/mock-gitea.ts @@ -10,6 +10,18 @@ import { createServer, type Server } from "node:http"; import type { AddressInfo } from "node:net"; import { join } from "node:path"; +/** PEP-191: the fields of Gitea's branch protection Peppa uses. */ +export interface MockProtection { + rule_name: string; + enable_push: boolean; + enable_push_whitelist: boolean; + push_whitelist_usernames: string[]; + push_whitelist_deploy_keys: boolean; + enable_merge_whitelist: boolean; + merge_whitelist_usernames: string[]; + required_approvals: number; +} + interface MockRepo { id: number; owner: string; @@ -24,6 +36,8 @@ interface MockRepo { hooks: Array<{ id: number; url: string; secret: string; events: string[] }>; tags: Array<{ name: string; target: string }>; issues: MockIssue[]; + /** PEP-191: branch protection rules by branch name (like Gitea's `branch_protections`). */ + protections: Map; } /** PEP-46: an issue with its comments (by login). */ @@ -58,6 +72,8 @@ export class MockGitea { readonly repos = new Map(); /** Every request answers 500, like Gitea being down (PEP-127). */ down = false; + /** PEP-191: the branch_protections API answers 500 (a failed setup must not break projects). */ + protectionDown = false; readonly users = new Map(); readonly oauthCodes = new Map(); // code → token readonly runnerTokens: Array<{ scope: string; token: string }> = []; @@ -137,6 +153,7 @@ export class MockGitea { hooks: [], tags: [], issues: [], + protections: new Map(), private: opts.private ?? true, }; this.repos.set(`${owner}/${name}`, repo); @@ -300,6 +317,14 @@ export class MockGitea { p.state = "closed"; } + /** PEP-191: may `login` push to / merge into `branch`? (open when there is no rule). */ + mayWrite(r: MockRepo, branch: string, login: string, what: "push" | "merge"): boolean { + const rule = r.protections.get(branch); + if (!rule) return true; + if (what === "push") return !rule.enable_push || (rule.enable_push_whitelist && rule.push_whitelist_usernames.includes(login)); + return rule.enable_merge_whitelist ? rule.merge_whitelist_usernames.includes(login) : true; + } + private isEmpty(r: MockRepo) { return execFileSync("git", ["--git-dir", r.path, "for-each-ref"], { encoding: "utf8" }).trim() === ""; } @@ -431,6 +456,32 @@ export class MockGitea { this.runnerTokens.push({ scope: `repo:${r.owner}/${r.name}`, token }); return { status: 200, body: { token } }; } + if (this.protectionDown && /^branch_protections/.test(sub)) return { status: 500, body: { message: "mock-gitea: branch protection down" } }; + if (method === "GET" && (m = sub.match(/^branch_protections\/([^/]+)$/))) { + if (!isAdmin) return { status: 403, body: { message: "forbidden" } }; + const rule = r.protections.get(decodeURIComponent(m[1]!)); + return rule ? { status: 200, body: rule } : { status: 404, body: { message: "branch protection does not exist" } }; + } + if ((method === "POST" && sub === "branch_protections") || (method === "PATCH" && (m = sub.match(/^branch_protections\/([^/]+)$/)))) { + if (!isAdmin) return { status: 403, body: { message: "forbidden" } }; + const name = method === "POST" ? String(body.rule_name ?? body.branch_name) : decodeURIComponent(m![1]!); + const cur = r.protections.get(name); + if (method === "POST" && cur) return { status: 403, body: { message: "branch protection already exists" } }; + if (method === "PATCH" && !cur) return { status: 404, body: { message: "branch protection does not exist" } }; + const b = body as Partial; + const rule: MockProtection = { + rule_name: name, + enable_push: b.enable_push ?? cur?.enable_push ?? false, + enable_push_whitelist: b.enable_push_whitelist ?? cur?.enable_push_whitelist ?? false, + push_whitelist_usernames: b.push_whitelist_usernames ?? cur?.push_whitelist_usernames ?? [], + push_whitelist_deploy_keys: b.push_whitelist_deploy_keys ?? cur?.push_whitelist_deploy_keys ?? false, + enable_merge_whitelist: b.enable_merge_whitelist ?? cur?.enable_merge_whitelist ?? false, + merge_whitelist_usernames: b.merge_whitelist_usernames ?? cur?.merge_whitelist_usernames ?? [], + required_approvals: b.required_approvals ?? cur?.required_approvals ?? 0, + }; + r.protections.set(name, rule); + return { status: method === "POST" ? 201 : 200, body: rule }; + } if (method === "PUT" && (m = sub.match(/^actions\/secrets\/([^/]+)$/))) { if (!isAdmin && r.owner !== me.login) return { status: 403, body: { message: "forbidden" } }; r.secrets[decodeURIComponent(m[1]!)] = String(body.data); @@ -479,6 +530,7 @@ export class MockGitea { } if (method === "POST" && m[2] === "/merge") { if (!canWrite) return { status: 403, body: { message: "forbidden" } }; + if (!this.mayWrite(r, p.base, me.login, "merge")) return { status: 403, body: { message: "user not allowed to merge PR" } }; if (p.merged) return { status: 405, body: { message: "already merged" } }; if (!p.mergeable) return { status: 405, body: { message: "Please try again later: merge conflict" } }; if (body.head_commit_id && body.head_commit_id !== this.sha(r.owner, r.name, p.head)) return { status: 409, body: { message: "head out of date" } }; @@ -541,6 +593,7 @@ export class MockGitea { // Gitea's create (POST, file must not exist) / update (PUT, `sha` = current blob) — one commit on `branch`. const path = decodeURIComponent(m[1]!); const branch = String(body.branch ?? "main"); + if (!this.mayWrite(r, branch, me.login, "push")) return { status: 403, body: { message: `Branch protected: ${branch}` } }; const git = (args: string[], env?: NodeJS.ProcessEnv, input?: string) => execFileSync("git", ["--git-dir", r.path, ...args], { encoding: "utf8", input, env: { ...process.env, ...env }, stdio: ["pipe", "pipe", "ignore"] }).trim(); let parent: string | null = null; diff --git a/packages/testkit/test/branch-protection.test.ts b/packages/testkit/test/branch-protection.test.ts new file mode 100644 index 00000000..ed3e1465 --- /dev/null +++ b/packages/testkit/test/branch-protection.test.ts @@ -0,0 +1,125 @@ +// PEP-191: the default branch of a project is protected in Gitea — only peppa-bot pushes and merges. +// Tests are named after the scenarios of openspec/specs/branch-protection. +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { after, before, describe, test } from "node:test"; +import { like } from "drizzle-orm"; +import { telegramOutbox } from "@peppa/db"; +import { core, db, runner, superadmin, teardown } from "./helpers.ts"; +import { MockGitea } from "../src/mock-gitea.ts"; + +const ROOT = resolve(fileURLToPath(import.meta.url), "../../../.."); +const TMP = mkdtempSync(join(tmpdir(), "peppa-protect-")); +process.env.PEPPA_SECRET = "mock-secret-for-tests"; +process.env.PEPPA_WORKSPACES = join(TMP, "workspaces"); + +const gitea = new MockGitea(join(TMP, "gitea")); +const ALICE = { id: 91, login: "mock-prot-alice", token: "mock-token-prot-alice" }; +const BOT = { id: 92, login: "peppa-bot", token: "mock-token-prot-bot" }; +type U = Awaited>; +let alice: U; +let templateUrl = ""; + +before(async () => { + await gitea.start(); + process.env.GITEA_URL = gitea.url; + process.env.GITEA_TOKEN = BOT.token; + for (const u of [ALICE, BOT]) gitea.addUser(u); + const tpl = gitea.addRepo("peppa-bot", "template"); + execFileSync("bash", ["-c", `cd ${JSON.stringify(join(ROOT, "template"))} && T=$(mktemp -d) && cp -R . "$T" && cd "$T" && git init -q -b main && git add -A && git -c user.name=t -c user.email=t@t commit -qm tpl && git push -q ${JSON.stringify(tpl.path)} main`]); + templateUrl = tpl.path; + alice = await core.upsertUserFromGitea(db, ALICE, { access_token: ALICE.token }); +}); +after(async () => { + gitea.protectionDown = false; + await gitea.stop(); + await teardown(); +}); + +const provision = async (over: Partial[1]> & { slug: string; key: string }) => + runner.provisionProject(db, { + gitea: await core.giteaForUser(db, alice), + owner: ALICE.login, + ownerIsUser: true, + name: `Mock ${over.key}`, + ownerId: alice.id, + templateUrl, + ...over, + }); + +const rule = (slug: string) => gitea.repos.get(`${ALICE.login}/${slug}`)!.protections.get("main"); +const protectAlerts = async () => (await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, "protect:%"))).length; + +describe("branch protection", () => { + test("new project gets main protected with peppa-bot", async () => { + await provision({ slug: "mock-prot-new", key: "MPNEW" }); + const r = rule("mock-prot-new")!; + assert.deepEqual(r.push_whitelist_usernames, ["peppa-bot"]); + assert.deepEqual(r.merge_whitelist_usernames, ["peppa-bot"]); + assert.equal(r.enable_push_whitelist, true); + assert.equal(r.push_whitelist_deploy_keys, false); + assert.equal(r.required_approvals, 0); + }); + + test("a connected existing repository gets it too", async () => { + const repo = gitea.addRepo(ALICE.login, "mock-prot-existing", { files: { "README.md": "# x\n" } }); + repo.collaborators["peppa-bot"] = "write"; + await provision({ slug: "mock-prot-existing", key: "MPEXI", existing: true }); + assert.deepEqual(rule("mock-prot-existing")!.push_whitelist_usernames, ["peppa-bot"]); + }); + + test("accept merges into protected main; another user is refused", async () => { + const p = await provision({ slug: "mock-prot-merge", key: "MPMRG" }); + const repo = gitea.repos.get(`${ALICE.login}/mock-prot-merge`)!; + const work = join(TMP, "work-merge"); + execFileSync("bash", ["-c", `git clone -q ${JSON.stringify(repo.path)} ${JSON.stringify(work)} && cd ${JSON.stringify(work)} && git checkout -q -b task/x && echo 1 > f.txt && git add -A && git -c user.name=t -c user.email=t@t commit -qm f && git push -q origin task/x`]); + gitea.openPull(ALICE.login, "mock-prot-merge", "task/x"); + const aliceClient = await core.giteaForUser(db, alice); + await assert.rejects(aliceClient.mergePullRequest(ALICE.login, "mock-prot-merge", 1), /403/); + await assert.rejects(aliceClient.writeFile(ALICE.login, "mock-prot-merge", "evil.txt", { text: "x", branch: "main", message: "m" }), /403/); + await core.giteaForBot().mergePullRequest(ALICE.login, "mock-prot-merge", 1); + assert.ok(gitea.files(ALICE.login, "mock-prot-merge").includes("f.txt")); + assert.ok(p); + }); + + test("a failed setup does not break the project and tells the superadmin once", async () => { + await superadmin(); + gitea.protectionDown = true; + const before = await protectAlerts(); + const p = await provision({ slug: "mock-prot-fail", key: "MPFAL" }); + assert.ok(p.id); + assert.equal(rule("mock-prot-fail"), undefined); + assert.equal(await protectAlerts(), before + 1); + assert.equal(await runner.ensureBranchProtection(db, p), false); + assert.equal(await protectAlerts(), before + 1, "no second message while it stays broken"); + gitea.protectionDown = false; + assert.equal(await runner.ensureBranchProtection(db, p), true); + assert.deepEqual(rule("mock-prot-fail")!.push_whitelist_usernames, ["peppa-bot"]); + }); + + test("the daily check repairs a changed rule; ensure is idempotent", async () => { + const p = await provision({ slug: "mock-prot-tick", key: "MPTIK" }); + rule("mock-prot-tick")!.push_whitelist_usernames.push("mock-prot-alice"); + assert.equal((await runner.branchProtectionState(db, p))!.protected, false); + process.env.PEPPA_BRANCH_PROTECT = "on"; + try { + await runner.branchProtectionTick(db, { now: new Date(Date.now() + 3 * 86400_000) }); + } finally { + process.env.PEPPA_BRANCH_PROTECT = "off"; + } + assert.equal((await runner.branchProtectionState(db, p))!.protected, true); + assert.equal(await runner.ensureBranchProtection(db, p), true); + }); + + test("saving AGENTS.md works while main is protected", async () => { + const p = await provision({ slug: "mock-prot-agents", key: "MPAGT" }); + const cur = await runner.readAgentsMd(db, p); + assert.equal(cur.error, null); + await runner.saveAgentsMd(db, alice, p, `${cur.text}\n- PEP-191 проверка\n`, cur.sha); + assert.match(gitea.show(ALICE.login, "mock-prot-agents", "AGENTS.md"), /PEP-191 проверка/); + }); +}); diff --git a/packages/testkit/test/helpers.ts b/packages/testkit/test/helpers.ts index 8684ce07..9c525375 100644 --- a/packages/testkit/test/helpers.ts +++ b/packages/testkit/test/helpers.ts @@ -31,6 +31,7 @@ Object.assign(process.env, { // PEP-145: the watchdog files «Продукт должен открываться по ссылке» for any project with // accepted stories and no deploy — every suite's projects. product-link.test.ts turns it on. PEPPA_PRODUCT_LINK: "off", + PEPPA_BRANCH_PROTECT: "off", // PEP-185: no «Взять в работу?» questions in other suites; pick-question.test.ts turns it on. PEPPA_PICK_QUESTION: "off", // PEP-168: no real HTTP probe of the live site :3100 from tests; monitor tests pass their own probe.