File size: 8,101 Bytes
adf68aa
 
 
 
 
 
 
 
 
5bac4c2
adf68aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5bac4c2
 
adf68aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c786dae
adf68aa
 
 
 
 
5bac4c2
adf68aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
"""The bot sandbox sidecar on localhost: python world/scripts/check-sidecar.py

Starts `sandbox.py serve` as a 2nd process and checks: its result equals the local path's (the seed,
the merge-check lines); `import socket` in a bot is blocked; merge_pr's shared tests (run_tests,
the seed's test_deck.py) pass there as locally, fail on a duplicate deck id (the data files went
along), and a test cannot import socket or write a file; a tree of 3,000 more files (a long run's
main) goes through for both; a bad token or an unreachable sidecar is `busy`, and a refusal logs
its HTTP status; a tar with `../`, a link, too many members or too many bytes is a 400; a timeout
works.
Local path without `unshare` (blocked on many boxes). Needs requirements.txt and legion, 3.12+.
"""
import base64
import io
import json
import logging
import os
import shutil
import socket
import subprocess
import sys
import tarfile
import tempfile
import time
import urllib.error
import urllib.request
from pathlib import Path

SRC = Path(__file__).resolve().parent.parent  # world/
sys.path.insert(0, str(SRC))
LINES = ["Hello", "My name is Sam", "", "What is my name?", "Bye"]


