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
184 changes: 184 additions & 0 deletions packages/@emulators/github/src/__tests__/issue-dependencies.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
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";
import { getGitHubStore } from "../store.js";
import { MAX_ISSUE_DEPENDENCIES } from "../routes/issue-dependencies.js";

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

type Issue = {
id: number;
number: number;
issue_dependencies_summary: {
blocked_by: number;
blocking: number;
total_blocked_by: number;
total_blocking: number;
};
};

function createTestApp() {
const store = new Store();
const tokenMap: TokenMap = new Map([
["octocat-token", { login: "octocat", id: 1, scopes: ["repo", "user"] }],
["hubot-token", { login: "hubot", id: 2, scopes: ["repo", "user"] }],
]);
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: "octocat" }, { login: "hubot" }],
repos: [
{ owner: "octocat", name: "alpha" },
{ owner: "octocat", name: "beta" },
{ owner: "hubot", name: "secret", private: true },
],
});
return { app, store };
}

describe("GitHub issue dependencies", () => {
let app: Hono;
let store: Store;

const call = (path: string, init: { method?: string; token?: string | null; body?: unknown } = {}) => {
const headers: Record<string, string> = {};
const token = init.token === undefined ? "octocat-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 createIssue = async (repo: string, token = "octocat-token"): Promise<Issue> => {
const res = await call(`/repos/${repo}/issues`, { method: "POST", token, body: { title: `Issue in ${repo}` } });
expect(res.status).toBe(201);
return (await res.json()) as Issue;
};

const addBlocker = (repo: string, number: number, issueId: unknown, token?: string | null) =>
call(`/repos/${repo}/issues/${number}/dependencies/blocked_by`, {
method: "POST",
token,
body: { issue_id: issueId },
});

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

it("adds, lists in both directions and removes an edge across repositories", async () => {
const blocked = await createIssue("octocat/alpha");
const blocker = await createIssue("octocat/beta");

const added = await addBlocker("octocat/alpha", blocked.number, blocker.id);
expect(added.status).toBe(201);
expect(((await added.json()) as Issue).id).toBe(blocker.id);

const blockedBy = (await (
await call(`/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by`)
).json()) as Issue[];
expect(blockedBy.map((issue) => issue.id)).toEqual([blocker.id]);
const blocking = (await (
await call(`/repos/octocat/beta/issues/${blocker.number}/dependencies/blocking`)
).json()) as Issue[];
expect(blocking.map((issue) => issue.id)).toEqual([blocked.id]);

const summary = ((await (await call(`/repos/octocat/alpha/issues/${blocked.number}`)).json()) as Issue)
.issue_dependencies_summary;
expect(summary).toEqual({ blocked_by: 1, blocking: 0, total_blocked_by: 1, total_blocking: 0 });

const removed = await call(`/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by/${blocker.id}`, {
method: "DELETE",
});
expect(removed.status).toBe(200);
expect(((await removed.json()) as Issue).id).toBe(blocker.id);
expect(await (await call(`/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by`)).json()).toEqual(
[],
);
const again = await call(`/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by/${blocker.id}`, {
method: "DELETE",
});
expect(again.status).toBe(404);
});

it("counts only open issues in blocked_by and blocking, and all in the totals", async () => {
const blocked = await createIssue("octocat/alpha");
const open = await createIssue("octocat/alpha");
const closed = await createIssue("octocat/alpha");
await addBlocker("octocat/alpha", blocked.number, open.id);
await addBlocker("octocat/alpha", blocked.number, closed.id);
await call(`/repos/octocat/alpha/issues/${closed.number}`, { method: "PATCH", body: { state: "closed" } });

const summary = ((await (await call(`/repos/octocat/alpha/issues/${blocked.number}`)).json()) as Issue)
.issue_dependencies_summary;
expect(summary).toEqual({ blocked_by: 1, blocking: 0, total_blocked_by: 2, total_blocking: 0 });
});

it("rejects a self-reference, a duplicate edge and a malformed id with 422", async () => {
const blocked = await createIssue("octocat/alpha");
const blocker = await createIssue("octocat/alpha");
expect((await addBlocker("octocat/alpha", blocked.number, blocked.id)).status).toBe(422);
expect((await addBlocker("octocat/alpha", blocked.number, blocker.id)).status).toBe(201);
expect((await addBlocker("octocat/alpha", blocked.number, blocker.id)).status).toBe(422);
expect((await addBlocker("octocat/alpha", blocked.number, "not-a-number")).status).toBe(422);
});

it("returns 404 for an unknown issue, an unknown issue id and an issue the caller cannot see", async () => {
const blocked = await createIssue("octocat/alpha");
const hidden = await createIssue("hubot/secret", "hubot-token");
expect((await call("/repos/octocat/alpha/issues/999/dependencies/blocked_by")).status).toBe(404);
expect((await addBlocker("octocat/alpha", blocked.number, 999_999)).status).toBe(404);
expect((await addBlocker("octocat/alpha", blocked.number, hidden.id)).status).toBe(404);
expect((await call(`/repos/hubot/secret/issues/${hidden.number}/dependencies/blocking`)).status).toBe(404);
});

it("omits related issues the caller cannot see from lists", 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 asOctocat = await call(`/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by`);
expect(await asOctocat.json()).toEqual([]);
const asHubot = await call(`/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by`, {
token: "hubot-token",
});
expect(((await asHubot.json()) as Issue[]).map((issue) => issue.id)).toEqual([hidden.id]);
});

it("requires authentication to add an edge", async () => {
const blocked = await createIssue("octocat/alpha");
const blocker = await createIssue("octocat/alpha");
expect((await addBlocker("octocat/alpha", blocked.number, blocker.id, null)).status).toBe(401);
});

it("paginates and caps each issue at the GitHub relationship limit", async () => {
const blocked = await createIssue("octocat/alpha");
const blockers: Issue[] = [];
for (let i = 0; i <= MAX_ISSUE_DEPENDENCIES; i++) blockers.push(await createIssue("octocat/beta"));
for (const blocker of blockers.slice(0, MAX_ISSUE_DEPENDENCIES)) {
expect((await addBlocker("octocat/alpha", blocked.number, blocker.id)).status).toBe(201);
}
expect((await addBlocker("octocat/alpha", blocked.number, blockers[MAX_ISSUE_DEPENDENCIES]!.id)).status).toBe(422);

const page = await call(`/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by?per_page=20&page=3`);
expect(((await page.json()) as Issue[]).length).toBe(10);
expect(page.headers.get("Link")).toContain('rel="first"');
const all = await call(`/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by?per_page=100`);
expect(((await all.json()) as Issue[]).length).toBe(MAX_ISSUE_DEPENDENCIES);
});
});
6 changes: 6 additions & 0 deletions packages/@emulators/github/src/entities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,12 @@ export interface GitHubIssueEvent extends Entity {
rename: { from: string; to: string } | null;
}

