"""Observe one bounded CI job on a selected dedicated Docker runner.

The probe uses only Python's standard library. It binds its report to the
checked-out commit and source bytes, records non-secret execution properties,
tests loopback, and checks three deliberately restricted network paths. Runner
manager inspection remains authoritative for Docker configuration and resource
limits; this process cannot prove its own host configuration.
"""

from __future__ import annotations

import argparse
import errno
import hashlib
import ipaddress
import json
import multiprocessing
import os
from pathlib import Path
import re
import socket
import threading
from typing import NoReturn
from urllib.parse import urlsplit


SCHEMA = "gss-dedicated-runner-probe-v1"
SOURCE_PATH = "examples/dedicated-runner/probe.py"
REQUIRED_ENVIRONMENT_NAMES = (
    "CI_COMMIT_REF_NAME",
    "CI_COMMIT_SHA",
    "CI_DEFAULT_BRANCH",
    "CI_JOB_ID",
    "CI_JOB_TOKEN",
    "CI_PIPELINE_ID",
    "CI_PIPELINE_SOURCE",
    "CI_PROJECT_DIR",
    "GSS_EGRESS_PROXY",
    "GSS_EXPECTED_GID",
    "GSS_EXPECTED_UID",
    "GSS_FORBIDDEN_AUTHORITY",
    "GSS_RUNNER_TAG",
    "HTTPS_PROXY",
    "HTTP_PROXY",
    "NO_PROXY",
    "https_proxy",
    "http_proxy",
    "no_proxy",
)


def fail(message: str) -> NoReturn:
    """Raise one stable, non-secret failure for a mismatched prerequisite.

    Args:
        message: Diagnostic that contains no environment value or credential.

    Raises:
        RuntimeError: Always, causing a nonzero job without a success report.

    Side effects:
        None. Calls are deterministic and serialized by the main process.
    """
    raise RuntimeError(message)


def require_environment() -> dict[str, str]:
    """Read only required variables and validate their non-secret relationships.

    Returns:
        Mapping of required names to process-local values. Callers must never
        serialize or print the values; the report contains the fixed names only.

    Raises:
        RuntimeError: If a variable is absent, proxy variants disagree, the
        proxy URL embeds credentials or is not an IP on port 3128, the no-proxy
        list differs, the expected identity is root/invalid, or the job-token
        helper credential is empty.

    Side effects:
        Reads the process environment once. It does not mutate or enumerate
        unrelated variables and is deterministic for the same environment.
    """
    values = {name: os.environ.get(name, "") for name in REQUIRED_ENVIRONMENT_NAMES}
    if any(not value for value in values.values()):
        fail("required runner or GitLab environment is missing")
    proxy = values["GSS_EGRESS_PROXY"]
    if any(values[name] != proxy for name in ("HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy")):
        fail("forced proxy variables differ")
    parsed = urlsplit(proxy)
    if parsed.scheme != "http" or parsed.username or parsed.password or parsed.port != 3128:
        fail("forced proxy URL differs")
    try:
        ipaddress.ip_address(parsed.hostname or "")
    except ValueError:
        fail("forced proxy host is not an IP literal")
    expected_no_proxy = f"127.0.0.1,localhost,{parsed.hostname}"
    if values["NO_PROXY"] != expected_no_proxy or values["no_proxy"] != expected_no_proxy:
        fail("no-proxy scope differs")
    try:
        expected_uid = int(values["GSS_EXPECTED_UID"])
        expected_gid = int(values["GSS_EXPECTED_GID"])
    except ValueError:
        fail("expected job identity is not numeric")
    if expected_uid <= 0 or expected_gid <= 0:
        fail("expected job identity must be non-root")
    if not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,62}", values["GSS_RUNNER_TAG"]):
        fail("runner tag format differs")
    if values["GSS_FORBIDDEN_AUTHORITY"] != "forbidden.invalid:443":
        fail("forbidden CONNECT authority differs")
    return values


