""" Tests for the auth-hub account-linking logic. This is the one place a login bug can silently orphan a real account: if `find_or_create_user` ever created a fresh row for a `auth_hub_sub` it had already seen, the same person logging in twice would end up owning two disconnected accounts — the second with none of the health data synced under the first. That exact bug shipped once already (a login test created a real duplicate in production before this file existed), so it is worth locking down explicitly rather than only trusting `find_or_create_user`'s docstring. """ from services.auth_hub_client import find_or_create_user class TestFindOrCreateUser: def test_first_login_creates_a_user(self, db): uid = find_or_create_user("42", "alice") row = db.query_one("SELECT * FROM users WHERE id = ?", [uid]) assert row["auth_hub_sub"] == "42" assert row["auth_hub_username"] == "alice" def test_repeat_login_returns_the_same_user_not_a_duplicate(self, db): first = find_or_create_user("42", "alice") second = find_or_create_user("42", "alice") assert first == second assert db.query_one( "SELECT COUNT(*) AS n FROM users WHERE auth_hub_sub = ?", ["42"] )["n"] == 1 def test_different_sub_gets_a_different_user(self, db): alice = find_or_create_user("42", "alice") bob = find_or_create_user("43", "bob") assert alice != bob def test_a_username_change_upstream_does_not_split_the_account(self, db): """auth-hub identifies accounts by `sub`; `preferred_username` can be renamed there without that being treated as a new local account.""" first = find_or_create_user("42", "alice") second = find_or_create_user("42", "alice_renamed") assert first == second def test_links_to_a_pre_existing_account_with_that_sub(self, db): """The legacy migration path: an account created before auth-hub existed gets its auth_hub_sub set once (by an operator, or a future self-service linking flow), and every login after that must resolve to that same row rather than minting a new one.""" import uuid legacy_id = str(uuid.uuid4()) db.execute( "INSERT INTO users (id, email, auth_hub_sub, auth_hub_username) " "VALUES (?, ?, ?, ?)", [legacy_id, "legacy@example.com", "42", "alice"], ) assert find_or_create_user("42", "alice") == legacy_id