caelum0x 6801c08af9
Some checks failed
ci / cargo test (abacus) (push) Has been cancelled
ci / cargo test (agent-runtime) (push) Has been cancelled
ci / cargo test (context-passport) (push) Has been cancelled
ci / cargo test (game-economy) (push) Has been cancelled
ci / cargo test (ledgerline) (push) Has been cancelled
ci / cargo test (mint) (push) Has been cancelled
ci / cargo test (rago) (push) Has been cancelled
ci / cargo test (relay) (push) Has been cancelled
ci / node suites (push) Has been cancelled
ci / cargo test (toolgate) (push) Has been cancelled
ci / cargo test (turnstile) (push) Has been cancelled
ci / cargo test (vend) (push) Has been cancelled
feat(RIT-OPS,RIT-BRD): rename gitea -> rit everywhere we control, deployed + live-verified
apps/gitea -> apps/rithub-server; compose services/containers renamed
(rithub-server-app/postgres/act-runner) with explicit project name and
volume names pinned to the exact existing Docker volumes (no data loss);
our own GITEA_* compose/env var names -> RIT_*; new rit-admin CLI wrapper
on railyard-box; giteaSession.mjs/giteaOAuth.mjs/giteaInfo.mjs ->
ritSession/ritOAuth/ritInfo across 6 apps; GiteaForgeAdapter -> RitForgeAdapter
+ giteaSyncService/importGiteaRepos/syncGiteaRepos -> rit* in ritgram
(tsc clean); apps/console/lib/gitea.ts -> lib/ritProvision.ts; Go
internal/giteaclient -> internal/ritclient in rithub-async-import (go
build/test clean); new /auth/rit + /forges/rit/connect routes with
/gitea back-compat aliases; locale/swagger/footer/captcha template text
scrubbed of remaining "Gitea" strings.

Deployed to railyard-box: old containers stopped/removed, /srv/railyard-gitea
renamed to /srv/rithub-server with a symlink kept, docker compose up -d from
the new path, act_runner network-alias fix for its persisted instance URL.
Live-verified: docker compose config diff showed zero unintended value
changes, DB row counts unchanged (19 users, 635 repos), full route
regression 200/expected, 0 "gitea" in headers/bodies on every checked page,
real git clone+push over HTTPS and SSH with a disposable account (deleted
after). Deferred on purpose (documented in plans/railyard.md): the forge
discriminator / DB column names / Postgres role+volume names (data
migrations, not a naming change) and the upstream GITEA__ env-to-ini keys
and X-Gitea-* wire headers (hardcoded in the vendored engine binary).

See plans/railyard.md RIT-OPS/RIT-BRD entry for the full old->new map and
live evidence.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-12-01 16:34:39 +03:00

345 lines
15 KiB
JavaScript

