Release: wave 11 + T13.2-T13.5 (D18 Okta sync), T13.1 held back until T14.1; mobile roadmap docs (BL-062..BL-069)
This commit is contained in:
@@ -254,27 +254,23 @@ def main():
|
||||
if ("el.textContent = '" in ln or "el.innerHTML = '" in ln)
|
||||
and "the project" not in ln and ("✓" in ln or "⚠" in ln or "↻" in ln or "✕" in ln)])
|
||||
|
||||
print("\n7. the analytics dwell listener still fires")
|
||||
print("\n7. autosave's own registration survives the retired analytics tracker")
|
||||
# This section used to also assert the per-browser usage-analytics dwell
|
||||
# listener (wp-usage.js) still fired alongside autosave, to catch autosave
|
||||
# accidentally replacing it. CR-019/T11.6 (2026-09-23) retired that tracker
|
||||
# on purpose - track() is now a documented no-op and wp-usage.js is gone -
|
||||
# so asserting it still records an event would be asserting the wrong
|
||||
# thing. What's still worth checking here is autosave's own registration,
|
||||
# which is what this section actually guards.
|
||||
boot(page, base, tok, "/work-package-suite.html?project=projA&tab=sop")
|
||||
time.sleep(0.8)
|
||||
chk("the wizard still has its analytics dwell tracker",
|
||||
page.eval("typeof trackStepDwell === 'function'"))
|
||||
chk("...and the wizard registered autosave too",
|
||||
chk("the wizard registered autosave",
|
||||
page.eval("typeof WPAutosave === 'object' && typeof sopDraftId === 'function'"))
|
||||
before = page.eval("""(() => {
|
||||
try { return (JSON.parse(localStorage.getItem('wp_suite_analytics_v1')||'{}').events||[]).length; }
|
||||
catch(e){ return -1; }
|
||||
})()""")
|
||||
# trackStepDwell only records a dwell longer than 400ms, so give it one.
|
||||
time.sleep(0.9)
|
||||
page.eval("typeof trackStepDwell==='function' && trackStepDwell()")
|
||||
time.sleep(0.4)
|
||||
after_n = page.eval("""(() => {
|
||||
try { return (JSON.parse(localStorage.getItem('wp_suite_analytics_v1')||'{}').events||[]).length; }
|
||||
catch(e){ return -1; }
|
||||
})()""")
|
||||
chk("calling it records an event (it was not replaced by the guard)",
|
||||
after_n > before, "%s -> %s" % (before, after_n))
|
||||
chk("...and the retired dwell tracker is a harmless no-op, not missing or throwing",
|
||||
page.eval("""(() => {
|
||||
if (typeof trackStepDwell !== 'function') return false;
|
||||
try { trackStepDwell(); return true; } catch (e) { return false; }
|
||||
})()"""))
|
||||
finally:
|
||||
page.close()
|
||||
browser.close()
|
||||
|
||||
252
tests/okta_sync_check.py
Normal file
252
tests/okta_sync_check.py
Normal file
@@ -0,0 +1,252 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Does the Okta Management API client keep its promises? - D18 / T13.2.
|
||||
|
||||
The one promise that matters: a failure is never an empty list. T13.3 reads an
|
||||
empty list as "nobody is active", so a client that returned [] when Okta was
|
||||
down would disable the whole org. Every failure below must raise OktaSyncError.
|
||||
|
||||
Also checked: the client uses its own credential (never the OIDC client secret),
|
||||
follows pagination, never sends the token to another host, never follows a
|
||||
redirect, and never lets the token reach a log line, an error message, or
|
||||
describe().
|
||||
|
||||
Self-contained: no server, no database, no network, no browser. httpx's
|
||||
MockTransport stands in for Okta.
|
||||
Exit 0 all passed, 1 a failure.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
import httpx # noqa: E402
|
||||
|
||||
from server import okta_auth, okta_sync # noqa: E402
|
||||
|
||||
TOKEN = "00tok-SECRET-api-token-xyz"
|
||||
CLIENT_SECRET = "oidc-client-SECRET-abc"
|
||||
ORG = "https://example.okta.com"
|
||||
|
||||
fails = 0
|
||||
|
||||
|
||||
def chk(label, ok, extra=""):
|
||||
global fails
|
||||
print(("PASS " if ok else "FAIL ") + label + (f" [{extra}]" if (extra and not ok) else ""))
|
||||
if not ok:
|
||||
fails += 1
|
||||
|
||||
|
||||
class Capture(logging.Handler):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.lines = []
|
||||
|
||||
def emit(self, record):
|
||||
self.lines.append(record.getMessage())
|
||||
|
||||
|
||||
cap = Capture()
|
||||
logging.getLogger("wpsuite").addHandler(cap)
|
||||
logging.getLogger("wpsuite").setLevel(logging.DEBUG)
|
||||
|
||||
|
||||
def reset_env():
|
||||
os.environ["OKTA_API_TOKEN"] = TOKEN
|
||||
os.environ["OKTA_CLIENT_SECRET"] = CLIENT_SECRET
|
||||
os.environ.pop("OKTA_ORG_URL", None)
|
||||
os.environ.pop("OKTA_SYNC_PROFILE_ATTRIBUTE", None)
|
||||
okta_auth.ISSUER = f"{ORG}/oauth2/default"
|
||||
okta_auth.IDENTITY_CLAIM = "preferred_username"
|
||||
|
||||
|
||||
def user(login, status="ACTIVE", **profile):
|
||||
p = {"login": login, "email": login}
|
||||
p.update(profile)
|
||||
return {"id": "00u" + login, "status": status, "profile": p}
|
||||
|
||||
|
||||
def client(handler):
|
||||
return httpx.Client(transport=httpx.MockTransport(handler))
|
||||
|
||||
|
||||
def raises(handler, label, **kw):
|
||||
"""Run fetch_users against `handler`; it must raise OktaSyncError, and the
|
||||
message must not hold the token."""
|
||||
reset_env()
|
||||
try:
|
||||
out = okta_sync.fetch_users(http=client(handler))
|
||||
except okta_sync.OktaSyncError as exc:
|
||||
msg = str(exc)
|
||||
clean = TOKEN not in msg and CLIENT_SECRET not in msg and "example.okta.com" not in msg
|
||||
chk(f"{label}: raises, message has no token or host", clean, msg)
|
||||
return msg
|
||||
except Exception as exc: # the wrong exception type
|
||||
chk(f"{label}: raises OktaSyncError", False, f"{type(exc).__name__}: {exc}")
|
||||
return ""
|
||||
chk(f"{label}: raises (did NOT raise, returned {out!r})", False)
|
||||
return ""
|
||||
|
||||
|
||||
def ok(body):
|
||||
return lambda req: httpx.Response(200, json=body)
|
||||
|
||||
|
||||
# ── 1. a good fetch ───────────────────────────────────────────────────────────
|
||||
print("\n1. a good fetch")
|
||||
reset_env()
|
||||
seen = []
|
||||
|
||||
|
||||
def good(req):
|
||||
seen.append(req)
|
||||
return httpx.Response(200, json=[user("alice", "ACTIVE"), user("bob", "suspended")])
|
||||
|
||||
|
||||
users = okta_sync.fetch_users(http=client(good))
|
||||
chk("returns every user", [u.identity for u in users] == ["alice", "bob"])
|
||||
chk("status is upper case", [u.status for u in users] == ["ACTIVE", "SUSPENDED"])
|
||||
chk("asks the users endpoint of the org", str(seen[0].url).startswith(f"{ORG}/api/v1/users"))
|
||||
chk("asks for the page maximum", seen[0].url.params.get("limit") == "200")
|
||||
chk("authenticates with the API token (SSWS)", seen[0].headers.get("authorization") == f"SSWS {TOKEN}")
|
||||
chk("never sends the OIDC client secret", CLIENT_SECRET not in str(seen[0].headers))
|
||||
|
||||
# ── 2. pagination ─────────────────────────────────────────────────────────────
|
||||
print("\n2. pagination")
|
||||
reset_env()
|
||||
calls = []
|
||||
|
||||
|
||||
def paged(req):
|
||||
calls.append(req)
|
||||
if "after=p2" not in str(req.url):
|
||||
return httpx.Response(200, json=[user("alice")],
|
||||
headers={"Link": f'<{ORG}/api/v1/users?limit=200&after=p2>; rel="next"'})
|
||||
return httpx.Response(200, json=[user("bob")])
|
||||
|
||||
|
||||
users = okta_sync.fetch_users(http=client(paged))
|
||||
chk("follows the next link and returns both pages", [u.identity for u in users] == ["alice", "bob"])
|
||||
chk("two requests, no more", len(calls) == 2)
|
||||
chk("page 2 also carries the token", calls[1].headers.get("authorization") == f"SSWS {TOKEN}")
|
||||
|
||||
# ── 3. the failure rule: an error is never an empty list ──────────────────────
|
||||
print("\n3. every failure raises (never returns an empty list)")
|
||||
for code in (401, 403, 404, 429, 500, 502, 503):
|
||||
raises(lambda req, c=code: httpx.Response(c, json={"errorCode": "x"}), f"HTTP {code}")
|
||||
raises(lambda req: httpx.Response(302, headers={"Location": "https://evil.example/"}), "a redirect (never followed)")
|
||||
raises(lambda req: (_ for _ in ()).throw(httpx.ConnectError("boom to https://example.okta.com/api/v1/users")), "connection error")
|
||||
raises(lambda req: (_ for _ in ()).throw(httpx.ReadTimeout("slow")), "timeout")
|
||||
raises(lambda req: httpx.Response(200, text="<html>not json</html>"), "body is not JSON")
|
||||
raises(ok({"errorCode": "E0000011"}), "body is an object, not a list")
|
||||
raises(ok("a string"), "body is a string")
|
||||
raises(ok([]), "an empty list (not credible for a real org)")
|
||||
raises(ok(["alice"]), "an item that is not an object")
|
||||
raises(ok([{"profile": {"login": "a"}}]), "an item with no status")
|
||||
raises(ok([{"status": "ACTIVE"}]), "an item with no profile")
|
||||
raises(ok([{"status": "ACTIVE", "profile": {}}]), "an item with no login")
|
||||
raises(ok([{"status": "ACTIVE", "profile": {"login": " "}}]), "an item with a blank login")
|
||||
raises(ok([user("alice"), {"status": "ACTIVE", "profile": {}}]), "one bad item among good ones (never skipped)")
|
||||
|
||||
# ── 4. misconfiguration raises ────────────────────────────────────────────────
|
||||
print("\n4. misconfiguration")
|
||||
reset_env()
|
||||
os.environ["OKTA_API_TOKEN"] = ""
|
||||
try:
|
||||
okta_sync.fetch_users(http=client(good))
|
||||
chk("no token raises", False)
|
||||
except okta_sync.OktaSyncError:
|
||||
chk("no token raises", True)
|
||||
reset_env()
|
||||
okta_auth.ISSUER = ""
|
||||
try:
|
||||
okta_sync.fetch_users(http=client(good))
|
||||
chk("no org URL raises", False)
|
||||
except okta_sync.OktaSyncError:
|
||||
chk("no org URL raises", True)
|
||||
reset_env()
|
||||
os.environ["OKTA_ORG_URL"] = "http://example.okta.com"
|
||||
sent = []
|
||||
try:
|
||||
okta_sync.fetch_users(http=client(lambda r: sent.append(r) or httpx.Response(200, json=[user("a")])))
|
||||
chk("an http org URL raises", False)
|
||||
except okta_sync.OktaSyncError:
|
||||
chk("an http org URL raises", True)
|
||||
chk("...and no request was made (token never sent over http)", sent == [])
|
||||
|
||||
# ── 5. never leaks the token to another host, never loops forever ─────────────
|
||||
print("\n5. next-link safety")
|
||||
reset_env()
|
||||
hosts = []
|
||||
|
||||
|
||||
def evil_link(req):
|
||||
hosts.append(req.url.host)
|
||||
return httpx.Response(200, json=[user("alice")],
|
||||
headers={"Link": '<https://evil.example/steal>; rel="next"'})
|
||||
|
||||
|
||||
raises(evil_link, "a next link to another host")
|
||||
chk("...the other host was never contacted", hosts == ["example.okta.com"])
|
||||
|
||||
count = []
|
||||
|
||||
|
||||
def endless(req):
|
||||
count.append(1)
|
||||
return httpx.Response(200, json=[user("alice")],
|
||||
headers={"Link": f'<{ORG}/api/v1/users?after={len(count)}>; rel="next"'})
|
||||
|
||||
|
||||
raises(endless, "an endless next chain (page cap)")
|
||||
chk(f"...stops at the cap ({okta_sync.MAX_PAGES} requests)", len(count) == okta_sync.MAX_PAGES, str(len(count)))
|
||||
|
||||
# ── 6. org URL and identity attribute ─────────────────────────────────────────
|
||||
print("\n6. org URL and identity attribute")
|
||||
reset_env()
|
||||
chk("org URL is the issuer's scheme and host", okta_sync.org_url() == ORG)
|
||||
os.environ["OKTA_ORG_URL"] = "https://corp.okta.com/"
|
||||
chk("OKTA_ORG_URL wins, trailing slash removed", okta_sync.org_url() == "https://corp.okta.com")
|
||||
reset_env()
|
||||
okta_auth.IDENTITY_CLAIM = "email"
|
||||
body = [{"status": "ACTIVE", "profile": {"login": "alice", "email": "alice@x.com"}}]
|
||||
chk("claim 'email' reads profile.email", okta_sync.fetch_users(http=client(ok(body)))[0].identity == "alice@x.com")
|
||||
okta_auth.IDENTITY_CLAIM = "sAMAccountName"
|
||||
body = [{"status": "ACTIVE", "profile": {"login": "alice@x.com", "sAMAccountName": "alice"}}]
|
||||
chk("a custom claim reads profile[<claim>]", okta_sync.fetch_users(http=client(ok(body)))[0].identity == "alice")
|
||||
os.environ["OKTA_SYNC_PROFILE_ATTRIBUTE"] = "login"
|
||||
chk("OKTA_SYNC_PROFILE_ATTRIBUTE overrides", okta_sync.fetch_users(http=client(ok(body)))[0].identity == "alice@x.com")
|
||||
|
||||
# ── 7. the token never leaks ──────────────────────────────────────────────────
|
||||
print("\n7. the token never leaks")
|
||||
reset_env()
|
||||
chk("describe() has no token", TOKEN not in okta_sync.describe() and "configured" in okta_sync.describe())
|
||||
os.environ["OKTA_API_TOKEN"] = ""
|
||||
chk("describe() says DISABLED without a token", "DISABLED" in okta_sync.describe())
|
||||
reset_env()
|
||||
every_log = " ".join(cap.lines)
|
||||
chk("no log line holds the API token", TOKEN not in every_log)
|
||||
chk("no log line holds the client secret", CLIENT_SECRET not in every_log)
|
||||
|
||||
# ── 8. the whole fetch is time-bounded (T13.4 relies on it) ──────────────────
|
||||
print("\n8. the whole fetch is time-bounded")
|
||||
reset_env()
|
||||
saved = okta_sync.TOTAL_DEADLINE_SECONDS
|
||||
okta_sync.TOTAL_DEADLINE_SECONDS = 0.0
|
||||
|
||||
|
||||
def slow_pages(req):
|
||||
return httpx.Response(200, json=[user("alice")],
|
||||
headers={"Link": f'<{ORG}/api/v1/users?after=x>; rel="next"'})
|
||||
|
||||
|
||||
raises(slow_pages, "a fetch that runs past the total deadline")
|
||||
okta_sync.TOTAL_DEADLINE_SECONDS = saved
|
||||
chk("the real deadline is under the shortest allowed interval",
|
||||
okta_sync.TOTAL_DEADLINE_SECONDS < okta_sync.INTERVAL_MIN_SECONDS)
|
||||
|
||||
print()
|
||||
print("ALL PASSED" if not fails else f"{fails} FAILED")
|
||||
sys.exit(0 if not fails else 1)
|
||||
218
tests/okta_sync_job_check.py
Normal file
218
tests/okta_sync_job_check.py
Normal file
@@ -0,0 +1,218 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Does the Okta deprovisioning sync fail closed? - D18 / T13.3.
|
||||
|
||||
The rule that must never be skipped or weakened: when Okta cannot be asked, or
|
||||
its answer cannot be trusted, the sync changes NO account and writes NO audit
|
||||
row. Treating "could not reach Okta" as "nobody is active" would lock the whole
|
||||
company out on one bad afternoon.
|
||||
|
||||
Also checked: the sync only ever disables (it never re-enables, under any
|
||||
input), writes one audit row per change with a non-human actor, leaves an
|
||||
already-disabled account alone, logs only changes, and keeps temporary Okta
|
||||
states (PASSWORD_EXPIRED, LOCKED_OUT, RECOVERY) from disabling anyone.
|
||||
|
||||
Self-contained: its own in-memory SQLite, no server, no network, no browser.
|
||||
Exit 0 all passed, 1 a failure.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
import httpx # noqa: E402
|
||||
from sqlalchemy import create_engine, select # noqa: E402
|
||||
from sqlalchemy.orm import sessionmaker # noqa: E402
|
||||
from sqlalchemy.pool import StaticPool # noqa: E402
|
||||
|
||||
from server import models, okta_auth, okta_sync # noqa: E402
|
||||
from server.okta_sync import OktaSyncError, OktaUser, run_sync # noqa: E402
|
||||
|
||||
fails = 0
|
||||
|
||||
|
||||
def chk(label, ok, extra=""):
|
||||
global fails
|
||||
print(("PASS " if ok else "FAIL ") + label + (f" [{extra}]" if (extra and not ok) else ""))
|
||||
if not ok:
|
||||
fails += 1
|
||||
|
||||
|
||||
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
|
||||
models.Base.metadata.create_all(engine)
|
||||
Session = sessionmaker(bind=engine, autoflush=False, future=True)
|
||||
|
||||
|
||||
def seed(rows):
|
||||
"""rows: list of (username, is_active[, email]). Wipes users and audit rows first."""
|
||||
with Session() as db:
|
||||
db.query(models.AuditLog).delete()
|
||||
db.query(models.User).delete()
|
||||
for r in rows:
|
||||
name, active = r[0], r[1]
|
||||
db.add(models.User(id="u_" + name, username=name, is_active=active,
|
||||
email=(r[2] if len(r) > 2 else "")))
|
||||
db.commit()
|
||||
|
||||
|
||||
def state():
|
||||
with Session() as db:
|
||||
users = {u.username: u.is_active for u in db.scalars(select(models.User))}
|
||||
audits = [a.to_dict() for a in db.scalars(select(models.AuditLog))]
|
||||
return users, audits
|
||||
|
||||
|
||||
def fixed(*pairs):
|
||||
return lambda: [OktaUser(identity=i, status=s) for i, s in pairs]
|
||||
|
||||
|
||||
# ── 1. the failure rule ───────────────────────────────────────────────────────
|
||||
print("\n1. FAIL CLOSED: a failed or untrusted fetch changes nothing")
|
||||
BASE = [("alice", True), ("bob", True), ("carol", True)]
|
||||
|
||||
|
||||
def boom(exc):
|
||||
def f():
|
||||
raise exc
|
||||
return f
|
||||
|
||||
|
||||
failing = [
|
||||
("OktaSyncError (auth failure)", boom(OktaSyncError("HTTP 401"))),
|
||||
("RuntimeError", boom(RuntimeError("boom"))),
|
||||
("ConnectionError", boom(ConnectionError("down"))),
|
||||
("TimeoutError", boom(TimeoutError("slow"))),
|
||||
("ValueError", boom(ValueError("bad"))),
|
||||
("KeyError", boom(KeyError("x"))),
|
||||
("fetch returns an empty list", lambda: []),
|
||||
("fetch returns None", lambda: None),
|
||||
("fetch returns garbage (strings)", lambda: ["alice", "bob"]),
|
||||
("fetch returns garbage (dicts)", lambda: [{"identity": "alice"}]),
|
||||
]
|
||||
for label, fetch in failing:
|
||||
seed(BASE)
|
||||
before = state()
|
||||
with Session() as db:
|
||||
res = run_sync(db, fetch=fetch)
|
||||
after = state()
|
||||
chk(f"{label}: ok is False", res.ok is False)
|
||||
chk(f"{label}: zero accounts changed", after[0] == before[0] == {"alice": True, "bob": True, "carol": True})
|
||||
chk(f"{label}: zero audit rows", after[1] == [] and res.disabled == [])
|
||||
|
||||
print("\n ...and through the real client, not a stand-in")
|
||||
okta_auth.ISSUER = "https://example.okta.com/oauth2/default"
|
||||
os.environ["OKTA_API_TOKEN"] = "tok"
|
||||
for code in (401, 403, 429, 500):
|
||||
seed(BASE)
|
||||
c = httpx.Client(transport=httpx.MockTransport(lambda r, k=code: httpx.Response(k, json={})))
|
||||
with Session() as db:
|
||||
res = run_sync(db, fetch=lambda c=c: okta_sync.fetch_users(http=c))
|
||||
u, a = state()
|
||||
chk(f"real client, HTTP {code}: nothing changed, no audit rows",
|
||||
(not res.ok) and all(u.values()) and a == [])
|
||||
seed(BASE)
|
||||
os.environ["OKTA_API_TOKEN"] = ""
|
||||
with Session() as db:
|
||||
res = run_sync(db) # fetch=None: the default path, no token set
|
||||
u, a = state()
|
||||
chk("default fetch with no token: nothing changed, no audit rows", (not res.ok) and all(u.values()) and a == [])
|
||||
|
||||
print("\n ...and when saving fails")
|
||||
seed(BASE)
|
||||
with Session() as db:
|
||||
real_commit = db.commit
|
||||
|
||||
def bad_commit():
|
||||
raise RuntimeError("disk full")
|
||||
|
||||
db.commit = bad_commit
|
||||
res = run_sync(db, fetch=fixed(("alice", "ACTIVE"))) # bob and carol would be disabled
|
||||
u, a = state()
|
||||
chk("a failed commit keeps no change and no audit row", (not res.ok) and all(u.values()) and a == [])
|
||||
|
||||
print("\n ...and when no local account matches any Okta user (wrong identity attribute)")
|
||||
seed(BASE)
|
||||
with Session() as db:
|
||||
res = run_sync(db, fetch=fixed(("zed@x.com", "ACTIVE"), ("yan@x.com", "ACTIVE")))
|
||||
u, a = state()
|
||||
chk("zero matches is refused, not read as 'everyone left'", (not res.ok) and all(u.values()) and a == [])
|
||||
chk("...and the error says why", "identity attribute" in res.error)
|
||||
|
||||
# ── 2. what it does disable ───────────────────────────────────────────────────
|
||||
print("\n2. a good run disables the right accounts")
|
||||
seed([("alice", True), ("bob", True), ("carol", True), ("dave", True),
|
||||
("erin", True), ("frank", True), ("gina", True), ("hank", True)])
|
||||
okta = fixed(("alice", "ACTIVE"), ("bob", "SUSPENDED"),
|
||||
# carol is MISSING from the list
|
||||
("dave", "DEPROVISIONED"), ("erin", "PASSWORD_EXPIRED"),
|
||||
("frank", "LOCKED_OUT"), ("gina", "RECOVERY"), ("hank", "ACTIVE"))
|
||||
with Session() as db:
|
||||
res = run_sync(db, fetch=okta)
|
||||
users, audits = state()
|
||||
chk("run is ok", res.ok, res.error)
|
||||
chk("missing, SUSPENDED and DEPROVISIONED are disabled",
|
||||
sorted(res.disabled) == ["bob", "carol", "dave"] and
|
||||
[users[n] for n in ("bob", "carol", "dave")] == [False, False, False])
|
||||
chk("ACTIVE stays active", users["alice"] is True and users["hank"] is True)
|
||||
chk("PASSWORD_EXPIRED, LOCKED_OUT and RECOVERY do NOT disable (temporary states)",
|
||||
users["erin"] is True and users["frank"] is True and users["gina"] is True)
|
||||
chk("one audit row per disabled account", len(audits) == 3, str(len(audits)))
|
||||
row = next(a for a in audits if a["summary"] == "bob")
|
||||
chk("audit actor is the sync job, not a person", {a["actor"] for a in audits} == {"system:okta_sync"})
|
||||
chk("audit action is user_deprovisioned_by_sync", {a["action"] for a in audits} == {"user_deprovisioned_by_sync"})
|
||||
chk("audit row names the user and the Okta status found",
|
||||
row["entity_type"] == "user" and row["entity_id"] == "u_bob" and row["detail"].get("okta_status") == "SUSPENDED")
|
||||
chk("a missing user is recorded as MISSING",
|
||||
next(a for a in audits if a["summary"] == "carol")["detail"].get("okta_status") == "MISSING")
|
||||
|
||||
print("\n ...run it again: only changes are logged")
|
||||
with Session() as db:
|
||||
res2 = run_sync(db, fetch=okta)
|
||||
users2, audits2 = state()
|
||||
chk("second run is ok, disables nobody", res2.ok and res2.disabled == [])
|
||||
chk("second run writes no new audit rows (no duplicates)", len(audits2) == 3)
|
||||
chk("accounts unchanged by the second run", users2 == users)
|
||||
|
||||
# ── 3. never re-enables, never touches a disabled account ─────────────────────
|
||||
print("\n3. never re-enables, never touches an already-disabled account")
|
||||
seed([("alice", True), ("hank", False), ("gina", False)])
|
||||
with Session() as db:
|
||||
res = run_sync(db, fetch=fixed(("alice", "ACTIVE"), ("hank", "ACTIVE"))) # gina missing
|
||||
users, audits = state()
|
||||
chk("a disabled account that is ACTIVE in Okta stays disabled", users["hank"] is False)
|
||||
chk("a disabled account that is missing from Okta stays as it is", users["gina"] is False)
|
||||
chk("no audit row for either (nothing changed)", audits == [] and res.disabled == [])
|
||||
src = open(os.path.join(ROOT, "server", "okta_sync.py")).read()
|
||||
chk("no assignment of is_active to True anywhere in okta_sync.py",
|
||||
"is_active = True" not in src and "is_active=True" not in src.replace("is_active.is_(True)", ""))
|
||||
|
||||
# ── 4. matching ───────────────────────────────────────────────────────────────
|
||||
print("\n4. matching")
|
||||
seed([("ALICE", True), ("bob", True, "Bob@X.com"), ("carol", True)])
|
||||
with Session() as db:
|
||||
res = run_sync(db, fetch=fixed(("alice", "ACTIVE"), ("bob@x.com", "ACTIVE"), ("carol", "SUSPENDED")))
|
||||
users, _ = state()
|
||||
chk("username match ignores case", users["ALICE"] is True)
|
||||
chk("email match works, ignoring case", users["bob"] is True)
|
||||
chk("a matching SUSPENDED user is disabled", users["carol"] is False)
|
||||
|
||||
seed([("alice", True), ("bob", True), ("carol", True)])
|
||||
with Session() as db:
|
||||
run_sync(db, fetch=fixed(("alice", "ACTIVE"), ("bob", "ACTIVE"), ("bob", "SUSPENDED"),
|
||||
("carol", "SUSPENDED"), ("carol", "DEPROVISIONED")))
|
||||
users, _ = state()
|
||||
chk("an identity listed twice, one entry active: stays active", users["bob"] is True)
|
||||
chk("an identity listed twice, every entry disabling: disabled", users["carol"] is False)
|
||||
|
||||
# ── 5. the secret never reaches the audit row or the result ───────────────────
|
||||
print("\n5. no secret in what is stored or returned")
|
||||
seed(BASE)
|
||||
os.environ["OKTA_API_TOKEN"] = "SECRET-TOKEN-123"
|
||||
c = httpx.Client(transport=httpx.MockTransport(lambda r: httpx.Response(401, json={})))
|
||||
with Session() as db:
|
||||
res = run_sync(db, fetch=lambda: okta_sync.fetch_users(http=c))
|
||||
chk("the failure message has no token", "SECRET-TOKEN-123" not in res.error and "example.okta.com" not in res.error)
|
||||
|
||||
print()
|
||||
print("ALL PASSED" if not fails else f"{fails} FAILED")
|
||||
sys.exit(0 if not fails else 1)
|
||||
242
tests/okta_sync_schedule_check.py
Normal file
242
tests/okta_sync_schedule_check.py
Normal file
@@ -0,0 +1,242 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Does the Okta sync run on a schedule without doubling up? - D18 / T13.4.
|
||||
|
||||
The api container runs 2 gunicorn workers, and each starts its own timer. Checked
|
||||
here: exactly one of them wins each cycle (including a race on a real file
|
||||
database), a restart inside the interval does not start a second run, the
|
||||
interval is configurable and cannot go below the minimum, the timer thread starts
|
||||
and stops, nothing starts when the sync is not configured, and a failure inside
|
||||
the scheduled path still changes nothing.
|
||||
|
||||
Self-contained: a throwaway SQLite file, threads, no server, no network, no browser.
|
||||
Exit 0 all passed, 1 a failure.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
from sqlalchemy import create_engine, select # noqa: E402
|
||||
from sqlalchemy.orm import sessionmaker # noqa: E402
|
||||
|
||||
from server import models, okta_auth, okta_sync # noqa: E402
|
||||
from server.okta_sync import OktaSyncError, OktaUser # noqa: E402
|
||||
|
||||
fails = 0
|
||||
|
||||
|
||||
def chk(label, ok, extra=""):
|
||||
global fails
|
||||
print(("PASS " if ok else "FAIL ") + label + (f" [{extra}]" if (extra and not ok) else ""))
|
||||
if not ok:
|
||||
fails += 1
|
||||
|
||||
|
||||
tmp = tempfile.mkdtemp(prefix="oktasync_")
|
||||
engine = create_engine(f"sqlite:///{os.path.join(tmp, 't.db')}",
|
||||
connect_args={"check_same_thread": False, "timeout": 20}, future=True)
|
||||
models.Base.metadata.create_all(engine)
|
||||
Session = sessionmaker(bind=engine, autoflush=False, future=True)
|
||||
INTERVAL = 900
|
||||
os.environ["OKTA_SYNC_INTERVAL_SECONDS"] = str(INTERVAL)
|
||||
T0 = datetime(2026, 10, 16, 12, 0, 0, tzinfo=timezone.utc)
|
||||
|
||||
|
||||
def wipe(users=()):
|
||||
with Session() as db:
|
||||
db.query(models.AuditLog).delete()
|
||||
db.query(models.User).delete()
|
||||
db.query(models.AppSetting).filter(models.AppSetting.key == okta_sync.CLAIM_KEY).delete()
|
||||
for name, active in users:
|
||||
db.add(models.User(id="u_" + name, username=name, is_active=active))
|
||||
db.commit()
|
||||
|
||||
|
||||
def users_state():
|
||||
with Session() as db:
|
||||
return ({u.username: u.is_active for u in db.scalars(select(models.User))},
|
||||
db.query(models.AuditLog).count())
|
||||
|
||||
|
||||
# ── 1. interval ───────────────────────────────────────────────────────────────
|
||||
print("\n1. interval")
|
||||
def iv(v):
|
||||
if v is None:
|
||||
os.environ.pop("OKTA_SYNC_INTERVAL_SECONDS", None)
|
||||
else:
|
||||
os.environ["OKTA_SYNC_INTERVAL_SECONDS"] = v
|
||||
return okta_sync.interval_seconds()
|
||||
|
||||
chk("default is 900 seconds (15 minutes)", iv(None) == 900 and iv("") == 900)
|
||||
chk("an env value is used", iv("600") == 600 and iv("3600") == 3600)
|
||||
chk("not a number: the default", iv("soon") == 900 and iv("1.5") == 900)
|
||||
chk("under the minimum is raised to 300 (a slow cycle can never overlap the next)",
|
||||
iv("60") == 300 and iv("0") == 300 and iv("-5") == 300)
|
||||
chk("a fetch is bounded below the minimum interval",
|
||||
okta_sync.TOTAL_DEADLINE_SECONDS < okta_sync.INTERVAL_MIN_SECONDS)
|
||||
iv(str(INTERVAL))
|
||||
|
||||
# ── 2. the claim ──────────────────────────────────────────────────────────────
|
||||
print("\n2. the claim gate")
|
||||
wipe()
|
||||
with Session() as db:
|
||||
chk("first ever claim wins (the insert is the claim)", okta_sync.claim(db, INTERVAL, now=T0) is True)
|
||||
with Session() as db:
|
||||
chk("a second claim in the same instant loses", okta_sync.claim(db, INTERVAL, now=T0) is False)
|
||||
with Session() as db:
|
||||
chk("one second before the interval is up: loses",
|
||||
okta_sync.claim(db, INTERVAL, now=T0 + timedelta(seconds=INTERVAL - 1)) is False)
|
||||
with Session() as db:
|
||||
chk("when the interval is up: wins",
|
||||
okta_sync.claim(db, INTERVAL, now=T0 + timedelta(seconds=INTERVAL)) is True)
|
||||
with Session() as db:
|
||||
chk("and then the next caller loses again",
|
||||
okta_sync.claim(db, INTERVAL, now=T0 + timedelta(seconds=INTERVAL + 1)) is False)
|
||||
|
||||
# ── 3. the race ───────────────────────────────────────────────────────────────
|
||||
print("\n3. exactly one of many workers wins (a real race on a file database)")
|
||||
|
||||
|
||||
def race(n=8):
|
||||
barrier = threading.Barrier(n)
|
||||
wins, errors = [], []
|
||||
|
||||
def worker():
|
||||
try:
|
||||
with Session() as db:
|
||||
barrier.wait()
|
||||
wins.append(okta_sync.claim(db, INTERVAL, now=datetime.now(timezone.utc)))
|
||||
except Exception as exc: # a lost race may surface as an error
|
||||
errors.append(type(exc).__name__)
|
||||
wins.append(False)
|
||||
|
||||
ts = [threading.Thread(target=worker) for _ in range(n)]
|
||||
[t.start() for t in ts]
|
||||
[t.join() for t in ts]
|
||||
return sum(1 for w in wins if w), errors
|
||||
|
||||
|
||||
wipe()
|
||||
won, errs = race()
|
||||
chk("no row yet, 8 workers at once: exactly 1 wins (the insert race)", won == 1, f"{won} {errs}")
|
||||
bad = []
|
||||
for i in range(15):
|
||||
with Session() as db: # age the claim so the next race is due again
|
||||
db.query(models.AppSetting).filter(models.AppSetting.key == okta_sync.CLAIM_KEY).update(
|
||||
{"updated_at": datetime.now(timezone.utc) - timedelta(seconds=INTERVAL + 5)})
|
||||
db.commit()
|
||||
won, errs = race()
|
||||
if won != 1:
|
||||
bad.append((i, won, errs))
|
||||
chk("row due, 8 workers at once, 15 rounds: exactly 1 wins every round", not bad, str(bad))
|
||||
|
||||
# ── 4. one tick ───────────────────────────────────────────────────────────────
|
||||
print("\n4. a tick runs the sync once per cycle")
|
||||
wipe([("alice", True), ("bob", True)])
|
||||
calls = []
|
||||
|
||||
|
||||
def fetch_ok():
|
||||
calls.append(1)
|
||||
return [OktaUser("alice", "ACTIVE"), OktaUser("bob", "SUSPENDED")]
|
||||
|
||||
|
||||
r1 = okta_sync.run_if_due(Session, fetch=fetch_ok, now=T0)
|
||||
chk("first tick claims and runs", r1 is not None and r1.ok and r1.disabled == ["bob"])
|
||||
r2 = okta_sync.run_if_due(Session, fetch=fetch_ok, now=T0 + timedelta(seconds=30))
|
||||
chk("a tick 30 seconds later does nothing (not due)", r2 is None and len(calls) == 1)
|
||||
r3 = okta_sync.run_if_due(Session, fetch=fetch_ok, now=T0 + timedelta(seconds=INTERVAL))
|
||||
chk("a tick when due runs again", r3 is not None and r3.ok and len(calls) == 2)
|
||||
|
||||
print("\n ...a restart inside the interval does not start a second run")
|
||||
wipe([("alice", True), ("bob", True)])
|
||||
calls.clear()
|
||||
okta_sync.run_if_due(Session, fetch=fetch_ok, now=T0)
|
||||
# "restart": a brand-new caller with nothing in memory, 2 minutes later
|
||||
r = okta_sync.run_if_due(Session, fetch=fetch_ok, now=T0 + timedelta(seconds=120))
|
||||
chk("the claim row outlives the process: no duplicate run", r is None and len(calls) == 1)
|
||||
|
||||
print("\n ...two workers tick in the same instant")
|
||||
wipe([("alice", True), ("bob", True)])
|
||||
calls.clear()
|
||||
results = []
|
||||
barrier = threading.Barrier(2)
|
||||
|
||||
|
||||
def tick():
|
||||
barrier.wait()
|
||||
results.append(okta_sync.run_if_due(Session, fetch=fetch_ok))
|
||||
|
||||
|
||||
ts = [threading.Thread(target=tick) for _ in range(2)]
|
||||
[t.start() for t in ts]
|
||||
[t.join() for t in ts]
|
||||
chk("Okta is asked once, not twice", len(calls) == 1, str(len(calls)))
|
||||
chk("exactly one worker got a result", sum(1 for r in results if r is not None) == 1)
|
||||
_, audits = users_state()
|
||||
chk("one audit row, not two", audits == 1, str(audits))
|
||||
|
||||
# ── 5. fail closed through the scheduled path ─────────────────────────────────
|
||||
print("\n5. FAIL CLOSED through the scheduled wrapper (not just run_sync)")
|
||||
for label, exc in (("OktaSyncError", OktaSyncError("HTTP 500")), ("RuntimeError", RuntimeError("x")),
|
||||
("TimeoutError", TimeoutError("t"))):
|
||||
wipe([("alice", True), ("bob", True)])
|
||||
|
||||
def failing(e=exc):
|
||||
raise e
|
||||
|
||||
r = okta_sync.run_if_due(Session, fetch=failing, now=T0)
|
||||
u, a = users_state()
|
||||
chk(f"{label} in the scheduled path: ok is False, zero changes, zero audit rows",
|
||||
r is not None and r.ok is False and all(u.values()) and a == 0)
|
||||
|
||||
wipe([("alice", True), ("bob", True)])
|
||||
|
||||
|
||||
def broken_factory():
|
||||
raise RuntimeError("database is down")
|
||||
|
||||
|
||||
chk("the database failing at claim time: the tick ends quietly, returns None",
|
||||
okta_sync.run_if_due(broken_factory, fetch=fetch_ok, now=T0) is None)
|
||||
u, a = users_state()
|
||||
chk("...and nothing changed", all(u.values()) and a == 0)
|
||||
|
||||
# ── 6. the thread ─────────────────────────────────────────────────────────────
|
||||
print("\n6. the timer thread")
|
||||
os.environ["OKTA_API_TOKEN"] = ""
|
||||
okta_auth.ISSUER = "https://example.okta.com/oauth2/default"
|
||||
chk("no token: nothing starts", okta_sync.start_scheduler(Session) is None)
|
||||
chk("...no thread named okta-sync", not any(t.name == "okta-sync" for t in threading.enumerate()))
|
||||
|
||||
os.environ["OKTA_API_TOKEN"] = "tok"
|
||||
wipe([("alice", True), ("bob", True)])
|
||||
okta_sync.START_DELAY_SECONDS = 0.05
|
||||
okta_sync.TICK_SECONDS = 0.05
|
||||
ran = []
|
||||
real_fetch = okta_sync.fetch_users
|
||||
okta_sync.fetch_users = lambda http=None: (ran.append(1) or
|
||||
[OktaUser("alice", "ACTIVE"), OktaUser("bob", "DEPROVISIONED")])
|
||||
stop = okta_sync.start_scheduler(Session)
|
||||
chk("configured: a stop Event comes back", stop is not None)
|
||||
time.sleep(1.2) # about 20 ticks
|
||||
u, a = users_state()
|
||||
chk("the thread ran the sync on its own (bob was disabled without a manual call)", u["bob"] is False)
|
||||
chk("many ticks, one run (the claim gate holds)", len(ran) == 1 and a == 1, f"ran={len(ran)} audits={a}")
|
||||
th = [t for t in threading.enumerate() if t.name == "okta-sync"]
|
||||
chk("one timer thread is alive", len(th) == 1 and th[0].is_alive())
|
||||
chk("the thread is a daemon (never blocks shutdown)", th[0].daemon)
|
||||
stop.set()
|
||||
th[0].join(timeout=3)
|
||||
chk("setting the stop Event ends the thread", not th[0].is_alive())
|
||||
okta_sync.fetch_users = real_fetch
|
||||
os.environ["OKTA_API_TOKEN"] = ""
|
||||
|
||||
print()
|
||||
print("ALL PASSED" if not fails else f"{fails} FAILED")
|
||||
sys.exit(0 if not fails else 1)
|
||||
153
tests/okta_sync_ui_check.py
Normal file
153
tests/okta_sync_ui_check.py
Normal file
@@ -0,0 +1,153 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Does an auto-disable read clearly in the admin console? - D18 / T13.5.
|
||||
|
||||
T13.5 builds no new UI. It confirms that an account the Okta sync disabled shows
|
||||
up legibly in the surface admins already use (the Activity log card on
|
||||
admin.html), without special-casing, and that the disabled account is refused on
|
||||
its very next request. This runs the REAL sync against a throwaway database,
|
||||
then reads the real page in a headless browser at 1440px and 390px.
|
||||
|
||||
It does not rely on CR-019's Activity & usage card: only the Activity log card
|
||||
(AuditLog) is read.
|
||||
|
||||
Boots its own throwaway SQLite + uvicorn + headless browser; run it alone.
|
||||
Screenshots go to a folder printed at the end (WP_SHOTS_DIR overrides it).
|
||||
Exit 0 all passed, 1 a failure, 2 could not run.
|
||||
"""
|
||||
import json
|
||||
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
|
||||
|
||||
|
||||
def ascii_(v, n=300):
|
||||
return re.sub(r"\s+", " ", str(v)).encode("ascii", "replace").decode()[:n]
|
||||
|
||||
|
||||
ROWS_JS = """JSON.stringify([...document.querySelectorAll('#audit-admin tbody tr')].map(
|
||||
tr => [...tr.children].map(td => td.textContent.trim())))"""
|
||||
|
||||
|
||||
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-syncui-")
|
||||
shots = os.environ.get("WP_SHOTS_DIR") or os.path.join(tmpdir, "shots")
|
||||
db_path = os.path.join(tmpdir, "check.db")
|
||||
server = browser = None
|
||||
try:
|
||||
tok = seed(db_path)
|
||||
|
||||
print("\n1. run the real sync against the throwaway database")
|
||||
from server.db import SessionLocal
|
||||
from server import okta_sync
|
||||
from server.okta_sync import OktaUser
|
||||
okta = lambda: [OktaUser("root", "ACTIVE"), OktaUser("sue", "ACTIVE"),
|
||||
OktaUser("pat", "SUSPENDED"), OktaUser("mix", "ACTIVE"),
|
||||
OktaUser("sam", "ACTIVE"), OktaUser("legacy", "ACTIVE")] # bob is missing
|
||||
with SessionLocal() as db:
|
||||
res = okta_sync.run_sync(db, fetch=okta)
|
||||
chk("the sync disabled pat (SUSPENDED) and bob (missing)",
|
||||
res.ok and sorted(res.disabled) == ["bob", "pat"], ascii_((res.ok, res.error, res.disabled)))
|
||||
|
||||
port = cdp.free_port()
|
||||
base = "http://127.0.0.1:%d" % port
|
||||
server = start_server(port, db_path)
|
||||
if not server:
|
||||
print("the server did not start")
|
||||
return 2
|
||||
|
||||
print("\n2. a disabled account is refused on its very next request")
|
||||
st, _ = api(base, "/api/auth/me", tok["pat"])
|
||||
chk("pat (auto-disabled) is refused", st in (401, 403), st)
|
||||
st, _ = api(base, "/api/auth/me", tok["bob"])
|
||||
chk("bob (auto-disabled) is refused", st in (401, 403), st)
|
||||
st, _ = api(base, "/api/auth/me", tok["mix"])
|
||||
chk("mix (still active in Okta) still works", st == 200, st)
|
||||
|
||||
print("\n3. the audit rows through the API")
|
||||
st, audit = api(base, "/api/audit?entity_type=user&limit=50", tok["root"])
|
||||
mine = [e for e in (audit or []) if e.get("actor") == "system:okta_sync"]
|
||||
chk("an admin gets both rows", st == 200 and len(mine) == 2, ascii_((st, len(mine))))
|
||||
chk("each row names the action, the user, and the Okta status",
|
||||
{(e["summary"], e["detail"].get("okta_status")) for e in mine} == {("pat", "SUSPENDED"), ("bob", "MISSING")},
|
||||
ascii_([(e["summary"], e["detail"]) for e in mine]))
|
||||
st, audit_sue = api(base, "/api/audit?entity_type=user&limit=50", tok["sue"])
|
||||
chk("a project super user does not see them (they belong to no project)",
|
||||
st == 200 and not [e for e in audit_sue if e.get("actor") == "system:okta_sync"])
|
||||
|
||||
print("\n4. the admin console, as an admin")
|
||||
browser = cdp.Browser(exe)
|
||||
page = browser.page()
|
||||
for width, label in ((1440, "1440"), (390, "390")):
|
||||
page.clear_cookies()
|
||||
page.set_cookie("wp_session", tok["root"])
|
||||
page.viewport(width, 900, mobile=(width < 500))
|
||||
page.goto(base + "/admin.html")
|
||||
time.sleep(2.0)
|
||||
page.eval("void loadAudit()")
|
||||
time.sleep(1.2)
|
||||
rows = json.loads(page.eval(ROWS_JS) or "[]")
|
||||
sync_rows = [r for r in rows if "system:okta_sync" in r]
|
||||
chk("[%s] the Activity log lists both auto-disables" % label, len(sync_rows) == 2,
|
||||
ascii_(rows[:4]))
|
||||
if sync_rows:
|
||||
r = next((x for x in sync_rows if "pat" in x), sync_rows[0])
|
||||
# columns: When, Who, Action, Type, Item, Detail
|
||||
chk("[%s] Who reads 'system:okta_sync', not a person" % label, r[1] == "system:okta_sync", r)
|
||||
chk("[%s] Action reads 'user deprovisioned by sync'" % label,
|
||||
r[2] == "user deprovisioned by sync", r)
|
||||
chk("[%s] Type and Item name the account" % label, r[3] == "user" and r[4] == "pat", r)
|
||||
chk("[%s] Detail gives the Okta status found" % label,
|
||||
"SUSPENDED" in r[5] and "okta" in r[5].lower(), r)
|
||||
miss = next((x for x in sync_rows if "bob" in x), None)
|
||||
chk("[%s] a person missing from Okta reads 'MISSING'" % label,
|
||||
bool(miss) and "MISSING" in miss[5], miss)
|
||||
# filter + search work on it with no special-casing
|
||||
page.eval("document.getElementById('audit-search').value='okta_sync'; renderAudit();")
|
||||
rows = json.loads(page.eval(ROWS_JS) or "[]")
|
||||
chk("[%s] searching 'okta_sync' finds exactly the sync rows" % label,
|
||||
len(rows) == 2 and all("system:okta_sync" in r for r in rows), ascii_(rows))
|
||||
page.eval("document.getElementById('audit-search').value='';"
|
||||
"document.getElementById('audit-type').value='user'; renderAudit();")
|
||||
rows = json.loads(page.eval(ROWS_JS) or "[]")
|
||||
chk("[%s] the 'User accounts' filter keeps them" % label,
|
||||
len([r for r in rows if "system:okta_sync" in r]) == 2)
|
||||
page.eval("document.getElementById('audit-type').value=''; renderAudit();")
|
||||
over = page.eval("document.documentElement.scrollWidth - document.documentElement.clientWidth")
|
||||
chk("[%s] no sideways scroll on the page" % label, (over or 0) <= 0, over)
|
||||
card = page.eval("(()=>{const e=document.getElementById('audit-admin');"
|
||||
"e.scrollIntoView();return e.getBoundingClientRect().width>0})()")
|
||||
chk("[%s] the card is on screen" % label, bool(card))
|
||||
time.sleep(0.4)
|
||||
page.screenshot(os.path.join(shots, "admin-activity-log-%s.png" % label), full_page=False)
|
||||
errs = [e for e in page.js_errors() if "beforeunload" not in e]
|
||||
chk("no JavaScript errors", not errs, ascii_(errs[:3]))
|
||||
print("\n screenshots: " + shots)
|
||||
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())
|
||||
236
tests/session_idle_check.py
Normal file
236
tests/session_idle_check.py
Normal file
@@ -0,0 +1,236 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Does the sliding session with a hard ceiling work? - D18 / T13.1 (checked in T13.6).
|
||||
|
||||
T13.1 shipped with its done-when list unchecked and no test of its own; the old
|
||||
session tests had no idea about idle time. This is that test.
|
||||
|
||||
1. Continuous activity keeps a session alive past 30 minutes, but never past the
|
||||
absolute ceiling (AUTH_SESSION_HOURS) measured from the ORIGINAL sign-in.
|
||||
2. A session idle for more than 30 minutes is refused on its next request.
|
||||
3. The cookie is not rewritten on every request (the refresh is throttled).
|
||||
4. A token from before this shipped (no login_at) still gets a hard ceiling,
|
||||
from its iat.
|
||||
5. A refresh carries identity and login_at forward unchanged.
|
||||
6. The two variables are documented, and both defaults are flagged as proposed.
|
||||
|
||||
Self-contained: throwaway SQLite, in-process test client, no network, no browser.
|
||||
Exit 0 all passed, 1 a failure.
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, ROOT)
|
||||
os.environ["DATABASE_URL"] = "sqlite:///" + os.path.join(tempfile.mkdtemp(prefix="wp-idle-"), "t.db").replace("\\", "/")
|
||||
os.environ["AUTH_SECRET_KEY"] = "session-idle-check-secret-not-for-production"
|
||||
os.environ.pop("AUTH_IDLE_MINUTES", None)
|
||||
os.environ.pop("AUTH_SESSION_HOURS", None)
|
||||
|
||||
import jwt # noqa: E402
|
||||
from fastapi.testclient import TestClient # noqa: E402
|
||||
|
||||
from server import app as appmod, auth, models # noqa: E402
|
||||
from server.db import Base, SessionLocal, engine # noqa: E402
|
||||
|
||||
if not hasattr(auth, "maybe_refresh_token"):
|
||||
print("SKIP: T13.1 (sliding session) is not on this branch. It waits for T14.1.")
|
||||
sys.exit(0)
|
||||
|
||||
fails = 0
|
||||
|
||||
|
||||
def chk(label, ok, extra=""):
|
||||
global fails
|
||||
print(("PASS " if ok else "FAIL ") + label + (f" [{extra}]" if (extra and not ok) else ""))
|
||||
if not ok:
|
||||
fails += 1
|
||||
|
||||
|
||||
Base.metadata.create_all(bind=engine)
|
||||
with SessionLocal() as db:
|
||||
db.add(models.User(id="u1", username="alice", email="a@x.test", role=auth.ROLE_ADMIN))
|
||||
db.commit()
|
||||
USER = db.get(models.User, "u1")
|
||||
db.expunge(USER)
|
||||
|
||||
# A route the auth gate covers. NOT /api/auth/me: everything under /api/auth/ is
|
||||
# exempt from the gate (auth._EXEMPT_PREFIXES), so no session refresh happens there
|
||||
# and a probe on it would pass without testing anything.
|
||||
PROBE = "/api/projects"
|
||||
IDLE = auth.IDLE_MINUTES
|
||||
CEIL_H = auth.SESSION_HOURS
|
||||
NOW = datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def mint(login_at=None, iat=None, exp=None, **extra):
|
||||
"""A token with exactly the claims given (None = leave the claim out)."""
|
||||
p = {"sub": "u1", "username": "alice", "role": auth.ROLE_ADMIN, "ver": 0}
|
||||
if iat is not None:
|
||||
p["iat"] = iat
|
||||
if login_at is not None:
|
||||
p["login_at"] = login_at.timestamp()
|
||||
if exp is not None:
|
||||
p["exp"] = exp
|
||||
p.update(extra)
|
||||
return jwt.encode(p, auth.SECRET_KEY, algorithm=auth.JWT_ALG)
|
||||
|
||||
|
||||
def raw_claims(tok):
|
||||
return jwt.decode(tok, auth.SECRET_KEY, algorithms=[auth.JWT_ALG], options={"verify_exp": False, "verify_iat": False, "verify_nbf": False})
|
||||
|
||||
|
||||
class FakeClock(datetime):
|
||||
_now = NOW
|
||||
|
||||
@classmethod
|
||||
def now(cls, tz=None):
|
||||
return cls._now
|
||||
|
||||
|
||||
real_dt = auth.datetime
|
||||
|
||||
|
||||
def at(t):
|
||||
FakeClock._now = t
|
||||
auth.datetime = FakeClock
|
||||
|
||||
|
||||
def real():
|
||||
auth.datetime = real_dt
|
||||
|
||||
|
||||
print("defaults: idle %d min, ceiling %d h" % (IDLE, CEIL_H))
|
||||
|
||||
# ── 1. continuous activity, then the ceiling ──────────────────────────────────
|
||||
print("\n1. continuous activity stays alive past 30 minutes, but is cut off at the ceiling")
|
||||
at(NOW)
|
||||
tok = auth.create_token(USER)
|
||||
c = raw_claims(tok)
|
||||
chk("a new token carries login_at", "login_at" in c)
|
||||
chk("a new token expires one idle window out, not at the ceiling",
|
||||
abs(c["exp"] - (NOW + timedelta(minutes=IDLE)).timestamp()) < 2)
|
||||
login_at = NOW
|
||||
cur = c
|
||||
alive_past_30 = False
|
||||
rewrites = 0
|
||||
last_exp = cur["exp"]
|
||||
t = NOW
|
||||
STEP = timedelta(minutes=1) # an active user: a request every minute
|
||||
end = NOW + timedelta(hours=CEIL_H + 2)
|
||||
cut_off_at = None
|
||||
while t < end:
|
||||
t += STEP
|
||||
at(t)
|
||||
if cur["exp"] <= t.timestamp(): # the session already lapsed
|
||||
cut_off_at = t
|
||||
break
|
||||
if t - NOW > timedelta(minutes=IDLE):
|
||||
alive_past_30 = True
|
||||
new = auth.maybe_refresh_token(cur)
|
||||
if new:
|
||||
rewrites += 1
|
||||
cur = raw_claims(new)
|
||||
last_exp = cur["exp"]
|
||||
real()
|
||||
chk("with a request every minute the session is alive well past 30 minutes", alive_past_30)
|
||||
chk("it is never extended past the ceiling (last exp <= login + %d h)" % CEIL_H,
|
||||
last_exp <= (login_at + timedelta(hours=CEIL_H)).timestamp() + 1,
|
||||
str(datetime.fromtimestamp(last_exp, timezone.utc)))
|
||||
chk("it IS cut off once the ceiling is reached, however active the session",
|
||||
cut_off_at is not None and cut_off_at <= login_at + timedelta(hours=CEIL_H) + timedelta(minutes=IDLE) + STEP,
|
||||
str(cut_off_at))
|
||||
chk("the claims after the last refresh still carry the ORIGINAL login_at",
|
||||
abs(cur["login_at"] - login_at.timestamp()) < 1)
|
||||
steps = int((CEIL_H * 60) / 1)
|
||||
chk("the cookie was rewritten far less often than once per request (%d rewrites for ~%d requests)" % (rewrites, steps),
|
||||
0 < rewrites < steps / 5, f"{rewrites}/{steps}")
|
||||
|
||||
# ── 2. idle ───────────────────────────────────────────────────────────────────
|
||||
print("\n2. a session idle for more than %d minutes is refused on its next request" % IDLE)
|
||||
client = TestClient(appmod.app)
|
||||
idle_tok = mint(login_at=NOW - timedelta(minutes=IDLE + 1), iat=NOW - timedelta(minutes=IDLE + 1),
|
||||
exp=NOW - timedelta(minutes=1))
|
||||
client.cookies.set(auth.COOKIE_NAME, idle_tok)
|
||||
r = client.get(PROBE)
|
||||
chk("an idle session gets 401", r.status_code == 401, r.status_code)
|
||||
live_tok = mint(login_at=NOW - timedelta(minutes=5), iat=NOW - timedelta(minutes=5),
|
||||
exp=NOW + timedelta(minutes=IDLE - 5))
|
||||
client.cookies.clear()
|
||||
client.cookies.set(auth.COOKIE_NAME, live_tok)
|
||||
chk("a session inside the window gets 200", client.get(PROBE).status_code == 200)
|
||||
|
||||
# ── 3. throttle ───────────────────────────────────────────────────────────────
|
||||
print("\n3. the cookie is not rewritten on every request")
|
||||
fresh = auth.create_token(USER)
|
||||
client.cookies.clear()
|
||||
client.cookies.set(auth.COOKIE_NAME, fresh)
|
||||
cookies_set = 0
|
||||
for _ in range(20):
|
||||
r = client.get(PROBE)
|
||||
if "set-cookie" in r.headers and auth.COOKIE_NAME in r.headers["set-cookie"]:
|
||||
cookies_set += 1
|
||||
chk("20 rapid requests on a fresh session: 0 cookie rewrites", cookies_set == 0, cookies_set)
|
||||
|
||||
aged = mint(login_at=NOW - timedelta(minutes=20), iat=NOW - timedelta(minutes=20),
|
||||
exp=NOW + timedelta(minutes=2)) # 2 minutes of idle window left
|
||||
client.cookies.clear()
|
||||
client.cookies.set(auth.COOKIE_NAME, aged)
|
||||
r = client.get(PROBE)
|
||||
chk("an aged session gets a refreshed cookie on its next request",
|
||||
r.status_code == 200 and auth.COOKIE_NAME in r.headers.get("set-cookie", ""))
|
||||
m = re.search(auth.COOKIE_NAME + r"=([^;]+)", r.headers.get("set-cookie", ""))
|
||||
newc = raw_claims(m.group(1)) if m else {}
|
||||
chk("the refreshed cookie keeps the original login_at",
|
||||
abs(newc.get("login_at", 0) - (NOW - timedelta(minutes=20)).timestamp()) < 1)
|
||||
client.cookies.clear()
|
||||
client.cookies.set(auth.COOKIE_NAME, m.group(1) if m else "")
|
||||
r2 = client.get(PROBE)
|
||||
chk("...and the very next request does not rewrite it again", auth.COOKIE_NAME not in r2.headers.get("set-cookie", ""))
|
||||
|
||||
# ── 4. tokens from before D18 ─────────────────────────────────────────────────
|
||||
print("\n4. a token with no login_at still gets a hard ceiling (via iat)")
|
||||
old = {"sub": "u1", "username": "alice", "role": auth.ROLE_ADMIN, "ver": 0,
|
||||
"iat": (NOW - timedelta(hours=CEIL_H + 1)).timestamp(),
|
||||
"exp": (NOW + timedelta(hours=3)).timestamp()} # the old flat 12 h exp, still valid
|
||||
chk("past its iat-based ceiling: no refresh, the old exp is not extended", auth.maybe_refresh_token(old) is None)
|
||||
young = {"sub": "u1", "username": "alice", "role": auth.ROLE_ADMIN, "ver": 0,
|
||||
"iat": (NOW - timedelta(hours=1)).timestamp(),
|
||||
"exp": (NOW + timedelta(minutes=2)).timestamp()}
|
||||
ref = auth.maybe_refresh_token(young)
|
||||
rc = raw_claims(ref) if ref else {}
|
||||
chk("inside the ceiling: refreshed, and login_at is taken from iat (not 'now')",
|
||||
bool(ref) and abs(rc["login_at"] - young["iat"]) < 1)
|
||||
chk("the refreshed token cannot outlive iat + ceiling",
|
||||
bool(ref) and rc["exp"] <= young["iat"] + CEIL_H * 3600 + 1)
|
||||
nothing = {"sub": "u1", "username": "alice", "role": auth.ROLE_ADMIN, "ver": 0,
|
||||
"exp": (NOW + timedelta(minutes=2)).timestamp()}
|
||||
chk("no login_at and no iat: no refresh, and no crash", auth.maybe_refresh_token(nothing) is None)
|
||||
junk = dict(young, login_at="not-a-number")
|
||||
chk("an unparseable login_at falls back to iat, no crash", auth.maybe_refresh_token(junk) is not None)
|
||||
|
||||
# ── 5. identity carried forward ───────────────────────────────────────────────
|
||||
print("\n5. a refresh carries the identity forward unchanged")
|
||||
src = {"sub": "u9", "username": "zed", "role": "project_admin", "ver": 7,
|
||||
"iat": (NOW - timedelta(minutes=20)).timestamp(),
|
||||
"login_at": (NOW - timedelta(minutes=20)).timestamp(),
|
||||
"exp": (NOW + timedelta(minutes=2)).timestamp()}
|
||||
rc = raw_claims(auth.maybe_refresh_token(src))
|
||||
chk("sub, username, role, ver are unchanged",
|
||||
(rc["sub"], rc["username"], rc["role"], rc["ver"]) == ("u9", "zed", "project_admin", 7))
|
||||
|
||||
# ── 6. documentation ──────────────────────────────────────────────────────────
|
||||
print("\n6. the two variables are documented, defaults flagged as proposed")
|
||||
env = open(os.path.join(ROOT, "server", ".env.example"), encoding="utf-8").read()
|
||||
dep = open(os.path.join(ROOT, "DEPLOYMENT.md"), encoding="utf-8").read()
|
||||
for name in ("AUTH_IDLE_MINUTES", "AUTH_SESSION_HOURS"):
|
||||
chk(f"{name} is in .env.example", name in env)
|
||||
chk(f"{name} is in DEPLOYMENT.md", name in dep)
|
||||
chk(".env.example calls the defaults proposed, not confirmed", re.search(r"propos", env, re.I) is not None)
|
||||
chk("DEPLOYMENT.md calls the defaults proposed, not confirmed", re.search(r"propos", dep, re.I) is not None)
|
||||
|
||||
print()
|
||||
print("ALL PASSED" if not fails else f"{fails} FAILED")
|
||||
sys.exit(0 if not fails else 1)
|
||||
@@ -1,192 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Is there exactly one analytics implementation, reported from admin? — D5, T7.10.
|
||||
|
||||
Usage analytics existed twice (creator + wizard), five of the nine colliding
|
||||
globals `creator-frame.md` counted, and the wizard's copy had no caller. One
|
||||
core survives in wp-usage.js; the pages keep thin track() wrappers; the report
|
||||
and its downloads live on the admin console behind the same role gate as the
|
||||
rest of that page. Keys are unchanged, so pre-move data still reads.
|
||||
|
||||
Self-contained: throwaway SQLite, its own uvicorn, headless Edge or Chrome.
|
||||
Exit 0 all passed, 1 a failure, 2 could not run.
|
||||
"""
|
||||
import json
|
||||
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 sections_check import set_sop # noqa: E402
|
||||
from stepper_check import dismiss_dialogs # noqa: E402
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
HTML = os.path.join(ROOT, "html")
|
||||
|
||||
|
||||
def ascii_(v, n=280):
|
||||
return re.sub(r"\s+", " ", str(v)).encode("ascii", "replace").decode()[:n]
|
||||
|
||||
|
||||
def settle(seconds=0.6):
|
||||
time.sleep(seconds)
|
||||
|
||||
|
||||
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 main():
|
||||
exe = cdp.find_browser()
|
||||
if not exe:
|
||||
print("no headless-capable browser found; set WP_BROWSER.")
|
||||
return 2
|
||||
|
||||
# ── 1. the grep half: one implementation, no leftover controls ───────────
|
||||
print("\n1. grep: one implementation, nothing unreferenced")
|
||||
files = {}
|
||||
for name in os.listdir(HTML):
|
||||
if name.endswith((".js", ".html")):
|
||||
files[name] = strip_js(open(os.path.join(HTML, name), encoding="utf-8").read())
|
||||
|
||||
core_defs = [n for n, src in files.items() if "window.WPUsage" in src]
|
||||
chk("the WPUsage core is defined in wp-usage.js and only there",
|
||||
core_defs == ["wp-usage.js"], ascii_(core_defs))
|
||||
chk("the pages record THROUGH it - no page touches the storage keys directly",
|
||||
all("wp_iwp_analytics_v1" not in src and "wp_suite_analytics_v1" not in src
|
||||
for n, src in files.items()
|
||||
if n not in ("wp-usage.js",) and n.endswith(".js")))
|
||||
leftovers = {n: re.findall(r"analyticsLoad|analyticsSave|downloadAnalytics|showAnalytics"
|
||||
r"|ANALYTICS_KEY|USAGE_KEY|usageLoad|downloadUsage", src)
|
||||
for n, src in files.items() if n != "wp-usage.js"}
|
||||
leftovers = {n: v for n, v in leftovers.items() if v}
|
||||
chk("none of the five colliding globals survives anywhere; grep confirms",
|
||||
not leftovers, ascii_(leftovers))
|
||||
chk("no analytics control remains on the creator or the wizard; grep confirms",
|
||||
"Usage data" not in files["wp-creation-index.html"]
|
||||
and "showAnalytics" not in files["work-package-suite.html"])
|
||||
chk("both storage keys survive, verbatim, in the core (data continuity)",
|
||||
"wp_iwp_analytics_v1" in files["wp-usage.js"]
|
||||
and "wp_suite_analytics_v1" in files["wp-usage.js"])
|
||||
|
||||
tmpdir = tempfile.mkdtemp(prefix="wpsuite-usage-")
|
||||
db_path = os.path.join(tmpdir, "check.db")
|
||||
server = None
|
||||
browser = None
|
||||
try:
|
||||
tok = seed(db_path)
|
||||
set_sop(db_path, {})
|
||||
port = cdp.free_port()
|
||||
base = "http://127.0.0.1:%d" % port
|
||||
server = start_server(port, db_path)
|
||||
|
||||
browser = cdp.Browser(exe)
|
||||
page = browser.page()
|
||||
page.clear_cookies()
|
||||
page.set_cookie("wp_session", tok["root"])
|
||||
page.viewport(1440, 900)
|
||||
|
||||
# ── 2. recording still works from both tools ─────────────────────────
|
||||
print("\n2. the tools still record")
|
||||
page.goto(base + "/wp-creation-index.html?project=projA")
|
||||
dismiss_dialogs(page)
|
||||
settle(2.0)
|
||||
# Plant a LEGACY-format event under the pre-move key: the done-when is
|
||||
# that data recorded before this task is still readable after it.
|
||||
page.eval("""(() => {
|
||||
const d = JSON.parse(localStorage.getItem('wp_iwp_analytics_v1')) || {events: []};
|
||||
d.events.unshift({ts: '2026-07-01T10:00:00Z', session: 's_legacy',
|
||||
event: 'legacy_probe_event', detail: null});
|
||||
localStorage.setItem('wp_iwp_analytics_v1', JSON.stringify(d));
|
||||
})()""")
|
||||
n0 = page.eval("WPUsage.load(WPUsage.KEYS.creator).events.length")
|
||||
page.eval("track('probe_event')")
|
||||
chk("the creator's track() still lands events under the old key",
|
||||
page.eval("WPUsage.load(WPUsage.KEYS.creator).events.length") == n0 + 1)
|
||||
|
||||
page.goto(base + "/work-package-suite.html?tab=sop")
|
||||
dismiss_dialogs(page)
|
||||
settle(2.0)
|
||||
n0 = page.eval("WPUsage.load(WPUsage.KEYS.wizard).events.length")
|
||||
page.eval("track('probe_event_wizard')")
|
||||
chk("the wizard's track() still lands events under its old key",
|
||||
page.eval("WPUsage.load(WPUsage.KEYS.wizard).events.length") == n0 + 1)
|
||||
wiz_errors = [e for e in page.js_errors() if "beforeunload" not in e]
|
||||
chk("...and the wizard page throws no errors without its old globals "
|
||||
"(the blocked-beforeunload console line is BL-020, filtered not hidden)",
|
||||
not wiz_errors, ascii_(wiz_errors[:2]))
|
||||
|
||||
# ── 3. the report, on admin, behind the admin gate ───────────────────
|
||||
print("\n3. the admin report")
|
||||
page.goto(base + "/admin.html")
|
||||
dismiss_dialogs(page)
|
||||
settle(2.0)
|
||||
page.eval("loadUsage()")
|
||||
settle(0.5)
|
||||
report = page.eval("(document.getElementById('usage-admin')||{textContent:''}).textContent")
|
||||
chk("usage data is reachable from admin.html, both tools reported",
|
||||
"Work package creator" in report and "SOP wizard" in report, ascii_(report, 160))
|
||||
chk("the pre-move legacy event is readable in the report",
|
||||
"legacy_probe_event" in report)
|
||||
chk("this session's fresh events are in it too",
|
||||
"probe_event" in report and "probe_event_wizard" in report)
|
||||
chk("each tool offers its download from the report",
|
||||
page.eval("[...document.querySelectorAll('#usage-admin button')].length") >= 2)
|
||||
|
||||
page.viewport(390, 844, mobile=True)
|
||||
settle(0.6)
|
||||
fits = page.eval("""(() => {
|
||||
const box = document.getElementById('usage-admin');
|
||||
return box && box.scrollWidth <= box.clientWidth + 2
|
||||
&& document.documentElement.scrollWidth <= 392;
|
||||
})()""")
|
||||
chk("the report is usable at 390px - no sideways scrolling", bool(fits))
|
||||
page.viewport(1440, 900)
|
||||
settle(0.4)
|
||||
|
||||
# The same role gate as the rest of the console: a non-admin sees the
|
||||
# denied card and no cards, this one included.
|
||||
page.clear_cookies()
|
||||
page.set_cookie("wp_session", tok["pat"])
|
||||
page.goto(base + "/admin.html")
|
||||
dismiss_dialogs(page)
|
||||
settle(2.0)
|
||||
chk("a non-administrator gets the denied notice, not the usage report",
|
||||
page.eval("""(() => {
|
||||
const denied = document.getElementById('admin-denied');
|
||||
const usage = document.getElementById('usage-admin');
|
||||
const visible = el => !!el && el.offsetParent !== null;
|
||||
return visible(denied) && !visible(usage);
|
||||
})()"""))
|
||||
|
||||
js_errors = [e for e in page.js_errors() if "beforeunload" not in e]
|
||||
chk("no JavaScript errors anywhere in this run", not js_errors,
|
||||
ascii_(js_errors[:2]))
|
||||
|
||||
finally:
|
||||
if browser is not None:
|
||||
try:
|
||||
browser.close()
|
||||
except Exception:
|
||||
pass
|
||||
if server is not None:
|
||||
try:
|
||||
server.terminate()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
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())
|
||||
Reference in New Issue
Block a user