""" Tests for who may create an account. This matters because the deployment is reachable from the public internet: an unconditionally open /register would let a stranger sign up and start pulling health data. """ import pytest def signup(client, email="new@example.com"): return client.post( "/api/auth/register", json={ "email": email, "garminEmail": "g@example.com", "garminPassword": "pw123456", }, ) @pytest.fixture(autouse=True) def _default_policy(monkeypatch): monkeypatch.delenv("ALLOW_REGISTRATION", raising=False) class TestAutoPolicy: """Default: open until the first account exists, then closed.""" def test_first_account_is_allowed(self, client, db): assert signup(client).status_code == 201 def test_second_account_is_refused(self, client, user): r = signup(client, "stranger@example.com") assert r.status_code == 403 assert "注册已关闭" in r.get_json()["error"] def test_refusal_does_not_create_the_account(self, client, user, db): signup(client, "stranger@example.com") assert db.query_one( "SELECT id FROM users WHERE email = ?", ["stranger@example.com"] ) is None def test_status_reports_open_before_any_signup(self, client, db): assert client.get("/api/auth/registration-status").get_json()["open"] is True def test_status_reports_closed_afterwards(self, client, user): assert client.get("/api/auth/registration-status").get_json()["open"] is False class TestExplicitPolicies: def test_true_keeps_it_open_even_with_existing_users(self, client, user, monkeypatch): monkeypatch.setenv("ALLOW_REGISTRATION", "true") assert signup(client, "second@example.com").status_code == 201 def test_false_closes_it_even_on_an_empty_instance(self, client, db, monkeypatch): monkeypatch.setenv("ALLOW_REGISTRATION", "false") assert signup(client).status_code == 403 def test_policy_is_read_per_request_not_at_import(self, client, db, monkeypatch): monkeypatch.setenv("ALLOW_REGISTRATION", "false") assert client.get("/api/auth/registration-status").get_json()["open"] is False monkeypatch.setenv("ALLOW_REGISTRATION", "true") assert client.get("/api/auth/registration-status").get_json()["open"] is True def test_value_is_case_insensitive(self, client, user, monkeypatch): monkeypatch.setenv("ALLOW_REGISTRATION", "TRUE") assert signup(client, "second@example.com").status_code == 201 class TestUnaffectedBehaviour: def test_status_endpoint_needs_no_auth(self, client, db): """The login page must be able to ask before anyone is signed in.""" assert client.get("/api/auth/registration-status").status_code == 200 def test_closing_registration_does_not_block_login(self, client, user): r = client.post( "/api/auth/login", json={"email": user["email"], "password": user["password"]}, ) assert r.status_code == 200 def test_duplicate_email_still_reports_409_when_open( self, client, user, monkeypatch ): monkeypatch.setenv("ALLOW_REGISTRATION", "true") assert signup(client, user["email"]).status_code == 409