273 lines · 11.7 KBRaw
| 1 | export type GitService = "git-upload-pack" | "git-receive-pack"; |
| 2 | |
| 3 | export interface GitRoute { |
| 4 | repo: string; |
| 5 | service: GitService; |
| 6 | suffix: string; |
| 7 | } |
| 8 | |
| 9 | const SERVICES = new Set<string>(["git-upload-pack", "git-receive-pack"]); |
| 10 | const FORWARDED_REQUEST_HEADERS = ["content-type", "accept", "git-protocol", "content-encoding", "user-agent"]; |
| 11 | const FORWARDED_RESPONSE_HEADERS = ["content-type", "cache-control", "expires", "pragma"]; |
| 12 | const TOKEN_TTL_SECONDS = 600; |
| 13 | |
| 14 | export function parseGitRoute(method: string, url: URL): GitRoute | null { |
| 15 | const match = url.pathname.match(/^\/([A-Za-z0-9._-]+\/[A-Za-z0-9._-]+)\.git(\/info\/refs|\/git-upload-pack|\/git-receive-pack)$/); |
| 16 | if (!match) return null; |
| 17 | const [, repo, suffix] = match; |
| 18 | |
| 19 | if (suffix === "/info/refs") { |
| 20 | const service = url.searchParams.get("service"); |
| 21 | if (method !== "GET" || !service || !SERVICES.has(service)) return null; |
| 22 | return { repo, service: service as GitService, suffix }; |
| 23 | } |
| 24 | if (method !== "POST") return null; |
| 25 | return { repo, service: suffix.slice(1) as GitService, suffix }; |
| 26 | } |
| 27 | |
| 28 | export function scopeFor(service: GitService): "read" | "write" { |
| 29 | return service === "git-receive-pack" ? "write" : "read"; |
| 30 | } |
| 31 | |
| 32 | export async function proxyGit(request: Request, artifacts: Artifacts, artifactsName: string, route: GitRoute): Promise<Response> { |
| 33 | let remote: string; |
| 34 | let token: string; |
| 35 | try { |
| 36 | using repo = await artifacts.get(artifactsName); |
| 37 | const [info, minted] = await Promise.all([repo.info(), repo.createToken(scopeFor(route.service), TOKEN_TTL_SECONDS)]); |
| 38 | remote = info.remote; |
| 39 | token = minted.plaintext; |
| 40 | } catch (error) { |
| 41 | console.error("artifacts lookup failed", artifactsName, error); |
| 42 | return new Response("Repository not found\n", { status: 404 }); |
| 43 | } |
| 44 | |
| 45 | const headers = new Headers({ authorization: `Bearer ${token}` }); |
| 46 | for (const name of FORWARDED_REQUEST_HEADERS) { |
| 47 | const value = request.headers.get(name); |
| 48 | if (value) headers.set(name, value); |
| 49 | } |
| 50 | |
| 51 | const upstream = await fetch(remote + route.suffix + new URL(request.url).search, { |
| 52 | method: request.method, |
| 53 | headers, |
| 54 | body: request.method === "POST" ? request.body : undefined, |
| 55 | }); |
| 56 | |
| 57 | const responseHeaders = new Headers(); |
| 58 | for (const name of FORWARDED_RESPONSE_HEADERS) { |
| 59 | const value = upstream.headers.get(name); |
| 60 | if (value) responseHeaders.set(name, value); |
| 61 | } |
| 62 | return new Response(upstream.body, { status: upstream.status, headers: responseHeaders }); |
| 63 | } |
| 64 | |
| 65 | export interface Refs { |
| 66 | head: string | null; |
| 67 | branches: Map<string, string>; |
| 68 | tags: Map<string, string>; |
| 69 | } |
| 70 | |
| 71 | export async function readRefs(repo: ArtifactsRepo): Promise<Refs> { |
| 72 | const [info, token] = await Promise.all([repo.info(), repo.createToken("read", 60)]); |
| 73 | const response = await fetch(`${info.remote}/info/refs?service=git-upload-pack`, { |
| 74 | headers: { authorization: `Bearer ${token.plaintext}` }, |
| 75 | }); |
| 76 | if (!response.ok) throw new Error(`ref advertisement failed with ${response.status}`); |
| 77 | return parseRefAdvertisement(new Uint8Array(await response.arrayBuffer())); |
| 78 | } |
| 79 | |
| 80 | export function parseRefAdvertisement(bytes: Uint8Array): Refs { |
| 81 | const decoder = new TextDecoder(); |
| 82 | const refs: Refs = { head: null, branches: new Map(), tags: new Map() }; |
| 83 | |
| 84 | for (let offset = 0; offset + 4 <= bytes.length; ) { |
| 85 | const length = parseInt(decoder.decode(bytes.subarray(offset, offset + 4)), 16); |
| 86 | if (Number.isNaN(length)) break; |
| 87 | if (length < 4) { |
| 88 | offset += 4; |
| 89 | continue; |
| 90 | } |
| 91 | const line = decoder.decode(bytes.subarray(offset + 4, offset + length)).replace(/\n$/, ""); |
| 92 | offset += length; |
| 93 | |
| 94 | const [ref, capabilities] = line.split("\0"); |
| 95 | const symref = capabilities?.match(/(?:^| )symref=HEAD:refs\/heads\/(\S+)/); |
| 96 | if (symref) refs.head = symref[1]; |
| 97 | |
| 98 | const match = ref.match(/^([0-9a-f]{40}) refs\/(heads|tags)\/(.+)$/); |
| 99 | if (!match || match[3].endsWith("^{}")) continue; |
| 100 | (match[2] === "heads" ? refs.branches : refs.tags).set(match[3], match[1]); |
| 101 | } |
| 102 | return refs; |
| 103 | } |
| 104 | |
| 105 | export interface RefUpdate { |
| 106 | ref: string; |
| 107 | from: string | null; |
| 108 | to: string | null; |
| 109 | } |
| 110 | |
| 111 | const ZERO_ID = "0".repeat(40); |
| 112 | |
| 113 | export interface ReceiveCommands { |
| 114 | updates: RefUpdate[]; |
| 115 | capabilities: string[]; |
| 116 | /** Bytes the command list takes at the start of the body, flush packet included. */ |
| 117 | length: number; |
| 118 | } |
| 119 | |
| 120 | /** Parses the command list at the start of a receive-pack request. Returns null until the flush packet has been seen. */ |
| 121 | export function parseReceiveCommands(bytes: Uint8Array): ReceiveCommands | null { |
| 122 | const decoder = new TextDecoder(); |
| 123 | const commands: ReceiveCommands = { updates: [], capabilities: [], length: 0 }; |
| 124 | for (let offset = 0; offset + 4 <= bytes.length; ) { |
| 125 | const length = parseInt(decoder.decode(bytes.subarray(offset, offset + 4)), 16); |
| 126 | if (Number.isNaN(length)) return { ...commands, length: offset }; |
| 127 | if (length === 0) return { ...commands, length: offset + 4 }; |
| 128 | if (offset + length > bytes.length) return null; |
| 129 | const [command, capabilities] = decoder.decode(bytes.subarray(offset + 4, offset + length)).replace(/\n$/, "").split("\0"); |
| 130 | if (capabilities !== undefined && !commands.updates.length) commands.capabilities = capabilities.split(" ").filter(Boolean); |
| 131 | offset += length; |
| 132 | const match = command.match(/^([0-9a-f]{40}) ([0-9a-f]{40}) (refs\/\S+)$/); |
| 133 | if (match) commands.updates.push({ ref: match[3], from: match[1] === ZERO_ID ? null : match[1], to: match[2] === ZERO_ID ? null : match[2] }); |
| 134 | } |
| 135 | return null; |
| 136 | } |
| 137 | |
| 138 | const MAX_COMMAND_BYTES = 64 * 1024; |
| 139 | |
| 140 | /** Reads just enough of a receive-pack body to see its ref updates, then releases the stream. */ |
| 141 | export async function readReceiveCommands(body: ReadableStream<Uint8Array>): Promise<ReceiveCommands> { |
| 142 | const reader = body.getReader(); |
| 143 | let buffered = new Uint8Array(0); |
| 144 | try { |
| 145 | while (buffered.length < MAX_COMMAND_BYTES) { |
| 146 | const { done, value } = await reader.read(); |
| 147 | if (done) break; |
| 148 | const next = new Uint8Array(buffered.length + value.length); |
| 149 | next.set(buffered); |
| 150 | next.set(value, buffered.length); |
| 151 | buffered = next; |
| 152 | const commands = parseReceiveCommands(buffered); |
| 153 | if (commands) return commands; |
| 154 | } |
| 155 | return parseReceiveCommands(buffered) ?? { updates: [], capabilities: [], length: 0 }; |
| 156 | } finally { |
| 157 | await reader.cancel().catch(() => {}); |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | const encoder = new TextEncoder(); |
| 162 | |
| 163 | function pktLine(payload: Uint8Array): Uint8Array<ArrayBuffer> { |
| 164 | const line = new Uint8Array(payload.length + 4); |
| 165 | line.set(encoder.encode((payload.length + 4).toString(16).padStart(4, "0"))); |
| 166 | line.set(payload, 4); |
| 167 | return line; |
| 168 | } |
| 169 | |
| 170 | /** |
| 171 | * Answers a receive-pack request with a status per ref: `ok` where `results` holds null, `ng` with the |
| 172 | * reason otherwise. Git prints each reason next to its ref, and prints `messages` as `remote:` lines |
| 173 | * when the client asked for side-band. |
| 174 | */ |
| 175 | export function reportPush(commands: ReceiveCommands, results: ReadonlyMap<string, string | null>, messages: readonly string[] = []): Response { |
| 176 | const status = [ |
| 177 | pktLine(encoder.encode("unpack ok\n")), |
| 178 | ...commands.updates.map((update) => { |
| 179 | const reason = results.has(update.ref) ? results.get(update.ref) : "rejected with the other refs in this push"; |
| 180 | return pktLine(encoder.encode(reason === null ? `ok ${update.ref}\n` : `ng ${update.ref} ${reason}\n`)); |
| 181 | }), |
| 182 | encoder.encode("0000"), |
| 183 | ]; |
| 184 | const sideband = commands.capabilities.includes("side-band-64k") || commands.capabilities.includes("side-band"); |
| 185 | const chunks = sideband |
| 186 | ? [...messages.map((message) => pktLine(new Uint8Array([2, ...encoder.encode(`${message}\n`)]))), ...status.map((chunk) => pktLine(new Uint8Array([1, ...chunk]))), encoder.encode("0000")] |
| 187 | : status; |
| 188 | return new Response(new Blob(chunks), { headers: { "content-type": "application/x-git-receive-pack-result", "cache-control": "no-cache" } }); |
| 189 | } |
| 190 | |
| 191 | /** Answers a receive-pack request without forwarding it: every ref is reported as rejected, with `reasons` naming why. */ |
| 192 | export function rejectPush(commands: ReceiveCommands, reasons: ReadonlyMap<string, string>, messages: readonly string[] = []): Response { |
| 193 | return reportPush(commands, new Map(commands.updates.map((update) => [update.ref, reasons.get(update.ref) ?? "rejected with the other refs in this push"])), messages); |
| 194 | } |
| 195 | |
| 196 | export const ZERO_OID = ZERO_ID; |
| 197 | |
| 198 | /** A pack with no objects, which git sends when every object a push needs is already on the remote. */ |
| 199 | export const EMPTY_PACK = new Uint8Array([0x50, 0x41, 0x43, 0x4b, 0, 0, 0, 2, 0, 0, 0, 0, ...hexBytes("029d08823bd8a8eab510ad6ac75c823cfd3ed31e")]); |
| 200 | |
| 201 | function hexBytes(hex: string): number[] { |
| 202 | return hex.match(/../g)!.map((pair) => parseInt(pair, 16)); |
| 203 | } |
| 204 | |
| 205 | export interface ReceiveResult { |
| 206 | /** `ok`, or why the remote could not unpack the pack. */ |
| 207 | unpack: string; |
| 208 | /** Null for each ref the remote updated, or its reason for refusing. */ |
| 209 | refs: Map<string, string | null>; |
| 210 | } |
| 211 | |
| 212 | /** |
| 213 | * Sends a push of its own to the repository: `commands` as `"<from> <to> <ref>"`, then `pack`. Side-band |
| 214 | * is never asked for, so the report comes back plain. |
| 215 | */ |
| 216 | export async function receivePack(repo: ArtifactsRepo, commands: readonly string[], capabilities: readonly string[], pack: ReadableStream<Uint8Array> | Uint8Array<ArrayBuffer>): Promise<ReceiveResult> { |
| 217 | const [info, token] = await Promise.all([repo.info(), repo.createToken("write", TOKEN_TTL_SECONDS)]); |
| 218 | const wanted = [...new Set(["report-status", ...capabilities.filter((capability) => !/^(side-band|report-status)/.test(capability))])]; |
| 219 | const head = new Blob([...commands.map((command, index) => pktLine(encoder.encode(index === 0 ? `${command}\0${wanted.join(" ")}\n` : `${command}\n`))), encoder.encode("0000")]); |
| 220 | const body = pack instanceof Uint8Array ? new Blob([head, pack]).stream() : concatStreams(head.stream(), pack); |
| 221 | const response = await fetch(`${info.remote}/git-receive-pack`, { |
| 222 | method: "POST", |
| 223 | headers: { authorization: `Bearer ${token.plaintext}`, "content-type": "application/x-git-receive-pack-request", accept: "application/x-git-receive-pack-result" }, |
| 224 | body, |
| 225 | }); |
| 226 | if (!response.ok) throw new Error(`receive-pack failed with ${response.status}`); |
| 227 | return parseReceiveResult(new Uint8Array(await response.arrayBuffer())); |
| 228 | } |
| 229 | |
| 230 | export function parseReceiveResult(bytes: Uint8Array): ReceiveResult { |
| 231 | const decoder = new TextDecoder(); |
| 232 | const result: ReceiveResult = { unpack: "no report", refs: new Map() }; |
| 233 | for (let offset = 0; offset + 4 <= bytes.length; ) { |
| 234 | const length = parseInt(decoder.decode(bytes.subarray(offset, offset + 4)), 16); |
| 235 | if (Number.isNaN(length) || length < 4) { |
| 236 | offset += 4; |
| 237 | continue; |
| 238 | } |
| 239 | const line = decoder.decode(bytes.subarray(offset + 4, offset + length)).replace(/\n$/, ""); |
| 240 | offset += length; |
| 241 | const [kind, ref, ...reason] = line.split(" "); |
| 242 | if (kind === "unpack") result.unpack = [ref, ...reason].join(" "); |
| 243 | else if (kind === "ok") result.refs.set(ref, null); |
| 244 | else if (kind === "ng") result.refs.set(ref, reason.join(" ") || "rejected"); |
| 245 | } |
| 246 | return result; |
| 247 | } |
| 248 | |
| 249 | /** `stream` without its first `count` bytes. */ |
| 250 | export function dropBytes(stream: ReadableStream<Uint8Array>, count: number): ReadableStream<Uint8Array> { |
| 251 | let left = count; |
| 252 | return stream.pipeThrough( |
| 253 | new TransformStream<Uint8Array, Uint8Array>({ |
| 254 | transform(chunk, controller) { |
| 255 | if (left >= chunk.length) { |
| 256 | left -= chunk.length; |
| 257 | return; |
| 258 | } |
| 259 | controller.enqueue(left ? chunk.subarray(left) : chunk); |
| 260 | left = 0; |
| 261 | }, |
| 262 | }), |
| 263 | ); |
| 264 | } |
| 265 | |
| 266 | function concatStreams(first: ReadableStream<Uint8Array>, second: ReadableStream<Uint8Array>): ReadableStream<Uint8Array> { |
| 267 | const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>(); |
| 268 | (async () => { |
| 269 | await first.pipeTo(writable, { preventClose: true }); |
| 270 | await second.pipeTo(writable); |
| 271 | })().catch((error) => writable.abort(error).catch(() => {})); |
| 272 | return readable; |
| 273 | } |