T14.1 (D26): a sign-in problem never destroys a queued change

A 401 holds the queue: nothing is marked dead, no try is counted, and only
wp-auth-ready releases it. A 403 marks only that change dead, with a reason.
qWrite reports failure; a change the device cannot store stays in memory and the
badge says so. Each change has an owner and is sent only under that person.

tests/outbox_check.py (26 checks) fails against the old 401 rule.
This commit is contained in:
2026-10-17 14:00:52 -07:00
parent 512f0b6b1d
commit 73f0b5e69d
2 changed files with 341 additions and 33 deletions

226
tests/outbox_check.py Normal file
View File

@@ -0,0 +1,226 @@
#!/usr/bin/env python3
"""Does a sign-in problem destroy queued work? - D26 / T14.1.
The outbox in html/project-data.js queues every save and sends it later. It used to
treat a 401 (the session ended) like any other 4xx: the change was marked dead and
never sent again. It also hid a full device store and sent a change under whoever
was signed in. This check drives the real page in a real browser. It replaces
window.fetch for the write endpoints only, so no real server state is needed.
1. a 401 holds the whole queue: nothing dead, no try counted, state is "held"
2. online, tab focus and the timer do not release a held queue
3. a good sign-in (wp-auth-ready) sends every change, in the original order
4. a 403 kills only that change and says why
5. a full device store is reported to the caller and the badge; nothing is dropped
6. a change is sent only under the person who made it
7. auth-guard.js never deletes the outbox
Exit 0 all passed, 1 a failure, 2 could not run.
"""
import json
import os
import re
import subprocess
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
KEY = "wp_sync_outbox_v1"
HERE = os.path.dirname(os.path.abspath(__file__))
HTML = os.path.join(os.path.dirname(HERE), "html")
# Replaces fetch for POST /api/wps, POST /api/sops and DELETE /api/wps/<id> only.
# window.__plan maps a work package id to a status; the default is window.__status.
STUB = """(() => {
if (!window.__realFetch) window.__realFetch = window.fetch.bind(window);
window.__calls = []; window.__status = 200; window.__plan = {};
window.fetch = function (url, opts) {
const m = ((opts && opts.method) || 'GET').toUpperCase();
const u = String(url);
if ((m === 'POST' && /\\/api\\/(wps|sops)$/.test(u)) || (m === 'DELETE' && /\\/api\\/wps\\//.test(u))) {
let id = '';
try { id = JSON.parse(opts.body).id; } catch (e) { id = decodeURIComponent(u.split('/').pop()); }
window.__calls.push(id);
const st = (id in window.__plan) ? window.__plan[id] : window.__status;
return Promise.resolve(new Response(JSON.stringify(st >= 400 ? { detail: 'stub ' + st } : { ok: true }),
{ status: st, headers: { 'Content-Type': 'application/json' } }));
}
return window.__realFetch(url, opts);
};
localStorage.removeItem('wp_sync_outbox_v1');
return true;
})()"""
def boot(page, base, tok, user="root"):
page.clear_cookies()
page.set_cookie("wp_session", tok[user])
page.goto(base + "/field.html")
for _ in range(40):
if page.eval("!!(window.WP_USER && window.ProjectData)"):
break
time.sleep(0.3)
time.sleep(0.5)
page.eval(STUB)
def queue(page):
return json.loads(page.eval("localStorage.getItem(%r) || '[]'" % KEY))
def status(page):
return page.eval("ProjectData.syncStatus()")
def push(page, ids):
page.eval("(() => { %s; return true; })()" % ";".join(
"ProjectData.pushWP({id:%r, name:%r}, 'projA')" % (i, i) for i in ids))
def main():
exe = cdp.find_browser()
if not exe:
print("no headless-capable browser found; set WP_BROWSER.")
return 2
tmpdir = tempfile.mkdtemp(prefix="wpsuite-outbox-")
db_path = os.path.join(tmpdir, "check.db")
server = None
try:
tok = seed(db_path)
port = cdp.free_port()
base = "http://127.0.0.1:%d" % port
server = start_server(port, db_path)
if server is None:
print("the test server would not start.")
return 2
print("\nThe outbox keeps every change - D26 / T14.1\nTarget: %s" % base)
browser = cdp.Browser(exe)
page = browser.page()
try:
ids = ["wp_o1", "wp_o2", "wp_o3"]
print("\n1. a 401 holds the whole queue")
boot(page, base, tok)
page.eval("window.__status = 401")
push(page, ids)
page.eval("ProjectData.flushSync()")
q = queue(page)
st = status(page)
chk("all 3 changes are still queued", [o["key"] for o in q] == ids, str([o["key"] for o in q]))
chk("none is marked dead", not any(o.get("dead") for o in q) and st["dead"] == 0)
chk("no try was counted", all((o.get("tries") or 0) == 0 for o in q), str([o.get("tries") for o in q]))
chk("the state is held", st["held"] is True, json.dumps(st))
chk("the run stopped at the first 401", len(page.eval("window.__calls")) == 1,
str(page.eval("window.__calls")))
badge = page.eval("document.getElementById('wp-sync-badge').textContent")
chk("the badge asks for a new sign-in", "Sign in again" in badge, badge)
print("\n2. only a good sign-in releases it")
page.eval("window.__status = 200")
page.eval("window.dispatchEvent(new Event('online'))")
page.eval("document.dispatchEvent(new Event('visibilitychange'))")
page.eval("ProjectData.flushSync()")
time.sleep(1.0)
chk("online, focus and a manual flush send nothing while held",
len(page.eval("window.__calls")) == 1 and len(queue(page)) == 3,
str(page.eval("window.__calls")))
print("\n3. a good sign-in sends all of them, in order")
page.eval("document.dispatchEvent(new CustomEvent('wp-auth-ready', {detail: window.WP_USER}))")
for _ in range(30):
if not queue(page):
break
time.sleep(0.3)
calls = page.eval("window.__calls")
chk("the queue is empty", queue(page) == [], str(queue(page)))
chk("the changes arrived in the original order", calls[1:] == ids or calls[-3:] == ids, str(calls))
chk("the state is no longer held", status(page)["held"] is False)
print("\n4. a 403 kills only that change, with a reason")
boot(page, base, tok)
page.eval("window.__plan = {wp_o2: 403}")
push(page, ids)
page.eval("ProjectData.flushSync()")
q = queue(page)
dead = [o for o in q if o.get("dead")]
chk("only wp_o2 is dead", [o["key"] for o in dead] == ["wp_o2"], str([o["key"] for o in q]))
chk("the others were sent", [o["key"] for o in q if not o.get("dead")] == [])
chk("the reason names the cause", dead and "no longer have access" in dead[0].get("lastErr", ""),
dead[0].get("lastErr", "") if dead else "")
chk("a 403 does not hold the queue", status(page)["held"] is False)
print("\n5. a full device store is never silent")
boot(page, base, tok)
page.eval("window.__status = 500") # keep it queued so the badge state stays visible
page.eval("""(() => {
window.__setItem = Storage.prototype.setItem;
Storage.prototype.setItem = function (k, v) {
if (k === 'wp_sync_outbox_v1') { const e = new Error('full'); e.name = 'QuotaExceededError'; throw e; }
return window.__setItem.call(this, k, v);
};
return true; })()""")
stored = page.eval("ProjectData.pushWP({id:'wp_full', name:'full'}, 'projA')")
st = status(page)
chk("the caller is told it was not stored", stored is False, repr(stored))
chk("the state says device full, 1 unsaved", st["deviceFull"] is True and st["unsaved"] == 1, json.dumps(st))
badge = page.eval("document.getElementById('wp-sync-badge').textContent")
chk("the badge says it is not saved on this device", "not saved on this device" in badge, badge)
page.eval("window.__status = 200")
page.eval("ProjectData.flushSync()")
chk("the change is still sent from memory", "wp_full" in page.eval("window.__calls"),
str(page.eval("window.__calls")))
page.eval("Storage.prototype.setItem = window.__setItem")
chk("the state clears once it is sent", status(page)["unsaved"] == 0)
print("\n6. a change is sent only under the person who made it")
boot(page, base, tok)
page.eval("window.__status = 503") # keep the change queued while we look at it
push(page, ["wp_owned"])
time.sleep(0.5)
page.eval("window.__status = 200")
q0 = queue(page)
owner = (q0[0].get("owner") if q0 else None)
chk("the change records its owner", owner == "root", repr(owner))
page.eval("window.__calls = []; window.__me = window.WP_USER; window.WP_USER = {username: 'pat'}")
page.eval("ProjectData.flushSync()")
st = status(page)
chk("person B sends nothing", page.eval("window.__calls") == [], str(page.eval("window.__calls")))
chk("the change is kept", [o["key"] for o in queue(page)] == ["wp_owned"])
chk("the badge names the owner", st["others"] == 1 and st["otherOwner"] == "root", json.dumps(st))
page.eval("window.WP_USER = window.__me")
page.eval("ProjectData.flushSync()")
chk("it is sent after the owner signs in", page.eval("window.__calls") == ["wp_owned"]
and queue(page) == [], str(page.eval("window.__calls")))
finally:
page.close()
browser.close()
print("\n7. auth-guard.js never deletes the outbox")
src = open(os.path.join(HTML, "auth-guard.js"), encoding="utf-8").read()
code = re.sub(r"/\*.*?\*/|//[^\n]*", "", src, flags=re.S)
chk("no code path touches the outbox key", KEY not in code)
chk("nothing clears all of localStorage", "localStorage.clear" not in code)
finally:
if server is not None:
server.kill()
try:
server.wait(timeout=10)
except subprocess.TimeoutExpired:
pass
try:
from server.db import engine
engine.dispose()
except Exception:
pass
print("\n%d passed, %d failed" % (len(_PASS), len(_FAIL)))
return 1 if _FAIL else 0
if __name__ == "__main__":
sys.exit(main())