"""One local, bounded archive exercise. Never extract an external archive."""
import datetime
import io
import json
import pathlib
import platform
import tarfile
import tempfile


def probe():
    # Both possible destinations are inside our disposable directory. The second
    # member is a tiny authored traversal case, not data from an untrusted upload.
    archive = io.BytesIO()
    with tarfile.open(fileobj=archive, mode='w') as tar:
        for name in ['first.txt', '../outside.txt']:
            data = b'authored probe\n'
            info = tarfile.TarInfo(name)
            info.size = len(data)
            tar.addfile(info, io.BytesIO(data))
    archive.seek(0)
    with tempfile.TemporaryDirectory(prefix='brief-tarfile-') as temporary:
        root = pathlib.Path(temporary)
        target = root / 'destination'
        target.mkdir()
        with tarfile.open(fileobj=archive, mode='r:') as tar:
            result = {'extraction_filter_is_none': tar.extraction_filter is None,
                      'errorlevel': tar.errorlevel, 'exception': None}
            try:
                tar.extractall(target)  # Deliberately inspect this runtime's default.
            except tarfile.TarError as error:
                result['exception'] = type(error).__name__  # No private temp paths.
        result['first_file_remains'] = (target / 'first.txt').read_bytes() == b'authored probe\n'
        result['outside_file_exists'] = (root / 'outside.txt').exists()
    return {'observed_at': datetime.datetime.now(datetime.timezone.utc).isoformat(),
            'runtime': platform.python_implementation() + ' ' + platform.python_version(),
            'inputs': ['first.txt', '../outside.txt'], 'results': result,
            'scope': 'One CPython runtime and a two-member, 28-byte authored payload inside a disposable directory. No external archive, older interpreter, production restore, security audit or complete attack-resistance test. Directory removed after inspection.'}


if __name__ == '__main__':
    print(json.dumps(probe(), indent=2))