/** 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;
blocking_issue_id: number;
}

export interface GitHubBranch extends Entity {
repo_id: number;
name: string;
Expand Down
19 changes: 19 additions & 0 deletions packages/@emulators/github/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,25 @@ export function formatIssue(issue: GitHubIssue, store: GitHubStore, baseUrl: str
timeline_url: `${repoUrl}/issues/${issue.number}/timeline`,
performed_via_github_app: null,
author_association: computeAuthorAssociation(store, issue.user_id, issue.repo_id),
issue_dependencies_summary: issueDependenciesSummary(issue, store),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔴 issue_dependencies_summary leaks private-repo issue counts.

🤖 Fix with your agent
Fix this code review finding (aictrl-dev/github-emulator PR #12, packages/@emulators/github/src/helpers.ts:387-405):

Problem: issue_dependencies_summary leaks private-repo issue counts
Detail: formatIssue is the shared serializer for every issue-returning endpoint (get/list/search/webhooks) but takes no authUser, and issueDependenciesSummary counts ALL dependency edges with no caller-visibility filtering — while the new list endpoints in the same PR deliberately filter edges through canRead(). Any caller who can read a public issue gets issue_dependencies_summary exposing the count, open/closed split and existence of blocker issues living in private repos they cannot see. This directly contradicts the PR's own test ("omits related issues the caller cannot see from lists") and the emulator's stated rule that private repos are invisible (404). Repro: given an octocat/alpha issue A and a private hubot/secret issue S with edge {blocked: A, blocking: S}, octocat's GET .../dependencies/blocked_by returns [] but GET /repos/octocat/alpha/issues/{A.number} returns issue_dependencies_summary {blocked_by:1, total_blocked_by:1} — octocat learns A is blocked by exactly one open issue inside a private repo. All three review agents (Security, Consistency, Bug Hunter) independently flagged this.
Suggested fix: Thread the requesting user into issue serialization (e.g. an optional authUser/visibility-predicate param on formatIssue, mirroring how formatRepo handles viewer permissions) and count only edges whose far-end issue lives in a repo the caller can read — the same canRead() check the list endpoints use. Alternatively compute the summary only inside the dependency routes where the caller is known, leaving the shared formatIssue payload unchanged. At minimum the summary must be consistent with the filtered GET .../dependencies/blocked_by response.

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

formatIssue is the shared serializer for every issue-returning endpoint (get/list/search/webhooks) but takes no authUser, and issueDependenciesSummary counts ALL dependency edges with no caller-visibility filtering — while the new list endpoints in the same PR deliberately filter edges through canRead(). Any caller who can read a public issue gets issue_dependencies_summary exposing the count, open/closed split and existence of blocker issues living in private repos they cannot see. This directly contradicts the PR's own test ("omits related issues the caller cannot see from lists") and the emulator's stated rule that private repos are invisible (404). Repro: given an octocat/alpha issue A and a private hubot/secret issue S with edge {blocked: A, blocking: S}, octocat's GET .../dependencies/blocked_by returns [] but GET /repos/octocat/alpha/issues/{A.number} returns issue_dependencies_summary {blocked_by:1, total_blocked_by:1} — octocat learns A is blocked by exactly one open issue inside a private repo. All three review agents (Security, Consistency, Bug Hunter) independently flagged this.

    author_association: computeAuthorAssociation(store, issue.user_id, issue.repo_id),
    issue_dependencies_summary: issueDependenciesSummary(issue, store),
  };
}

/** Counts as GitHub reports them: `blocked_by` and `blocking` count open issues, the totals count all. */
function issueDependenciesSummary(issue: GitHubIssue, store: GitHubStore) {
  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);
  const blocked = store.issueDependencies
    .findBy("blocking_issue_id", issue.id)

};
}

