Files
rar-autopass/tests/test_web_signup.py
Claude Agent 504b490d3b feat(web): self-onboarding multi-tenant + auth sesiune (PRD 3.3a)
Canalul web trece de la 100% deschis (hardcodat cont 1) la autentificat si
multi-tenant. Un service nou se inregistreaza din browser, primeste o cheie API
(o singura data) si o sesiune; contul se creeaza "in asteptare" (active=0) si nu
trimite la RAR pana la activarea de catre admin (tools/account.py activate).

- users + app/users.py: parole scrypt (salt per-user, eticheta parametri onorata
  la verify pentru migrare cost), email unic case-insensitive
- sesiune: SessionMiddleware (same_site=strict, https_only config) + app/web/session.py
  (current_account/web_account/require_login->LoginRequired, set_session clear-inainte)
- CSRF (app/web/csrf.py) enforce in prod inclusiv pe login/signup + rate-limit
  in-proces (app/web/ratelimit.py) pe signup si login
- signup/login/logout (app/web/auth_routes.py): signup tranzactie atomica,
  cheie-o-data, log SIGNUP pentru descoperire admin
- dashboard + import scoped pe contul sesiunii (regula NULL->cont 1); toate rutele
  web care ating date sensibile sub require_login; nomenclator ramane global
- banner "cont in asteptare" pentru conturi active=0
- gate worker: claim_one LEFT JOIN accounts COALESCE(active,1)=1 (account_id NULL=activ)

VERIFY context curat (2 runde): leak cross-account /_fragments/mapari prins+reparat.
/code-review high: csrf_token lipsa pe re-randari de eroare, scrypt_params ignorat,
login fara rate-limit -- toate reparate. 361 teste pass (de la 313).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 16:43:21 +00:00

155 lines
4.6 KiB
Python

"""Teste US-003 (PRD 3.3): GET/POST /signup.
TDD: testele se scriu INAINTE de implementarea auth_routes.py; la inceput pica (RED),
dupa implementare trec (GREEN).
"""
from __future__ import annotations
import os
import re
import tempfile
import pytest
from starlette.testclient import TestClient
@pytest.fixture()
def client(monkeypatch):
tmp = tempfile.mkdtemp()
monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "t.db"))
monkeypatch.setenv("AUTOPASS_SIGNUP_RATE_MAX", "100")
from app.config import get_settings
get_settings.cache_clear()
from app.web import ratelimit
ratelimit._hits.clear()
from app.main import app
with TestClient(app) as c:
yield c
get_settings.cache_clear()
def _csrf(html: str) -> str:
m = re.search(r'name="csrf_token"\s+value="([^"]+)"', html)
if not m:
m = re.search(r'value="([^"]+)"\s+name="csrf_token"', html)
assert m, "csrf_token negasit in HTML"
return m.group(1)
def test_signup_creeaza_cont_user_si_cheie(client):
"""POST /signup valid -> cont active=0, user, api_key create in DB; cheie rfak_ in raspuns."""
resp = client.get("/signup")
assert resp.status_code == 200
token = _csrf(resp.text)
resp = client.post("/signup", data={
"name": "Service Auto Test",
"cui": "RO12345678",
"email": "test@example.com",
"parola": "parolasecreta",
"csrf_token": token,
})
assert resp.status_code == 200
assert "rfak_" in resp.text
from app.db import get_connection
conn = get_connection()
try:
acct = conn.execute(
"SELECT * FROM accounts WHERE name='Service Auto Test'"
).fetchone()
assert acct is not None
assert acct["active"] == 0, "Contul trebuie creat inactive (in asteptare)"
user = conn.execute(
"SELECT * FROM users WHERE email='test@example.com'"
).fetchone()
assert user is not None
assert user["account_id"] == acct["id"]
key = conn.execute(
"SELECT * FROM api_keys WHERE account_id=?", (acct["id"],)
).fetchone()
assert key is not None
assert key["active"] == 1
finally:
conn.close()
def test_signup_email_duplicat_eroare(client):
"""Email duplicat -> ROLLBACK; COUNT(accounts) neschimbat (fara cont orfan)."""
resp = client.get("/signup")
token = _csrf(resp.text)
client.post("/signup", data={
"name": "Service A",
"email": "dup@example.com",
"parola": "parolasecreta",
"csrf_token": token,
})
from app.db import get_connection
conn = get_connection()
count_before = conn.execute("SELECT COUNT(*) AS n FROM accounts").fetchone()["n"]
conn.close()
resp = client.get("/signup")
token = _csrf(resp.text)
resp2 = client.post("/signup", data={
"name": "Service B",
"email": "dup@example.com",
"parola": "altaparola123",
"csrf_token": token,
})
assert resp2.status_code in (200, 422)
assert "rfak_" not in resp2.text
conn = get_connection()
count_after = conn.execute("SELECT COUNT(*) AS n FROM accounts").fetchone()["n"]
conn.close()
assert count_after == count_before, "Cont orfan creat la email duplicat (ROLLBACK a esuat)"
def test_signup_parola_scurta_eroare(client):
"""Parola sub 10 caractere -> eroare, fara creare cont/user."""
resp = client.get("/signup")
token = _csrf(resp.text)
resp = client.post("/signup", data={
"name": "Service Test",
"email": "scurta@test.com",
"parola": "scurt",
"csrf_token": token,
})
assert resp.status_code in (200, 422)
assert "rfak_" not in resp.text
from app.db import get_connection
conn = get_connection()
try:
acct = conn.execute(
"SELECT * FROM accounts WHERE name='Service Test'"
).fetchone()
assert acct is None, "Cont creat desi parola era prea scurta"
finally:
conn.close()
def test_cheie_afisata_o_data(client):
"""Cheia rfak_ apare in raspunsul POST /signup; GET /signup nu o contine."""
resp = client.get("/signup")
token = _csrf(resp.text)
resp_post = client.post("/signup", data={
"name": "Service Cheie",
"email": "cheie@test.com",
"parola": "parolasecreta",
"csrf_token": token,
})
assert resp_post.status_code == 200
assert "rfak_" in resp_post.text, "Cheia trebuia afisata in raspunsul POST /signup"
resp_get = client.get("/signup")
assert "rfak_" not in resp_get.text, "GET /signup nu trebuie sa contina cheia (afisata o singura data)"