def read_checkout_sha(project: Path) -> str:
    """Resolve the checkout's Git HEAD using repository metadata only.

    Args:
        project: Trusted CI project directory containing the normal Runner
            helper checkout and its ``.git`` metadata.

    Returns:
        Full lowercase 40-character SHA-1 named by detached or symbolic HEAD.

    Raises:
        RuntimeError: If HEAD, a loose ref, or packed refs cannot resolve to one
        exact SHA. No Git binary or package installation is required.

    Side effects:
        Reads ``.git/HEAD`` and, for symbolic HEAD, its loose or packed ref.
        Files are never changed and concurrent repository mutation is unsupported.
    """
    git = project / ".git"
    head = (git / "HEAD").read_text(encoding="utf-8").strip()
    if re.fullmatch(r"[0-9a-f]{40}", head):
        return head
    if not head.startswith("ref: "):
        fail("checkout HEAD format differs")
    ref = head.removeprefix("ref: ")
    if ref.startswith("/") or ".." in Path(ref).parts:
        fail("checkout HEAD ref is unsafe")
    loose = git / ref
    if loose.is_file():
        sha = loose.read_text(encoding="utf-8").strip()
    else:
        sha = ""
        for line in (git / "packed-refs").read_text(encoding="utf-8").splitlines():
            if not line.startswith(("#", "^")):
                candidate, name = line.split(" ", 1)
                if name == ref:
                    sha = candidate
                    break
    if not re.fullmatch(r"[0-9a-f]{40}", sha):
        fail("checkout HEAD did not resolve to one full SHA")
    return sha


def read_process_controls() -> dict[str, object]:
    """Require the selected non-root identity and inherited process restrictions.

    Returns:
        Non-secret UID/GID, zero effective-capability value, and enabled
        no-new-privileges flag observed from PID 1.

    Raises:
        RuntimeError: If actual identity differs from runner-configured exact
        UID/GID or PID 1 does not report zero ``CapEff`` and ``NoNewPrivs: 1``.

    Side effects:
        Reads UID/GID and ``/proc/1/status`` only. Docker-manager inspection is
        still required to prove the configured container controls.
    """
    expected_uid = int(os.environ["GSS_EXPECTED_UID"])
    expected_gid = int(os.environ["GSS_EXPECTED_GID"])
    if (os.getuid(), os.getgid()) != (expected_uid, expected_gid):
        fail("actual job identity differs from the configured identity")
    fields = {}
    for line in Path("/proc/1/status").read_text(encoding="utf-8").splitlines():
        if ":" in line:
            name, value = line.split(":", 1)
            fields[name] = value.strip()
    cap_eff = fields.get("CapEff", "")
    no_new_privs = fields.get("NoNewPrivs", "")
    if not re.fullmatch(r"0+", cap_eff) or no_new_privs != "1":
        fail("process privilege observations differ")
    return {"uid": os.getuid(), "gid": os.getgid(), "cap_eff": cap_eff,
            "no_new_privs": True}


def exercise_filesystem(project: Path) -> dict[str, object]:
    """Prove a small project-workspace write and denial of a root-level create.

    Args:
        project: Runner-managed project directory; it must equal the current
            working directory and is the bounded writable path exercised here.

    Returns:
        Fixed write size and a boolean root-write denial result.

    Raises:
        RuntimeError: If project identity differs, the bounded write/hash fails,
        the cleanup fails, or the root-level write succeeds or returns an errno
        other than ``EACCES`` or ``EROFS``.

    Side effects:
        Creates, hashes, and removes one 64-KiB project file. Attempts one
        root-level file creation that must be denied. Calls are sequential.
    """
    if project.resolve() != Path.cwd().resolve():
        fail("project directory differs from the working directory")
    probe = project / ".gss-workspace-probe"
    payload = b"w" * 65536
    probe.write_bytes(payload)
    if hashlib.sha256(probe.read_bytes()).digest() != hashlib.sha256(payload).digest():
        fail("workspace write readback differs")
    probe.unlink()
    try:
        Path("/gss-runner-root-write-probe").write_text("unexpected\n", encoding="utf-8")
    except OSError as error:
        if error.errno in {errno.EACCES, errno.EROFS}:
            return {"workspace_write_bytes": len(payload), "root_write_denied": True}
        fail(f"root write probe returned errno {error.errno}")
    fail("root-level write unexpectedly succeeded")


