File size: 12,053 Bytes
e172b08
 
 
 
 
 
 
 
 
 
 
 
 
 
1612302
a1aca76
e172b08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd4b30b
 
e172b08
 
 
 
 
 
 
 
 
 
 
 
 
fccc0d5
 
 
 
 
 
 
 
e1de877
fccc0d5
 
 
 
 
 
 
e172b08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d13196
1612302
 
e172b08
 
 
 
 
 
 
 
 
 
 
 
 
4ec2d9d
e172b08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1612302
 
e172b08
 
 
1537839
 
e172b08
 
a1aca76
e172b08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ec2d9d
 
e172b08
 
 
 
 
 
 
 
 
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
"""ViKernel Desktop Space server: serves the static desktop and proxies /api/ag/* server-side
to a private Agent Guard backend. Backend credentials live in Space secrets and never reach the browser."""
import json, os, time, urllib.error, urllib.request
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
import rt_challenge as RC

BACKEND = os.environ.get("BACKEND_URL", "").rstrip("/")
BACKEND2 = os.environ.get("BACKEND2_URL", "").rstrip("/")  # in-weights graft backend (GPU)
HF_AUTH = os.environ.get("BACKEND_HF_TOKEN", "")
# The in-weights backend may live in a different account, so it can carry its own read token.
HF_AUTH2 = os.environ.get("BACKEND2_HF_TOKEN", "") or HF_AUTH
BK_TOKEN = os.environ.get("BACKEND_TOKEN", "")
RATE = int(os.environ.get("RATE_PER_10MIN", "20"))
TIMEOUT = float(os.environ.get("BACKEND_TIMEOUT", "300"))
GET_OK = {"health", "status", "audit"}  # challenge build: attack surface limited to the kernel tasks
POST_OK = {"chat", "scenario", "kill", "resume", "tamper", "reset", "gate/decide", "vmask", "settings/locked", "session/start", "s3/run"}
STATIC = {"challenge.html", "warm.js", "tour.js", "index.html", "app.js", "ag.js", "store.js", "common.js", "display.js", "terminal.js", "mines.js", "browser.js", "settings.js", "live_apps.js", "game.js", "rsi.js", "gpulab.js", "ztc.js", "backdoor.js", "backdoor.css", "backdoor_metrics.json", "downloads/vdrpack.py", "demo/poisoned-page", "samples/weather-plus.vdr", "samples/weather-plus-tampered.vdr", "i18n.js", "demo_data.js", "styles.css", "ag_replay.json"}
HITS = {}
BACKEND2_SPACE = os.environ.get("BACKEND2_SPACE", "SeaWolf-AI/vk-ag-graft")
RT = {"t": 0, "v": None}


def space_stage():
    """Hub runtime stage of the in-weights backend Space (cached 10 s). Read only; it never wakes or changes the Space."""
    if time.time() - RT["t"] < 10:
        return RT["v"]
    v = None
    try:
        req = urllib.request.Request("https://huggingface.co/api/spaces/" + BACKEND2_SPACE + "/runtime",
                                     headers={"Authorization": "Bearer " + HF_AUTH2} if HF_AUTH2 else {})
        with urllib.request.urlopen(req, timeout=5) as r:
            v = json.loads(r.read()).get("stage")
    except Exception:  # noqa: BLE001
        v = None
    RT.update(t=time.time(), v=v)
    return v


def waking(stage):
    pct, label = {"SLEEPING": (1, "the in-weights model is asleep; waking it now"),
                  "BUILDING": (3, "building the server"), "APP_STARTING": (6, "starting the server"),
                  "RUNNING_APP_STARTING": (6, "starting the server"), "RUNNING": (8, "starting the server"),
                  "PAUSED": (0, "the in-weights model is stopped right now")}.get(stage or "", (2, "waking the in-weights model"))
    return {"ok": False, "live": False, "loading": {"stage": (stage or "waking").lower(), "pct": pct, "label": label, "eta_s": 240}}


def limited(ip):
    now = time.time()
    h = [x for x in HITS.get(ip, []) if now - x < 600]
    full = len(h) >= RATE
    if not full:
        h.append(now)
    HITS[ip] = h
    if len(HITS) > 5000:
        HITS.clear()
    return full


