Public: anyone can read this; the crew can change it.

/api/v1/search keeps to one repository for ?repo=owner/name and repo: in q, a… #17906

opened this in answer to

Merged 25h 21m ago, live in production

mason/forge:mason/17905-api-v1-search-keeps-to-one-repository-fo → main 0 commits fork 2 threads · 2 unresolved

  • Merged. mason/17905-api-v1-search-keeps-to-one-repository-fo was merged into main as 261648b.

Review

Sign in to review this change.
4 files changed +73 −7
docs/features/search-finds-guides.md +5
@@ -23,3 +23,8 @@ links to `/search?q=…&kind=pulls` and shows as current; the API takes the same
2323 --kind pulls --limit 5` passes it through. In the terminal's search (palette,
2424 `ctrl+k`) start the query with `pulls:` — `pulls: retry` — for pull requests
2525 only.
26
27 To keep a search to one repository, `GET /api/v1/search?q=glow&repo=alice/pebble`
28 or `q=glow repo:alice/pebble` does it, as the MCP search tool does. It reaches
29 past the cap on repositories an unscoped search reads. A malformed `repo` or two
30 different ones is `invalid_repo` (422); an unreadable one is `not_found` (404).
src/contract/openapi/routes/getApiV1Search.ts +1 −1
@@ -1,4 +1,4 @@
11 import { type Route, limitTo } from "../shared.ts";
22 import { SEARCH_LIMIT_MAX } from "../../../actions/search_limit.ts";
33
4 export const route: Route = { method: "get", path: "/api/v1/search", summary: "Search guides, issues, pulls, repositories and code; `kind` narrows it", auth: false, role: "anonymous", query: { q: "string", kind: "string", limit: limitTo(SEARCH_LIMIT_MAX) }, refusals: { invalid_kind: "kind is not all, repos, issues, pulls or code (422)", invalid_limit: "limit is not a whole number from 1 to 100 (422)" }, reply: { repos: "array", issues: "array", code: "array", docs: "array of { title, path, snippet }, at most 5, guides matching; only for kind all", truncated: "object", moreCode: "boolean", codeSkipped: "boolean", note: "string, only when q is blank: what to send" } };
4 export const route: Route = { method: "get", path: "/api/v1/search", summary: "Search guides, issues, pulls, repositories and code; `kind` narrows it", auth: false, role: "anonymous", query: { q: "string", kind: "string", repo: "string", limit: limitTo(SEARCH_LIMIT_MAX) }, refusals: { invalid_kind: "kind is not all, repos, issues, pulls or code (422)", invalid_repo: "repo is not owner/name, or q names a different one with repo: (422)", not_found: "the repository does not exist or is unreadable (404)", invalid_limit: "limit is not a whole number from 1 to 100 (422)" }, reply: { repos: "array", issues: "array", code: "array", docs: "array of { title, path, snippet }, at most 5, guides matching; only for kind all", truncated: "object", moreCode: "boolean", codeSkipped: "boolean", note: "string, only when q is blank: what to send" } };
src/http/api.ts +27 −6
@@ -159,7 +159,7 @@ import {
159159 getRepoById,
160160 isLanding,
161161 } from "../core/repos.ts";
162 import { CODE_BUDGET_MS, greppable, searchKind, searchNote } from "../core/search.ts";
162 import { CODE_BUDGET_MS, greppable, repoQualifier, searchKind, searchNote } from "../core/search.ts";
163163 import { strangerCodeSearch } from "./strangers.ts";
164164
165165 import { contributeMint } from "./api/contribute_token.ts";
@@ -1566,6 +1566,17 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
15661566
15671567 orgRoutes(router);
15681568
1569 /**
1570 * The repository a search's `?repo=`/`repo:` names: 422 if not owner/name; the 404 of a missing
1571 * one if unreadable.
1572 */
1573 function searchScope(ctx: Ctx, named: string): Repo | Response {
1574 const [owner, name, ...rest] = named.split("/");
1575 if (!owner || !name || rest.length > 0) return apiError("invalid_repo", 422, "repo is owner/name");
1576 const repo = getRepo(ctx.app.db, owner, name);
1577 return repo !== undefined && canRead(ctx.app.db, repo, ctx.auth.user) ? repo : notFound();
1578 }
outdated

This helper splits the route's own comment (// caller has connected… live=1 …) from the route it describes. Move it above that comment block.

1579
15691580 // ── search ───────────────────────────────────────────────────────────
15701581 //
15711582 // One query, four sources: repos here, repos cached from every origin the
@@ -1585,7 +1596,17 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
15851596 }
15861597 if (queryTooLong(q.get("q"))) return json({ error: "invalid", field: "q", message: QUERY_TOO_LONG }, 422);
15871598 const kind = searchKind(q.get("kind"));
1588 const query = q.get("q") ?? "";
1599 // `repo:owner/name` in the words is the `repo` scope, as on the MCP tool (#16463).
1600 const qualified = repoQualifier(q.get("q") ?? "");
1601 const query = qualified.q;
1602 if (qualified.repo !== undefined && q.has("repo") && q.get("repo")?.toLowerCase() !== qualified.repo.toLowerCase())
1603 return apiError("invalid_repo", 422, "q names one repository with repo: and repo another: give one");
1604 const named = qualified.repo ?? q.get("repo") ?? undefined;
1605 const only = named === undefined ? undefined : searchScope(ctx, named);
1606 if (only instanceof Response) return only;
1607 const mine = runRepos(ctx.app, ctx.auth);
1608 const within = mine === undefined || only === undefined ? mine : mine.filter((r) => r.id === only.id);
1609 if (only !== undefined && within !== undefined && within.length === 0) return notFound();
15891610 const greps =
15901611 ctx.auth.user === undefined &&
15911612 (kind === "code" || kind === "all") &&
@@ -1598,6 +1619,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
15981619 const input = {
15991620 q: query,
16001621 kind,
1622 ...(only !== undefined ? { repo: only } : {}),
16011623 ...(q.has("limit") ? { limit: Number(q.get("limit")) } : {}),
16021624 live: q.get("live") === "1" || q.get("live") === "true",
16031625 // The page's budget; `code=all` lifts it, as on the page.
@@ -1605,12 +1627,11 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
16051627 ? {}
16061628 : { codeBudgetMs: ctx.app.config.codeBudgetMs ?? CODE_BUDGET_MS }),
16071629 };
1608 const mine = runRepos(ctx.app, ctx.auth);
16091630 const timed = { ...input, phase: (name: SearchPhase, ms: number) => notePhase(ctx.request, name, ms) };
1610 const found = await (mine === undefined
1631 const found = await (within === undefined
16111632 ? search(ctx.app, ctx.auth.user, timed)
1612 : searchWithin(ctx.app, ctx.auth.user, mine, timed));
1613 const note = searchNote(q.get("q"), kind);
1633 : searchWithin(ctx.app, ctx.auth.user, within, timed));
1634 const note = searchNote(query, kind);
16141635 return timePhase(ctx.request, "render", () => json(note === undefined ? found : { ...found, note }));
16151636 } finally {
16161637 held?.release();
test/mcp-search.test.ts +40
@@ -10,8 +10,10 @@ import { join } from "node:path";
1010 import { createApp, type App } from "../src/app.ts";
1111 import { createRepo, setArchived } from "../src/actions/repos.ts";
1212 import { createIssue } from "../src/core/issues.ts";
13 import { mintRunToken } from "../src/core/run_token.ts";
1314 import { createToken } from "../src/core/tokens.ts";
1415 import { SEARCH_LIMIT } from "../src/actions/search.ts";
16 import { getRepo } from "../src/core/repos.ts";
1517 import { createUser, getUserByName } from "../src/core/users.ts";
1618 import { serve, type Servers } from "../src/http/server.ts";
1719
@@ -122,6 +124,44 @@ describe("MCP search", () => {
122124 expect((await tool(bobRo, { q: "glow repo:alice/secretpebble" })).error).toContain("no such app or repository");
123125 });
outdated

Add a case for a repo-limited token. When repo= names a repository outside what the token may read, within is empty and the route answers 404. Nothing here exercises that branch.

124126
127 test("/api/v1/search takes the same scope, as ?repo= or repo: in q; a second, malformed or unreadable one is refused", async () => {
128 const api = async (path: string, token?: string) => {
129 const res = await fetch(`${servers.url}/api/v1/search?${path}`, token === undefined ? {} : { headers: { authorization: `Bearer ${token}` } });
130 const text = await res.text();
131 return { status: res.status, body: (text === "" ? {} : JSON.parse(text)) as any };
132 };
133 const names = (r: { body: any }) => r.body.issues.map((i: any) => i.repo.name);
134 expect(names(await api("q=glow&kind=issues", aliceRo))).not.toContain("pebble");
135 for (const p of ["q=glow&kind=issues&repo=alice/pebble", "q=glow%20repo:alice/pebble&kind=issues", "q=REPO:alice/pebble%20glow&kind=issues&repo=alice/pebble"])
136 expect(names(await api(p, aliceRo))).toEqual(["pebble"]);
137 expect(names(await api("q=glow%20repo:alice/pebble&kind=issues"))).toEqual(["pebble"]);
138 expect((await api("q=glow%20repo:alice/pebble&repo=alice/noisy", aliceRo)).body.error).toBe("invalid_repo");
139 for (const repo of ["pebble", "alice/", "a/b/c", ""]) expect((await api(`q=glow&repo=${repo}`, aliceRo)).status).toBe(422);
140 expect((await api("q=glow&repo=alice/secretpebble", bobRo)).status).toBe(404);
141 expect((await api("q=glow&repo=alice/nothing-here", aliceRo)).status).toBe(404);
142 });
143
144 test("/api/v1/search: a run token reaches only its own repositories; repo= outside them is 404, inside them is found; the qualifier's case is no second repository", async () => {
145 const alice = getUserByName(app.db, "alice")!;
146 const pebble = getRepo(app.db, "alice", "pebble")!;
147 const secret = getRepo(app.db, "alice", "secretpebble")!;
148 const run = mintRunToken(app.db, alice.id, "run-search", { repoId: pebble.id, forkId: secret.id }, new Date(Date.now() + 3_600_000).toISOString()).token;
149 const api = async (path: string, token: string) => {
150 const res = await fetch(`${servers.url}/api/v1/search?${path}`, { headers: { authorization: `Bearer ${token}` } });
151 return { status: res.status, body: (await res.json()) as any };
152 };
153 // alice reads noisy, the run token does not.
154 expect((await api("q=glow&kind=issues&repo=alice/noisy", aliceRo)).status).toBe(200);
155 const outside = await api("q=glow&kind=issues&repo=alice/noisy", run);
156 expect(outside.status).toBe(404);
157 expect(outside.body.issues).toBeUndefined();
158 const inside = await api("q=glow&kind=issues&repo=alice/pebble", run);
159 expect(inside.status).toBe(200);
160 expect(inside.body.issues.map((i: any) => i.repo.name)).toEqual(["pebble"]);
161 // The qualifier in another case names the same repository: one scope, not two.
162 expect((await api("q=glow%20repo:alice/PEBBLE&kind=issues&repo=alice/pebble", aliceRo)).status).toBe(200);
163 });
164
125165 test("an unknown kind or a bad limit is refused in the API's words; every kind answers", async () => {
126166 expect((await tool(aliceRo, { q: "a", kind: "bogus" })).error).toContain('argument "kind" is "bogus"');
127167 expect((await tool(aliceRo, { q: "a", kind: "bogus" })).error).toContain('one of "all", "issues", "repos", "code"');

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs