Skip to content
refs
73 lines · 3.8 KBRaw
1import { now } from "./auth.ts";
2import { recordEvent, repoStream } from "./events.ts";
3import { parseGitRoute, proxyGit, readReceiveCommands, rejectPush, scopeFor, type RefUpdate } from "./git.ts";
4import { admitAgentPush } from "./decisions.ts";
5import type { Actor } from "./contract/actor.ts";
6import { resolveActor } from "./identity.ts";
7import { oauth } from "./oauth.ts";
8import { ok } from "./outcomes.ts";
9import { heldBranch, Policy } from "./policy.ts";
10import { findRepoRecord, namespacePolicy, repoFacts } from "./repos.ts";
11import { pusher, type PushMessage } from "./pushes.ts";
12import { claimableBranch, refProblem } from "@refs/protocol";
13
14export async function serveGit(env: Env, ctx: ExecutionContext, request: Request): Promise<Response | null> {
15 const route = parseGitRoute(request.method, new URL(request.url));
16 if (!route) return null;
17
18 const unauthorized = () => new Response("Authentication required\n", { status: 401, headers: { "www-authenticate": 'Basic realm="refs"' } });
19 const { actor, badCredentials } = await resolveActor(env.DB, ctx, request, oauth(env));
20 if (badCredentials) return unauthorized();
21
22 const record = await findRepoRecord(env.DB, route.repo);
23 const policy = record ? await namespacePolicy(env.DB, new Policy(actor, null), record.namespace_id) : new Policy(actor, null);
24 const facts = record ? repoFacts(record) : null;
25 const allowed = facts !== null && policy.canSeeRepo(facts) && (scopeFor(route.service) === "read" || policy.canWriteRepo(facts));
26 if (!allowed) return policy.signedIn ? new Response("Repository not found\n", { status: 404 }) : unauthorized();
27
28 if (route.suffix !== "/git-receive-pack" || !request.body) return proxyGit(request, env.ARTIFACTS, record!.artifacts_name, route);
29
30 const [forwarded, inspected] = request.body.tee();
31 const commands = readReceiveCommands(inspected);
32
33 if (actor.kind === "agent") {
34 const received = await commands;
35 const branch = heldBranch(actor.grant);
36 const claim = branch === null ? claimableBranch(received.updates, record!.default_branch) : null;
37 const reasons = new Map<string, string>();
38 for (const update of received.updates) {
39 const reason = claim ? null : refProblem(branch, update);
40 if (reason) reasons.set(update.ref, reason);
41 }
42 if (reasons.size) {
43 ctx.waitUntil(forwarded.cancel());
44 return rejectPush(received, reasons);
45 }
46 const admitted = await admitAgentPush(env, record!, received, forwarded);
47 if (admitted.landed && claim) await claimBranch(env.DB, actor, record!.id, claim);
48 if (admitted.landed) {
49 ctx.waitUntil(queuePush(env, record!.id, actor, received.updates));
50 }
51 return admitted.response;
52 }
53
54 const response = await proxyGit(new Request(request, { body: forwarded }), env.ARTIFACTS, record!.artifacts_name, route);
55 if (response.ok) {
56 ctx.waitUntil(
57 commands.then(async ({ updates }) => {
58 return queuePush(env, record!.id, actor, updates);
59 }),
60 );
61 }
62 return response;
63}
64
65/** Makes the branch an agent just created by pushing it the session's branch, unless the session claimed another one meanwhile. */
66async function claimBranch(db: D1Database, actor: Extract<Actor, { kind: "agent" }>, repoId: string, branch: string): Promise<void> {
67 const { meta } = await db.prepare("UPDATE agent_sessions SET branch = ? WHERE id = ? AND branch IS NULL AND ended_at IS NULL").bind(branch, actor.sessionId).run();
68 if (meta.changes) await recordEvent(db, actor, repoStream(repoId), "session.tasked", { session: actor.sessionId, branch }, now()).run();
69}
70
71async function queuePush(env: Env, repoId: string, actor: Actor, updates: RefUpdate[]): Promise<void> {
72 if (updates.length) await env.PUSHES.send({ repoId, actor: pusher(actor), updates, at: now() } satisfies PushMessage).catch((error) => console.error(`push not queued for repo ${repoId}`, error));
73}