/** Counts as GitHub reports them: `blocked_by` and `blocking` count open issues, the totals count all. */
function issueDependenciesSummary(issue: GitHubIssue, store: GitHubStore) {
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);
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);
return {
blocked_by: blockers.filter((other) => other.state === "open").length,
blocking: blocked.filter((other) => other.state === "open").length,
total_blocked_by: blockers.length,
total_blocking: blocked.length,
};
}

Expand Down
2 changes: 2 additions & 0 deletions packages/@emulators/github/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { generateNodeId } from "./helpers.js";
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 { pullsRoutes } from "./routes/pulls.js";
import { commentsRoutes } from "./routes/comments.js";
import { reviewsRoutes } from "./routes/reviews.js";
Expand Down Expand Up @@ -700,6 +701,7 @@ export const githubPlugin: ServicePlugin = {
usersRoutes(ctx);
reposRoutes(ctx);
issuesRoutes(ctx);
issueDependenciesRoutes(ctx);
pullsRoutes(ctx);
commentsRoutes(ctx);
reviewsRoutes(ctx);
Expand Down
102 changes: 102 additions & 0 deletions packages/@emulators/github/src/routes/issue-dependencies.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import type { Context, RouteContext } from "@emulators/core";
import { ApiError, parseJsonBody, parsePagination, setLinkHeader } from "@emulators/core";
import type { AuthUser } from "@emulators/core";
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";

/** GitHub limits each issue to 50 relationships of each kind. */
export const MAX_ISSUE_DEPENDENCIES = 50;

type Direction = "blocked_by" | "blocking";

function canRead(gh: GitHubStore, authUser: AuthUser | undefined, repo: GitHubRepo): boolean {
try {
assertRepoPermission(gh, authUser, repo, "issues");
return repo.has_issues;
} catch {
return false;
}
}

/** The issue in the path, visible to the caller, or 404 as on GitHub. */
function pathIssue(gh: GitHubStore, c: Context, required: "read" | "write"): { repo: GitHubRepo; issue: GitHubIssue } {
const repo = lookupRepo(gh, c.req.param("owner")!, c.req.param("repo")!);
if (!repo) throw notFoundResponse();
if (required === "write") assertIssueWrite(gh, c.get("authUser"), repo);
else assertRepoPermission(gh, c.get("authUser"), repo, "issues");
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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 pathIssue re-implements issues.ts findIssueForRepo.

Suggested change
const issue = gh.issues.findBy("repo_id", repo.id).find((i) => i.number === issueNumber && !i.is_pull_request);
Export findIssueForRepo (or a shared lookupIssue) from src/helpers.ts next to lookupRepo and use it both in routes/issues.ts and in pathIssue here.
🤖 Fix with your agent
Fix this code review finding (aictrl-dev/github-emulator PR #12, packages/@emulators/github/src/routes/issue-dependencies.ts:33):

Problem: pathIssue re-implements issues.ts findIssueForRepo
Detail: pathIssue inlines `gh.issues.findBy("repo_id", repo.id).find((i) => i.number === issueNumber && !i.is_pull_request)` — the same lookup rule as the findIssueForRepo helper used by routes/issues.ts. Two route modules now maintain identical issue-lookup logic; if the rule changes (e.g. pull-request filtering or number parsing), they will drift. helpers.ts already hosts the analogous shared lookupRepo.
Suggested fix: Export findIssueForRepo (or a shared lookupIssue) from src/helpers.ts next to lookupRepo and use it both in routes/issues.ts and in pathIssue here.

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

pathIssue inlines gh.issues.findBy("repo_id", repo.id).find((i) => i.number === issueNumber && !i.is_pull_request) — the same lookup rule as the findIssueForRepo helper used by routes/issues.ts. Two route modules now maintain identical issue-lookup logic; if the rule changes (e.g. pull-request filtering or number parsing), they will drift. helpers.ts already hosts the analogous shared lookupRepo.

  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);
  if (!issue) throw notFoundResponse();
  return { repo, issue };
}

if (!issue) throw notFoundResponse();
return { repo, issue };
}

