interplane.Get Omega
Read in your language

aienos.com

Source of www.aienos.com, served from my own hardware

Brought by drakestapleton

branch main Branches Tags History

aienos.com / scripts / allen / test_build_loop.py

213 lines · 12073 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Build-loop tests for allen-chat + omega-projects-pusher, each guard with a control.
3
4A throwaway gateway on loopback (never the production unit, never the model: no chat is
5sent) writes save/publish items into a temporary spool; the real pusher program files them
6against github_stub.py (127.0.0.1, fake token, in-memory git store). Checked: homes and
7ownership (two visitors cannot write each other's folders; anonymous claim codes), file
8rules, dedupe, the status route, two saves = two commits on u/<handle>, publish = one PR
9to main and main untouched, Drake's console list with decline, refresh, and the gallery.
10
11Usage: test_build_loop.py --omc PATH --irwasm PATH --system-prompt PATH [--pusher-dir DIR]
12"""
13
14import argparse
15import hashlib
16import hmac
17import json
18import os
19import subprocess
20import sys
21import time
22
23HERE = os.path.dirname(os.path.abspath(__file__))
24sys.path.insert(0, HERE)
25import test_gateway as T # noqa: E402
26from test_gateway import Console, Gateway, TOKEN, check, cortex_stub # noqa: E402
27
28SECRET = "b" * 40
29KEY_A, KEY_B = "a1" * 16, "b2" * 16
30README = "# Calculator\n\nAdds, subtracts, multiplies and divides. It helps anyone who needs quick sums.\n"
31
32
33def calc(handle, html="<!doctype html><p>calc</p>", **kw):
34 it = {"handle": handle, "project": "calculator", "title": "Calculator",
35 "description": "A small calculator built with Allen.",
36 "files": [{"name": "index.html", "content": html}, {"name": "README.md", "content": README}]}
37 it.update(kw)
38 return it
39
40
41def js(r):
42 raw = r.read()
43 try:
44 return json.loads(raw)
45 except ValueError:
46 return {"raw": raw[:200].decode("utf-8", "replace")}
47
48
49def main():
50 ap = argparse.ArgumentParser()
51 ap.add_argument("--omc", required=True)
52 ap.add_argument("--irwasm", required=True)
53 ap.add_argument("--system-prompt", required=True)
54 ap.add_argument("--pusher-dir", default="/tmp/allenchat/pusher")
55 a = ap.parse_args()
56 sys.path.insert(0, a.pusher_dir)
57 from github_stub import FAKE_PAT, Stub
58
59 cx = cortex_stub()
60 stub = Stub().start()
61 g = Gateway(a, "--memory-url", "http://127.0.0.1:%d" % cx.server_address[1], console=True,
62 env={"CORTEX_VISITORS_TOKEN": "t" * 40, "ALLEN_VISITOR_SECRET": SECRET,
63 "ALLEN_CONSOLE_TOKEN_SHA256": hashlib.sha256(TOKEN.encode()).hexdigest()})
64 state = os.path.join(g.dirs["console"], "pusher-state")
65 tokfile = os.path.join(g.dirs["console"], "token")
66 with open(tokfile, "w") as f:
67 f.write(FAKE_PAT)
68 A = {"X-Allen-Key": KEY_A}
69 B = {"X-Allen-Key": KEY_B}
70
71 def pusher():
72 r = subprocess.run([sys.executable, os.path.join(a.pusher_dir, "omega_projects_pusher.py"),
73 "--spool-in", g.dirs["in"], "--spool-status", g.dirs["status"], "--state-dir", state,
74 "--areas", "/nonexistent", "--spool-module-dir", HERE, "--api-base", stub.base,
75 "--token-file", tokfile, "--backoff", "0.1", "--idle-delay", "0"],
76 capture_output=True, text=True, timeout=60, env={"PATH": "/usr/bin:/bin"})
77 return r.returncode, r.stderr
78
79 try:
80 # Homes.
81 c, r = g.post("/allen/api/projects/handle", {"name": "ada"}, headers=A)
82 ha = js(r)
83 c, r = g.post("/allen/api/projects/handle", {"name": "ada"}, headers=A, ip="203.0.113.2")
84 ha2 = js(r)
85 c, r = g.post("/allen/api/projects/handle", {"name": "ada"}, headers=B, ip="203.0.113.3")
86 hb = js(r)
87 check("remembered handle is name + 8 hex, stable per key", r.status == 200 and ha["handle"] == ha2["handle"]
88 and ha["handle"].startswith("ada-") and len(ha["handle"]) == 12, "%s %s" % (ha, ha2))
89 check("same name, other key: other handle", hb["handle"] != ha["handle"], "%s %s" % (ha["handle"], hb["handle"]))
90 check("handle remembered in the visitor Cortex", ha.get("remembered") is True, "%s" % ha)
91 c, r = g.get("/allen/api/projects/me", headers=A)
92 me = js(r)
93 check("projects/me recalls the handle from Cortex", me.get("handle") == ha["handle"], "%s" % me)
94 c, r = g.get("/allen/api/projects/me", headers={"X-Allen-Key": "c3" * 16})
95 check("projects/me control: unknown key has no handle", js(r).get("handle") is None, "")
96 c, r = g.post("/allen/api/projects/handle", {"name": "bob@example.com"}, headers=A, ip="203.0.113.4")
97 check("an email is never a name", r.status == 422, "%d %s" % (r.status, js(r)))
98 c, r = g.post("/allen/api/projects/handle", {}, ip="203.0.113.5")
99 an = js(r)
100 check("anonymous: one-time handle with a claim code", r.status == 200 and an["handle"].startswith("anon-")
101 and len(an.get("claim", "")) == 24, "%s" % {k: an.get(k) for k in ("handle", "anonymous")})
102 claim = {"X-Allen-Claim": an["claim"]}
103 c, r = g.get("/allen/api/projects/me", headers=claim)
104 check("claim code gives back the anonymous handle", js(r).get("handle") == an["handle"], "")
105
106 # Ownership: two visitors cannot write each other's folders.
107 A_h, B_h, N_h = ha["handle"], hb["handle"], an["handle"]
108 cases = [("key B saves into A's home", calc(A_h), B, 403),
109 ("no key saves into A's home", calc(A_h), {}, 403),
110 ("anonymous mode with A's key saves into A's home", calc(A_h),
111 dict(A, **{"X-Allen-Anonymous": "1"}), 403),
112 ("key A saves into an anon home without its claim", calc(N_h), A, 403),
113 ("wrong claim saves into the anon home", calc(N_h), {"X-Allen-Claim": "0" * 24}, 403),
114 ("A forges a handle with A's name and another tag", calc("ada-00000000"), A, 403),
115 ("A's handle with traversal in the project", calc(A_h, project="../x"), A, 422),
116 ("A publishes a workflow file", calc(A_h, files=[{"name": "README.md", "content": README},
117 {"name": "ci.yml", "content": "on: push"}]), A, 422),
118 ("A publishes a page that loads a remote script",
119 calc(A_h, html='<script src="https://evil.example/x.js"></script>'), A, 422)]
120 for i, (name, body, hdr, want) in enumerate(cases):
121 c, r = g.post("/allen/api/projects/save", body, headers=hdr, ip="198.51.100.%d" % (10 + i))
122 j = js(r)
123 check(name + " -> refused", r.status == want, "%d %s" % (r.status, j.get("message", j)))
124 check("refusals wrote nothing to the spool", g.files("in") == [], "%s" % g.files("in"))
125
126 # Controls, then two saves = two commits.
127 c, r = g.post("/allen/api/projects/save", calc(A_h), headers=A, ip="198.51.100.40")
128 s1 = js(r)
129 check("A saves into A's home (control)", r.status == 200 and s1["branch"] == "u/" + A_h, "%s" % s1)
130 c, r = g.post("/allen/api/projects/save", calc(A_h), headers=A, ip="198.51.100.40")
131 check("the same save again is a duplicate", js(r).get("duplicate") is True, "")
132 c, r = g.post("/allen/api/projects/save", calc(N_h), headers=claim, ip="198.51.100.41")
133 s3 = js(r)
134 check("anon saves into its home with its claim (control)", r.status == 200, "%s" % s3)
135 rc, err = pusher()
136 st1 = json.loads(g.get("/allen/api/status/" + s1["id"])[1].read())
137 check("pusher files the save; status shows the commit", rc == 0 and st1["state"] == "filed"
138 and "/commit/" in (st1.get("url") or ""), "%s %s" % (st1, err[-300:]))
139 c, r = g.post("/allen/api/projects/save", calc(A_h, html="<!doctype html><p>calc 2</p>"), headers=A,
140 ip="198.51.100.40")
141 s2 = js(r)
142 pusher()
143 st2 = json.loads(g.get("/allen/api/status/" + s2["id"])[1].read())
144 head = stub.refs["refs/heads/u/" + A_h]
145 c1 = st1["url"].rsplit("/", 1)[1]
146 check("second save is a second commit on u/<handle>", st2["url"].endswith(head)
147 and stub.commits[head]["parents"] == [c1], "%s parents=%s" % (head, stub.commits[head]["parents"]))
148 files_a = stub.files_at("u/" + A_h)
149 files_n = stub.files_at("u/" + N_h)
150 check("each branch holds only its own home", all(p.startswith(("projects/%s/" % A_h, "README.md",
151 "projects/README.md")) for p in files_a) and all(p.startswith(("projects/%s/" % N_h, "README.md",
152 "projects/README.md")) for p in files_n), "%s | %s" % (sorted(files_a), sorted(files_n)))
153 meta = json.loads(files_a["projects/%s/calculator/meta.json" % A_h])
154 check("meta.json carries no personal data", set(meta) == {"v", "handle", "project", "title", "description",
155 "saved", "item", "built_with", "files"} and KEY_A not in json.dumps(meta), "%s" % sorted(meta))
156
157 # Publish: one PR to main, main untouched.
158 c, r = g.post("/allen/api/projects/publish", calc(A_h, html="<!doctype html><p>calc 2</p>"), headers=A,
159 ip="198.51.100.40")
160 p1 = js(r)
161 c, r = g.post("/allen/api/projects/publish", calc(A_h), headers=B, ip="198.51.100.42")
162 check("key B cannot publish A's project", r.status == 403, "%d" % r.status)
163 pusher()
164 stp = json.loads(g.get("/allen/api/status/" + p1["id"])[1].read())
165 check("publish opens one pull request to main", stp["state"] == "filed" and "/pull/" in stp["url"]
166 and len(stub.pulls) == 1 and stub.pulls[0]["base"] == {"ref": "main"}
167 and stub.pulls[0]["head"] == {"ref": "p/%s/calculator" % A_h}, "%s" % stp)
168 check("main untouched by save and publish", stub.refs["refs/heads/main"] == "c" * 40,
169 stub.refs["refs/heads/main"])
170
171 # Drake's console: the list, decline, refresh.
172 cons = Console(g)
173 cons.login()
174 st, _, page = cons.req("GET", "/")
175 n = stub.pulls[0]["number"]
176 check("console lists the publish request with approve and decline", st == 200 and "#%d" % n in page
177 and "Review and approve on GitHub" in page and "/projects/decline" in page, "%d" % st)
178 st, _, _ = cons.req("POST", "/projects/decline", {"pr": str(n), "reason": "x"})
179 check("decline without CSRF is refused", st == 403, "%d" % st)
180 st, _, _ = cons.post("/projects/decline", pr=str(n), reason="Please say who it helps.")
181 pusher()
182 check("decline closes the pull request with a comment", st == 303 and stub.pulls[0]["state"] == "closed"
183 and "Declined by Drake" in stub.comments[0]["body"], "%d %s" % (st, stub.pulls[0]["state"]))
184 _, _, page = cons.req("GET", "/")
185 check("declined request leaves the list", "#%d" % n not in page, "")
186
187 # Gallery: Drake merges a re-publish; refresh shows it.
188 c, r = g.post("/allen/api/projects/publish", calc(A_h, title="Calculator for everyone"), headers=A,
189 ip="198.51.100.43")
190 pusher()
191 check("re-publish after decline opens a new request", len(stub.pulls) == 2
192 and stub.pulls[1]["state"] == "open", "%d" % len(stub.pulls))
193 stub.refs["refs/heads/main"] = stub.refs["refs/heads/p/%s/calculator" % A_h] # Drake merged
194 stub.pulls[1]["state"] = "closed"
195 c, r = g.get("/allen/api/gallery")
196 check("gallery empty before refresh (control)", js(r)["gallery"] == [], "")
197 cons.post("/projects/refresh")
198 pusher()
199 c, r = g.get("/allen/api/gallery")
200 gal = js(r)["gallery"]
201 check("gallery lists the merged project", [(x["handle"], x["title"]) for x in gal]
202 == [(A_h, "Calculator for everyone")], "%s" % gal)
203 finally:
204 g.close()
205 stub.shutdown()
206 cx.shutdown()
207 bad = [n for n, ok in T.results if not ok]
208 print("\n%d/%d passed%s" % (len(T.results) - len(bad), len(T.results), (": FAILED " + ", ".join(bad)) if bad else ""))
209 return 1 if bad else 0
210
211
212if __name__ == "__main__":
213 sys.exit(main())