class H(SimpleHTTPRequestHandler):
    def _json(self, code, obj):
        b = json.dumps(obj).encode()
        self.send_response(code); self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(b))); self.send_header("Cache-Control", "no-store"); self.end_headers(); self.wfile.write(b)

    def _proxy(self, name, body=None, base=None, query=""):
        if base and base == BACKEND2 and name == "health":
            return self._health2(h=None)
        base = base or BACKEND
        if not base:
            return self._json(503, {"error": "backend not configured"})
        u = RC.user_from(self.headers) or "anon"
        h = {"Content-Type": "application/json", "X-Backend-Token": BK_TOKEN, "X-VK-Session": ("rt-" + u + "-" + (self.headers.get("X-VK-Session") or ""))[:60],
             "X-Forwarded-For": "rt-" + u}  # per-player rate-limit bucket on the backend (all players share this Space's IP)
        auth = HF_AUTH2 if base == BACKEND2 else HF_AUTH
        if auth:
            h["Authorization"] = "Bearer " + auth
        req = urllib.request.Request(base + "/api/" + name + query, data=body, headers=h, method="POST" if body is not None else "GET")
        try:
            with urllib.request.urlopen(req, timeout=8 if name == "health" else TIMEOUT) as r:
                data, code = r.read(), r.status
            if name in ("browser/img", "browser/res") and code == 200:
                self.send_response(200); self.send_header("Content-Type", r.headers.get("Content-Type", "application/octet-stream"))
                self.send_header("Content-Length", str(len(data))); self.send_header("Cache-Control", "max-age=600"); self.end_headers(); self.wfile.write(data)
                return
            if not data.lstrip().startswith(b"{"):
                return self._json(503, {"error": "backend starting"})
            if name == "audit" and code == 200 and u.lower() not in RC.EXCLUDE:
                # Call arguments in the shared audit chain belong to the player who made the call. Other players must not read them.
                try:
                    j = json.loads(data); out = []
                    for ln in j.get("lines") or []:
                        try:
                            o = json.loads(ln) if isinstance(ln, str) else dict(ln)
                            o["args"] = "[hidden during the hackathon]"; o["args_hidden"] = True
                            o["chain"] = o["prev"] = "[hidden]"  # a hash over the record would let anyone test guesses of the hidden arguments
                            out.append(json.dumps(o, ensure_ascii=False) if isinstance(ln, str) else o)
                        except Exception:  # noqa: BLE001
                            continue  # a record that cannot be parsed is not passed on
                    j["lines"] = out; j["redacted"] = True
                    data = json.dumps(j, ensure_ascii=False).encode()
                except Exception:  # noqa: BLE001
                    return self._json(503, {"error": "audit view unavailable"})
            self.send_response(code); self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(data))); self.send_header("Cache-Control", "no-store"); self.end_headers(); self.wfile.write(data)
        except urllib.error.HTTPError as e:
            self._json(503 if e.code >= 500 or e.code in (401, 403, 404) else e.code, {"error": "backend unavailable"})
        except Exception:  # noqa: BLE001
            self._json(503, {"error": "backend unavailable"})

    def _health2(self, h=None):
        hd = {"X-Backend-Token": BK_TOKEN}
        if HF_AUTH2:
            hd["Authorization"] = "Bearer " + HF_AUTH2
        try:
            with urllib.request.urlopen(urllib.request.Request(BACKEND2 + "/api/health", headers=hd), timeout=8) as r:
                data = r.read()
            if data.lstrip().startswith(b"{"):
                return self._json(200, json.loads(data))
        except Exception:  # noqa: BLE001
            pass
        return self._json(200, waking(space_stage()))

    def _redirect(self, loc, cookie=None):
        self.send_response(302); self.send_header("Location", loc)
        if cookie:
            self.send_header("Set-Cookie", cookie)
        self.send_header("Cache-Control", "no-store"); self.end_headers()

    def do_GET(self):
        p = self.path.split("?")[0]
        if p == "/login":
            return self._redirect(RC.login_url())
        if p == "/oauth/callback":
            name, err = RC.callback(self.path.split("?", 1)[1] if "?" in self.path else "")
            return self._redirect("/challenge.html?login=ok", RC.cookie_for(name)) if name else self._redirect("/challenge.html?login=" + err)
        if p == "/logout":
            return self._redirect("/challenge.html", "rt_user=; Path=/; Max-Age=0; Secure; SameSite=None")
        if p == "/api/rt/me":
            return self._json(200, {"user": RC.user_from(self.headers)})
        if p == "/api/rt/leaderboard":
            return self._json(200, RC.board_info())
        if p.startswith("/api/agx/"):
            return self._json(404, {"error": "not available in the challenge"})
        if p.startswith("/api/ag/") or p.startswith("/api/agx/"):
            x = p.startswith("/api/agx/")
            name = p[9:] if x else p[8:]
            q = ("?" + self.path.split("?", 1)[1]) if (name in ("browser/img", "browser/res") and "?" in self.path) else ""
            return self._proxy(name, base=BACKEND2 if x else None, query=q) if name in GET_OK else self._json(404, {"error": "not found"})
        f = "challenge.html" if p == "/" else p.lstrip("/")
        if f == "demo/poisoned-page":
            b = open("demo_poisoned_page.html", "rb").read()
            self.send_response(200); self.send_header("Content-Type", "text/html; charset=utf-8"); self.send_header("Content-Length", str(len(b))); self.end_headers(); self.wfile.write(b)
            return
        if f not in STATIC:
            return self._json(404, {"error": "not found"})
        self.path = "/" + f
        self._static = True
        return super().do_GET()

    def do_POST(self):
        p = self.path.split("?")[0]
        if p == "/api/rt/submit":
            u = RC.user_from(self.headers)
            if not u:
                return self._json(401, {"error": "sign in with Hugging Face first"})
            n = int(self.headers.get("Content-Length", 0) or 0)
            if n > 16384:
                return self._json(413, {"error": "too large"})
            try:
                req = json.loads(self.rfile.read(n) or b"{}")
            except ValueError:
                return self._json(400, {"error": "bad json"})
            code, out = RC.submit(u, req)
            return self._json(code, out)
        if (p.startswith("/api/ag/") or p.startswith("/api/agx/")) and p != "/api/ag/session/start" and not RC.user_from(self.headers):
            return self._json(401, {"error": "sign in with Hugging Face to take part"})
        x = False  # challenge build: no in-weights GPU backend
        name = p[8:] if p.startswith("/api/ag/") else ""
        if name not in POST_OK:
            return self._json(404, {"error": "not found"})
        ip = (self.headers.get("X-Forwarded-For") or self.client_address[0]).split(",")[0].strip()
        _u = RC.user_from(self.headers)
        if not (_u and _u.lower() in RC.EXCLUDE) and limited(_u or ip):  # per signed-in account; organizer replays are exempt
            return self._json(429, {"error": "rate limit"})
        n = int(self.headers.get("Content-Length", 0) or 0)
        if n > (700000 if name == "store/submit" else 16384 if name == "s3/run" else 4096):
            return self._json(413, {"error": "too large"})
        try:
            req = json.loads(self.rfile.read(n) or b"{}")
        except ValueError:
            return self._json(400, {"error": "bad json"})
        if "message" in req:
            req["message"] = str(req["message"])[:500]
        if x and not BACKEND2:
            return self._json(503, {"error": "in-weights backend not configured"})
        if x and name in ("kill", "resume"):
            x = False  # visitor KILL/RESUME is per session; the in-weights kernel is never halted globally by a visitor
        self._proxy(name, json.dumps(req).encode(), base=BACKEND2 if x else None)

    def end_headers(self):
        self.send_header("X-Content-Type-Options", "nosniff")
        if getattr(self, "_static", False):  # pages and scripts: always check for a newer copy
            self.send_header("Cache-Control", "no-cache")
        super().end_headers()

    def log_message(self, *a):
        pass


if __name__ == "__main__":
    os.chdir(os.path.dirname(os.path.abspath(__file__)))
    ThreadingHTTPServer(("0.0.0.0", int(os.environ.get("PORT", "7860"))), H).serve_forever()