Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 26 additions & 4 deletions src/mcp/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import type { RequestHandlerExtra } from "@modelcontextprotocol/sdk/shared/proto
import { ElicitResultSchema, type ServerNotification, type ServerRequest } from "@modelcontextprotocol/sdk/types.js";
import { z } from "zod";
import { authenticatePrivateToken, extractBearerToken, type AuthIdentity } from "../auth/security";
import { loadControlPanelAccessScope, loadControlPanelRoleSummary } from "../services/control-panel-roles";
import { loadControlPanelAccessScope, loadControlPanelRoleSummary, type ControlPanelAccessScope } from "../services/control-panel-roles";
import {
countOpenIssues,
countOpenPullRequests,
Expand Down Expand Up @@ -423,6 +423,8 @@ async function describeMcpUsageRequest(request: Request, telemetryMetadata: Reco
}

export class GittensoryMcp {
private accessScopePromise: Promise<ControlPanelAccessScope> | null = null;

constructor(
private readonly env: Env,
private readonly identity: AuthIdentity = { kind: "static", actor: "mcp" },
Expand Down Expand Up @@ -816,8 +818,20 @@ export class GittensoryMcp {
}
}

private async requireRepoAccess(repoFullName: string): Promise<void> {
if (await this.canAccessRepo(repoFullName)) return;
throw new Error("Forbidden: session cannot access this repository.");
}

private loadSessionAccessScope(): Promise<ControlPanelAccessScope> {
if (this.identity.kind !== "session") throw new Error("Session access scope is only available for session identities.");
this.accessScopePromise ??= loadControlPanelAccessScope(this.env, this.identity.actor);
return this.accessScopePromise;
}

private async getRepoContext(input: { owner: string; repo: string }): Promise<ToolPayload> {
const fullName = `${input.owner}/${input.repo}`;
await this.requireRepoAccess(fullName);
const [repo, issues, pullRequests, recentMergedPullRequests, queueCounts, queueTrends] = await Promise.all([
getRepository(this.env, fullName),
listIssueSignalSample(this.env, fullName),
Expand All @@ -844,6 +858,7 @@ export class GittensoryMcp {

private async getBurdenForecast(input: { owner: string; repo: string }): Promise<ToolPayload> {
const fullName = `${input.owner}/${input.repo}`;
await this.requireRepoAccess(fullName);
const response = await loadOrComputeBurdenForecastResponse(this.env, fullName);
if (!response) {
return {
Expand Down Expand Up @@ -886,16 +901,16 @@ export class GittensoryMcp {

private async canAccessRepo(fullName: string): Promise<boolean> {
if (this.identity.kind !== "session") return true;
const [summary, repo] = await Promise.all([loadControlPanelRoleSummary(this.env, this.identity.actor), getRepository(this.env, fullName)]);
if (summary.roles.includes("operator")) return true;
const scope = await loadControlPanelAccessScope(this.env, this.identity.actor);
const [scope, repo] = await Promise.all([this.loadSessionAccessScope(), getRepository(this.env, fullName)]);
if (scope.operator) return true;
const requestedRepo = fullName.toLowerCase();
if (scope.repositoryFullNames.some((name) => name.toLowerCase() === requestedRepo)) return true;
return Boolean(repo && scope.accountLogins.some((login) => login.toLowerCase() === repo.owner.toLowerCase()));
}

private async getRepoOutcomePatterns(input: { owner: string; repo: string }): Promise<ToolPayload> {
const fullName = `${input.owner}/${input.repo}`;
await this.requireRepoAccess(fullName);
const response = await loadOrComputeRepoOutcomePatternsResponse(this.env, fullName);
if (!response) {
return {
Expand Down Expand Up @@ -967,6 +982,7 @@ export class GittensoryMcp {
private async explainRepoDecision(input: { login: string; owner: string; repo: string }): Promise<ToolPayload> {
this.requireContributorAccess(input.login);
const fullName = `${input.owner}/${input.repo}`;
await this.requireRepoAccess(fullName);
const serving = await loadContributorDecisionPackForServing(this.env, input.login);
if (serving.kind === "needs_refresh") {
return {
Expand Down Expand Up @@ -1017,6 +1033,7 @@ export class GittensoryMcp {
}

private async preflightPr(input: z.infer<z.ZodObject<typeof preflightShape>>): Promise<ToolPayload> {
await this.requireRepoAccess(input.repoFullName);
const [repo, issues, pullRequests, bounties, issueQuality] = await Promise.all([
getRepository(this.env, input.repoFullName),
listIssues(this.env, input.repoFullName),
Expand All @@ -1031,6 +1048,7 @@ export class GittensoryMcp {
}

private async preflightLocalDiff(input: z.infer<z.ZodObject<typeof localDiffPreflightShape>>): Promise<ToolPayload> {
await this.requireRepoAccess(input.repoFullName);
const [repo, issues, pullRequests, bounties, issueQuality] = await Promise.all([
getRepository(this.env, input.repoFullName),
listIssues(this.env, input.repoFullName),
Expand All @@ -1046,6 +1064,7 @@ export class GittensoryMcp {

private async previewScore(input: z.infer<z.ZodObject<typeof scorePreviewShape>>): Promise<ToolPayload> {
if (input.contributorLogin) this.requireContributorAccess(input.contributorLogin);
await this.requireRepoAccess(input.repoFullName);
const [repo, snapshot, evidence] = await Promise.all([
getRepository(this.env, input.repoFullName),
getOrCreateScoringModelSnapshot(this.env),
Expand All @@ -1060,6 +1079,7 @@ export class GittensoryMcp {

private async explainReviewRisk(input: z.infer<z.ZodObject<typeof preflightShape>>): Promise<ToolPayload> {
if (input.contributorLogin) this.requireContributorAccess(input.contributorLogin);
await this.requireRepoAccess(input.repoFullName);
const [repo, issues, pullRequests, bounties] = await Promise.all([
getRepository(this.env, input.repoFullName),
listIssues(this.env, input.repoFullName),
Expand Down Expand Up @@ -1248,6 +1268,7 @@ export class GittensoryMcp {

private async analyzeLocalBranch(input: z.infer<z.ZodObject<typeof localBranchAnalysisShape>>) {
this.requireContributorAccess(input.login);
await this.requireRepoAccess(input.repoFullName);
const [context, repo, issues, pullRequests, recentMergedPullRequests, bounties, snapshot, issueQuality, repoManifest] = await Promise.all([
this.loadContributorFastContext(input.login),
getRepository(this.env, input.repoFullName),
Expand Down Expand Up @@ -1296,6 +1317,7 @@ export class GittensoryMcp {
private async getBountyAdvisory(id: string): Promise<ToolPayload> {
const bounty = await getBounty(this.env, id);
if (!bounty) throw new Error("Bounty not found.");
if (!(await this.canAccessRepo(bounty.repoFullName))) throw new Error("Bounty not found.");
const [repo, issue, pullRequests] = await Promise.all([
getRepository(this.env, bounty.repoFullName),
getIssue(this.env, bounty.repoFullName, bounty.issueNumber),
Expand Down
39 changes: 39 additions & 0 deletions test/integration/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3553,6 +3553,45 @@ describe("api routes", () => {
expect(body).not.toContain("SECRET roadmap PR title");
expect(body).not.toContain("SECRET-LAUNCH-CODE");
expect(body).not.toContain("confidential-roadmap");

const allowedMcpContext = await app.request(
"/mcp",
{
method: "POST",
headers: { ...mcpHeaders(env), authorization: `Bearer ${token}` },
body: JSON.stringify({
jsonrpc: "2.0",
id: "allowed-session-repo-context",
method: "tools/call",
params: { name: "gittensory_get_repo_context", arguments: { owner: "target-org", repo: "allowed" } },
}),
},
env,
);
expect(allowedMcpContext.status).toBe(200);
await expect(mcpJson(allowedMcpContext)).resolves.toMatchObject({ result: { structuredContent: { repoFullName: "target-org/allowed" } } });

const siblingMcpContext = await app.request(
"/mcp",
{
method: "POST",
headers: { ...mcpHeaders(env), authorization: `Bearer ${token}` },
body: JSON.stringify({
jsonrpc: "2.0",
id: "forbidden-session-repo-context",
method: "tools/call",
params: { name: "gittensory_get_repo_context", arguments: { owner: "target-org", repo: "secret" } },
}),
},
env,
);
expect(siblingMcpContext.status).toBe(200);
const siblingMcpBody = await siblingMcpContext.text();
expect(siblingMcpBody).toContain("Forbidden");
expect(siblingMcpBody).toContain("session cannot access this repository");
expect(siblingMcpBody).not.toContain("SECRET roadmap PR title");
expect(siblingMcpBody).not.toContain("SECRET-LAUNCH-CODE");
expect(siblingMcpBody).not.toContain("confidential-roadmap");
});

it("returns 404 for unknown repos and serves cached snapshot with freshness for known repos", async () => {
Expand Down
23 changes: 22 additions & 1 deletion test/unit/mcp-upstream.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { authenticatePrivateToken, createSessionForGitHubUser } from "../../src/auth/security";
import { persistSignalSnapshot, persistUpstreamRulesetSnapshot, upsertRepositoryFromGitHub, upsertUpstreamDriftReport } from "../../src/db/repositories";
import { persistSignalSnapshot, persistUpstreamRulesetSnapshot, upsertBounty, upsertRepositoryFromGitHub, upsertUpstreamDriftReport } from "../../src/db/repositories";
import { GittensoryMcp } from "../../src/mcp/server";
import type { UpstreamDriftReportRecord, UpstreamRulesetSnapshotRecord } from "../../src/types";
import { createTestEnv } from "../helpers/d1";
Expand Down Expand Up @@ -43,6 +43,27 @@ describe("MCP contributor access", () => {
expect(payload.data).toEqual({ status: "forbidden", repoFullName: "victim/private-repo" });
expect(JSON.stringify(payload)).not.toContain("SECRET private issue");
});

it("does not reveal inaccessible bounty ids through advisory errors", async () => {
const env = createTestEnv();
await upsertRepositoryFromGitHub(env, { name: "private-repo", full_name: "victim/private-repo", private: true, owner: { login: "victim" }, default_branch: "main" });
await upsertBounty(env, {
id: "secret-bounty",
repoFullName: "victim/private-repo",
issueNumber: 7,
status: "Open",
amountText: "5.0000",
sourceUrl: "contract://issues/7",
payload: { title: "SECRET bounty" },
});
const { token } = await createSessionForGitHubUser(env, { login: "attacker", id: 7 });
const identity = await authenticatePrivateToken(env, token);
if (!identity || identity.kind !== "session") throw new Error("expected session identity");
const mcp = new GittensoryMcp(env, identity) as unknown as { getBountyAdvisory(id: string): Promise<unknown> };

await expect(mcp.getBountyAdvisory("missing-bounty")).rejects.toThrow("Bounty not found.");
await expect(mcp.getBountyAdvisory("secret-bounty")).rejects.toThrow("Bounty not found.");
});
});

describe("MCP upstream drift tool", () => {
Expand Down