def post_tar(port, members):
    """POST /run with a hand-made tar: members are (TarInfo, data or None)."""
    buf = io.BytesIO()
    with tarfile.open(fileobj=buf, mode="w:gz") as t:
        for info, data in members:
            t.addfile(info, None if data is None else io.BytesIO(data))
    req = urllib.request.Request(f"http://127.0.0.1:{port}/run", json.dumps(
        {"lines": ["hi"], "tree": base64.b64encode(buf.getvalue()).decode()}).encode(),
        headers={"X-Sandbox-Token": "tok", "Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=60) as r:
            return r.status, json.load(r)
    except urllib.error.HTTPError as e:
        return e.code, json.loads(e.read())


def member(name, size=4, kind=tarfile.REGTYPE, link=""):
    info = tarfile.TarInfo(name)
    info.size, info.type, info.linkname = size, kind, link
    return info, bytes(size) if kind == tarfile.REGTYPE else None


def main():
    import sandbox
    from legion.world import ToolError

    with socket.socket() as s:
        s.bind(("127.0.0.1", 0))
        port = s.getsockname()[1]
    srv = subprocess.Popen([sys.executable, str(SRC / "sandbox.py"), "serve"], stderr=subprocess.DEVNULL,
                           env={"PYBOT_SANDBOX_TOKEN": "tok", "PORT": str(port)})
    try:
        for _ in range(300):
            try:
                socket.create_connection(("127.0.0.1", port), timeout=1).close()
                break
            except OSError:
                assert srv.poll() is None, "sandbox.py serve exited"
                time.sleep(0.1)
        tmp = Path(tempfile.mkdtemp(prefix="check-sidecar-"))
        tree = tmp / "tree"
        shutil.copytree(SRC / "seed", tree)
        local = sandbox.run(tree, LINES, isolate=False)
        os.environ.update(PYBOT_SANDBOX_URL=f"http://${{SB_HOST}}:{port}", SB_HOST="127.0.0.1",
                          PYBOT_SANDBOX_TOKEN="tok")
        remote = sandbox.run(tree, LINES)
        assert remote == local and remote["ok"], (remote, local)
        print("ok  merge-check lines via the sidecar == local:", remote["replies"][:2])

        bad = tmp / "bad"
        shutil.copytree(tree, bad)
        (bad / "bot/modules/greeting.py").write_text(
            "PRIORITY = -1000\ndef respond(text, memory):\n    try:\n        import socket\n"
            "        return 'NET'\n    except PermissionError:\n        return 'BLOCKED'\n")
        r1, r2 = sandbox.run(bad, LINES), sandbox.run(bad, LINES, isolate=False)
        assert r1 == r2 and set(r1["replies"]) == {"BLOCKED"}, (r1, r2)
        print("ok  import socket in a bot: blocked, as locally")

        r1, r2 = sandbox.run_tests(tree, "test_deck.py"), sandbox.run_tests(tree, "test_deck.py", isolate=False)
        assert r1["ok"] and r2["ok"] and "Ran 2 tests" in r1["output"], (r1, r2)
        print("ok  shared tests (test_deck.py) via the sidecar: pass, as locally")
        dup = tmp / "dup"
        shutil.copytree(tree, dup)
        deck = dup / "deck" / "single.jsonl"
        deck.write_text(deck.read_text() + deck.read_text().splitlines()[0] + "\n")
        r1, r2 = sandbox.run_tests(dup, "test_deck.py"), sandbox.run_tests(dup, "test_deck.py", isolate=False)
        assert (r1["status"], r2["status"]) == ("exit 1", "exit 1") and "FAIL:" in r1["output"], (r1, r2)
        print("ok  a duplicate deck id fails them via the sidecar too (the data files went along)")
        (dup / "tests" / "test_side_effects.py").write_text(
            "import unittest\nclass T(unittest.TestCase):\n    def test_blocked(self):\n"
            "        with self.assertRaises(PermissionError):\n            import socket\n"
            "        with self.assertRaises(PermissionError):\n            open('written', 'w')\n")
        r1 = sandbox.run_tests(dup, "test_side_effects.py")
        assert r1["ok"] and "Ran 1 test" in r1["output"], r1
        print("ok  a test's import socket and file write: blocked in the sidecar")

        big = tmp / "big"  # main after a long run: thousands of files, half of them *.py
        shutil.copytree(tree, big)
        for i in range(1500):
            (big / "tools" / "gen").mkdir(parents=True, exist_ok=True)
            (big / "tools" / "gen" / f"m{i}.py").write_text(f"X = {i}\n" * 20)
            (big / "notes").mkdir(exist_ok=True)
            (big / "notes" / f"n{i}.txt").write_text(f"note {i}\n" * 20)
        files = sum(1 for f in big.rglob("*") if f.is_file())
        r1, r2 = sandbox.run_tests(big, "test_deck.py"), sandbox.run(big, LINES)
        assert r1["ok"] and r2 == local, (r1, r2)
        print(f"ok  a tree of {files} files: shared tests and the bot run via the sidecar")

        os.environ["PYBOT_SANDBOX_TOKEN"] = "nope"
        logged = []
        handler = logging.Handler()
        handler.emit = lambda record: logged.append(record.getMessage())
        sandbox.log.addHandler(handler)
        try:
            sandbox.run(tree, LINES)
            raise AssertionError("a bad token was accepted")
        except ToolError as e:
            assert e.code == "busy", e.code
        sandbox.log.removeHandler(handler)
        assert len(logged) == 1 and "HTTP 403" in logged[0], logged
        os.environ["PYBOT_SANDBOX_TOKEN"] = "tok"
        print(f"ok  bad token -> busy, logged: {logged[0]}")

        refused = {
            "../ in a path": [member("../escape.py")],
            "a symlink": [member("bot/x.py", 0, tarfile.SYMTYPE, "/etc/passwd")],
            f"{sandbox.MAX_TREE_MEMBERS + 1} members": [member(f"m{i}.py") for i in range(sandbox.MAX_TREE_MEMBERS + 1)],
            f"{(sandbox.MAX_TREE_BYTES >> 20) + 1} MB of zeros": [member("big.py", sandbox.MAX_TREE_BYTES + (1 << 20))],
        }
        for what, members in refused.items():
            status, body = post_tar(port, members)
            assert status == 400, (what, status, body)
            print(f"ok  tar with {what} -> 400 {body['status']}")
        status, body = post_tar(port, [member(f"m{i}.py") for i in range(10)])
        assert status == 200, (status, body)  # within the caps: extracted and run (no bot: a failed run)

        slow = tmp / "slow"
        shutil.copytree(tree, slow)
        (slow / "bot/modules/greeting.py").write_text("while True: pass\n")
        t0 = time.time()
        r = sandbox.run(slow, ["hi"], timeout=2)
        assert r["status"] == "timeout" and time.time() - t0 < 10, r
        print(f"ok  timeout after {time.time() - t0:.1f} s")

        os.environ.update(SB_HOST="127.0.0.2", PYBOT_SANDBOX_URL="http://${SB_HOST}:1")
        try:
            sandbox.run(tree, LINES)
            raise AssertionError("an unreachable sidecar did not raise")
        except ToolError as e:
            assert e.code == "busy", e.code
        print("ok  unreachable sidecar -> busy")
        shutil.rmtree(tmp)
        print("PASS")
    finally:
        srv.terminate()


if __name__ == "__main__":
    main()