PEP-258: маскировка всех форм ключа подключения и тест-ловушка
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
8b3f7e9159
commit
562aef4d68
17
openspec/changes/pep-258-access-hub-key-leak/design.md
Normal file
17
openspec/changes/pep-258-access-hub-key-leak/design.md
Normal file
@ -0,0 +1,17 @@
|
||||
## Context
|
||||
Шлюз (`callConnection`, PEP-234/249/254) расшифровывает ключ, строит запрос (`buildRequest`) и отдаёт агенту `{status, contentType, body, truncated}`. Заголовки ответа и адрес `Location` агенту не отдаются никогда; ошибки — только код причины (`ConnectionReason`), текст исключения не уходит.
|
||||
|
||||
## Decisions
|
||||
- **Маскировка по списку форм, а не по одному значению.** Формы считаются один раз на вызов из ключа и способа подстановки: исходный ключ; для basic — логин:пароль целиком и пароль отдельно (если ≥ 4 символов); base64 стандартный и url-safe, с паддингом и без, плюс «ядро» для выравниваний 1 и 2 (ключ внутри более длинной base64-строки, например `Basic base64(login:password)` или base64 всего JSON с ключом) — граничные символы, зависящие от соседних байтов, отбрасываются, ядро короче 8 символов не берётся (ложные срабатывания); `encodeURIComponent`, нижний регистр %xx, form-кодировка (`+`); hex нижним и верхним регистром; JSON-строка (`\/`, `\uXXXX` для всех символов). Замена — от длинных к коротким.
|
||||
- **Переносы строк.** base64 и hex часто переносят по 64/76 символов (MIME, PEM): для форм длиной ≥ 16 ищем и вариант с `\r?\n` между любыми символами (регулярное выражение строится лениво, только если в тексте есть перевод строки).
|
||||
- **Обрезка на 256 КБ.** Если ответ обрезан, а текст кончается началом какой-либо формы (≥ 4 символов), хвост маскируется.
|
||||
- **Тип содержимого** тоже проходит маскировку (его видит агент в первой строке MCP-ответа).
|
||||
- **Редирект** не выполняется (PEP-234), `Location` не читается дальше признака «есть»; на другой хост ключ не уходит, потому что запрос не повторяется вовсе.
|
||||
- **Где ключ живёт.** Расшифровка (`openConnectionSecret`) — только внутри `callConnection` и `runCheck`; из них возвращается только результат. Ключ не входит в `projectSecretEnv` (окружение агента и контейнера — из `project_secrets`), не пишется в `connection_log`/`events` (журнал — метод, путь без query, решение, причина), ответ сервиса не сохраняется. `guardUntrusted` цитирует в событие `injection_suspected` уже замаскированный текст. Шаги (`recordStep`) и терминал видят только то, что вернул шлюз.
|
||||
|
||||
## Пути, которые не закрыть маскировкой (заведена задача)
|
||||
Сервис, который по запросу агента преобразует строку произвольно (реверс, ROT13, по одному символу за вызов, сжатие gzip/zip в теле, шифрование), может вернуть ключ в неузнаваемом виде. Маскировка такие пути не закрывает в принципе; защита — права (только нужные операции, «спрашивать владельца» для записи) и журнал. Отдельно: бинарные ответы (`toString("utf8")` портит байты, но gzip-тело с ключом внутри не распознать). Заведена задача про ограничение типов ответов (только текстовые типы) и подсказку владельцу «эхо-операции».
|
||||
|
||||
## Risks
|
||||
- Ложная маскировка короткого совпадения base64-ядра в данных — ядро ≥ 8 символов, вероятность пренебрежимо мала.
|
||||
- Стоимость: формы для ключа ≤ 8 КБ — десятки строк; `split/join` по телу ≤ 256 КБ — миллисекунды.
|
||||
14
openspec/changes/pep-258-access-hub-key-leak/proposal.md
Normal file
14
openspec/changes/pep-258-access-hub-key-leak/proposal.md
Normal file
@ -0,0 +1,14 @@
|
||||
## Why
|
||||
Главное обещание Access Hub (эпик #16): агент никогда не видит ключ сервиса. Шлюз `callConnection` маскировал только ключ в исходном виде. Сервис может вернуть его иначе — в base64 (Basic, PEP-249), в URL-кодировке (ключ в query), в hex, экранированным в JSON, переносом строк в base64, обрезанным на границе 256 КБ, в типе содержимого. Нужно закрыть эти пути и закрепить тестом-ловушкой, чтобы PEP-236/251/252 их не открыли.
|
||||
|
||||
## What Changes
|
||||
- Новый модуль `core/connection-mask.ts`: `connectionKeyForms(secret, authKind)` — все формы ключа (исходная, части basic, base64 стандартный/url-safe с тремя выравниваниями, URL-кодировка, form-кодировка, hex в обоих регистрах, JSON-экранирование, `\uXXXX`) и `maskConnectionKey(text, forms, {truncated})` — замена форм (base64 и hex — и с переносами строк), обрезанный хвост с началом формы.
|
||||
- `callConnection` маскирует тело и тип содержимого ответа этим модулем; заголовки ответа, адрес редиректа и текст сетевой ошибки агенту по-прежнему не отдаются (только причина), редирект не выполняется.
|
||||
- Тест-ловушка в `access-hub.test.ts`: мок-сервис возвращает ключ во всех формах (тело, заголовки, тип содержимого, ошибка 500 со стектрейсом, редирект, обрыв на границе), для каждого способа ключа (bearer / header / basic / query / path); проверяется ответ шлюза, MCP `call_connection`, `execute`, журнал, события, шаги, секреты проекта.
|
||||
|
||||
## Capabilities
|
||||
### Modified Capabilities
|
||||
- `access-hub`: требование «Агент не получает ключ» дополнено формами ключа.
|
||||
|
||||
## Impact
|
||||
`packages/core/src/connection-mask.ts` (новый), `packages/core/src/connections.ts`, `packages/testkit/test/access-hub.test.ts`. Без миграций.
|
||||
@ -0,0 +1,38 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Агент не получает ключ
|
||||
Ключ подключения SHALL NOT попадать агенту: в окружение, файлы сессии, ответы MCP, журнал, сообщения. Ключ SHALL подставлять только серверный шлюз; заголовки от агента, кроме типа содержимого, SHALL NOT передаваться сервису. Шлюз SHALL маскировать в ответе агенту ключ в любой узнаваемой форме: исходной, base64 (в том числе внутри более длинной base64-строки и с переносами строк), URL-кодировке, hex, JSON-экранировании, а для basic — и пароль отдельно; в теле и типе содержимого. Заголовки ответа, адрес перенаправления и текст сетевой ошибки SHALL NOT отдаваться агенту, перенаправление SHALL NOT выполняться.
|
||||
|
||||
#### Scenario: Ключ не утекает в ответ и журнал
|
||||
- **GIVEN** сервис возвращает в ответе строку с ключом «sk_live_123456»
|
||||
- **WHEN** агент вызывает «call_connection»
|
||||
- **THEN** в ответе агенту «••••» вместо ключа
|
||||
- **AND** в журнале нет ни ключа, ни строки запроса после «?»
|
||||
|
||||
#### Scenario Outline: Ключ в другой форме тоже скрыт
|
||||
- **GIVEN** подключение со способом ключа «<способ>» и ключом «mock:sk_live_TRAP_7f3a9c»
|
||||
- **AND** сервис возвращает ключ в base64, URL-кодировке, hex, JSON-экранировании, в заголовке, в типе содержимого и в ошибке 500
|
||||
- **WHEN** агент вызывает «call_connection» и «execute»
|
||||
- **THEN** ни в ответе, ни в журнале, ни в событиях проекта нет ни одной формы ключа
|
||||
|
||||
| способ |
|
||||
| bearer |
|
||||
| header |
|
||||
| basic |
|
||||
| query |
|
||||
| path |
|
||||
|
||||
#### Scenario: Обрыв на границе ответа не открывает начало ключа
|
||||
- **GIVEN** ответ сервиса длиннее 256 КБ, и на границе обрезки стоит начало ключа
|
||||
- **WHEN** агент вызывает «call_connection»
|
||||
- **THEN** в конце ответа «••••», начала ключа нет
|
||||
|
||||
#### Scenario: Перенаправление не выполняется
|
||||
- **GIVEN** сервис отвечает 302 с адресом, содержащим ключ
|
||||
- **WHEN** агент вызывает «call_connection»
|
||||
- **THEN** операция отклонена с причиной «перенаправление», адреса в ответе нет
|
||||
|
||||
#### Scenario: Внутренний адрес недоступен через шлюз
|
||||
- **GIVEN** подключение с адресом, который резолвится в 127.0.0.1
|
||||
- **WHEN** агент с разрешением вызывает операцию
|
||||
- **THEN** операция отклонена с причиной «адрес недоступен»
|
||||
12
openspec/changes/pep-258-access-hub-key-leak/tasks.md
Normal file
12
openspec/changes/pep-258-access-hub-key-leak/tasks.md
Normal file
@ -0,0 +1,12 @@
|
||||
## 1. Маскировка
|
||||
- [x] 1.1 `core/connection-mask.ts`: `connectionKeyForms`, `maskConnectionKey` (формы, переносы, обрезанный хвост)
|
||||
- [x] 1.2 `callConnection`: маскировка тела и типа содержимого через модуль; экспорт из `@peppa/core`
|
||||
|
||||
## 2. Тест-ловушка
|
||||
- [x] 2.1 Мок-сервис-ловушка: ключ во всех формах в теле, заголовках, типе содержимого, 500 со стектрейсом, редирект, обрыв на границе
|
||||
- [x] 2.2 Прогон для bearer / header / basic / query / path: ответ шлюза, MCP `call_connection`, `execute`, журнал, события, шаги, секреты проекта — без единой формы ключа
|
||||
- [x] 2.3 Модульные тесты `maskConnectionKey` (выравнивания base64, переносы, хвост)
|
||||
|
||||
## 3. Завершение
|
||||
- [ ] 3.1 Задача на неустранимые маскировкой пути (бинарные/сжатые ответы, эхо-операции)
|
||||
- [ ] 3.2 Проверки, память, архив, результат
|
||||
98
packages/core/src/connection-mask.ts
Normal file
98
packages/core/src/connection-mask.ts
Normal file
@ -0,0 +1,98 @@
|
||||
// PEP-258: every recognisable form of a connection key, and masking of them in what reaches the agent.
|
||||
// A service may echo the key back encoded (base64 of «login:password», URL-encoded query key, hex,
|
||||
// JSON-escaped, line-wrapped base64) or cut at the 256 KB boundary — none of it may reach the agent.
|
||||
import type { CatalogAuth } from "./connection-catalog.ts";
|
||||
import { MASK } from "./secrets.ts";
|
||||
|
||||
/** Shorter fragments (base64 cores of short keys) are not masked on their own: false positives. */
|
||||
const CORE_MIN = 8;
|
||||
/** Forms at least this long are also looked for with line breaks inside (MIME/PEM wrapping). */
|
||||
const WRAP_MIN = 16;
|
||||
/** A truncated answer ending with this many first characters of a form gets its tail masked. */
|
||||
const TAIL_MIN = 4;
|
||||
|
||||
const urlSafe = (b64: string) => b64.replace(/\+/g, "-").replace(/\//g, "_");
|
||||
|
||||
/**
|
||||
* base64 of the value as it appears inside a longer base64 stream at byte offset 0, 1 and 2:
|
||||
* characters that depend on neighbouring bytes are dropped. Plus the whole value with and without padding.
|
||||
*/
|
||||
function base64Forms(value: string): string[] {
|
||||
const bytes = Buffer.from(value, "utf8");
|
||||
const out: string[] = [];
|
||||
const full = bytes.toString("base64");
|
||||
out.push(full, full.replace(/=+$/, ""));
|
||||
for (let k = 0; k < 3; k++) {
|
||||
const enc = Buffer.concat([Buffer.alloc(k), bytes]).toString("base64").replace(/=+$/, "");
|
||||
const head = k === 0 ? 0 : 4; // the first group mixes the prefix bytes
|
||||
const tail = (k + bytes.length) % 3 === 0 ? 0 : (((k + bytes.length) % 3) + 1); // the last partial group depends on what follows
|
||||
const core = enc.slice(head, enc.length - tail);
|
||||
if (core.length >= CORE_MIN) out.push(core);
|
||||
}
|
||||
return [...out, ...out.map(urlSafe)];
|
||||
}
|
||||
|
||||
function textForms(value: string): string[] {
|
||||
const uri = encodeURIComponent(value);
|
||||
const hex = Buffer.from(value, "utf8").toString("hex");
|
||||
const json = JSON.stringify(value).slice(1, -1);
|
||||
const uEsc = [...value].map((ch) => (ch.codePointAt(0)! > 0xffff ? JSON.stringify(ch).slice(1, -1) : `\\u${ch.codePointAt(0)!.toString(16).padStart(4, "0")}`)).join("");
|
||||
return [
|
||||
value,
|
||||
uri,
|
||||
uri.replace(/%[0-9A-F]{2}/g, (m) => m.toLowerCase()),
|
||||
uri.replace(/%20/g, "+"),
|
||||
encodeURI(value),
|
||||
escape(value),
|
||||
hex,
|
||||
hex.toUpperCase(),
|
||||
json,
|
||||
json.replace(/\//g, "\\/"),
|
||||
uEsc,
|
||||
uEsc.toUpperCase().replace(/\\U/g, "\\u"),
|
||||
...base64Forms(value),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* All forms of a connection key the gateway masks, longest first. For basic the password alone is a
|
||||
* secret too (the login is not: it is often public — an email).
|
||||
*/
|
||||
export function connectionKeyForms(secret: string, authKind?: CatalogAuth | string | null): string[] {
|
||||
const values = [secret];
|
||||
if (authKind === "basic") {
|
||||
const i = secret.indexOf(":");
|
||||
const password = i >= 0 ? secret.slice(i + 1) : "";
|
||||
if (password.length >= TAIL_MIN) values.push(password);
|
||||
}
|
||||
const forms = new Set<string>();
|
||||
for (const v of values) for (const f of textForms(v)) if (f.length >= TAIL_MIN) forms.add(f);
|
||||
return [...forms].sort((a, b) => b.length - a.length);
|
||||
}
|
||||
|
||||
const reEscape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
|
||||
/** The form with an optional line break between any two characters. */
|
||||
const wrapped = (form: string) => new RegExp([...form].map(reEscape).join("(?:\\r?\\n)?"), "g");
|
||||
|
||||
/**
|
||||
* Replaces every form of the key with «••••». `truncated`: the answer was cut, so its very end may hold
|
||||
* the beginning of a form — masked too.
|
||||
*/
|
||||
export function maskConnectionKey(text: string, forms: string[], o: { truncated?: boolean } = {}): string {
|
||||
if (!forms.length || !text) return text;
|
||||
let out = text;
|
||||
for (const f of forms) if (out.includes(f)) out = out.split(f).join(MASK);
|
||||
if (/[\r\n]/.test(out)) for (const f of forms) if (f.length >= WRAP_MIN) out = out.replace(wrapped(f), MASK);
|
||||
if (o.truncated) {
|
||||
const maxCut = Math.max(...forms.map((f) => f.length)) - 1;
|
||||
for (let n = Math.min(maxCut, out.length); n >= TAIL_MIN; n--) {
|
||||
const tail = out.slice(-n);
|
||||
if (forms.some((f) => f.length > n && f.startsWith(tail))) {
|
||||
out = out.slice(0, -n) + MASK;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@ -19,7 +19,7 @@ import { appendJournal, type ConnectionJournalDecision } from "./connection-jour
|
||||
import { decrypt, encrypt, newDataKey, openWithKey, sealWithKey } from "./crypto.ts";
|
||||
import { deliverToUser } from "./notifications.ts";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
import { maskSecrets } from "./secrets.ts";
|
||||
import { connectionKeyForms, maskConnectionKey } from "./connection-mask.ts";
|
||||
import { projectForUser } from "./users.ts";
|
||||
|
||||
export const CONNECTION_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"] as const;
|
||||
@ -801,8 +801,11 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?:
|
||||
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 };
|
||||
// PEP-258: every recognisable form of the key (base64, URL, hex, JSON, wrapped, cut at the limit).
|
||||
const forms = connectionKeyForms(secret, conn.authKind);
|
||||
const text = maskConnectionKey(res.body.toString("utf8"), forms, { truncated: res.truncated });
|
||||
const contentType = res.contentType == null ? null : maskConnectionKey(res.contentType, forms);
|
||||
return { ok: true, status: res.status, contentType, body: text, truncated: res.truncated };
|
||||
} catch (e) {
|
||||
const reason = e instanceof Refused ? e.reason : "upstream_error";
|
||||
await result(reason === "blocked_address" ? "denied" : "failed", reason, null);
|
||||
|
||||
@ -111,6 +111,7 @@ export * from "./accept-digest.ts";
|
||||
export * from "./connections.ts";
|
||||
export * from "./connection-journal.ts";
|
||||
export * from "./connection-catalog.ts";
|
||||
export * from "./connection-mask.ts";
|
||||
export * from "./edge-dns.ts";
|
||||
export * from "./retention.ts";
|
||||
export * from "./history.ts";
|
||||
|
||||
@ -7,7 +7,7 @@ import type { AddressInfo } from "node:net";
|
||||
import { after, before, describe, test } from "node:test";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { core, db, project, teardown } from "./helpers.ts";
|
||||
|
||||
process.env.PEPPA_SECRET ??= "mock-access-hub-secret";
|
||||
@ -368,3 +368,181 @@ describe("разбор операций и путей", () => {
|
||||
for (const ip of ["8.8.8.8", "1.1.1.1", "2606:4700:4700::1111"]) assert.equal(core.isBlockedAddress(ip), false, ip);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------- PEP-258: the key never reaches the agent in any form ----------
|
||||
// Scenario names follow openspec/changes/pep-258-access-hub-key-leak/specs/access-hub/spec.md.
|
||||
|
||||
/** What a careless/hostile service may echo back; checked independently of connectionKeyForms. */
|
||||
function trapForms(key: string): Record<string, string> {
|
||||
const b64 = (s: string) => Buffer.from(s).toString("base64");
|
||||
return {
|
||||
raw: key,
|
||||
base64: b64(key),
|
||||
base64url: Buffer.from(key).toString("base64url"),
|
||||
basicHeader: `Basic ${b64(key)}`,
|
||||
base64InJson1: b64(`{"token":"${key}"}`),
|
||||
base64InJson2: b64(`x{"t":"${key}"}`),
|
||||
base64InJson3: b64(`xy{"t":"${key}"}`),
|
||||
base64Wrapped: (b64(`-----BEGIN-----\n${key}\n${key}\n${key}`).match(/.{1,20}/g) ?? []).join("\r\n"),
|
||||
uri: encodeURIComponent(key),
|
||||
uriLower: encodeURIComponent(key).replace(/%[0-9A-F]{2}/g, (m) => m.toLowerCase()),
|
||||
form: new URLSearchParams({ k: key }).toString().slice(2),
|
||||
hex: Buffer.from(key).toString("hex"),
|
||||
HEX: Buffer.from(key).toString("hex").toUpperCase(),
|
||||
json: JSON.stringify(key).slice(1, -1).replace(/\//g, "\\/"),
|
||||
unicode: [...key].map((c) => `\\u${c.codePointAt(0)!.toString(16).padStart(4, "0")}`).join(""),
|
||||
};
|
||||
}
|
||||
|
||||
/** Every way to read the key (or the basic password) back out of a text: plain, URL, JSON, hex, base64 at any offset, unwrapped. */
|
||||
function leaks(text: string, secrets: string[]): string[] {
|
||||
const found: string[] = [];
|
||||
const candidates = new Set<string>([text, text.replace(/\r?\n/g, "")]);
|
||||
for (const t of [...candidates]) {
|
||||
try {
|
||||
candidates.add(decodeURIComponent(t));
|
||||
} catch {}
|
||||
try {
|
||||
candidates.add(decodeURIComponent(t.replace(/\+/g, " ")));
|
||||
} catch {}
|
||||
candidates.add(t.replace(/\\u([0-9a-fA-F]{4})/g, (_, h) => String.fromCharCode(parseInt(h, 16))).replace(/\\\//g, "/"));
|
||||
for (const run of t.match(/[0-9a-fA-F]{8,}/g) ?? []) for (const o of [0, 1]) candidates.add(Buffer.from(run.slice(o), "hex").toString("latin1") + Buffer.from(run.slice(o), "hex").toString("utf8"));
|
||||
for (const run of t.match(/[A-Za-z0-9+/_-]{8,}/g) ?? []) for (let o = 0; o < 4; o++) candidates.add(Buffer.from(run.slice(o), "base64").toString("utf8"));
|
||||
}
|
||||
for (const c of candidates) for (const s of secrets) if (c.includes(s)) found.push(`${s.slice(0, 6)}… in ${JSON.stringify(c.slice(0, 120))}`);
|
||||
return found;
|
||||
}
|
||||
|
||||
const TRAP_LIMIT = 256 * 1024;
|
||||
let trap: Server;
|
||||
let trapOrigin: string;
|
||||
|
||||
/** Pulls the key out of a request the way the service sees it, for every placement. */
|
||||
function keyOf(req: { url?: string; headers: IncomingHttpHeaders }): string {
|
||||
const u = new URL(req.url!, "http://x");
|
||||
const auth = String(req.headers.authorization ?? "");
|
||||
if (auth.startsWith("Bearer ")) return auth.slice(7);
|
||||
if (auth.startsWith("Basic ")) return Buffer.from(auth.slice(6), "base64").toString("utf8");
|
||||
if (req.headers["x-trap-key"]) return String(req.headers["x-trap-key"]);
|
||||
if (u.searchParams.get("trap_key")) return u.searchParams.get("trap_key")!;
|
||||
const m = /\/bot([^/]+)\//.exec(u.pathname);
|
||||
return m ? decodeURIComponent(m[1]!) : "";
|
||||
}
|
||||
|
||||
before(async () => {
|
||||
trap = createServer((req, res) => {
|
||||
req.resume();
|
||||
req.on("end", () => {
|
||||
const key = keyOf(req);
|
||||
const forms = trapForms(key);
|
||||
const path = new URL(req.url!, "http://x").pathname;
|
||||
const leakHeaders = { "x-echo-key": encodeURIComponent(key), "set-cookie": `s=${forms.base64}`, "www-authenticate": `Bearer realm="${forms.uri}"` };
|
||||
if (path.endsWith("/trap/redirect")) {
|
||||
res.writeHead(302, { ...leakHeaders, location: `https://evil.example/collect?k=${forms.uri}` });
|
||||
return res.end(`moved: ${key}`);
|
||||
}
|
||||
if (path.endsWith("/trap/error")) {
|
||||
res.writeHead(500, { ...leakHeaders, "content-type": "text/plain" });
|
||||
return res.end(`Error: invalid token ${key}\n at checkAuth (/srv/app/auth.js:12:7) [header=${forms.basicHeader}]\n at handler (/srv/app/index.js:40:3) url=${forms.uri}`);
|
||||
}
|
||||
if (path.endsWith("/trap/big")) {
|
||||
// The key starts 6 bytes before the gateway's 256 KB cut.
|
||||
res.writeHead(200, { ...leakHeaders, "content-type": "text/plain" });
|
||||
return res.end("x".repeat(TRAP_LIMIT - 6) + key + "y".repeat(1000));
|
||||
}
|
||||
res.writeHead(200, { ...leakHeaders, "content-type": `application/json; charset=utf-8; boundary=${forms.uri}` });
|
||||
res.end(JSON.stringify({ ...forms, message: `Your token is ${key}`, nested: { wrapped: forms.base64Wrapped } }, null, 1));
|
||||
});
|
||||
});
|
||||
await new Promise<void>((r) => trap.listen(0, "127.0.0.1", r));
|
||||
trapOrigin = `http://127.0.0.1:${(trap.address() as AddressInfo).port}`;
|
||||
});
|
||||
after(async () => {
|
||||
await new Promise<void>((r) => trap.close(() => r()));
|
||||
});
|
||||
|
||||
describe("Ключ в другой форме тоже скрыт (PEP-258)", () => {
|
||||
// Special characters exercise every encoding (header values are ASCII only); the path placement allows only [A-Za-z0-9:_.-].
|
||||
const SPECIAL = "mock-user:sk_live_TRAP/7f+3a9c=ключ&x y";
|
||||
const kinds: Array<{ kind: string; secret: string; input: (n: string) => Parameters<typeof core.createConnection>[2] }> = [
|
||||
{ kind: "bearer", secret: SPECIAL.replace(/[^\x20-\x7e]/g, "Q"), input: (name) => ({ name, baseUrl: `${trapOrigin}/api`, secret: SPECIAL.replace(/[^\x20-\x7e]/g, "Q") }) },
|
||||
{ kind: "header", secret: SPECIAL.replace(/[^\x20-\x7e]/g, "Q"), input: (name) => ({ name, baseUrl: `${trapOrigin}/api`, secret: SPECIAL.replace(/[^\x20-\x7e]/g, "Q"), authKind: "header", authHeader: "X-Trap-Key" }) },
|
||||
{ kind: "basic", secret: SPECIAL, input: (name) => ({ name, baseUrl: `${trapOrigin}/api`, secret: SPECIAL, authKind: "basic" }) },
|
||||
{ kind: "query", secret: SPECIAL, input: (name) => ({ name, baseUrl: `${trapOrigin}/api`, secret: SPECIAL, authKind: "query", authHeader: "trap_key" }) },
|
||||
{ kind: "path", secret: "123456789:AAH_mock-TRAP.key_7f3a9c", input: (name) => ({ name, catalogId: "telegram", secret: "123456789:AAH_mock-TRAP.key_7f3a9c" }) },
|
||||
];
|
||||
|
||||
for (const k of kinds) {
|
||||
test(`Тест-ловушка: способ ключа ${k.kind} — ни одна форма ключа не доходит до агента`, async () => {
|
||||
const name = `Trap-${k.kind}`;
|
||||
const c = await core.createConnection(db, anna.id, k.input(name));
|
||||
// The catalog card's address is fixed (api.telegram.org): point the row at the trap for the test.
|
||||
if (k.kind === "path") await db.update(connections).set({ baseUrl: trapOrigin }).where(eq(connections.id, c.id));
|
||||
const { proj, task } = await ownedProject(anna.id);
|
||||
await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, operations: "GET /trap" });
|
||||
const { sessionId } = await agentSession(proj.id, task.id);
|
||||
const secrets = [k.secret, ...(k.kind === "basic" ? [k.secret.slice(k.secret.indexOf(":") + 1)] : [])];
|
||||
const seenByAgent: string[] = [];
|
||||
|
||||
// 1. The gateway itself, every trap route.
|
||||
const body = await call(sessionId, c.id, "GET", "/trap/body");
|
||||
assert.equal(body.ok, true, JSON.stringify(body));
|
||||
if (body.ok) {
|
||||
assert.match(body.body, /••••/, "the service did echo the key");
|
||||
assert.ok(body.contentType?.startsWith("application/json"));
|
||||
}
|
||||
const err = await call(sessionId, c.id, "GET", "/trap/error");
|
||||
assert.equal(err.ok && err.status, 500);
|
||||
const red = await call(sessionId, c.id, "GET", "/trap/redirect");
|
||||
assert.deepEqual(red, { ok: false, reason: "redirect", status: 302 }, "a redirect is never followed, its address never returned");
|
||||
const big = await call(sessionId, c.id, "GET", "/trap/big");
|
||||
assert.equal(big.ok && big.truncated, true);
|
||||
if (big.ok) assert.ok(big.body.endsWith("••••"), "the cut beginning of the key is masked");
|
||||
seenByAgent.push(JSON.stringify([body, err, red, big]));
|
||||
|
||||
// 2. The agent's MCP: direct tool and code mode (PEP-212), answers and errors.
|
||||
const mcp = await mcpAgent(sessionId, proj.key);
|
||||
for (const p of ["/trap/body", "/trap/error", "/trap/redirect", "/trap/big"]) {
|
||||
const r = await mcp("call_connection", { connection: c.slug ?? name, method: "GET", path: p });
|
||||
seenByAgent.push(r.text);
|
||||
const ex = await mcp("execute", { code: `return await peppa.connections.call({ connection: ${JSON.stringify(c.slug ?? name)}, method: "GET", path: ${JSON.stringify(p)} })` });
|
||||
seenByAgent.push(ex.text);
|
||||
}
|
||||
const exErr = await mcp("execute", { code: `try { await peppa.connections.call({ connection: ${JSON.stringify(c.slug ?? name)}, method: "GET", path: "/trap/redirect" }) } catch (e) { return String(e && e.stack || e) }` });
|
||||
seenByAgent.push(exErr.text);
|
||||
seenByAgent.push((await mcp("list_connections")).text, (await mcp("list_secrets")).text, (await mcp("get_task", { task: task.key })).text);
|
||||
|
||||
// 3. The agent's environment (PEP-54) and the session's steps.
|
||||
seenByAgent.push(JSON.stringify(await core.projectSecretEnv(db, proj.id, "agent")), JSON.stringify(await core.projectSecretEnv(db, proj.id, "deploy")));
|
||||
seenByAgent.push(JSON.stringify(await core.sessionSteps(db, sessionId, 200)));
|
||||
|
||||
// 4. Nothing stored anywhere: every table of the database (journal, events, chats, settings…).
|
||||
const tables = (await db.all<{ name: string }>(sql`SELECT name FROM sqlite_master WHERE type = 'table'`)).map((t) => t.name);
|
||||
for (const t of tables) seenByAgent.push(JSON.stringify(await db.all(sql.raw(`SELECT * FROM "${t}"`))));
|
||||
|
||||
for (const text of seenByAgent) assert.deepEqual(leaks(text, secrets), [], text.slice(0, 300));
|
||||
// The journal has the calls — without query, key or body.
|
||||
const log = await core.connectionJournal(db, anna.id, { connectionId: c.id });
|
||||
assert.ok(log.length >= 8);
|
||||
assert.ok(log.every((l) => l.path.startsWith("/trap/")));
|
||||
});
|
||||
}
|
||||
|
||||
test("Маскировка: base64 внутри длинной строки, переносы, обрезанный хвост", () => {
|
||||
const key = "sk_live_TRAP_7f3a9c_long";
|
||||
const forms = core.connectionKeyForms(key, "bearer");
|
||||
for (const [name, form] of Object.entries(trapForms(key))) {
|
||||
const out = core.maskConnectionKey(`before ${form} after`, forms);
|
||||
assert.deepEqual(leaks(out, [key]), [], `${name}: ${out}`);
|
||||
}
|
||||
// A short tail that is not a key prefix stays as is; the beginning of the key at the cut is masked.
|
||||
assert.equal(core.maskConnectionKey("abc xyz", forms, { truncated: true }), "abc xyz");
|
||||
assert.equal(core.maskConnectionKey("data sk_live_TR", forms, { truncated: true }), "data ••••");
|
||||
assert.equal(core.maskConnectionKey("data sk_live_TR", forms), "data sk_live_TR", "not cut — not a key");
|
||||
// basic: the password alone is masked, the login is not.
|
||||
const basic = core.connectionKeyForms("anna@example.com:pa55word!", "basic");
|
||||
assert.equal(core.maskConnectionKey("user anna@example.com pass pa55word!", basic), "user anna@example.com pass ••••");
|
||||
// Ordinary data is untouched.
|
||||
assert.equal(core.maskConnectionKey('{"items":[1,2,3],"name":"Анна"}', forms), '{"items":[1,2,3],"name":"Анна"}');
|
||||
});
|
||||
});
|
||||
|
||||
Loading…
Reference in New Issue
Block a user