# SPDX-License-Identifier: AGPL-3.0-or-later
"""Sandbox-isolation acceptance tests (step 27 subset), run before any
repository code executes.

These exercise the ``NAMESPACE_V1`` profile directly with *controller-authored*
probe programs: no repository, candidate, or validator code is involved. The
programs are trusted code executing inside the sandbox; their kernel-observed
results are the enforcement evidence.

The suite is gated: ``test_sandbox_profile_is_available`` fails (not skips) when
no profile can be provisioned, so the milestone cannot be reported complete on a
host that cannot demonstrate isolation. The remaining isolation cases skip only
after that gate has failed, keeping the failure explicit.
"""

from __future__ import annotations

import dataclasses
import hashlib
import json
import os
import signal
import shutil
import tempfile

import pytest

from orchestrator import sandbox

# Toolchains mounted read-only at their real absolute paths (ELF interpreters
# and shared-library search paths are absolute, so neutral remapping would break
# dynamic linking). None of these live under /home, so the host home directory
# stays absent from the sandbox view.
TOOLCHAIN_PATHS = (
    "/usr",
    "/lib",
    "/lib64",
    "/bin",
    "/sbin",
    "/etc/ld.so.cache",
    "/etc/ld.so.conf",
    "/etc/ld.so.conf.d",
    "/etc/alternatives",
    "/etc/ssl/certs",
    "/etc/nsswitch.conf",
    "/etc/passwd",
    "/etc/group",
)

PROBE_PYTHON = "/usr/bin/python3"


def _probe_environment() -> dict:
    return {
        "PATH": "/usr/bin:/bin",
        "HOME": "/work",
        "LANG": "C.UTF-8",
        "PYTHONDONTWRITEBYTECODE": "1",
    }


class SandboxHarness:
    """Run controller-authored probe programs under the sandbox."""

    def __init__(self):
        self.runner = sandbox.SandboxRunner()
        self._dirs = []

    def _new_dir(self, prefix: str) -> str:
        path = tempfile.mkdtemp(prefix=prefix)
        self._dirs.append(path)
        return path

    def run(self, source: str, *, limits=None, tmpfs=("/tmp",), env_extra=None):
        work = self._new_dir("sandbox-test-work-")
        new_root = self._new_dir("sandbox-test-root-")
        with open(os.path.join(work, "probe.py"), "w") as handle:
            handle.write(source)
        env = _probe_environment()
        if env_extra:
            env.update(env_extra)
        ro = [
            sandbox.MountSpec(host=path, guest=path, readonly=True)
            for path in TOOLCHAIN_PATHS
            if os.path.exists(path)
        ]
        plan = sandbox.SandboxPlan(
            new_root=new_root,
            rw_mounts=(sandbox.MountSpec(host=work, guest="/work", readonly=False),),
            ro_mounts=tuple(ro),
            tmpfs_mounts=tuple(tmpfs),
            workdir="/work",
            command=(PROBE_PYTHON, "/work/probe.py"),
            env=env,
            limits=limits or sandbox.SandboxLimits(wall_seconds=30),
        )
        return self.runner.run(plan)

    def cleanup(self):
        for path in self._dirs:
            shutil.rmtree(path, ignore_errors=True)
        self._dirs = []


@pytest.fixture(scope="module")
def capabilities():
    return sandbox.capabilities(refresh=True)


@pytest.fixture
def harness(capabilities):
    if not capabilities.profile_available:
        pytest.fail(f"NAMESPACE_V1 unavailable (fail-closed gate): {capabilities.unavailable_reason()}")
    harness = SandboxHarness()
    yield harness
    harness.cleanup()


def probe_result(observation):
    """Extract the JSON line a controller-authored probe prints."""
    for line in observation.stdout.decode(errors="replace").splitlines():
        if line.startswith("PROBE:"):
            return json.loads(line[len("PROBE:"):])
    raise AssertionError(
        f"probe produced no PROBE: line (exit={observation.exit_code}, "
        f"signal={observation.signal}, stderr={observation.stderr.decode(errors='replace')[:300]})"
    )


# -- the capability gate -------------------------------------------------------


def test_sandbox_profile_is_available(capabilities):
    if not capabilities.profile_available:
        pytest.fail(
            "NAMESPACE_V1 cannot be provisioned, so sandbox isolation cannot be "
            f"demonstrated: {capabilities.unavailable_reason()}"
        )
    assert capabilities.libseccomp
    assert capabilities.landlock_abi >= sandbox.MIN_LANDLOCK_ABI


def test_unavailable_profile_fails_closed(capabilities, tmp_path):
    """The sandbox refuses to execute rather than degrading to unsandboxed."""
    unavailable = dataclasses.replace(capabilities, user_namespaces=False, pivot_root=False)
    runner = sandbox.SandboxRunner(capabilities_override=unavailable)
    with pytest.raises(sandbox.SandboxUnavailable):
        runner.require_available()
    plan = sandbox.SandboxPlan(
        new_root=str(tmp_path / "root"),
        rw_mounts=(sandbox.MountSpec(host=str(tmp_path), guest="/work", readonly=False),),
        ro_mounts=(),
        tmpfs_mounts=(),
        workdir="/work",
        command=(PROBE_PYTHON, "-c", "print('must not run')"),
        env=_probe_environment(),
    )
    with pytest.raises(sandbox.SandboxUnavailable):
        runner.run(plan)
    # Fail-closed means nothing was set up or executed: no sandbox root and no
    # output file were produced.
    assert os.listdir(tmp_path) == []


# -- execution, filesystem, credentials, network, syscalls, limits -------------