/** The other end of an edge, addressed by its issue id; it may live in another repository. */
function issueById(gh: GitHubStore, authUser: AuthUser | undefined, raw: unknown): GitHubIssue {
const id = typeof raw === "string" && /^\d+$/.test(raw) ? Number(raw) : raw;
if (typeof id !== "number" || !Number.isInteger(id)) throw new ApiError(422, "Validation failed");
const issue = gh.issues.get(id);
const repo = issue ? gh.repos.get(issue.repo_id) : undefined;
if (!issue || issue.is_pull_request || !repo || !canRead(gh, authUser, repo)) throw notFoundResponse();
return issue;
}

function related(gh: GitHubStore, issue: GitHubIssue, direction: Direction): GitHubIssue[] {
const edges =
direction === "blocked_by"
? gh.issueDependencies.findBy("blocked_issue_id", issue.id).map((edge) => edge.blocking_issue_id)
: gh.issueDependencies.findBy("blocking_issue_id", issue.id).map((edge) => edge.blocked_issue_id);
return edges.map((id) => gh.issues.get(id)).filter((other): other is GitHubIssue => !!other);
}

export function issueDependenciesRoutes({ app, store, baseUrl }: RouteContext): void {
const gh = getGitHubStore(store);

const list = (direction: Direction) => (c: Context) => {
const { issue } = pathIssue(gh, c, "read");
const authUser = c.get("authUser");
const visible = related(gh, issue, direction).filter((other) => {
const repo = gh.repos.get(other.repo_id);
return !!repo && canRead(gh, authUser, repo);
});
const { page, per_page } = parsePagination(c);
setLinkHeader(c, visible.length, page, per_page);
const start = (page - 1) * per_page;
return c.json(visible.slice(start, start + per_page).map((other) => formatIssue(other, gh, baseUrl)));
};

app.get("/repos/:owner/:repo/issues/:issue_number/dependencies/blocked_by", list("blocked_by"));
app.get("/repos/:owner/:repo/issues/:issue_number/dependencies/blocking", list("blocking"));

app.post("/repos/:owner/:repo/issues/:issue_number/dependencies/blocked_by", async (c) => {
const { issue } = pathIssue(gh, c, "write");
const body = (await parseJsonBody(c)) as { issue_id?: unknown };
const blocking = issueById(gh, c.get("authUser"), body.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.

🟡 Read-only far end lets writers publish private issue links.

Suggested change
const blocking = issueById(gh, c.get("authUser"), body.issue_id);
Either fix the disclosure at the source by filtering issue_dependencies_summary per caller (see the helpers.ts finding), or additionally require the caller to hold write/push permission on the far-end repo when the edge crosses repositories, so private issues cannot be linked into publicly readable issues.
🤖 Fix with your agent
Fix this code review finding (aictrl-dev/github-emulator PR #12, packages/@emulators/github/src/routes/issue-dependencies.ts:78-88):

Problem: Read-only far end lets writers publish private issue links
Detail: POST requires write only on the path repo and merely READ on the blocking issue's repo, so anyone with write on a public repo can attach an issue from a private repo they can only read as a blocker of a publicly readable issue. Combined with the unfiltered issue_dependencies_summary (flagged separately), this makes the writer the injection vector that publishes the existence and count of private-repo issues to every reader of the public repo. Even once the summary is caller-filtered, the linkage itself deserves a deliberate decision: either filter the summary per caller (preferred) or require stronger permission on the far-end repo for cross-repo edges.
Suggested fix: Either fix the disclosure at the source by filtering issue_dependencies_summary per caller (see the helpers.ts finding), or additionally require the caller to hold write/push permission on the far-end repo when the edge crosses repositories, so private issues cannot be linked into publicly readable issues.

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

POST requires write only on the path repo and merely READ on the blocking issue's repo, so anyone with write on a public repo can attach an issue from a private repo they can only read as a blocker of a publicly readable issue. Combined with the unfiltered issue_dependencies_summary (flagged separately), this makes the writer the injection vector that publishes the existence and count of private-repo issues to every reader of the public repo. Even once the summary is caller-filtered, the linkage itself deserves a deliberate decision: either filter the summary per caller (preferred) or require stronger permission on the far-end repo for cross-repo edges.

  app.post("/repos/:owner/:repo/issues/:issue_number/dependencies/blocked_by", async (c) => {
    const { issue } = pathIssue(gh, c, "write");
    const body = (await parseJsonBody(c)) as { issue_id?: unknown };
    const blocking = issueById(gh, c.get("authUser"), body.issue_id);
    if (blocking.id === issue.id) throw new ApiError(422, "Validation failed");

if (blocking.id === issue.id) throw new ApiError(422, "Validation failed");
const existing = gh.issueDependencies.findBy("blocked_issue_id", issue.id);
if (existing.some((edge) => edge.blocking_issue_id === blocking.id)) throw new ApiError(422, "Validation failed");
if (
existing.length >= MAX_ISSUE_DEPENDENCIES ||
gh.issueDependencies.findBy("blocking_issue_id", blocking.id).length >= MAX_ISSUE_DEPENDENCIES
) {
throw new ApiError(422, "Validation failed");
}
gh.issueDependencies.insert({ blocked_issue_id: issue.id, blocking_issue_id: blocking.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.

🟡 Dependency mutations emit no webhooks or timeline events.

Suggested change
gh.issueDependencies.insert({ blocked_issue_id: issue.id, blocking_issue_id: blocking.id });
Destructure `webhooks` from RouteContext and, on POST/DELETE, insert an issue event via the shared insertIssueEvent helper and dispatch the corresponding `issues` webhook, matching the pattern in routes/issues.ts (or document why dependency changes intentionally emit none).
🤖 Fix with your agent
Fix this code review finding (aictrl-dev/github-emulator PR #12, packages/@emulators/github/src/routes/issue-dependencies.ts:88-89):

Problem: Dependency mutations emit no webhooks or timeline events
Detail: Every other mutating issue route in routes/issues.ts records an issue event (insertIssueEvent) and dispatches an `issues` webhook (opened/closed/assigned/...), but the new POST/DELETE dependency handlers destructures only { app, store, baseUrl } and do neither. Webhook subscribers and the issue timeline silently miss dependency changes, breaking the emulator's change-notification convention now that issue_dependencies_summary is part of every issue payload.
Suggested fix: Destructure `webhooks` from RouteContext and, on POST/DELETE, insert an issue event via the shared insertIssueEvent helper and dispatch the corresponding `issues` webhook, matching the pattern in routes/issues.ts (or document why dependency changes intentionally emit none).

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

Every other mutating issue route in routes/issues.ts records an issue event (insertIssueEvent) and dispatches an issues webhook (opened/closed/assigned/...), but the new POST/DELETE dependency handlers destructures only { app, store, baseUrl } and do neither. Webhook subscribers and the issue timeline silently miss dependency changes, breaking the emulator's change-notification convention now that issue_dependencies_summary is part of every issue payload.

    if (
      existing.length >= MAX_ISSUE_DEPENDENCIES ||
      gh.issueDependencies.findBy("blocking_issue_id", blocking.id).length >= MAX_ISSUE_DEPENDENCIES
    ) {
      throw new ApiError(422, "Validation failed");
    }
    gh.issueDependencies.insert({ blocked_issue_id: issue.id, blocking_issue_id: blocking.id });
    return c.json(formatIssue(blocking, gh, baseUrl), 201);
  });

return c.json(formatIssue(blocking, gh, baseUrl), 201);
});

app.delete("/repos/:owner/:repo/issues/:issue_number/dependencies/blocked_by/:issue_id", (c) => {
const { issue } = pathIssue(gh, c, "write");
const blocking = issueById(gh, c.get("authUser"), c.req.param("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 404s when far-end issue becomes unreadable.

Suggested change
const blocking = issueById(gh, c.get("authUser"), c.req.param("issue_id"));
For DELETE, resolve the edge without the canRead gate: look the far issue up with a visibility-free gh.issues.get(id) (still 422/404 on a malformed or unknown id), authorize on write access to the PATH repo's issue, and 404 only if the edge itself doesn't exist.
🤖 Fix with your agent
Fix this code review finding (aictrl-dev/github-emulator PR #12, packages/@emulators/github/src/routes/issue-dependencies.ts:94-98):

Problem: DELETE 404s when far-end issue becomes unreadable
Detail: DELETE resolves the far end via issueById, which returns 404 unless the caller can currently READ the blocking issue's repo. If that repo later becomes private or the caller's read access is revoked, a user with write access on the path repo can no longer remove an existing edge — the dependency becomes undeletable through the API even though removal should only require write on the blocked issue. POST only needed read at creation time, so the two endpoints are inconsistent about the far end. Repro: Given octocat can read hubot/secret and write octocat/alpha, and creates edge alpha#1 blocked_by secret#2 via POST; When hubot revokes octocat's read on hubot/secret; Then DELETE /repos/octocat/alpha/issues/1/dependencies/blocked_by/2 returns 404 instead of removing the edge, and the stale dependency can never be deleted via the API.
Suggested fix: For DELETE, resolve the edge without the canRead gate: look the far issue up with a visibility-free gh.issues.get(id) (still 422/404 on a malformed or unknown id), authorize on write access to the PATH repo's issue, and 404 only if the edge itself doesn't exist.

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

DELETE resolves the far end via issueById, which returns 404 unless the caller can currently READ the blocking issue's repo. If that repo later becomes private or the caller's read access is revoked, a user with write access on the path repo can no longer remove an existing edge — the dependency becomes undeletable through the API even though removal should only require write on the blocked issue. POST only needed read at creation time, so the two endpoints are inconsistent about the far end. Repro: Given octocat can read hubot/secret and write octocat/alpha, and creates edge alpha#1 blocked_by secret#2 via POST; When hubot revokes octocat's read on hubot/secret; Then DELETE /repos/octocat/alpha/issues/1/dependencies/blocked_by/2 returns 404 instead of removing the edge, and the stale dependency can never be deleted via the API.

  app.delete("/repos/:owner/:repo/issues/:issue_number/dependencies/blocked_by/:issue_id", (c) => {
    const { issue } = pathIssue(gh, c, "write");
    const blocking = issueById(gh, c.get("authUser"), c.req.param("issue_id"));
    const edge = gh.issueDependencies
      .findBy("blocked_issue_id", issue.id)
      .find((candidate) => candidate.blocking_issue_id === blocking.id);
    if (!edge) throw notFoundResponse();

const edge = gh.issueDependencies
.findBy("blocked_issue_id", issue.id)
.find((candidate) => candidate.blocking_issue_id === blocking.id);
if (!edge) 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 returns 200+body; GitHub contract is 204.

Suggested change
return c.json(formatIssue(blocking, gh, baseUrl));
Return c.body(null, 204) from the DELETE handler (and update the test's expectations accordingly), matching GitHub's documented remove-dependency response and the sibling lock/unlock DELETE routes.
🤖 Fix with your agent
Fix this code review finding (aictrl-dev/github-emulator PR #12, packages/@emulators/github/src/routes/issue-dependencies.ts:100):

Problem: DELETE returns 200+body; GitHub contract is 204
Detail: The DELETE dependency endpoint returns 200 with the full blocking-issue JSON body. GitHub's remove-issue-dependency contract responds 204 No Content on success, and the emulator's own destructive issue routes (e.g. DELETE /repos/:o/:r/issues/:n/lock) already follow the 204 convention. Clients written against GitHub's contract will parse this response differently than expected.
Suggested fix: Return c.body(null, 204) from the DELETE handler (and update the test's expectations accordingly), matching GitHub's documented remove-dependency response and the sibling lock/unlock DELETE routes.

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 DELETE dependency endpoint returns 200 with the full blocking-issue JSON body. GitHub's remove-issue-dependency contract responds 204 No Content on success, and the emulator's own destructive issue routes (e.g. DELETE /repos/:o/:r/issues/:n/lock) already follow the 204 convention. Clients written against GitHub's contract will parse this response differently than expected.

    if (!edge) throw notFoundResponse();
    gh.issueDependencies.delete(edge.id);
    return c.json(formatIssue(blocking, gh, baseUrl));
  });
}

});
}
6 changes: 6 additions & 0 deletions packages/@emulators/github/src/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import type {
GitHubComment,
GitHubReview,
GitHubIssueEvent,
GitHubIssueDependency,
GitHubBranch,
GitHubBranchProtection,
GitHubRef,
Expand Down Expand Up @@ -53,6 +54,7 @@ export interface GitHubStore {
comments: Collection<GitHubComment>;
reviews: Collection<GitHubReview>;
issueEvents: Collection<GitHubIssueEvent>;
issueDependencies: Collection<GitHubIssueDependency>;
branches: Collection<GitHubBranch>;
branchProtections: Collection<GitHubBranchProtection>;
refs: Collection<GitHubRef>;
Expand Down Expand Up @@ -93,6 +95,10 @@ export function getGitHubStore(store: Store): GitHubStore {
comments: store.collection<GitHubComment>("github.comments", ["repo_id"]),
reviews: store.collection<GitHubReview>("github.reviews", ["repo_id", "pull_number"]),
issueEvents: store.collection<GitHubIssueEvent>("github.issue_events", ["repo_id", "issue_number"]),
issueDependencies: store.collection<GitHubIssueDependency>("github.issue_dependencies", [
"blocked_issue_id",
"blocking_issue_id",
]),
branches: store.collection<GitHubBranch>("github.branches", ["repo_id"]),
branchProtections: store.collection<GitHubBranchProtection>("github.branch_protections", ["repo_id"]),
refs: store.collection<GitHubRef>("github.refs", ["repo_id"]),
Expand Down
2 changes: 2 additions & 0 deletions packages/github-emulator/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ try {

Tokens are checked as GitHub checks them: a bearer token that the seed did not configure and the emulator did not issue (for example one issued before `reset()`) gets `401 Bad credentials`. Upstream emulate treats such a token as the default user; set `strict_scopes: false` in the seed to restore that. Private repositories answer `404` to callers who cannot see them.

Issue dependencies follow GitHub's REST API: `GET`/`POST /repos/{owner}/{repo}/issues/{number}/dependencies/blocked_by`, `DELETE .../dependencies/blocked_by/{issue_id}` and `GET .../dependencies/blocking`, across repositories, with GitHub's 50-relationship limit. Issue objects carry `issue_dependencies_summary`.

The default seed is synthetic. Configure `seed` and `tokens` for your tests. The instance provides `url`, `generatedSecrets`, `reset()`, and `close()`; tokens are resolved to seeded user IDs. Reset clears dynamic credentials and replays fixture state while preserving generated App keys.

After installing the tarball, `npx github-emulator --help` lists CLI options. It listens on loopback port 4200 by default and accepts `--port`, `--host`, `--base-url`, and `--config` for JSON configuration.
Expand Down
Loading