scorpiox-bot-plugin-github
←cgi.pypython
240 lines · 10 KBHEADBlameDownload
1#!/usr/bin/env python3
2"""tests/cgi.py - the control JSON API of plugin_github, driven as real CGI.
3
4The binary is spawned per request with QUERY_STRING / REQUEST_METHOD /
5CONTENT_LENGTH + stdin, exactly the way scorpiox-server invokes it, so the
6CGI contract itself is what is tested:
7
8 * every ?action= without the node password is 401 (never "works anyway")
9 * status / save / test / tools / clear answer valid JSON with the right
10 fields, and NONE of them ever contains the saved token text
11 * save writes config.json at mode 0600 under SX_CONNECTOR_DIR
12 * save validates the api base (rejects a userinfo URL, accepts the mock's
13 loopback http base)
14 * test relays GitHub's own "Bad credentials" for a wrong token, and the
15 account login for a good one
16 * clear deletes the token and keeps the api base
17 * the HTML page: 200, no <script src=, CSP-free but theme-bearing, honours
18 embed, and lists the five tools after ?action=tools
19
20Run from tests/run.sh with BIN/PORT/CFGDIR in the environment.
21"""
22
23import json
24import os
25import stat
26import subprocess
27import sys
28
29ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
30BIN = os.environ.get("BIN", os.path.join(ROOT, "plugin_github"))
31PORT = os.environ["PORT"]
32CFGDIR = os.environ.get("CFGDIR", "/tmp/gh-cgi-test")
33TOKEN = "GHPAT-MOCK-TOKEN-1"
34BASE = "http://127.0.0.1:%s" % PORT
35
36PASS = 0
37FAILS = []
38
39
40def ok(desc, detail=""):
41 global PASS
42 PASS += 1
43 print(" ok %s" % desc)
44
45
46def bad(desc, detail=""):
47 FAILS.append(desc)
48 print(" FAIL %s%s" % (desc, (" (" + str(detail)[:240] + ")") if detail else ""))
49
50
51def check(cond, desc, detail=""):
52 (ok if cond else bad)(desc, detail)
53
54
55def cgi(query="", body="", method="GET", bot_password=None, pwd=None,
56 env_extra=None, node_password=None):
57 """Spawn the plugin as a CGI. The node password is supplied through
58 HTTP_X_BOT_PASSWORD ONLY - BOT_PASSWORD stays removed from the
59 environment, so a "no password" call is really unauthenticated no matter
60 what the developer's shell happens to export."""
61 env = dict(os.environ)
62 env["QUERY_STRING"] = query
63 env["REQUEST_METHOD"] = method
64 env["SX_CONNECTOR_DIR"] = CFGDIR
65 env.pop("GITHUB_TOKEN", None) # config file only: exercise the store
66 env.pop("GITHUB_API_BASE", None)
67 env.pop("BOT_PASSWORD", None)
68 env.pop("HTTP_X_BOT_PASSWORD", None)
69 env.pop("SX_TLS_INSECURE", None)
70 # The node's own password lives in BOT_PASSWORD (that is what the node
71 # process carries); the client proves knowledge via X-Bot-Password, a
72 # Bearer header or ?pwd=. An unauthenticated call therefore still sets
73 # BOT_PASSWORD - and simply sends no credential at all.
74 if bot_password or pwd or node_password:
75 env["BOT_PASSWORD"] = node_password or "nodepw-1"
76 if bot_password:
77 env["HTTP_X_BOT_PASSWORD"] = bot_password
78 if pwd:
79 env["QUERY_STRING"] = (query + "&pwd=" + pwd).lstrip("&")
80 if env_extra:
81 env.update(env_extra)
82 data = body.encode() if body else b""
83 if data:
84 env["CONTENT_LENGTH"] = str(len(data))
85 p = subprocess.run([BIN], input=data, capture_output=True, env=env, timeout=30)
86 raw = p.stdout.decode(errors="replace")
87 head, _, payload = raw.partition("\r\n\r\n")
88 status = "200"
89 ctype = ""
90 for line in head.split("\r\n"):
91 if line.startswith("Status:"):
92 status = line.split()[1]
93 if line.lower().startswith("content-type:"):
94 ctype = line.split(":", 1)[1].strip()
95 return status, ctype, payload
96
97
98def jbody(payload):
99 try:
100 return json.loads(payload)
101 except Exception:
102 return None
103
104
105def main():
106 os.makedirs(CFGDIR, exist_ok=True)
107 cfg_path = os.path.join(CFGDIR, "config.json")
108 if os.path.exists(cfg_path):
109 os.unlink(cfg_path)
110
111 # ---------- auth gate: every action without a password is 401 ----------
112 for action in ("status", "save", "test", "tools", "clear"):
113 # node_password=... guards a passworded node, and NO client
114 # credential is sent at all: this is what an intruder on the port
115 # actually looks like
116 st, ct, pl = cgi("action=%s&format=json" % action,
117 node_password="nodepw-1")
118 check(st == "401", "?action=%s on a passworded node without a client "
119 "credential is 401" % action, st)
120
121 # Bearer auth also works (the hub proxy path)
122 st, ct, pl = cgi("action=status&format=json", pwd="nodepw-1")
123 check(st == "200", "?pwd= auth is accepted", st)
124
125 # an OPEN node (no BOT_PASSWORD at all) stays usable - that is the
126 # documented single-user default, and the check above proves the gate is
127 # the password's presence, not an accident
128 st, ct, pl = cgi("action=status&format=json")
129 check(st == "200", "with no BOT_PASSWORD set the node is open by design", st)
130
131 # ---------- status on a clean install ----------
132 st, ct, pl = cgi("action=status&format=json", bot_password="nodepw-1")
133 d = jbody(pl)
134 check(st == "200" and d and d.get("ok") is True and d.get("has_token") is False,
135 "status on a fresh node: ok, no token", pl[:160])
136 check(d and d.get("api_base") == "https://api.github.com",
137 "status defaults api_base to github.com", d and d.get("api_base"))
138
139 # ---------- save via POST JSON ----------
140 body = json.dumps({"token": TOKEN, "api_base": BASE})
141 st, ct, pl = cgi("action=save&format=json", body=body, method="POST",
142 bot_password="nodepw-1")
143 d = jbody(pl)
144 check(st == "200" and d and d.get("has_token") is True,
145 "save stores the credential (answer says has_token)", pl[:160])
146 check(TOKEN not in pl, "the save answer never contains the token itself")
147 check(os.path.exists(cfg_path), "config.json exists in the connector dir")
148 mode = stat.S_IMODE(os.stat(cfg_path).st_mode)
149 check(mode == 0o600, "config.json is mode 0600", oct(mode))
150 stored = json.load(open(cfg_path))
151 check(stored.get("token") == TOKEN and stored.get("api_base") == BASE,
152 "config.json round-trips both values")
153
154 # ---------- status now knows who the token is ----------
155 st, ct, pl = cgi("action=status&format=json", bot_password="nodepw-1")
156 d = jbody(pl)
157 check(d and d.get("user") == "mockuser" and d.get("has_token") is True,
158 "status resolves the account through the saved token", pl[:200])
159 check(TOKEN not in pl, "status never leaks the token")
160
161 # ---------- test action ----------
162 st, ct, pl = cgi("action=test&format=json", bot_password="nodepw-1")
163 d = jbody(pl)
164 check(st == "200" and d and d.get("ok") is True and d.get("user") == "mockuser",
165 "test connection reports the account", pl[:200])
166
167 # wrong token: relay GitHub's message, keep 200-JSON-envelope honesty
168 body = json.dumps({"token": "WRONG-TOKEN-XYZ"})
169 st, ct, pl = cgi("action=save&format=json", body=body, method="POST", bot_password="nodepw-1")
170 st, ct, pl = cgi("action=test&format=json", bot_password="nodepw-1")
171 d = jbody(pl)
172 check(d and d.get("ok") is False and "Bad credentials" in (d.get("error") or ""),
173 "test relays GitHub's own refusal text for a bad token", pl[:200])
174
175 # restore the good token for the rest of the suite
176 body = json.dumps({"token": TOKEN})
177 cgi("action=save&format=json", body=body, method="POST", bot_password="nodepw-1")
178
179 # ---------- save validation ----------
180 body = json.dumps({"token": "sh"})
181 st, ct, pl = cgi("action=save&format=json", body=body, method="POST", bot_password="nodepw-1")
182 check(st == "400", "a 2-char token is refused with 400", st)
183
184 body = json.dumps({"api_base": "https://evil%40x.test/"})
185 st, ct, pl = cgi("action=save&format=json", body=body, method="POST", bot_password="nodepw-1")
186 check(st == "400", "a userinfo api_base is refused with 400", st)
187
188 body = json.dumps({"api_base": "ftp://x.test"})
189 st, ct, pl = cgi("action=save&format=json", body=body, method="POST", bot_password="nodepw-1")
190 check(st == "400", "an ftp api_base is refused with 400", st)
191
192 # ---------- tools action mirrors the MCP schemas ----------
193 st, ct, pl = cgi("action=tools&format=json", bot_password="nodepw-1")
194 d = jbody(pl)
195 names = sorted(t["name"] for t in (d or {}).get("tools", []))
196 check(names == sorted(["github_get_repo", "github_list_issues",
197 "github_create_issue", "github_get_pull_request",
198 "github_search_code"]),
199 "action=tools lists the same five tools as --mcp", names)
200 check(all("inputSchema" in t for t in (d or {}).get("tools", [])),
201 "action=tools carries the real inputSchemas")
202
203 # ---------- clear keeps the base, deletes the token ----------
204 st, ct, pl = cgi("action=clear&format=json", bot_password="nodepw-1")
205 d = jbody(pl)
206 check(d and d.get("has_token") is False, "clear deletes the token", pl[:160])
207 stored = json.load(open(cfg_path))
208 check(stored.get("token", "") == "" and stored.get("api_base") == BASE,
209 "clear keeps the api base and empties only the token")
210
211 # unknown action
212 st, ct, pl = cgi("action=bogus&format=json", bot_password="nodepw-1")
213 check(st == "400", "an unknown action is 400", st)
214
215 # ---------- HTML page ----------
216 # The page is a credential control surface, so it is gated like every
217 # action: a passworded node hands a stranger a 401, not the form.
218 st, ct, pl = cgi("", node_password="nodepw-1")
219 check(st == "401", "the page itself is 401 on a passworded node with no "
220 "client credential", st)
221
222 st, ct, pl = cgi("", bot_password="nodepw-1")
223 check(st == "200" and ct.startswith("text/html"), "GET serves the page", ct)
224 check("<script src=" not in pl and "cdnjs" not in pl and
225 "jsdelivr" not in pl and "unpkg" not in pl,
226 "the page loads no external scripts (offline/CSP safe)")
227 check("data-theme" in pl and "sx-theme-request" in pl,
228 "the page carries the bot theme handoff")
229 check("Test connection" in pl and "Disconnect" in pl,
230 "the page renders the controls the suite drives")
231 st, ct, pl = cgi("embed=1", bot_password="nodepw-1")
232 check("embed=(1|true)" in pl or "embedded" in pl,
233 "embed support present (prepaint script flags <html embedded>)")
234
235 print("cgi.py: %d passed, %d failed" % (PASS, len(FAILS)))
236 return 1 if FAILS else 0
237
238
239if __name__ == "__main__":
240 sys.exit(main())