askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
test_object_signup.py · 43.1 KB · 828 lines
| 1 | """Self-service signup, email verification and password reset (object_signup + the browser routes).""" |
| 2 | |
| 3 | import os |
| 4 | import re |
| 5 | import stat |
| 6 | import urllib.parse |
| 7 | from datetime import datetime, timedelta, timezone |
| 8 | from pathlib import Path |
| 9 | |
| 10 | import pytest |
| 11 | |
| 12 | import object_credentials |
| 13 | import object_identity |
| 14 | import object_packages |
| 15 | import object_permission_store |
| 16 | import object_permissions |
| 17 | import object_records |
| 18 | import object_server |
| 19 | import object_signup |
| 20 | |
| 21 | from test_object_server import raw_request |
| 22 | |
| 23 | PACKAGES_ROOT = Path(__file__).resolve().parents[1] / "packages" |
| 24 | NOW = datetime(2026, 9, 28, 12, 0, tzinfo=timezone.utc) |
| 25 | PASSWORD = "correct horse battery" |
| 26 | |
| 27 | |
| 28 | # ---- tokens --------------------------------------------------------------- |
| 29 | |
| 30 | |
| 31 | def test_token_is_single_use_and_stored_only_as_a_hash(tmp_path): |
| 32 | token = object_signup.issue_token(object_signup.VERIFY_EMAIL, "u1", "a@example.org", base_dir=tmp_path, now=NOW) |
| 33 | |
| 34 | stored = object_signup.tokens_path(tmp_path).read_text() |
| 35 | assert token not in stored |
| 36 | assert object_identity.hash_token(token) in stored |
| 37 | assert stat.S_IMODE(os.stat(object_signup.tokens_path(tmp_path)).st_mode) == 0o600 |
| 38 | |
| 39 | assert object_signup.peek_token(token, object_signup.VERIFY_EMAIL, base_dir=tmp_path, now=NOW) is not None |
| 40 | row = object_signup.consume_token(token, object_signup.VERIFY_EMAIL, base_dir=tmp_path, now=NOW) |
| 41 | assert row["user_id"] == "u1" |
| 42 | assert object_signup.consume_token(token, object_signup.VERIFY_EMAIL, base_dir=tmp_path, now=NOW) is None |
| 43 | # the used row is gone, not kept around |
| 44 | assert object_identity.hash_token(token) not in object_signup.tokens_path(tmp_path).read_text() |
| 45 | |
| 46 | |
| 47 | def test_token_expires_and_only_works_for_its_purpose(tmp_path): |
| 48 | token = object_signup.issue_token(object_signup.PASSWORD_RESET, "u1", "a@example.org", base_dir=tmp_path, now=NOW) |
| 49 | |
| 50 | assert object_signup.consume_token(token, object_signup.VERIFY_EMAIL, base_dir=tmp_path, now=NOW) is None |
| 51 | later = NOW + object_signup.TOKEN_TTL[object_signup.PASSWORD_RESET] + timedelta(seconds=1) |
| 52 | assert object_signup.consume_token(token, object_signup.PASSWORD_RESET, base_dir=tmp_path, now=later) is None |
| 53 | assert object_signup.consume_token("", object_signup.PASSWORD_RESET, base_dir=tmp_path, now=NOW) is None |
| 54 | assert object_signup.consume_token("nope", object_signup.PASSWORD_RESET, base_dir=tmp_path, now=NOW) is None |
| 55 | |
| 56 | |
| 57 | def test_a_new_link_retires_the_previous_one_and_the_file_stays_small(tmp_path): |
| 58 | first = object_signup.issue_token(object_signup.VERIFY_EMAIL, "u1", "a@example.org", base_dir=tmp_path, now=NOW) |
| 59 | second = object_signup.issue_token(object_signup.VERIFY_EMAIL, "u1", "a@example.org", base_dir=tmp_path, now=NOW) |
| 60 | object_signup.issue_token(object_signup.PASSWORD_RESET, "u1", "a@example.org", base_dir=tmp_path, now=NOW) |
| 61 | |
| 62 | assert object_signup.peek_token(first, object_signup.VERIFY_EMAIL, base_dir=tmp_path, now=NOW) is None |
| 63 | assert object_signup.peek_token(second, object_signup.VERIFY_EMAIL, base_dir=tmp_path, now=NOW) is not None |
| 64 | |
| 65 | # a write long after everything expired keeps only the new row |
| 66 | much_later = NOW + timedelta(days=30) |
| 67 | object_signup.issue_token(object_signup.VERIFY_EMAIL, "u2", "b@example.org", base_dir=tmp_path, now=much_later) |
| 68 | rows = object_signup._read_tokens(object_signup.tokens_path(tmp_path)) |
| 69 | assert [r["user_id"] for r in rows] == ["u2"] |
| 70 | |
| 71 | |
| 72 | # ---- accounts --------------------------------------------------------------- |
| 73 | |
| 74 | |
| 75 | def test_register_creates_a_pending_user_in_its_own_account(tmp_path): |
| 76 | result = object_signup.register("Ann@Example.org", base_dir=tmp_path, now=NOW) |
| 77 | |
| 78 | assert result["outcome"] == "created" |
| 79 | user = result["user"] |
| 80 | assert user["status"] == object_identity.PENDING_STATUS |
| 81 | assert user["roles"] == [] |
| 82 | assert user["display_name"] == "" |
| 83 | assert object_identity.get_account(user["account_id"], base_dir=tmp_path)["status"] == "active" |
| 84 | # no password exists until the person who holds the mailbox chooses one |
| 85 | assert not object_credentials.has_password(user["user_id"], base_dir=tmp_path) |
| 86 | # pending means no session, through the same gate every login uses |
| 87 | with pytest.raises(ValueError): |
| 88 | object_identity.create_session({"user_id": user["user_id"]}, base_dir=tmp_path, require_known_user=True) |
| 89 | |
| 90 | |
| 91 | def test_register_again_does_not_create_a_second_user(tmp_path): |
| 92 | first = object_signup.register("ann@example.org", base_dir=tmp_path, now=NOW) |
| 93 | again = object_signup.register("ANN@example.org", base_dir=tmp_path, now=NOW) |
| 94 | assert again["outcome"] == "pending" |
| 95 | assert again["user"]["user_id"] == first["user"]["user_id"] |
| 96 | |
| 97 | object_identity.set_user_status(first["user"]["user_id"], "active", base_dir=tmp_path) |
| 98 | exists = object_signup.register("ann@example.org", base_dir=tmp_path, now=NOW) |
| 99 | assert exists["outcome"] == "exists" |
| 100 | assert len(object_identity.list_users(base_dir=tmp_path)) == 1 |
| 101 | assert not object_credentials.has_password(first["user"]["user_id"], base_dir=tmp_path) |
| 102 | |
| 103 | |
| 104 | @pytest.mark.parametrize("email", ["not-an-email", "a@b", "a b@example.org"]) |
| 105 | def test_register_refuses_bad_input_before_creating_anything(tmp_path, email): |
| 106 | with pytest.raises(object_signup.SignupError): |
| 107 | object_signup.register(email, base_dir=tmp_path) |
| 108 | assert object_identity.list_users(base_dir=tmp_path) == [] |
| 109 | assert object_identity.list_accounts(base_dir=tmp_path) == [] |
| 110 | |
| 111 | |
| 112 | def test_confirming_sets_the_chosen_password_and_activates_once(tmp_path): |
| 113 | user = object_signup.register("ann@example.org", base_dir=tmp_path, now=NOW)["user"] |
| 114 | token = object_signup.issue_token(object_signup.VERIFY_EMAIL, user["user_id"], user["email"], base_dir=tmp_path) |
| 115 | |
| 116 | with pytest.raises(object_signup.SignupError): |
| 117 | object_signup.confirm_signup(token, "short", base_dir=tmp_path) |
| 118 | # a password that won't do leaves the link usable, and the user pending with no password |
| 119 | assert object_signup.peek_token(token, object_signup.VERIFY_EMAIL, base_dir=tmp_path) is not None |
| 120 | assert not object_credentials.has_password(user["user_id"], base_dir=tmp_path) |
| 121 | |
| 122 | confirmed = object_signup.confirm_signup(token, PASSWORD, base_dir=tmp_path) |
| 123 | assert confirmed["status"] == "active" |
| 124 | assert object_credentials.verify_password(user["user_id"], PASSWORD, base_dir=tmp_path) |
| 125 | assert object_signup.confirm_signup(token, "a second password", base_dir=tmp_path) is None |
| 126 | assert object_credentials.verify_password(user["user_id"], PASSWORD, base_dir=tmp_path) |
| 127 | |
| 128 | |
| 129 | def test_a_stranger_who_signs_up_with_my_address_gets_no_way_in(tmp_path): |
| 130 | """The pre-hijack: signing up first with someone's address must not choose their password.""" |
| 131 | stranger = object_signup.register("victim@example.org", base_dir=tmp_path, now=NOW)["user"] |
| 132 | # nothing the stranger typed can be used to sign in as that address |
| 133 | assert not object_credentials.has_password(stranger["user_id"], base_dir=tmp_path) |
| 134 | with pytest.raises(ValueError): |
| 135 | object_identity.create_session({"user_id": stranger["user_id"]}, base_dir=tmp_path, require_known_user=True) |
| 136 | |
| 137 | # the real owner signs up too, gets the link, and chooses the password |
| 138 | owner = object_signup.register("Victim@Example.org", base_dir=tmp_path, now=NOW) |
| 139 | assert owner["outcome"] == "pending" and owner["user"]["user_id"] == stranger["user_id"] |
| 140 | token = object_signup.issue_token(object_signup.VERIFY_EMAIL, stranger["user_id"], "victim@example.org", base_dir=tmp_path) |
| 141 | confirmed = object_signup.confirm_signup(token, "the owner's own password", " Victim Owner ", base_dir=tmp_path) |
| 142 | assert object_credentials.verify_password(stranger["user_id"], "the owner's own password", base_dir=tmp_path) |
| 143 | # the name is the mailbox holder's too, not whatever the first signup typed |
| 144 | assert confirmed["display_name"] == "Victim Owner" |
| 145 | |
| 146 | |
| 147 | def test_a_pending_user_made_before_the_fix_keeps_no_stranger_password(tmp_path): |
| 148 | """Old data: a pending user whose password a stranger chose at signup.""" |
| 149 | user = object_signup.register("ann@example.org", base_dir=tmp_path, now=NOW)["user"] |
| 150 | object_credentials.set_password(user["user_id"], "the stranger's password", base_dir=tmp_path) |
| 151 | # pending users cannot sign in, password or no password |
| 152 | with pytest.raises(ValueError): |
| 153 | object_identity.create_session({"user_id": user["user_id"]}, base_dir=tmp_path, require_known_user=True) |
| 154 | |
| 155 | token = object_signup.issue_token(object_signup.VERIFY_EMAIL, user["user_id"], user["email"], base_dir=tmp_path) |
| 156 | object_signup.confirm_signup(token, PASSWORD, base_dir=tmp_path) |
| 157 | assert object_credentials.verify_password(user["user_id"], PASSWORD, base_dir=tmp_path) |
| 158 | assert not object_credentials.verify_password(user["user_id"], "the stranger's password", base_dir=tmp_path) |
| 159 | |
| 160 | |
| 161 | def test_a_confirm_link_never_changes_an_account_already_in_use(tmp_path): |
| 162 | user = object_signup.register("ann@example.org", base_dir=tmp_path, now=NOW)["user"] |
| 163 | token = object_signup.issue_token(object_signup.VERIFY_EMAIL, user["user_id"], user["email"], base_dir=tmp_path) |
| 164 | object_credentials.set_password(user["user_id"], PASSWORD, base_dir=tmp_path) |
| 165 | object_identity.set_user_status(user["user_id"], "active", base_dir=tmp_path) |
| 166 | |
| 167 | assert object_signup.confirm_signup(token, "an attacker's password", base_dir=tmp_path) is None |
| 168 | assert object_credentials.verify_password(user["user_id"], PASSWORD, base_dir=tmp_path) |
| 169 | |
| 170 | |
| 171 | def test_verify_never_reactivates_a_disabled_user(tmp_path): |
| 172 | user = object_signup.register("ann@example.org", base_dir=tmp_path, now=NOW)["user"] |
| 173 | token = object_signup.issue_token(object_signup.VERIFY_EMAIL, user["user_id"], user["email"], base_dir=tmp_path) |
| 174 | object_identity.set_user_status(user["user_id"], "disabled", base_dir=tmp_path) |
| 175 | |
| 176 | assert object_signup.confirm_signup(token, PASSWORD, base_dir=tmp_path) is None |
| 177 | assert object_identity.get_user(user["user_id"], base_dir=tmp_path)["status"] == "disabled" |
| 178 | |
| 179 | |
| 180 | def test_a_link_sent_to_an_old_address_proves_nothing(tmp_path): |
| 181 | user = object_signup.register("ann@example.org", base_dir=tmp_path, now=NOW)["user"] |
| 182 | token = object_signup.issue_token(object_signup.VERIFY_EMAIL, user["user_id"], "someone-else@example.org", base_dir=tmp_path) |
| 183 | |
| 184 | assert object_signup.confirm_signup(token, PASSWORD, base_dir=tmp_path) is None |
| 185 | assert object_identity.get_user(user["user_id"], base_dir=tmp_path)["status"] == "pending" |
| 186 | assert not object_credentials.has_password(user["user_id"], base_dir=tmp_path) |
| 187 | |
| 188 | |
| 189 | def test_reset_sets_the_password_and_signs_out_everywhere(tmp_path): |
| 190 | user = object_signup.register("ann@example.org", base_dir=tmp_path, now=NOW)["user"] |
| 191 | object_credentials.set_password(user["user_id"], PASSWORD, base_dir=tmp_path) |
| 192 | object_identity.set_user_status(user["user_id"], "active", base_dir=tmp_path) |
| 193 | session = object_identity.create_session({"user_id": user["user_id"]}, base_dir=tmp_path, require_known_user=True) |
| 194 | token = object_signup.issue_token(object_signup.PASSWORD_RESET, user["user_id"], user["email"], base_dir=tmp_path) |
| 195 | |
| 196 | with pytest.raises(object_signup.SignupError): |
| 197 | object_signup.reset_password(token, "short", base_dir=tmp_path) |
| 198 | # a password that won't do leaves the link usable |
| 199 | assert object_signup.peek_token(token, object_signup.PASSWORD_RESET, base_dir=tmp_path) is not None |
| 200 | |
| 201 | assert object_signup.reset_password(token, "a brand new password", base_dir=tmp_path)["user_id"] == user["user_id"] |
| 202 | assert object_credentials.verify_password(user["user_id"], "a brand new password", base_dir=tmp_path) |
| 203 | assert not object_credentials.verify_password(user["user_id"], PASSWORD, base_dir=tmp_path) |
| 204 | assert object_identity.resolve_session_token(session["token"], base_dir=tmp_path) is None |
| 205 | assert object_signup.reset_password(token, "yet another password", base_dir=tmp_path) is None |
| 206 | |
| 207 | |
| 208 | def test_reset_confirms_a_pending_address(tmp_path): |
| 209 | user = object_signup.register("ann@example.org", base_dir=tmp_path, now=NOW)["user"] |
| 210 | token = object_signup.issue_token(object_signup.PASSWORD_RESET, user["user_id"], user["email"], base_dir=tmp_path) |
| 211 | |
| 212 | assert object_signup.reset_password(token, "a brand new password", base_dir=tmp_path)["status"] == "active" |
| 213 | |
| 214 | |
| 215 | def _active_user_with_password(tmp_path): |
| 216 | user = object_signup.register("ann@example.org", base_dir=tmp_path, now=NOW)["user"] |
| 217 | object_credentials.set_password(user["user_id"], PASSWORD, base_dir=tmp_path) |
| 218 | object_identity.set_user_status(user["user_id"], "active", base_dir=tmp_path) |
| 219 | return user |
| 220 | |
| 221 | |
| 222 | @pytest.mark.parametrize("change", ["set", "removed"]) |
| 223 | def test_a_reset_link_does_not_survive_a_later_password_change(tmp_path, change): |
| 224 | """An admin resets or removes the password after the link went out (say, because the account was |
| 225 | compromised): before, the link still chose a new password for the rest of its hour.""" |
| 226 | user = _active_user_with_password(tmp_path) |
| 227 | token = object_signup.issue_token(object_signup.PASSWORD_RESET, user["user_id"], user["email"], base_dir=tmp_path) |
| 228 | if change == "set": |
| 229 | object_credentials.set_password(user["user_id"], "the admin's new password", base_dir=tmp_path) |
| 230 | else: |
| 231 | object_credentials.remove_password(user["user_id"], base_dir=tmp_path) |
| 232 | |
| 233 | assert object_signup.peek_token(token, object_signup.PASSWORD_RESET, base_dir=tmp_path) is None |
| 234 | assert object_signup.reset_password(token, "an attacker's password", base_dir=tmp_path) is None |
| 235 | assert not object_credentials.verify_password(user["user_id"], "an attacker's password", base_dir=tmp_path) |
| 236 | |
| 237 | |
| 238 | def test_a_confirm_link_does_not_survive_a_password_set_after_it(tmp_path): |
| 239 | """A pending user whose password an operator set after the link went out: the link must not replace it.""" |
| 240 | user = object_signup.register("ann@example.org", base_dir=tmp_path, now=NOW)["user"] |
| 241 | token = object_signup.issue_token(object_signup.VERIFY_EMAIL, user["user_id"], user["email"], base_dir=tmp_path) |
| 242 | object_credentials.set_password(user["user_id"], "the operator's password", base_dir=tmp_path) |
| 243 | |
| 244 | assert object_signup.confirm_signup(token, "someone else's password", base_dir=tmp_path) is None |
| 245 | assert object_credentials.verify_password(user["user_id"], "the operator's password", base_dir=tmp_path) |
| 246 | |
| 247 | |
| 248 | def test_a_link_from_before_links_were_bound_to_the_password_is_refused(tmp_path): |
| 249 | """A row written without the credential column (an older server) fails closed.""" |
| 250 | user = _active_user_with_password(tmp_path) |
| 251 | token = object_signup.issue_token(object_signup.PASSWORD_RESET, user["user_id"], user["email"], base_dir=tmp_path) |
| 252 | path = object_signup.tokens_path(tmp_path) |
| 253 | rows = object_signup._read_tokens(path) |
| 254 | for row in rows: |
| 255 | row.pop("credential", None) |
| 256 | object_signup._write_tokens(path, rows) |
| 257 | |
| 258 | assert object_signup.reset_password(token, "a brand new password", base_dir=tmp_path) is None |
| 259 | assert object_credentials.verify_password(user["user_id"], PASSWORD, base_dir=tmp_path) |
| 260 | |
| 261 | |
| 262 | @pytest.mark.parametrize("status", ["disabled", "suspended", ""]) |
| 263 | def test_a_reset_link_does_nothing_for_a_user_who_is_no_longer_active_or_pending(tmp_path, status): |
| 264 | """Only "disabled" used to be refused: a status this version does not know (a hand edit, a newer |
| 265 | version's "suspended", an emptied cell) let the link set the password. Unknown is not active.""" |
| 266 | import csv |
| 267 | user = _active_user_with_password(tmp_path) |
| 268 | token = object_signup.issue_token(object_signup.PASSWORD_RESET, user["user_id"], user["email"], base_dir=tmp_path) |
| 269 | path = object_identity.users_path(tmp_path) |
| 270 | with path.open(newline="") as handle: |
| 271 | reader = csv.DictReader(handle, delimiter="\t") |
| 272 | fields, rows = reader.fieldnames, list(reader) |
| 273 | for row in rows: |
| 274 | row["status"] = status |
| 275 | with path.open("w", newline="") as handle: |
| 276 | writer = csv.DictWriter(handle, fieldnames=fields, delimiter="\t") |
| 277 | writer.writeheader() |
| 278 | writer.writerows(rows) |
| 279 | |
| 280 | assert object_signup.reset_password(token, "a brand new password", base_dir=tmp_path) is None |
| 281 | assert object_credentials.verify_password(user["user_id"], PASSWORD, base_dir=tmp_path) |
| 282 | |
| 283 | |
| 284 | def test_disabled_users_get_no_reset_link(tmp_path): |
| 285 | user = object_signup.register("ann@example.org", base_dir=tmp_path, now=NOW)["user"] |
| 286 | assert object_signup.reset_candidate("ANN@example.org", base_dir=tmp_path)["user_id"] == user["user_id"] |
| 287 | object_identity.set_user_status(user["user_id"], "disabled", base_dir=tmp_path) |
| 288 | assert object_signup.reset_candidate("ann@example.org", base_dir=tmp_path) is None |
| 289 | assert object_signup.reset_candidate("nobody@example.org", base_dir=tmp_path) is None |
| 290 | |
| 291 | |
| 292 | # ---- whether it may run --------------------------------------------------- |
| 293 | |
| 294 | |
| 295 | @pytest.mark.parametrize("value,expected", [ |
| 296 | ("https://example.org", "https://example.org"), |
| 297 | ("https://example.org/", "https://example.org"), |
| 298 | ("https://example.org/app", "https://example.org/app"), |
| 299 | ("http://localhost:8001", "http://localhost:8001"), |
| 300 | ("http://example.org", None), |
| 301 | ("example.org", None), |
| 302 | ("https://example.org/?next=x", None), |
| 303 | ("", None), |
| 304 | ]) |
| 305 | def test_public_url_must_be_https_except_on_this_machine(value, expected): |
| 306 | assert object_signup.public_url({object_signup.PUBLIC_URL_ENV: value}) == expected |
| 307 | |
| 308 | |
| 309 | def test_the_starter_policy_no_longer_blocks_open_signup_but_the_rule_it_used_to_carry_does(): |
| 310 | starter = object_permissions.policy_from_dict(object_permission_store.starter_policy_payload()) |
| 311 | assert object_signup.unscoped_registered_rules(starter) == [] |
| 312 | |
| 313 | # The rule the starter policy used to ship, still present on a box that |
| 314 | # started from it and that nobody removed. |
| 315 | legacy = object_permissions.policy_from_dict({ |
| 316 | "access_mode": "role_based", |
| 317 | "rules": [{"effect": "allow", "principal": "registered", "actions": ["read", "execute"], |
| 318 | "reason": "signed-in users can read and run objects"}], |
| 319 | }) |
| 320 | assert object_signup.unscoped_registered_rules(legacy) |
| 321 | |
| 322 | scoped = object_permissions.PermissionPolicy(rules=( |
| 323 | object_permissions.PermissionRule.allow("registered", ["read", "create"], collection="notes", row_filter={"owner_id": "$user_id"}), |
| 324 | object_permissions.PermissionRule.allow("public", ["read"]), |
| 325 | )) |
| 326 | assert object_signup.unscoped_registered_rules(scoped) == [] |
| 327 | |
| 328 | |
| 329 | def test_blockers_name_everything_that_is_missing(tmp_path): |
| 330 | blockers = object_signup.signup_blockers( |
| 331 | policy=object_permissions.PermissionPolicy(), |
| 332 | enforcement_enabled=False, |
| 333 | password_login_enabled=False, |
| 334 | base_dir=tmp_path, |
| 335 | env={}, |
| 336 | ) |
| 337 | text = "\n".join(blockers) |
| 338 | for needed in ("DBBASIC_ENABLE_SIGNUP", "DBBASIC_ENABLE_PASSWORD_LOGIN", "DBBASIC_ENABLE_PERMISSION_ENFORCEMENT", |
| 339 | "DBBASIC_SMTP_MODE", "app-email", "DBBASIC_PUBLIC_URL"): |
| 340 | assert needed in text |
| 341 | |
| 342 | reset = "\n".join(object_signup.reset_blockers(password_login_enabled=True, base_dir=tmp_path, env={})) |
| 343 | assert "DBBASIC_ENABLE_PASSWORD_RESET" in reset and "DBBASIC_ENABLE_PERMISSION_ENFORCEMENT" not in reset |
| 344 | |
| 345 | |
| 346 | # ---- the browser flow ------------------------------------------------------- |
| 347 | |
| 348 | |
| 349 | @pytest.fixture |
| 350 | def open_signup(tmp_path, monkeypatch): |
| 351 | """A server where signup and reset may run: email in log mode, app-email installed.""" |
| 352 | data_dir = tmp_path / "data" |
| 353 | object_root = tmp_path / "objects" |
| 354 | object_root.mkdir() |
| 355 | object_packages.install_package("app-email", root=PACKAGES_ROOT, base_dir=data_dir, |
| 356 | object_roots=[object_root], allow_replace=True) |
| 357 | monkeypatch.setenv(object_server.DATA_DIR_ENV, str(data_dir)) |
| 358 | monkeypatch.setenv(object_server.PASSWORD_LOGIN_ENV, "true") |
| 359 | monkeypatch.setenv(object_signup.SIGNUP_ENV, "true") |
| 360 | monkeypatch.setenv(object_signup.PASSWORD_RESET_ENV, "true") |
| 361 | monkeypatch.setenv(object_signup.PUBLIC_URL_ENV, "https://desk.example.org") |
| 362 | monkeypatch.setenv("DBBASIC_SMTP_MODE", "log") |
| 363 | monkeypatch.setenv(object_server.COOKIE_SECURE_ENV, "false") |
| 364 | monkeypatch.setattr(object_server, "_permission_enforcement_enabled", lambda: True) |
| 365 | monkeypatch.setattr(object_server, "PASSWORD_LOGIN_FAILURE_DELAY_SECONDS", 0) |
| 366 | assert object_server._signup_blockers() == [] |
| 367 | return data_dir |
| 368 | |
| 369 | |
| 370 | def _post(path, form, headers=()): |
| 371 | return raw_request( |
| 372 | path, |
| 373 | method="POST", |
| 374 | body=urllib.parse.urlencode(form).encode(), |
| 375 | headers=[("content-type", "application/x-www-form-urlencoded"), *headers], |
| 376 | ) |
| 377 | |
| 378 | |
| 379 | def _mail(data_dir): |
| 380 | return object_records.read_collection_records("email_outbox", base_dir=data_dir) |
| 381 | |
| 382 | |
| 383 | def _token_from(mail_row, path): |
| 384 | match = re.search(r"https://desk\.example\.org" + re.escape(path) + r"\?token=([A-Za-z0-9_%-]+)", mail_row["text_body"]) |
| 385 | assert match, mail_row["text_body"] |
| 386 | return urllib.parse.unquote(match.group(1)) |
| 387 | |
| 388 | |
| 389 | def _cookie(headers): |
| 390 | value = headers.get(b"set-cookie", b"").decode() |
| 391 | return value.split(";", 1)[0] |
| 392 | |
| 393 | |
| 394 | def test_signup_is_closed_until_everything_is_in_place(tmp_path, monkeypatch): |
| 395 | monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path)) |
| 396 | monkeypatch.setenv(object_signup.SIGNUP_ENV, "true") |
| 397 | |
| 398 | status, _, body = raw_request("/signup") |
| 399 | assert status == 403 |
| 400 | assert b"can't be created" in body |
| 401 | status, _, _ = _post("/signup", {"email": "ann@example.org"}) |
| 402 | assert status == 403 |
| 403 | assert object_identity.list_users(base_dir=tmp_path) == [] |
| 404 | |
| 405 | monkeypatch.setenv(object_server.PASSWORD_LOGIN_ENV, "true") |
| 406 | _, _, login = raw_request("/login") |
| 407 | assert b"Create an account" not in login and b"Forgot your password" not in login |
| 408 | |
| 409 | |
| 410 | def test_signup_verify_and_sign_in(open_signup, monkeypatch): |
| 411 | data_dir = open_signup |
| 412 | _, _, login = raw_request("/login") |
| 413 | assert b'href="/signup"' in login and b'href="/reset"' in login |
| 414 | assert b"choose your password there" in login |
| 415 | |
| 416 | # the form asks for no password |
| 417 | _, _, form = raw_request("/signup") |
| 418 | assert b'name="password"' not in form |
| 419 | |
| 420 | # a password sent anyway (an old form, a script) is ignored |
| 421 | status, headers, _ = _post("/signup", {"email": "ann@example.org", "display_name": "Not Ann", "password": "sent by a stranger"}) |
| 422 | assert status == 303 and headers[b"location"] == b"/signup?sent=1" |
| 423 | (pending,) = object_identity.find_users_by_email("ann@example.org", base_dir=data_dir) |
| 424 | assert not object_credentials.has_password(pending["user_id"], base_dir=data_dir) |
| 425 | assert pending["display_name"] == "" |
| 426 | status, _, body = raw_request("/signup", query_string="sent=1") |
| 427 | assert b"Check your email" in body |
| 428 | |
| 429 | (mail,) = _mail(data_dir) |
| 430 | assert mail["to"] == "ann@example.org" |
| 431 | assert "choose your password" in mail["text_body"] |
| 432 | token = _token_from(mail, "/verify") |
| 433 | (user,) = object_identity.find_users_by_email("ann@example.org", base_dir=data_dir) |
| 434 | assert user["status"] == "pending" |
| 435 | |
| 436 | # a password typed into the signup form, or at sign-in, gets a stranger nothing |
| 437 | for guess in (PASSWORD, "sent by a stranger"): |
| 438 | status, headers, _ = _post("/login", {"email": "ann@example.org", "password": guess}) |
| 439 | assert headers[b"location"] == b"/login?error=1" |
| 440 | assert b"set-cookie" not in headers |
| 441 | assert len(_mail(data_dir)) == 1 |
| 442 | |
| 443 | # opening the link only shows the form, and does not use the link up |
| 444 | status, _, body = raw_request("/verify", query_string=f"token={token}") |
| 445 | assert status == 200 and b"Confirm my email" in body and b'name="password"' in body |
| 446 | assert object_signup.peek_token(token, object_signup.VERIFY_EMAIL, base_dir=data_dir) is not None |
| 447 | |
| 448 | # a password that won't do keeps the link alive |
| 449 | status, _, body = _post("/verify", {"token": token, "password": "short", "display_name": "Ann <b>"}) |
| 450 | assert status == 400 and b"at least 8 characters" in body and b"Ann <b>" in body |
| 451 | assert object_signup.peek_token(token, object_signup.VERIFY_EMAIL, base_dir=data_dir) is not None |
| 452 | |
| 453 | monkeypatch.setenv(object_server.LANDING_PATH_ENV, "/sell/?confirmed=1") |
| 454 | status, headers, _ = _post("/verify", {"token": token, "password": PASSWORD, "display_name": "Ann"}) |
| 455 | assert status == 303 and headers[b"location"] == b"/sell/?confirmed=1" |
| 456 | assert _cookie(headers).startswith("dbbasic_session=") and _cookie(headers) != "dbbasic_session=" |
| 457 | (user,) = object_identity.find_users_by_email("ann@example.org", base_dir=data_dir) |
| 458 | assert user["status"] == "active" and user["display_name"] == "Ann" |
| 459 | |
| 460 | status, _, body = raw_request("/verify", query_string=f"token={token}") |
| 461 | assert status == 400 and b"expired or was already used" in body and b'href="/signup"' in body |
| 462 | status, _, body = _post("/verify", {"token": token, "password": "another password"}) |
| 463 | assert status == 400 and b"expired or was already used" in body |
| 464 | |
| 465 | status, headers, _ = _post("/login", {"email": "ann@example.org", "password": PASSWORD}) |
| 466 | assert headers[b"location"] == b"/sell/?confirmed=1" and _cookie(headers).startswith("dbbasic_session=") |
| 467 | |
| 468 | |
| 469 | def test_a_landing_path_that_is_not_local_is_reported_not_silently_ignored(open_signup, monkeypatch): |
| 470 | assert object_server._signup_blockers() == [] |
| 471 | monkeypatch.setenv(object_server.LANDING_PATH_ENV, "https://evil.example/") |
| 472 | (blocker,) = object_server._signup_blockers() |
| 473 | assert "DBBASIC_AUTH_LANDING_PATH" in blocker |
| 474 | monkeypatch.setenv(object_server.LANDING_PATH_ENV, "/sell/?confirmed=1") |
| 475 | assert object_server._signup_blockers() == [] |
| 476 | |
| 477 | |
| 478 | def test_the_landing_path_is_local_only(monkeypatch): |
| 479 | monkeypatch.delenv(object_server.LANDING_PATH_ENV, raising=False) |
| 480 | assert object_server._landing_path() == "/" |
| 481 | for bad in ("https://evil.example/", "//evil.example", "evil", "/a\\b"): |
| 482 | monkeypatch.setenv(object_server.LANDING_PATH_ENV, bad) |
| 483 | assert object_server._landing_path() == "/" |
| 484 | monkeypatch.setenv(object_server.LANDING_PATH_ENV, "/sell/") |
| 485 | assert object_server._landing_path() == "/sell/" |
| 486 | |
| 487 | |
| 488 | def test_auth_pages_send_an_origin_with_their_forms(open_signup): |
| 489 | """no-referrer made browsers send "Origin: null" with a form post, which the same-origin check refuses.""" |
| 490 | for path in ("/login", "/signup", "/reset"): |
| 491 | _, _, body = raw_request(path) |
| 492 | assert b'<meta name="referrer" content="strict-origin">' in body |
| 493 | assert b"no-referrer" not in body |
| 494 | |
| 495 | |
| 496 | def test_signup_for_a_taken_address_looks_the_same_but_tells_the_mailbox(open_signup): |
| 497 | data_dir = open_signup |
| 498 | user = object_signup.register("ann@example.org", base_dir=data_dir)["user"] |
| 499 | object_credentials.set_password(user["user_id"], PASSWORD, base_dir=data_dir) |
| 500 | object_identity.set_user_status(user["user_id"], "active", base_dir=data_dir) |
| 501 | |
| 502 | status, headers, _ = _post("/signup", {"email": "Ann@Example.org"}) |
| 503 | assert status == 303 and headers[b"location"] == b"/signup?sent=1" |
| 504 | (mail,) = _mail(data_dir) |
| 505 | assert mail["subject"] == "You already have an account" |
| 506 | assert "https://desk.example.org/reset" in mail["text_body"] |
| 507 | assert len(object_identity.list_users(base_dir=data_dir)) == 1 |
| 508 | |
| 509 | |
| 510 | def test_signup_form_errors_keep_what_was_typed(open_signup): |
| 511 | status, _, body = _post("/signup", {"email": "not an email"}) |
| 512 | assert status == 400 |
| 513 | assert b"valid email" in body |
| 514 | assert b'value="not an email"' in body |
| 515 | |
| 516 | |
| 517 | def test_signup_is_rate_limited_per_address_and_per_ip(open_signup, monkeypatch): |
| 518 | monkeypatch.setattr(object_server, "SIGNUP_ATTEMPTS_PER_HOUR_PER_IP", 2) |
| 519 | _post("/signup", {"email": "a1@example.org"}) |
| 520 | _post("/signup", {"email": "a2@example.org"}) |
| 521 | status, _, body = _post("/signup", {"email": "a3@example.org"}) |
| 522 | assert status == 429 and b"Too many" in body |
| 523 | assert len(object_identity.list_users(base_dir=open_signup)) == 2 |
| 524 | |
| 525 | |
| 526 | def test_a_cross_site_signup_form_is_refused(open_signup): |
| 527 | status, _, _ = _post("/signup", {"email": "ann@example.org"}, |
| 528 | headers=[("host", "desk.example.org"), ("origin", "https://evil.example")]) |
| 529 | assert status == 400 |
| 530 | assert object_identity.list_users(base_dir=open_signup) == [] |
| 531 | |
| 532 | |
| 533 | def test_password_reset_end_to_end(open_signup): |
| 534 | data_dir = open_signup |
| 535 | user = object_signup.register("ann@example.org", base_dir=data_dir)["user"] |
| 536 | object_credentials.set_password(user["user_id"], PASSWORD, base_dir=data_dir) |
| 537 | object_identity.set_user_status(user["user_id"], "active", base_dir=data_dir) |
| 538 | session = object_identity.create_session({"user_id": user["user_id"]}, base_dir=data_dir, require_known_user=True) |
| 539 | |
| 540 | # an unknown address gets the same answer and no email |
| 541 | status, headers, _ = _post("/reset", {"email": "nobody@example.org"}) |
| 542 | assert headers[b"location"] == b"/reset?sent=1" |
| 543 | assert _mail(data_dir) == [] |
| 544 | |
| 545 | status, headers, _ = _post("/reset", {"email": "ANN@example.org"}) |
| 546 | assert headers[b"location"] == b"/reset?sent=1" |
| 547 | (mail,) = _mail(data_dir) |
| 548 | token = _token_from(mail, "/reset/confirm") |
| 549 | |
| 550 | status, _, body = raw_request("/reset/confirm", query_string=f"token={token}") |
| 551 | assert status == 200 and b"Choose a new password" in body |
| 552 | |
| 553 | status, _, body = _post("/reset/confirm", {"token": token, "password": "short"}) |
| 554 | assert status == 400 and b"at least 8 characters" in body |
| 555 | |
| 556 | status, headers, _ = _post("/reset/confirm", {"token": token, "password": "a brand new password"}) |
| 557 | assert status == 303 and headers[b"location"] == b"/login?reset=1" |
| 558 | assert object_identity.resolve_session_token(session["token"], base_dir=data_dir) is None |
| 559 | |
| 560 | _, _, body = raw_request("/login", query_string="reset=1") |
| 561 | assert b"Your password was changed" in body |
| 562 | status, headers, _ = _post("/login", {"email": "ann@example.org", "password": "a brand new password"}) |
| 563 | assert headers[b"location"] == b"/" |
| 564 | |
| 565 | status, _, body = _post("/reset/confirm", {"token": token, "password": "another new password"}) |
| 566 | assert status == 400 and b"expired or was already used" in body |
| 567 | |
| 568 | |
| 569 | def _count_reset_work(monkeypatch): |
| 570 | """Wrap the steps a reset request spends its time on, and count the calls to each.""" |
| 571 | import secrets as secrets_module |
| 572 | |
| 573 | counts = {} |
| 574 | |
| 575 | def counted(owner, name): |
| 576 | original = getattr(owner, name) |
| 577 | |
| 578 | def wrapper(*args, **kwargs): |
| 579 | counts[name] = counts.get(name, 0) + 1 |
| 580 | return original(*args, **kwargs) |
| 581 | |
| 582 | monkeypatch.setattr(owner, name, wrapper) |
| 583 | |
| 584 | counted(secrets_module, "token_urlsafe") |
| 585 | counted(object_identity, "hash_token") |
| 586 | counted(object_signup, "_credential_state") |
| 587 | counted(object_signup, "_read_tokens") |
| 588 | counted(object_signup, "_write_tokens") |
| 589 | counted(object_signup, "reset_email") |
| 590 | counted(object_server, "_email_address_rate_limited") |
| 591 | counted(object_identity, "find_users_by_email") |
| 592 | return counts |
| 593 | |
| 594 | |
| 595 | def test_a_reset_request_does_the_same_work_for_an_address_without_an_account(open_signup, monkeypatch): |
| 596 | """An unknown address used to answer after a user lookup and nothing else; a known one also made, hashed and |
| 597 | stored a token and queued an email. The difference could be timed to learn which addresses have accounts.""" |
| 598 | data_dir = open_signup |
| 599 | user = object_signup.register("ann@example.org", base_dir=data_dir)["user"] |
| 600 | object_credentials.set_password(user["user_id"], PASSWORD, base_dir=data_dir) |
| 601 | object_identity.set_user_status(user["user_id"], "active", base_dir=data_dir) |
| 602 | gone = object_signup.register("gone@example.org", base_dir=data_dir)["user"] |
| 603 | object_identity.set_user_status(gone["user_id"], "disabled", base_dir=data_dir) |
| 604 | |
| 605 | answers, work = {}, {} |
| 606 | for address in ("ann@example.org", "nobody@example.org", "gone@example.org"): |
| 607 | with pytest.MonkeyPatch.context() as counting: |
| 608 | counts = _count_reset_work(counting) |
| 609 | status, headers, body = _post("/reset", {"email": address}) |
| 610 | answers[address] = (status, headers.get(b"location"), headers.get(b"content-type"), body) |
| 611 | work[address] = dict(counts) |
| 612 | |
| 613 | assert answers["ann@example.org"] == answers["nobody@example.org"] == answers["gone@example.org"] |
| 614 | assert work["ann@example.org"] == work["nobody@example.org"] == work["gone@example.org"] |
| 615 | assert work["ann@example.org"]["token_urlsafe"] >= 1 and work["ann@example.org"]["_write_tokens"] == 1 |
| 616 | |
| 617 | # only the address with an account was sent a link, and only its link was stored |
| 618 | (mail,) = _mail(data_dir) |
| 619 | assert mail["to"] == "ann@example.org" |
| 620 | rows = object_signup._read_tokens(object_signup.tokens_path(data_dir)) |
| 621 | assert [r["user_id"] for r in rows] == [user["user_id"]] |
| 622 | |
| 623 | |
| 624 | def test_a_reset_email_that_cannot_be_queued_does_not_change_the_answer(open_signup, monkeypatch): |
| 625 | data_dir = open_signup |
| 626 | user = object_signup.register("ann@example.org", base_dir=data_dir)["user"] |
| 627 | object_identity.set_user_status(user["user_id"], "active", base_dir=data_dir) |
| 628 | unknown = _post("/reset", {"email": "nobody@example.org"}) |
| 629 | |
| 630 | def broken_outbox(*args, **kwargs): |
| 631 | raise OSError("outbox is not writable") |
| 632 | |
| 633 | monkeypatch.setattr(object_signup, "send", broken_outbox) |
| 634 | known = _post("/reset", {"email": "ann@example.org"}) |
| 635 | assert (known[0], known[1][b"location"], known[2]) == (unknown[0], unknown[1][b"location"], unknown[2]) |
| 636 | events = object_server.object_ops_log.read_events(base_dir=data_dir, kind="auth") |
| 637 | assert any(e.get("event") == "password_reset_mail_failed" and e.get("user_id") == user["user_id"] for e in events) |
| 638 | |
| 639 | |
| 640 | def test_a_reset_clears_the_login_lockout(open_signup, monkeypatch): |
| 641 | data_dir = open_signup |
| 642 | monkeypatch.setenv(object_server.LOGIN_LOCKOUT_ATTEMPTS_ENV, "2") |
| 643 | user = object_signup.register("ann@example.org", base_dir=data_dir)["user"] |
| 644 | object_credentials.set_password(user["user_id"], PASSWORD, base_dir=data_dir) |
| 645 | object_identity.set_user_status(user["user_id"], "active", base_dir=data_dir) |
| 646 | for _ in range(2): |
| 647 | _post("/login", {"email": "ann@example.org", "password": "wrong password"}) |
| 648 | _, headers, _ = _post("/login", {"email": "ann@example.org", "password": PASSWORD}) |
| 649 | assert headers[b"location"] == b"/login?error=locked" |
| 650 | |
| 651 | token = object_signup.issue_token(object_signup.PASSWORD_RESET, user["user_id"], user["email"], base_dir=data_dir) |
| 652 | _post("/reset/confirm", {"token": token, "password": "a brand new password"}) |
| 653 | _, headers, _ = _post("/login", {"email": "ann@example.org", "password": "a brand new password"}) |
| 654 | assert headers[b"location"] == b"/" |
| 655 | |
| 656 | |
| 657 | def _json_login(email, password): |
| 658 | import json |
| 659 | status, _, _ = raw_request("/identity/session", method="POST", |
| 660 | body=json.dumps({"email": email, "password": password}).encode(), |
| 661 | headers=[("content-type", "application/json")]) |
| 662 | return status |
| 663 | |
| 664 | |
| 665 | def test_the_login_lockout_counts_every_spelling_of_one_address(open_signup, monkeypatch): |
| 666 | """Sign-in matches the address ignoring case and surrounding spaces, but the lockout counted failures per |
| 667 | spelling, so changing one letter's case (or adding a space, endlessly, over JSON) bought fresh tries.""" |
| 668 | data_dir = open_signup |
| 669 | monkeypatch.setenv(object_server.LOGIN_LOCKOUT_ATTEMPTS_ENV, "3") |
| 670 | user = object_signup.register("Ann@Example.org", base_dir=data_dir)["user"] |
| 671 | object_credentials.set_password(user["user_id"], PASSWORD, base_dir=data_dir) |
| 672 | object_identity.set_user_status(user["user_id"], "active", base_dir=data_dir) |
| 673 | |
| 674 | _post("/login", {"email": "ann@example.org", "password": "wrong password"}) |
| 675 | _post("/login", {"email": "ANN@example.org", "password": "wrong password"}) |
| 676 | assert _json_login(" ann@example.org ", "wrong password") == 401 |
| 677 | |
| 678 | _, headers, _ = _post("/login", {"email": "aNn@example.org", "password": PASSWORD}) |
| 679 | assert headers[b"location"] == b"/login?error=locked" |
| 680 | assert _json_login("ann@EXAMPLE.org ", PASSWORD) == 429 |
| 681 | assert _json_login("someone-else@example.org", PASSWORD) == 401 # still per address |
| 682 | |
| 683 | # and a reset, logged under the address as stored ("Ann@Example.org"), ends the run of failures for all of them |
| 684 | token = object_signup.issue_token(object_signup.PASSWORD_RESET, user["user_id"], user["email"], base_dir=data_dir) |
| 685 | _post("/reset/confirm", {"token": token, "password": "a brand new password"}) |
| 686 | _, headers, _ = _post("/login", {"email": "ann@example.org", "password": "a brand new password"}) |
| 687 | assert headers[b"location"] == b"/" |
| 688 | |
| 689 | |
| 690 | def test_admin_capabilities_show_why_signup_is_off(tmp_path, monkeypatch): |
| 691 | monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path)) |
| 692 | identity = object_server._admin_capabilities_payload()["identity"] |
| 693 | assert identity["signup_enabled"] is False |
| 694 | assert any("DBBASIC_ENABLE_SIGNUP" in b for b in identity["signup_blockers"]) |
| 695 | assert identity["public_url_env"] == "DBBASIC_PUBLIC_URL" |
| 696 | |
| 697 | |
| 698 | # ---- lookalike addresses ------------------------------------------------------ |
| 699 | |
| 700 | FULLWIDTH_ANN = "\uff41nn@example.org" # "\uff41nn": looks like ann@example.org, NFKC folds it to that |
| 701 | |
| 702 | |
| 703 | def _active(data_dir, user_id, email, password=PASSWORD): |
| 704 | object_identity.create_user({"user_id": user_id, "email": email}, base_dir=data_dir) |
| 705 | object_credentials.set_password(user_id, password, base_dir=data_dir) |
| 706 | |
| 707 | |
| 708 | def test_a_lookalike_address_is_the_same_address_at_signup(open_signup): |
| 709 | data_dir = open_signup |
| 710 | user = object_signup.register("ann@example.org", base_dir=data_dir)["user"] |
| 711 | object_identity.set_user_status(user["user_id"], "active", base_dir=data_dir) |
| 712 | |
| 713 | for lookalike in (FULLWIDTH_ANN, "ANN@EXAMPLE.ORG", "ann@ex\uff41mple.org"): |
| 714 | result = object_signup.register(lookalike, base_dir=data_dir) |
| 715 | assert result["outcome"] == "exists" and result["user"]["user_id"] == user["user_id"] |
| 716 | assert len(object_identity.list_users(base_dir=data_dir)) == 1 |
| 717 | |
| 718 | status, headers, _ = _post("/signup", {"email": FULLWIDTH_ANN}) |
| 719 | assert headers[b"location"] == b"/signup?sent=1" |
| 720 | (mail,) = _mail(data_dir) |
| 721 | assert mail["subject"] == "You already have an account" and mail["to"] == "ann@example.org" |
| 722 | |
| 723 | |
| 724 | @pytest.mark.parametrize("hidden", ["\u200b", "\u200d", "\u202e", "\u2066", "\u00ad", "\ufeff", "\x07"]) |
| 725 | def test_an_address_with_an_invisible_or_control_character_is_refused(tmp_path, hidden): |
| 726 | with pytest.raises(object_signup.SignupError): |
| 727 | object_signup.register(f"ann{hidden}@example.org", base_dir=tmp_path) |
| 728 | assert object_identity.list_users(base_dir=tmp_path) == [] |
| 729 | |
| 730 | |
| 731 | def test_sign_in_and_reset_find_a_user_by_a_lookalike_spelling(open_signup): |
| 732 | data_dir = open_signup |
| 733 | _active(data_dir, "ann", "ann@example.org") |
| 734 | _, headers, _ = _post("/login", {"email": FULLWIDTH_ANN, "password": PASSWORD}) |
| 735 | assert headers[b"location"] == b"/" |
| 736 | assert object_signup.reset_candidate(FULLWIDTH_ANN, base_dir=data_dir)["user_id"] == "ann" |
| 737 | |
| 738 | |
| 739 | def test_a_user_stored_under_a_lookalike_form_is_still_found(open_signup): |
| 740 | """No migration: stored addresses are folded when compared, so a user saved under any form is found by |
| 741 | that form and by its plain one.""" |
| 742 | data_dir = open_signup |
| 743 | _active(data_dir, "ann", FULLWIDTH_ANN) |
| 744 | for typed in (FULLWIDTH_ANN, "ann@example.org"): |
| 745 | _, headers, _ = _post("/login", {"email": typed, "password": PASSWORD}) |
| 746 | assert headers[b"location"] == b"/", typed |
| 747 | assert object_signup.register("ann@example.org", base_dir=data_dir)["outcome"] == "exists" |
| 748 | |
| 749 | |
| 750 | def test_two_users_stored_before_folding_each_keep_signing_in(open_signup): |
| 751 | """Two users stored under addresses that now share a key are not locked out as ambiguous: the spelling |
| 752 | each was stored under still finds exactly that user.""" |
| 753 | data_dir = open_signup |
| 754 | _active(data_dir, "plain", "ann@example.org", "plain password 1") |
| 755 | _active(data_dir, "wide", FULLWIDTH_ANN, "wide password 22") |
| 756 | _, headers, _ = _post("/login", {"email": "ann@example.org", "password": "plain password 1"}) |
| 757 | assert headers[b"location"] == b"/" |
| 758 | _, headers, _ = _post("/login", {"email": FULLWIDTH_ANN, "password": "wide password 22"}) |
| 759 | assert headers[b"location"] == b"/" |
| 760 | assert object_signup.reset_candidate("ANN@example.org", base_dir=data_dir)["user_id"] == "plain" |
| 761 | assert object_signup.reset_candidate(FULLWIDTH_ANN, base_dir=data_dir)["user_id"] == "wide" |
| 762 | # a third spelling names both, so it names nobody |
| 763 | assert object_signup.reset_candidate("\uff41\uff4e\uff4e@example.org", base_dir=data_dir) is None |
| 764 | |
| 765 | |
| 766 | def test_the_login_lockout_counts_lookalike_spellings_together(open_signup, monkeypatch): |
| 767 | data_dir = open_signup |
| 768 | monkeypatch.setenv(object_server.LOGIN_LOCKOUT_ATTEMPTS_ENV, "2") |
| 769 | _active(data_dir, "ann", "ann@example.org") |
| 770 | _post("/login", {"email": "ann@example.org", "password": "wrong password"}) |
| 771 | _post("/login", {"email": FULLWIDTH_ANN, "password": "wrong password"}) |
| 772 | _, headers, _ = _post("/login", {"email": "ann@example.org", "password": PASSWORD}) |
| 773 | assert headers[b"location"] == b"/login?error=locked" |
| 774 | assert object_server._lockout_identifier(FULLWIDTH_ANN) == "ann@example.org" |
| 775 | |
| 776 | |
| 777 | def test_a_signup_never_inherits_a_password_left_under_its_new_id(tmp_path, monkeypatch): |
| 778 | object_credentials.set_password("recycled-id", "the old owner's pass", base_dir=tmp_path) |
| 779 | monkeypatch.setattr(object_identity.object_ids, "new_uuid4", lambda: "recycled-id") |
| 780 | user = object_signup.register("ann@example.org", base_dir=tmp_path)["user"] |
| 781 | assert user["user_id"] == "recycled-id" and user["status"] == "pending" |
| 782 | assert not object_credentials.has_password("recycled-id", base_dir=tmp_path) |
| 783 | |
| 784 | |
| 785 | # ---- the lockout when the ops log can't be read -------------------------------- |
| 786 | |
| 787 | |
| 788 | def test_an_unreadable_ops_log_lets_sign_in_through_but_tells_the_operator(open_signup, monkeypatch, caplog, capsys): |
| 789 | """Fail-open is the owner's decision and stays; what changes is that it is no longer silent.""" |
| 790 | data_dir = open_signup |
| 791 | monkeypatch.setenv(object_server.LOGIN_LOCKOUT_ATTEMPTS_ENV, "2") |
| 792 | _active(data_dir, "ann", "ann@example.org") |
| 793 | real_read = object_server.object_ops_log.read_events |
| 794 | |
| 795 | def unreadable(*args, **kwargs): |
| 796 | raise OSError("ops log is unreadable") |
| 797 | |
| 798 | monkeypatch.setattr(object_server.object_ops_log, "read_events", unreadable) |
| 799 | assert object_server._login_lockout_alert() is None |
| 800 | |
| 801 | with caplog.at_level("ERROR", logger="dbbasic.object_server"): |
| 802 | for _ in range(4): |
| 803 | _post("/login", {"email": "ann@example.org", "password": "wrong password"}) |
| 804 | _, headers, _ = _post("/login", {"email": "ann@example.org", "password": PASSWORD}) |
| 805 | assert headers[b"location"] == b"/" # still fail-open: no lockout without the count |
| 806 | |
| 807 | # one warning for five sign-ins, not one each |
| 808 | warnings = [r for r in caplog.records if "Sign-in lockout is not working" in r.getMessage()] |
| 809 | assert len(warnings) == 1 and "ops log is unreadable" in warnings[0].getMessage() |
| 810 | assert "1 sign-in attempt(s)" in warnings[0].getMessage() # the first one warns at once |
| 811 | assert capsys.readouterr().err.count("Sign-in lockout is not working") == 1 |
| 812 | alert = object_server._login_lockout_alert() |
| 813 | assert alert and "5 time(s)" in alert and "ops log is unreadable" in alert |
| 814 | assert alert in object_server._admin_status_payload()["alerts"] |
| 815 | |
| 816 | # after the quiet period the next one warns again, counting the four held back and itself |
| 817 | monkeypatch.setattr(object_server, "LOGIN_LOCKOUT_ALERT_SECONDS", 0.0) |
| 818 | caplog.clear() |
| 819 | with caplog.at_level("ERROR", logger="dbbasic.object_server"): |
| 820 | _post("/login", {"email": "ann@example.org", "password": "wrong password"}) |
| 821 | (again,) = [r for r in caplog.records if "Sign-in lockout is not working" in r.getMessage()] |
| 822 | assert "5 sign-in attempt(s)" in again.getMessage() |
| 823 | |
| 824 | # a read that works again ends the alert |
| 825 | monkeypatch.setattr(object_server.object_ops_log, "read_events", real_read) |
| 826 | _post("/login", {"email": "ann@example.org", "password": PASSWORD}) |
| 827 | assert object_server._login_lockout_alert() is None |
| 828 | assert object_server._login_lockout_alert() not in object_server._admin_status_payload()["alerts"] |