Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,20 @@ describe("GitHub issue dependencies", () => {
token: "hubot-token",
});
expect(((await asHubot.json()) as Issue[]).map((issue) => issue.id)).toEqual([hidden.id]);
// The shared issue payload never counts a blocker some readers of this issue cannot see.
const summary = ((await (await call(`/repos/octocat/alpha/issues/${blocked.number}`)).json()) as Issue)
.issue_dependencies_summary;
expect(summary).toEqual({ blocked_by: 0, blocking: 0, total_blocked_by: 0, total_blocking: 0 });
});

it("removes an edge whose far end the caller can no longer read, and rejects a malformed id", async () => {
const blocked = await createIssue("octocat/alpha");
const hidden = await createIssue("hubot/secret", "hubot-token");
getGitHubStore(store).issueDependencies.insert({ blocked_issue_id: blocked.id, blocking_issue_id: hidden.id });
const path = `/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by`;
expect((await call(`${path}/not-a-number`, { method: "DELETE" })).status).toBe(400);
expect((await call(`${path}/${hidden.id}`, { method: "DELETE" })).status).toBe(200);
expect(getGitHubStore(store).issueDependencies.findBy("blocked_issue_id", blocked.id)).toEqual([]);
});

it("requires authentication to add an edge", async () => {
Expand Down
128 changes: 128 additions & 0 deletions packages/@emulators/github/src/__tests__/issue-types.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import { beforeEach, describe, expect, it } from "vitest";
import {
Hono,
Store,
WebhookDispatcher,
authMiddleware,
createApiErrorHandler,
createErrorHandler,
type TokenMap,
} from "@emulators/core";
import { githubPlugin, seedFromConfig } from "../index.js";

const base = "http://localhost:4000";

type IssueType = { id: number; name: string; is_enabled: boolean; description: string | null };
type Issue = { number: number; type: IssueType | null };

function createTestApp() {
const store = new Store();
const tokenMap: TokenMap = new Map([
["admin-token", { login: "admin", id: 1, scopes: ["repo", "user", "read:org"] }],
["outsider-token", { login: "outsider", id: 2, scopes: ["repo", "user", "read:org"] }],
]);
const app = new Hono();
app.onError(createApiErrorHandler());
app.use("*", createErrorHandler());
app.use("*", authMiddleware(tokenMap));
githubPlugin.register(app as any, store, new WebhookDispatcher(), base, tokenMap);
githubPlugin.seed?.(store, base);
seedFromConfig(store, base, {
users: [{ login: "admin" }, { login: "outsider" }],
orgs: [
{ login: "acme", members: [{ login: "admin", role: "admin" }] },
{
login: "custom",
members: [{ login: "admin", role: "admin" }],
issue_types: [
{ name: "Epic", description: "A large body of work" },
{ name: "Chore", is_enabled: false },
],
},
{ login: "untyped", members: [{ login: "admin", role: "admin" }], issue_types: [] },
],
repos: [
{ owner: "acme", name: "widget" },
{ owner: "custom", name: "tool" },
{ owner: "admin", name: "personal" },
],
});
return app;
}

describe("GitHub issue types", () => {
let app: Hono;
const call = (path: string, init: { method?: string; token?: string | null; body?: unknown } = {}) => {
const headers: Record<string, string> = {};
const token = init.token === undefined ? "admin-token" : init.token;
if (token) headers.Authorization = `Bearer ${token}`;
if (init.body !== undefined) headers["Content-Type"] = "application/json";
return app.request(`${base}${path}`, {
method: init.method ?? "GET",
headers,
body: init.body === undefined ? undefined : JSON.stringify(init.body),
});
};
const names = async (res: Response) => ((await res.json()) as IssueType[]).map((type) => type.name);

beforeEach(() => {
app = createTestApp();
});

it("seeds GitHub's default types, custom types or none per organization", async () => {
expect(await names(await call("/orgs/acme/issue-types"))).toEqual(["Task", "Bug", "Feature"]);
const custom = (await (await call("/orgs/custom/issue-types")).json()) as IssueType[];
expect(custom.map((type) => [type.name, type.is_enabled, type.description])).toEqual([
["Epic", true, "A large body of work"],
["Chore", false, null],
]);
expect(await names(await call("/orgs/untyped/issue-types"))).toEqual([]);
});

it("lists a repository's types from its organization, and none for a personal repository", async () => {
expect(await names(await call("/repos/acme/widget/issue-types"))).toEqual(["Task", "Bug", "Feature"]);
expect(await names(await call("/repos/admin/personal/issue-types"))).toEqual([]);
});

it("hides an organization's types from non-members", async () => {
expect((await call("/orgs/acme/issue-types", { token: "outsider-token" })).status).toBe(404);
expect((await call("/orgs/acme/issue-types", { token: null })).status).toBe(404);
expect((await call("/orgs/missing/issue-types")).status).toBe(404);
});

it("sets, changes and clears an issue's type by name", async () => {
const created = await call("/repos/acme/widget/issues", { method: "POST", body: { title: "Typed", type: "bug" } });
expect(created.status).toBe(201);
const issue = (await created.json()) as Issue;
expect(issue.type?.name).toBe("Bug");

const changed = await call(`/repos/acme/widget/issues/${issue.number}`, {
method: "PATCH",
body: { type: "Feature" },
});
expect(((await changed.json()) as Issue).type?.name).toBe("Feature");
const untouched = await call(`/repos/acme/widget/issues/${issue.number}`, {
method: "PATCH",
body: { title: "Renamed" },
});
expect(((await untouched.json()) as Issue).type?.name).toBe("Feature");
const cleared = await call(`/repos/acme/widget/issues/${issue.number}`, { method: "PATCH", body: { type: null } });
expect(((await cleared.json()) as Issue).type).toBeNull();

const plain = await call("/repos/acme/widget/issues", { method: "POST", body: { title: "Untyped" } });
expect(((await plain.json()) as Issue).type).toBeNull();
});

it("rejects an unknown, disabled or personal-repository type with 422 and writes nothing", async () => {
const before = ((await (await call("/repos/custom/tool/issues?state=all")).json()) as unknown[]).length;
for (const type of ["Bug", "Chore", ""]) {
const res = await call("/repos/custom/tool/issues", { method: "POST", body: { title: "Rejected", type } });
expect(res.status, type).toBe(422);
}
expect(((await (await call("/repos/custom/tool/issues?state=all")).json()) as unknown[]).length).toBe(before);
expect(
(await call("/repos/admin/personal/issues", { method: "POST", body: { title: "Personal", type: "Task" } }))
.status,
).toBe(422);
});
});
12 changes: 12 additions & 0 deletions packages/@emulators/github/src/entities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,8 @@ export interface GitHubIssue extends Entity {
closed_at: string | null;
closed_by_id: number | null;
is_pull_request: boolean;
/** Organization issue type; absent on rows written before issue types existed. */
type_id?: number | null;
}

export interface GitHubPullRequest extends Entity {
Expand Down Expand Up @@ -237,6 +239,16 @@ export interface GitHubIssueEvent extends Entity {
rename: { from: string; to: string } | null;
}

/** An organization's issue type (Task, Bug, Feature by default). */
export interface GitHubIssueType extends Entity {
node_id: string;
org_id: number;
name: string;
description: string | null;
color: string | null;
is_enabled: boolean;
}

/** A directed "blocked by" edge: `blocked_issue_id` cannot proceed until `blocking_issue_id` is done. */
export interface GitHubIssueDependency extends Entity {
blocked_issue_id: number;
Expand Down
37 changes: 34 additions & 3 deletions packages/@emulators/github/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type {
GitHubOrg,
GitHubRepo,
GitHubIssue,
GitHubIssueType,
GitHubPullRequest,
GitHubLabel,
GitHubMilestone,
Expand Down Expand Up @@ -374,6 +375,7 @@ export function formatIssue(issue: GitHubIssue, store: GitHubStore, baseUrl: str
assignee: assignees[0] ?? null,
assignees,
milestone: milestone ? formatMilestone(milestone, repo, store, baseUrl) : null,
type: issueTypeJson(issue, store),
comments: issue.comments,
created_at: issue.created_at,
updated_at: issue.updated_at,
Expand All @@ -388,16 +390,45 @@ export function formatIssue(issue: GitHubIssue, store: GitHubStore, baseUrl: str
};
}

/** Counts as GitHub reports them: `blocked_by` and `blocking` count open issues, the totals count all. */
export function formatIssueType(type: GitHubIssueType) {
return {
id: type.id,
node_id: type.node_id,
name: type.name,
description: type.description,
color: type.color,
created_at: type.created_at,
updated_at: type.updated_at,
is_enabled: type.is_enabled,
};
}

function issueTypeJson(issue: GitHubIssue, store: GitHubStore) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟑 issueTypeJson duplicates formatIssueType serializer.

Suggested change
function issueTypeJson(issue: GitHubIssue, store: GitHubStore) {
Move formatIssueType into helpers.ts next to formatLabel/formatMilestone (keeping the one-directional import graph), have issueTypeJson call it, and re-export/import it in routes/issue-types.ts and issue-types.ts.
πŸ€– Fix with your agent
Fix this code review finding (aictrl-dev/github-emulator PR #14, packages/@emulators/github/src/helpers.ts:392-397):

Problem: issueTypeJson duplicates formatIssueType serializer
Detail: The private issueTypeJson helper in helpers.ts builds the exact same 8-field object ({id, node_id, name, description, color, created_at, updated_at, is_enabled}) as formatIssueType in issue-types.ts, and breaks the file's format* naming convention for serializers (formatLabel, formatMilestone, ...). Two copies of the issue-type API shape in one PR will drift when a field is added or renamed. helpers.ts cannot import issue-types.ts (issue-types.ts already imports generateNodeId from helpers.js), so the shared formatter belongs in helpers.ts.
Suggested fix: Move formatIssueType into helpers.ts next to formatLabel/formatMilestone (keeping the one-directional import graph), have issueTypeJson call it, and re-export/import it in routes/issue-types.ts and issue-types.ts.

Implement the fix on the PR head branch and add a regression test that fails before the fix and passes after.
Why this matters

The private issueTypeJson helper in helpers.ts builds the exact same 8-field object ({id, node_id, name, description, color, created_at, updated_at, is_enabled}) as formatIssueType in issue-types.ts, and breaks the file's format* naming convention for serializers (formatLabel, formatMilestone, ...). Two copies of the issue-type API shape in one PR will drift when a field is added or renamed. helpers.ts cannot import issue-types.ts (issue-types.ts already imports generateNodeId from helpers.js), so the shared formatter belongs in helpers.ts.

  };
}

function issueTypeJson(issue: GitHubIssue, store: GitHubStore) {
  const type = issue.type_id ? store.issueTypes.get(issue.type_id) : undefined;
  if (!type) return null;
  const { id, node_id, name, description, color, created_at, updated_at, is_enabled } = type;
  return { id, node_id, name, description, color, created_at, updated_at, is_enabled };
}

/** Counts as GitHub reports them: `blocked_by` and `blocking` count open issues, the totals count all. */

const type = issue.type_id ? store.issueTypes.get(issue.type_id) : undefined;
return type ? formatIssueType(type) : null;
}

export function findIssueForRepo(gh: GitHubStore, repoId: number, issueNumber: number): GitHubIssue | undefined {
return gh.issues.findBy("repo_id", repoId).find((i) => i.number === issueNumber && !i.is_pull_request);
}

/**
* Counts as GitHub reports them: `blocked_by` and `blocking` count open issues, the totals count all.
* The issue payload is shared by every reader, so only related issues every reader of this issue can
* see are counted: those in the same repository or in a public one. The dependency list endpoints,
* which know the caller, return the rest to callers who may see them.
*/
function issueDependenciesSummary(issue: GitHubIssue, store: GitHubStore) {
const visibleToAllReaders = (other: GitHubIssue | undefined): other is GitHubIssue =>
!!other && (other.repo_id === issue.repo_id || store.repos.get(other.repo_id)?.visibility === "public");
const blockers = store.issueDependencies
.findBy("blocked_issue_id", issue.id)
.map((edge) => store.issues.get(edge.blocking_issue_id))
.filter((other): other is GitHubIssue => !!other);
.filter(visibleToAllReaders);
const blocked = store.issueDependencies
.findBy("blocking_issue_id", issue.id)
.map((edge) => store.issues.get(edge.blocked_issue_id))
.filter((other): other is GitHubIssue => !!other);
.filter(visibleToAllReaders);
return {
blocked_by: blockers.filter((other) => other.state === "open").length,
blocking: blocked.filter((other) => other.state === "open").length,
Expand Down
10 changes: 8 additions & 2 deletions packages/@emulators/github/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createHmac, generateKeyPair } from "crypto";
import { createHmac, generateKeyPair, randomUUID } from "crypto";
import { constantTimeSecretEqual } from "@emulators/core";
import type { Context, Hono } from "@emulators/core";
import type {
Expand All @@ -19,6 +19,8 @@ import { usersRoutes } from "./routes/users.js";
import { reposRoutes } from "./routes/repos.js";
import { issuesRoutes } from "./routes/issues.js";
import { issueDependenciesRoutes } from "./routes/issue-dependencies.js";
import { issueTypesRoutes } from "./routes/issue-types.js";
import { seedIssueTypes, type IssueTypeSeed } from "./issue-types.js";
import { pullsRoutes } from "./routes/pulls.js";
import { commentsRoutes } from "./routes/comments.js";
import { reviewsRoutes } from "./routes/reviews.js";
Expand Down Expand Up @@ -67,6 +69,8 @@ export interface GitHubSeedConfig {
login: string;
role?: "member" | "admin";
}>;
/** Defaults to GitHub's Task, Bug and Feature; an empty list seeds none. */
issue_types?: IssueTypeSeed[];
}>;
tokens?: Record<string, { login: string; scopes?: string[] }>;
repos?: Array<{
Expand Down Expand Up @@ -359,6 +363,7 @@ export function seedFromConfig(store: Store, baseUrl: string, config: GitHubSeed
billing_email: null,
});
gh.orgs.update(org.id, { node_id: generateNodeId("Org", org.id) });
seedIssueTypes(gh, gh.orgs.get(org.id)!, o.issue_types);
}
}

Expand Down Expand Up @@ -631,7 +636,7 @@ async function deliverToAppWebhookUrls(
const headers: Record<string, string> = {
"Content-Type": "application/json",
"X-GitHub-Event": event,
"X-GitHub-Delivery": crypto.randomUUID(),
"X-GitHub-Delivery": randomUUID(),
};
if (ghApp.webhook_secret) {
const hmac = createHmac("sha256", ghApp.webhook_secret).update(body).digest("hex");
Expand Down Expand Up @@ -702,6 +707,7 @@ export const githubPlugin: ServicePlugin = {
reposRoutes(ctx);
issuesRoutes(ctx);
issueDependenciesRoutes(ctx);
issueTypesRoutes(ctx);
pullsRoutes(ctx);
commentsRoutes(ctx);
reviewsRoutes(ctx);
Expand Down
58 changes: 58 additions & 0 deletions packages/@emulators/github/src/issue-types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { ApiError } from "@emulators/core";
import type { GitHubIssueType, GitHubOrg, GitHubRepo } from "./entities.js";
import type { GitHubStore } from "./store.js";
import { generateNodeId } from "./helpers.js";
export { formatIssueType } from "./helpers.js";

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

βšͺ formatIssueType re-export adds needless indirection.

πŸ€– Fix with your agent
Fix this code review finding (aictrl-dev/github-emulator PR #14, packages/@emulators/github/src/issue-types.ts:5):

Problem: formatIssueType re-export adds needless indirection
Detail: issue-types.ts re-exports formatIssueType from ./helpers.js purely so routes/issue-types.ts can import it via ../issue-types.js. All other serializers (formatIssue, formatRepo, formatLabel, ...) live in helpers.ts and route files import them directly from ../helpers.js β€” routes/issue-types.ts already imports lookupRepo from there on line 4, so this one symbol arrives through a different path. Single copy and no cycle (correct), just a needless indirection that splits the serializer convention across two modules.
Suggested fix: Drop the re-export in issue-types.ts and import formatIssueType from "../helpers.js" in routes/issue-types.ts alongside lookupRepo.

Implement the fix on the PR head branch and add a regression test that fails before the fix and passes after.
Why this matters

issue-types.ts re-exports formatIssueType from ./helpers.js purely so routes/issue-types.ts can import it via ../issue-types.js. All other serializers (formatIssue, formatRepo, formatLabel, ...) live in helpers.ts and route files import them directly from ../helpers.js β€” routes/issue-types.ts already imports lookupRepo from there on line 4, so this one symbol arrives through a different path. Single copy and no cycle (correct), just a needless indirection that splits the serializer convention across two modules.

import type { GitHubIssueType, GitHubOrg, GitHubRepo } from "./entities.js";
import type { GitHubStore } from "./store.js";
import { generateNodeId } from "./helpers.js";
export { formatIssueType } from "./helpers.js";


export interface IssueTypeSeed {
name: string;
description?: string | null;
color?: string | null;
is_enabled?: boolean;
}

/** The issue types GitHub creates for a new organization. */
export const DEFAULT_ISSUE_TYPES: IssueTypeSeed[] = [
{ name: "Task", description: "A specific piece of work", color: "yellow" },
{ name: "Bug", description: "An unexpected problem or behavior", color: "red" },
{ name: "Feature", description: "A request, idea, or new functionality", color: "blue" },
];

export function seedIssueTypes(gh: GitHubStore, org: GitHubOrg, types?: IssueTypeSeed[] | null): void {
for (const type of types ?? DEFAULT_ISSUE_TYPES) {
if (!type.name?.trim()) throw new Error(`Issue type for ${org.login} needs a name`);
if (orgIssueTypes(gh, org.id).some((existing) => existing.name.toLowerCase() === type.name.toLowerCase())) continue;
const row = gh.issueTypes.insert({
node_id: "",
org_id: org.id,
name: type.name.trim(),
description: type.description ?? null,
color: type.color ?? null,
is_enabled: type.is_enabled ?? true,
} as Omit<GitHubIssueType, "id" | "created_at" | "updated_at">);
gh.issueTypes.update(row.id, { node_id: generateNodeId("IssueType", row.id) });
}
}

export function orgIssueTypes(gh: GitHubStore, orgId: number): GitHubIssueType[] {
return gh.issueTypes.findBy("org_id", orgId);
}

/** Issue types belong to organizations; a personal repository has none. */
export function repoIssueTypes(gh: GitHubStore, repo: GitHubRepo): GitHubIssueType[] {
return repo.owner_type === "Organization" ? orgIssueTypes(gh, repo.owner_id) : [];
}

/**
* Resolves the `type` field of an issue write: `null` or an absent field clears it, and a name selects an
* enabled type of the repository's organization, matched without regard to case.
*/

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

βšͺ resolveIssueTypeId undefined branch is unreachable.

πŸ€– Fix with your agent
Fix this code review finding (aictrl-dev/github-emulator PR #14, packages/@emulators/github/src/issue-types.ts:61-62):

Problem: resolveIssueTypeId undefined branch is unreachable
Detail: The documented tri-state contract ("undefined leaves the type unchanged") never takes effect: the PATCH call site is guarded by `"type" in body` and JSON bodies cannot carry a literal undefined, and the POST call site immediately collapses undefined with `?? null`. Both callers therefore carry a redundant `?? null` and the undefined return path is dead.
Suggested fix: Simplify the contract to `number | null` (return null for absent input) and drop the `?? null` at both call sites in routes/issues.ts; or, if the tri-state is kept, remove the `?? null` on the PATCH path so undefined genuinely means "unchanged".

Implement the fix on the PR head branch and add a regression test that fails before the fix and passes after.
Why this matters

The documented tri-state contract ("undefined leaves the type unchanged") never takes effect: the PATCH call site is guarded by "type" in body and JSON bodies cannot carry a literal undefined, and the POST call site immediately collapses undefined with ?? null. Both callers therefore carry a redundant ?? null and the undefined return path is dead.

/**
 * Resolves the `type` field of an issue write. `undefined` leaves the type unchanged, `null` clears it,
 * and a name selects an enabled type of the repository's organization, matched without regard to case.
 */
export function resolveIssueTypeId(gh: GitHubStore, repo: GitHubRepo, raw: unknown): number | null | undefined {
  if (raw === undefined) return undefined;
  if (raw === null) return null;
  if (typeof raw !== "string" || !raw.trim()) throw new ApiError(422, "Validation failed");

export function resolveIssueTypeId(gh: GitHubStore, repo: GitHubRepo, raw: unknown): number | null {
if (raw === undefined || raw === null) return null;
if (typeof raw !== "string" || !raw.trim()) throw new ApiError(422, "Validation failed");
const type = repoIssueTypes(gh, repo).find(
(candidate) => candidate.is_enabled && candidate.name.toLowerCase() === raw.trim().toLowerCase(),
);
if (!type) throw new ApiError(422, "Validation failed");
return type.id;
}
14 changes: 9 additions & 5 deletions packages/@emulators/github/src/routes/issue-dependencies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { getGitHubStore } from "../store.js";
import type { GitHubStore } from "../store.js";
import type { GitHubIssue, GitHubRepo } from "../entities.js";
import { assertIssueWrite, assertRepoPermission, notFoundResponse } from "../route-helpers.js";
import { formatIssue, lookupRepo } from "../helpers.js";
import { findIssueForRepo, formatIssue, lookupRepo } from "../helpers.js";

/** GitHub limits each issue to 50 relationships of each kind. */
export const MAX_ISSUE_DEPENDENCIES = 50;
Expand All @@ -30,7 +30,7 @@ function pathIssue(gh: GitHubStore, c: Context, required: "read" | "write"): { r
if (!repo.has_issues) throw notFoundResponse();
const issueNumber = Number(c.req.param("issue_number"));
if (!Number.isInteger(issueNumber)) throw notFoundResponse();
const issue = gh.issues.findBy("repo_id", repo.id).find((i) => i.number === issueNumber && !i.is_pull_request);
const issue = findIssueForRepo(gh, repo.id, issueNumber);
if (!issue) throw notFoundResponse();
return { repo, issue };
}
Expand Down Expand Up @@ -90,12 +90,16 @@ export function issueDependenciesRoutes({ app, store, baseUrl }: RouteContext):
});

app.delete("/repos/:owner/:repo/issues/:issue_number/dependencies/blocked_by/:issue_id", (c) => {
// Removing an edge needs write on the blocked issue only: the far end may have become unreadable since.
const { issue } = pathIssue(gh, c, "write");
const blocking = issueById(gh, c.get("authUser"), c.req.param("issue_id"));
const raw = c.req.param("issue_id")!;
if (!/^\d+$/.test(raw)) throw new ApiError(400, "Problems parsing issue_id");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟑 DELETE 400 for bad issue_id vs POST's 422.

Suggested change
if (!/^\d+$/.test(raw)) throw new ApiError(400, "Problems parsing issue_id");
Throw new ApiError(422, "Validation failed") for the malformed id, or extract a shared parse helper used by both issueById and the DELETE handler so the two endpoints agree.
πŸ€– Fix with your agent
Fix this code review finding (aictrl-dev/github-emulator PR #14, packages/@emulators/github/src/routes/issue-dependencies.ts:96):

Problem: DELETE 400 for bad issue_id vs POST's 422
Detail: The rewritten DELETE rejects a malformed :issue_id with 400 "Problems parsing issue_id", while the sibling POST in the same file resolves the same kind of id through issueById() (line 41) and rejects it with 422 "Validation failed". Across this PR (resolveIssueTypeId, milestone parsing in routes/issues.ts) malformed values consistently map to 422 "Validation failed"; the "Problems parsing XXX" message appears nowhere else in the package. Identical malformed input now yields different status codes depending on which endpoint of the same resource receives it. If the 400 deliberately mirrors an observed GitHub response, that intent is invisible; otherwise the error contract of the two dependency endpoints has split.
Suggested fix: Throw new ApiError(422, "Validation failed") for the malformed id, or extract a shared parse helper used by both issueById and the DELETE handler so the two endpoints agree.

Implement the fix on the PR head branch and add a regression test that fails before the fix and passes after.
Why this matters

The rewritten DELETE rejects a malformed :issue_id with 400 "Problems parsing issue_id", while the sibling POST in the same file resolves the same kind of id through issueById() (line 41) and rejects it with 422 "Validation failed". Across this PR (resolveIssueTypeId, milestone parsing in routes/issues.ts) malformed values consistently map to 422 "Validation failed"; the "Problems parsing XXX" message appears nowhere else in the package. Identical malformed input now yields different status codes depending on which endpoint of the same resource receives it. If the 400 deliberately mirrors an observed GitHub response, that intent is invisible; otherwise the error contract of the two dependency endpoints has split.

    // Removing an edge needs write on the blocked issue only: the far end may have become unreadable since.
    const { issue } = pathIssue(gh, c, "write");
    const raw = c.req.param("issue_id")!;
    if (!/^\d+$/.test(raw)) throw new ApiError(400, "Problems parsing issue_id");
    const blockingId = Number(raw);

const blockingId = Number(raw);
const edge = gh.issueDependencies
.findBy("blocked_issue_id", issue.id)
.find((candidate) => candidate.blocking_issue_id === blocking.id);
if (!edge) throw notFoundResponse();
.find((candidate) => candidate.blocking_issue_id === blockingId);
const blocking = edge ? gh.issues.get(blockingId) : undefined;
if (!edge || !blocking) throw notFoundResponse();
gh.issueDependencies.delete(edge.id);
return c.json(formatIssue(blocking, gh, baseUrl));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 DELETE dependency returns unreadable far-end issue JSON.

Suggested change
return c.json(formatIssue(blocking, gh, baseUrl));
Keep the permissive delete, but never serialize the unreadable far end: return 204 No Content, or return formatIssue(issue, ...) (the blocked issue the caller just proved write access to), or only serialize `blocking` when canRead(gh, c.get("authUser"), gh.repos.get(blocking.repo_id)) is true.
πŸ€– Fix with your agent
Fix this code review finding (aictrl-dev/github-emulator PR #14, packages/@emulators/github/src/routes/issue-dependencies.ts:104):

Problem: DELETE dependency returns unreadable far-end issue JSON
Detail: The reworked DELETE handler drops the far-end read check that issueById used to enforce (the comment even says "the far end may have become unreadable since"), yet still returns `formatIssue(blocking, gh, baseUrl)` β€” the FULL payload (title, body, labels, author, new `type` field, dependency summary) of an issue the caller may have no read access to. Every sibling path is hardened: POST resolves the far end via issueById which 404s unreadable repos, the LIST handlers filter `related()` by canRead, and this very PR tightens issueDependenciesSummary to hide cross-repo private far ends from the shared issue payload. DELETE alone both removes the edge and discloses the private far end's complete contents. Repro: seed org O with repos A (issue #1, attacker V has issues:write on A) and private B (issue id 5); an edge A#1 blocked_by 5 exists; V sends DELETE /repos/O/A/issues/1/dependencies/blocked_by/5 β€” pre-PR this 404'd, now it returns 200 with B#5's private title/body/labels/type. The PR's own test (deleting an edge into hubot/secret) demonstrates the flow. The 200-vs-404 differential is also an existence oracle for private issue ids.
Suggested fix: Keep the permissive delete, but never serialize the unreadable far end: return 204 No Content, or return formatIssue(issue, ...) (the blocked issue the caller just proved write access to), or only serialize `blocking` when canRead(gh, c.get("authUser"), gh.repos.get(blocking.repo_id)) is true.

Implement the fix on the PR head branch and add a regression test that fails before the fix and passes after.
Why this matters

The reworked DELETE handler drops the far-end read check that issueById used to enforce (the comment even says "the far end may have become unreadable since"), yet still returns formatIssue(blocking, gh, baseUrl) β€” the FULL payload (title, body, labels, author, new type field, dependency summary) of an issue the caller may have no read access to. Every sibling path is hardened: POST resolves the far end via issueById which 404s unreadable repos, the LIST handlers filter related() by canRead, and this very PR tightens issueDependenciesSummary to hide cross-repo private far ends from the shared issue payload. DELETE alone both removes the edge and discloses the private far end's complete contents. Repro: seed org O with repos A (issue #1, attacker V has issues:write on A) and private B (issue id 5); an edge A#1 blocked_by 5 exists; V sends DELETE /repos/O/A/issues/1/dependencies/blocked_by/5 β€” pre-PR this 404'd, now it returns 200 with B#5's private title/body/labels/type. The PR's own test (deleting an edge into hubot/secret) demonstrates the flow. The 200-vs-404 differential is also an existence oracle for private issue ids.

    const edge = gh.issueDependencies
      .findBy("blocked_issue_id", issue.id)
      .find((candidate) => candidate.blocking_issue_id === blockingId);
    const blocking = edge ? gh.issues.get(blockingId) : undefined;
    if (!edge || !blocking) throw notFoundResponse();
    gh.issueDependencies.delete(edge.id);
    return c.json(formatIssue(blocking, gh, baseUrl));

});
Expand Down
Loading
Loading