2026-06-13 16:32:33 +02:00
|
|
|
# retoor <retoor@molodetz.nl>
|
|
|
|
|
|
|
|
|
|
import time
|
|
|
|
|
from datetime import datetime, timezone
|
|
|
|
|
import pytest
|
|
|
|
|
import requests
|
|
|
|
|
from tests.conftest import BASE_URL
|
|
|
|
|
from devplacepy.database import get_table, refresh_snapshot, set_setting
|
|
|
|
|
from devplacepy.utils import generate_uid, make_combined_slug
|
|
|
|
|
JSON_audit_log = {"Accept": "application/json"}
|
|
|
|
|
_counter_audit_log = [0]
|
|
|
|
|
@pytest.fixture(scope="module", autouse=True)
|
|
|
|
|
def _audit_test_settings(app_server):
|
|
|
|
|
# On a fresh DB init_db skips seeding the operational/upload settings (its
|
|
|
|
|
# `tables` snapshot predates site_settings creation), so those rows are
|
|
|
|
|
# absent and the admin settings form would INSERT them as "" - which both
|
|
|
|
|
# closes registration and makes consumers that do int("") crash. Seed sane
|
|
|
|
|
# values here so the form's empty submissions are skipped (existing key), and
|
|
|
|
|
# lift the per-IP rate limit since this file fires many mutating requests.
|
|
|
|
|
for key, value in {
|
|
|
|
|
"rate_limit_per_minute": "1000000",
|
|
|
|
|
"rate_limit_window_seconds": "60",
|
|
|
|
|
"registration_open": "1",
|
|
|
|
|
"maintenance_mode": "0",
|
|
|
|
|
"max_upload_size_mb": "10",
|
|
|
|
|
"allowed_file_types": "",
|
|
|
|
|
"max_attachments_per_resource": "10",
|
|
|
|
|
"session_max_age_days": "7",
|
|
|
|
|
"session_remember_days": "30",
|
|
|
|
|
"news_service_interval": "3600",
|
|
|
|
|
"news_grade_threshold": "7",
|
|
|
|
|
}.items():
|
|
|
|
|
set_setting(key, value)
|
|
|
|
|
yield
|
|
|
|
|
def _db_user(name):
|
|
|
|
|
# the user is created by the server subprocess; refresh the test-process
|
|
|
|
|
# SQLite snapshot before reading it back across the process boundary.
|
|
|
|
|
refresh_snapshot()
|
|
|
|
|
return get_table("users").find_one(username=name)
|
|
|
|
|
def _unique(prefix="au"):
|
|
|
|
|
_counter_audit_log[0] += 1
|
|
|
|
|
return f"{prefix}{int(time.time() * 1000)}{_counter_audit_log[0]}"
|
|
|
|
|
def _member():
|
|
|
|
|
name = _unique("aumem")
|
|
|
|
|
s = requests.Session()
|
|
|
|
|
s.post(
|
|
|
|
|
f"{BASE_URL}/auth/signup",
|
|
|
|
|
data={
|
|
|
|
|
"username": name,
|
|
|
|
|
"email": f"{name}@t.dev",
|
|
|
|
|
"password": "secret123",
|
|
|
|
|
"confirm_password": "secret123",
|
|
|
|
|
},
|
|
|
|
|
allow_redirects=True,
|
|
|
|
|
)
|
|
|
|
|
return s, name
|
|
|
|
|
def _member_key():
|
|
|
|
|
_, name = _member()
|
|
|
|
|
return _db_user(name)["api_key"]
|
|
|
|
|
def _admin(seeded_db):
|
|
|
|
|
# authenticate via the seeded admin's API key (header auth) rather than a
|
|
|
|
|
# login POST - GET reads are exempt from the rate limiter, so reusing this
|
|
|
|
|
# across the file's many tests never counts against the per-IP write budget.
|
|
|
|
|
key = _db_user("alice_test")["api_key"]
|
|
|
|
|
s = requests.Session()
|
|
|
|
|
s.headers.update({"X-API-KEY": key})
|
|
|
|
|
return s
|
|
|
|
|
def _audit(admin, **params):
|
|
|
|
|
r = admin.get(f"{BASE_URL}/admin/audit-log", headers=JSON_audit_log, params=params)
|
|
|
|
|
assert r.status_code == 200, r.text[:300]
|
|
|
|
|
return r.json()
|
|
|
|
|
def _find(admin, event_key, predicate):
|
|
|
|
|
data = _audit(admin, event_key=event_key)
|
|
|
|
|
for entry in data["entries"]:
|
|
|
|
|
if predicate(entry):
|
|
|
|
|
return entry
|
|
|
|
|
return None
|
|
|
|
|
def _new_post(session, body="audited post body here"):
|
|
|
|
|
return session.post(
|
|
|
|
|
f"{BASE_URL}/posts/create",
|
|
|
|
|
headers=JSON_audit_log,
|
|
|
|
|
data={"title": _unique("aup"), "content": body, "topic": "devlog"},
|
|
|
|
|
).json()["data"]
|
|
|
|
|
def _new_project(session):
|
|
|
|
|
return session.post(
|
|
|
|
|
f"{BASE_URL}/projects/create",
|
|
|
|
|
headers=JSON_audit_log,
|
|
|
|
|
data={
|
|
|
|
|
"title": _unique("aupr"),
|
|
|
|
|
"description": "audited project description text",
|
|
|
|
|
"project_type": "software",
|
|
|
|
|
"status": "In Development",
|
|
|
|
|
"platforms": "",
|
|
|
|
|
},
|
|
|
|
|
).json()["data"]
|
|
|
|
|
def _seed_news_audit_log():
|
|
|
|
|
uid = generate_uid()
|
|
|
|
|
title = _unique("aunews")
|
|
|
|
|
get_table("news").insert(
|
|
|
|
|
{
|
2026-06-14 16:46:36 +02:00
|
|
|
"deleted_at": None,
|
|
|
|
|
"deleted_by": None,
|
2026-06-13 16:32:33 +02:00
|
|
|
"uid": uid,
|
|
|
|
|
"slug": make_combined_slug(title, uid),
|
|
|
|
|
"title": title,
|
|
|
|
|
"external_id": uid,
|
|
|
|
|
"status": "draft",
|
|
|
|
|
"featured": 0,
|
|
|
|
|
"show_on_landing": 0,
|
|
|
|
|
"grade": 5,
|
|
|
|
|
"source_name": "AuditTest",
|
|
|
|
|
"synced_at": datetime.now(timezone.utc).isoformat(),
|
|
|
|
|
"description": "audited news article",
|
|
|
|
|
}
|
|
|
|
|
)
|
|
|
|
|
refresh_snapshot()
|
|
|
|
|
return uid
|
|
|
|
|
from devplacepy.database import get_table
|
|
|
|
|
JSON_content_negotiation = {"Accept": "application/json"}
|
|
|
|
|
_counter_content_negotiation = [0]
|
|
|
|
|
def _session_content_negotiation(password="secret123"):
|
|
|
|
|
_counter_content_negotiation[0] += 1
|
|
|
|
|
name = f"cn{int(time.time() * 1000)}{_counter_content_negotiation[0]}"
|
|
|
|
|
s = requests.Session()
|
|
|
|
|
s.post(
|
|
|
|
|
f"{BASE_URL}/auth/signup",
|
|
|
|
|
data={
|
|
|
|
|
"username": name,
|
|
|
|
|
"email": f"{name}@t.dev",
|
|
|
|
|
"password": password,
|
|
|
|
|
"confirm_password": password,
|
|
|
|
|
},
|
|
|
|
|
allow_redirects=True,
|
|
|
|
|
)
|
|
|
|
|
return s, name
|
2026-06-14 09:48:10 +02:00
|
|
|
PUBLIC_PAGES = ["/feed", "/projects", "/gists", "/news", "/leaderboard", "/issues"]
|
2026-06-13 16:32:33 +02:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_security_authz_denied_recorded(seeded_db):
|
|
|
|
|
requests.get(f"{BASE_URL}/messages", allow_redirects=False)
|
|
|
|
|
admin = _admin(seeded_db)
|
|
|
|
|
event = _find(
|
|
|
|
|
admin,
|
|
|
|
|
"security.authz.denied",
|
|
|
|
|
lambda e: e.get("request_path") == "/messages",
|
|
|
|
|
)
|
|
|
|
|
assert event is not None
|
|
|
|
|
assert event["result"] == "denied"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_unauthenticated_json_request_is_401_not_redirect(app_server):
|
|
|
|
|
r = requests.get(f"{BASE_URL}/messages", headers=JSON_content_negotiation, allow_redirects=False)
|
|
|
|
|
assert r.status_code == 401
|
|
|
|
|
# browser guest still redirects to login
|
|
|
|
|
rh = requests.get(f"{BASE_URL}/messages", allow_redirects=False)
|
|
|
|
|
assert rh.status_code == 303
|
2026-07-05 00:08:20 +02:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_messages_conversation_renders_presence_indicator(app_server):
|
|
|
|
|
sender, _ = _member()
|
|
|
|
|
_, other_name = _member()
|
|
|
|
|
other_uid = _db_user(other_name)["uid"]
|
|
|
|
|
r = sender.get(f"{BASE_URL}/messages?with_uid={other_uid}")
|
|
|
|
|
assert r.status_code == 200
|
|
|
|
|
assert "messages-presence" in r.text
|
|
|
|
|
assert f'data-presence-uid="{other_uid}"' in r.text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_messages_conversation_list_avatar_has_presence_dot(app_server):
|
|
|
|
|
sender, _ = _member()
|
|
|
|
|
_, other_name = _member()
|
|
|
|
|
other_uid = _db_user(other_name)["uid"]
|
|
|
|
|
sent = sender.post(
|
|
|
|
|
f"{BASE_URL}/messages/send",
|
|
|
|
|
data={"receiver_uid": other_uid, "content": "hi there"},
|
|
|
|
|
allow_redirects=True,
|
|
|
|
|
)
|
|
|
|
|
assert sent.status_code == 200, sent.text[:300]
|
|
|
|
|
html = sender.get(f"{BASE_URL}/messages").text
|
|
|
|
|
assert "conversation-item" in html
|
|
|
|
|
assert "presence-dot" in html
|
|
|
|
|
assert f'data-presence-uid="{other_uid}"' in html
|
Make the presence roster the single source of truth for online status
Online status had three server-side candidate populations and two
client-side deciders, so the feed roster and the /messages indicators
could legitimately disagree.
PresenceRelayService built its online set from whichever topics happened
to be subscribed on a given tick: the roster candidates on /feed, only
the per-uid dot rows on /messages. Different populations meant a
different hysteresis baseline, so the same user could be online in one
place and offline in the other. On top of that, PresenceManager re-derived
online status client-side from a frozen data-presence-last-seen with a
strict timeout and no hysteresis, re-evaluated every 20s, so any element
whose relay frame was missed drifted grey after the timeout and stayed
there. AppChat carried a third renderer with its own PubSubClient that
only ever wrote online/offline, plus hand-built dot markup duplicating
_presence_dot.html.
The relay now collapses to one set on one topic. Each tick it reads the
online population in a single indexed query (online_candidates, capped by
the new PRESENCE_TRACK_LIMIT), applies hysteresis once, and publishes
{count, online, users} on public.presence.roster only when the uid set
changes. online is the authority for every avatar dot; users is the same
set trimmed to PRESENCE_ONLINE_LIMIT for the feed panel. The per-uid
public.presence.{uid} topics are gone, which also removes one
subscription per distinct author on a page.
is_online(user) is now stays_online(seconds_since(last_seen), False), so
the server-rendered initial state and the live set apply one formula.
PresenceManager makes one subscription and renders every
[data-presence-uid] element as membership of that set, with no clock and
no expiry timer; before the first frame the server-rendered state stands.
Relative "last seen" text is a <time data-dt data-dt-mode="ago"> handled
by the shared LocalTime. AppChat lost its presence code entirely, and the
new Avatar.badgeElement is the JS twin of _presence_dot.html, so dot
markup now lives in exactly two places.
Also fix the awards column ensure-block, which the awards tests exposed.
backfill_api_keys opened with an "if users not in db.tables" guard, but
on a brand-new database that is precisely the state at init_db time, so
the whole users ensure-block was skipped. The first signup then created
users with only the columns of that INSERT, leaving every ensured-but-
unwritten column absent from the server's reflected metadata for the rest
of the process lifetime. That is why the awards tab, the prominent award
banner and the avatar award badge were invisible on a fresh database. It
now calls get_table("users") unconditionally.
test_avatar_badge_on_feed_when_prominent asserted that any online user
carries an award badge while only awarding a user who was never active,
so it passed only by accident. It now makes the awarded user active and
asserts the badge on that user's roster entry.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-06 19:19:21 +02:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_chat_presence_agrees_with_the_feed_online_roster(app_server):
|
|
|
|
|
sender, _ = _member()
|
|
|
|
|
# the roster is alphabetical and capped, so name the partner to sort first
|
|
|
|
|
other_name = _unique("0chat")
|
|
|
|
|
other = requests.Session()
|
|
|
|
|
other.post(
|
|
|
|
|
f"{BASE_URL}/auth/signup",
|
|
|
|
|
data={
|
|
|
|
|
"username": other_name,
|
|
|
|
|
"email": f"{other_name}@t.dev",
|
|
|
|
|
"password": "secret123",
|
|
|
|
|
"confirm_password": "secret123",
|
|
|
|
|
},
|
|
|
|
|
allow_redirects=True,
|
|
|
|
|
)
|
|
|
|
|
other_uid = _db_user(other_name)["uid"]
|
|
|
|
|
|
|
|
|
|
# the partner is active, so the feed roster - the single source of truth - lists them
|
|
|
|
|
roster = sender.get(f"{BASE_URL}/feed").text
|
|
|
|
|
assert f'class="online-user" title="{other_name}"' in roster
|
|
|
|
|
|
|
|
|
|
# ...and the chat header must say exactly the same thing
|
|
|
|
|
chat = sender.get(f"{BASE_URL}/messages?with_uid={other_uid}").text
|
|
|
|
|
header = chat.split('id="messages-presence"', 1)[1].split("</span>", 1)[0]
|
|
|
|
|
assert header.endswith("online"), header
|
|
|
|
|
assert f'data-presence-uid="{other_uid}"' in header
|