def loopback_exchange() -> str:
    """Exchange one fixed request with an in-process loopback TCP helper.

    Returns:
        Exact response ``loopback-ok``.

    Raises:
        RuntimeError: If bind, connection, message, or two-second join differs.

    Side effects:
        Opens one ephemeral loopback listener and client. The helper thread is
        joined before return; no listener remains and no retry occurs.
    """
    ready = threading.Event()
    port: list[int] = []
    response: list[bytes] = []

    def serve() -> None:
        """Handle one fixed loopback connection, closing all sockets on return."""
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
            server.bind(("127.0.0.1", 0))
            server.listen(1)
            server.settimeout(2)
            port.append(server.getsockname()[1])
            ready.set()
            connection, _ = server.accept()
            with connection:
                if connection.recv(64) == b"runner-probe":
                    connection.sendall(b"loopback-ok")

    thread = threading.Thread(target=serve, name="loopback-helper", daemon=False)
    thread.start()
    if not ready.wait(2) or len(port) != 1:
        fail("loopback helper did not become ready")
    with socket.create_connection(("127.0.0.1", port[0]), timeout=2) as client:
        client.sendall(b"runner-probe")
        response.append(client.recv(64))
    thread.join(2)
    if thread.is_alive() or response != [b"loopback-ok"]:
        fail("loopback exchange differed")
    return response[0].decode("utf-8")


def require_direct_unreachable() -> int:
    """Require one direct off-host TCP attempt to return exact ``ENETUNREACH``.

    Returns:
        Numeric ``errno.ENETUNREACH``.

    Raises:
        RuntimeError: If the direct connection succeeds, times out, or returns
        another errno. Uncertainty is never classified as isolation.

    Side effects:
        Attempts one direct connection to documentation address
        ``198.51.100.1:9`` with a one-second timeout and no retry.
    """
    try:
        with socket.create_connection(("198.51.100.1", 9), timeout=1):
            fail("direct off-host connection unexpectedly succeeded")
    except socket.timeout:
        fail("direct off-host connection timed out")
    except OSError as error:
        if error.errno != errno.ENETUNREACH:
            fail(f"direct off-host probe returned errno {error.errno}")
        return error.errno
    fail("direct off-host probe returned no result")


def require_proxy_denial(proxy_url: str, authority: str) -> int:
    """Require the runner proxy to deny one explicit non-GitLab CONNECT authority.

    Args:
        proxy_url: Runner-forced credential-free HTTP proxy URL using an IP.
        authority: Harmless forbidden hostname and port 443. The proxy denial
            occurs before any external connection is authorized.

    Returns:
        HTTP status 403 parsed from the proxy status line.

    Raises:
        RuntimeError: If the local proxy connection, bounded response, HTTP
        format, or exact denial status differs. Response headers/body are not
        printed or placed in the report.

    Side effects:
        Connects only to the configured proxy IP and sends one CONNECT request.
        Reads through the first status-line terminator within 4096 bytes and
        performs no retry or external connection.
    """
    parsed = urlsplit(proxy_url)
    with socket.create_connection((parsed.hostname or "", parsed.port or 0), timeout=2) as client:
        request = (f"CONNECT {authority} HTTP/1.1\r\n"
                   f"Host: {authority}\r\nConnection: close\r\n\r\n").encode("ascii")
        client.sendall(request)
        response = bytearray()
        while b"\r\n" not in response and len(response) < 4096:
            chunk = client.recv(min(1024, 4096 - len(response)))
            if not chunk:
                break
            response.extend(chunk)
    status_line = response.split(b"\r\n", 1)[0]
    match = re.fullmatch(rb"HTTP/1\.[01] ([0-9]{3})(?: .*)?", status_line)
    if not match or int(match.group(1)) != 403:
        fail("forbidden proxy CONNECT did not return HTTP 403")
    return 403


def _resolve_in_child(host: str, connection: object) -> None:
    """Resolve one benign public name and return only a classified result.

    Args:
        host: Fixed benign public DNS name selected by the parent.
        connection: One-way multiprocessing pipe endpoint.

    Side effects:
        Performs one system resolver call and sends one short result tuple. The
        parent owns the deadline and terminates this process if resolution hangs.
    """
    try:
        socket.getaddrinfo(host, 443, type=socket.SOCK_STREAM)
    except socket.gaierror as error:
        connection.send(("gaierror", error.errno))
    except BaseException:
        connection.send(("other", None))
    else:
        connection.send(("resolved", None))
    finally:
        connection.close()


