Public: anyone can read this; the crew can change it.
src/http/server.ts hands the app-hook handling to its own module, with the same answers #15627
Check · Review · Land · Live done — Landed and live in production.
torque/forge:torque/15622-src-http-server-ts-hands-the-app-hook-ha → main 0 commits fork
3 files
changed +290
−284
docs/CACHING.md +2 −2
| @@ -401,7 +401,7 @@ or stops saying what it did, this doc goes red before the cache goes stale. | ||
| 401 | 401 | |
| 402 | 402 | | write | event | changes | |
| 403 | 403 | | ------------------------------------ | ---------------------- | --------------------------- | |
| 404 | | `http/server#handleHook` | `push` | landings per hour | | |
| 404 | | `http/hook#handleHook` | `push` | landings per hour | | |
| 405 | 405 | | `actions/pulls#mergePull` | `pull.merged` | landings per hour | |
| 406 | 406 | | `actions/runs#announceRun` | `run.finished` | median check time, builders | |
| 407 | 407 | | `actions/runs#announceRun` | `run.started` | builders active | |
| @@ -416,7 +416,7 @@ or stops saying what it did, this doc goes red before the cache goes stale. | ||
| 416 | 416 | | `actions/boards#writeBoard` | `board.saved` | a panel's query | |
| 417 | 417 | | `actions/boards#changeBoard` | `board.saved` | a panel's query | |
| 418 | 418 | | `actions/boards#deleteBoard` | `board.deleted` | a pinned panel goes | |
| 419 | | `http/server#handleHook` | `push` | a board edited in git | | |
| 419 | | `http/hook#handleHook` | `push` | a board edited in git | | |
| 420 | 420 | |
| 421 | 421 | ## Gaps: writes that change a lane without an event on its repository |
| 422 | 422 |
src/http/hook.ts added +285
| @@ -0,0 +1,285 @@ | ||
| 1 | /** | |
| 2 | * The app-hook answers of the internal listener (`serveInternal` in | |
| 3 | * `http/server.ts`): who may call it (`hookCallerAllowed`, this boot's hook | |
| 4 | * secret) and what a git hook relayed from `git/hooks.ts` is told | |
| 5 | * (`handleHook`): pre-receive refuses or lets a push land, post-receive | |
| 6 | * records it and prints what the pusher should read. Plain functions of `app` | |
| 7 | * and the request; the listener puts the security floor on every answer. | |
| 8 | */ | |
| 9 | import { timingSafeEqual } from "node:crypto"; | |
| 10 | import type { App } from "../app.ts"; | |
| 11 | import { BODY_CAPS, readBounded } from "./limits.ts"; | |
| 12 | import { canAdmin, getRepoById } from "../core/repos.ts"; | |
| 13 | import { getUserById, isActive } from "../core/users.ts"; | |
| 14 | import { pullForBranch, trackPullHead } from "../core/pulls.ts"; | |
| 15 | import { recombine } from "../core/recombine.ts"; | |
| 16 | import { carryApproval } from "../core/carry_approval.ts"; | |
| 17 | import { holdFor } from "../core/fork_reach.ts"; | |
| 18 | import { inNamespace } from "../core/proposal_token.ts"; | |
| 19 | import { inContribNamespace } from "../core/contribute_token.ts"; | |
| 20 | import { unsealReleased } from "../actions/sealed.ts"; | |
| 21 | import { forkPushLines } from "../actions/fork_push.ts"; | |
| 22 | import { contribPushPulls, contribPushRefusal } from "../actions/contribute_push.ts"; | |
| 23 | import { queueScanPush } from "../checks/scan.ts"; | |
| 24 | import { PUSH_HOLDS_SECRET, pushHolds } from "../crew/leak.ts"; | |
| 25 | import { heldLongForms } from "../kernel/log.ts"; | |
| 26 | import { runGit } from "../git/env.ts"; | |
| 27 | import { ZERO_OID, type HookRequest } from "../git/hooks.ts"; | |
| 28 | import { asksForPull, forwardedGitEnv, HOOK_SECRET_HEADER } from "../git/hook-protocol.ts"; | |
| 29 | import { resolveOid } from "../git/merge.ts"; | |
| 30 | import { repoDir } from "../git/repos.ts"; | |
| 31 | import { pushCarriesWhatItNames, SEND_WHAT_YOU_NAME } from "../git/own_refs.ts"; | |
| 32 | import { pushThrough } from "../origins/push-through.ts"; | |
| 33 | ||
| 34 | /** Whether the request carries this boot's hook secret (constant-time). */ | |
| 35 | export function hookCallerAllowed(app: App, request: Request): boolean { | |
| 36 | const given = Buffer.from(request.headers.get(HOOK_SECRET_HEADER) ?? ""); | |
| 37 | const want = Buffer.from(app.hookSecret); | |
| 38 | return given.length === want.length && timingSafeEqual(given, want); | |
| 39 | } | |
| 40 | ||
| 41 | export async function handleHook(app: App, request: Request): Promise<Response> { | |
| 42 | // The internal listener is still a door: its body is counted like any other. | |
| 43 | const bytes = await readBounded(request, BODY_CAPS.gitHook.bytes); | |
| 44 | if (bytes === "too_large") return new Response("hook call too large", { status: 413 }); | |
| 45 | let parsed: HookRequest; | |
| 46 | try { | |
| 47 | parsed = JSON.parse(new TextDecoder().decode(bytes)) as HookRequest; | |
| 48 | } catch { | |
| 49 | return new Response("hook call is not JSON", { status: 400 }); | |
| 50 | } | |
| 51 | const input: HookRequest = { ...parsed, gitEnv: forwardedGitEnv(parsed.gitEnv) }; | |
| 52 | const repo = getRepoById(app.db, input.repoId); | |
| 53 | if (!repo) return new Response("unknown repository", { status: 400 }); | |
| 54 | ||
| 55 | if (input.hook === "pre-receive") { | |
| 56 | const actor = input.actorId | |
| 57 | ? getUserById(app.db, input.actorId) | |
| 58 | : undefined; | |
| 59 | for (const update of input.updates) { | |
| 60 | // A proposal token pushes inside its child's namespace and nowhere | |
| 61 | // else: checked first, for every update, so nothing below can let a | |
| 62 | // ref through that this refused. | |
| 63 | if ( | |
| 64 | input.proposalChild !== undefined && | |
| 65 | !inNamespace(update.ref, input.proposalChild) | |
| 66 | ) { | |
| 67 | return new Response( | |
| 68 | `${update.ref}: a proposal token pushes only child/${input.proposalChild}/… branches`, | |
| 69 | { status: 403 }, | |
| 70 | ); | |
| 71 | } | |
| 72 | // An outside agent's token pushes inside `contrib/<agent>/` and nowhere else. | |
| 73 | if ( | |
| 74 | input.contribAgent !== undefined && | |
| 75 | !inContribNamespace(update.ref, input.contribAgent) | |
| 76 | ) { | |
| 77 | return new Response( | |
| 78 | `${update.ref}: this token pushes only contrib/${input.contribAgent}/… branches`, | |
| 79 | { status: 403 }, | |
| 80 | ); | |
| 81 | } | |
| 82 | // New branches of an outside agent's open pulls: the push is refused, with the | |
| 83 | // number, when its caps are spent or it makes more branches than there is room for. | |
| 84 | if (input.contribAgent !== undefined && actor !== undefined) { | |
| 85 | const spent = contribPushRefusal(app, repo, actor.id, input.updates); | |
| 86 | if (spent !== undefined) return new Response(spent, { status: 403 }); | |
| 87 | } | |
| 88 | // The pull namespace belongs to the forge, never to pushers. | |
| 89 | if (update.ref.startsWith("refs/pull/")) { | |
| 90 | return new Response(`${update.ref}: refs/pull/* is reserved`, { | |
| 91 | status: 403, | |
| 92 | }); | |
| 93 | } | |
| 94 | // A push that began before its account was suspended or removed does | |
| 95 | // not land: standing is asked again here, at the ref update. | |
| 96 | if (actor !== undefined && !isActive(actor)) { | |
| 97 | return new Response("this account is suspended: the push is refused", { | |
| 98 | status: 403, | |
| 99 | }); | |
| 100 | } | |
| 101 | // Rule 1 in docs/APPS.md: the crew proposes, a person lands. An agent | |
| 102 | // never moves the default branch — protected or not — so production | |
| 103 | // changes only through a pull someone merged. | |
| 104 | if ( | |
| 105 | actor?.kind === "agent" && | |
| 106 | update.ref === `refs/heads/${repo.defaultBranch}` | |
| 107 | ) { | |
| 108 | return new Response( | |
| 109 | `${repo.defaultBranch}: agents propose through pulls; a person merges`, | |
| 110 | { status: 403 }, | |
| 111 | ); | |
| 112 | } | |
| 113 | if ( | |
| 114 | repo.protectDefault && | |
| 115 | update.ref === `refs/heads/${repo.defaultBranch}` | |
| 116 | ) { | |
| 117 | if (ZERO_OID.test(update.newOid)) { | |
| 118 | return new Response( | |
| 119 | `${repo.defaultBranch} is protected: deletion refused`, | |
| 120 | { | |
| 121 | status: 403, | |
| 122 | }, | |
| 123 | ); | |
| 124 | } | |
| 125 | // A protected default takes commits from its admins only, as the web | |
| 126 | // editor's (`actions/contents.ts`): every other writer lands through | |
| 127 | // a pull. A merge moves the ref itself and never comes here. | |
| 128 | if (!canAdmin(app.db, repo, actor)) { | |
| 129 | return new Response( | |
| 130 | `${repo.defaultBranch} is protected: only its admins push it; open a pull from a branch`, | |
| 131 | { status: 403 }, | |
| 132 | ); | |
| 133 | } | |
| 134 | if (!ZERO_OID.test(update.oldOid)) { | |
| 135 | const dir = repoDir(app.reposRoot, repo.ownerName, repo.name); | |
| 136 | // Quarantine env forwarded from the hook makes the new objects visible. | |
| 137 | const ancestor = await runGit( | |
| 138 | ["merge-base", "--is-ancestor", update.oldOid, update.newOid], | |
| 139 | { cwd: dir, env: input.gitEnv }, | |
| 140 | ); | |
| 141 | if (!ancestor.ok) { | |
| 142 | return new Response( | |
| 143 | `${repo.defaultBranch} is protected: force push refused`, | |
| 144 | { | |
| 145 | status: 403, | |
| 146 | }, | |
| 147 | ); | |
| 148 | } | |
| 149 | } | |
| 150 | } | |
| 151 | } | |
| 152 | // A crew run's push that carries a value the forge holds (a granted secret, the run's token, | |
| 153 | // the model credential) is refused before any ref moves: history is not scrubbed quietly, | |
| 154 | // and the forge's own push for the run refuses the same (`crew/leak.ts`). | |
| 155 | if (actor?.kind === "agent" && heldLongForms().length > 0) { | |
| 156 | const tips = input.updates.map((u) => u.newOid).filter((oid) => !ZERO_OID.test(oid)); | |
| 157 | const dir = repoDir(app.reposRoot, repo.ownerName, repo.name); | |
| 158 | if (await pushHolds(dir, tips, heldLongForms(), input.gitEnv)) | |
| 159 | return new Response(PUSH_HOLDS_SECRET, { status: 403 }); | |
| 160 | } | |
| 161 | // A pusher who may not read the repository this fork borrows its objects | |
| 162 | // from sends every new object the push names: a tip named and not sent | |
| 163 | // would be the lender's commit under the fork's own refs (`git/own_refs.ts`). | |
| 164 | const hold = holdFor(app.db, app.reposRoot, repo, actor); | |
| 165 | if (hold !== undefined) { | |
| 166 | const tips = input.updates.map((u) => u.newOid).filter((oid) => !ZERO_OID.test(oid)); | |
| 167 | if (!(await pushCarriesWhatItNames(hold, tips, input.gitEnv))) | |
| 168 | return new Response(SEND_WHAT_YOU_NAME, { status: 403 }); | |
| 169 | } | |
| 170 | // Everything the forge itself would refuse has passed. If this repo | |
| 171 | // mirrors an origin, the origin gets the last word: it is truth for a | |
| 172 | // mirror, so a push it refuses must not land here either. This runs | |
| 173 | // while the objects are still in the push's quarantine — see | |
| 174 | // origins/push-through.ts for why that both works and matters. | |
| 175 | const forwarded = await pushThrough( | |
| 176 | app, | |
| 177 | repo, | |
| 178 | input.updates, | |
| 179 | input.gitEnv, | |
| 180 | input.actorId, | |
| 181 | ); | |
| 182 | if (!forwarded.ok) { | |
| 183 | return new Response(forwarded.error.message, { status: 403 }); | |
| 184 | } | |
| 185 | return new Response(""); | |
| 186 | } | |
| 187 | ||
| 188 | // post-receive: a same-repo pull whose head is one of these branches | |
| 189 | // follows the push before anything hears about it — the same call the web | |
| 190 | // editor and the API make, so a real `git push` lands on the identical | |
| 191 | // updater rather than a second one that could drift from it. | |
| 192 | for (const update of input.updates) { | |
| 193 | if (!update.ref.startsWith("refs/heads/") || ZERO_OID.test(update.newOid)) | |
| 194 | continue; | |
| 195 | const branch = update.ref.slice("refs/heads/".length); | |
| 196 | // A force-push that only rebases keeps the pull's approval (#12107). | |
| 197 | const open = pullForBranch(app.db, repo.id, branch); | |
| 198 | if (open !== undefined && !open.crossRepo && open.mergedAt === null && open.state === "open") { | |
| 199 | const dir = repoDir(app.reposRoot, repo.ownerName, repo.name); | |
| 200 | const baseTip = await resolveOid(dir, `refs/heads/${open.baseBranch}`); | |
| 201 | if (baseTip !== undefined) | |
| 202 | await carryApproval(app.db, dir, open, baseTip, update.newOid).catch(() => false); | |
| 203 | } | |
| 204 | trackPullHead(app.db, repo.id, branch, update.newOid); | |
| 205 | } | |
| 206 | ||
| 207 | // An outside agent's push opens its pull (or finds it) and prints where it is. | |
| 208 | let printed = ""; | |
| 209 | if (input.contribAgent !== undefined) { | |
| 210 | const origin = (() => { | |
| 211 | try { | |
| 212 | return new URL(input.pushOrigin ?? "").origin; | |
| 213 | } catch { | |
| 214 | return app.config.url !== undefined ? new URL(app.config.url).origin : `http://localhost:${app.config.port}`; | |
| 215 | } | |
| 216 | })(); | |
| 217 | const actor = input.actorId ? getUserById(app.db, input.actorId) : undefined; | |
| 218 | printed = (await contribPushPulls(app, repo, actor, input.updates, origin) | |
| 219 | .catch((error) => { | |
| 220 | app.log.warn("could not open the outside agent's pull", { repo: `${repo.ownerName}/${repo.name}`, error: String(error) }); | |
| 221 | return []; | |
| 222 | })).join("\n"); | |
| 223 | } | |
| 224 | ||
| 225 | // A push to a fork says where its pull is, or opens it when asked (`-o pull`). | |
| 226 | if (input.contribAgent === undefined && repo.forkParentId !== null) { | |
| 227 | const origin = (() => { | |
| 228 | try { | |
| 229 | return new URL(input.pushOrigin ?? "").origin; | |
| 230 | } catch { | |
| 231 | return app.config.url !== undefined ? new URL(app.config.url).origin : `http://localhost:${app.config.port}`; | |
| 232 | } | |
| 233 | })(); | |
| 234 | const actor = input.actorId ? getUserById(app.db, input.actorId) : undefined; | |
| 235 | const lines = await forkPushLines(app, repo, actor, input.updates, origin, asksForPull(input.pushOptions)).catch((error) => { | |
| 236 | app.log.warn("could not offer the fork's pull", { repo: `${repo.ownerName}/${repo.name}`, error: String(error) }); | |
| 237 | return [] as string[]; | |
| 238 | }); | |
| 239 | printed = lines.join("\n"); | |
| 240 | } | |
| 241 | ||
| 242 | // post-receive: the push is durable — record it and wake listeners. | |
| 243 | app.bus.append({ | |
| 244 | kind: "push", | |
| 245 | repoId: repo.id, | |
| 246 | actorId: input.actorId || undefined, | |
| 247 | payload: { updates: input.updates }, | |
| 248 | }); | |
| 249 | // A tag that releases a sealed report's fix opens the report | |
| 250 | // (`actions/sealed.ts`). Off the hook's answer: git need not wait for it. | |
| 251 | void unsealReleased( | |
| 252 | app, | |
| 253 | repo, | |
| 254 | input.updates, | |
| 255 | input.actorId ? getUserById(app.db, input.actorId) : undefined, | |
| 256 | ).catch((error) => | |
| 257 | app.log.warn("could not unseal released reports", { | |
| 258 | repo: `${repo.ownerName}/${repo.name}`, | |
| 259 | error: String(error), | |
| 260 | }), | |
| 261 | ); | |
| 262 | // A push that moves the default branch brings every kept-fork pull's | |
| 263 | // `combined/N` up to date (`core/recombine.ts`). Off the hook's answer: | |
| 264 | // the pusher never waits for it, and never hears of its errors. | |
| 265 | const tip = `refs/heads/${repo.defaultBranch}`; | |
| 266 | if (input.updates.some((u) => u.ref === tip && !ZERO_OID.test(u.newOid))) | |
| 267 | void recombine( | |
| 268 | { db: app.db, reposRoot: app.reposRoot, log: app.log }, | |
| 269 | repo.id, | |
| 270 | ).catch((error) => | |
| 271 | app.log.warn("could not recombine after the push", { | |
| 272 | repo: `${repo.ownerName}/${repo.name}`, | |
| 273 | error: String(error), | |
| 274 | }), | |
| 275 | ); | |
| 276 | // Every push is scanned for secrets and advisories (`checks/scan.ts`, | |
| 277 | // #9593). Off the hook's answer too: a finding is recorded, not refused. | |
| 278 | void queueScanPush(app, repo, input.updates).catch((error) => | |
| 279 | app.log.warn("could not scan the push", { | |
| 280 | repo: `${repo.ownerName}/${repo.name}`, | |
| 281 | error: String(error), | |
| 282 | }), | |
| 283 | ); | |
| 284 | return new Response(printed); | |
| 285 | } |
src/http/server.ts +3 −282
| @@ -35,8 +35,6 @@ import { startClaimAccountSubmit, startClaimPage, startClaimSubmit } from "../we | ||
| 35 | 35 | import { signupOptions, signupPasskey } from "../web/pages/signup-passkey.ts"; |
| 36 | 36 | import { toolbarComment, toolbarPage } from "../web/studio/toolbar.ts"; |
| 37 | 37 | import { TOOLBAR_NAME, toolbarResponse } from "../apps/toolbar.ts"; |
| 38 | import { unsealReleased } from "../actions/sealed.ts"; | |
| 39 | import { queueScanPush } from "../checks/scan.ts"; | |
| 40 | 38 | import { parentCallback, parentStart } from "./rp.ts"; |
| 41 | 39 | import { prerenderComments } from "../web/prerender.ts"; |
| 42 | 40 | import { heapCensusSubmit, systemPage, systemStream } from "../web/pages/system.ts"; |
| @@ -79,7 +77,6 @@ import { | ||
| 79 | 77 | import { defect } from "../kernel/error.ts"; |
| 80 | 78 | import { |
| 81 | 79 | armClose, |
| 82 | BODY_CAPS, | |
| 83 | 80 | BODY_MAX, |
| 84 | 81 | carryNotes, |
| 85 | 82 | closeAfter, |
| @@ -90,14 +87,11 @@ import { | ||
| 90 | 87 | settleBody, |
| 91 | 88 | } from "./limits.ts"; |
| 92 | 89 | import { |
| 93 | canAdmin, | |
| 94 | 90 | canRead, |
| 95 | 91 | canWrite, |
| 96 | 92 | getRepo, |
| 97 | getRepoById, | |
| 98 | 93 | } from "../core/repos.ts"; |
| 99 | import { pullForBranch, trackPullHead } from "../core/pulls.ts"; | |
| 100 | import { recombine } from "../core/recombine.ts"; | |
| 94 | import { hookCallerAllowed, handleHook } from "./hook.ts"; | |
| 101 | 95 | import { createRepo, repositoryLimitMessage, resolveOwner } from "../actions/repos.ts"; |
| 102 | 96 | import { sessionOf } from "../core/sessions.ts"; |
| 103 | 97 | import { browserName } from "../auth/browser_name.ts"; |
| @@ -105,7 +99,6 @@ import { scopeAllows, verifyToken } from "../core/tokens.ts"; | ||
| 105 | 99 | import { |
| 106 | 100 | ensureEdgeUser, |
| 107 | 101 | getUserByName, |
| 108 | isActive, | |
| 109 | 102 | verifyPasswordThrottled, |
| 110 | 103 | } from "../core/users.ts"; |
| 111 | 104 | import { activeEdgeToken, edgeIdentity } from "./edge.ts"; |
| @@ -117,20 +110,13 @@ import { ownSchedules, recordOwnRun } from "../core/own_schedules.ts"; | ||
| 117 | 110 | import { isRead, readOnlyRefusal } from "./read_only.ts"; |
| 118 | 111 | import { fullRefusal, isFullError, noteFull } from "../kernel/full_disk.ts"; |
| 119 | 112 | import { running } from "../kernel/version.ts"; |
| 120 | import { runGit } from "../git/env.ts"; | |
| 121 | 113 | import { failedPage, requestId } from "../web/failed_page.ts"; |
| 122 | 114 | import { noteRefusedInternal } from "../kernel/internal_refused.ts"; |
| 123 | 115 | import { CONTRIBUTE_PUSH_MAX_BYTES } from "../core/contribute_token.ts"; |
| 124 | import { forkPushLines } from "../actions/fork_push.ts"; | |
| 125 | import { contribPushPulls, contribPushRefusal } from "../actions/contribute_push.ts"; | |
| 126 | 116 | import { pushCap, storageChanged, storageRefusal, storageRefusedText, storageSentence } from "../core/storage.ts"; |
| 127 | import { hookEnv, ZERO_OID, type HookRequest } from "../git/hooks.ts"; | |
| 128 | import { carryApproval } from "../core/carry_approval.ts"; | |
| 129 | import { resolveOid } from "../git/merge.ts"; | |
| 117 | import { hookEnv } from "../git/hooks.ts"; | |
| 130 | 118 | import { repoDir } from "../git/repos.ts"; |
| 131 | import { PUSH_HOLDS_SECRET, pushHolds } from "../crew/leak.ts"; | |
| 132 | import { heldLongForms } from "../kernel/log.ts"; | |
| 133 | import { asReader, heldPushConfig, pushCarriesWhatItNames, SEND_WHAT_YOU_NAME } from "../git/own_refs.ts"; | |
| 119 | import { asReader, heldPushConfig } from "../git/own_refs.ts"; | |
| 134 | 120 | import { holdFor, lendersBeyond } from "../core/fork_reach.ts"; |
| 135 | 121 | import { bundleUriFor, noteBundle } from "../git/bundle_uri.ts"; |
| 136 | 122 | import { |
| @@ -146,12 +132,6 @@ import { | ||
| 146 | 132 | takeDoor, |
| 147 | 133 | tooManyStrangers, |
| 148 | 134 | } from "./strangers.ts"; |
| 149 | import { timingSafeEqual } from "node:crypto"; | |
| 150 | import { | |
| 151 | asksForPull, | |
| 152 | forwardedGitEnv, | |
| 153 | HOOK_SECRET_HEADER, | |
| 154 | } from "../git/hook-protocol.ts"; | |
| 155 | 135 | import { lstat, readdir, rm } from "node:fs/promises"; |
| 156 | 136 | import { rmSync } from "node:fs"; |
| 157 | 137 | import { join } from "node:path"; |
| @@ -562,15 +542,12 @@ import { | ||
| 562 | 542 | browseTree, |
| 563 | 543 | } from "../web/pages/browse.ts"; |
| 564 | 544 | import { bringConnect, bringEnvSubmit, bringJobPage, bringPage, bringRun, bringSubmit } from "../web/pages/bring.ts"; |
| 565 | import { pushThrough } from "../origins/push-through.ts"; | |
| 566 | 545 | import { assetNotFound, MACHINE_PREFIX, typedMiss } from "./asset_miss.ts"; |
| 567 | 546 | import { CAME_FROM_ELSEWHERE, forbiddenPage, notFoundPage, SENT_FROM_ELSEWHERE, signInHref } from "../web/chrome.ts"; |
| 568 | 547 | import { targetForShortCode } from "../origins/oauth.ts"; |
| 569 | 548 | import { apiRoutes, oauthCallbackUri } from "./api.ts"; |
| 570 | 549 | import { brokerStart } from "../spawn/origin_broker.ts"; |
| 571 | 550 | import { pageParamRefused, takeFields, withFields, withLinkNext } from "./cursor_lists.ts"; |
| 572 | import { inNamespace } from "../core/proposal_token.ts"; | |
| 573 | import { inContribNamespace } from "../core/contribute_token.ts"; | |
| 574 | 551 | import { takesOutside } from "../actions/contribute_token.ts"; |
| 575 | 552 | import { reportsOpenSet, contributeOpenSet, contributeTokenRevoke, proposalTokenMint, proposalTokenRevoke } from "../web/pages/proposal-tokens.ts"; |
| 576 | 553 | import { adminGate } from "./admin_gate.ts"; |
| @@ -688,7 +665,6 @@ import { | ||
| 688 | 665 | import { sseStream, viewerStream } from "./sse.ts"; |
| 689 | 666 | import { isAdminRoute } from "./route_marks.ts"; |
| 690 | 667 | import { Router } from "./router.ts"; |
| 691 | import { getUserById } from "../core/users.ts"; | |
| 692 | 668 | import { appsRuntime } from "../apps/runtime.ts"; |
| 693 | 669 | import { holdAppHost } from "../apps/holding.ts"; |
| 694 | 670 | import { isArcadeHost, serveArcade } from "../arcade/host.ts"; |
| @@ -2372,261 +2348,6 @@ const fromStored = (stored: StoredResponse, replay: boolean): Response => { | ||
| 2372 | 2348 | return new Response(stored.body === "" ? null : stored.body, { status: stored.status, headers }); |
| 2373 | 2349 | }; |
| 2374 | 2350 | |
| 2375 | // ---- the internal server (unix socket, hooks only) ---- | |
| 2376 | ||
| 2377 | /** Whether the request carries this boot's hook secret (constant-time). */ | |
| 2378 | function hookCallerAllowed(app: App, request: Request): boolean { | |
| 2379 | const given = Buffer.from(request.headers.get(HOOK_SECRET_HEADER) ?? ""); | |
| 2380 | const want = Buffer.from(app.hookSecret); | |
| 2381 | return given.length === want.length && timingSafeEqual(given, want); | |
| 2382 | } | |
| 2383 | ||
| 2384 | async function handleHook(app: App, request: Request): Promise<Response> { | |
| 2385 | // The internal listener is still a door: its body is counted like any other. | |
| 2386 | const bytes = await readBounded(request, BODY_CAPS.gitHook.bytes); | |
| 2387 | if (bytes === "too_large") return new Response("hook call too large", { status: 413 }); | |
| 2388 | let parsed: HookRequest; | |
| 2389 | try { | |
| 2390 | parsed = JSON.parse(new TextDecoder().decode(bytes)) as HookRequest; | |
| 2391 | } catch { | |
| 2392 | return new Response("hook call is not JSON", { status: 400 }); | |
| 2393 | } | |
| 2394 | const input: HookRequest = { ...parsed, gitEnv: forwardedGitEnv(parsed.gitEnv) }; | |
| 2395 | const repo = getRepoById(app.db, input.repoId); | |
| 2396 | if (!repo) return new Response("unknown repository", { status: 400 }); | |
| 2397 | ||
| 2398 | if (input.hook === "pre-receive") { | |
| 2399 | const actor = input.actorId | |
| 2400 | ? getUserById(app.db, input.actorId) | |
| 2401 | : undefined; | |
| 2402 | for (const update of input.updates) { | |
| 2403 | // A proposal token pushes inside its child's namespace and nowhere | |
| 2404 | // else: checked first, for every update, so nothing below can let a | |
| 2405 | // ref through that this refused. | |
| 2406 | if ( | |
| 2407 | input.proposalChild !== undefined && | |
| 2408 | !inNamespace(update.ref, input.proposalChild) | |
| 2409 | ) { | |
| 2410 | return new Response( | |
| 2411 | `${update.ref}: a proposal token pushes only child/${input.proposalChild}/… branches`, | |
| 2412 | { status: 403 }, | |
| 2413 | ); | |
| 2414 | } | |
| 2415 | // An outside agent's token pushes inside `contrib/<agent>/` and nowhere else. | |
| 2416 | if ( | |
| 2417 | input.contribAgent !== undefined && | |
| 2418 | !inContribNamespace(update.ref, input.contribAgent) | |
| 2419 | ) { | |
| 2420 | return new Response( | |
| 2421 | `${update.ref}: this token pushes only contrib/${input.contribAgent}/… branches`, | |
| 2422 | { status: 403 }, | |
| 2423 | ); | |
| 2424 | } | |
| 2425 | // New branches of an outside agent's open pulls: the push is refused, with the | |
| 2426 | // number, when its caps are spent or it makes more branches than there is room for. | |
| 2427 | if (input.contribAgent !== undefined && actor !== undefined) { | |
| 2428 | const spent = contribPushRefusal(app, repo, actor.id, input.updates); | |
| 2429 | if (spent !== undefined) return new Response(spent, { status: 403 }); | |
| 2430 | } | |
| 2431 | // The pull namespace belongs to the forge, never to pushers. | |
| 2432 | if (update.ref.startsWith("refs/pull/")) { | |
| 2433 | return new Response(`${update.ref}: refs/pull/* is reserved`, { | |
| 2434 | status: 403, | |
| 2435 | }); | |
| 2436 | } | |
| 2437 | // A push that began before its account was suspended or removed does | |
| 2438 | // not land: standing is asked again here, at the ref update. | |
| 2439 | if (actor !== undefined && !isActive(actor)) { | |
| 2440 | return new Response("this account is suspended: the push is refused", { | |
| 2441 | status: 403, | |
| 2442 | }); | |
| 2443 | } | |
| 2444 | // Rule 1 in docs/APPS.md: the crew proposes, a person lands. An agent | |
| 2445 | // never moves the default branch — protected or not — so production | |
| 2446 | // changes only through a pull someone merged. | |
| 2447 | if ( | |
| 2448 | actor?.kind === "agent" && | |
| 2449 | update.ref === `refs/heads/${repo.defaultBranch}` | |
| 2450 | ) { | |
| 2451 | return new Response( | |
| 2452 | `${repo.defaultBranch}: agents propose through pulls; a person merges`, | |
| 2453 | { status: 403 }, | |
| 2454 | ); | |
| 2455 | } | |
| 2456 | if ( | |
| 2457 | repo.protectDefault && | |
| 2458 | update.ref === `refs/heads/${repo.defaultBranch}` | |
| 2459 | ) { | |
| 2460 | if (ZERO_OID.test(update.newOid)) { | |
| 2461 | return new Response( | |
| 2462 | `${repo.defaultBranch} is protected: deletion refused`, | |
| 2463 | { | |
| 2464 | status: 403, | |
| 2465 | }, | |
| 2466 | ); | |
| 2467 | } | |
| 2468 | // A protected default takes commits from its admins only, as the web | |
| 2469 | // editor's (`actions/contents.ts`): every other writer lands through | |
| 2470 | // a pull. A merge moves the ref itself and never comes here. | |
| 2471 | if (!canAdmin(app.db, repo, actor)) { | |
| 2472 | return new Response( | |
| 2473 | `${repo.defaultBranch} is protected: only its admins push it; open a pull from a branch`, | |
| 2474 | { status: 403 }, | |
| 2475 | ); | |
| 2476 | } | |
| 2477 | if (!ZERO_OID.test(update.oldOid)) { | |
| 2478 | const dir = repoDir(app.reposRoot, repo.ownerName, repo.name); | |
| 2479 | // Quarantine env forwarded from the hook makes the new objects visible. | |
| 2480 | const ancestor = await runGit( | |
| 2481 | ["merge-base", "--is-ancestor", update.oldOid, update.newOid], | |
| 2482 | { cwd: dir, env: input.gitEnv }, | |
| 2483 | ); | |
| 2484 | if (!ancestor.ok) { | |
| 2485 | return new Response( | |
| 2486 | `${repo.defaultBranch} is protected: force push refused`, | |
| 2487 | { | |
| 2488 | status: 403, | |
| 2489 | }, | |
| 2490 | ); | |
| 2491 | } | |
| 2492 | } | |
| 2493 | } | |
| 2494 | } | |
| 2495 | // A crew run's push that carries a value the forge holds (a granted secret, the run's token, | |
| 2496 | // the model credential) is refused before any ref moves: history is not scrubbed quietly, | |
| 2497 | // and the forge's own push for the run refuses the same (`crew/leak.ts`). | |
| 2498 | if (actor?.kind === "agent" && heldLongForms().length > 0) { | |
| 2499 | const tips = input.updates.map((u) => u.newOid).filter((oid) => !ZERO_OID.test(oid)); | |
| 2500 | const dir = repoDir(app.reposRoot, repo.ownerName, repo.name); | |
| 2501 | if (await pushHolds(dir, tips, heldLongForms(), input.gitEnv)) | |
| 2502 | return new Response(PUSH_HOLDS_SECRET, { status: 403 }); | |
| 2503 | } | |
| 2504 | // A pusher who may not read the repository this fork borrows its objects | |
| 2505 | // from sends every new object the push names: a tip named and not sent | |
| 2506 | // would be the lender's commit under the fork's own refs (`git/own_refs.ts`). | |
| 2507 | const hold = holdFor(app.db, app.reposRoot, repo, actor); | |
| 2508 | if (hold !== undefined) { | |
| 2509 | const tips = input.updates.map((u) => u.newOid).filter((oid) => !ZERO_OID.test(oid)); | |
| 2510 | if (!(await pushCarriesWhatItNames(hold, tips, input.gitEnv))) | |
| 2511 | return new Response(SEND_WHAT_YOU_NAME, { status: 403 }); | |
| 2512 | } | |
| 2513 | // Everything the forge itself would refuse has passed. If this repo | |
| 2514 | // mirrors an origin, the origin gets the last word: it is truth for a | |
| 2515 | // mirror, so a push it refuses must not land here either. This runs | |
| 2516 | // while the objects are still in the push's quarantine — see | |
| 2517 | // origins/push-through.ts for why that both works and matters. | |
| 2518 | const forwarded = await pushThrough( | |
| 2519 | app, | |
| 2520 | repo, | |
| 2521 | input.updates, | |
| 2522 | input.gitEnv, | |
| 2523 | input.actorId, | |
| 2524 | ); | |
| 2525 | if (!forwarded.ok) { | |
| 2526 | return new Response(forwarded.error.message, { status: 403 }); | |
| 2527 | } | |
| 2528 | return new Response(""); | |
| 2529 | } | |
| 2530 | ||
| 2531 | // post-receive: a same-repo pull whose head is one of these branches | |
| 2532 | // follows the push before anything hears about it — the same call the web | |
| 2533 | // editor and the API make, so a real `git push` lands on the identical | |
| 2534 | // updater rather than a second one that could drift from it. | |
| 2535 | for (const update of input.updates) { | |
| 2536 | if (!update.ref.startsWith("refs/heads/") || ZERO_OID.test(update.newOid)) | |
| 2537 | continue; | |
| 2538 | const branch = update.ref.slice("refs/heads/".length); | |
| 2539 | // A force-push that only rebases keeps the pull's approval (#12107). | |
| 2540 | const open = pullForBranch(app.db, repo.id, branch); | |
| 2541 | if (open !== undefined && !open.crossRepo && open.mergedAt === null && open.state === "open") { | |
| 2542 | const dir = repoDir(app.reposRoot, repo.ownerName, repo.name); | |
| 2543 | const baseTip = await resolveOid(dir, `refs/heads/${open.baseBranch}`); | |
| 2544 | if (baseTip !== undefined) | |
| 2545 | await carryApproval(app.db, dir, open, baseTip, update.newOid).catch(() => false); | |
| 2546 | } | |
| 2547 | trackPullHead(app.db, repo.id, branch, update.newOid); | |
| 2548 | } | |
| 2549 | ||
| 2550 | // An outside agent's push opens its pull (or finds it) and prints where it is. | |
| 2551 | let printed = ""; | |
| 2552 | if (input.contribAgent !== undefined) { | |
| 2553 | const origin = (() => { | |
| 2554 | try { | |
| 2555 | return new URL(input.pushOrigin ?? "").origin; | |
| 2556 | } catch { | |
| 2557 | return app.config.url !== undefined ? new URL(app.config.url).origin : `http://localhost:${app.config.port}`; | |
| 2558 | } | |
| 2559 | })(); | |
| 2560 | const actor = input.actorId ? getUserById(app.db, input.actorId) : undefined; | |
| 2561 | printed = (await contribPushPulls(app, repo, actor, input.updates, origin) | |
| 2562 | .catch((error) => { | |
| 2563 | app.log.warn("could not open the outside agent's pull", { repo: `${repo.ownerName}/${repo.name}`, error: String(error) }); | |
| 2564 | return []; | |
| 2565 | })).join("\n"); | |
| 2566 | } | |
| 2567 | ||
| 2568 | // A push to a fork says where its pull is, or opens it when asked (`-o pull`). | |
| 2569 | if (input.contribAgent === undefined && repo.forkParentId !== null) { | |
| 2570 | const origin = (() => { | |
| 2571 | try { | |
| 2572 | return new URL(input.pushOrigin ?? "").origin; | |
| 2573 | } catch { | |
| 2574 | return app.config.url !== undefined ? new URL(app.config.url).origin : `http://localhost:${app.config.port}`; | |
| 2575 | } | |
| 2576 | })(); | |
| 2577 | const actor = input.actorId ? getUserById(app.db, input.actorId) : undefined; | |
| 2578 | const lines = await forkPushLines(app, repo, actor, input.updates, origin, asksForPull(input.pushOptions)).catch((error) => { | |
| 2579 | app.log.warn("could not offer the fork's pull", { repo: `${repo.ownerName}/${repo.name}`, error: String(error) }); | |
| 2580 | return [] as string[]; | |
| 2581 | }); | |
| 2582 | printed = lines.join("\n"); | |
| 2583 | } | |
| 2584 | ||
| 2585 | // post-receive: the push is durable — record it and wake listeners. | |
| 2586 | app.bus.append({ | |
| 2587 | kind: "push", | |
| 2588 | repoId: repo.id, | |
| 2589 | actorId: input.actorId || undefined, | |
| 2590 | payload: { updates: input.updates }, | |
| 2591 | }); | |
| 2592 | // A tag that releases a sealed report's fix opens the report | |
| 2593 | // (`actions/sealed.ts`). Off the hook's answer: git need not wait for it. | |
| 2594 | void unsealReleased( | |
| 2595 | app, | |
| 2596 | repo, | |
| 2597 | input.updates, | |
| 2598 | input.actorId ? getUserById(app.db, input.actorId) : undefined, | |
| 2599 | ).catch((error) => | |
| 2600 | app.log.warn("could not unseal released reports", { | |
| 2601 | repo: `${repo.ownerName}/${repo.name}`, | |
| 2602 | error: String(error), | |
| 2603 | }), | |
| 2604 | ); | |
| 2605 | // A push that moves the default branch brings every kept-fork pull's | |
| 2606 | // `combined/N` up to date (`core/recombine.ts`). Off the hook's answer: | |
| 2607 | // the pusher never waits for it, and never hears of its errors. | |
| 2608 | const tip = `refs/heads/${repo.defaultBranch}`; | |
| 2609 | if (input.updates.some((u) => u.ref === tip && !ZERO_OID.test(u.newOid))) | |
| 2610 | void recombine( | |
| 2611 | { db: app.db, reposRoot: app.reposRoot, log: app.log }, | |
| 2612 | repo.id, | |
| 2613 | ).catch((error) => | |
| 2614 | app.log.warn("could not recombine after the push", { | |
| 2615 | repo: `${repo.ownerName}/${repo.name}`, | |
| 2616 | error: String(error), | |
| 2617 | }), | |
| 2618 | ); | |
| 2619 | // Every push is scanned for secrets and advisories (`checks/scan.ts`, | |
| 2620 | // #9593). Off the hook's answer too: a finding is recorded, not refused. | |
| 2621 | void queueScanPush(app, repo, input.updates).catch((error) => | |
| 2622 | app.log.warn("could not scan the push", { | |
| 2623 | repo: `${repo.ownerName}/${repo.name}`, | |
| 2624 | error: String(error), | |
| 2625 | }), | |
| 2626 | ); | |
| 2627 | return new Response(printed); | |
| 2628 | } | |
| 2629 | ||
| 2630 | 2351 | // ---- wiring ---- |
| 2631 | 2352 | |
| 2632 | 2353 | export interface Servers { |
new above
offline