247 lines
13 KiB
TypeScript
247 lines
13 KiB
TypeScript
// PEP-15: where the project's Gitea repo is, its visibility and who can see it.
|
||
// PEP-64: public by default, private by choice; the owner (or the CLI) changes it later.
|
||
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 { 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" };
|
||
type U = Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
let alice: U, bob: 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]) 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 });
|
||
});
|
||
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("new project by default is public", async () => {
|
||
const p = await provision({ slug: "mock-vis-default", key: "MVDEF" });
|
||
assert.equal(gitea.repos.get(`${ALICE.login}/mock-vis-default`)!.private, false);
|
||
const repo = await runner.describeRepo(db, p);
|
||
assert.equal(core.repoVisibilityLabel(repo.private), "публичный");
|
||
assert.equal(core.repoAudience(repo), "все, у кого есть доступ к Gitea");
|
||
});
|
||
|
||
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); // Peppa 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 Peppa, 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("MCP: create_project without visibility makes a public 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, false);
|
||
} finally {
|
||
delete process.env.PEPPA_TEMPLATE_URL;
|
||
}
|
||
});
|
||
});
|
||
|
||
describe("changing visibility of an existing project (PEP-64)", () => {
|
||
test("owner makes the repo private: 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, false); // cached as public
|
||
const repo = await runner.setProjectVisibility(db, p, "private", { actor: alice });
|
||
assert.equal(gitea.repos.get(`${ALICE.login}/mock-vis-default`)!.private, true);
|
||
assert.equal(repo.private, true);
|
||
const card = await runner.describeRepo(db, p); // no stale cache
|
||
assert.equal(core.repoVisibilityLabel(card.private), "приватный");
|
||
assert.equal(core.repoAudience(card), `${ALICE.login} и соавторы: peppa-bot`);
|
||
});
|
||
|
||
test("MCP: set_project_visibility makes it public and says who sees it", async () => {
|
||
const call = await mcpAs(alice);
|
||
const r = await call("set_project_visibility", { project: "MVDEF", visibility: "public" });
|
||
assert.equal(r.isError, false, r.text);
|
||
assert.match(r.text, new RegExp(`MVDEF: репозиторий ${ALICE.login}/mock-vis-default теперь публичный`));
|
||
assert.match(r.text, /Who can see it: все, у кого есть доступ к Gitea/);
|
||
assert.equal(gitea.repos.get(`${ALICE.login}/mock-vis-default`)!.private, false);
|
||
});
|
||
|
||
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, "private", { actor: bob }), /меняет только владелец проекта/);
|
||
const call = await mcpAs(bob);
|
||
const r = await call("set_project_visibility", { project: "MVDEF", visibility: "private" });
|
||
assert.equal(r.isError, true);
|
||
assert.match(r.text, /меняет только владелец проекта/);
|
||
assert.equal(gitea.repos.get(`${ALICE.login}/mock-vis-default`)!.private, false);
|
||
});
|
||
|
||
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: нет прав администратора в Gitea/);
|
||
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/);
|
||
});
|
||
});
|