def require_restricted_dns() -> dict[str, object]:
    """Require loopback-only resolver configuration and failed external lookup.

    Returns:
        Sole configured nameserver and the accepted resolver error number.

    Raises:
        RuntimeError: If another resolver is configured, the public name
        resolves, resolution exceeds two seconds, the child fails, or the
        resolver returns anything except ``EAI_AGAIN`` or ``EAI_NONAME``.

    Side effects:
        Reads ``/etc/resolv.conf`` and forks one bounded child for one
        ``getaddrinfo`` call. A timed-out child is terminated and joined.
    """
    nameservers = []
    for line in Path("/etc/resolv.conf").read_text(encoding="utf-8").splitlines():
        fields = line.split()
        if fields and fields[0] == "nameserver":
            nameservers.extend(fields[1:])
    if nameservers != ["127.0.0.11"]:
        fail("resolver configuration differs")
    receive, send = multiprocessing.get_context("fork").Pipe(duplex=False)
    process = multiprocessing.get_context("fork").Process(
        target=_resolve_in_child, args=("example.com", send), daemon=False)
    process.start()
    send.close()
    if not receive.poll(2):
        process.terminate()
        process.join(1)
        fail("public DNS lookup timed out")
    outcome, error_number = receive.recv()
    receive.close()
    process.join(1)
    if process.is_alive():
        process.terminate()
        process.join(1)
        fail("public DNS lookup child did not stop")
    if process.exitcode != 0 or outcome != "gaierror" \
            or error_number not in {socket.EAI_AGAIN, socket.EAI_NONAME}:
        fail("public DNS lookup result differed")
    return {"nameservers": nameservers, "public_lookup_errno": error_number}


def write_report(output: Path, report: dict[str, object]) -> None:
    """Write and print one canonical non-secret report.

    Args:
        output: New JSON artifact path inside the project workspace.
        report: Fully validated result containing no environment values.

    Raises:
        RuntimeError: If output exists or its exact readback differs.

    Side effects:
        Creates one small JSON artifact and writes the identical single line to
        stdout. No secret or environment value is serialized. Not concurrency-safe.
    """
    if output.exists():
        fail("report output already exists")
    raw = (json.dumps(report, sort_keys=True, separators=(",", ":")) + "\n").encode("utf-8")
    if len(raw) > 8192:
        fail("report exceeds the fixed size bound")
    output.write_bytes(raw)
    if output.read_bytes() != raw:
        fail("report write readback differs")
    print(raw.decode("utf-8"), end="", flush=True)


def main() -> None:
    """Run the bounded observations and emit one success report.

    Inputs:
        Parses required GitLab/runner environment values and ``--output``.

    Outputs:
        Creates and prints one canonical JSON success record.

    Raises:
        RuntimeError, OSError, or ValueError on any mismatch. No success artifact
        is emitted before every control passes.

    Side effects:
        Reads checkout/process state, performs one bounded workspace cycle, one
        loopback exchange, one bounded DNS lookup, one direct denied connection,
        and one proxy denial. Execution uses joined loopback and DNS helpers.
    """
    parser = argparse.ArgumentParser()
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    env = require_environment()
    project = Path(env["CI_PROJECT_DIR"]).resolve(strict=True)
    checkout_sha = read_checkout_sha(project)
    if checkout_sha != env["CI_COMMIT_SHA"] or env["CI_COMMIT_REF_NAME"] != env["CI_DEFAULT_BRANCH"] \
            or env["CI_PIPELINE_SOURCE"] != "push":
        fail("checked-out revision or pipeline source differs")
    source = project / SOURCE_PATH
    if not source.is_file():
        fail("probe source is absent from the checkout")
    report: dict[str, object] = {
        "schema": SCHEMA,
        "outcome": "passed",
        "checkout": {
            "ci_commit_sha": env["CI_COMMIT_SHA"],
            "head_sha": checkout_sha,
            "ref": env["CI_COMMIT_REF_NAME"],
            "pipeline_source": env["CI_PIPELINE_SOURCE"],
            "source_path": SOURCE_PATH,
            "source_sha256": hashlib.sha256(source.read_bytes()).hexdigest(),
        },
        "gitlab": {
            "job_id": env["CI_JOB_ID"],
            "pipeline_id": env["CI_PIPELINE_ID"],
            "job_token_present": True,
        },
        "required_environment_names": list(REQUIRED_ENVIRONMENT_NAMES),
        "runner_tag": env["GSS_RUNNER_TAG"],
        "process": read_process_controls(),
        "filesystem": exercise_filesystem(project),
        "network": {
            "loopback": loopback_exchange(),
            "dns": require_restricted_dns(),
            "direct_off_host_errno": require_direct_unreachable(),
            "forbidden_connect_authority": env["GSS_FORBIDDEN_AUTHORITY"],
            "forbidden_connect_status": require_proxy_denial(
                env["GSS_EGRESS_PROXY"], env["GSS_FORBIDDEN_AUTHORITY"]),
        },
    }
    write_report(args.output, report)


if __name__ == "__main__":
    main()
