feat(publication): carry explicit immutable source repository identity

This commit is contained in:
2026-10-11 20:55:11 +03:00
parent bc5bb86245
commit 021328c9c1
12 changed files with 442 additions and 2 deletions

View File

@@ -0,0 +1,150 @@
# #region Core.SourceRepositoryIdentity [C:4] [TYPE Module] [SEMANTICS source,repository,identity,publication]
# @BRIEF Validate the single current immutable build-source identity without runtime Git or inferred aliases.
# @PRE A builder observed the exact clean source commit and one unambiguous configured origin.
# @POST Missing, malformed or ambiguous identity raises the fixed unavailable code; URLs never retain credentials.
# @RATIONALE Containers exclude .git; explicit build metadata carries observed identity into the publication boundary.
# @REJECTED Guessed origins, destination-only trust and runtime checkout fallback cannot establish source ownership.
from dataclasses import dataclass
import ipaddress
import json
import os
from pathlib import Path
import re
from urllib.parse import unquote, urlsplit
UNAVAILABLE = "SOURCE_REPOSITORY_IDENTITY_UNAVAILABLE"
FORBIDDEN = "SOURCE_REPOSITORY_FORBIDDEN"
# #region Core.SourceRepositoryIdentity.Refusal [C:1] [TYPE Class]
class SourceRepositoryRefusal(ValueError):
def __init__(self, code=UNAVAILABLE):
if code not in {UNAVAILABLE, FORBIDDEN}:
raise ValueError(UNAVAILABLE)
self.code = code
super().__init__(code)
# #endregion Core.SourceRepositoryIdentity.Refusal
# #region Core.SourceRepositoryIdentity.Repository [C:1] [TYPE Class]
@dataclass(frozen=True, slots=True)
class RepositoryIdentity:
host: str
port: int | None
repository: str
# #endregion Core.SourceRepositoryIdentity.Repository
# #region Core.SourceRepositoryIdentity.Build [C:1] [TYPE Class]
@dataclass(frozen=True, slots=True)
class SourceRepositoryIdentity:
source_commit: str
origin: RepositoryIdentity
# #endregion Core.SourceRepositoryIdentity.Build
# #region Core.SourceRepositoryIdentity.Host [C:3] [TYPE Function]
def canonical_host(value):
if not isinstance(value, str) or not value or value != value.strip():
raise SourceRepositoryRefusal()
if ":" in value:
try:
return str(ipaddress.IPv6Address(value))
except ValueError:
raise SourceRepositoryRefusal() from None
try:
host = value.encode("idna").decode("ascii").lower()
except UnicodeError:
raise SourceRepositoryRefusal() from None
if not re.fullmatch(r"[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?", host) or ".." in host:
raise SourceRepositoryRefusal()
return host
# #endregion Core.SourceRepositoryIdentity.Host
# #region Core.SourceRepositoryIdentity.Fields [C:3] [TYPE Function]
def repository_identity(host, port, repository):
host = canonical_host(host)
if port is not None and (type(port) is not int or not 1 <= port <= 65535):
raise SourceRepositoryRefusal()
if (not isinstance(repository, str)
or re.fullmatch(r"[A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.-]+)+", repository) is None
or any(part in {".", ".."} for part in repository.split("/"))):
raise SourceRepositoryRefusal()
return RepositoryIdentity(host, port, repository)
# #endregion Core.SourceRepositoryIdentity.Fields
# #region Core.SourceRepositoryIdentity.Normalize [C:4] [TYPE Function]
# @POST Canonical identity preserves explicit ports and full namespace/path, dropping only transport syntax and .git.
def normalize_repository_url(value):
if not isinstance(value, str) or not value or value != value.strip() or any(c.isspace() for c in value):
raise SourceRepositoryRefusal()
try:
if "://" in value:
parsed = urlsplit(value)
if parsed.scheme not in {"http", "https", "ssh"} or parsed.query or parsed.fragment or not parsed.hostname:
raise SourceRepositoryRefusal()
host, port, path = parsed.hostname, parsed.port, parsed.path
else:
match = re.fullmatch(r"(?:[^@/:]+@)?([^/:]+):(.+)", value)
if match is None:
raise SourceRepositoryRefusal()
host, path = match.groups()
port = None
path = unquote(path).strip("/")
if path.lower().endswith(".git"):
path = path[:-4]
return repository_identity(host, port, path)
except ValueError:
raise SourceRepositoryRefusal() from None
# #endregion Core.SourceRepositoryIdentity.Normalize
# #region Core.SourceRepositoryIdentity.UniqueJSON [C:2] [TYPE Function]
def unique_fields(pairs):
result = {}
for key, value in pairs:
if key in result:
raise SourceRepositoryRefusal()
result[key] = value
return result
# #endregion Core.SourceRepositoryIdentity.UniqueJSON
# #region Core.SourceRepositoryIdentity.Decode [C:4] [TYPE Function]
# @POST Only the current exact field set is accepted; there is no older metadata reader or missing-field inference.
def decode_source_identity(raw):
try:
value = json.loads(raw, object_pairs_hook=unique_fields)
if not isinstance(value, dict) or set(value) != {"source_commit", "origin"}:
raise SourceRepositoryRefusal()
commit, origin = value["source_commit"], value["origin"]
if not isinstance(commit, str) or re.fullmatch(r"[a-f0-9]{40}", commit) is None:
raise SourceRepositoryRefusal()
if not isinstance(origin, dict) or set(origin) != {"host", "port", "repository"}:
raise SourceRepositoryRefusal()
identity = repository_identity(origin["host"], origin["port"], origin["repository"])
if identity.host != origin["host"]:
raise SourceRepositoryRefusal()
return SourceRepositoryIdentity(commit, identity)
except (ValueError, TypeError, UnicodeError):
raise SourceRepositoryRefusal() from None
# #endregion Core.SourceRepositoryIdentity.Decode
# #region Core.SourceRepositoryIdentity.Load [C:3] [TYPE Function]
# @PRE SOURCE_REPOSITORY_IDENTITY_FILE explicitly names the deployment-owned immutable metadata file.
def load_source_identity():
configured = os.environ.get("SOURCE_REPOSITORY_IDENTITY_FILE")
if not configured:
raise SourceRepositoryRefusal()
try:
path = Path(configured)
if not path.is_file() or path.stat().st_size > 16384:
raise SourceRepositoryRefusal()
return decode_source_identity(path.read_bytes())
except OSError:
raise SourceRepositoryRefusal() from None
# #endregion Core.SourceRepositoryIdentity.Load
# #endregion Core.SourceRepositoryIdentity

