Files
devplacepy/tests/api/auth/login.py
T
retoor 8e9d3fad98 Add the trust and safety subsystem and the App Store compliance work
Implements the moderation and consent obligations a social platform carries,
so the web version and any client that speaks to it enforce the same rules.

Moderation core (services/moderation/, database/moderation.py): a reportable
target registry, the content filter and its choke points, the report queue with
atomic resolution, enforcement actions, consent tracking, maturity gating, and
account deletion with a grace window.

Surfaces: POST /reports plus the member report list, /admin/moderation and the
per-report admin view, /workspaces, terms acceptance at /auth/terms, consent and
account deletion under /profile, the report button and dialog partials, the
maturity gate, and the moderation stylesheet and ReportDialog client.

Every user-generated surface stays reportable by construction: new content tables
are registered in REPORTABLE_TARGETS or listed in UNREPORTABLE_TABLES with a
reason, and the registry test fails the suite on anything left unclassified.

Docs: community guidelines, content moderation, intellectual property, privacy,
terms, contact, and the admin-only moderation operations page, plus the
moderation API group and the Devii moderation actions.

Compliance record: applecomp.md is the requirement register, applechanges.md the
gap analysis against this codebase, and appleimpl.md the implementation design
they resolve to.

Tests cover the report flow, admin moderation, consent, account deletion, terms
acceptance, workspaces, and the registry invariant across the unit, api, and e2e
tiers.
2026-08-09 00:18:20 +02:00

228 lines
7.6 KiB
Python

# 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",
"birth_date": "1990-01-01",
"accept_terms": "1",
},
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(
{
"deleted_at": None,
"deleted_by": None,
"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
def test_login_failure_is_recorded(seeded_db):
email = f"{_unique('aufail')}@t.dev"
requests.post(
f"{BASE_URL}/auth/login",
data={"email": email, "password": "wrongpassword"},
allow_redirects=False,
)
admin = _admin(seeded_db)
event = _find(
admin,
"auth.login.failure",
lambda e: email in (e.get("summary") or ""),
)
assert event is not None
assert event["result"] == "failure"
assert event["actor_kind"] == "guest"
def test_filter_by_result(seeded_db):
# ensure at least one failure exists
requests.post(
f"{BASE_URL}/auth/login",
data={"email": f"{_unique('aurf')}@t.dev", "password": "nope"},
allow_redirects=False,
)
admin = _admin(seeded_db)
data = _audit(admin, result="failure")
assert data["pagination"]["total"] >= 1
assert all(e["result"] == "failure" for e in data["entries"])
def test_rate_limit_block_recorded(monkeypatch):
# The limiter is disabled suite-wide (conftest sets DEVPLACE_DISABLE_RATE_LIMIT),
# and the shared server runs in its own process, so this runs in-process with the
# limiter re-enabled for itself - the same approach as test_ratelimit.py - and
# asserts the block emits the security.rate_limit.block audit row.
import devplacepy.main as m
from starlette.testclient import TestClient
monkeypatch.setattr(m, "RATE_LIMIT_DISABLED", False)
monkeypatch.setattr(
m,
"get_int_setting",
lambda key, default: {
"rate_limit_per_minute": 1,
"rate_limit_window_seconds": 60,
}.get(key, default),
)
m._rate_limit_store.clear()
ip = "203.0.113.77"
client = TestClient(m.app)
codes = [
client.post(
"/auth/login",
data={"email": "x@y.dev", "password": "nope"},
headers={"X-Real-IP": ip},
).status_code
for _ in range(4)
]
assert 429 in codes, codes
event = get_table("audit_log").find_one(
event_key="security.rate_limit.block", result="denied"
)
assert event is not None
def _member_with_null_is_active():
session, name = _member()
row = _db_user(name)
get_table("users").update({"uid": row["uid"], "is_active": None}, ["uid"])
refresh_snapshot()
return name, row
def test_login_works_when_is_active_was_never_written(seeded_db):
name, _row = _member_with_null_is_active()
response = requests.post(
f"{BASE_URL}/auth/login",
headers=JSON_audit_log,
data={"email": f"{name}@t.dev", "password": "secret123"},
allow_redirects=False,
)
assert response.status_code == 200, response.text[:300]
def test_api_key_works_when_is_active_was_never_written(seeded_db):
_name, row = _member_with_null_is_active()
response = requests.get(
f"{BASE_URL}/profile",
headers={**JSON_audit_log, "X-API-KEY": row["api_key"]},
allow_redirects=False,
)
assert response.status_code == 200, response.text[:300]
def test_an_explicitly_disabled_account_still_cannot_log_in(seeded_db):
session, name = _member()
row = _db_user(name)
get_table("users").update({"uid": row["uid"], "is_active": False}, ["uid"])
refresh_snapshot()
response = requests.get(
f"{BASE_URL}/profile",
headers={**JSON_audit_log, "X-API-KEY": row["api_key"]},
allow_redirects=False,
)
assert response.status_code == 401