feat(sbom): project immutable Forgejo source refs

Assistant: codex
Assistant-Model: gpt-5.6-sol
Assistant-Session: 01a023c0-a0a3-7c03-b395-5a0d2757214d
This commit is contained in:
tegwick 2026-08-22 23:34:01 +02:00
parent b068e9da42
commit e6cc18bf18
6 changed files with 543 additions and 3 deletions

View file

@ -361,6 +361,18 @@ def main(argv: list[str] | None = None) -> int:
)
p_sbom_report.add_argument("--path", default=".")
p_sbom_report.add_argument("--slug", default=None)
p_sbom_source = sbom_sub.add_parser(
"source-ref",
help="Resolve a controlled Forgejo source reference and optionally project it",
)
p_sbom_source.add_argument("--path", default=".")
p_sbom_source.add_argument("--slug", default=None)
p_sbom_source.add_argument("--remote", default="origin")
p_sbom_source.add_argument(
"--forgejo-base", default="https://forgejo.coulomb.social"
)
p_sbom_source.add_argument("--project", action="store_true")
p_sbom_source.add_argument("--confirm-authoritative", action="store_true")
p_authority = sub.add_parser("authority", help="Resolve the one authoritative record owner")
authority_sub = p_authority.add_subparsers(dest="authority_command")
@ -811,6 +823,60 @@ def main(argv: list[str] | None = None) -> int:
if not args.sbom_command:
p_sbom.print_help()
return 2
if args.sbom_command == "source-ref":
from repo_manager.sbom_client import (
SBOMNexusClient,
SBOMNexusConfig,
SBOMServiceError,
)
from repo_manager.source_ref import ForgejoSourceResolver
resolution = ForgejoSourceResolver(base_url=args.forgejo_base).resolve(
Path(args.path),
repo_slug=args.slug,
remote_name=args.remote,
)
if not args.project:
print(json.dumps(resolution, indent=2))
return 0 if resolution.get("supported") else 1
if not args.confirm_authoritative:
print(
json.dumps(
{
"ok": False,
"error": "--project requires --confirm-authoritative",
"resolution": resolution,
},
indent=2,
)
)
return 2
if not resolution.get("supported"):
print(json.dumps(resolution, indent=2))
return 1
try:
client = SBOMNexusClient(SBOMNexusConfig.from_environment())
projection = client.upsert_repository(
resolution["repo_slug"],
nexus_checkout_path=None,
source_ref=resolution["source_ref"],
)
except (ValueError, SBOMServiceError) as exc:
error = exc.to_dict() if isinstance(exc, SBOMServiceError) else {"code": "config_error"}
print(
json.dumps(
{"ok": False, "error": error, "resolution": resolution},
indent=2,
)
)
return 1
print(
json.dumps(
{"ok": True, "resolution": resolution, "projection": projection},
indent=2,
)
)
return 0
from repo_manager.sbom_client import (
licence_report_from_snapshot,
scan_repository_via_nexus,

View file

@ -129,16 +129,30 @@ class SBOMNexusClient:
*,
nexus_checkout_path: str | None,
active: bool = True,
source_ref: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Project identity/path; the path must resolve inside Nexus's controlled source plane."""
return self._request_object(
body: dict[str, Any] = {"checkout_path": nexus_checkout_path, "active": active}
if source_ref is not None:
body["source_ref"] = source_ref
result = self._request_object(
"PUT",
f"/repositories/{quote(repo_slug, safe='')}",
body={"checkout_path": nexus_checkout_path, "active": active},
body=body,
operation="repository-projection",
writes_state=True,
required_fields=frozenset({"slug", "active"}),
required_fields=frozenset(
{"slug", "active"} | ({"source_ref"} if source_ref is not None else set())
),
)
if source_ref is not None and result.get("source_ref") != source_ref:
raise SBOMServiceError(
"source_ref_projection_mismatch",
"PUT",
f"/repositories/{quote(repo_slug, safe='')}",
mutation_may_have_committed=True,
)
return result
def ingest_repository(
self,

View file

@ -0,0 +1,174 @@
"""Controlled Forgejo source references for authoritative SBOM ingestion."""
from __future__ import annotations
import re
import subprocess
from collections.abc import Callable
from pathlib import Path
from typing import Any
from urllib.parse import quote, urlparse
import httpx
from repo_manager.time import utc_now_text
DEFAULT_FORGEJO_BASE_URL = "https://forgejo.coulomb.social"
SOURCE_REF_KIND = "forgejo-archive-v1"
_SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9-]*$")
_SHA_RE = re.compile(r"^[0-9a-f]{40}$")
_SCP_REMOTE_RE = re.compile(r"^(?:[^@]+@)?(?P<host>[^:]+):(?P<path>.+)$")
_ALLOWED_REMOTE_HOSTS = frozenset({"forgejo.coulomb.social", "forgejo-remote"})
def canonical_coulomb_repository(remote_url: str, repo_slug: str) -> str | None:
"""Normalize accepted Forgejo remotes to the strict public v1 identity."""
if not _SLUG_RE.fullmatch(repo_slug):
return None
remote_url = remote_url.strip()
parsed = urlparse(remote_url)
if "://" in remote_url:
if parsed.scheme not in {"http", "https", "ssh"}:
return None
if (
parsed.username not in {None, "git"}
or parsed.password
or parsed.query
or parsed.fragment
):
return None
host = parsed.hostname
path = parsed.path
else:
match = _SCP_REMOTE_RE.fullmatch(remote_url)
if not match:
return None
host = match.group("host")
path = match.group("path")
if host not in _ALLOWED_REMOTE_HOSTS:
return None
parts = path.strip("/").removesuffix(".git").split("/")
if parts != ["coulomb", repo_slug]:
return None
return f"coulomb/{repo_slug}"
class ForgejoSourceResolver:
"""Observe a public default-branch commit without using workstation Git state."""
def __init__(
self,
*,
base_url: str = DEFAULT_FORGEJO_BASE_URL,
timeout_seconds: float = 10.0,
transport: httpx.BaseTransport | None = None,
now: Callable[[], str] = utc_now_text,
) -> None:
parsed = httpx.URL(base_url)
if parsed.scheme not in {"http", "https"} or not parsed.host:
raise ValueError("Forgejo base_url must be an absolute HTTP(S) URL")
if parsed.username or parsed.password or parsed.query or parsed.fragment:
raise ValueError("Forgejo base_url must not contain credentials, query, or fragment")
if not 0.1 <= timeout_seconds <= 60.0:
raise ValueError("Forgejo timeout_seconds must be between 0.1 and 60")
self.base_url = base_url.rstrip("/")
self.timeout_seconds = timeout_seconds
self._transport = transport
self._now = now
def resolve(
self,
repo_root: Path,
*,
repo_slug: str | None = None,
remote_name: str = "origin",
) -> dict[str, Any]:
repo_root = repo_root.expanduser().resolve()
slug = repo_slug or repo_root.name
if not _SLUG_RE.fullmatch(slug):
return self._unsupported(slug, "invalid-repo-slug")
remote = subprocess.run(
["git", "remote", "get-url", remote_name],
cwd=repo_root,
capture_output=True,
text=True,
check=False,
)
if remote.returncode != 0:
return self._unsupported(slug, "missing-canonical-remote")
repository = canonical_coulomb_repository(remote.stdout, slug)
if repository is None:
return self._unsupported(slug, "non-coulomb-or-identity-mismatch")
repo_path = f"/api/v1/repos/coulomb/{quote(slug, safe='')}"
metadata = self._get_object(repo_path)
if metadata is None:
return self._unsupported(slug, "source-unresolvable")
if metadata.get("private") is True:
return self._unsupported(slug, "private-repository")
if metadata.get("full_name") != repository:
return self._unsupported(slug, "forgejo-identity-mismatch")
branch = metadata.get("default_branch")
if not isinstance(branch, str) or not branch or branch.startswith("/"):
return self._unsupported(slug, "default-branch-unresolvable")
observed_ref = f"refs/heads/{branch}"
ref_path = f"{repo_path}/git/refs/heads/{quote(branch, safe='')}"
refs = self._get_json(ref_path)
if isinstance(refs, dict):
refs = [refs]
if not isinstance(refs, list):
return self._unsupported(slug, "default-branch-unresolvable")
matching = next(
(item for item in refs if isinstance(item, dict) and item.get("ref") == observed_ref),
None,
)
obj = matching.get("object") if matching else None
revision = obj.get("sha") if isinstance(obj, dict) else None
if not isinstance(revision, str) or not _SHA_RE.fullmatch(revision):
return self._unsupported(slug, "default-branch-unresolvable")
return {
"ok": True,
"supported": True,
"repo_slug": slug,
"source_ref": {
"kind": SOURCE_REF_KIND,
"repository": repository,
"revision": revision,
"observed_ref": observed_ref,
"observed_at": self._now(),
},
}
def _get_object(self, path: str) -> dict[str, Any] | None:
payload = self._get_json(path)
return payload if isinstance(payload, dict) else None
def _get_json(self, path: str) -> Any | None:
try:
with httpx.Client(
base_url=self.base_url,
timeout=self.timeout_seconds,
transport=self._transport,
) as client:
response = client.get(path)
except httpx.RequestError:
return None
if response.status_code != 200:
return None
try:
return response.json()
except ValueError:
return None
@staticmethod
def _unsupported(repo_slug: str, reason: str) -> dict[str, Any]:
return {
"ok": True,
"supported": False,
"repo_slug": repo_slug,
"reason": reason,
"source_ref": None,
}