Migrate Flask React template into Forge
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
TEST_DEFAULTS = {
|
||||
"APP_ENV": "testing",
|
||||
"SQLALCHEMY_DATABASE_URI": "sqlite:///:memory:",
|
||||
"SECRET_KEY": "test-key",
|
||||
"REGISTRATION_MODE": "open",
|
||||
"EMAIL_DELIVERY_ENABLED": "false",
|
||||
"RATELIMIT_ENABLED": "true",
|
||||
}
|
||||
for name, value in TEST_DEFAULTS.items():
|
||||
os.environ.setdefault(name, value)
|
||||
|
||||
import pytest
|
||||
|
||||
from api import app
|
||||
from settings import db, limiter
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client():
|
||||
with app.app_context():
|
||||
limiter.reset()
|
||||
db.create_all()
|
||||
yield app.test_client()
|
||||
db.session.remove()
|
||||
db.drop_all()
|
||||
limiter.reset()
|
||||
@@ -0,0 +1,157 @@
|
||||
import base64
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from models.account_token import AccountToken
|
||||
from models.user import User
|
||||
from settings import app, db
|
||||
|
||||
|
||||
def register(client, **overrides):
|
||||
payload = {
|
||||
"email": "person@example.com",
|
||||
"username": "person",
|
||||
"password": "long-enough-password",
|
||||
**overrides,
|
||||
}
|
||||
return client.post("/api/user/register", json=payload)
|
||||
|
||||
|
||||
def basic_header(email="person@example.com", password="long-enough-password"):
|
||||
encoded = base64.b64encode(f"{email}:{password}".encode()).decode()
|
||||
return {"Authorization": f"Basic {encoded}"}
|
||||
|
||||
|
||||
def test_health_and_registration_status(client):
|
||||
assert client.get("/api/health").get_json() == {"status": "ok"}
|
||||
assert client.get("/api/health/live").get_json() == {"status": "ok"}
|
||||
assert client.get("/api/health/ready").get_json() == {"status": "ready"}
|
||||
assert client.get("/api/user/registration-status").get_json() == {
|
||||
"mode": "open"
|
||||
}
|
||||
|
||||
|
||||
def test_readiness_failure_is_generic(client, monkeypatch):
|
||||
from sqlalchemy.exc import OperationalError
|
||||
|
||||
def fail(_statement):
|
||||
raise OperationalError("SELECT 1", {}, RuntimeError("private database detail"))
|
||||
|
||||
monkeypatch.setattr("routes.routes.db.session.execute", fail)
|
||||
response = client.get("/api/health/ready")
|
||||
assert response.status_code == 503
|
||||
assert response.get_json() == {"status": "unavailable"}
|
||||
|
||||
|
||||
def test_registration_normalizes_email_and_hashes_one_time_token(client):
|
||||
response = register(client, email=" PERSON@Example.COM ")
|
||||
assert response.status_code == 201
|
||||
user = User.query.one()
|
||||
token = AccountToken.query.one()
|
||||
assert user.email == "person@example.com"
|
||||
assert user.password_hash != "long-enough-password"
|
||||
assert token.purpose == AccountToken.PURPOSE_EMAIL_VERIFICATION
|
||||
assert len(token.token_hash) == 64
|
||||
|
||||
|
||||
def test_registration_validates_input_and_duplicate_email(client):
|
||||
assert register(client, password="short").status_code == 400
|
||||
assert register(client).status_code == 201
|
||||
assert register(client, email="PERSON@example.com").status_code == 409
|
||||
|
||||
|
||||
def test_closed_registration_rejects_accounts(client):
|
||||
original = app.config["REGISTRATION_MODE"]
|
||||
app.config["REGISTRATION_MODE"] = "closed"
|
||||
try:
|
||||
assert register(client).status_code == 403
|
||||
finally:
|
||||
app.config["REGISTRATION_MODE"] = original
|
||||
|
||||
|
||||
def test_login_refresh_logout_cycle(client):
|
||||
assert register(client).status_code == 201
|
||||
login = client.post("/api/auth/tokens", headers=basic_header())
|
||||
assert login.status_code == 200
|
||||
token = login.get_json()["token"]
|
||||
refreshed = client.get("/api/auth/refresh")
|
||||
assert refreshed.status_code == 200
|
||||
assert refreshed.get_json()["user_id"] == login.get_json()["user_id"]
|
||||
logout = client.delete(
|
||||
"/api/auth/tokens", headers={"Authorization": f"Bearer {token}"}
|
||||
)
|
||||
assert logout.status_code == 200
|
||||
assert client.get("/api/auth/refresh").status_code == 400
|
||||
|
||||
|
||||
def test_password_reset_is_non_enumerating_and_single_use(client):
|
||||
assert register(client).status_code == 201
|
||||
assert client.post(
|
||||
"/api/user/reset-password", json={"email": "missing@example.com"}
|
||||
).status_code == 200
|
||||
assert client.post(
|
||||
"/api/user/reset-password", json={"email": "person@example.com"}
|
||||
).status_code == 200
|
||||
token = AccountToken.query.filter_by(
|
||||
purpose=AccountToken.PURPOSE_PASSWORD_RESET
|
||||
).one()
|
||||
assert token.token_hash
|
||||
assert client.post(
|
||||
"/api/user/update-password",
|
||||
json={"token": "not-the-token", "password": "new-password-value"},
|
||||
).status_code == 400
|
||||
|
||||
|
||||
def test_verification_and_password_reset_tokens_are_consumed(client, monkeypatch):
|
||||
captured = {}
|
||||
|
||||
def capture_verification(user, raw_token):
|
||||
captured["verification"] = raw_token
|
||||
|
||||
def capture_reset(user, raw_token):
|
||||
captured["reset"] = raw_token
|
||||
|
||||
monkeypatch.setattr("routes.user_routes.send_verification_email", capture_verification)
|
||||
monkeypatch.setattr("routes.user_routes.send_password_reset_email", capture_reset)
|
||||
assert register(client).status_code == 201
|
||||
assert client.post(
|
||||
"/api/user/verify-email", json={"token": captured["verification"]}
|
||||
).status_code == 200
|
||||
assert client.post(
|
||||
"/api/user/verify-email", json={"token": captured["verification"]}
|
||||
).status_code == 400
|
||||
|
||||
assert client.post(
|
||||
"/api/user/reset-password", json={"email": "person@example.com"}
|
||||
).status_code == 200
|
||||
assert client.post(
|
||||
"/api/user/update-password",
|
||||
json={"token": captured["reset"], "password": "replacement-password"},
|
||||
).status_code == 200
|
||||
assert client.post(
|
||||
"/api/user/update-password",
|
||||
json={"token": captured["reset"], "password": "another-password"},
|
||||
).status_code == 400
|
||||
assert client.post(
|
||||
"/api/auth/tokens",
|
||||
headers=basic_header(password="replacement-password"),
|
||||
).status_code == 200
|
||||
|
||||
|
||||
def test_expired_account_tokens_are_rejected(client, monkeypatch):
|
||||
captured = {}
|
||||
monkeypatch.setattr(
|
||||
"routes.user_routes.send_verification_email",
|
||||
lambda _user, raw_token: captured.update(verification=raw_token),
|
||||
)
|
||||
assert register(client).status_code == 201
|
||||
token = AccountToken.query.filter_by(
|
||||
purpose=AccountToken.PURPOSE_EMAIL_VERIFICATION
|
||||
).one()
|
||||
token.expires_at = datetime.utcnow() - timedelta(seconds=1)
|
||||
db.session.commit()
|
||||
|
||||
response = client.post(
|
||||
"/api/user/verify-email", json={"token": captured["verification"]}
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert response.get_json()["message"] == "Verification link is invalid or expired"
|
||||
@@ -0,0 +1,67 @@
|
||||
from email_service import EmailDeliveryError
|
||||
|
||||
|
||||
VALID_MESSAGE = {
|
||||
"name": "Example Person",
|
||||
"email": "person@example.com",
|
||||
"subject": "A useful question",
|
||||
"message": "This message is long enough to be accepted.",
|
||||
"website": "",
|
||||
}
|
||||
|
||||
|
||||
def test_contact_delivers_valid_message(client, monkeypatch):
|
||||
delivered = {}
|
||||
|
||||
def capture(**payload):
|
||||
delivered.update(payload)
|
||||
|
||||
monkeypatch.setattr("routes.contact_routes.send_contact_email", capture)
|
||||
response = client.post("/api/contact", json=VALID_MESSAGE)
|
||||
assert response.status_code == 200
|
||||
assert delivered == {
|
||||
key: VALID_MESSAGE[key] for key in ("name", "email", "subject", "message")
|
||||
}
|
||||
|
||||
|
||||
def test_contact_rejects_invalid_and_injection_input(client):
|
||||
assert client.post("/api/contact", json={}).status_code == 400
|
||||
assert client.post(
|
||||
"/api/contact",
|
||||
json={**VALID_MESSAGE, "email": "person@example.com\nBcc:test@example.com"},
|
||||
).status_code == 400
|
||||
assert client.post(
|
||||
"/api/contact",
|
||||
json={**VALID_MESSAGE, "subject": "Hello\r\nBcc: test@example.com"},
|
||||
).status_code == 400
|
||||
assert client.post(
|
||||
"/api/contact", json={**VALID_MESSAGE, "message": "short"}
|
||||
).status_code == 400
|
||||
|
||||
|
||||
def test_contact_honeypot_does_not_deliver(client, monkeypatch):
|
||||
def unexpected(**_payload):
|
||||
raise AssertionError("honeypot submission must not be delivered")
|
||||
|
||||
monkeypatch.setattr("routes.contact_routes.send_contact_email", unexpected)
|
||||
response = client.post(
|
||||
"/api/contact", json={**VALID_MESSAGE, "website": "https://bot.invalid"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
|
||||
def test_contact_delivery_failure_is_generic(client, monkeypatch):
|
||||
def fail(**_payload):
|
||||
raise EmailDeliveryError("provider detail must not escape")
|
||||
|
||||
monkeypatch.setattr("routes.contact_routes.send_contact_email", fail)
|
||||
response = client.post("/api/contact", json=VALID_MESSAGE)
|
||||
assert response.status_code == 503
|
||||
assert response.get_json()["message"] == "Unable to send message right now"
|
||||
|
||||
|
||||
def test_contact_rate_limit_rejects_sixth_submission(client, monkeypatch):
|
||||
monkeypatch.setattr("routes.contact_routes.send_contact_email", lambda **_: None)
|
||||
responses = [client.post("/api/contact", json=VALID_MESSAGE) for _ in range(6)]
|
||||
assert [response.status_code for response in responses[:5]] == [200] * 5
|
||||
assert responses[5].status_code == 429
|
||||
Reference in New Issue
Block a user