Public: anyone can read this; the crew can change it.
GET /api/v1/repos/{owner}/{name}/commits reads `path`: only the commits that touched it #18007
Merged 13h 19m ago, live in production
scout/forge:scout/18002-get-api-v1-repos-owner-name-commits-read → main 0 commits fork 1 thread · 1 unresolved
4 files
changed +189
−4
docs/features/commits-path.md added +16
| @@ -0,0 +1,16 @@ | ||
| 1 | --- | |
| 2 | topic: Agents: MCP, git, or the terminal | |
| 3 | row: path= on the commits list: only the commits that touched a file or directory | |
| 4 | --- | |
| 5 | # path= on the commits list | |
| 6 | ||
| 7 | ||
| 8 | GET /api/v1/repos/OWNER/NAME/commits?path=README.md | |
| 9 | GET /api/v1/repos/OWNER/NAME/commits?path=src/http&limit=1 | |
| 10 | ||
| 11 | ||
| 12 | - **`path=`** keeps only the commits that touched a file or directory (repository-relative), newest first, like `git log -- <path>`. It works with `ref`, `limit` and `cursor`. `limit=1` is a file's last commit. | |
| 13 | - The path is a literal name: `*` and `:(…)` are not pathspec magic here. A path nothing touched is an empty list, not a 404. | |
| 14 | - A path that is empty, longer than 4096 characters, starts with `/`, holds a `..` segment or a control character such as NUL is a 400 `invalid_path` in words. | |
| 15 | - Git is held to 10 seconds on a path read; a large repository answers the newest matches or fails in that time: a read that times out is a 504 `path_read_timed_out`, any other failed read (an unknown `ref`, say) a 502 `path_read_failed`, never an empty list. | |
| 16 | - Any other parameter is a 422 `unknown_parameter` naming `ref, path, cursor, limit`, as the issue and pull lists do (see [](api-list-filters.md)). |
src/contract/openapi/routes/getApiV1ReposOwnerNameCommits.ts +1 −1
| @@ -1,4 +1,4 @@ | ||
| 1 | 1 | import { ref } from "../schema_kit.ts"; |
| 2 | 2 | import { REPO, type Route, limitTo } from "../shared.ts"; |
| 3 | 3 | |
| 4 | export const route: Route = { method: "get", path: `${REPO}/commits`, summary: "List commits newest first from `ref` as `{ items, next_cursor }`", detail: "List commits newest first from `ref` (default: the default branch) as `{ items, next_cursor }`, items of { oid, parents, author, email, date, subject, body }; limit 1 to 100 (default 30); a cursor (the next_cursor of the page before, 40 to 64 hex) continues the log after that commit and `ref` is then ignored, so the cursor's own history is paged (a malformed cursor or one naming no commit is a 422 invalid_cursor); an unsafe ref is a 422 bad_ref; a private repository needs a token; the 200 carries a weak etag, cache-control private, no-cache and vary authorization, cookie, and a repeat sending If-None-Match gets 304 with no body until the ref moves", auth: false, role: "anonymous", alsoStatus: [304], query: { ref: "string", cursor: "string", limit: limitTo(100) }, response: ref("CommitList"), refuses: [404] }; | |
| 4 | export const route: Route = { method: "get", path: `${REPO}/commits`, summary: "List commits newest first from `ref` as `{ items, next_cursor }`", detail: "List commits newest first from `ref` (default: the default branch) as `{ items, next_cursor }`, items of { oid, parents, author, email, date, subject, body }; limit 1 to 100 (default 30); a cursor (the next_cursor of the page before, 40 to 64 hex) continues the log after that commit and `ref` is then ignored, so the cursor's own history is paged (a malformed cursor or one naming no commit is a 422 invalid_cursor); `path` (a file or directory, repository-relative) keeps only the commits that touched it, like `git log -- <path>`, with the same cursor, limit and ref (limit=1 is a file's last commit; git is held to 10 s); a path with .. , a leading / or a NUL is a 400 invalid_path, a path nothing touched is an empty list, and a path read that fails is a 502 path_read_failed (a 504 path_read_timed_out past the 10 s); any other parameter is a 422 unknown_parameter; an unsafe ref is a 422 bad_ref; a private repository needs a token; the 200 carries a weak etag, cache-control private, no-cache and vary authorization, cookie, and a repeat sending If-None-Match gets 304 with no body until the ref moves", auth: false, role: "anonymous", alsoStatus: [304, 502, 504], query: { ref: "string", path: "string", cursor: "string", limit: limitTo(100) }, response: ref("CommitList"), refuses: [404] }; |
src/http/api.ts +44 −3
| @@ -169,7 +169,7 @@ import { | ||
| 169 | 169 | } from "../core/users.ts"; |
| 170 | 170 | import { isPinned } from "../core/pins.ts"; |
| 171 | 171 | import { diffCommit } from "../git/diff.ts"; |
| 172 | import { runGit } from "../git/env.ts"; | |
| 172 | import { runGit, STOPPED } from "../git/env.ts"; | |
| 173 | 173 | import { appLimitWords, appsOwnedBy } from "../actions/app_limit.ts"; |
| 174 | 174 | import { getQuota, quotaOf } from "../settings/quotas.ts"; |
| 175 | 175 | import { isSafeOid, isSafeRef, isSafeTreePath } from "../git/guard.ts"; |
| @@ -904,6 +904,18 @@ export function contributeFailure(error: unknown): Response { | ||
| 904 | 904 | |
| 905 | 905 | // ---- query parsing ---- |
| 906 | 906 | |
| 907 | /** | |
| 908 | * Why a repository-relative `?path=` is refused, in words; undefined when it is fine. A NUL | |
| 909 | * or other control character never gets here: the boundary's own check answers it first. | |
| 910 | */ | |
| 911 | function commitPathRefusal(path: string): string | undefined { | |
| 912 | if (path === "") return "path is empty: name a file or directory, or leave path out"; | |
| 913 | if (path.length > 4096) return "path is longer than 4096 characters"; | |
| 914 | if (path.startsWith("/")) return "path is relative to the repository: no leading /"; | |
| 915 | if (path.split("/").includes("..")) return "path may not hold a .. segment"; | |
| 916 | return undefined; | |
| 917 | } | |
| 918 | ||
| 907 | 919 | /** |
| 908 | 920 | * `?limit=`: absent is `fallback`, a whole number from 1 to 200 is itself, |
| 909 | 921 | * anything else is the 422 to answer. |
| @@ -2053,6 +2065,22 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo | ||
| 2053 | 2065 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); |
| 2054 | 2066 | const repo = loadRepo(ctx); |
| 2055 | 2067 | if (!repo) return notFound(); |
| 2068 | const accepted = ["ref", "path", "cursor", "limit"]; | |
| 2069 | const unknown = [...new Set(ctx.url.searchParams.keys())].filter((k) => !accepted.includes(k)); | |
| 2070 | if (unknown.length > 0) | |
| 2071 | return json( | |
| 2072 | { | |
| 2073 | error: "unknown_parameter", | |
| 2074 | message: `this list does not read ${unknown.map((k) => JSON.stringify(k.slice(0, 40))).join(", ")}; it reads ${accepted.join(", ")}`, | |
| 2075 | accepted, | |
| 2076 | }, | |
| 2077 | 422, | |
| 2078 | ); | |
| 2079 | const path = ctx.url.searchParams.get("path"); | |
| 2080 | if (path !== null) { | |
| 2081 | const bad = commitPathRefusal(path); | |
| 2082 | if (bad) return apiError("invalid_path", 400, bad); | |
| 2083 | } | |
| 2056 | 2084 | const ref = ctx.url.searchParams.get("ref") || repo.defaultBranch; |
| 2057 | 2085 | if (!isSafeRef(ref)) return json({ error: "bad_ref" }, 422); |
| 2058 | 2086 | const limit = parseLimit(ctx.url.searchParams.get("limit"), 100, 30); |
| @@ -2062,10 +2090,23 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo | ||
| 2062 | 2090 | if (cursor !== null && !/^[0-9a-f]{40,64}$/.test(cursor)) |
| 2063 | 2091 | return cursorRefusal("cursor is the next_cursor of a page before"); |
| 2064 | 2092 | const log = await timePhaseAsync(ctx.request, "git", () => |
| 2065 | commitLog(dirOf(ctx, repo), cursor ?? ref, { limit: limit + 1, skip: cursor === null ? 0 : 1 }), | |
| 2093 | commitLog(dirOf(ctx, repo), cursor ?? ref, { | |
| 2094 | limit: limit + 1, | |
| 2095 | skip: cursor === null ? 0 : 1, | |
| 2096 | // A literal pathspec: no magic, glob or exclusion from a query string. | |
| 2097 | ...(path === null ? {} : { path: `:(literal)${path}`, timeoutMs: 10_000 }), | |
| 2098 | }), | |
| 2066 | 2099 | ); |
| 2067 | 2100 | if (cursor !== null && !log.ok) |
| 2068 | 2101 | return cursorRefusal("cursor names a commit that is gone: start again without it"); |
| 2102 | // A path read that failed says nothing about the path: an empty list would read as | |
| 2103 | // "no commit touched it", so the failure is answered as one (killed by the 10 s hold: 504). | |
| 2104 | if (path !== null && !log.ok) { | |
| 2105 | const held = log.error.code === 137 || log.error.code === STOPPED; | |
| 2106 | return held | |
| 2107 | ? apiError("path_read_timed_out", 504, "reading the history of that path took too long: try a narrower path or a smaller limit") | |
| 2108 | : apiError("path_read_failed", 502, "the history of that path could not be read: check the ref and try again"); | |
| 2109 | } | |
| 2069 | 2110 | // The tag is of the exact bytes sent plus the ref and limit asked, so a moved tip |
| 2070 | 2111 | // misses, a push to another branch does not, and two queries never share a tag. |
| 2071 | 2112 | return timePhase(ctx.request, "render", () => { |
| @@ -2075,7 +2116,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo | ||
| 2075 | 2116 | items, |
| 2076 | 2117 | next_cursor: all.length > limit ? items[items.length - 1]!.oid : null, |
| 2077 | 2118 | }); |
| 2078 | const etag = weakEtag(`${ref}\n${limit}\n${cursor ?? ""}\n${text}`); | |
| 2119 | const etag = weakEtag(`${ref}\n${limit}\n${cursor ?? ""}\n${path ?? ""}\n${text}`); | |
| 2079 | 2120 | const headers = { etag, "cache-control": "private, no-cache", vary: "authorization, cookie" }; |
| 2080 | 2121 | if (holds(ctx.request, etag)) return new Response(null, { status: 304, headers }); |
| 2081 | 2122 | return new Response(text, { headers: { "content-type": "application/json", ...headers } }); |
test/commits-path.test.ts added +128
| @@ -0,0 +1,128 @@ | ||
| 1 | /** | |
| 2 | * GET …/commits reads `path`: only the commits that touched it; any other unknown parameter is | |
| 3 | * refused (#18002). | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 6 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 7 | import { tmpdir } from "node:os"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { createApp, type App } from "../src/app.ts"; | |
| 10 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 11 | import type { Repo } from "../src/core/repos.ts"; | |
| 12 | import type { User } from "../src/core/users.ts"; | |
| 13 | import { createUser } from "../src/core/users.ts"; | |
| 14 | import { repoDir } from "../src/git/repos.ts"; | |
| 15 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 16 | import { quietLogs } from "./helpers/globals.ts"; | |
| 17 | ||
| 18 | quietLogs(); | |
| 19 | ||
| 20 | let dataDir: string; | |
| 21 | let app: App; | |
| 22 | let servers: Servers; | |
| 23 | let alice: User; | |
| 24 | let repo: Repo; | |
| 25 | const cells = process.env["FORGE_CELLS"]; | |
| 26 | const URL_ = "/api/v1/repos/alice/r/commits"; | |
| 27 | const get = (path = URL_, headers: Record<string, string> = {}) => | |
| 28 | fetch(`${servers.url}${path}`, { headers }); | |
| 29 | const commitFile = async (path: string, content: string) => { | |
| 30 | const done = await commitToBranch(app, alice, repo, { message: `${path} ${content}`, files: [{ path, content }] }); | |
| 31 | if (!done.ok) throw new Error(JSON.stringify(done.error)); | |
| 32 | }; | |
| 33 | ||
| 34 | beforeAll(async () => { | |
| 35 | process.env["FORGE_CELLS"] = "off"; | |
| 36 | dataDir = await mkdtemp(join(tmpdir(), "forge-commits-path-")); | |
| 37 | app = createApp({ dataDir, port: 0 }); | |
| 38 | servers = await serve(app); | |
| 39 | const made = await createUser(app.db, { | |
| 40 | origin: "seed", | |
| 41 | trusted: true, | |
| 42 | username: "alice", | |
| 43 | email: "[email protected]", | |
| 44 | password: "a-good-passphrase", | |
| 45 | adminIfFirst: true, | |
| 46 | }); | |
| 47 | if (!made.ok) throw new Error(String(made.error)); | |
| 48 | alice = made.value; | |
| 49 | const r = await createRepo(app, alice, { name: "r", visibility: "public" }); | |
| 50 | if (!r.ok) throw new Error(String(r.error)); | |
| 51 | repo = r.value; | |
| 52 | await commitFile("a.txt", "a1"); | |
| 53 | await commitFile("b.txt", "b1"); | |
| 54 | await commitFile("a.txt", "a2"); | |
| 55 | }); | |
| 56 | ||
| 57 | afterAll(async () => { | |
| 58 | await servers.stop(); | |
| 59 | app.close(); | |
| 60 | if (cells === undefined) delete process.env["FORGE_CELLS"]; | |
| 61 | else process.env["FORGE_CELLS"] = cells; | |
| 62 | await rm(dataDir, { recursive: true, force: true }); | |
| 63 | }); | |
| 64 | ||
| 65 | type Page = { items: { subject: string }[]; next_cursor: string | null }; | |
| 66 | ||
| 67 | test("?path= keeps the commits that touched it, newest first, with a working cursor", async () => { | |
| 68 | const all = (await (await get(`${URL_}?path=a.txt`)).json()) as Page; | |
| 69 | expect(all.items.map((c) => c.subject)).toEqual(["a.txt a2", "a.txt a1"]); | |
| 70 | const first = (await (await get(`${URL_}?path=a.txt&limit=1`)).json()) as Page; | |
| 71 | expect(first.items.map((c) => c.subject)).toEqual(["a.txt a2"]); | |
| 72 | expect(first.next_cursor).not.toBeNull(); | |
| 73 | const second = (await (await get(`${URL_}?path=a.txt&limit=1&cursor=${first.next_cursor}`)).json()) as Page; | |
| 74 | expect(second.items.map((c) => c.subject)).toEqual(["a.txt a1"]); | |
| 75 | expect(second.next_cursor).toBeNull(); | |
| 76 | expect(((await (await get(URL_)).json()) as Page).items.length).toBe(3); | |
| 77 | }); | |
| 78 | ||
| 79 | test("a path nothing touched is an empty list; a magic pathspec is only a name", async () => { | |
| 80 | for (const p of ["nope.txt", ":(top)a.txt", "*.txt"]) { | |
| 81 | const res = await get(`${URL_}?path=${encodeURIComponent(p)}`); | |
| 82 | expect(res.status).toBe(200); | |
| 83 | expect(((await res.json()) as Page).items).toEqual([]); | |
| 84 | } | |
| 85 | }); | |
| 86 | ||
| 87 | test("a path with .., a leading / or a NUL is a 400 in words", async () => { | |
| 88 | for (const p of ["..%2Fx", "a%2F..%2Fb", "%2Fa.txt", "a%00b", ""]) { | |
| 89 | const res = await get(`${URL_}?path=${p}`); | |
| 90 | expect(res.status).toBe(400); | |
| 91 | expect(((await res.json()) as { message: string }).message.length).toBeGreaterThan(10); | |
| 92 | } | |
| 93 | }); | |
| 94 | ||
| 95 | test("another unknown parameter is refused like the other lists refuse it", async () => { | |
| 96 | const res = await get(`${URL_}?paht=a.txt`); | |
| 97 | expect(res.status).toBe(422); | |
| 98 | expect(((await res.json()) as { error: string }).error).toBe("unknown_parameter"); | |
| 99 | }); | |
| 100 | ||
| 101 | test("the tag differs by path", async () => { | |
| 102 | const a = (await get(`${URL_}?path=a.txt`)).headers.get("etag"); | |
| 103 | const b = (await get(`${URL_}?path=b.txt`)).headers.get("etag"); | |
| 104 | expect(a).not.toBe(b); | |
| 105 | }); | |
| 106 | ||
| 107 | test("a failed path read is an error in words, not an empty list", async () => { | |
| 108 | const res = await get(`${URL_}?path=a.txt&ref=no-such-branch`); | |
| 109 | expect(res.status).toBe(502); | |
| 110 | const body = (await res.json()) as { error: string; message: string }; | |
| 111 | expect(body.error).toBe("path_read_failed"); | |
| 112 | expect(body.message.length).toBeGreaterThan(10); | |
| 113 | }); | |
| 114 | ||
| 115 | test("a path over 4096 characters is a 400", async () => { | |
| 116 | const res = await get(`${URL_}?path=${"a".repeat(4097)}`); | |
| 117 | expect(res.status).toBe(400); | |
| 118 | expect(((await res.json()) as { error: string }).error).toBe("invalid_path"); | |
| 119 | }); | |
| 120 | ||
| 121 | test("path works with ref on a second branch", async () => { | |
| 122 | const dir = repoDir(app.reposRoot, "alice", "r"); | |
| 123 | const made = await Bun.spawn(["git", "-C", dir, "branch", "side", "HEAD~1"]).exited; | |
| 124 | expect(made).toBe(0); | |
| 125 | const res = await get(`${URL_}?path=a.txt&ref=side`); | |
| 126 | expect(res.status).toBe(200); | |
| 127 | expect(((await res.json()) as Page).items.map((c) => c.subject)).toEqual(["a.txt a1"]); | |
| 128 | }); |
new above
offline
The failure branch only covers the cursor case. A failed path read without a cursor falls through to
log.ok ? log.value : []below, so a timeout becomes a 200 empty list and a client concludes the path was never touched. Return an error status with a message in words when!log.ok, and test it.