View File

@@ -0,0 +1,169 @@
# #region Test.SourceRepositoryIdentity [C:4] [TYPE Module] [SEMANTICS build,source,origin,refusal]
# @BRIEF Independent URL/metadata fixtures and real clean temporary Git repositories falsify identity admission.
# @RELATION VERIFIES -> [Core.SourceRepositoryIdentity]
# @RELATION VERIFIES -> [Tooling.SourceRepositoryIdentity.Observe]
import json
from pathlib import Path
import subprocess
import sys
import pytest
from src.core.source_repository_identity import (
RepositoryIdentity, SourceRepositoryRefusal, decode_source_identity,
load_source_identity, normalize_repository_url,
)
SCRIPT = Path(__file__).resolve().parents[3] / 'scripts/write_source_repository_identity.py'
# #region Test.SourceRepositoryIdentity.URL [C:2] [TYPE Function]
@pytest.mark.parametrize('url,expected', [
('https://Source.Example/Team/Repo.git', RepositoryIdentity('source.example', None, 'Team/Repo')),
('ssh://git@Source.Example/Team/Repo.git', RepositoryIdentity('source.example', None, 'Team/Repo')),
('git@Source.Example:Team/Repo.git', RepositoryIdentity('source.example', None, 'Team/Repo')),
('https://user:private-fixture@source.example:8443/Team/Repo.git', RepositoryIdentity('source.example', 8443, 'Team/Repo')),
('ssh://git@[::1]:2222/team/repo.git', RepositoryIdentity('::1', 2222, 'team/repo')),
])
def test_repository_url_keeps_host_explicit_port_and_full_path(url, expected):
assert normalize_repository_url(url) == expected
# #endregion Test.SourceRepositoryIdentity.URL
# #region Test.SourceRepositoryIdentity.BadURL [C:2] [TYPE Function]
@pytest.mark.parametrize('url', ['', '/local/repository', 'file:///team/repo', 'https://host/team/repo?token=private-fixture',
'https://host/team/repo#fragment', 'https://host:wrong/team/repo', 'https://host/team/../repo',
'host:repo', 'https://host/team/repo name'])
def test_unknown_url_cannot_establish_identity(url):
with pytest.raises(SourceRepositoryRefusal) as failure:
normalize_repository_url(url)
assert failure.value.code == 'SOURCE_REPOSITORY_IDENTITY_UNAVAILABLE'
assert 'private-fixture' not in str(failure.value)
# #endregion Test.SourceRepositoryIdentity.BadURL
# #region Test.SourceRepositoryIdentity.Metadata [C:2] [TYPE Function]
@pytest.mark.parametrize('raw', [
'{}', '{"source_commit":"a"}',
'{"source_commit":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","origin":{"host":"host","port":null,"repository":"team/repo"},"schema_version":0}',
'{"source_commit":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","source_commit":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","origin":{"host":"host","port":null,"repository":"team/repo"}}',
'{"source_commit":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","origin":{"host":"Host","port":null,"repository":"team/repo"}}',
])
def test_metadata_has_one_current_exact_shape(raw):
with pytest.raises(SourceRepositoryRefusal) as failure:
decode_source_identity(raw)
assert failure.value.code == 'SOURCE_REPOSITORY_IDENTITY_UNAVAILABLE'
# #endregion Test.SourceRepositoryIdentity.Metadata
# #region Test.SourceRepositoryIdentity.Port [C:2] [TYPE Function]
@pytest.mark.parametrize('port', [True, 0, 65536, '443', 1.5])
def test_metadata_port_is_explicit_integer_or_null(port):
raw = json.dumps({'source_commit': 'a' * 40,
'origin': {'host': 'source.example', 'port': port, 'repository': 'team/repo'}})
with pytest.raises(SourceRepositoryRefusal) as failure:
decode_source_identity(raw)
assert failure.value.code == 'SOURCE_REPOSITORY_IDENTITY_UNAVAILABLE'
# #endregion Test.SourceRepositoryIdentity.Port
# #region Test.SourceRepositoryIdentity.ComposeBuild [C:2] [TYPE Function]
# @TEST_INVARIANT Every backend build entry forwards the explicit metadata argument; this does not claim an image was built.
@pytest.mark.parametrize('name', ['docker-compose.yml', 'docker-compose.enterprise-clean.yml', 'docker-compose.e2e.yml',
'docker-compose.full-flow.yml', 'docker-compose.investigations-e2e.yml'])
def test_compose_backend_builds_forward_only_explicit_metadata(name):
import yaml
value = yaml.safe_load((SCRIPT.parents[1] / name).read_text())
builds = [s['build'] for s in value['services'].values()
if isinstance(s.get('build'), dict) and s['build'].get('dockerfile') == 'docker/backend.Dockerfile']
assert builds
for build in builds:
assert build['args']['SOURCE_REPOSITORY_IDENTITY_JSON'] == '${SOURCE_REPOSITORY_IDENTITY_JSON:-}'
# #endregion Test.SourceRepositoryIdentity.ComposeBuild
# #region Test.SourceRepositoryIdentity.Load [C:2] [TYPE Function]
def test_runtime_requires_explicit_file_without_checkout_fallback(tmp_path, monkeypatch):
monkeypatch.delenv('SOURCE_REPOSITORY_IDENTITY_FILE', raising=False)
with pytest.raises(SourceRepositoryRefusal):
load_source_identity()
target = tmp_path / 'identity.json'
monkeypatch.setenv('SOURCE_REPOSITORY_IDENTITY_FILE', str(target))
with pytest.raises(SourceRepositoryRefusal):
load_source_identity()
target.write_text('{"source_commit":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","origin":{"host":"source.example","port":null,"repository":"team/repo"}}')
actual = load_source_identity()
assert actual.source_commit == 'a' * 40
assert actual.origin == RepositoryIdentity('source.example', None, 'team/repo')
# #endregion Test.SourceRepositoryIdentity.Load
# #region Test.SourceRepositoryIdentity.GitFixture [C:2] [TYPE Function]
def git(root, *args):
return subprocess.check_output(['git', '-C', str(root), *args], stderr=subprocess.DEVNULL, text=True).strip()
@pytest.fixture
def clean_checkout(tmp_path):
git(tmp_path, 'init', '-q')
git(tmp_path, 'config', 'user.name', 'Synthetic identity fixture')
git(tmp_path, 'config', 'user.email', 'fixture@example.invalid')
(tmp_path / 'source.py').write_text('explicit synthetic source\n')
git(tmp_path, 'add', 'source.py')
git(tmp_path, 'commit', '-qm', 'Synthetic initial source')
git(tmp_path, 'remote', 'add', 'origin', 'https://Source.Example/team/repository.git')
return tmp_path
# #endregion Test.SourceRepositoryIdentity.GitFixture
# #region Test.SourceRepositoryIdentity.Producer [C:3] [TYPE Function]
def test_clean_git_producer_observes_exact_commit_without_credentials(clean_checkout):
result = subprocess.run([sys.executable, str(SCRIPT), '--checkout', str(clean_checkout)], capture_output=True, text=True)
assert result.returncode == 0
assert json.loads(result.stdout) == {
'source_commit': git(clean_checkout, 'rev-parse', 'HEAD'),
'origin': {'host': 'source.example', 'port': None, 'repository': 'team/repository'},
}
assert not result.stderr
# #endregion Test.SourceRepositoryIdentity.Producer
# #region Test.SourceRepositoryIdentity.RefusingProducer [C:3] [TYPE Function]
@pytest.mark.parametrize('change', ['dirty', 'untracked_source', 'missing', 'multiple_fetch', 'different_push', 'multiple_push', 'rewritten_fetch'])
def test_producer_refuses_ambiguous_or_dirty_source(clean_checkout, change):
if change == 'dirty':
(clean_checkout / 'source.py').write_text('uncommitted source bytes\n')
elif change == 'untracked_source':
backend = clean_checkout / 'backend'
backend.mkdir()
(backend / 'uncaptured_module.py').write_text('untracked synthetic source\n')
elif change == 'missing':
git(clean_checkout, 'remote', 'remove', 'origin')
elif change == 'multiple_fetch':
git(clean_checkout, 'config', '--add', 'remote.origin.url', 'https://foreign.example/other/repo')
elif change == 'rewritten_fetch':
git(clean_checkout, 'config', 'url.https://foreign.example/.insteadOf', 'https://Source.Example/')
git(clean_checkout, 'config', 'remote.origin.pushurl', 'ssh://git@source.example/team/repository.git')
else:
git(clean_checkout, 'config', '--add', 'remote.origin.pushurl', 'https://foreign.example/other/repo')
if change == 'multiple_push':
git(clean_checkout, 'config', '--add', 'remote.origin.pushurl', 'https://source.example/team/repository')
result = subprocess.run([sys.executable, str(SCRIPT), '--checkout', str(clean_checkout)], capture_output=True, text=True)
assert result.returncode == 2
assert not result.stdout
assert result.stderr.strip() == 'SOURCE_REPOSITORY_IDENTITY_UNAVAILABLE'
# #endregion Test.SourceRepositoryIdentity.RefusingProducer
# #region Test.SourceRepositoryIdentity.IgnoredArtifacts [C:2] [TYPE Function]
def test_ignored_artifacts_do_not_change_source_identity(clean_checkout):
(clean_checkout / '.git/info/exclude').write_text('/artifacts/\n')
artifacts = clean_checkout / 'artifacts'
artifacts.mkdir()
(artifacts / 'synthetic-result.json').write_text('{}')
result = subprocess.run([sys.executable, str(SCRIPT), '--checkout', str(clean_checkout)], capture_output=True, text=True)
assert result.returncode == 0
assert json.loads(result.stdout)['source_commit'] == git(clean_checkout, 'rev-parse', 'HEAD')
# #endregion Test.SourceRepositoryIdentity.IgnoredArtifacts
# #endregion Test.SourceRepositoryIdentity

