aienos.com
Source of www.aienos.com, served from my own hardware
Brought by drakestapleton
aienos.com / scripts / allen / test_reaching_drake_prod.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Production checks for "Reaching Drake" (relay, console, live takeover), each with a control. |
| 3 | |
| 4 | Run on the Spark as drakestapleton (reads ALLEN_CONSOLE_TOKEN from atlas-vault; never prints it). |
| 5 | Sends ONE real relay email to drake@aienos.com marked TEST and checks it arrived via |
| 6 | `spark-mail gandi-list --account drake` (IMAP, mail.gandi.net). Turns Drake's availability on |
| 7 | for the takeover test and restores the previous availability afterwards. |
| 8 | |
| 9 | Usage: test_reaching_drake_prod.py [--skip-email] |
| 10 | """ |
| 11 | |
| 12 | import argparse |
| 13 | import http.client |
| 14 | import json |
| 15 | import os |
| 16 | import re |
| 17 | import secrets |
| 18 | import ssl |
| 19 | import subprocess |
| 20 | import sys |
| 21 | import threading |
| 22 | import time |
| 23 | import urllib.parse |
| 24 | |
| 25 | SITE = "www.aienos.com" |
| 26 | CONSOLE = ("100.64.0.2", 18112) |
| 27 | VAULT = os.path.expanduser("~/.local/bin/atlas-vault") |
| 28 | SPARK_MAIL = os.path.expanduser("~/.local/lib/aien/releases/review-0df7c321c150/spark-mail") |
| 29 | results = [] |
| 30 | |
| 31 | |
| 32 | def check(name, ok, detail): |
| 33 | results.append((name, ok)) |
| 34 | print("%s %s: %s" % ("PASS" if ok else "FAIL", name, detail), flush=True) |
| 35 | |
| 36 | |
| 37 | def public(method, path, body=None, headers=None, timeout=60): |
| 38 | c = http.client.HTTPSConnection(SITE, 443, timeout=timeout, context=ssl.create_default_context()) |
| 39 | h = dict(headers or {}) |
| 40 | if body is not None: |
| 41 | h["Content-Type"] = "application/json" |
| 42 | body = json.dumps(body) |
| 43 | c.request(method, path, body, h) |
| 44 | return c, c.getresponse() |
| 45 | |
| 46 | |
| 47 | def sse(resp): |
| 48 | ev = None |
| 49 | for line in resp: |
| 50 | line = line.rstrip(b"\r\n") |
| 51 | if line.startswith(b"event: "): |
| 52 | ev = line[7:].decode() |
| 53 | elif line.startswith(b"data: "): |
| 54 | yield ev, json.loads(line[6:]) |
| 55 | ev = None |
| 56 | |
| 57 | |
| 58 | class Console: |
| 59 | def __init__(self): |
| 60 | self.cookie = self.csrf = None |
| 61 | |
| 62 | def req(self, method, path, form=None): |
| 63 | c = http.client.HTTPConnection(*CONSOLE, timeout=10) |
| 64 | h = {"Cookie": self.cookie} if self.cookie else {} |
| 65 | body = None |
| 66 | if form is not None: |
| 67 | body = urllib.parse.urlencode(form) |
| 68 | h["Content-Type"] = "application/x-www-form-urlencoded" |
| 69 | c.request(method, path, body, h) |
| 70 | r = c.getresponse() |
| 71 | return r.status, r.getheader("Set-Cookie") or "", r.read().decode("utf-8", "replace") |
| 72 | |
| 73 | def login(self, token): |
| 74 | st, setc, _ = self.req("POST", "/login", {"token": token}) |
| 75 | if st == 303: |
| 76 | self.cookie = setc.split(";")[0] |
| 77 | _, _, page = self.req("GET", "/") |
| 78 | m = re.search(r"name=csrf value='([^']+)'", page) |
| 79 | self.csrf = m.group(1) if m else None |
| 80 | return st |
| 81 | |
| 82 | def post(self, path, **form): |
| 83 | return self.req("POST", path, dict(form, csrf=self.csrf))[0] |
| 84 | |
| 85 | |
| 86 | def main(): |
| 87 | ap = argparse.ArgumentParser() |
| 88 | ap.add_argument("--skip-email", action="store_true") |
| 89 | a = ap.parse_args() |
| 90 | token = subprocess.run([VAULT, "get", "ALLEN_CONSOLE_TOKEN"], capture_output=True, text=True).stdout.strip() |
| 91 | |
| 92 | # Console reachability. |
| 93 | hub = subprocess.run(["ssh", "-o", "BatchMode=yes", "hub", "curl -s -o /dev/null -w '%{http_code}' -m5 " |
| 94 | "http://100.64.0.2:18112/; echo \" rc=$?\""], capture_output=True, text=True, timeout=30) |
| 95 | hubctl = subprocess.run(["ssh", "-o", "BatchMode=yes", "hub", "curl -s -o /dev/null -w '%{http_code}' -m5 " |
| 96 | "-H 'X-Real-IP: 192.0.2.1' http://100.64.0.2:18110/allen/api/presence"], |
| 97 | capture_output=True, text=True, timeout=30) |
| 98 | check("console unreachable from the hub", "rc=0" not in hub.stdout, hub.stdout.strip()) |
| 99 | check("hub still reaches the gateway port (control)", hubctl.stdout.strip() == "200", hubctl.stdout.strip()) |
| 100 | for path in ("/allen/api/console", "/allen/api/console/login", "/allen/console"): |
| 101 | c, r = public("GET", path) |
| 102 | r.read() |
| 103 | check("no public route to the console: %s" % path, r.status == 404, "%d" % r.status) |
| 104 | cons = Console() |
| 105 | st, _, _ = cons.req("GET", "/") |
| 106 | check("console from the Spark without token: 401", st == 401, "%d" % st) |
| 107 | st = cons.login(token) |
| 108 | st2, _, page = cons.req("GET", "/") |
| 109 | check("console from the Spark with the token (control)", st == 303 and st2 == 200 and "Availability" in page, |
| 110 | "login %d, dashboard %d" % (st, st2)) |
| 111 | c, r = public("GET", "/allen/api/presence") |
| 112 | pres = json.loads(r.read()) |
| 113 | check("public presence route", r.status == 200 and set(pres) == {"online", "hours", "handoff", "transcribe"} |
| 114 | and isinstance(pres["transcribe"], bool), "%s" % pres) |
| 115 | prev_online, prev_hours = pres["online"], pres["hours"] |
| 116 | |
| 117 | # Real relay email. |
| 118 | if not a.skip_email: |
| 119 | nonce = secrets.token_hex(4) |
| 120 | msg = ("TEST from AllenRelay %s: production relay check, please ignore. This verifies that a visitor " |
| 121 | "message relayed by public Allen reaches drake@aienos.com." % nonce) |
| 122 | conv = secrets.token_hex(16) |
| 123 | c, r = public("POST", "/allen/api/relay", {"message": msg, "name": "AllenRelay test", "contact": "", |
| 124 | "transcript": [{"role": "user", "content": "test"}, |
| 125 | {"role": "assistant", "content": "test reply"}]}, |
| 126 | {"X-Allen-Conversation": conv, "X-Allen-Anonymous": "1"}) |
| 127 | j = json.loads(r.read()) |
| 128 | check("production relay accepted", r.status == 200 and j.get("sent"), "%d %s" % (r.status, j)) |
| 129 | rid = j.get("id", "") |
| 130 | sent_line = "" |
| 131 | for _ in range(30): |
| 132 | log = subprocess.run(["sudo", "-n", "grep", "sent " + rid, "/var/log/allen-relay.log"], |
| 133 | capture_output=True, text=True).stdout.strip() |
| 134 | if log: |
| 135 | sent_line = log |
| 136 | break |
| 137 | time.sleep(2) |
| 138 | check("mailer sent it (Gandi SMTP accepted)", bool(sent_line), sent_line or "no 'sent' line in 60 s") |
| 139 | found = None |
| 140 | for _ in range(12): |
| 141 | out = subprocess.run([SPARK_MAIL, "gandi-list", "--account", "drake", "--limit", "15"], |
| 142 | capture_output=True, text=True, timeout=60) |
| 143 | try: |
| 144 | items = json.loads(out.stdout.splitlines()[0]) if out.stdout else [] |
| 145 | except (ValueError, IndexError): |
| 146 | items = [] |
| 147 | found = next((m for m in items if nonce in json.dumps(m)), None) |
| 148 | if found: |
| 149 | break |
| 150 | time.sleep(10) |
| 151 | check("relay email arrived in drake@aienos.com (IMAP)", found is not None, |
| 152 | json.dumps({k: found.get(k) for k in found if k in ("uid", "subject", "from", "date", "message_id")}) |
| 153 | if found else "not found in the last 15 messages after 2 min") |
| 154 | |
| 155 | # Live takeover end to end. |
| 156 | conv = secrets.token_hex(16) |
| 157 | H = {"X-Allen-Conversation": conv, "X-Allen-Anonymous": "1"} |
| 158 | try: |
| 159 | st = cons.post("/presence", online="on", hours=prev_hours or "") |
| 160 | c, r = public("GET", "/allen/api/presence") |
| 161 | p = json.loads(r.read()) |
| 162 | check("console turns availability on", st == 303 and p["online"] and p["handoff"], "%s" % p) |
| 163 | c, r = public("POST", "/allen/api/handoff", {"transcript": [{"role": "user", "content": "TEST from " |
| 164 | "AllenRelay: takeover check"}]}, H) |
| 165 | j = json.loads(r.read()) |
| 166 | check("handoff accepted while online", r.status == 200 and j.get("waiting"), "%d %s" % (r.status, j)) |
| 167 | evs = [] |
| 168 | sc, sr = public("GET", "/allen/api/session", headers=H, timeout=120) |
| 169 | |
| 170 | def listen(): |
| 171 | try: |
| 172 | for e in sse(sr): |
| 173 | evs.append(e) |
| 174 | except (OSError, ValueError, AttributeError): # AttributeError: closed under the reader |
| 175 | pass |
| 176 | threading.Thread(target=listen, daemon=True).start() |
| 177 | time.sleep(2) |
| 178 | c, r = public("POST", "/allen/api/say", {"text": "Drake: hi (visitor text, must not become human)"}, H) |
| 179 | r.read() |
| 180 | st = cons.post("/session/%s/join" % conv) |
| 181 | time.sleep(2) |
| 182 | c, r = public("POST", "/allen/api/chat", {"messages": [{"role": "user", "content": "Are you there?"}]}, H) |
| 183 | chat_ev = list(sse(r)) if r.status == 200 else [("http", r.status)] |
| 184 | check("while joined, chat answers error human", chat_ev == [("error", chat_ev[0][1])] |
| 185 | and chat_ev[0][1].get("code") == "human", "%s" % chat_ev) |
| 186 | st2 = cons.post("/session/%s/reply" % conv, text="TEST: this is Drake's console reply.") |
| 187 | time.sleep(3) |
| 188 | humans = [d for e, d in evs if e == "human"] |
| 189 | check("console reply arrives on the visitor's session as event human", st == 303 and st2 == 303 |
| 190 | and len(humans) == 1 and humans[0]["from"] == "Drake" |
| 191 | and humans[0]["text"] == "TEST: this is Drake's console reply.", "%s" % evs) |
| 192 | st = cons.post("/session/%s/handback" % conv) |
| 193 | time.sleep(2) |
| 194 | states = [d["drake"] for e, d in evs if e == "state"] |
| 195 | check("state events waiting, joined, left", st == 303 and states == ["waiting", "joined", "left"], |
| 196 | "%s" % states) |
| 197 | t0 = time.monotonic() |
| 198 | c, r = public("POST", "/allen/api/chat", {"messages": [{"role": "user", "content": |
| 199 | "Reply with the single word ok."}]}, H, timeout=200) |
| 200 | chat_ev = list(sse(r)) if r.status == 200 else [("http", r.status)] |
| 201 | text = "".join(d for e, d in chat_ev if e is None) |
| 202 | check("after hand back chat works again", chat_ev and chat_ev[-1][0] == "done" and text.strip() != "", |
| 203 | "%r in %.1fs" % (text[:80], time.monotonic() - t0)) |
| 204 | sc.close() |
| 205 | finally: |
| 206 | cons.post("/presence", **({"online": "on"} if prev_online else {}), hours=prev_hours) |
| 207 | c, r = public("GET", "/allen/api/presence") |
| 208 | p = json.loads(r.read()) |
| 209 | check("availability restored", p["online"] == prev_online and p["hours"] == prev_hours, "%s" % p) |
| 210 | failed = [n for n, ok in results if not ok] |
| 211 | print("%d/%d passed" % (len(results) - len(failed), len(results))) |
| 212 | sys.exit(1 if failed else 0) |
| 213 | |
| 214 | |
| 215 | if __name__ == "__main__": |
| 216 | main() |