PEP-254: журнал Access Hub до действия и с цепочкой хэшей, контрольные точки, выгрузка; свой ключ данных у каждого подключения
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
63ef6d6e04
commit
c8652e57ae
@ -30,11 +30,8 @@
|
||||
- Продукт на другой docker переносить только с данными (PEP-231): `scripts/server-move/products-move.sh` — тома со сверкой сумм, Postgres дампом, без отчёта о выкладке; `peppa deploy redeploy` поднимает продукт с пустыми томами.
|
||||
- Агент в контейнере не видит хост сервера, Mac и Cloudflare (PEP-231): инфраструктуру — скриптом в `scripts/server-move/` + шаги в docs/SERVER.md, выполнить просить суперадмина через `report_blocker`.
|
||||
- Пути сессий с Mac (PEP-246): `runnerCwd` пересоздаёт копию сам; чистка — `peppa session paths --fix`.
|
||||
- Сервер (PEP-230): памятка — docs/SERVER.md. В контейнере агента нет глобального git: автор коммита — `gitRelayEnv` (GIT_AUTHOR_*); на старом образе — `git -c user.name=peppa-bot -c user.email=peppa-bot@telecom.quest commit`.
|
||||
- Песочница раннера: нет tmux, openspec, Node 26 (есть 22). tmux — `.deb` с deb.debian.org (tmux_3.3a-3, libevent-core-2.1-7, libutempter0) → `dpkg-deb -x` + LD_LIBRARY_PATH; openspec — `npm i -g --prefix /tmp/os @fission-ai/openspec`; e2e на 22 — MIN_MAJOR в scripts/lib/require-node.mjs (не коммитить).
|
||||
- Сервер (PEP-230): docs/SERVER.md. Нет глобального git в контейнере: автор — `gitRelayEnv`; иначе `git -c user.name=peppa-bot -c user.email=peppa-bot@telecom.quest commit`.
|
||||
- Песочница раннера: нет tmux, openspec, Node 26 (есть 22). tmux — .deb с deb.debian.org (tmux_3.3a-3, libevent-core-2.1-7, libutempter0) → `dpkg-deb -x` + обёртка с LD_LIBRARY_PATH; openspec — `npm i -g --prefix /tmp/os @fission-ai/openspec`; тесты на 22 — MIN_MAJOR в scripts/lib/require-node.mjs (не коммитить).
|
||||
- Сервер (PEP-230): памятка — docs/SERVER.md. В контейнере агента нет глобального git: автор коммита — `gitRelayEnv` (GIT_AUTHOR_*).
|
||||
- Песочница раннера: нет tmux, openspec, Node 26 (есть 22: тесты с бинарями peppa и glossary-check.test падают — это среда). openspec — `npm i -g --prefix /tmp/os @fission-ai/openspec`; tmux — `.deb` с deb.debian.org + `dpkg-deb -x`.
|
||||
- Codex (PEP-241): доверие папке — по корню основного репо worktree; `-c` режет ключ по точкам — пишем в config.toml CODEX_HOME (`codex-trust.ts`).
|
||||
|
||||
@ -59,6 +56,7 @@
|
||||
- act_runner (PEP-233): идут контейнеры `GITEA-ACTIONS-TASK-*` — не рестартовать; голова без ci.yml или >2 суток — `orphan`, не очередь.
|
||||
|
||||
## Решения
|
||||
- Access Hub (PEP-254): журнал — только `appendJournal` (core/connection-journal.ts, цепочка хэшей; правка строки задним числом = нарушение), ключ подключения — `sealConnectionSecret`/`openConnectionSecret`, не `encrypt`/`decrypt`.
|
||||
- История (PEP-221): журнал/статусы — `history.db` (core/history.ts), логи — `archive/<вид>/<день>.jsonl.gz`; из основной базы события удаляет только `runRetention` после переноса.
|
||||
- Docker (PEP-222): раннеры по умолчанию `container` (тесты — `PEPPA_DEFAULT_ISOLATION=none`).
|
||||
- Медленные запросы (PEP-213): `core/request-timing.ts` (`http.Server` в instrumentation.ts, probe в db) → warning Bugsink; порог `PEPPA_SLOW_REQUEST_MS`.
|
||||
|
||||
@ -7,6 +7,7 @@ import {
|
||||
CONNECTION_CHECK_TEXT,
|
||||
CONNECTION_REASON_TEXT,
|
||||
connectionJournal,
|
||||
JOURNAL_VERIFY_SCRIPT,
|
||||
grantableAgents,
|
||||
listConnections,
|
||||
listUserProjects,
|
||||
@ -43,6 +44,9 @@ const SELECT = "h-9 rounded-md border border-input bg-background px-2 text-sm";
|
||||
const BACK = "/connections";
|
||||
|
||||
function Decision({ row, t }: { row: ConnectionLogView; t: Translator }) {
|
||||
// PEP-254: the call is written before the service answers; no result after a while — a crash in the middle.
|
||||
if (row.state === "running") return <Badge variant="outline">{t("выполняется")}</Badge>;
|
||||
if (row.state === "unfinished") return <Badge variant="warn">{t("начато, итога нет")}</Badge>;
|
||||
if (row.decision === "allowed") return <Badge variant="ok">{t("разрешено")}</Badge>;
|
||||
if (row.decision === "denied") return <Badge variant="danger">{t("запрещено")}</Badge>;
|
||||
return <Badge variant="warn">{t("не выполнено")}</Badge>;
|
||||
@ -320,6 +324,34 @@ function Catalog({ q, kind, t }: { q: string; kind: string | null; t: Translator
|
||||
);
|
||||
}
|
||||
|
||||
/** PEP-254: download the journal with hashes and how to check it yourself. */
|
||||
function JournalExport({ t, engineer }: { t: Translator; engineer: boolean }) {
|
||||
return (
|
||||
<div className="mt-3 space-y-2 text-sm">
|
||||
<p className="m-0 text-muted-foreground">
|
||||
{t("Журнал нельзя незаметно изменить: каждая запись связана с предыдущей, и раз в сутки FORGE сохраняет отметку журнала отдельно. Если запись изменят, вы и администратор получите сообщение.")}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button asChild size="sm" variant="outline">
|
||||
<a href="/api/connections/journal?format=csv" download>{t("Скачать журнал (таблица)")}</a>
|
||||
</Button>
|
||||
<Button asChild size="sm" variant="outline">
|
||||
<a href="/api/connections/journal?format=jsonl" download>{t("Скачать журнал для проверки")}</a>
|
||||
</Button>
|
||||
</div>
|
||||
<details open={engineer}>
|
||||
<summary className="cursor-pointer text-muted-foreground">{t("Как проверить журнал самому")}</summary>
|
||||
<div className="mt-2 space-y-2">
|
||||
<p className="m-0">
|
||||
{t("Скачайте журнал для проверки и сохраните программу ниже рядом с ним. Запустите её так, как написано в её первой строке. Ответ «ok» значит, что журнал не меняли; иначе программа назовёт первую изменённую запись.")}
|
||||
</p>
|
||||
<pre className="overflow-x-auto rounded-md bg-muted p-2 text-xs">{JOURNAL_VERIFY_SCRIPT}</pre>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** PEP-234/249 Access Hub: «Подключения» — the user's own external services and who may use them. */
|
||||
export default async function ConnectionsPage({ searchParams }: { searchParams: Promise<Params> }) {
|
||||
const q = await searchParams;
|
||||
@ -390,6 +422,7 @@ export default async function ConnectionsPage({ searchParams }: { searchParams:
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
<JournalExport t={t} engineer={engineer} />
|
||||
</Section>
|
||||
</Workspace>
|
||||
);
|
||||
|
||||
25
apps/web/app/api/connections/journal/route.ts
Normal file
25
apps/web/app/api/connections/journal/route.ts
Normal file
@ -0,0 +1,25 @@
|
||||
// PEP-254: the owner downloads their whole Access Hub journal with hashes (JSONL or CSV) to
|
||||
// check it on their own. Only the signed-in user's own rows.
|
||||
import { exportConnectionJournal } from "@peppa/core";
|
||||
import { currentUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET(req: Request) {
|
||||
const t = await getT();
|
||||
const me = await currentUser();
|
||||
if (!me) return Response.json({ error: t("Нужен вход") }, { status: 401 });
|
||||
const format = new URL(req.url).searchParams.get("format") === "csv" ? "csv" : "jsonl";
|
||||
const body = await exportConnectionJournal(db, me.id, format);
|
||||
const day = new Date().toISOString().slice(0, 10);
|
||||
return new Response(body, {
|
||||
headers: {
|
||||
"content-type": format === "csv" ? "text/csv; charset=utf-8" : "application/x-ndjson; charset=utf-8",
|
||||
"content-disposition": `attachment; filename="connections-journal-${day}.${format}"`,
|
||||
"cache-control": "no-store",
|
||||
"x-content-type-options": "nosniff",
|
||||
},
|
||||
});
|
||||
}
|
||||
@ -0,0 +1,29 @@
|
||||
## Context
|
||||
|
||||
`connection_log` (PEP-234/249) — одна строка на решение шлюза, пишется после запроса. `connections.secret_enc` — `encrypt()` ключом, производным от `PEPPA_SECRET`.
|
||||
|
||||
## Decisions
|
||||
|
||||
### Запись до действия — две строки, а не правка одной
|
||||
Цепочка хэшей не терпит правку строки после того, как за ней появились следующие. Поэтому разрешённый вызов — строка `kind = call` (решение `allowed`, до запроса), итог — строка `kind = result` с `parent_id` вызова (код, `duration_ms`, решение `allowed`/`failed`, причина). Отказ (`denied`) — одна строка `call`, итога не ждёт. Проверка ключа владельцем — `call` + `result` как у шлюза. На экране и в `connectionJournal` итог подклеивается к вызову; разрешённый вызов без итога старше таймаута шлюза — «начато, итога нет». Лимит 60/мин считает только `call`.
|
||||
|
||||
### Цепочка по владельцу, хэш без внешних ключей
|
||||
Журнал читает владелец — цепочка тоже по `owner_id`. Хэш = `sha256(prev_hash + "\n" + JSON.stringify([id, owner_id, kind, parent_id, connection_name, project_key, agent_name, method, path, decision, reason, status_code, duration_ms, created_at_ms]))`, первая строка владельца — `prev_hash = ""`. Внешние ключи (`connection_id`, `project_id`, `session_id`, `agent_id`) в хэш не входят: при удалении подключения/проекта/сессии они становятся `null` (`onDelete: set null`), и честная цепочка сломалась бы. Вместо них — снимки `connection_name`, `project_key`, `agent_name`. Вставка — синхронная транзакция (`BEGIN IMMEDIATE`): чтение головы и вставка не разойдутся при параллельных вызовах.
|
||||
|
||||
Хэш без ключа (не HMAC) — чтобы владелец проверил выгрузку сам. Подделку «пересчитать всю цепочку» ловят контрольные точки вне таблицы: событие платформы и сообщение в канал «services».
|
||||
|
||||
### Контрольные точки
|
||||
`connectionJournalTick` (вачдог, раз в час проверяет, раз в сутки пишет): для каждого владельца `verifyConnectionJournal` и сверка с прошлой точкой (`settings` `connection.journal.checkpoint:<ownerId>` `{id, hash, at}`: строка `id` всё ещё имеет хэш `hash`). Новая голова → событие `connection_journal_checkpoint` в платформенном проекте и одна строка в общем сообщении канала «services» за день. Нарушение → `alertAdmins` + сообщение владельцу (мастер-чат и `deliverToUser`), одно на нарушение (`connection.journal.broken:<ownerId>` = id первой плохой строки). Строки до первой сохранившейся — якорь: начало цепочки берётся из `prev_hash` первой строки (на будущее, если журнал будут чистить по сроку).
|
||||
|
||||
### Envelope
|
||||
`connections.dek_enc` = `encrypt(base64(dek))` (ключ платформы), `secret_enc` = `v2.` + AES-256-GCM ключом данных (`sealWithKey`/`openWithKey` в crypto.ts, AAD `connection-secret`). Без `dek_enc` строка — старого формата (`decrypt`). `upgradeConnectionKeys` переводит старые: расшифровка и шифрование в памяти процесса, без вывода. В `encryptedColumns` вместо `connections.secret_enc` — `connections.dek_enc` и `connections.secret_enc` только у строк без `dek_enc` (вдруг перевод ещё не прошёл). `reencryptAll` перед обходом зовёт `upgradeConnectionKeys`. Расшифровка одного подключения даёт только его ключ данных.
|
||||
|
||||
### Ответы сервисов
|
||||
Шлюз отдаёт ответ агенту и ничего из него не сохраняет. Частичной выдачи (`fetch_body`) нет. Хранения нет — нечего шифровать и удалять; в спеке это требование «тело ответа не хранится и не попадает в уведомления».
|
||||
|
||||
### Выгрузка
|
||||
`exportConnectionJournal(db, userId, "jsonl" | "csv")` — все строки владельца по `id` с `prev_hash` и `hash`; `GET /api/connections/journal?format=…` (только вход, только свои). Инструкция на экране под «Подробнее»: формула и короткий скрипт Node.
|
||||
|
||||
## Risks
|
||||
- Рост журнала вдвое (две строки на вызов) — приемлемо: строки короткие, лимит 60/мин на сессию.
|
||||
- Старые строки без хэша: миграция строит цепочку для них в `upgradeConnectionJournal` (тот же вызов, что и для ключей).
|
||||
@ -0,0 +1,22 @@
|
||||
## Why
|
||||
|
||||
Журнал Access Hub (PEP-234) — обычная таблица: при доступе к базе запись можно тихо изменить или удалить, а запись появляется только после вызова сервиса — сбой посередине не оставляет следа. Все ключи подключений зашифрованы одним ключом платформы (`PEPPA_SECRET`): утечка его вместе с базой открывает все ключи сразу, а ротация перешифровывает сами секреты.
|
||||
|
||||
## What Changes
|
||||
|
||||
- **Запись до действия**: строка журнала «вызов» пишется до запроса к сервису, итог (код ответа, длительность) — отдельной строкой «итог» после. Вызов без итога виден владельцу как «начато, итога нет».
|
||||
- **Цепочка хэшей** по владельцу: каждая строка хранит хэш предыдущей и свой хэш (SHA-256 от канонической записи). `verifyConnectionJournal` проверяет цепочку.
|
||||
- **Контрольные точки** раз в сутки (`connectionJournalTick` в вачдоге): голова цепочки каждого владельца — в журнал событий платформы и в канал «services»; заодно проверка цепочек. Нарушение — одно сообщение суперадмину и владельцу.
|
||||
- **Выгрузка** журнала владельцем — JSONL и CSV с хэшами (`GET /api/connections/journal`), на экране «Подключения» — кнопки и инструкция, как проверить самому.
|
||||
- **Отдельный ключ на каждый ключ (envelope)**: у подключения свой случайный ключ данных (`connections.dek_enc` — зашифрован ключом платформы), секрет шифруется ключом данных. Ротация `PEPPA_SECRET` (`reencryptAll`) перешифровывает только ключи данных. Старые подключения переводятся `upgradeConnectionKeys` (в `peppa db migrate` и в тике вачдога) — расшифровка только в памяти процесса.
|
||||
- **Ответы сервисов** шлюз не хранит (ни целиком, ни по частям) — требование о шифровании и сроке 30 дней фиксируется в спеке как запрет хранения.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### Modified Capabilities
|
||||
- `access-hub`: журнал с записью до действия и цепочкой хэшей, контрольные точки, выгрузка, ключ данных на каждое подключение.
|
||||
|
||||
## Impact
|
||||
|
||||
- База: миграция 0030 — `connections.dek_enc`; `connection_log.kind`, `parent_id`, `project_key`, `duration_ms`, `prev_hash`, `hash`.
|
||||
- Код: `core/connections.ts`, новый `core/connection-journal.ts`, `core/crypto.ts` (шифрование ключом данных), `core/secrets-audit.ts` (`encryptedColumns`), вачдог, CLI `peppa db migrate`, веб «Подключения» и маршрут выгрузки, переводы.
|
||||
@ -0,0 +1,69 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Журнал пишется до действия
|
||||
Шлюз SHALL записывать вызов в журнал до запроса к внешнему сервису, а итог (код ответа, длительность) — отдельной записью после. Вызов без итога SHALL быть виден владельцу как «начато, итога нет».
|
||||
|
||||
#### Scenario: Итог дописывается после вызова
|
||||
- **GIVEN** агенту проекта «SHOP» разрешено «GET /items» подключения «CRM» пользователя «anna»
|
||||
- **WHEN** агент просит «GET /items/5» и сервис отвечает 200
|
||||
- **THEN** в журнале «anna» есть запись вызова «GET /items/5»
|
||||
- **AND** к ней итог с кодом 200
|
||||
|
||||
#### Scenario: Сбой посередине виден
|
||||
- **GIVEN** вызов «GET /items/5» через «CRM» записан, а процесс упал до ответа сервиса
|
||||
- **WHEN** «anna» открывает журнал через минуту
|
||||
- **THEN** у вызова видно «начато, итога нет»
|
||||
|
||||
### Requirement: Журнал защищён от подделки
|
||||
Каждая запись журнала SHALL хранить хэш предыдущей записи того же владельца и свой хэш. Проверка цепочки SHALL обнаруживать изменённую или удалённую запись. Раз в сутки голова цепочки SHALL сохраняться вне таблицы журнала (журнал событий платформы и канал «services»); о нарушении SHALL узнавать суперадмин и владелец.
|
||||
|
||||
#### Scenario: Изменённая запись обнаруживается
|
||||
- **GIVEN** в журнале «anna» три записи
|
||||
- **WHEN** во второй записи путь «/items/5» заменён на «/items/6» прямо в базе
|
||||
- **THEN** проверка журнала «anna» сообщает о нарушении на второй записи
|
||||
|
||||
#### Scenario: Нарушение доходит до людей
|
||||
- **GIVEN** запись журнала «anna» изменена в базе
|
||||
- **WHEN** проходит ежедневная проверка
|
||||
- **THEN** суперадмин получает одно сообщение о нарушении журнала
|
||||
- **AND** «anna» получает одно сообщение
|
||||
- **AND** следующая проверка того же нарушения повторно не пишет
|
||||
|
||||
#### Scenario: Пересчитанная цепочка не совпадает с контрольной точкой
|
||||
- **GIVEN** вчерашняя контрольная точка журнала «anna» сохранена
|
||||
- **WHEN** запись до неё изменена и хэши всех следующих пересчитаны
|
||||
- **THEN** проверка сообщает о нарушении
|
||||
|
||||
### Requirement: Выгрузка журнала
|
||||
Владелец SHALL выгружать свой журнал в JSONL и CSV вместе с хэшами и SHALL иметь инструкцию, как проверить цепочку самому. Чужой журнал выгрузить SHALL NOT.
|
||||
|
||||
#### Scenario: Выгрузка проверяется
|
||||
- **GIVEN** в журнале «anna» пять записей
|
||||
- **WHEN** она выгружает журнал в JSONL
|
||||
- **THEN** в файле пять строк с полями «prev_hash» и «hash»
|
||||
- **AND** пересчёт хэшей по инструкции совпадает с файлом
|
||||
|
||||
#### Scenario: Чужой журнал не выгружается
|
||||
- **GIVEN** у «anna» есть записи в журнале
|
||||
- **WHEN** «boris» запрашивает выгрузку
|
||||
- **THEN** он получает только свои записи
|
||||
|
||||
### Requirement: Отдельный ключ шифрования у каждого подключения
|
||||
У каждого подключения SHALL быть свой случайный ключ данных, которым шифруется ключ доступа; ключ данных SHALL шифроваться ключом платформы. Смена ключа платформы SHALL перешифровывать только ключи данных. Ответы сервисов шлюз SHALL NOT хранить и SHALL NOT отправлять в уведомления.
|
||||
|
||||
#### Scenario: Ключ данных одного подключения не открывает другое
|
||||
- **GIVEN** у «anna» подключения «CRM» и «Почта»
|
||||
- **WHEN** ключ данных «CRM» применяют к зашифрованному ключу «Почты»
|
||||
- **THEN** расшифровка не удаётся
|
||||
|
||||
#### Scenario: Ротация ключа платформы
|
||||
- **GIVEN** подключение «CRM» сохранено при старом ключе платформы
|
||||
- **WHEN** ключ платформы меняется и запускается перешифровка
|
||||
- **THEN** перешифрован только ключ данных «CRM», а зашифрованный ключ доступа не изменился
|
||||
- **AND** агент по-прежнему вызывает «CRM»
|
||||
|
||||
#### Scenario: Старое подключение переводится на свой ключ
|
||||
- **GIVEN** подключение «CRM» создано до этого изменения
|
||||
- **WHEN** выполняется перевод ключей
|
||||
- **THEN** у «CRM» появляется свой ключ данных
|
||||
- **AND** вызов через «CRM» работает с прежним ключом доступа
|
||||
@ -0,0 +1,16 @@
|
||||
## 1. База и шифрование
|
||||
- [x] 1.1 Схема и миграция 0030: `connections.dek_enc`; `connection_log.kind`, `parent_id`, `project_key`, `duration_ms`, `prev_hash`, `hash`
|
||||
- [x] 1.2 crypto.ts: `newDataKey`, `sealWithKey`/`openWithKey`; connections.ts: `sealConnectionSecret`/`openConnectionSecret`, `upgradeConnectionKeys`
|
||||
- [x] 1.3 secrets-audit: `encryptedColumns` — `dek_enc` (+ старые `secret_enc`), `reencryptAll` сначала переводит старые
|
||||
|
||||
## 2. Журнал
|
||||
- [x] 2.1 `core/connection-journal.ts`: хэш, `appendJournal` (синхронная транзакция), `verifyJournalRows`, `verifyConnectionJournal`, `exportConnectionJournal`, построение цепочки для старых строк
|
||||
- [x] 2.2 Шлюз и проверка ключа: вызов до запроса, итог после; лимит считает только вызовы; `connectionJournal` подклеивает итог, «начато, итога нет»
|
||||
- [x] 2.3 `connectionJournalTick`: проверка, контрольная точка (событие + канал), сообщения о нарушении; вачдог; `peppa db migrate` зовёт перевод ключей и цепочки
|
||||
|
||||
## 3. Веб
|
||||
- [x] 3.1 `GET /api/connections/journal?format=jsonl|csv`, кнопки выгрузки и инструкция; «начато, итога нет» в журнале; переводы ru/kk/en
|
||||
|
||||
## 4. Тесты и завершение
|
||||
- [x] 4.1 Тест `access-hub-journal.test.ts`: подделка, пересчёт после точки, выгрузка, сообщения, envelope, ротация, перевод старых
|
||||
- [x] 4.2 Прогон access-hub тестов, lint, typecheck; память; archive; PR
|
||||
@ -213,8 +213,17 @@ const env = loadEnv();
|
||||
if (positionals[0] === "db") {
|
||||
try {
|
||||
if (positionals[1] === "migrate") {
|
||||
migrateDb(createDb(env.PEPPA_DB));
|
||||
const mdb = createDb(env.PEPPA_DB);
|
||||
migrateDb(mdb);
|
||||
console.log(`migrated ${env.PEPPA_DB}`);
|
||||
// PEP-254: old Access Hub keys get their own data key, old journals a hash chain (in-process only).
|
||||
const core = await import("@peppa/core");
|
||||
const journal = await core.upgradeConnectionJournal(mdb).catch((e: Error) => (console.error(`connection journal: ${e.message}`), 0));
|
||||
if (journal) console.log(`connection journal: ${journal} rows chained`);
|
||||
if (env.PEPPA_SECRET) {
|
||||
const keys = await core.upgradeConnectionKeys(mdb).catch((e: Error) => (console.error(`connection keys: ${e.message}`), null));
|
||||
if (keys?.upgraded || keys?.unreadable) console.log(`connection keys: ${keys.upgraded} moved to own data keys, ${keys.unreadable} unreadable`);
|
||||
}
|
||||
} else if (positionals[1] === "backup") {
|
||||
const db = createDb(env.PEPPA_DB);
|
||||
// PEP-48: CLI commands are an admin's actions on this machine.
|
||||
|
||||
357
packages/core/src/connection-journal.ts
Normal file
357
packages/core/src/connection-journal.ts
Normal file
@ -0,0 +1,357 @@
|
||||
// PEP-254: the Access Hub journal can't be changed quietly.
|
||||
// Every row of an owner carries the hash of the owner's previous row and its own:
|
||||
// hash = sha256(prev_hash + "\n" + JSON.stringify([id, owner_id, kind, parent_id, connection,
|
||||
// project, agent, method, path, decision, reason, status_code, duration_ms, created_at]))
|
||||
// (created_at in ms; the first row of an owner has prev_hash ""). Foreign keys are not hashed —
|
||||
// they turn null when a connection, project or session is deleted; their name snapshots are.
|
||||
// The hash has no key, so an owner can check an export alone; rewriting the whole chain is caught
|
||||
// by daily checkpoints kept outside the table (platform journal + the «services» channel).
|
||||
import { asIs, m as tr } from "@peppa/shared/i18n";
|
||||
import { connectionLog, projects, users, type Db } from "@peppa/db";
|
||||
import { and, asc, desc, eq, isNotNull, isNull, sql } from "drizzle-orm";
|
||||
import { createHash } from "node:crypto";
|
||||
import { logEvent } from "./audit.ts";
|
||||
import { addMasterMessage } from "./chats.ts";
|
||||
import { alertAdmins } from "./monitor.ts";
|
||||
import { deliverToUser } from "./notifications.ts";
|
||||
import { platformProjectKey, postToChannel } from "./platform-channel.ts";
|
||||
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
|
||||
|
||||
export type ConnectionJournalKind = "call" | "result";
|
||||
export type ConnectionJournalDecision = "allowed" | "denied" | "failed";
|
||||
|
||||
/** What a gateway decision writes; ids and the hash are added by `appendJournal`. */
|
||||
export interface ConnectionJournalEntry {
|
||||
ownerId: number;
|
||||
kind: ConnectionJournalKind;
|
||||
parentId?: number | null;
|
||||
connectionId: number | null;
|
||||
connectionName: string | null;
|
||||
projectId?: number | null;
|
||||
projectKey?: string | null;
|
||||
sessionId?: number | null;
|
||||
agentId?: number | null;
|
||||
agentName?: string | null;
|
||||
method: string;
|
||||
path: string;
|
||||
decision: ConnectionJournalDecision;
|
||||
reason: string | null;
|
||||
statusCode: number | null;
|
||||
durationMs?: number | null;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
/** One row as exported and as hashed (snake_case — the same names as in the file). */
|
||||
export interface ConnectionJournalRecord {
|
||||
id: number;
|
||||
owner_id: number;
|
||||
kind: ConnectionJournalKind;
|
||||
parent_id: number | null;
|
||||
connection: string | null;
|
||||
project: string | null;
|
||||
agent: string | null;
|
||||
method: string;
|
||||
path: string;
|
||||
decision: ConnectionJournalDecision;
|
||||
reason: string | null;
|
||||
status_code: number | null;
|
||||
duration_ms: number | null;
|
||||
created_at: number;
|
||||
prev_hash: string | null;
|
||||
hash: string | null;
|
||||
}
|
||||
|
||||
export function journalCanonical(r: Omit<ConnectionJournalRecord, "prev_hash" | "hash">): string {
|
||||
return JSON.stringify([r.id, r.owner_id, r.kind, r.parent_id, r.connection, r.project, r.agent, r.method, r.path, r.decision, r.reason, r.status_code, r.duration_ms, r.created_at]);
|
||||
}
|
||||
|
||||
export const journalHash = (prevHash: string, r: Omit<ConnectionJournalRecord, "prev_hash" | "hash">): string =>
|
||||
createHash("sha256").update(`${prevHash}\n${journalCanonical(r)}`).digest("hex");
|
||||
|
||||
type LogRow = typeof connectionLog.$inferSelect;
|
||||
|
||||
export const toRecord = (r: LogRow): ConnectionJournalRecord => ({
|
||||
id: r.id,
|
||||
owner_id: r.ownerId!,
|
||||
kind: r.kind,
|
||||
parent_id: r.parentId ?? null,
|
||||
connection: r.connectionName ?? null,
|
||||
project: r.projectKey ?? null,
|
||||
agent: r.agentName ?? null,
|
||||
method: r.method,
|
||||
path: r.path,
|
||||
decision: r.decision,
|
||||
reason: r.reason ?? null,
|
||||
status_code: r.statusCode ?? null,
|
||||
duration_ms: r.durationMs ?? null,
|
||||
created_at: r.createdAt.getTime(),
|
||||
prev_hash: r.prevHash ?? null,
|
||||
hash: r.hash ?? null,
|
||||
});
|
||||
|
||||
/**
|
||||
* Appends one row to the owner's chain. One synchronous transaction (BEGIN IMMEDIATE): reading
|
||||
* the head and inserting can't interleave with another call of the same owner.
|
||||
*/
|
||||
export function appendJournal(db: Db, e: ConnectionJournalEntry): number {
|
||||
return db.transaction((tx) => {
|
||||
const head = tx
|
||||
.select({ hash: connectionLog.hash })
|
||||
.from(connectionLog)
|
||||
.where(and(eq(connectionLog.ownerId, e.ownerId), isNotNull(connectionLog.hash)))
|
||||
.orderBy(desc(connectionLog.id))
|
||||
.limit(1)
|
||||
.get();
|
||||
const projectKey = e.projectKey ?? (e.projectId ? (tx.select({ key: projects.key }).from(projects).where(eq(projects.id, e.projectId)).get()?.key ?? null) : null);
|
||||
const prevHash = head?.hash ?? "";
|
||||
const row = tx
|
||||
.insert(connectionLog)
|
||||
.values({
|
||||
ownerId: e.ownerId,
|
||||
kind: e.kind,
|
||||
parentId: e.parentId ?? null,
|
||||
connectionId: e.connectionId,
|
||||
connectionName: e.connectionName,
|
||||
projectId: e.projectId ?? null,
|
||||
projectKey,
|
||||
sessionId: e.sessionId ?? null,
|
||||
agentId: e.agentId ?? null,
|
||||
agentName: e.agentName ?? null,
|
||||
method: e.method,
|
||||
path: e.path,
|
||||
decision: e.decision,
|
||||
reason: e.reason,
|
||||
statusCode: e.statusCode,
|
||||
durationMs: e.durationMs ?? null,
|
||||
createdAt: e.createdAt,
|
||||
prevHash,
|
||||
})
|
||||
.returning()
|
||||
.get();
|
||||
const hash = journalHash(prevHash, toRecord(row));
|
||||
tx.update(connectionLog).set({ hash }).where(eq(connectionLog.id, row.id)).run();
|
||||
return row.id;
|
||||
});
|
||||
}
|
||||
|
||||
export type ConnectionJournalBreak = "hash" | "link" | "missing_hash" | "checkpoint";
|
||||
|
||||
export interface ConnectionJournalVerdict {
|
||||
ok: boolean;
|
||||
/** Rows checked (hashed ones). */
|
||||
checked: number;
|
||||
/** Rows written before the journal was protected (no hash, before the first hashed row). */
|
||||
unprotected: number;
|
||||
head: { id: number; hash: string } | null;
|
||||
first: { id: number; hash: string } | null;
|
||||
brokenAt?: number;
|
||||
reason?: ConnectionJournalBreak;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks a chain (rows of ONE owner, any order). Leading rows without a hash are older than
|
||||
* PEP-254 and are not checked; the first hashed row anchors the chain (its prev_hash is taken).
|
||||
* Works on exported records too — the same code an owner could run.
|
||||
*/
|
||||
export function verifyJournalRows(input: ConnectionJournalRecord[]): ConnectionJournalVerdict {
|
||||
const rows = [...input].sort((a, b) => a.id - b.id);
|
||||
let i = 0;
|
||||
while (i < rows.length && rows[i]!.hash == null) i++;
|
||||
const out: ConnectionJournalVerdict = { ok: true, checked: 0, unprotected: i, head: null, first: null };
|
||||
let prev: string | null = null;
|
||||
for (; i < rows.length; i++) {
|
||||
const r = rows[i]!;
|
||||
const fail = (reason: ConnectionJournalBreak) => ({ ...out, ok: false, brokenAt: r.id, reason });
|
||||
if (r.hash == null || r.prev_hash == null) return fail("missing_hash");
|
||||
if (prev !== null && r.prev_hash !== prev) return fail("link");
|
||||
if (journalHash(r.prev_hash, r) !== r.hash) return fail("hash");
|
||||
if (!out.first) out.first = { id: r.id, hash: r.hash };
|
||||
out.head = { id: r.id, hash: r.hash };
|
||||
prev = r.hash;
|
||||
out.checked++;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export interface ConnectionJournalCheckpoint {
|
||||
id: number;
|
||||
hash: string;
|
||||
firstId: number;
|
||||
firstHash: string;
|
||||
at: number;
|
||||
}
|
||||
|
||||
const checkpointKey = (ownerId: number) => `connection.journal.checkpoint:${ownerId}`;
|
||||
const brokenKey = (ownerId: number) => `connection.journal.broken:${ownerId}`;
|
||||
|
||||
export const getJournalCheckpoint = (db: Db, ownerId: number) => getSetting<ConnectionJournalCheckpoint>(db, checkpointKey(ownerId));
|
||||
|
||||
async function ownerRows(db: Db, ownerId: number): Promise<ConnectionJournalRecord[]> {
|
||||
return (await db.select().from(connectionLog).where(eq(connectionLog.ownerId, ownerId)).orderBy(asc(connectionLog.id))).map(toRecord);
|
||||
}
|
||||
|
||||
/**
|
||||
* The owner's chain plus the last checkpoint: the row it names must still be there with the same
|
||||
* hash, and so must the first row — a chain rewritten from scratch doesn't pass.
|
||||
*/
|
||||
export async function verifyConnectionJournal(db: Db, ownerId: number): Promise<ConnectionJournalVerdict> {
|
||||
const rows = await ownerRows(db, ownerId);
|
||||
const v = verifyJournalRows(rows);
|
||||
if (!v.ok) return v;
|
||||
const cp = await getJournalCheckpoint(db, ownerId);
|
||||
if (cp) {
|
||||
const byId = new Map(rows.map((r) => [r.id, r]));
|
||||
if (byId.get(cp.firstId)?.hash !== cp.firstHash) return { ...v, ok: false, brokenAt: cp.firstId, reason: "checkpoint" };
|
||||
if (byId.get(cp.id)?.hash !== cp.hash) return { ...v, ok: false, brokenAt: cp.id, reason: "checkpoint" };
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives a hash chain to owners whose journal has none yet (rows from before PEP-254). Owners that
|
||||
* already have a chain keep their older rows as «before protection».
|
||||
*/
|
||||
export async function upgradeConnectionJournal(db: Db): Promise<number> {
|
||||
const owners = await db
|
||||
.select({ ownerId: connectionLog.ownerId })
|
||||
.from(connectionLog)
|
||||
.where(isNotNull(connectionLog.ownerId))
|
||||
.groupBy(connectionLog.ownerId)
|
||||
.having(sql`count(${connectionLog.hash}) = 0`);
|
||||
let n = 0;
|
||||
for (const { ownerId } of owners) {
|
||||
n += db.transaction((tx) => {
|
||||
if (tx.select({ id: connectionLog.id }).from(connectionLog).where(and(eq(connectionLog.ownerId, ownerId!), isNotNull(connectionLog.hash))).limit(1).get()) return 0;
|
||||
const rows = tx.select().from(connectionLog).where(and(eq(connectionLog.ownerId, ownerId!), isNull(connectionLog.hash))).orderBy(asc(connectionLog.id)).all();
|
||||
let prev = "";
|
||||
for (const r of rows) {
|
||||
const hash = journalHash(prev, toRecord(r));
|
||||
tx.update(connectionLog).set({ prevHash: prev, hash }).where(eq(connectionLog.id, r.id)).run();
|
||||
prev = hash;
|
||||
}
|
||||
return rows.length;
|
||||
});
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
// ---------- export ----------
|
||||
|
||||
export const JOURNAL_EXPORT_FIELDS = ["id", "owner_id", "kind", "parent_id", "connection", "project", "agent", "method", "path", "decision", "reason", "status_code", "duration_ms", "created_at", "prev_hash", "hash"] as const;
|
||||
|
||||
const csvCell = (v: unknown) => {
|
||||
if (v == null) return "";
|
||||
const s = String(v);
|
||||
// A leading = + - @ would be a formula in a spreadsheet: quote it with an apostrophe.
|
||||
const safe = /^[=+\-@\t\r]/.test(s) ? `'${s}` : s;
|
||||
return /[",\n\r]/.test(safe) ? `"${safe.replace(/"/g, '""')}"` : safe;
|
||||
};
|
||||
|
||||
/** The owner's whole journal with hashes, oldest first. Only the owner's own rows. */
|
||||
export async function exportConnectionJournal(db: Db, ownerId: number, format: "jsonl" | "csv"): Promise<string> {
|
||||
const rows = await ownerRows(db, ownerId);
|
||||
if (format === "jsonl") return rows.map((r) => JSON.stringify(Object.fromEntries(JOURNAL_EXPORT_FIELDS.map((f) => [f, r[f]])))).join("\n") + (rows.length ? "\n" : "");
|
||||
return [JOURNAL_EXPORT_FIELDS.join(","), ...rows.map((r) => JOURNAL_EXPORT_FIELDS.map((f) => csvCell(r[f])).join(","))].join("\n") + "\n";
|
||||
}
|
||||
|
||||
/** Reads an exported JSONL back (for checking it). */
|
||||
export const parseJournalJsonl = (text: string): ConnectionJournalRecord[] =>
|
||||
text
|
||||
.split("\n")
|
||||
.filter((l) => l.trim())
|
||||
.map((l) => JSON.parse(l) as ConnectionJournalRecord);
|
||||
|
||||
/** A self-contained Node script that checks an exported JSONL (shown on the «Подключения» page). */
|
||||
export const JOURNAL_VERIFY_SCRIPT = `// node verify.mjs journal.jsonl
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFileSync } from "node:fs";
|
||||
const rows = readFileSync(process.argv[2], "utf8").split("\\n").filter(Boolean).map((l) => JSON.parse(l));
|
||||
let prev = null, bad = 0;
|
||||
for (const r of rows) {
|
||||
if (r.hash == null) continue; // written before the protection
|
||||
const body = JSON.stringify([r.id, r.owner_id, r.kind, r.parent_id, r.connection, r.project, r.agent, r.method, r.path, r.decision, r.reason, r.status_code, r.duration_ms, r.created_at]);
|
||||
const h = createHash("sha256").update(r.prev_hash + "\\n" + body).digest("hex");
|
||||
if ((prev !== null && r.prev_hash !== prev) || h !== r.hash) { console.log("BROKEN at id", r.id); bad++; break; }
|
||||
prev = r.hash;
|
||||
}
|
||||
console.log(bad ? "journal changed" : "ok, head " + prev);
|
||||
`;
|
||||
|
||||
// ---------- daily checkpoint and check ----------
|
||||
|
||||
const CHECKPOINT_EVERY_MS = 24 * 3600_000;
|
||||
const TICK_EVERY_MS = 3600_000;
|
||||
let lastTick = 0;
|
||||
|
||||
export interface ConnectionJournalTickResult {
|
||||
checked: number;
|
||||
checkpoints: number;
|
||||
broken: number[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Watchdog, once an hour: moves old keys and journals onto PEP-254, checks every owner's chain,
|
||||
* once a day per owner writes a checkpoint (platform journal event + one «services» channel post
|
||||
* for the day). A broken chain — one message to the superadmins and to the owner per break.
|
||||
*/
|
||||
export async function connectionJournalTick(db: Db, o: { now?: Date; force?: boolean; log?: (m: string) => void } = {}): Promise<ConnectionJournalTickResult> {
|
||||
const now = o.now ?? new Date();
|
||||
const out: ConnectionJournalTickResult = { checked: 0, checkpoints: 0, broken: [] };
|
||||
if (process.env.PEPPA_CONNECTION_JOURNAL === "off") return out;
|
||||
if (!o.force && now.getTime() - lastTick < TICK_EVERY_MS) return out;
|
||||
lastTick = now.getTime();
|
||||
const log = o.log ?? (() => {});
|
||||
const { upgradeConnectionKeys } = await import("./connections.ts");
|
||||
await upgradeConnectionKeys(db).catch(() => null);
|
||||
await upgradeConnectionJournal(db);
|
||||
|
||||
const owners = (await db.select({ ownerId: connectionLog.ownerId }).from(connectionLog).where(isNotNull(connectionLog.hash)).groupBy(connectionLog.ownerId)).map((r) => r.ownerId!);
|
||||
const [platform] = await db.select({ id: projects.id }).from(projects).where(eq(projects.key, platformProjectKey()));
|
||||
const heads: string[] = [];
|
||||
for (const ownerId of owners) {
|
||||
out.checked++;
|
||||
const v = await verifyConnectionJournal(db, ownerId);
|
||||
if (!v.ok) {
|
||||
out.broken.push(ownerId);
|
||||
await reportBreak(db, ownerId, v, log);
|
||||
continue;
|
||||
}
|
||||
await deleteSetting(db, brokenKey(ownerId));
|
||||
const cp = await getJournalCheckpoint(db, ownerId);
|
||||
if (!v.head || !v.first) continue;
|
||||
if (cp && (cp.id === v.head.id || now.getTime() - cp.at < CHECKPOINT_EVERY_MS)) continue;
|
||||
const next: ConnectionJournalCheckpoint = { id: v.head.id, hash: v.head.hash, firstId: v.first.id, firstHash: v.first.hash, at: now.getTime() };
|
||||
await setSetting(db, checkpointKey(ownerId), next);
|
||||
if (platform) await logEvent(db, { projectId: platform.id, type: "connection_journal_checkpoint", payload: { ownerId, headId: next.id, headHash: next.hash, firstId: next.firstId, firstHash: next.firstHash } });
|
||||
heads.push(`u${ownerId} #${next.id} <code>${next.hash.slice(0, 16)}</code>`);
|
||||
out.checkpoints++;
|
||||
}
|
||||
if (heads.length) {
|
||||
// glossary-ignore: the «services» channel is read by the platform's engineers.
|
||||
const html = `${tr("Журнал подключений: контрольные точки")}\n${heads.join("\n")}`;
|
||||
await postToChannel(db, "services", `mon:ch:connection-journal:${now.toISOString().slice(0, 13)}`, html).catch(() => false);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function reportBreak(db: Db, ownerId: number, v: ConnectionJournalVerdict, log: (m: string) => void): Promise<void> {
|
||||
const seen = await getSetting<{ id: number }>(db, brokenKey(ownerId));
|
||||
if (seen?.id === v.brokenAt) return; // already told about this break
|
||||
await setSetting(db, brokenKey(ownerId), { id: v.brokenAt, reason: v.reason, at: Date.now() });
|
||||
const [u] = await db.select().from(users).where(eq(users.id, ownerId));
|
||||
const [platform] = await db.select({ id: projects.id }).from(projects).where(eq(projects.key, platformProjectKey()));
|
||||
if (platform) await logEvent(db, { projectId: platform.id, type: "connection_journal_broken", payload: { ownerId, id: v.brokenAt, reason: v.reason } });
|
||||
const admin = tr("Журнал подключений пользователя {login} изменён в обход FORGE (запись {id}). Проверьте доступ к базе.", { login: asIs(u?.login ?? `#${ownerId}`), id: v.brokenAt ?? 0 });
|
||||
await alertAdmins(db, `connection-journal:${ownerId}:${v.brokenAt}`, admin, log).catch(() => 0);
|
||||
if (!u || u.disabledAt) return;
|
||||
const text = tr("Журнал ваших подключений изменён в обход FORGE. Администратор уже знает и разбирается; ключи доступа лучше заменить в разделе «Подключения».");
|
||||
const key = `connection-journal:${ownerId}:${v.brokenAt}`;
|
||||
await addMasterMessage(db, ownerId, { kind: "event", important: true, text, dedupeKey: `master:${key}`, url: "/connections" }).catch(() => null);
|
||||
await deliverToUser(db, u, {
|
||||
event: "failures",
|
||||
dedupeKey: `${key}:${u.telegramChatId}`,
|
||||
pushKey: `${key}:u${u.id}`,
|
||||
telegram: { params: { text } },
|
||||
push: { title: tr("FORGE"), body: text, url: "/connections", tag: "connection-journal" },
|
||||
}).catch(() => null);
|
||||
}
|
||||
@ -7,7 +7,7 @@
|
||||
// pep-234-access-hub (design.md — threat model).
|
||||
import { asIs, m as tr } from "@peppa/shared/i18n";
|
||||
import { agents, connectionGrants, connectionLog, connections, projects, sessions, users, type Db } from "@peppa/db";
|
||||
import { and, asc, count, desc, eq, gt, inArray } from "drizzle-orm";
|
||||
import { and, asc, count, desc, eq, gt, inArray, isNotNull, isNull, sql } from "drizzle-orm";
|
||||
import { lookup as dnsLookup, type LookupAddress } from "node:dns";
|
||||
import { request as httpRequest, type IncomingMessage } from "node:http";
|
||||
import { request as httpsRequest } from "node:https";
|
||||
@ -15,7 +15,8 @@ import { isIP } from "node:net";
|
||||
import { logEvent } from "./audit.ts";
|
||||
import { catalogService, classifyRequest, type CatalogAuth, type CatalogCheck } from "./connection-catalog.ts";
|
||||
import { addMasterMessage } from "./chats.ts";
|
||||
import { decrypt, encrypt } from "./crypto.ts";
|
||||
import { appendJournal, type ConnectionJournalDecision } from "./connection-journal.ts";
|
||||
import { decrypt, encrypt, newDataKey, openWithKey, sealWithKey } from "./crypto.ts";
|
||||
import { deliverToUser } from "./notifications.ts";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
import { maskSecrets } from "./secrets.ts";
|
||||
@ -130,6 +131,10 @@ export interface ConnectionLogView {
|
||||
decision: "allowed" | "denied" | "failed";
|
||||
reason: string | null;
|
||||
statusCode: number | null;
|
||||
/** PEP-254: how long the service took (from the result row). */
|
||||
durationMs: number | null;
|
||||
/** done — a decision or a result is written; running — the call is in flight; unfinished — started, no result (a crash in the middle). */
|
||||
state: "done" | "running" | "unfinished";
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
@ -249,6 +254,49 @@ function secretError(secret: string): string | null {
|
||||
const HEADER_RE = /^[A-Za-z][A-Za-z0-9-]{0,63}$/;
|
||||
const FORBIDDEN_HEADERS = new Set(["host", "content-length", "content-type", "transfer-encoding", "connection", "cookie", "accept-encoding"]);
|
||||
|
||||
// ---------- PEP-254: one data key per connection (envelope) ----------
|
||||
|
||||
const SECRET_V2 = "v2.";
|
||||
const SECRET_AAD = "connection-secret";
|
||||
|
||||
/**
|
||||
* Encrypts a connection key with a fresh data key of its own; the data key goes under
|
||||
* PEPPA_SECRET. Decrypting one connection's data key opens nothing else.
|
||||
*/
|
||||
export function sealConnectionSecret(secret: string): { secretEnc: string; dekEnc: string } {
|
||||
const dek = newDataKey();
|
||||
return { secretEnc: SECRET_V2 + sealWithKey(dek, secret, SECRET_AAD), dekEnc: encrypt(dek.toString("base64url")) };
|
||||
}
|
||||
|
||||
/** The key of a connection (gateway and check only — never returned anywhere else). */
|
||||
export function openConnectionSecret(c: { secretEnc: string | null; dekEnc: string | null }): string | null {
|
||||
if (!c.secretEnc) return null;
|
||||
if (!c.dekEnc || !c.secretEnc.startsWith(SECRET_V2)) return decrypt(c.secretEnc); // an old row
|
||||
return openWithKey(Buffer.from(decrypt(c.dekEnc), "base64url"), c.secretEnc.slice(SECRET_V2.length), SECRET_AAD);
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves connections stored before PEP-254 (secret under PEPPA_SECRET) to their own data key.
|
||||
* The key is decrypted and re-encrypted inside this process only. Unreadable rows are skipped.
|
||||
*/
|
||||
export async function upgradeConnectionKeys(db: Db): Promise<{ upgraded: number; unreadable: number }> {
|
||||
const rows = await db.select({ id: connections.id, secretEnc: connections.secretEnc }).from(connections).where(and(isNotNull(connections.secretEnc), isNull(connections.dekEnc)));
|
||||
let upgraded = 0;
|
||||
let unreadable = 0;
|
||||
for (const r of rows) {
|
||||
let plain: string;
|
||||
try {
|
||||
plain = decrypt(r.secretEnc!);
|
||||
} catch {
|
||||
unreadable++;
|
||||
continue;
|
||||
}
|
||||
await db.update(connections).set(sealConnectionSecret(plain)).where(and(eq(connections.id, r.id), isNull(connections.dekEnc)));
|
||||
upgraded++;
|
||||
}
|
||||
return { upgraded, unreadable };
|
||||
}
|
||||
|
||||
export interface ConnectionInput {
|
||||
/** Default: the catalog card's name. */
|
||||
name?: string;
|
||||
@ -303,7 +351,7 @@ export async function createConnection(db: Db, userId: number, i: ConnectionInpu
|
||||
const [dup] = await db.select({ id: connections.id }).from(connections).where(and(eq(connections.ownerId, userId), eq(connections.name, name)));
|
||||
if (dup) throw new PeppaError(tr("Подключение «{name}» уже есть", { name }));
|
||||
const slug = await freeSlug(db, userId, card?.id ?? slugify(name));
|
||||
const [row] = await db.insert(connections).values({ ownerId: userId, name, baseUrl, authKind, authHeader, catalogId: card?.id ?? null, slug, secretEnc: encrypt(i.secret) }).returning({ id: connections.id });
|
||||
const [row] = await db.insert(connections).values({ ownerId: userId, name, baseUrl, authKind, authHeader, catalogId: card?.id ?? null, slug, ...sealConnectionSecret(i.secret) }).returning({ id: connections.id });
|
||||
return (await listConnections(db, userId)).find((c) => c.id === row!.id)!;
|
||||
}
|
||||
|
||||
@ -313,7 +361,7 @@ export async function replaceConnectionSecret(db: Db, userId: number, connection
|
||||
const err = secretError(secret) ?? keyShapeError(c.authKind, secret);
|
||||
if (err) throw new PeppaError(err);
|
||||
// A new key: the old check result and the «key stopped working» message no longer apply.
|
||||
await db.update(connections).set({ secretEnc: encrypt(secret), status: "active", revokedAt: null, checkStatus: null, checkedAt: null, checkAlertedAt: null }).where(eq(connections.id, connectionId));
|
||||
await db.update(connections).set({ ...sealConnectionSecret(secret), status: "active", revokedAt: null, checkStatus: null, checkedAt: null, checkAlertedAt: null }).where(eq(connections.id, connectionId));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -323,7 +371,7 @@ export async function replaceConnectionSecret(db: Db, userId: number, connection
|
||||
*/
|
||||
export async function revokeConnection(db: Db, userId: number, connectionId: number): Promise<void> {
|
||||
const c = await ownConnection(db, userId, connectionId);
|
||||
await db.update(connections).set({ status: "revoked", secretEnc: null, revokedAt: new Date() }).where(eq(connections.id, c.id));
|
||||
await db.update(connections).set({ status: "revoked", secretEnc: null, dekEnc: null, revokedAt: new Date() }).where(eq(connections.id, c.id));
|
||||
const grants = await db.select({ projectId: connectionGrants.projectId }).from(connectionGrants).where(eq(connectionGrants.connectionId, c.id));
|
||||
for (const projectId of new Set(grants.map((g) => g.projectId))) await logEvent(db, { projectId, type: "connection_revoked", payload: { connectionId: c.id } });
|
||||
}
|
||||
@ -431,13 +479,13 @@ export async function listConnections(db: Db, userId: number): Promise<Connectio
|
||||
}
|
||||
|
||||
/** The owner's journal (all their connections, or one). */
|
||||
export async function connectionJournal(db: Db, userId: number, o: { connectionId?: number; limit?: number } = {}): Promise<ConnectionLogView[]> {
|
||||
return db
|
||||
export async function connectionJournal(db: Db, userId: number, o: { connectionId?: number; limit?: number; now?: Date } = {}): Promise<ConnectionLogView[]> {
|
||||
const calls = await db
|
||||
.select({
|
||||
id: connectionLog.id,
|
||||
connectionId: connectionLog.connectionId,
|
||||
connectionName: connectionLog.connectionName,
|
||||
projectKey: projects.key,
|
||||
projectKey: sql<string | null>`coalesce(${connectionLog.projectKey}, ${projects.key})`,
|
||||
agentName: connectionLog.agentName,
|
||||
sessionId: connectionLog.sessionId,
|
||||
method: connectionLog.method,
|
||||
@ -445,13 +493,26 @@ export async function connectionJournal(db: Db, userId: number, o: { connectionI
|
||||
decision: connectionLog.decision,
|
||||
reason: connectionLog.reason,
|
||||
statusCode: connectionLog.statusCode,
|
||||
durationMs: connectionLog.durationMs,
|
||||
createdAt: connectionLog.createdAt,
|
||||
})
|
||||
.from(connectionLog)
|
||||
.leftJoin(projects, eq(projects.id, connectionLog.projectId))
|
||||
.where(and(eq(connectionLog.ownerId, userId), o.connectionId != null ? eq(connectionLog.connectionId, o.connectionId) : undefined))
|
||||
.where(and(eq(connectionLog.ownerId, userId), eq(connectionLog.kind, "call"), o.connectionId != null ? eq(connectionLog.connectionId, o.connectionId) : undefined))
|
||||
.orderBy(desc(connectionLog.id))
|
||||
.limit(Math.min(o.limit ?? 100, 500));
|
||||
// PEP-254: an allowed call is written before the request; its result is a row of its own.
|
||||
const ids = calls.filter((c) => c.decision === "allowed" && c.statusCode == null).map((c) => c.id);
|
||||
const results = ids.length ? await db.select().from(connectionLog).where(and(eq(connectionLog.ownerId, userId), eq(connectionLog.kind, "result"), inArray(connectionLog.parentId, ids))) : [];
|
||||
const byParent = new Map(results.map((r) => [r.parentId!, r]));
|
||||
const now = (o.now ?? new Date()).getTime();
|
||||
return calls.map((c) => {
|
||||
const r = byParent.get(c.id);
|
||||
if (r) return { ...c, decision: r.decision, reason: r.reason, statusCode: r.statusCode, durationMs: r.durationMs, state: "done" as const };
|
||||
const open = c.decision === "allowed" && c.statusCode == null && ids.includes(c.id);
|
||||
if (!open) return { ...c, state: "done" as const };
|
||||
return { ...c, state: now - c.createdAt.getTime() > CONNECTION_TIMEOUT_MS * 2 ? ("unfinished" as const) : ("running" as const) };
|
||||
});
|
||||
}
|
||||
|
||||
/** Agents to choose from in a grant (the platform's team). */
|
||||
@ -654,10 +715,13 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?:
|
||||
const s = await sessionCtx(db, call.sessionId);
|
||||
let conn: typeof connections.$inferSelect | null = null;
|
||||
|
||||
const record = async (decision: "allowed" | "denied" | "failed", reason: ConnectionReason | null, statusCode: number | null) => {
|
||||
if (!conn) return; // nothing to attribute: an unknown connection is not someone's journal
|
||||
await db.insert(connectionLog).values({
|
||||
// PEP-254: every row goes into the owner's hash chain; an allowed call is written BEFORE the request.
|
||||
const record = async (decision: ConnectionJournalDecision, reason: ConnectionReason | null, statusCode: number | null, extra: { kind?: "call" | "result"; parentId?: number; durationMs?: number } = {}): Promise<number | null> => {
|
||||
if (!conn) return null; // nothing to attribute: an unknown connection is not someone's journal
|
||||
return appendJournal(db, {
|
||||
ownerId: conn.ownerId,
|
||||
kind: extra.kind ?? "call",
|
||||
parentId: extra.parentId ?? null,
|
||||
connectionId: conn.id,
|
||||
connectionName: conn.name,
|
||||
projectId: s?.projectId ?? null,
|
||||
@ -669,7 +733,8 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?:
|
||||
decision,
|
||||
reason,
|
||||
statusCode,
|
||||
createdAt: now,
|
||||
durationMs: extra.durationMs ?? null,
|
||||
createdAt: extra.kind === "result" ? new Date(now.getTime() + (extra.durationMs ?? 0)) : now,
|
||||
});
|
||||
};
|
||||
const deny = async (reason: ConnectionReason): Promise<ConnectionResult> => {
|
||||
@ -707,12 +772,12 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?:
|
||||
if (body && (body.length > CONNECTION_BODY_MAX_BYTES || method === "GET")) return deny("bad_request");
|
||||
const contentType = call.contentType?.trim() || (body ? "application/json" : null);
|
||||
if (contentType && !CONTENT_TYPE_RE.test(contentType)) return deny("bad_request");
|
||||
const [{ n }] = (await db.select({ n: count() }).from(connectionLog).where(and(eq(connectionLog.sessionId, s.id), gt(connectionLog.createdAt, new Date(now.getTime() - 60_000))))) as [{ n: number }];
|
||||
const [{ n }] = (await db.select({ n: count() }).from(connectionLog).where(and(eq(connectionLog.sessionId, s.id), eq(connectionLog.kind, "call"), gt(connectionLog.createdAt, new Date(now.getTime() - 60_000))))) as [{ n: number }];
|
||||
if (n >= CONNECTION_RATE_PER_MIN) return deny("rate_limited");
|
||||
|
||||
let secret: string;
|
||||
try {
|
||||
secret = decrypt(conn.secretEnc);
|
||||
secret = openConnectionSecret(conn)!;
|
||||
} catch {
|
||||
await record("failed", "upstream_error", null);
|
||||
return { ok: false, reason: "upstream_error" };
|
||||
@ -722,19 +787,25 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?:
|
||||
if (!built) return deny("bad_path");
|
||||
const { url, headers } = built;
|
||||
|
||||
// Written before the service is called: a crash in the middle leaves «started, no result».
|
||||
const callId = (await record("allowed", null, null))!;
|
||||
const started = Date.now();
|
||||
const result = (decision: ConnectionJournalDecision, reason: ConnectionReason | null, statusCode: number | null) =>
|
||||
record(decision, reason, statusCode, { kind: "result", parentId: callId, durationMs: Date.now() - started });
|
||||
try {
|
||||
const res = await (o.fetch ?? defaultConnectionFetch)({ url, method, headers, body });
|
||||
if (res.status >= 300 && res.status < 400 && res.location) {
|
||||
await record("failed", "redirect", res.status);
|
||||
await result("failed", "redirect", res.status);
|
||||
return { ok: false, reason: "redirect", status: res.status };
|
||||
}
|
||||
await record("allowed", res.truncated ? "too_large" : null, res.status);
|
||||
await result("allowed", res.truncated ? "too_large" : null, res.status);
|
||||
await db.update(connections).set({ lastUsedAt: now }).where(eq(connections.id, conn.id));
|
||||
// The answer goes to the agent only: nothing of it is stored or sent anywhere (PEP-254).
|
||||
const text = maskSecrets(res.body.toString("utf8"), secret.length >= 4 ? [secret] : []);
|
||||
return { ok: true, status: res.status, contentType: res.contentType, body: text, truncated: res.truncated };
|
||||
} catch (e) {
|
||||
const reason = e instanceof Refused ? e.reason : "upstream_error";
|
||||
await record(reason === "blocked_address" ? "denied" : "failed", reason, null);
|
||||
await result(reason === "blocked_address" ? "denied" : "failed", reason, null);
|
||||
return { ok: false, reason };
|
||||
}
|
||||
}
|
||||
@ -773,9 +844,12 @@ async function runCheck(db: Db, conn: typeof connections.$inferSelect, o: { fetc
|
||||
const raw = check?.path ?? "/";
|
||||
const clean = cleanPath(raw) ?? { path: "/", query: "" };
|
||||
let res: { status: number; body: string } | null = null;
|
||||
let secret = "";
|
||||
// PEP-254: the check is journaled like a gateway call — the call first, its result after.
|
||||
const entry = { ownerId: conn.ownerId, connectionId: conn.id, connectionName: conn.name, method, path: clean.path.slice(0, 300), createdAt: now };
|
||||
const callId = appendJournal(db, { ...entry, kind: "call", decision: "allowed", reason: "owner_check", statusCode: null });
|
||||
const started = Date.now();
|
||||
try {
|
||||
secret = decrypt(conn.secretEnc!);
|
||||
const secret = openConnectionSecret(conn)!;
|
||||
const built = buildRequest(conn, secret, clean, null, null);
|
||||
if (built) {
|
||||
// Own service: the check is the base address itself (no trailing «/» added).
|
||||
@ -787,17 +861,8 @@ async function runCheck(db: Db, conn: typeof connections.$inferSelect, o: { fetc
|
||||
res = null;
|
||||
}
|
||||
const verdict = judgeCheck(check, res);
|
||||
await db.insert(connectionLog).values({
|
||||
ownerId: conn.ownerId,
|
||||
connectionId: conn.id,
|
||||
connectionName: conn.name,
|
||||
method,
|
||||
path: clean.path.slice(0, 300),
|
||||
decision: verdict.status === "ok" ? "allowed" : "failed",
|
||||
reason: "owner_check",
|
||||
statusCode: res?.status ?? null,
|
||||
createdAt: now,
|
||||
});
|
||||
const durationMs = Date.now() - started;
|
||||
appendJournal(db, { ...entry, kind: "result", parentId: callId, decision: verdict.status === "ok" ? "allowed" : "failed", reason: "owner_check", statusCode: res?.status ?? null, durationMs, createdAt: new Date(now.getTime() + durationMs) });
|
||||
const patch: Partial<typeof connections.$inferInsert> = { checkStatus: verdict.status, checkedAt: now };
|
||||
if (verdict.status === "ok") patch.checkAlertedAt = null;
|
||||
await db.update(connections).set(patch).where(eq(connections.id, conn.id));
|
||||
|
||||
@ -50,6 +50,27 @@ export function decrypt(enc: string): string {
|
||||
}
|
||||
}
|
||||
|
||||
/** PEP-254: a fresh random 256-bit data key (envelope encryption). */
|
||||
export const newDataKey = (): Buffer => randomBytes(32);
|
||||
|
||||
/** AES-256-GCM with a given data key and associated data; base64url(iv | tag | ciphertext). */
|
||||
export function sealWithKey(dataKey: Buffer, plain: string, aad: string): string {
|
||||
const iv = randomBytes(12);
|
||||
const c = createCipheriv("aes-256-gcm", dataKey, iv);
|
||||
c.setAAD(Buffer.from(aad, "utf8"));
|
||||
const data = Buffer.concat([c.update(plain, "utf8"), c.final()]);
|
||||
return Buffer.concat([iv, c.getAuthTag(), data]).toString("base64url");
|
||||
}
|
||||
|
||||
/** Opens `sealWithKey`; throws on a wrong key or tampered data. */
|
||||
export function openWithKey(dataKey: Buffer, enc: string, aad: string): string {
|
||||
const buf = Buffer.from(enc, "base64url");
|
||||
const d = createDecipheriv("aes-256-gcm", dataKey, buf.subarray(0, 12));
|
||||
d.setAAD(Buffer.from(aad, "utf8"));
|
||||
d.setAuthTag(buf.subarray(12, 28));
|
||||
return Buffer.concat([d.update(buf.subarray(28)), d.final()]).toString("utf8");
|
||||
}
|
||||
|
||||
/** Which key an encrypted value opens with (PEP-19: what still waits for `reencrypt`). */
|
||||
export function encryptedWith(enc: string): "current" | "previous" | "unknown" {
|
||||
const buf = Buffer.from(enc, "base64url");
|
||||
|
||||
@ -108,6 +108,7 @@ export * from "./feature-status.ts";
|
||||
export * from "./accept-screen.ts";
|
||||
export * from "./accept-digest.ts";
|
||||
export * from "./connections.ts";
|
||||
export * from "./connection-journal.ts";
|
||||
export * from "./connection-catalog.ts";
|
||||
export * from "./edge-dns.ts";
|
||||
export * from "./retention.ts";
|
||||
|
||||
@ -8,6 +8,7 @@ import { connections, oauthClients, oauthTokens, projects, projectSecrets, sessi
|
||||
import { and, eq, gt, isNotNull, isNull, notInArray, sql } from "drizzle-orm";
|
||||
import { logEvent } from "./audit.ts";
|
||||
import { encrypt, decrypt, encryptedWith, rotatingSecret } from "./crypto.ts";
|
||||
import { upgradeConnectionKeys } from "./connections.ts";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
import { GiteaClient } from "./gitea.ts";
|
||||
import { FINISHED_SESSION_STATUSES } from "./sessions.ts";
|
||||
@ -190,8 +191,10 @@ function encryptedColumns(db: Db) {
|
||||
{ table: "users", column: "telegram_bot_token_enc", rows: () => db.select({ id: users.id, enc: users.telegramBotTokenEnc }).from(users).where(isNotNull(users.telegramBotTokenEnc)), set: (id: number, enc: string) => db.update(users).set({ telegramBotTokenEnc: enc }).where(eq(users.id, id)) },
|
||||
{ table: "subscriptions", column: "secret_enc", rows: () => db.select({ id: subscriptions.id, enc: subscriptions.secretEnc }).from(subscriptions).where(isNotNull(subscriptions.secretEnc)), set: (id: number, enc: string) => db.update(subscriptions).set({ secretEnc: enc }).where(eq(subscriptions.id, id)) },
|
||||
{ table: "project_secrets", column: "value_enc", rows: () => db.select({ id: projectSecrets.id, enc: projectSecrets.valueEnc }).from(projectSecrets), set: (id: number, enc: string) => db.update(projectSecrets).set({ valueEnc: enc }).where(eq(projectSecrets.id, id)) },
|
||||
// PEP-234: Access Hub keys (revoked connections have none).
|
||||
{ table: "connections", column: "secret_enc", rows: () => db.select({ id: connections.id, enc: connections.secretEnc }).from(connections).where(isNotNull(connections.secretEnc)), set: (id: number, enc: string) => db.update(connections).set({ secretEnc: enc }).where(eq(connections.id, id)) },
|
||||
// PEP-254: Access Hub keys sit under their own data key; PEPPA_SECRET guards only the data
|
||||
// keys. Old rows not yet moved by `upgradeConnectionKeys` still hold the key itself.
|
||||
{ table: "connections", column: "dek_enc", rows: () => db.select({ id: connections.id, enc: connections.dekEnc }).from(connections).where(isNotNull(connections.dekEnc)), set: (id: number, enc: string) => db.update(connections).set({ dekEnc: enc }).where(eq(connections.id, id)) },
|
||||
{ table: "connections", column: "secret_enc", rows: () => db.select({ id: connections.id, enc: connections.secretEnc }).from(connections).where(and(isNotNull(connections.secretEnc), isNull(connections.dekEnc))), set: (id: number, enc: string) => db.update(connections).set({ secretEnc: enc }).where(and(eq(connections.id, id), isNull(connections.dekEnc))) },
|
||||
];
|
||||
}
|
||||
|
||||
@ -315,6 +318,8 @@ export interface ReencryptResult {
|
||||
export async function reencryptAll(db: Db, by: string | null = null): Promise<ReencryptResult> {
|
||||
if (!envSet("PEPPA_SECRET", process.env)) throw new PeppaError(tr("PEPPA_SECRET не задан"));
|
||||
const out: ReencryptResult = { reencrypted: 0, alreadyCurrent: 0, unreadable: [] };
|
||||
// PEP-254: old Access Hub rows first get a data key of their own (then only it is re-encrypted).
|
||||
await upgradeConnectionKeys(db);
|
||||
for (const c of encryptedColumns(db)) {
|
||||
for (const r of await c.rows()) {
|
||||
const k = encryptedWith(r.enc!);
|
||||
|
||||
8
packages/db/migrations/0030_access_hub_journal.sql
Normal file
8
packages/db/migrations/0030_access_hub_journal.sql
Normal file
@ -0,0 +1,8 @@
|
||||
ALTER TABLE `connection_log` ADD `kind` text DEFAULT 'call' NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE `connection_log` ADD `parent_id` integer;--> statement-breakpoint
|
||||
ALTER TABLE `connection_log` ADD `project_key` text;--> statement-breakpoint
|
||||
ALTER TABLE `connection_log` ADD `duration_ms` integer;--> statement-breakpoint
|
||||
ALTER TABLE `connection_log` ADD `prev_hash` text;--> statement-breakpoint
|
||||
ALTER TABLE `connection_log` ADD `hash` text;--> statement-breakpoint
|
||||
ALTER TABLE `connections` ADD `dek_enc` text;--> statement-breakpoint
|
||||
UPDATE `connection_log` SET `project_key` = (SELECT `key` FROM `projects` WHERE `projects`.`id` = `connection_log`.`project_id`) WHERE `project_id` IS NOT NULL;
|
||||
5267
packages/db/migrations/meta/0030_snapshot.json
Normal file
5267
packages/db/migrations/meta/0030_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
@ -211,6 +211,13 @@
|
||||
"when": 1795445709219,
|
||||
"tag": "0029_access_hub_catalog",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 30,
|
||||
"version": "6",
|
||||
"when": 1795512094088,
|
||||
"tag": "0030_access_hub_journal",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -684,7 +684,11 @@ export const connections = sqliteTable(
|
||||
checkStatus: text("check_status").$type<"ok" | "bad_key" | "down">(),
|
||||
checkedAt: integer("checked_at", { mode: "timestamp_ms" }),
|
||||
checkAlertedAt: integer("check_alerted_at", { mode: "timestamp_ms" }),
|
||||
// PEP-254 envelope: `secret_enc` = "v2." + AES-GCM with this connection's own data key;
|
||||
// `dek_enc` = that data key under PEPPA_SECRET (rotation re-encrypts only it). No dek_enc —
|
||||
// an old row, secret_enc is under PEPPA_SECRET until `upgradeConnectionKeys`.
|
||||
secretEnc: text("secret_enc"),
|
||||
dekEnc: text("dek_enc"),
|
||||
status: text("status").$type<"active" | "revoked">().notNull().default("active"),
|
||||
revokedAt: integer("revoked_at", { mode: "timestamp_ms" }),
|
||||
lastUsedAt: integer("last_used_at", { mode: "timestamp_ms" }),
|
||||
@ -730,6 +734,14 @@ export const connectionLog = sqliteTable(
|
||||
decision: text("decision").$type<"allowed" | "denied" | "failed">().notNull(),
|
||||
reason: text("reason"),
|
||||
statusCode: integer("status_code"),
|
||||
// PEP-254: `call` is written before the request, its `result` (parent_id) after it.
|
||||
kind: text("kind").$type<"call" | "result">().notNull().default("call"),
|
||||
parentId: integer("parent_id"),
|
||||
projectKey: text("project_key"),
|
||||
durationMs: integer("duration_ms"),
|
||||
// Hash chain per owner (core/connection-journal.ts): sha256(prev_hash + "\n" + canonical row).
|
||||
prevHash: text("prev_hash"),
|
||||
hash: text("hash"),
|
||||
createdAt: createdAt(),
|
||||
},
|
||||
(t) => [index("connection_log_owner").on(t.ownerId, t.id), index("connection_log_session_created").on(t.sessionId, t.createdAt)],
|
||||
|
||||
@ -39,7 +39,7 @@ import { limitDelay, limitOver } from "./limit-delay.ts";
|
||||
import { checksQueueTick, platformDelayTick } from "./platform-delays.ts";
|
||||
import { readyDigestTick } from "./ready-digest.ts";
|
||||
import { stuckTaskTick } from "./stuck-tasks.ts";
|
||||
import { connectionCheckTick } from "@peppa/core";
|
||||
import { connectionCheckTick, connectionJournalTick } from "@peppa/core";
|
||||
import { domainGuardTick } from "./domain-guard.ts";
|
||||
import { edgeDnsTick } from "./edge-dns.ts";
|
||||
import { actRunnerTick } from "./act-runner.ts";
|
||||
@ -422,6 +422,8 @@ export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortS
|
||||
await stuckTaskTick(db, { log }).catch(failed(db, log, "stuck tasks failed"));
|
||||
// PEP-249: each connection's key is checked once a day; a key that stopped working — one message to its owner.
|
||||
await connectionCheckTick(db).catch(failed(db, log, "connection check failed"));
|
||||
// PEP-254: hourly — the connections journal chain is checked, a daily checkpoint goes outside the table.
|
||||
await connectionJournalTick(db, { log }).catch(failed(db, log, "connection journal failed"));
|
||||
// PEP-209: one «Готово к приёмке» summary instead of many «готово» messages in Telegram.
|
||||
await acceptDigestTick(db, { log }).catch(failed(db, log, "accept digest failed"));
|
||||
await pruneAcceptFailures(db).catch(() => {});
|
||||
|
||||
@ -153,4 +153,14 @@ export const accessHub: Record<string, string> = {
|
||||
"Имя параметра для ключа: латинские буквы, цифры, дефис и подчёркивание, например key": "Key parameter name: Latin letters, digits, hyphens and underscores, for example key",
|
||||
"Разрешите чтение, запись или хотя бы одну операцию": "Allow reading, writing or at least one operation",
|
||||
"Ключ доступа подключения «{name}» перестал работать: агенты не смогут им пользоваться. Замените ключ в разделе «Подключения».": "The access key of connection «{name}» stopped working: agents can't use it. Replace the key in «Connections».",
|
||||
"выполняется": "in progress",
|
||||
"начато, итога нет": "started, no result",
|
||||
"Журнал нельзя незаметно изменить: каждая запись связана с предыдущей, и раз в сутки FORGE сохраняет отметку журнала отдельно. Если запись изменят, вы и администратор получите сообщение.": "The journal can't be changed unnoticed: each entry is linked to the previous one, and once a day FORGE keeps a mark of the journal separately. If an entry is changed, you and the administrator get a message.",
|
||||
"Скачать журнал (таблица)": "Download the journal (table)",
|
||||
"Скачать журнал для проверки": "Download the journal for checking",
|
||||
"Как проверить журнал самому": "How to check the journal yourself",
|
||||
"Скачайте журнал для проверки и сохраните программу ниже рядом с ним. Запустите её так, как написано в её первой строке. Ответ «ok» значит, что журнал не меняли; иначе программа назовёт первую изменённую запись.": "Download the journal for checking and save the program below next to it. Run it as its first line says. The answer «ok» means the journal wasn't changed; otherwise the program names the first changed entry.",
|
||||
"Журнал подключений: контрольные точки": "Connections journal: checkpoints",
|
||||
"Журнал подключений пользователя {login} изменён в обход FORGE (запись {id}). Проверьте доступ к базе.": "The connections journal of user {login} was changed bypassing FORGE (entry {id}). Check access to the database.",
|
||||
"Журнал ваших подключений изменён в обход FORGE. Администратор уже знает и разбирается; ключи доступа лучше заменить в разделе «Подключения».": "The journal of your connections was changed bypassing FORGE. The administrator already knows and is looking into it; better replace the access keys in «Connections».",
|
||||
};
|
||||
|
||||
@ -153,4 +153,14 @@ export const accessHub: Record<string, string> = {
|
||||
"Имя параметра для ключа: латинские буквы, цифры, дефис и подчёркивание, например key": "Кілт параметрінің атауы: латын әріптері, сандар, дефис және астын сызу, мысалы key",
|
||||
"Разрешите чтение, запись или хотя бы одну операцию": "Оқуға, жазуға немесе кемінде бір операцияға рұқсат беріңіз",
|
||||
"Ключ доступа подключения «{name}» перестал работать: агенты не смогут им пользоваться. Замените ключ в разделе «Подключения».": "«{name}» қосылымының қолжетімділік кілті жұмыс істемей қалды: агенттер оны пайдалана алмайды. Кілтті «Қосылымдар» бөлімінде ауыстырыңыз.",
|
||||
"выполняется": "орындалуда",
|
||||
"начато, итога нет": "басталды, нәтижесі жоқ",
|
||||
"Журнал нельзя незаметно изменить: каждая запись связана с предыдущей, и раз в сутки FORGE сохраняет отметку журнала отдельно. Если запись изменят, вы и администратор получите сообщение.": "Журналды байқатпай өзгерту мүмкін емес: әр жазба алдыңғысымен байланысты, ал FORGE тәулігіне бір рет журналдың белгісін бөлек сақтайды. Жазба өзгертілсе, сіз де, әкімші де хабарлама аласыз.",
|
||||
"Скачать журнал (таблица)": "Журналды жүктеу (кесте)",
|
||||
"Скачать журнал для проверки": "Тексеруге арналған журналды жүктеу",
|
||||
"Как проверить журнал самому": "Журналды өзіңіз қалай тексеруге болады",
|
||||
"Скачайте журнал для проверки и сохраните программу ниже рядом с ним. Запустите её так, как написано в её первой строке. Ответ «ok» значит, что журнал не меняли; иначе программа назовёт первую изменённую запись.": "Тексеруге арналған журналды жүктеп, төмендегі бағдарламаны оның жанына сақтаңыз. Оны бірінші жолында жазылғандай іске қосыңыз. «ok» жауабы журнал өзгертілмегенін білдіреді; әйтпесе бағдарлама алғашқы өзгертілген жазбаны атайды.",
|
||||
"Журнал подключений: контрольные точки": "Қосылымдар журналы: бақылау нүктелері",
|
||||
"Журнал подключений пользователя {login} изменён в обход FORGE (запись {id}). Проверьте доступ к базе.": "{login} пайдаланушысының қосылымдар журналы FORGE-ды айналып өтіп өзгертілді (жазба {id}). Дерекқорға қолжетімділікті тексеріңіз.",
|
||||
"Журнал ваших подключений изменён в обход FORGE. Администратор уже знает и разбирается; ключи доступа лучше заменить в разделе «Подключения».": "Қосылымдарыңыздың журналы FORGE-ды айналып өтіп өзгертілді. Әкімші біледі және анықтап жатыр; қолжетімділік кілттерін «Қосылымдар» бөлімінде ауыстырған жөн.",
|
||||
};
|
||||
|
||||
276
packages/testkit/test/access-hub-journal.test.ts
Normal file
276
packages/testkit/test/access-hub-journal.test.ts
Normal file
@ -0,0 +1,276 @@
|
||||
// PEP-254 Access Hub: the journal is written before the action and can't be changed quietly
|
||||
// (hash chain + checkpoints outside the table), the owner exports and checks it; every connection
|
||||
// key sits under its own data key. Scenario names follow
|
||||
// openspec/changes/pep-254-access-hub-journal-integrity/specs/access-hub/spec.md.
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdtempSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { after, before, describe, test } from "node:test";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { stripAsIs } from "@peppa/shared/i18n";
|
||||
import type { ConnectionFetch } from "@peppa/core";
|
||||
import { core, db, project, teardown } from "./helpers.ts";
|
||||
|
||||
process.env.PEPPA_SECRET = "mock-journal-secret-current";
|
||||
delete process.env.PEPPA_SECRET_PREVIOUS;
|
||||
const { connections, connectionLog, agents, sessions, events, telegramOutbox } = await import("@peppa/db");
|
||||
|
||||
const KEY = "sk_live_mock_journal_111111";
|
||||
const KEY_MAIL = "sk_live_mock_mail_222222";
|
||||
|
||||
let anna: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||||
let boris: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||||
|
||||
before(async () => {
|
||||
anna = await core.upsertUserFromGitea(db, { id: 2541, login: "mock-j-anna" }, { access_token: "a" });
|
||||
boris = await core.upsertUserFromGitea(db, { id: 2542, login: "mock-j-boris" }, { access_token: "b" });
|
||||
process.env.PEPPA_PLATFORM_KEY = (await project({ turns: [] })).key;
|
||||
await db.update((await import("@peppa/db")).users).set({ telegramChatId: 254001 }).where(eq((await import("@peppa/db")).users.id, anna.id));
|
||||
});
|
||||
after(teardown);
|
||||
|
||||
process.env.PEPPA_CONNECTIONS_UNISOLATED = "on";
|
||||
|
||||
/** A mock external service in-process: status per path, optional hang. */
|
||||
function mockFetch(o: { status?: number; fail?: boolean } = {}): ConnectionFetch {
|
||||
return async ({ url }) => {
|
||||
if (o.fail) throw new Error("mock crash in the middle");
|
||||
return { status: o.status ?? 200, contentType: "application/json", body: Buffer.from(JSON.stringify({ path: url.pathname })), truncated: false };
|
||||
};
|
||||
}
|
||||
|
||||
async function setup(ownerId: number, name: string, secret = KEY) {
|
||||
const p = await project({ turns: [] });
|
||||
const proj = await core.getProject(db, p.key);
|
||||
await core.setProjectOwner(db, proj.id, ownerId);
|
||||
const task = (await core.listTasks(db, { projectId: proj.id }))[0]!;
|
||||
const c = await core.createConnection(db, ownerId, { name, baseUrl: "https://crm.example.com/api", secret });
|
||||
await core.grantConnection(db, ownerId, c.id, { projectId: proj.id, operations: "GET /items" });
|
||||
const s = await core.createSession(db, { projectId: proj.id, taskId: task.id });
|
||||
const [a] = await db.insert(agents).values({ name: `Мок-журнал ${s.id}` }).returning();
|
||||
await db.update(sessions).set({ agentId: a!.id }).where(eq(sessions.id, s.id));
|
||||
return { proj, c, sessionId: s.id };
|
||||
}
|
||||
|
||||
const ownerRows = (ownerId: number) => db.select().from(connectionLog).where(eq(connectionLog.ownerId, ownerId)).orderBy(connectionLog.id);
|
||||
|
||||
describe("Журнал пишется до действия", () => {
|
||||
test("Итог дописывается после вызова", async () => {
|
||||
const { c, sessionId, proj } = await setup(anna.id, "CRM");
|
||||
let seenRows = -1;
|
||||
const r = await core.callConnection(db, { sessionId, connection: "CRM", method: "GET", path: "/items/5" }, {
|
||||
fetch: async (req) => {
|
||||
// At the moment of the request the call is already in the journal.
|
||||
seenRows = (await db.select().from(connectionLog).where(and(eq(connectionLog.connectionId, c.id), eq(connectionLog.kind, "call")))).length;
|
||||
return mockFetch()(req);
|
||||
},
|
||||
});
|
||||
assert.equal(r.ok, true);
|
||||
assert.equal(seenRows, 1, "the call is written before the service is called");
|
||||
const rows = (await ownerRows(anna.id)).filter((x) => x.connectionId === c.id);
|
||||
assert.deepEqual(rows.map((x) => x.kind), ["call", "result"]);
|
||||
assert.equal(rows[1]!.parentId, rows[0]!.id);
|
||||
assert.equal(rows[1]!.statusCode, 200);
|
||||
assert.equal(rows[0]!.projectKey, proj.key);
|
||||
const view = (await core.connectionJournal(db, anna.id, { connectionId: c.id }))[0]!;
|
||||
assert.equal(view.path, "/items/5");
|
||||
assert.equal(view.statusCode, 200);
|
||||
assert.equal(view.state, "done");
|
||||
assert.equal((await core.connectionJournal(db, anna.id, { connectionId: c.id })).length, 1, "the result joins its call on screen");
|
||||
});
|
||||
|
||||
test("Сбой посередине виден", async () => {
|
||||
const { c, sessionId } = await setup(anna.id, "CRM-crash");
|
||||
const t0 = new Date();
|
||||
// The process «dies» between the call row and the result: simulate by dropping the result.
|
||||
await core.callConnection(db, { sessionId, connection: "CRM-crash", method: "GET", path: "/items/5" }, { fetch: mockFetch(), now: t0 });
|
||||
const [res] = await db.select().from(connectionLog).where(and(eq(connectionLog.connectionId, c.id), eq(connectionLog.kind, "result")));
|
||||
// A real crash leaves no result row; it is the last row of the chain, so removing it keeps the chain whole.
|
||||
await db.delete(connectionLog).where(eq(connectionLog.id, res!.id));
|
||||
const soon = (await core.connectionJournal(db, anna.id, { connectionId: c.id, now: new Date(t0.getTime() + 1000) }))[0]!;
|
||||
assert.equal(soon.state, "running");
|
||||
const later = (await core.connectionJournal(db, anna.id, { connectionId: c.id, now: new Date(t0.getTime() + 60_000) }))[0]!;
|
||||
assert.equal(later.state, "unfinished");
|
||||
assert.equal((await core.verifyConnectionJournal(db, anna.id)).ok, true);
|
||||
});
|
||||
|
||||
test("Отказ — одна запись, лимит считает только вызовы", async () => {
|
||||
const { c, sessionId } = await setup(anna.id, "CRM-deny");
|
||||
const r = await core.callConnection(db, { sessionId, connection: "CRM-deny", method: "DELETE", path: "/items/5" }, { fetch: mockFetch() });
|
||||
assert.equal(r.ok, false);
|
||||
const rows = await db.select().from(connectionLog).where(eq(connectionLog.connectionId, c.id));
|
||||
assert.equal(rows.length, 1);
|
||||
assert.equal(rows[0]!.decision, "denied");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Журнал защищён от подделки", () => {
|
||||
test("Изменённая запись обнаруживается", async () => {
|
||||
const { sessionId } = await setup(boris.id, "CRM-b");
|
||||
for (const p of ["/items/1", "/items/5", "/items/9"]) await core.callConnection(db, { sessionId, connection: "CRM-b", method: "GET", path: p }, { fetch: mockFetch() });
|
||||
const before = await core.verifyConnectionJournal(db, boris.id);
|
||||
assert.equal(before.ok, true);
|
||||
assert.equal(before.checked, 6);
|
||||
const rows = await ownerRows(boris.id);
|
||||
const second = rows.find((r) => r.path === "/items/5" && r.kind === "call")!;
|
||||
await db.update(connectionLog).set({ path: "/items/6" }).where(eq(connectionLog.id, second.id));
|
||||
const v = await core.verifyConnectionJournal(db, boris.id);
|
||||
assert.equal(v.ok, false);
|
||||
assert.equal(v.brokenAt, second.id);
|
||||
assert.equal(v.reason, "hash");
|
||||
await db.update(connectionLog).set({ path: "/items/5" }).where(eq(connectionLog.id, second.id));
|
||||
// A deleted row in the middle breaks the link.
|
||||
const third = rows.find((r) => r.path === "/items/9" && r.kind === "call")!;
|
||||
const saved = rows.find((r) => r.id === third.id)!;
|
||||
await db.delete(connectionLog).where(eq(connectionLog.id, third.id));
|
||||
const d = await core.verifyConnectionJournal(db, boris.id);
|
||||
assert.equal(d.ok, false);
|
||||
assert.equal(d.reason, "link");
|
||||
await db.insert(connectionLog).values(saved);
|
||||
assert.equal((await core.verifyConnectionJournal(db, boris.id)).ok, true);
|
||||
});
|
||||
|
||||
test("Пересчитанная цепочка не совпадает с контрольной точкой", async () => {
|
||||
const t0 = new Date("2026-11-24T10:00:00Z");
|
||||
const r = await core.connectionJournalTick(db, { now: t0, force: true });
|
||||
assert.ok(r.checkpoints >= 2, "a checkpoint per owner");
|
||||
const cp = await core.getJournalCheckpoint(db, boris.id);
|
||||
assert.ok(cp);
|
||||
const [ev] = await db.select().from(events).where(eq(events.type, "connection_journal_checkpoint"));
|
||||
assert.ok(ev, "the checkpoint is in the platform journal");
|
||||
|
||||
// Rewrite a row before the checkpoint and recompute every hash after it.
|
||||
const rows = (await ownerRows(boris.id)).map(core.toRecord);
|
||||
rows[0]!.path = "/forged";
|
||||
let prev = rows[0]!.prev_hash!;
|
||||
for (const r2 of rows) {
|
||||
r2.prev_hash = prev;
|
||||
r2.hash = core.journalHash(prev, r2);
|
||||
prev = r2.hash;
|
||||
await db.update(connectionLog).set({ path: r2.path, prevHash: r2.prev_hash, hash: r2.hash }).where(eq(connectionLog.id, r2.id));
|
||||
}
|
||||
assert.equal(core.verifyJournalRows(rows).ok, true, "the chain alone looks fine");
|
||||
const v = await core.verifyConnectionJournal(db, boris.id);
|
||||
assert.equal(v.ok, false);
|
||||
assert.equal(v.reason, "checkpoint");
|
||||
});
|
||||
|
||||
test("Нарушение доходит до людей", async () => {
|
||||
const asel = await core.upsertUserFromGitea(db, { id: 2543, login: "mock-j-asel" }, { access_token: "c" });
|
||||
const users = (await import("@peppa/db")).users;
|
||||
await db.update(users).set({ telegramChatId: 254003 }).where(eq(users.id, asel.id));
|
||||
await core.setPlatformAdmins(db, ["mock-j-asel"]);
|
||||
await db.update(users).set({ telegramChatId: 254002 }).where(eq(users.id, boris.id));
|
||||
const t1 = new Date("2026-11-24T12:00:00Z");
|
||||
const r = await core.connectionJournalTick(db, { now: t1, force: true });
|
||||
assert.deepEqual(r.broken, [boris.id]);
|
||||
const outbox = async (chat: number) => (await db.select().from(telegramOutbox)).filter((m) => (m.params as { chat_id?: number }).chat_id === chat);
|
||||
assert.equal((await outbox(254003)).length, 1, "the superadmin gets one message");
|
||||
assert.equal((await outbox(254002)).length, 1, "the owner gets one message");
|
||||
assert.match(stripAsIs(String((await outbox(254002))[0]!.params.text)), /изменён в обход FORGE/);
|
||||
await core.connectionJournalTick(db, { now: new Date(t1.getTime() + 3600_000), force: true });
|
||||
assert.equal((await outbox(254003)).length, 1, "the same break is not reported again");
|
||||
assert.equal((await outbox(254002)).length, 1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Выгрузка журнала", () => {
|
||||
test("Выгрузка проверяется", async () => {
|
||||
const jsonl = await core.exportConnectionJournal(db, anna.id, "jsonl");
|
||||
const rows = core.parseJournalJsonl(jsonl);
|
||||
const own = await ownerRows(anna.id);
|
||||
assert.equal(rows.length, own.length);
|
||||
assert.ok(rows.every((r) => typeof r.hash === "string" && typeof r.prev_hash === "string"));
|
||||
assert.equal(core.verifyJournalRows(rows).ok, true);
|
||||
// The script from the page checks the file on its own.
|
||||
const dir = mkdtempSync(join(tmpdir(), "mock-journal-"));
|
||||
writeFileSync(join(dir, "journal.jsonl"), jsonl);
|
||||
writeFileSync(join(dir, "verify.mjs"), core.JOURNAL_VERIFY_SCRIPT);
|
||||
assert.match(execFileSync(process.execPath, [join(dir, "verify.mjs"), join(dir, "journal.jsonl")], { encoding: "utf8" }), /^ok, head [0-9a-f]{64}/m);
|
||||
const forged = jsonl.replace('"/items/5"', '"/items/6"');
|
||||
writeFileSync(join(dir, "journal.jsonl"), forged);
|
||||
assert.match(execFileSync(process.execPath, [join(dir, "verify.mjs"), join(dir, "journal.jsonl")], { encoding: "utf8" }), /journal changed/);
|
||||
const csv = await core.exportConnectionJournal(db, anna.id, "csv");
|
||||
assert.equal(csv.trim().split("\n").length, own.length + 1);
|
||||
assert.match(csv.split("\n")[0]!, /prev_hash,hash$/);
|
||||
});
|
||||
|
||||
test("Чужой журнал не выгружается", async () => {
|
||||
const mine = core.parseJournalJsonl(await core.exportConnectionJournal(db, anna.id, "jsonl"));
|
||||
assert.ok(mine.every((r) => r.owner_id === anna.id));
|
||||
assert.ok(!mine.some((r) => r.connection === "CRM-b"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("Отдельный ключ шифрования у каждого подключения", () => {
|
||||
test("Ключ данных одного подключения не открывает другое", async () => {
|
||||
const a = await core.createConnection(db, anna.id, { name: "CRM-env", baseUrl: "https://crm.example.com/api", secret: KEY });
|
||||
const b = await core.createConnection(db, anna.id, { name: "Почта", baseUrl: "https://mail.example.com/api", secret: KEY_MAIL });
|
||||
const [ra] = await db.select().from(connections).where(eq(connections.id, a.id));
|
||||
const [rb] = await db.select().from(connections).where(eq(connections.id, b.id));
|
||||
assert.ok(ra!.dekEnc && rb!.dekEnc && ra!.dekEnc !== rb!.dekEnc);
|
||||
assert.ok(ra!.secretEnc!.startsWith("v2."));
|
||||
assert.equal(core.openConnectionSecret(ra!), KEY);
|
||||
assert.equal(core.openConnectionSecret(rb!), KEY_MAIL);
|
||||
assert.throws(() => core.openConnectionSecret({ secretEnc: rb!.secretEnc, dekEnc: ra!.dekEnc }), "CRM's data key does not open Почта");
|
||||
assert.throws(() => core.decrypt(rb!.secretEnc!.slice(3)), "the platform key alone does not open a key either");
|
||||
});
|
||||
|
||||
test("Старое подключение переводится на свой ключ", async () => {
|
||||
const c = await core.createConnection(db, anna.id, { name: "CRM-old", baseUrl: "https://crm.example.com/api", secret: KEY });
|
||||
// As stored before PEP-254: the key itself under PEPPA_SECRET, no data key.
|
||||
await db.update(connections).set({ secretEnc: core.encrypt(KEY), dekEnc: null }).where(eq(connections.id, c.id));
|
||||
const [old] = await db.select().from(connections).where(eq(connections.id, c.id));
|
||||
assert.equal(core.openConnectionSecret(old!), KEY, "old rows still work before the move");
|
||||
const r = await core.upgradeConnectionKeys(db);
|
||||
assert.ok(r.upgraded >= 1);
|
||||
const [moved] = await db.select().from(connections).where(eq(connections.id, c.id));
|
||||
assert.ok(moved!.dekEnc && moved!.secretEnc!.startsWith("v2."));
|
||||
assert.equal(core.openConnectionSecret(moved!), KEY);
|
||||
assert.equal((await core.upgradeConnectionKeys(db)).upgraded, 0, "idempotent");
|
||||
});
|
||||
|
||||
test("Ротация ключа платформы", async () => {
|
||||
const { c, sessionId } = await setup(anna.id, "CRM-rot");
|
||||
const [beforeRow] = await db.select().from(connections).where(eq(connections.id, c.id));
|
||||
process.env.PEPPA_SECRET_PREVIOUS = process.env.PEPPA_SECRET;
|
||||
process.env.PEPPA_SECRET = "mock-journal-secret-next";
|
||||
try {
|
||||
const r = await core.reencryptAll(db, "mock-j-asel");
|
||||
assert.ok(r.reencrypted >= 1);
|
||||
assert.equal(r.unreadable.length, 0);
|
||||
const [afterRow] = await db.select().from(connections).where(eq(connections.id, c.id));
|
||||
assert.notEqual(afterRow!.dekEnc, beforeRow!.dekEnc, "the data key is re-encrypted");
|
||||
assert.equal(afterRow!.secretEnc, beforeRow!.secretEnc, "the encrypted key itself is untouched");
|
||||
delete process.env.PEPPA_SECRET_PREVIOUS;
|
||||
assert.equal(core.encryptedWith(afterRow!.dekEnc!), "current");
|
||||
let auth = "";
|
||||
const res = await core.callConnection(db, { sessionId, connection: "CRM-rot", method: "GET", path: "/items" }, {
|
||||
fetch: async (req) => {
|
||||
auth = req.headers.Authorization ?? req.headers.authorization ?? "";
|
||||
return mockFetch()(req);
|
||||
},
|
||||
});
|
||||
assert.equal(res.ok, true);
|
||||
assert.equal(auth, `Bearer ${KEY}`);
|
||||
} finally {
|
||||
delete process.env.PEPPA_SECRET_PREVIOUS;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Старый журнал получает цепочку", () => {
|
||||
test("Записи до изменения связываются при переводе", async () => {
|
||||
const carl = await core.upsertUserFromGitea(db, { id: 2544, login: "mock-j-carl" }, { access_token: "d" });
|
||||
const c = await core.createConnection(db, carl.id, { name: "Old", baseUrl: "https://crm.example.com/api", secret: KEY });
|
||||
for (const p of ["/a", "/b"]) await db.insert(connectionLog).values({ ownerId: carl.id, connectionId: c.id, connectionName: "Old", method: "GET", path: p, decision: "allowed", statusCode: 200, createdAt: new Date() });
|
||||
assert.equal((await core.verifyConnectionJournal(db, carl.id)).unprotected, 2);
|
||||
assert.equal(await core.upgradeConnectionJournal(db), 2);
|
||||
const v = await core.verifyConnectionJournal(db, carl.id);
|
||||
assert.equal(v.ok, true);
|
||||
assert.equal(v.checked, 2);
|
||||
assert.equal(await core.upgradeConnectionJournal(db), 0, "idempotent");
|
||||
});
|
||||
});
|
||||
@ -95,10 +95,10 @@ describe("Подключение внешнего сервиса", () => {
|
||||
assert.ok(!JSON.stringify(list).includes(KEY), "the list never carries the key");
|
||||
const [row] = await db.select().from(connections).where(eq(connections.id, c.id));
|
||||
assert.ok(row!.secretEnc && !row!.secretEnc.includes(KEY), "stored encrypted");
|
||||
assert.equal(core.decrypt(row!.secretEnc), KEY);
|
||||
// PEP-19: the key column takes part in PEPPA_SECRET rotation.
|
||||
assert.equal(core.openConnectionSecret(row!), KEY);
|
||||
// PEP-19/254: the connection's own data key takes part in PEPPA_SECRET rotation.
|
||||
const audit = await core.secretsAudit(db);
|
||||
assert.ok(audit.encryption.columns.some((col) => col.table === "connections" && col.column === "secret_enc" && col.total >= 1));
|
||||
assert.ok(audit.encryption.columns.some((col) => col.table === "connections" && col.column === "dek_enc" && col.total >= 1));
|
||||
});
|
||||
|
||||
test("Небезопасный адрес отклоняется", async () => {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user