Source code for fleetmesh_protocols.grasp.git_http

"""Git Smart HTTP and the node portal for the GRASP git store (`node.protocols.grasp.git_http`).

`/git/<repo>.git/...`: fetching (`git-upload-pack`) is open; pushing (`git-receive-pack` and its
advertisement) is the repo owner's alone, as the request principal. A fetch never creates a repo.
"""
from __future__ import annotations

import html
import json
import re
import subprocess
from typing import Dict, Optional, Tuple

from fleetmesh_core.textile.principal import MeshAccessError, Principal, require_principal

from .git_store import GIT_TIMEOUT_SEC, StandaloneGraspGitStore, _clean_slug


def _pkt_line(payload: bytes) -> bytes:
    length = len(payload) + 4
    return f"{length:04x}".encode("ascii") + payload


[docs]def handle_git_smart_http( store: StandaloneGraspGitStore, method: str, route: str, query: str, body: bytes = b"", principal: Principal = None, ) -> Optional[Tuple[int, bytes, str, Dict[str, str]]]: """Handle Git Smart HTTP requests (`/git/<slug>.git/info/refs`, `git-upload-pack`, `git-receive-pack`).""" if not route.startswith("/git/"): return None sub = route[len("/git/") :].lstrip("/") m = re.match(r"^([^/]+(?:/[^/]+)?)\.git(?:/(.*))?$", sub) if not m: m = re.match(r"^([^/]+)/(info/refs|git-upload-pack|git-receive-pack|HEAD)$", sub) if not m: slug = _clean_slug(sub.split("/")[0]) repo = store.get_repo(slug) if repo and method == "GET": raw = json.dumps({"ok": True, "repo": repo}, separators=(",", ":")).encode("utf-8") return 200, raw, "application/json; charset=utf-8", {} return None raw_repo_name, git_action = m.group(1), (m.group(2) or "").strip("/") slug = _clean_slug(raw_repo_name.split("/")[-1]) headers = {"Cache-Control": "no-cache, max-age=0, must-revalidate"} wants_push = git_action == "git-receive-pack" or "service=git-receive-pack" in str(query or "") with store._lock: if wants_push: try: store._owned(slug, require_principal(principal)) except MeshAccessError as exc: return exc.status, exc.error.encode("utf-8"), "text/plain; charset=utf-8", headers bare_path = store._ensure_bare_git_synced(slug) if not bare_path: return 404, b"repo_not_found", "text/plain; charset=utf-8", headers if git_action == "HEAD" and method == "GET": return 200, b"ref: refs/heads/main\n", "text/plain; charset=utf-8", headers if git_action == "info/refs" and method == "GET": from urllib.parse import parse_qs svc = (parse_qs(query).get("service") or [""])[0].strip() if svc not in ("git-upload-pack", "git-receive-pack"): return 400, b"Invalid service", "text/plain; charset=utf-8", headers sub_cmd = "upload-pack" if svc == "git-upload-pack" else "receive-pack" try: proc = subprocess.run( ["git", sub_cmd, "--stateless-rpc", "--advertise-refs", bare_path], capture_output=True, check=False, timeout=GIT_TIMEOUT_SEC, ) except subprocess.TimeoutExpired: return 504, b"git_timeout", "text/plain; charset=utf-8", headers pkt = _pkt_line(f"# service={svc}\n".encode("ascii")) + b"0000" + proc.stdout return 200, pkt, f"application/x-{svc}-advertisement", headers if git_action in ("git-upload-pack", "git-receive-pack") and method == "POST": sub_cmd = "upload-pack" if git_action == "git-upload-pack" else "receive-pack" try: proc = subprocess.run( ["git", sub_cmd, "--stateless-rpc", bare_path], input=body, capture_output=True, check=False, timeout=GIT_TIMEOUT_SEC, ) except subprocess.TimeoutExpired: return 504, b"git_timeout", "text/plain; charset=utf-8", headers if git_action == "git-receive-pack": with store._lock: store._sync_from_bare_git(slug) return 200, proc.stdout, f"application/x-{git_action}-result", headers return None
[docs]def render_node_portal_html(store: StandaloneGraspGitStore) -> bytes: repos = store.list_repos() rows = "".join( f"<tr><td><strong>{html.escape(r['title'])}</strong><br><small>{html.escape(r['description'])}</small></td>" f"<td><code>{html.escape(r['clone_url'] or '/git/' + r['repo_id'] + '.git')}</code></td>" f"<td><code>{html.escape(r['bao_root'][:24])}...</code></td>" f"<td>{len(r.get('files') or {})} files · {len(r.get('commits') or [])} commits</td></tr>" for r in repos ) where = f" (<code>{html.escape(store.public_base_url)}</code>)" if store.public_base_url else "" doc = ( '<!doctype html><html><head><meta charset="utf-8"><title>FleetMesh GRASP Git & Sovereign Node</title>' "<style>body{background:#0b0f17;color:#f1f5f9;font-family:system-ui,sans-serif;padding:32px;max-width:1080px;margin:0 auto}" "table{width:100%;border-collapse:collapse;margin-top:20px;background:#111827;border-radius:10px;overflow:hidden}" "th,td{padding:12px 14px;text-align:left;border-bottom:1px solid #1f2937}th{background:#1e293b;font-size:12px;text-transform:uppercase}" "code{background:#020617;padding:3px 6px;border-radius:5px;color:#38bdf8;font-size:12px}</style></head>" f"<body><h1>FleetMesh GRASP Git &amp; Sovereign Node{where}</h1>" f"<p>Hosting <strong>{len(repos)}</strong> Bao-verified Git repositories over Smart HTTP (<code>/git/&lt;repo&gt;.git</code>) &amp; NIP-34 <code>Kind 30617</code>.</p>" f"<table><thead><tr><th>Repository</th><th>HTTPS+Git Clone URL</th><th>1,024B Bao Root</th><th>State</th></tr></thead><tbody>{rows}</tbody></table></body></html>" ) return doc.encode("utf-8")