peppa/packages/testkit/test/repo-visibility.test.ts
peppa-bot ec7345f483
Some checks failed
peppa/lint lint: success за 3с
peppa/typecheck typecheck: success за 51с
peppa/build build: success за 36с
peppa/bundle bundle: success за 0с
peppa/test test: failure за 1591с
peppa-ci / ci (pull_request) Failing after 28m44s
PEP-317: страница «Gitea» не ждёт Git-сервер — список из памяти при любом возрасте, переживает перезапуск
Последний список отдаётся сразу (старше минуты — обновление в фоне), хранится в settings
`gitea.overview` и прогревается при старте веба; без списка — «загружается». Ждёт Gitea
только «Получить заново» и «Сделать закрытым».

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:13:36 +00:00

324 lines
18 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PEP-15: where the project's Gitea repo is, its visibility and who can see it.
// PEP-64: the owner (or the CLI) changes visibility later. PEP-280: private by default, public by choice;
// the superadmin closes public repos one by one on the «Gitea» page.
import assert from "node:assert/strict";
import { execFile, execFileSync } from "node:child_process";
import { promisify } from "node:util";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { after, before, describe, test } from "node:test";
import { core, db, runner, teardown } from "./helpers.ts";
import { events } from "@peppa/db";
import { MockGitea } from "../src/mock-gitea.ts";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
const TMP = mkdtempSync(join(tmpdir(), "peppa-vis-"));
process.env.PEPPA_SECRET = "mock-secret-for-tests";
process.env.PEPPA_WORKSPACES = join(TMP, "workspaces");
const { createManagerServer } = await import("@peppa/mcp/manager");
const gitea = new MockGitea(join(TMP, "gitea"));
const ALICE = { id: 61, login: "mock-vis-alice", token: "mock-token-vis-alice", orgs: ["mock-vis-team"] };
const BOB = { id: 62, login: "mock-vis-bob", token: "mock-token-vis-bob" };
const BOT = { id: 63, login: "peppa-bot", token: "mock-token-vis-bot", siteAdmin: true };
const ROOT_ADMIN = { id: 64, login: "mock-vis-root", token: "mock-token-vis-root" };
type U = Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
let alice: U, bob: U, root: U;
let templateUrl = "";
before(async () => {
await gitea.start();
process.env.GITEA_URL = gitea.url;
process.env.GITEA_TOKEN = BOT.token;
for (const u of [ALICE, BOB, BOT, ROOT_ADMIN]) gitea.addUser(u);
const tpl = gitea.addRepo("peppa-bot", "template");
execFileSync("bash", ["-c", `cd ${JSON.stringify(join(ROOT, "template"))} && T=$(mktemp -d) && cp -R . "$T" && cd "$T" && git init -q -b main && git add -A && git -c user.name=t -c user.email=t@t commit -qm tpl && git push -q ${JSON.stringify(tpl.path)} main`]);
templateUrl = tpl.path;
alice = await core.upsertUserFromGitea(db, ALICE, { access_token: ALICE.token });
bob = await core.upsertUserFromGitea(db, BOB, { access_token: BOB.token });
root = await core.upsertUserFromGitea(db, ROOT_ADMIN, { access_token: ROOT_ADMIN.token });
await core.setSetting(db, "platform.admins", [ROOT_ADMIN.login]);
});
after(async () => {
await gitea.stop();
await teardown();
});
const provision = async (over: Partial<Parameters<typeof runner.provisionProject>[1]> & { slug: string; key: string }) =>
runner.provisionProject(db, {
gitea: await core.giteaForUser(db, alice),
owner: ALICE.login,
ownerIsUser: true,
name: `Mock ${over.key}`,
ownerId: alice.id,
templateUrl,
...over,
});
async function mcpAs(user: U) {
const [a, b] = InMemoryTransport.createLinkedPair();
await createManagerServer(db, user, "https://peppa.test").connect(a);
const client = new Client({ name: "mock-chatgpt", version: "0" });
await client.connect(b);
return async (name: string, args: Record<string, unknown> = {}) => {
const r = await client.callTool({ name, arguments: args });
return { text: (r.content as Array<{ text: string }>)[0]!.text, isError: !!r.isError };
};
}
describe("repo visibility and namespace", () => {
test("PEP-280: new project by default is private", async () => {
const p = await provision({ slug: "mock-vis-default", key: "MVDEF" });
assert.equal(gitea.repos.get(`${ALICE.login}/mock-vis-default`)!.private, true);
const repo = await runner.describeRepo(db, p);
assert.equal(core.repoVisibilityLabel(repo.private), "приватный");
assert.equal(core.repoAudience(repo), `${ALICE.login} и соавторы: peppa-bot`);
});
test("PEP-215: peekRepo does not wait for Gitea — cache or fallback at once, refreshed in the background", async () => {
const p = await provision({ slug: "mock-vis-peek", key: "MVPEEK" });
runner.forgetRepoInfo(p.id);
const cold = runner.peekRepo(db, p);
assert.equal(cold.private, null);
assert.equal(cold.fullName, `${ALICE.login}/mock-vis-peek`);
assert.equal(cold.url, `${gitea.url}/${ALICE.login}/mock-vis-peek`);
// The background refresh fills the cache; the next call has the visibility.
for (let i = 0; i < 50 && runner.peekRepo(db, p).private === null; i++) await new Promise((r) => setTimeout(r, 40));
assert.equal(runner.peekRepo(db, p).private, true);
});
test("PEP-215: listSessions with a limit returns the newest sessions of the project only", async () => {
const all = await core.listSessions(db);
const some = all[0];
if (!some) return;
const one = await core.listSessions(db, { projectId: some.projectId, limit: 1 });
assert.equal(one.length, 1);
assert.ok(one.every((x) => x.projectId === some.projectId));
});
test("private by choice: private repo in the personal namespace, seen by the owner and collaborators", async () => {
const p = await provision({ slug: "mock-vis-demo", key: "MVDEMO", visibility: "private" });
assert.equal(gitea.repos.get(`${ALICE.login}/mock-vis-demo`)!.private, true);
const repo = await runner.describeRepo(db, p);
assert.equal(repo.fullName, `${ALICE.login}/mock-vis-demo`);
assert.equal(repo.url, `${gitea.url}/${ALICE.login}/mock-vis-demo`);
assert.equal(repo.private, true);
assert.equal(repo.ownerKind, "user");
assert.deepEqual(repo.collaborators, ["peppa-bot"]);
assert.equal(core.repoAudience(repo), `${ALICE.login} и соавторы: peppa-bot`);
});
test("public repo in an org", async () => {
const p = await provision({ slug: "mock-vis-pub", key: "MVPUB", owner: "mock-vis-team", ownerIsUser: false, visibility: "public" });
assert.equal(gitea.repos.get("mock-vis-team/mock-vis-pub")!.private, false);
const repo = await runner.describeRepo(db, p);
assert.equal(repo.private, false);
assert.equal(repo.ownerKind, "org");
assert.equal(core.repoAudience(repo), "все, у кого есть доступ к Gitea");
assert.equal(core.repoVisibilityLabel(repo.private), "публичный");
});
test("existing repo keeps its visibility", async () => {
gitea.addRepo(ALICE.login, "mock-vis-legacy", { files: { "main.go": "package main\n" }, private: true });
await provision({ slug: "mock-vis-legacy", key: "MVLEG", existing: true, visibility: "public" });
assert.equal(gitea.repos.get(`${ALICE.login}/mock-vis-legacy`)!.private, true);
});
test("who can see: outline", () => {
const rows: Array<[boolean | null, "user" | "org", string, string]> = [
[true, "user", "alice/x", "alice и соавторы: peppa-bot, bob"],
[true, "org", "team/x", "участники организации team с доступом к репозиторию и соавторы: peppa-bot, bob"],
[false, "user", "alice/x", "все, у кого есть доступ к Gitea"],
[null, "user", "alice/x", "не удалось узнать у Gitea"],
];
for (const [priv, ownerKind, fullName, want] of rows) {
assert.equal(core.repoAudience({ fullName, private: priv, ownerKind, collaborators: ["peppa-bot", "bob"] }), want);
}
});
test("member without repo access is visible; owner grants access to all members", async () => {
const p = await provision({ slug: "mock-vis-team-app", key: "MVTEAM", visibility: "private" });
await core.addMember(db, p, BOB.login, alice.id); // FORGE membership only, no Gitea collaborator
let repo = await runner.describeRepo(db, p, { fresh: true });
assert.ok(!repo.collaborators!.includes(BOB.login));
await assert.rejects(runner.grantRepoAccess(db, bob, p), /только владелец/);
const r = await runner.grantRepoAccess(db, alice, p);
assert.deepEqual(r, { granted: [BOB.login], failed: [] });
assert.equal(gitea.repos.get(`${ALICE.login}/mock-vis-team-app`)!.collaborators[BOB.login], "write");
repo = await runner.describeRepo(db, p);
assert.ok(repo.collaborators!.includes(BOB.login), "cache dropped after granting");
});
test("Gitea unreachable: path and link from FORGE, visibility unknown", async () => {
const p = await core.getProject(db, "MVDEMO");
const url = process.env.GITEA_URL;
process.env.GITEA_URL = "http://127.0.0.1:9";
try {
const repo = await runner.describeRepo(db, p, { fresh: true });
assert.equal(repo.fullName, `${ALICE.login}/mock-vis-demo`);
assert.equal(repo.url, `http://127.0.0.1:9/${ALICE.login}/mock-vis-demo`);
assert.equal(repo.private, null);
assert.equal(core.repoAudience(repo), "не удалось узнать у Gitea");
} finally {
process.env.GITEA_URL = url;
}
});
test("MCP: create_project takes visibility and returns the repo URL and who sees it; list_projects shows URLs", async () => {
const call = await mcpAs(alice);
process.env.PEPPA_TEMPLATE_URL = templateUrl;
try {
const r = await call("create_project", { name: "Mock MCP", slug: "mock-vis-mcp", key: "MVMCP", visibility: "public" });
assert.equal(r.isError, false, r.text);
assert.match(r.text, new RegExp(`Repo: ${gitea.url}/${ALICE.login}/mock-vis-mcp \\(публичный, personal namespace\\)`));
assert.match(r.text, /Who can see it: все, у кого есть доступ к Gitea/);
assert.equal(gitea.repos.get(`${ALICE.login}/mock-vis-mcp`)!.private, false);
} finally {
delete process.env.PEPPA_TEMPLATE_URL;
}
const list = await call("list_projects");
assert.match(list.text, new RegExp(`MVMCP — Mock MCP \\(${gitea.url}/${ALICE.login}/mock-vis-mcp\\)`));
});
test("PEP-280: MCP create_project without visibility makes a private repo", async () => {
const call = await mcpAs(alice);
process.env.PEPPA_TEMPLATE_URL = templateUrl;
try {
const r = await call("create_project", { name: "Mock MCP default", slug: "mock-vis-mcp-def", key: "MVMCPD" });
assert.equal(r.isError, false, r.text);
assert.match(r.text, /\(приватный, personal namespace\)/);
assert.equal(gitea.repos.get(`${ALICE.login}/mock-vis-mcp-def`)!.private, true);
} finally {
delete process.env.PEPPA_TEMPLATE_URL;
}
});
});
describe("changing visibility of an existing project (PEP-64)", () => {
test("owner makes the repo public: Gitea and the project card show it at once", async () => {
const p = await core.getProject(db, "MVDEF");
assert.equal((await runner.describeRepo(db, p)).private, true); // cached as private
const repo = await runner.setProjectVisibility(db, p, "public", { actor: alice });
assert.equal(gitea.repos.get(`${ALICE.login}/mock-vis-default`)!.private, false);
assert.equal(repo.private, false);
const card = await runner.describeRepo(db, p); // no stale cache
assert.equal(core.repoVisibilityLabel(card.private), "публичный");
assert.equal(core.repoAudience(card), "все, у кого есть доступ к Gitea");
});
test("MCP: set_project_visibility makes it private and says who sees it", async () => {
const call = await mcpAs(alice);
const r = await call("set_project_visibility", { project: "MVDEF", visibility: "private" });
assert.equal(r.isError, false, r.text);
assert.match(r.text, new RegExp(`MVDEF: репозиторий ${ALICE.login}/mock-vis-default теперь приватный`));
assert.match(r.text, new RegExp(`Who can see it: ${ALICE.login} и соавторы: peppa-bot`));
assert.equal(gitea.repos.get(`${ALICE.login}/mock-vis-default`)!.private, true);
// PEP-280: the change is in the project's journal.
const p = await core.getProject(db, "MVDEF");
const ev = (await db.select().from(events)).filter((e) => e.projectId === p.id && e.type === "repo_visibility_changed");
assert.deepEqual(ev.map((e) => (e.payload as { visibility: string }).visibility), ["public", "private"]);
});
test("not the owner: refused, visibility unchanged", async () => {
const p = await core.getProject(db, "MVDEF");
await core.addMember(db, p, BOB.login, alice.id);
await assert.rejects(runner.setProjectVisibility(db, p, "public", { actor: bob }), /меняет только владелец проекта/);
const call = await mcpAs(bob);
const r = await call("set_project_visibility", { project: "MVDEF", visibility: "public" });
assert.equal(r.isError, true);
assert.match(r.text, /меняет только владелец проекта/);
assert.equal(gitea.repos.get(`${ALICE.login}/mock-vis-default`)!.private, true);
});
test("no admin rights in Gitea: clear error, visibility unchanged", async () => {
// A repo in bob's namespace that alice's project points to: neither alice nor peppa-bot administers it.
gitea.addRepo(BOB.login, "mock-vis-foreign", { admins: [BOB.login], private: false });
const p = await core.createProject(db, { slug: "mock-vis-foreign", key: "MVFOR", name: "Foreign", giteaOwner: BOB.login, giteaRepo: "mock-vis-foreign", workspacePath: join(TMP, "foreign") });
await core.setProjectOwner(db, p.id, alice.id);
const owned = await core.getProject(db, "MVFOR");
await assert.rejects(runner.setProjectVisibility(db, owned, "private", { actor: alice }), /Не удалось сменить видимость mock-vis-bob\/mock-vis-foreign: нет прав администратора на код проекта/);
assert.equal(gitea.repos.get(`${BOB.login}/mock-vis-foreign`)!.private, false);
});
test("CLI: peppa project visibility --all public|private, one line per project", async () => {
// Async: mock-gitea answers from this process.
const cli = async (...a: string[]) => {
try {
const r = await promisify(execFile)(join(ROOT, "packages/cli/bin/peppa"), ["project", "visibility", ...a], { encoding: "utf8", env: process.env });
return { out: r.stdout + r.stderr, code: 0 };
} catch (e) {
const x = e as { stdout: string; stderr: string; code: number };
return { out: x.stdout + x.stderr, code: x.code };
}
};
const mine = [...gitea.repos.values()].filter((r) => r.owner === ALICE.login || r.owner === "mock-vis-team");
const one = await cli("MVDEMO", "public");
assert.equal(one.code, 0, one.out);
assert.match(one.out, new RegExp(`MVDEMO\\s+${ALICE.login}/mock-vis-demo → публичный`));
const all = await cli("--all", "private");
assert.equal(all.code, 1, all.out); // MVFOR: no admin rights → reported, the rest still switched
assert.match(all.out, /MVFOR .*✗ Не удалось сменить видимость/);
assert.match(all.out, /MVMCP\s+.*→ приватный/);
const projects = ["mock-vis-demo", "mock-vis-pub", "mock-vis-mcp", "mock-vis-default"];
for (const name of projects) {
const r = mine.find((x) => x.name === name)!;
assert.equal(r.private, true, `${name} private`);
}
const back = await cli("--all", "public");
for (const name of projects) assert.equal(mine.find((x) => x.name === name)!.private, false, `${name} public again`);
assert.match(back.out, /MVPUB\s+mock-vis-team\/mock-vis-pub → публичный/);
assert.match((await cli("MVDEMO")).out, /usage: peppa project visibility/);
});
});
describe("PEP-280: the superadmin closes public repositories one by one", () => {
test("the «Gitea» overview shows which repositories are public", async () => {
gitea.addRepo("peppa-bot", "mock-vis-old", { admins: ["peppa-bot"], private: false });
const o = await core.giteaServerOverview(db, { fresh: true });
assert.equal(o.error, null);
assert.equal(o.bot?.admin, true);
const pub = o.repos.filter((r) => !r.private).map((r) => r.fullName).sort();
assert.ok(pub.includes("peppa-bot/mock-vis-old"), pub.join(","));
assert.ok(pub.includes(`${ALICE.login}/mock-vis-demo`), pub.join(",")); // made public by the CLI test
assert.equal(o.repos.find((r) => r.fullName === `${ALICE.login}/mock-vis-demo`)!.project?.key, "MVDEMO");
});
test("not a superadmin: refused, nothing changes", async () => {
await assert.rejects(runner.makeRepoPrivate(db, alice, `${ALICE.login}/mock-vis-demo`), /только суперадмин/);
assert.equal(gitea.repos.get(`${ALICE.login}/mock-vis-demo`)!.private, false);
});
test("a project's repository: closed the owner's way, in the project's journal, by the superadmin's name", async () => {
const r = await runner.makeRepoPrivate(db, root, `${ALICE.login}/mock-vis-demo`);
assert.deepEqual(r, { fullName: `${ALICE.login}/mock-vis-demo`, projectKey: "MVDEMO" });
assert.equal(gitea.repos.get(`${ALICE.login}/mock-vis-demo`)!.private, true);
const p = await core.getProject(db, "MVDEMO");
assert.equal((await runner.describeRepo(db, p)).private, true); // no stale cache
const ev = (await db.select().from(events)).filter((e) => e.projectId === p.id && e.type === "repo_visibility_changed").at(-1)!;
assert.deepEqual(ev.payload, { visibility: "private", repo: `${ALICE.login}/mock-vis-demo`, login: ROOT_ADMIN.login });
// Only that one: the other public repositories stay as they were.
assert.equal(gitea.repos.get("mock-vis-team/mock-vis-pub")!.private, false);
});
test("a repository without a project: closed as the bot", async () => {
const r = await runner.makeRepoPrivate(db, root, "peppa-bot/mock-vis-old");
assert.deepEqual(r, { fullName: "peppa-bot/mock-vis-old", projectKey: null });
assert.equal(gitea.repos.get("peppa-bot/mock-vis-old")!.private, true);
await assert.rejects(runner.makeRepoPrivate(db, root, "peppa-bot/mock-vis-missing"), /код проекта не найден/);
await assert.rejects(runner.makeRepoPrivate(db, root, "nonsense"), /Не понял, какой код закрыть/);
});
test("CLI: peppa project create is private unless --public", async () => {
const create = async (...a: string[]) =>
promisify(execFile)(join(ROOT, "packages/cli/bin/peppa"), ["project", "create", ...a], { encoding: "utf8", env: { ...process.env, PEPPA_TEMPLATE_URL: templateUrl } });
await create("mock-vis-cli", "MVCLI", "CLI default");
assert.equal(gitea.repos.get("peppa-bot/mock-vis-cli")!.private, true);
await create("mock-vis-cli-pub", "MVCLIP", "CLI public", "--public");
assert.equal(gitea.repos.get("peppa-bot/mock-vis-cli-pub")!.private, false);
});
});