Files
Project-SDE-WP-Suite/tests/console_dialogs_check.py
Cody Schaefer c47b2ae210 T10.7 D13 - the suite runs without a domain controller
Far smaller than estimated, because the premise was wrong. I had said four
checks sign in and would each need a fake directory. They do not: seed() mints
a session token with auth.create_token() and sets the cookie directly -
browser_check's own docstring says so - and the only breakage was a leftover
password_hash= kwarg on a model that no longer has the column. Deleting that one
line in browser_check.seed() unblocked 39 files that import seed/start_server
from it. launcher_check needed the same.

console_dialogs_check's password-reset half is deleted rather than ported. Its
docstring now records what went and where the prompt kit is still covered
(wpPromptDialog has five callers left in wp-creation-app.js; creator_dialogs_check
exercises them, validation included - verified, 20/20). Nothing was left skipped
in place of the removed section.

Exactly one check genuinely needed a seam: url_state_check drives the real login
form to prove a deep link's ?next= survives authentication. That cannot be faked
by minting a cookie, because the login round trip is the thing under test.

The seam is env-driven because it has to be: start_server launches the app as a
SUBPROCESS, so a monkeypatch in the test process would never reach the code doing
the authenticating. server/ldap_fake.py reads WP_LDAP_FAKE_DIRECTORY and
ldap_auth dispatches to it AFTER the empty-input guard, so the anonymous-bind
guard covers the fake path too - a fake that reimplemented it would let the real
one rot unnoticed.

The production guard is the point of that module. An env var that makes any
password work is exactly the kind of thing that escapes into production, and D13
left no other way in. is_active() refuses whenever a non-SQLite DATABASE_URL is
configured - the same test auth._load_secret uses - and describe() shouts in
capitals so a fake run can never be mistaken for a real one in the startup log.

Two things found on the way, neither of them the app's fault:

- url_state_check's "signing in continues to the requested page" asserted
  `"wp-creation-index.html" in location.href`. That string is in the ?next=
  parameter too, so it passed while sitting on login.html with the sign-in
  rejected. It would have passed with login entirely broken. Tightened to assert
  we actually left the login page.
- Two assertions in my own new ldap_auth_check read the WRONG database:
  server/db.py binds its engine from DATABASE_URL at import, so setting the env
  var afterwards keeps reading whichever file was configured first. users_in()
  now opens the file it is asked about with sqlite3. The CERT_NONE check also had
  to become an AST walk - the module docstring names validate=ssl.CERT_NONE in
  order to explain why it is banned, and a text search cannot tell that apart
  from a real call.

tests/ldap_auth_check.py is new coverage rather than repair: the anonymous-bind
guard, CERT_REQUIRED by AST, the nested matching rule in the filter, the
production refusal, a refused sign-in creating no account, and an existing admin
still being an admin with their locally-set name intact. 20/20.

Run so far, all green: browser_check 71/71, launcher_check 58/58,
console_dialogs 12/12, url_state 23/23, qa_gate 41/41, critical_reopen 11/11,
creator_dialogs 20/20, a11y 22/22, kitting_notify 17/17, ldap_auth 20/20.
A full sweep of the remaining ~30 is running; its box stays unticked until it
reports.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-24 09:18:05 -05:00

125 lines
5.0 KiB
Python