#!/usr/bin/env node
// RIT-ACT gap 1 -- server-side enforcement (2026-12-01). Sits in front of
// ONLY the one real git-smart-HTTP write path, `POST /{owner}/{repo}(.git)/
// git-receive-pack` (Caddy `handle` block, matched before the engine's own
// catch-all reverse_proxy -- every other path, including clone/fetch and
// the web UI, never reaches this process at all). Everything not needing
// inspection is a pure byte-for-byte reverse proxy to the real engine
// (127.0.0.1:3350) -- zero behavior change for a human token, and for an
// agent-session token doing an ordinary push to a non-protected branch.
//
// What this closes: today a raw `git push`/`git push --force`/branch
// delete made with an agent-session token completely bypasses `rit
// push`'s own client-side hold logic (packages/rithub-cli/src/
// push-approval.mjs) -- the server never saw a reason to stop it. This
// service is the `pre-receive`-equivalent hold point the architecture doc
// calls for (plans/rithub-docs/architecture/00-overview.md §3/§4,
// "push-approval hold mechanism": drive a hold check for agent-token
// pushes only, human pushes exit immediately, no behavior change) --
// implemented as a thin HTTP reverse proxy rather than the engine's own
// Go-binary `pre-receive` hook, since that hook has no way to see which
// HTTP credential authenticated a given push (the engine's hook env only
// ever carries the signed-in *user*, never *which of their tokens*); a
// proxy sitting in front of the git-http routes is the one place in this
// stack that still has the raw Authorization header.
//
// Decision for what gets held, same semantics as `rit push`'s own
// protectedBranches check (push-approval.mjs): a push whose target is a
// DELETE, or whose target ref is a protected branch (the repo's own
// default branch, or main/master, or RITHUB_PROTECTED_BRANCHES) is held
// -- regardless of whether the client happened to pass `--force` (the
// wire protocol carries no such flag to inspect; protected-branch-or-
// delete is the real, closeable half of the gap -- see README "Known
// boundary").
import http from "node:http";
import { tryParseReceivePackHeader, encodePktLine, FLUSH_PKT, isAllZero, buildReceivePackResult } from "../src/pktLine.mjs";
import { agentMarkFor } from "../src/agentLedger.mjs";
import { createPendingApproval, confirmPendingPush } from "../src/approvalsClient.mjs";
import { repoDefaultBranch, protectedBranches } from "../src/ritInfo.mjs";
const PORT = Number(process.env.PORT || 3363);
const UPSTREAM_HOST = process.env.RITHUB_UPSTREAM_HOST || "127.0.0.1";
const UPSTREAM_PORT = Number(process.env.RITHUB_UPSTREAM_PORT || 3350);
const RITHUB_BASE_URL = (process.env.RITHUB_BASE_URL || "https://rithub.dev").replace(/\/+$/, "");
const RECEIVE_PACK_RE = /^\/([^/]+)\/([^/]+?)(\.git)?\/git-receive-pack$/;
function extractToken(authHeader) {
if (!authHeader) return null;
let m = /^(?:token|bearer)\s+(.+)$/i.exec(authHeader);
if (m) return m[1].trim();
m = /^Basic\s+(.+)$/i.exec(authHeader);
if (!m) return null;
try {
const decoded = Buffer.from(m[1], "base64").toString("utf8");
const idx = decoded.indexOf(":");
return idx === -1 ? decoded : decoded.slice(idx + 1);
} catch {
return null;
}
}
/** Headers safe to forward as-is to a request this process is about to
* rewrite the framing of. `content-length`/`transfer-encoding` are
* dropped on purpose: Node's http.IncomingMessage already hands us
* de-chunked bytes regardless of how the client framed them, and we may
* be writing a different total length than the original (rewritten ref
* line) or an unknown-ahead-of-time length (plain pipe) -- in both cases
* the safe move is to let Node's own http client choose the outbound
* framing (chunked, since we never set Content-Length here) rather than
* copy a framing header that would then describe the wrong thing. */
function forwardableHeaders(headers) {
const copy = { ...headers };
delete copy["content-length"];
delete copy["transfer-encoding"];
delete copy["host"];
return copy;
}
/** Pure byte-for-byte reverse proxy to the real engine. `prefix`, if
* given, is bytes already pulled off `req` (while peeking for a ref-
* update header) that must be replayed before the live stream continues. */
function passthrough(req, res, { prefix } = {}) {
const upstreamReq = http.request(
{ host: UPSTREAM_HOST, port: UPSTREAM_PORT, method: req.method, path: req.url, headers: forwardableHeaders(req.headers) },
(upstreamRes) => {
res.writeHead(upstreamRes.statusCode, forwardableHeaders(upstreamRes.headers));
upstreamRes.pipe(res);
}
);
upstreamReq.on("error", (err) => {
if (!res.headersSent) res.writeHead(502, { "content-type": "text/plain" });
res.end(`agent-gateway: upstream error: ${err.message}`);
});
if (prefix && prefix.length) upstreamReq.write(prefix);
req.pipe(upstreamReq);
}
/** Reads `req` until a complete ref-update header (ending in the flush
* pkt) has been seen, then pauses the stream. Resolves `{ commands,
* headerLength, buf }` -- `buf` is everything read so far (header +
* whatever of the packfile happened to arrive in the same chunk(s)),
* `buf.subarray(headerLength)` is that already-read packfile prefix. */
function bufferReceivePackHeader(req) {
return new Promise((resolve, reject) => {
let buf = Buffer.alloc(0);
const onData = (chunk) => {
buf = Buffer.concat([buf, chunk]);
let parsed;
try {
parsed = tryParseReceivePackHeader(buf);
} catch (err) {
cleanup();
reject(err);
return;
}
if (parsed) {
cleanup();
req.pause();
resolve({ ...parsed, buf });
}
};
const onEnd = () => {
cleanup();
reject(new Error("request ended before a complete ref-update header was seen"));
};
const onError = (err) => {
cleanup();
reject(err);
};
function cleanup() {
req.off("data", onData);
req.off("end", onEnd);
req.off("error", onError);
}
req.on("data", onData);
req.on("end", onEnd);
req.on("error", onError);
});
}
function drainAndDiscard(req) {
req.resume();
req.on("data", () => {});
}
function sendReceivePackResult(res, { refResults, sideband }) {
const body = buildReceivePackResult({ refResults, sideband });
res.writeHead(200, { "content-type": "application/x-git-receive-pack-result", "content-length": String(body.length) });
res.end(body);
}
function hasSideband(caps) {
return /\bside-band-64k\b/.test(caps || "");
}
async function handleReceivePack(req, res, owner, repo) {
const token = extractToken(req.headers.authorization);
const mark = token ? agentMarkFor(token) : null;
if (!mark) {
// No agent-session attribution for this token (unmarked = treated as
// human, the safe default) -- zero behavior change, pure pipe.
passthrough(req, res);
return;
}
let header;
try {
header = await bufferReceivePackHeader(req);
} catch (err) {
console.error(`agent-gateway: could not read ref-update header for ${owner}/${repo}:`, err.message);
res.writeHead(400, { "content-type": "text/plain" });
res.end(`agent-gateway: ${err.message}`);
return;
}
const { commands, headerLength, buf } = header;
if (commands.length === 0) {
passthrough(req, res, { prefix: buf });
return;
}
if (mark.revoked) {
// One-click "Revoke" from the token-settings panel (apps/gitea's
// applications.tmpl override, via apps/rithub-approvals's
// `revokeMarkForLogin`) -- a revoked agent token can never push
// anything through this gateway again, not just protected branches.
// No hold is registered (there's nothing a human needs to approve
// into existence): every ref update in this push is rejected outright.
drainAndDiscard(req);
sendReceivePackResult(res, {
sideband: hasSideband(commands[0]?.caps),
refResults: commands.map((c) => ({ ref: c.ref, ok: false, message: "agent-gateway: this agent token was revoked, sign in again" })),
});
return;
}
const defaultBranch = await repoDefaultBranch({ owner, repo, token });
const protectedSet = protectedBranches(defaultBranch);
const decided = commands.map((cmd) => {
// Scoped to branch refs only, same as `rit branch delete`/`rit push`
// (neither ever touches a tag) -- a tag delete/push is never held by
// this pass, it's simply out of scope, not silently widened.
const isBranchRef = cmd.ref.startsWith("refs/heads/");
const isDelete = isAllZero(cmd.newrev);
const branchName = isBranchRef ? cmd.ref.replace(/^refs\/heads\//, "") : null;
const needsHold = isBranchRef && (isDelete || protectedSet.has(branchName));
return { ...cmd, isDelete, branchName, needsHold };
});
if (!decided.some((c) => c.needsHold)) {
// Agent-session token, but nothing here needs a hold (ordinary push
// to a non-protected branch) -- replay exactly what was read, then
// let the live stream continue untouched.
passthrough(req, res, { prefix: buf });
return;
}
if (decided.length > 1) {
// Mixed/multi-ref pushes aren't split across held + passthrough in
// this pass (matches `rit push`'s own one-branch-at-a-time model) --
// the real target refs are never touched; nothing is forwarded.
drainAndDiscard(req);
sendReceivePackResult(res, {
sideband: hasSideband(commands[0]?.caps),
refResults: decided.map((c) => ({ ref: c.ref, ok: false, message: "agent-gateway: push one ref at a time with an agent-session token" })),
});
return;
}
const cmd = decided[0];
const sideband = hasSideband(cmd.caps);
if (cmd.isDelete) {
drainAndDiscard(req);
const created = await createPendingApproval({
token,
owner,
repo,
action: "delete",
branch: cmd.branchName,
forced: false,
reason: "raw `git push` with an agent-session token (server-held, apps/rithub-agent-gateway)",
sessionId: mark.sessionId,
});
if (created.status !== 201) {
console.error(`agent-gateway: could not register held delete for ${owner}/${repo}/${cmd.branchName}: HTTP ${created.status}`, created.body);
sendReceivePackResult(res, { sideband, refResults: [{ ref: cmd.ref, ok: false, message: "agent-gateway: could not hold this delete, try again" }] });
return;
}
sendReceivePackResult(res, { sideband, refResults: [{ ref: cmd.ref, ok: false, message: `held for approval, see ${created.body.html_url}` }] });
return;
}
// Force/protected-branch push: register the hold FIRST, then relay the
// same packfile bytes to the real engine -- but retarget the one
// rewritten ref-update line at the unprotected staging ref
// (refs/pending/<id>) instead of the real branch, exactly the ref
// `rit push`'s own stageHeldPush already stages to. The packfile itself
// is never parsed or modified, only this one header line is.
const created = await createPendingApproval({
token,
owner,
repo,
action: "push",
branch: cmd.branchName,
forced: true,
reason: "raw `git push` with an agent-session token (server-held, apps/rithub-agent-gateway)",
sessionId: mark.sessionId,
newrevHint: cmd.newrev,
});
if (created.status !== 201) {
console.error(`agent-gateway: could not register held push for ${owner}/${repo}/${cmd.branchName}: HTTP ${created.status}`, created.body);
drainAndDiscard(req);
sendReceivePackResult(res, { sideband, refResults: [{ ref: cmd.ref, ok: false, message: "agent-gateway: could not hold this push, try again" }] });
return;
}
const pendingRef = created.body.pending_ref;
const zero = "0".repeat(cmd.oldrev.length);
const payloadText = `${zero} ${cmd.newrev} ${pendingRef}\0${cmd.caps}`;
const rewrittenHeader = Buffer.concat([encodePktLine(Buffer.from(payloadText, "utf8")), FLUSH_PKT]);
const prefix = Buffer.concat([rewrittenHeader, buf.subarray(headerLength)]);
let landed = false;
await new Promise((resolve) => {
const upstreamReq = http.request(
{ host: UPSTREAM_HOST, port: UPSTREAM_PORT, method: "POST", path: req.url, headers: forwardableHeaders(req.headers) },
(upstreamRes) => {
landed = upstreamRes.statusCode >= 200 && upstreamRes.statusCode < 300;
upstreamRes.on("data", () => {}); // never relay the engine's own raw result for a held ref -- we answer below
upstreamRes.on("end", resolve);
upstreamRes.on("error", () => resolve());
}
);
upstreamReq.on("error", (err) => {
console.error(`agent-gateway: staging push to ${pendingRef} failed:`, err.message);
resolve();
});
upstreamReq.write(prefix);
req.pipe(upstreamReq);
});
if (!landed) {
sendReceivePackResult(res, { sideband, refResults: [{ ref: cmd.ref, ok: false, message: "agent-gateway: could not stage this push, try again" }] });
return;
}
// The staging push really landed on refs/pending/<id> (we just relayed
// it to the real engine ourselves) -- flip the approval from
// "awaiting_push" to "pending" (visible to a human approver) the same
// way rit push's own stageHeldPush does, via the SAME /confirm route
// (which independently re-verifies the ref on the remote before
// trusting it -- never just takes our word for it either).
const confirmed = await confirmPendingPush({ token, id: created.body.id, newrev: cmd.newrev });
if (confirmed.status !== 200) {
console.error(`agent-gateway: staged ${pendingRef} but could not confirm approval ${created.body.id}: HTTP ${confirmed.status}`, confirmed.body);
}
sendReceivePackResult(res, { sideband, refResults: [{ ref: cmd.ref, ok: false, message: `held for approval, see ${created.body.html_url}` }] });
}
const server = http.createServer(async (req, res) => {
try {
const url = new URL(req.url, `http://${req.headers.host || "localhost"}`);
if (url.pathname === "/agent-gateway/health") {
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify({ ok: true }));
return;
}
if (req.method === "POST") {
const m = RECEIVE_PACK_RE.exec(decodeURIComponent(url.pathname));
if (m) {
await handleReceivePack(req, res, m[1], m[2]);
return;
}
}
// Defensive only -- Caddy routes exactly one path pattern here.
passthrough(req, res);
} catch (err) {
console.error("agent-gateway: unhandled error:", err);
if (!res.headersSent) res.writeHead(500, { "content-type": "text/plain" });
res.end("agent-gateway: internal error");
}
});
server.listen(PORT, "127.0.0.1", () => {
console.log(`rithub-agent-gateway listening on 127.0.0.1:${PORT} -> ${UPSTREAM_HOST}:${UPSTREAM_PORT}, approvals via ${process.env.RITHUB_APPROVALS_URL || "http://127.0.0.1:3361"}, RITHUB_BASE_URL=${RITHUB_BASE_URL}`);
});