def test_command_runs_inside_the_sandbox(harness):
    observation = harness.run(
        "import json, os\n"
        "print('PROBE:' + json.dumps({'cwd': os.getcwd(), 'uid': os.getuid()}))\n"
    )
    assert observation.exit_code == 0
    result = probe_result(observation)
    assert result["cwd"] == "/work"
    assert result["uid"] == 0  # namespaced root maps to the invoking user


def test_write_outside_owned_scope_is_denied(harness):
    observation = harness.run(
        "import json\n"
        "result = {}\n"
        "for path in ('/etc/hostname', '/tmp/../etc/hostname', '/root/escape'):\n"
        "    try:\n"
        "        open(path, 'w').write('x')\n"
        "        result[path] = 'WROTE'\n"
        "    except OSError as error:\n"
        "        result[path] = error.errno\n"
        "try:\n"
        "    open('/work/allowed.txt', 'w').write('ok')\n"
        "    result['/work/allowed.txt'] = 'WROTE'\n"
        "except OSError as error:\n"
        "    result['/work/allowed.txt'] = error.errno\n"
        "print('PROBE:' + json.dumps(result))\n"
    )
    result = probe_result(observation)
    assert result["/etc/hostname"] in (13, 30)  # EACCES or EROFS
    assert result["/tmp/../etc/hostname"] in (13, 30)
    # /root is absent from the view, so the write fails with ENOENT; either an
    # absent path or an explicit denial counts as rejected.
    assert result["/root/escape"] in (2, 13, 30)
    assert result["/work/allowed.txt"] == "WROTE"


def test_host_paths_and_credentials_are_absent(harness):
    observation = harness.run(
        "import json, os\n"
        "result = {\n"
        "  'home': os.path.exists('/home'),\n"
        "  'root': os.path.exists('/root'),\n"
        "  'docker_sock': os.path.exists('/run/docker.sock'),\n"
        "  'workspace': os.path.exists("
        "'/home/ruben/Projectos/meta-project/orchestrator'),\n"
        "  'env_keys': sorted(os.environ),\n"
        "}\n"
        "print('PROBE:' + json.dumps(result))\n"
    )
    result = probe_result(observation)
    assert result["home"] is False
    assert result["root"] is False
    assert result["docker_sock"] is False
    assert result["workspace"] is False
    # Only the explicit allow-list environment is visible; no inherited
    # credentials or CI secrets.
    assert set(result["env_keys"]) <= {"PATH", "HOME", "LANG", "PYTHONDONTWRITEBYTECODE"}


def test_toolchain_is_read_only(harness):
    observation = harness.run(
        "import json\n"
        "result = {}\n"
        "try:\n"
        "    open('/usr/bin/orchestrator-escape', 'w').write('x')\n"
        "    result['write'] = 'WROTE'\n"
        "except OSError as error:\n"
        "    result['write'] = error.errno\n"
        "print('PROBE:' + json.dumps(result))\n"
    )
    assert probe_result(observation)["write"] in (13, 30)


def test_network_egress_is_denied(harness):
    observation = harness.run(
        "import json, socket\n"
        "s = socket.socket(); s.settimeout(3)\n"
        "try:\n"
        "    s.connect(('1.1.1.1', 80))\n"
        "    outcome = 'CONNECTED'\n"
        "except OSError as error:\n"
        "    outcome = error.errno\n"
        "print('PROBE:' + json.dumps({'connect': outcome}))\n"
    )
    assert probe_result(observation)["connect"] == 101  # ENETUNREACH


def test_forbidden_syscall_is_denied_and_classified(harness):
    observation = harness.run(
        "import ctypes\n"
        "libc = ctypes.CDLL(None, use_errno=True)\n"
        "libc.ptrace(0, 0, 0, 0)\n"
        "print('PROBE: should not appear')\n"
    )
    assert observation.signal == signal.SIGSYS
    evidence = sandbox.violation_from_observation(observation)
    assert evidence is not None
    assert evidence["kind"] == sandbox.VIOLATION_FORBIDDEN_SYSCALL


def test_duration_overrun_is_killed(harness):
    observation = harness.run(
        "import time\n"
        "time.sleep(120)\n"
        "print('PROBE: should not appear')\n",
        limits=sandbox.SandboxLimits(wall_seconds=2),
    )
    assert observation.timed_out is True
    assert observation.exit_code is None
    assert observation.signal in (signal.SIGKILL, signal.SIGTERM)


def test_resource_limits_and_observations(harness):
    observation = harness.run(
        "import json\n"
        "blob = bytearray(32 * 1024 * 1024)\n"
        "print('PROBE:' + json.dumps({'allocated': len(blob)}))\n"
    )
    assert observation.max_rss_bytes is not None
    assert observation.cpu_seconds is not None
    assert observation.resource_source in ("CGROUP", "RUSAGE_CHILDREN")


def test_output_is_captured_and_fully_hashed(harness):
    payload = "x" * 2_000_000
    observation = harness.run(
        f"import sys\nsys.stdout.write('{payload}')\n"
    )
    expected = "sha256:" + hashlib.sha256(payload.encode()).hexdigest()
    assert observation.stdout_hash == expected
    assert observation.stdout_size == len(payload)
    assert observation.stdout_truncated is True
    assert len(observation.stdout) == 1_048_576


def test_controller_probe_violation_taxonomy():
    """The controller-computed violation kinds are declared here; the trusted
    detectors that produce them are wired by the command executor and the
    post-attempt write-scope check."""
    for kind in sandbox.VIOLATION_KINDS:
        evidence = sandbox.probe_violation(kind, {"probe": "unit"})
        assert evidence["kind"] == kind
        assert evidence["probe"] == "unit"
    with pytest.raises(ValueError):
        sandbox.probe_violation("NOT_A_VIOLATION", {})