View File

@@ -179,11 +179,20 @@ resolve_app_version() {
# SINGLE-IMAGE BUILD FUNCTIONS
# ======================================================================
# #region Tooling.Build.SourceIdentity [C:2] [TYPE Function]
# @POST A clean exact source identity is observed anew; caller environment cannot supply stale metadata.
observe_source_identity() {
SOURCE_REPOSITORY_IDENTITY_JSON="$(python3 "$SCRIPT_DIR/scripts/write_source_repository_identity.py" --checkout "$SCRIPT_DIR")" || return 1
export SOURCE_REPOSITORY_IDENTITY_JSON
}
# #endregion Tooling.Build.SourceIdentity
build_backend() {
local tag="$1"
local image="superset-tools-backend:${tag}"
echo "[build] Building backend image ${image}..."
docker build -f docker/backend.Dockerfile -t "${image}" .
observe_source_identity
docker build --build-arg SOURCE_REPOSITORY_IDENTITY_JSON -f docker/backend.Dockerfile -t "${image}" .
echo "[build] ✅ Backend image ${image} built"
}
@@ -310,6 +319,7 @@ compose_up() {
fi
echo "[1/2] Building project images..."
observe_source_identity
"${COMPOSE_CMD[@]}" "${COMPOSE_ARGS[@]}" build
echo "[2/2] Starting Docker services..."
@@ -335,6 +345,7 @@ compose_restart() {
ensure_backend_encryption_key
echo "[build] Restarting $profile (project: $PROJECT_NAME)..."
observe_source_identity
"${COMPOSE_CMD[@]}" "${COMPOSE_ARGS[@]}" build
"${COMPOSE_CMD[@]}" "${COMPOSE_ARGS[@]}" up -d --force-recreate
echo "[build] Done."
@@ -721,7 +732,8 @@ bundle_light() {
mkdir -p "$DIST_ROOT"
echo "[bundle:light] Building all-in-one image ${image_tag}..."
docker build --build-arg "APP_VERSION=${app_version}" -f docker/all-in-one.Dockerfile -t "${image_tag}" .
observe_source_identity
docker build --build-arg SOURCE_REPOSITORY_IDENTITY_JSON --build-arg "APP_VERSION=${app_version}" -f docker/all-in-one.Dockerfile -t "${image_tag}" .
echo "[bundle:light] Exporting .tar.xz..."
docker save "${image_tag}" | xz -T0 -3 > "${DIST_ROOT}/superset-tools.${tag}.tar.xz"

View File

@@ -28,6 +28,7 @@ services:
context: .
dockerfile: docker/backend.Dockerfile
args:
SOURCE_REPOSITORY_IDENTITY_JSON: ${SOURCE_REPOSITORY_IDENTITY_JSON:-}
INSTALL_PLAYWRIGHT_BROWSERS: "0"
restart: unless-stopped
depends_on:
@@ -79,6 +80,7 @@ services:
context: .
dockerfile: docker/backend.Dockerfile
args:
SOURCE_REPOSITORY_IDENTITY_JSON: ${SOURCE_REPOSITORY_IDENTITY_JSON:-}
INSTALL_PLAYWRIGHT_BROWSERS: "0"
entrypoint: ["python", "-m", "src.scripts.seed_scenario_disposition_e2e"]
working_dir: /app/backend
@@ -98,6 +100,7 @@ services:
context: .
dockerfile: docker/backend.Dockerfile
args:
SOURCE_REPOSITORY_IDENTITY_JSON: ${SOURCE_REPOSITORY_IDENTITY_JSON:-}
INSTALL_PLAYWRIGHT_BROWSERS: "0"
entrypoint: ["python", "-m", "src.scripts.seed_reference_url_e2e"]
working_dir: /app/backend

View File

@@ -54,6 +54,8 @@ services:
build:
context: .
dockerfile: docker/backend.Dockerfile
args:
SOURCE_REPOSITORY_IDENTITY_JSON: ${SOURCE_REPOSITORY_IDENTITY_JSON:-}
restart: unless-stopped
depends_on:
db:

View File

@@ -70,6 +70,7 @@ services:
context: .
dockerfile: docker/backend.Dockerfile
args:
SOURCE_REPOSITORY_IDENTITY_JSON: ${SOURCE_REPOSITORY_IDENTITY_JSON:-}
INSTALL_PLAYWRIGHT_BROWSERS: "1"
depends_on:
db:

View File

@@ -35,6 +35,7 @@ services:
context: .
dockerfile: docker/backend.Dockerfile
args:
SOURCE_REPOSITORY_IDENTITY_JSON: ${SOURCE_REPOSITORY_IDENTITY_JSON:-}
INSTALL_PLAYWRIGHT_BROWSERS: "0"
entrypoint: ["python", "-m", "src.scripts.investigation_superset_fixture"]
command: ["--host", "0.0.0.0", "--port", "18091"]

View File

@@ -23,6 +23,8 @@ services:
build:
context: .
dockerfile: docker/backend.Dockerfile
args:
SOURCE_REPOSITORY_IDENTITY_JSON: ${SOURCE_REPOSITORY_IDENTITY_JSON:-}
restart: unless-stopped
env_file:
- ./backend/.env

View File

@@ -49,6 +49,9 @@ RUN --mount=type=cache,target=/root/.cache/pip \
# Backend source
COPY backend/ /app/backend/
ARG SOURCE_REPOSITORY_IDENTITY_JSON
ENV SOURCE_REPOSITORY_IDENTITY_FILE=/app/source-repository-identity.json
RUN cd /app/backend && python -c 'import os; from pathlib import Path; from src.core.source_repository_identity import decode_source_identity; raw = os.environ.get("SOURCE_REPOSITORY_IDENTITY_JSON"); decode_source_identity(raw) if raw else None; path = Path("/app/source-repository-identity.json"); path.write_text(raw, encoding="utf-8") if raw else None; path.chmod(0o444) if raw else None'
# Frontend build (from stage 1)
COPY --from=frontend-builder /app/frontend/build /app/frontend/build

View File

@@ -34,6 +34,11 @@ RUN if [ "$INSTALL_PLAYWRIGHT_BROWSERS" = "1" ]; then python -m playwright insta
# Исходный код
COPY backend/ /app/backend/
ARG SOURCE_REPOSITORY_IDENTITY_JSON
ENV SOURCE_REPOSITORY_IDENTITY_FILE=/app/source-repository-identity.json
# Explicit build metadata is optional for API startup; absence makes publication unavailable.
# No shell interpolation of JSON and no runtime Git/source guess.
RUN cd /app/backend && python -c 'import os; from pathlib import Path; from src.core.source_repository_identity import decode_source_identity; raw = os.environ.get("SOURCE_REPOSITORY_IDENTITY_JSON"); decode_source_identity(raw) if raw else None; path = Path("/app/source-repository-identity.json"); path.write_text(raw, encoding="utf-8") if raw else None; path.chmod(0o444) if raw else None'
# Runtime JSON schemas used by catalog publication and capture profiles.
# Package the complete contract directories so baseline admission and evaluation
# use the same canonical schemas as the source checkout.

19
run.sh
View File

@@ -472,6 +472,25 @@ start_backend() {
fi
export SERVICE_JWT="$RUN_SERVICE_JWT"
export SERVICE_JWT STORAGE_ROOT_PATH
# Observe before writing metadata; dirty/ambiguous source cannot reuse a previous file.
local source_identity_json
source_identity_json="$(python3 "$PROJECT_ROOT/scripts/write_source_repository_identity.py" --checkout "$PROJECT_ROOT")" || return 1
SOURCE_REPOSITORY_IDENTITY_FILE="$(SOURCE_REPOSITORY_IDENTITY_JSON="$source_identity_json" python3 -c '
import os
from pathlib import Path
import tempfile
from src.core.source_repository_identity import decode_source_identity
raw = os.environ["SOURCE_REPOSITORY_IDENTITY_JSON"]
decode_source_identity(raw)
root = Path.cwd().parent / "artifacts" / "runtime"
root.mkdir(parents=True, exist_ok=True, mode=0o700)
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", prefix="source-repository-", suffix=".json", dir=root, delete=False) as stream:
stream.write(raw)
path = Path(stream.name)
path.chmod(0o400)
print(path)
')" || return 1
export SOURCE_REPOSITORY_IDENTITY_FILE
# PYTHONUNBUFFERED=1 prevents stderr buffering when piped through awk.
# awk with fflush() handles child-process stderr correctly (unlike sed),
# making --reload safe in DEV_MODE.

View File

@@ -0,0 +1,73 @@
#!/usr/bin/env python3
# #region Tooling.SourceRepositoryIdentity [C:4] [TYPE Module] [SEMANTICS build,source,origin,immutable]
# @BRIEF Observe a clean exact source commit and unambiguous fetch/push origin; emit credential-free current metadata.
# @POST No inferred origin, dirty tracked source, ambiguous origin or mismatched push identity can produce metadata.
# @RATIONALE Build-time observation replaces unavailable container Git, not runtime source discovery.
# @REJECTED Reusing stale files or guessing a repository from destination configuration cannot prove source identity.
import argparse
from dataclasses import asdict
import importlib.util
import json
from pathlib import Path
import subprocess
import sys
OWNER = Path(__file__).resolve().parents[1] / "backend/src/core/source_repository_identity.py"
SPEC = importlib.util.spec_from_file_location("source_repository_identity_build", OWNER)
owner = importlib.util.module_from_spec(SPEC)
sys.modules[SPEC.name] = owner
SPEC.loader.exec_module(owner)
# #region Tooling.SourceRepositoryIdentity.Git [C:2] [TYPE Function]
def git(checkout, *args):
result = subprocess.run(["git", "-C", str(checkout), *args], capture_output=True, text=True, timeout=15)
if result.returncode:
raise owner.SourceRepositoryRefusal()
return result.stdout.strip()
# #endregion Tooling.SourceRepositoryIdentity.Git
# #region Tooling.SourceRepositoryIdentity.Observe [C:4] [TYPE Function]
def observe(checkout):
try:
root = Path(git(checkout, "rev-parse", "--show-toplevel")).resolve(strict=True)
if root != Path(checkout).resolve(strict=True):
raise owner.SourceRepositoryRefusal()
commit = git(root, "rev-parse", "--verify", "HEAD")
if git(root, "status", "--porcelain", "--untracked-files=normal"):
raise owner.SourceRepositoryRefusal()
fetch = git(root, "config", "--get-all", "remote.origin.url").splitlines()
effective_fetch = git(root, "remote", "get-url", "--all", "origin").splitlines()
push = git(root, "remote", "get-url", "--push", "--all", "origin").splitlines()
if len(fetch) != 1 or len(effective_fetch) != 1 or len(push) != 1:
raise owner.SourceRepositoryRefusal()
origin = owner.normalize_repository_url(fetch[0])
if owner.normalize_repository_url(effective_fetch[0]) != origin or owner.normalize_repository_url(push[0]) != origin:
raise owner.SourceRepositoryRefusal()
value = {"source_commit": commit, "origin": asdict(origin)}
owner.decode_source_identity(json.dumps(value))
return value
except (OSError, RuntimeError, subprocess.SubprocessError):
raise owner.SourceRepositoryRefusal() from None
# #endregion Tooling.SourceRepositoryIdentity.Observe
# #region Tooling.SourceRepositoryIdentity.Main [C:2] [TYPE Function]
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--checkout", required=True, type=Path)
args = parser.parse_args()
try:
value = observe(args.checkout)
except owner.SourceRepositoryRefusal as failure:
print(failure.code, file=sys.stderr)
return 2
print(json.dumps(value, sort_keys=True, separators=(",", ":")))
return 0
# #endregion Tooling.SourceRepositoryIdentity.Main
if __name__ == "__main__":
sys.exit(main())
# #endregion Tooling.SourceRepositoryIdentity