File size: 6,615 Bytes
22c9027
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
"""Bounded, fail-closed execution and comparison. Never imports candidate code."""
from pathlib import Path
import ast
import concurrent.futures
import hashlib
import json
import os
import subprocess
import sys
import tempfile
import time

ROOT = Path(__file__).resolve().parents[1]
JAIL = Path('/home/user/.cache/python_curation/empty_jail')
WORKER = ROOT / 'scripts/sandbox_worker.py'
ALLOWED_IMPORTS = {
    'sys', 'math', 'bisect', 'heapq', 'collections', 'functools', 'itertools',
    'operator', 're', 'string', 'statistics', 'random', 'typing', 'fractions', 'decimal'
}
BANNED_CALLS = {'eval', 'exec', 'compile', 'open', '__import__', 'breakpoint',
                'globals', 'locals', 'getattr', 'setattr', 'delattr', 'vars', 'input_file'}


def sha(text):
    return hashlib.sha256(text.encode()).hexdigest()


def static_check(code):
    tree = ast.parse(code)
    for node in ast.walk(tree):
        if isinstance(node, (ast.Import, ast.ImportFrom)):
            names = [a.name.split('.')[0] for a in node.names] if isinstance(node, ast.Import) else [(node.module or '').split('.')[0]]
            if any(n not in ALLOWED_IMPORTS for n in names):
                raise ValueError('unsupported import: ' + ','.join(names))
        if isinstance(node, ast.Name) and node.id in BANNED_CALLS:
            raise ValueError('disallowed capability: ' + node.id)
        if isinstance(node, ast.Attribute) and (node.attr.startswith('__') or node.attr in {'modules', 'environ', 'path', 'stdout', 'stderr', '__stdin__'}):
            # Normal stdout use is unnecessary in this restricted pilot; do not
            # allow code to replace or introspect the result-capture mechanism.
            raise ValueError('disallowed attribute: ' + node.attr)
    return True


def execute(payload, timeout=6):
    JAIL.mkdir(parents=True, exist_ok=True)
    JAIL.chmod(0o755)
    if any(JAIL.iterdir()):
        raise RuntimeError('Jail must remain empty')
    before = time.monotonic()
    with tempfile.TemporaryFile() as output, tempfile.TemporaryFile() as error:
        proc = subprocess.Popen(
            [sys.executable, '-I', str(WORKER), str(JAIL)],
            stdin=subprocess.PIPE, stdout=output, stderr=error,
            cwd=str(JAIL), close_fds=True, start_new_session=True,
            env={'PATH': '/usr/bin:/bin', 'LANG': 'C.UTF-8', 'PYTHONHASHSEED': '0'},
        )
        status = 'completed'
        try:
            proc.communicate(json.dumps(payload, ensure_ascii=False).encode(), timeout=timeout)
        except subprocess.TimeoutExpired:
            os.killpg(proc.pid, 9)
            proc.communicate()
            status = 'timeout'
        output.seek(0); error.seek(0)
        stdout = output.read(4 * 1024**2 + 1).decode('utf-8', 'replace')
        stderr = error.read(16000).decode('utf-8', 'replace')
    return {'status': status, 'exit_code': proc.returncode, 'stdout': stdout,
            'stderr': stderr, 'wall_seconds': round(time.monotonic() - before, 5)}


def compare(actual, expected, mode):
    if mode == 'call':
        try:
            got = json.loads(actual)
        except (ValueError, TypeError):
            return False
        # Keep boolean vs integer and string vs numeric distinctions.
        return type(got) is type(expected) and got == expected
    # TACO judge whitespace is not semantically meaningful for these integer /
    # YES-NO tasks. No approximate numeric comparison or answer rewriting.
    return actual.split() == str(expected).split()


def run_case(code, entry_point, case):
    payload = {'code': code, 'mode': case['mode']}
    if case['mode'] == 'stdin':
        payload['input'] = case['input']
    else:
        payload['entry_point'] = entry_point
        payload['args'] = case['args']
    got = execute(payload)
    passed = (got['status'] == 'completed' and got['exit_code'] == 0
              and compare(got['stdout'], case['expected'], case['mode']))
    result = {'id': case['id'], 'kind': case['kind'], 'passed': passed,
              'exit_code': got['exit_code'], 'status': got['status'],
              'wall_seconds': got['wall_seconds'], 'actual_sha256': sha(got['stdout'])}
    if not passed:
        result.update(actual_preview=got['stdout'][:600], expected_preview=str(case['expected'])[:600], stderr=got['stderr'][:1800])
    return result


def verify_suite(code, entry_point, cases, workers=4):
    static_check(code)
    with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
        results = list(pool.map(lambda c: run_case(code, entry_point, c), cases))
    return {'total': len(results), 'passed': sum(r['passed'] for r in results),
            'failed': sum(not r['passed'] for r in results), 'cases': results}


def self_test():
    probes = {
        'identity': ("import os\nprint(os.getuid(), os.getgid())", '65534 65534'),
        'host_read': ("try:\n open('/home/user/hf_dataset_access.txt').read()\nexcept FileNotFoundError:\n print('HOST_INACCESSIBLE')", 'HOST_INACCESSIBLE'),
        'network': ("import socket\ntry:\n socket.socket()\nexcept PermissionError:\n print('NETWORK_DENIED')", 'NETWORK_DENIED'),
        'fork': ("import os\ntry:\n os.fork()\nexcept (PermissionError, BlockingIOError):\n print('FORK_DENIED')", 'FORK_DENIED'),
        'write': ("try:\n open('/escape', 'w')\nexcept PermissionError:\n print('WRITE_DENIED')", 'WRITE_DENIED'),
        'environment': ("import os\nprint(len(os.environ))", '0'),
        'normal_python': ("from bisect import bisect_left\nfrom heapq import heappop\nprint(bisect_left([1,3,5], 3), heappop([2,4]))", '1 2'),
    }
    # socket and os are intentionally imported by self-test BEFORE untrusted
    # evaluation; production payloads are AST-screened and cannot import them.
    result = {}
    for name, (code, expected) in probes.items():
        got = execute({'code': code, 'mode': 'stdin'})
        result[name] = {'passed': got['exit_code'] == 0 and got['stdout'].strip() == expected,
                        'stdout': got['stdout'].strip(), 'stderr': got['stderr'][-800:]}
    timeout = execute({'code': 'while True:\n    pass', 'mode': 'stdin'}, timeout=5)
    result['loop_bounded'] = {'passed': timeout['exit_code'] != 0,
                              'exit_code': timeout['exit_code'], 'seconds': timeout['wall_seconds']}
    if not all(x['passed'] for x in result.values()):
        raise RuntimeError(json.dumps(result, indent=2))
    return result


if __name__ == '__main__':
    report = self_test()
    (ROOT / 'sandbox_self_test.json').write_text(json.dumps(report, indent=2))
    print(json.dumps(report, indent=2))