/api/auth/me returns session_expires_at (the session token exp, UTC). The browser keeps it and never extends it: the fixed 12 hours and the sliding reset are gone. Offline before that time the app opens as normal. Offline after it the app opens in read-and-queue mode: no redirect, one mode line, changes are queued and held until a page load gets a good answer from the server. wpCacheAuth refreshes the cached user without moving the end time. D26 and D27 recorded as Accepted. tests/session_expiry_check.py (22 checks) fails against the old 12 hour rule.
221 lines
10 KiB
Python
221 lines
10 KiB
Python
#!/usr/bin/env python3
|
|
"""Does the offline sign-in window follow the server? - D27 / T14.2.
|
|
|
|
auth-guard.js used to let the app open offline for a fixed 12 hours after the last
|
|
good check, and every page load reset that time. The server session lasts
|
|
AUTH_SESSION_HOURS (8). This check proves the browser now uses the server's own end
|
|
time.
|
|
|
|
1. /api/auth/me returns session_expires_at and it matches the token's exp
|
|
2. the browser keeps it, and the fixed 12 hours is gone from the code
|
|
3. offline before that time: the app opens as normal
|
|
4. offline after that time: read and queue. No redirect, the mode line shows,
|
|
a new change is queued and held, not sent
|
|
5. an older cache with no end time is treated as ended (no hidden 12 hours)
|
|
6. a page load offline does not extend the cached window
|
|
7. no cache at all, offline: sign-in page
|
|
8. online with a dead session: sign-in page with next=, and the outbox is kept
|
|
9. refreshing the cached user keeps the end of the session
|
|
|
|
Exit 0 all passed, 1 a failure, 2 could not run.
|
|
"""
|
|
import base64
|
|
import calendar
|
|
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
|
|
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
HTML = os.path.join(os.path.dirname(HERE), "html")
|
|
KEY = "wp_sync_outbox_v1"
|
|
|
|
# Makes /api/auth/me fail like a missing network when localStorage.x_me_offline is set.
|
|
OFFLINE_SHIM = """(() => {
|
|
const real = window.fetch.bind(window);
|
|
window.fetch = function (u, o) {
|
|
let off = false; try { off = !!localStorage.getItem('x_me_offline'); } catch (e) {}
|
|
if (off && String(u).indexOf('/api/auth/me') !== -1) return Promise.reject(new TypeError('Failed to fetch'));
|
|
return real(u, o);
|
|
};
|
|
})();"""
|
|
|
|
STUB = """(() => {
|
|
if (!window.__realFetch) window.__realFetch = window.fetch.bind(window);
|
|
window.__calls = [];
|
|
window.fetch = function (url, opts) {
|
|
const m = ((opts && opts.method) || 'GET').toUpperCase();
|
|
if (m === 'POST' && /\\/api\\/(wps|sops)$/.test(String(url))) {
|
|
window.__calls.push(String(url));
|
|
return Promise.resolve(new Response('{}', { status: 200, headers: { 'Content-Type': 'application/json' } }));
|
|
}
|
|
return window.__realFetch(url, opts);
|
|
};
|
|
return true;
|
|
})()"""
|
|
|
|
|
|
def token_exp(token):
|
|
body = token.split(".")[1]
|
|
body += "=" * (-len(body) % 4)
|
|
return int(json.loads(base64.urlsafe_b64decode(body))["exp"])
|
|
|
|
|
|
def cache(page):
|
|
return json.loads(page.eval("localStorage.getItem('wp_auth_cache') || 'null'") or "null")
|
|
|
|
|
|
def load(page, base, path="/field.html"):
|
|
page.goto(base + path)
|
|
time.sleep(2.0)
|
|
|
|
|
|
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-expiry-")
|
|
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 offline window follows the server - D27 / T14.2\nTarget: %s" % base)
|
|
browser = cdp.Browser(exe)
|
|
page = browser.page()
|
|
try:
|
|
page.ws.call("Page.addScriptToEvaluateOnNewDocument", {"source": OFFLINE_SHIM})
|
|
page.clear_cookies()
|
|
page.set_cookie("wp_session", tok["root"])
|
|
want = token_exp(tok["root"])
|
|
|
|
print("\n1-2. the server sends its own end time and the browser keeps it")
|
|
load(page, base)
|
|
me = page.eval("fetch('/api/auth/me').then(r => r.json())")
|
|
got = (me or {}).get("session_expires_at")
|
|
chk("/api/auth/me returns session_expires_at", bool(got), json.dumps(me)[:200])
|
|
chk("it is a UTC time that matches the token exp",
|
|
bool(got) and bool(re.match(r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$", got)) and
|
|
abs(calendar.timegm(time.strptime(got, "%Y-%m-%dT%H:%M:%SZ")) - want) <= 1,
|
|
"%s vs %s" % (got, want))
|
|
c = cache(page)
|
|
chk("the cache holds the server's end time",
|
|
bool(c) and abs((c.get("exp") or 0) / 1000.0 - want) <= 1, json.dumps(c)[:200])
|
|
src = open(os.path.join(HTML, "auth-guard.js"), encoding="utf-8").read()
|
|
code = re.sub(r"/\*.*?\*/|//[^\n]*", "", src, flags=re.S)
|
|
chk("the fixed 12 hours is gone from auth-guard.js", "12 * 3600" not in code and "43200000" not in code)
|
|
|
|
user = json.dumps(c["user"]) if c else "{}"
|
|
now_ms = int(time.time() * 1000)
|
|
|
|
def set_cache(obj):
|
|
page.eval("localStorage.setItem('wp_auth_cache', %s); localStorage.setItem('x_me_offline','1'); true"
|
|
% json.dumps(json.dumps(obj)))
|
|
|
|
print("\n3. offline before the end time: opens as normal")
|
|
future = now_ms + 3600 * 1000
|
|
set_cache({"user": c["user"], "exp": future, "at": 111})
|
|
load(page, base)
|
|
chk("no redirect", page.eval("location.pathname") == "/field.html", page.eval("location.href"))
|
|
chk("the user is the cached user", page.eval("window.WP_USER && window.WP_USER.username") == "root")
|
|
chk("mode is offline, not read-and-queue", page.eval("window.WP_SESSION_MODE") == "offline",
|
|
page.eval("window.WP_SESSION_MODE"))
|
|
|
|
print("\n6. a page load offline does not extend the window")
|
|
c2 = cache(page)
|
|
chk("the end time did not move", c2 and c2.get("exp") == future, json.dumps(c2))
|
|
chk("the cache was not rewritten", c2 and c2.get("at") == 111, json.dumps(c2))
|
|
|
|
print("\n4. offline after the end time: read and queue")
|
|
set_cache({"user": c["user"], "exp": now_ms - 3600 * 1000, "at": now_ms})
|
|
load(page, base)
|
|
chk("no redirect to the sign-in page", page.eval("location.pathname") == "/field.html",
|
|
page.eval("location.href"))
|
|
chk("the user is the cached user", page.eval("window.WP_USER && window.WP_USER.username") == "root")
|
|
chk("mode is read and queue", page.eval("window.WP_SESSION_MODE") == "readqueue",
|
|
page.eval("window.WP_SESSION_MODE"))
|
|
badge = page.eval("(document.getElementById('wp-sync-badge')||{}).textContent || ''")
|
|
chk("the mode line shows", "Working offline. Sign in again when you have a signal to send your changes." in badge,
|
|
badge)
|
|
chk("the line sits in the live region",
|
|
page.eval("(document.getElementById('wp-sync-badge')||{getAttribute(){}}).getAttribute('role')") == "status")
|
|
page.eval(STUB)
|
|
page.eval("localStorage.removeItem(%r); ProjectData.pushWP({id:'wp_rq', name:'rq'}, 'projA'); true" % KEY)
|
|
page.eval("ProjectData.flushSync()")
|
|
time.sleep(0.5)
|
|
q = json.loads(page.eval("localStorage.getItem(%r) || '[]'" % KEY))
|
|
chk("a new change is queued", [o.get("key") for o in q] == ["wp_rq"], json.dumps(q)[:200])
|
|
chk("and held: nothing was sent", page.eval("window.__calls") == [], str(page.eval("window.__calls")))
|
|
|
|
print("\n5. an older cache with no end time counts as ended")
|
|
set_cache({"user": c["user"], "at": now_ms})
|
|
load(page, base)
|
|
chk("read and queue, no redirect, no hidden window",
|
|
page.eval("location.pathname") == "/field.html" and page.eval("window.WP_SESSION_MODE") == "readqueue",
|
|
page.eval("location.href") + " " + str(page.eval("window.WP_SESSION_MODE")))
|
|
|
|
print("\n9. refreshing the cached user keeps the end of the session")
|
|
set_cache({"user": c["user"], "exp": future, "at": 1})
|
|
page.eval("window.wpCacheAuth({username: 'renamed'}); true")
|
|
c3 = cache(page)
|
|
chk("the user changed", c3 and c3["user"].get("username") == "renamed", json.dumps(c3))
|
|
chk("the end time did not", c3 and c3.get("exp") == future, json.dumps(c3))
|
|
|
|
print("\n7. no cache, offline: the sign-in page")
|
|
page.eval("localStorage.removeItem('wp_auth_cache'); localStorage.setItem('x_me_offline','1'); true")
|
|
load(page, base)
|
|
chk("sent to login.html", page.eval("location.pathname") == "/login.html", page.eval("location.href"))
|
|
|
|
print("\n8. online with a dead session: sign-in page and the outbox is kept")
|
|
page.clear_cookies()
|
|
page.set_cookie("wp_session", tok["root"])
|
|
page.goto(base + "/field.html")
|
|
time.sleep(1.5)
|
|
page.eval("localStorage.removeItem('x_me_offline'); localStorage.setItem(%r, %s); true" % (
|
|
KEY, json.dumps(json.dumps([{"kind": "wp", "key": "wp_keep", "opId": "wp:wp_keep:1", "tries": 0,
|
|
"owner": "root", "body": {"id": "wp_keep"}}]))))
|
|
page.clear_cookies()
|
|
page.set_cookie("wp_session", "not-a-valid-token")
|
|
load(page, base)
|
|
loc = page.eval("location.pathname + location.search")
|
|
chk("online with a dead session: redirect to login.html?next=",
|
|
loc.startswith("/login.html") and "next=" in loc, loc)
|
|
q = json.loads(page.eval("localStorage.getItem(%r) || '[]'" % KEY))
|
|
chk("the queued change is still there", [o.get("key") for o in q] == ["wp_keep"], json.dumps(q)[:200])
|
|
finally:
|
|
page.close()
|
|
browser.close()
|
|
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())
|