"""Fail-closed Python I/O boundaries, installed before application imports.

Test infrastructure, not a sandbox for untrusted native code. Violations are
BaseExceptions and also recorded so a broad application handler cannot hide them.
"""
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
from urllib.parse import unquote


class TestSafetyViolation(BaseException):
    __test__ = False


VIOLATIONS = []
_installed = False


def _path(value):
    if isinstance(value, int) or value is None:
        return None
    path = os.path.realpath(os.fsdecode(value))
    if path.startswith("\\\\?\\UNC\\"):
        path = "\\\\" + path[8:]
    elif path.startswith("\\\\?\\"):
        path = path[4:]
    return os.path.normcase(path)


def _under(path, root):
    return path == root or path.startswith(root + os.sep)


def install(repo, protected):
    global _installed
    if _installed:
        return
    _installed = True
    temp = _path(tempfile.gettempdir())
    repo = _path(repo)
    protected = tuple(_path(p) for p in protected)
    support = str(Path(__file__).parent)
    null = _path(os.devnull)
    sys.dont_write_bytecode = True
    os.environ['PYTHONDONTWRITEBYTECODE'] = '1'

    def deny(event):
        VIOLATIONS.append(event)
        raise TestSafetyViolation('P1.1 test safety boundary: ' + event)

    def check(value, *, write=False):
        path = _path(value)
        if path is None or path == null:
            return
        if any(_under(path, root) for root in protected):
            deny('real runtime data access')
        if path == os.path.join(repo, '.env') or (
            os.path.dirname(path) == repo and os.path.basename(path).startswith('.env.')
            and os.path.basename(path) != '.env.example'
        ):
            deny('real dotenv access')
        # Never grant checkout writes just because a checkout is inside TEMP.
        if write and (_under(path, repo) or not _under(path, temp)):
            deny('write outside disposable test storage')

    def at(value, fd=-1):
        if isinstance(value, int):
            fd, value = value, ''
        if fd not in (None, -1) and not os.path.isabs(os.fsdecode(value)):
            # shutil.rmtree uses dir_fd on POSIX. Resolve it, never guess CWD.
            for base in ('/proc/self/fd', '/dev/fd'):
                try:
                    return os.path.join(os.readlink(base + '/' + str(fd)), os.fsdecode(value))
                except OSError:
                    continue
            deny('unresolvable descriptor mutation')
        return value

    def audit(event, args):
        if event in {'socket.connect', 'socket.getaddrinfo', 'socket.gethostbyname',
                     'socket.gethostbyaddr', 'socket.getnameinfo', 'socket.sendto',
                     'socket.sendmsg'}:
            deny('network: ' + event)
        if event == 'open':
            mode, flags = args[1:3]
            write = (isinstance(mode, str) and any(c in mode for c in 'wax+'))
            write = write or (isinstance(flags, int) and flags &
                              (os.O_WRONLY | os.O_RDWR | os.O_CREAT | os.O_TRUNC | os.O_APPEND))
            check(args[0], write=bool(write))
        elif event == 'sqlite3.connect':
            value = os.fsdecode(args[0])
            if value == ':memory:':
                return
            if value.startswith('file:'):
                value = unquote(value[5:].split('?', 1)[0])
                if os.name == 'nt' and len(value.lstrip('/')) > 1 and value.lstrip('/')[1] == ':':
                    value = value.lstrip('/')
            check(value, write=True)
        elif event in {'os.remove', 'os.rmdir', 'os.mkdir', 'os.chmod', 'os.utime', 'os.truncate'}:
            fd = -1 if event == 'os.truncate' else args[-1]
            check(at(args[0], fd), write=True)
        elif event in {'os.rename', 'os.link', 'os.symlink'}:
            if event != 'os.symlink':
                check(at(args[0], args[2]), write=True)
            check(at(args[1], args[-1]), write=True)
        elif event in {'os.system', 'os.exec', 'os.posix_spawn'}:
            deny('uncontrolled process launch: ' + event)

    sys.addaudithook(audit)
    original = subprocess.Popen.__init__

    def start(self, *args, **kwargs):
        command = args[0] if args else kwargs.get('args')
        # platform.win32_ver() uses this exact read-only cmd builtin on Windows.
        platform_ver = os.name == 'nt' and command == 'ver' and kwargs.get('shell') is True
        if not platform_ver and (kwargs.get('shell') or not isinstance(command, (list, tuple)) or not command):
            deny('uncontrolled subprocess command')
        executable = '' if platform_ver else Path(os.fsdecode(command[0])).name.lower()
        python = executable == Path(sys.executable).name.lower()
        node = executable in {'node', 'node.exe'}
        junction = (executable in {'cmd', 'cmd.exe'} and len(command) == 6 and
                    [str(x).lower() for x in command[1:4]] == ['/c', 'mklink', '/j'])
        if junction:
            check(command[4], write=True)
            check(command[5], write=True)
        if not (python or node or junction or platform_ver):
            deny('unapproved subprocess executable')
        if kwargs.get('executable'):
            deny('subprocess executable override')
        env = dict(os.environ if kwargs.get('env') is None else kwargs['env'])
        env['INVESTMENT_TEST_SAFETY'] = json.dumps([repo, list(protected)])
        if python:
            if any(str(a) in {'-I', '-E', '-S'} for a in command[1:]):
                deny('Python subprocess disabling safety bootstrap')
            env['PYTHONPATH'] = os.pathsep.join(filter(None, (support, env.get('PYTHONPATH'))))
            env['PYTHONDONTWRITEBYTECODE'] = '1'
        if node:
            preload = str(Path(support) / 'node_safety.cjs')
            env['NODE_OPTIONS'] = (env.get('NODE_OPTIONS', '') + ' --require ' + json.dumps(preload)).strip()
        kwargs['env'] = env
        return original(self, *args, **kwargs)

    subprocess.Popen.__init__ = start