#!/usr/bin/env python3
"""Are the consoles' and launcher's 21 native dialogs gone? — BL-024, 2026-08-20.
S1 counted 79 native dialogs app-wide; its two tasks (T5.8 wizard, T7.9
creator) removed 58 and the audit found the remaining 21 on surfaces no S1
task named: admin.js (6), users.js (10), the launcher's inline script (5).
They now go through `wp-dialog.js` — the T7.9 kit extracted as a shared,
self-injecting component (guarded so the creator's inline copy still wins on
its own page).
Static half greps the counts; browser half drives the password-reset prompt on
the users console with natives poisoned, and proves validate() answers AT the
input while the server round-trip completes end to end.
Boots its own throwaway SQLite + uvicorn + headless browser; run it alone.
Exit 0 all passed, 1 a failure, 2 could not run.
"""
import io
import os
import re
import sys
import tempfile
import time
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import cdp # noqa: E402
from browser_check import seed, start_server, chk, _PASS, _FAIL # noqa: E402
from qa_gate_check import api # noqa: E402
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
HTML = os.path.join(ROOT, "html")
def ascii_(v, n=240):
return re.sub(r"\s+", " ", str(v)).encode("ascii", "replace").decode()[:n]
def strip_js(src):
src = re.sub(r"/\*.*?\*/", "", src, flags=re.S)
return "\n".join(re.sub(r"(?<![:'\"])//.*$", "", ln) for ln in src.split("\n"))
def natives(name):
code = strip_js(io.open(os.path.join(HTML, name), encoding="utf-8").read())
return len(re.findall(r"(?<![\w.$])(alert|confirm|prompt)\(", code))
def main():
exe = cdp.find_browser()
if not exe:
print("no headless-capable browser found; set WP_BROWSER.")
return 2
print("\n1. the counts (baseline 6 + 10 + 5 = 21)")
for name in ("admin.js", "users.js", "index.html"):
chk("%s: 0 native dialogs" % name, natives(name) == 0, natives(name))
chk("wp-dialog.js exists, has the guard, and no natives of its own",
natives("wp-dialog.js") == 0
and "typeof global.wpConfirmDialog === 'function'" in
io.open(os.path.join(HTML, "wp-dialog.js"), encoding="utf-8").read())
for page in ("index.html", "admin.html", "users.html"):
chk("%s loads the kit" % page,
'src="wp-dialog.js"' in io.open(os.path.join(HTML, page), encoding="utf-8").read())
chk("the creator keeps its own copy (it owns the same-id markup in its HTML)",
"function wpConfirmDialog" in
io.open(os.path.join(HTML, "wp-creation-app.js"), encoding="utf-8").read())
tmpdir = tempfile.mkdtemp(prefix="wpsuite-condlg-")
db_path = os.path.join(tmpdir, "check.db")
server = None
browser = None
try:
tok = seed(db_path)
port = cdp.free_port()
base = "http://127.0.0.1:%d" % port
server = start_server(port, db_path)
print("\n2. the users console, natives poisoned")
browser = cdp.Browser(exe)
page = browser.page()
page.clear_cookies()
page.set_cookie("wp_session", tok["root"])
page.viewport(1440, 900)
page.goto(base + "/users.html")
time.sleep(2.0)
page.eval("window.alert=()=>{throw new Error('native alert reached')};"
"window.confirm=()=>{throw new Error('native confirm reached')};"
"window.prompt=()=>{throw new Error('native prompt reached')};")
chk("the console booted with a user table",
page.eval("!!document.querySelector('table')"))
print("\n3. destroy needs a real yes")
page.eval("void deleteUser('user_bob','bob')")
time.sleep(0.4)
chk("the delete asks through the kit, spelling out what goes with it",
page.eval("(() => { const o=document.getElementById('wp-dlg-overlay');"
" return o.classList.contains('open')"
" && /cannot be undone/.test(document.getElementById('wp-dlg-msg').textContent); })()"))
page.eval("document.getElementById('wp-dlg-cancel').click()")
time.sleep(0.6)
st, users = api(base, "/api/auth/users", tok["root"])
chk("cancel means no: bob is still an account",
st == 200 and any(u.get("username") == "bob" for u in (users or [])),
ascii_([u.get("username") for u in (users or [])]))
errs = [e for e in page.js_errors() if "beforeunload" not in e]
chk("no JavaScript errors, and no path reached a native dialog (they throw here)",
not errs, ascii_(errs[:3]))
finally:
if browser:
browser.close()
if server:
server.terminate()
print("\n" + "-" * 54)
print("%d/%d checks passed." % (len(_PASS), len(_PASS) + len(_FAIL)))
for f in _FAIL:
print(" - " + f)
return 1 if _FAIL else 0
if __name__ == "__main__":
sys.exit(main())