Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienos.com/blob/main/scripts/allen/relay/test_relay_mailer.py # aienos.com Source of www.aienos.com, served from my own hardware Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienos.com / scripts / allen / relay / test_relay_mailer.py` 255 lines ยท 12537 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """Offline tests for allen_relay_mailer.py against a loopback SMTP stub (never Gandi). 3 Each guard has a control. Usage: test_relay_mailer.py""" 4 5 import email 6 import email.policy 7 import json 8 import os 9 import shutil 10 import socket 11 import subprocess 12 import sys 13 import tempfile 14 import threading 15 16 HERE = os.path.dirname(os.path.abspath(__file__)) 17 # allen_spool.py sits one level up in the repo (scripts/allen/) and in ../gw in the work tree. 18 GW = next(d for d in (os.path.dirname(HERE), os.path.join(os.path.dirname(HERE), "gw")) 19 if os.path.exists(os.path.join(d, "allen_spool.py"))) 20 sys.path.insert(0, HERE) 21 sys.path.insert(0, GW) 22 import allen_relay_mailer as M # noqa: E402 23 24 results = [] 25 26 27 def check(name, ok, detail): 28 results.append((name, ok)) 29 print("%s %s: %s" % ("PASS" if ok else "FAIL", name, detail), flush=True) 30 31 32 class SMTPStub: 33 """Plain SMTP on loopback; records envelopes. reject=True answers DATA with 451.""" 34 35 def __init__(self): 36 self.s = socket.socket() 37 self.s.bind(("127.0.0.1", 0)) 38 self.s.listen(8) 39 self.port = self.s.getsockname()[1] 40 self.mail, self.reject = [], False 41 threading.Thread(target=self.serve, daemon=True).start() 42 43 def serve(self): 44 while True: 45 try: 46 c, _ = self.s.accept() 47 except OSError: 48 return 49 threading.Thread(target=self.one, args=(c,), daemon=True).start() 50 51 def one(self, c): 52 f = c.makefile("rb") 53 c.sendall(b"220 stub\r\n") 54 rcpt, frm, data = [], None, None 55 while True: 56 line = f.readline() 57 if not line: 58 return 59 cmd = line.decode().strip() 60 up = cmd.upper() 61 if data is not None: 62 if cmd == ".": 63 if self.reject: 64 c.sendall(b"451 try later\r\n") 65 else: 66 self.mail.append({"from": frm, "to": rcpt, "data": b"".join(data).decode()}) 67 c.sendall(b"250 queued\r\n") 68 data = None 69 else: 70 data.append(line) 71 continue 72 if up.startswith("EHLO") or up.startswith("HELO"): 73 c.sendall(b"250-stub\r\n250 8BITMIME\r\n") 74 elif up.startswith("MAIL FROM:"): 75 frm, rcpt = cmd[10:].strip(), [] 76 c.sendall(b"250 ok\r\n") 77 elif up.startswith("RCPT TO:"): 78 rcpt.append(cmd[8:].strip().split()[0]) 79 c.sendall(b"250 ok\r\n") 80 elif up == "DATA": 81 data = [] 82 c.sendall(b"354 go\r\n") 83 elif up == "QUIT": 84 c.sendall(b"221 bye\r\n") 85 c.close() 86 return 87 else: 88 c.sendall(b"250 ok\r\n") 89 90 91 def record(rid, **kw): 92 rec = {"v": 1, "type": "relay", "id": "r_" + rid, "received": "2026-10-26T12:00:00Z", 93 "conv": "`0123456789abcdef`" * 2, "message": "Hello Drake.\nI am building a kelp boat in Omega and want to talk.", 94 "name": "Test Visitor", "contact": "test@example.org", 95 "transcript": [{"role": "user", "content": "hi"}, {"role": "assistant", "content": "hello"}]} 96 rec.update(kw) 97 return rec 98 99 100 def put(d, rid, rec): 101 with open(os.path.join(d, rid + ".json"), "w") as f: 102 json.dump(rec, f) 103 104 105 def run_once(d, state, port, *extra): 106 p = subprocess.run([sys.executable, os.path.join(HERE, "allen_relay_mailer.py"), "--drop", d, "--state", state, 107 "--smtp-host", "127.0.0.1", "--smtp-port", str(port), "--smtp-plain", "--once"] + list(extra), 108 stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=30, 109 env=dict(os.environ, PYTHONPATH=GW)) 110 return p.returncode, p.stdout + p.stderr 111 112 113 def main(): 114 smtp = SMTPStub() 115 d = tempfile.mkdtemp(prefix="relay-test-drop") 116 sd = tempfile.mkdtemp(prefix="relay-test-state") 117 state = os.path.join(sd, "state.json") 118 try: 119 a, b = "a" * 16, "b" * 16 120 put(d, a, record(a)) 121 put(d, b, record(b, to="someone@example.org")) 122 put(d, "c" * 16, record("c" * 16, message="token ghp_" + "A1b2C3d4" * 5)) 123 put(d, "d" * 16, record("d" * 16, conv="`0123456789abcde`")) # 15 hex: neither 16 nor 32 124 rc, out = run_once(d, state, smtp.port) 125 m = smtp.mail[0] if smtp.mail else {"data": "", "to": []} 126 body = m["data"] 127 check("one valid item sends exactly one mail to drake@aienos.com", rc == 0 and len(smtp.mail) == 1 128 and m["to"] == [""] and m["from"] == "", 129 "rc %d, %d mails, rcpt %s" % (rc, len(smtp.mail), m["to"])) 130 subj = str(email.message_from_string(body, policy=email.policy.default)["Subject"]).strip() 131 check("subject is 'Aien relay: ', From display name 'Aien relay'", 132 subj == "Aien relay: Hello Drake. I am building a kelp boat in Omega and want to" 133 and "From: Aien relay " in body and "Allen" not in body and "AIEN" not in body, subj) 134 check("body carries message, name, contact, transcript, conversation and console link", 135 all(x in body for x in ("I am building a kelp boat", "Name: Test Visitor", "Contact: test@example.org", 136 "Visitor: hi", "Aien: hello", "asked Aien to pass this on", 137 "Conversation: " + "`0123456789abcdef`" * 2, 138 "http://100.64.0.2:18112/session/" + "`0123456789abcdef`" * 2, "Relay id: r_" + a)), 139 "%d bytes" % len(body)) 140 check("items with a recipient field, a secret or an invalid conversation id are rejected, not sent", 141 not os.listdir(d) and len(smtp.mail) == 1 and all("rejected %s.json" % x in out 142 for x in (b, "c" * 16, "d" * 16)), 143 out.strip()[-200:]) 144 st = json.load(open(state)) 145 check("sent id and daily count persisted", st["count"] == 1 and st["sent"] == ["r_" + a], "%s" % st) 146 147 # Already-sent id (crash between SMTP accept and delete): removed, not mailed again. 148 put(d, a, record(a)) 149 rc, out = run_once(d, state, smtp.port) 150 check("an already-sent id is never mailed twice", len(smtp.mail) == 1 and not os.listdir(d), 151 "%d mails" % len(smtp.mail)) 152 153 # Failure keeps the file; the next pass (control) sends it. 154 e = "e" * 16 155 put(d, e, record(e)) 156 smtp.reject = True 157 rc, out = run_once(d, state, smtp.port) 158 kept = os.listdir(d) 159 smtp.reject = False 160 rc2, out2 = run_once(d, state, smtp.port) 161 check("failed send keeps the drop and logs a backoff", kept == [e + ".json"] and "retry in" in out, 162 out.strip()[-120:]) 163 check("retry after a failure sends it (control)", len(smtp.mail) == 2 and not os.listdir(d), out2.strip()[-120:]) 164 165 # Daily cap persisted across runs. 166 f1, f2 = "f" * 16, "1" * 16 167 put(d, f1, record(f1)) 168 put(d, f2, record(f2)) 169 rc, out = run_once(d, state, smtp.port, "--per-day", "3") 170 check("global daily cap holds the rest", len(smtp.mail) == 3 and len(os.listdir(d)) == 1, "%d mails, %d kept" 171 % (len(smtp.mail), len(os.listdir(d)))) 172 rc, out = run_once(d, state, smtp.port, "--per-day", "3") 173 check("cap is persisted across restarts", len(smtp.mail) == 3 and len(os.listdir(d)) == 1, 174 "%d mails after restart" % len(smtp.mail)) 175 176 # Recipient is hardcoded: send() refuses anything else; control sends to Drake. 177 msg = M.compose(M.allen_spool.validate_relay_record(record("2" * 16))) 178 try: 179 M.send(msg, "someone@example.org", "", ("127.0.0.1", smtp.port, False)) 180 refused = False 181 except M.Refused: 182 refused = True 183 n = len(smtp.mail) 184 M.send(msg, M.RECIPIENT, "", ("127.0.0.1", smtp.port, False)) 185 check("send() refuses any recipient but drake@aienos.com", refused, "refused=%s" % refused) 186 check("send() to drake@aienos.com works (control)", len(smtp.mail) == n + 1, "%d mails" % len(smtp.mail)) 187 188 def conv_ok(conv): 189 try: 190 M.allen_spool.validate_relay_record(record("9" * 16, conv=conv)) 191 return True 192 except M.allen_spool.Invalid: 193 return False 194 195 check("relay record accepts a 32-hex conversation id", conv_ok("`0123456789abcdef`" * 2), "32") 196 check("relay record accepts a 16-hex conversation id from an open tab", conv_ok("`0123456789abcdef`"), "16") 197 check("relay record accepts an empty conversation id", conv_ok(""), "empty") 198 bad_convs = (("15 hex", "`0123456789abcde`"), ("17 hex", "`0123456789abcdef0`"), ("31 hex", "a" * 31), 199 ("33 hex", "a" * 33), ("64 hex", "a" * 64), ("uppercase 16", "A" * 16), 200 ("uppercase 32", "A" * 32), ("non-hex", "g" * 32), 201 ("trailing newline", "a" * 32 + "\n"), ("dotdot", "../" + "a" * 29), 202 ("fullwidth digits", "\uff10" * 32)) 203 accepted = [name for name, conv in bad_convs if conv_ok(conv)] 204 check("relay record refuses a conversation id that is not 16 or 32 hex", not accepted, "%s" % accepted) 205 # $ matches before a trailing newline. \Z / fullmatch must not. \d would 206 # accept a fullwidth digit; the received time is ASCII [0-9] only. 207 anchors = [] 208 fw_time = "\uff12" + "026-11-02T00:00:00Z" 209 for name, rx, good, bad in ( 210 ("RELAY_ID", M.allen_spool.RELAY_ID, "r_" + "a" * 16, "r_" + "a" * 16 + "\n"), 211 ("ID", M.allen_spool.ID, "a" * 20, "a" * 20 + "\n"), 212 ("RECEIVED", M.allen_spool.RECEIVED, "2026-11-02T00:00:00Z", "2026-11-02T00:00:00Z\n"), 213 ("DROP_NAME", M.DROP_NAME, "a" * 16 + ".json", "a" * 16 + ".json\n"), 214 ("CONV", M.allen_spool.CONV, "a" * 32, "a" * 32 + "\n")): 215 if not rx.fullmatch(good) or rx.fullmatch(bad) or rx.match(bad): 216 anchors.append(name) 217 if M.allen_spool.RECEIVED.fullmatch(fw_time) or M.allen_spool.CONV.fullmatch("\uff10" * 32): 218 anchors.append("unicode digit") 219 if M.DROP_NAME.fullmatch("../" + "a" * 13 + ".json"): 220 anchors.append("DROP_NAME dotdot") 221 check("id validators reject a trailing newline and a unicode digit", not anchors, "%s" % anchors) 222 legacy = "`abcdef0123456789`" 223 put(d, "3" * 16, record("3" * 16, conv=legacy)) 224 before = len(smtp.mail) 225 rc, out = run_once(d, state, smtp.port, "--per-day", "20") 226 sent = [m for m in smtp.mail[before:] if ("Conversation: " + legacy) in m["data"]] 227 check("a queued 16-hex conversation id is mailed, not rejected", 228 rc == 0 and len(sent) == 1 and not any(name.startswith("3" * 16) for name in os.listdir(d)) 229 and "rejected %s.json" % ("3" * 16) not in out, 230 "rc %d new mails %d" % (rc, len(smtp.mail) - before)) 231 try: 232 M.send(msg, M.RECIPIENT, "", ("192.0.2.1", 25, False)) 233 plain = False 234 except M.Refused: 235 plain = True 236 check("plain SMTP refused off loopback", plain, "refused=%s" % plain) 237 os.environ.pop("TELEGRAM_BOT_TOKEN", None) 238 os.environ.pop("TELEGRAM_CHAT_ID", None) 239 check("telegram hook disabled by default and without env", M.telegram_notify({}, False) == "disabled" 240 and M.telegram_notify({}, True).startswith("no TELEGRAM"), "ok") 241 p = subprocess.run([sys.executable, os.path.join(HERE, "allen_relay_mailer.py"), "--drop", d, "--state", state, 242 "--once"], stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=30, 243 env=dict(os.environ, PYTHONPATH=GW)) 244 check("refuses to start without a password on stdin", p.returncode != 0 and "no mail password" in p.stderr, 245 p.stderr.strip()) 246 finally: 247 shutil.rmtree(d, ignore_errors=True) 248 shutil.rmtree(sd, ignore_errors=True) 249 failed = [n for n, ok in results if not ok] 250 print("%d/%d passed" % (len(results) - len(failed), len(results))) 251 sys.exit(1 if failed else 0) 252 253 254 if __name__ == "__main__": 255 main()