diff options
Diffstat (limited to '')
| -rw-r--r-- | tests/cli/test_users.py | 110 | ||||
| -rw-r--r-- | tests/test_auth.py | 67 | ||||
| -rw-r--r-- | tests/test_config.py | 88 | ||||
| -rw-r--r-- | tests/test_models.py | 16 | ||||
| -rw-r--r-- | tests/test_views.py | 8 |
5 files changed, 267 insertions, 22 deletions
diff --git a/tests/cli/test_users.py b/tests/cli/test_users.py index 6538b27..4764c85 100644 --- a/tests/cli/test_users.py +++ b/tests/cli/test_users.py @@ -35,22 +35,23 @@ def test_users_cli_help_lists_management_commands(app: Flask) -> None: def test_users_cli_create_with_prompts_hashes_password(app: Flask) -> None: result = app.test_cli_runner().invoke( - args=["users", "create"], input="alice\nnew-secret\nnew-secret\n" + args=["users", "create"], + input="alice\nmy new secret passphrase\nmy new secret passphrase\n", ) assert result.exit_code == 0, result.output assert "Created user 'alice'." in result.output - assert "new-secret" not in result.output + assert "my new secret passphrase" not in result.output user = _get_user(app, "alice") assert user is not None - assert user.check_password("new-secret") - assert user.password_hash != "new-secret" + assert user.check_password("my new secret passphrase") + assert user.password_hash != "my new secret passphrase" def test_users_cli_create_with_username_option(app: Flask) -> None: result = app.test_cli_runner().invoke( args=["users", "create", "--username", "alice"], - input="new-secret\nnew-secret\n", + input="my new secret passphrase\nmy new secret passphrase\n", ) assert result.exit_code == 0, result.output @@ -61,7 +62,14 @@ def test_users_cli_create_rejects_duplicate(app: Flask) -> None: _add_user(app, "alice") result = app.test_cli_runner().invoke( - args=["users", "create", "--username", "alice", "--password", "other"] + args=[ + "users", + "create", + "--username", + "alice", + "--password", + "a stronger duplicate password", + ] ) assert result.exit_code != 0 @@ -74,7 +82,14 @@ def test_users_cli_create_rejects_duplicate(app: Flask) -> None: @pytest.mark.parametrize("username", ["", " "]) def test_users_cli_create_rejects_invalid_username(app: Flask, username: str) -> None: result = app.test_cli_runner().invoke( - args=["users", "create", "--username", username, "--password", "valid"] + args=[ + "users", + "create", + "--username", + username, + "--password", + "a strong password for testing", + ] ) assert result.exit_code != 0 @@ -117,22 +132,29 @@ def test_users_cli_set_password_updates_hash(app: Flask) -> None: old_hash = _get_user(app, "alice").password_hash # type: ignore[union-attr] result = app.test_cli_runner().invoke( - args=["users", "set-password", "alice"], input="replacement\nreplacement\n" + args=["users", "set-password", "alice"], + input="a long replacement passphrase\na long replacement passphrase\n", ) assert result.exit_code == 0, result.output assert "Updated password for user 'alice'." in result.output - assert "replacement" not in result.output + assert "a long replacement passphrase" not in result.output user = _get_user(app, "alice") assert user is not None assert user.password_hash != old_hash assert not user.check_password("original") - assert user.check_password("replacement") + assert user.check_password("a long replacement passphrase") def test_users_cli_set_password_missing_user(app: Flask) -> None: result = app.test_cli_runner().invoke( - args=["users", "set-password", "missing", "--password", "replacement"] + args=[ + "users", + "set-password", + "missing", + "--password", + "a long replacement passphrase", + ] ) assert result.exit_code != 0 @@ -208,13 +230,19 @@ def test_users_cli_can_manage_legacy_whitespace_username(app: Flask) -> None: _add_user(app, " alice ") reset = app.test_cli_runner().invoke( - args=["users", "set-password", " alice ", "--password", "replacement"] + args=[ + "users", + "set-password", + " alice ", + "--password", + "a long replacement passphrase", + ] ) assert reset.exit_code == 0, reset.output user = _get_user(app, " alice ") assert user is not None - assert user.check_password("replacement") + assert user.check_password("a long replacement passphrase") deleted = app.test_cli_runner().invoke(args=["users", "delete", " alice ", "--yes"]) assert deleted.exit_code == 0, deleted.output @@ -230,9 +258,63 @@ def test_users_cli_create_rolls_back_on_duplicate_race(app: Flask) -> None: patch.object(DATABASE.session, "rollback") as rollback, ): result = app.test_cli_runner().invoke( - args=["users", "create", "--username", "alice", "--password", "secret"] + args=[ + "users", + "create", + "--username", + "alice", + "--password", + "a long secret for testing", + ] ) rollback.assert_called_once() assert result.exit_code != 0 assert "User 'alice' already exists." in result.output + + +@pytest.mark.parametrize( + ("password", "error"), + [ + ("short", "at least 8 characters"), + ("good passphrase with\tab", "control characters"), + ], +) +@pytest.mark.parametrize("operation", ["create", "set-password"]) +def test_users_cli_enforces_password_policy( + app: Flask, password: str, error: str, operation: str +) -> None: + _add_user(app, "existing") + if operation == "create": + command = ["users", "create", "--username", "new"] + else: + command = ["users", "set-password", "existing"] + + result = app.test_cli_runner().invoke(args=[*command, "--password", password]) + assert result.exit_code != 0 + assert error in result.output + assert _get_user(app, "new") is None + existing = _get_user(app, "existing") + assert existing is not None and existing.check_password("original") + + +def test_users_cli_accepts_long_unicode_passphrase(app: Flask) -> None: + passphrase = "🦊 several words of my passphrase 🪁" + result = app.test_cli_runner().invoke( + args=["users", "create", "--username", "alice", "--password", passphrase] + ) + assert result.exit_code == 0, result.output + user = _get_user(app, "alice") + assert user is not None and user.check_password(passphrase) + + +@pytest.mark.parametrize("passphrase", ["12345678", " " * 8, "🦊" + "a" * 1025]) +def test_users_cli_accepts_minimum_whitespace_and_unbounded_passwords( + app: Flask, passphrase: str +) -> None: + result = app.test_cli_runner().invoke( + args=["users", "create", "--username", "alice", "--password", passphrase] + ) + assert result.exit_code == 0, result.output + user = _get_user(app, "alice") + assert user is not None and user.check_password(passphrase) diff --git a/tests/test_auth.py b/tests/test_auth.py index e0416b0..a6117b2 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -20,9 +20,72 @@ def test_load_user_returns_matching_user(app: Flask) -> None: user = User(username="account", password="secret") db.session.add(user) db.session.commit() - assert load_user(user.id) is user + assert load_user(user.get_id()) is user def test_load_user_returns_none_for_unknown_id(app: Flask) -> None: with app.app_context(): - assert load_user(99_999) is None + assert load_user("99999:" + "a" * 64) is None + + +def test_load_user_rejects_legacy_and_malformed_sessions(app: Flask) -> None: + with app.app_context(): + user = User(username="account", password="secret") + db.session.add(user) + db.session.commit() + + for identifier in ( + str(user.id), # Old ID-only sessions must not bypass revocation. + "", + "not-an-id:" + "a" * 64, + f"{user.id}:invalid", + f"{user.id}:" + "é" * 64, + f"{user.id}:" + "z" * 64, + f"{user.id}:" + "0" * 64, + f"{user.id}:" + "0" * 64 + ":trailing", + "-1:" + "0" * 64, + ): + assert load_user(identifier) is None + + +def test_password_change_invalidates_existing_session(app: Flask) -> None: + old_password = "a long original passphrase" + new_password = "a different long passphrase" + + with app.app_context(): + user = User(username="account", password=old_password) + db.session.add(user) + db.session.commit() + old_identifier = user.get_id() + + client = app.test_client() + response = client.post( + "/login", data={"username": "account", "password": old_password} + ) + assert response.status_code == 302 + assert client.get("/received").status_code == 200 + + with client.session_transaction() as session: + assert session["_user_id"] == old_identifier + + result = app.test_cli_runner().invoke( + args=["users", "set-password", "account", "--password", new_password] + ) + assert result.exit_code == 0, result.output + + with app.app_context(): + user = db.session.get(User, int(old_identifier.split(":", 1)[0])) + assert user is not None + assert user.get_id() != old_identifier + assert load_user(old_identifier) is None + assert load_user(user.get_id()) is user + + # A pre-existing, validly signed cookie no longer authenticates. + assert client.get("/received").status_code == 302 + + # Logging in with the newly chosen password still works. + response = client.post( + "/login", data={"username": "account", "password": new_password} + ) + assert response.status_code == 302 + assert client.get("/received").status_code == 200 diff --git a/tests/test_config.py b/tests/test_config.py index 1b45946..dd02c01 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -10,7 +10,7 @@ import pytest from wtforms import Field, ValidationError from wtforms.form import BaseForm -from webmentions_ssg import create_app +from webmentions_ssg import LIMITER, create_app from webmentions_ssg.config import ( DefaultConfig, DevelopmentConfig, @@ -126,7 +126,10 @@ def test_invalid_allowed_hostnames_fail_at_startup( def test_production_requires_nonempty_allowed_hostnames(tmp_path: Path) -> None: config_path = tmp_path / "production.cfg" - config_path.write_text('RATELIMIT_STORAGE_URI = "redis://localhost:6379"\n') + config_path.write_text( + 'RATELIMIT_STORAGE_URI = "redis://localhost:6379"\n' + 'SECRET_KEY = "the-production-secret-key-for-this-test"\n' + ) class EmptyHostnamesConfig(ProductionConfig): CONFIG_FILE = str(config_path) @@ -148,3 +151,84 @@ def test_environment_allowed_hostnames_override_config_file( app = create_app(LocalDevelopmentConfig) assert app.config["ALLOWED_HOSTNAMES"] == {"second.example"} + + +@pytest.mark.parametrize( + ("secret", "expected_exception"), + [ + (None, TypeError), + ("", RuntimeError), + ("short", RuntimeError), + ("REPLACE_WITH_A_LONG_RANDOM_SECRET", RuntimeError), + ("INSECURE_DEVELOPMENT_ONLY_SECRET_KEY", RuntimeError), + ("change_me_to_a_new_strong_secret_key", RuntimeError), + (123, TypeError), + ], +) +def test_production_refuses_missing_weak_or_example_secret_key( + tmp_path: Path, secret: object, expected_exception: type[Exception] +) -> None: + config_file = tmp_path / "production.cfg" + config_file.write_text("# This file intentionally has no signing key.\n") + + class SecretKeyConfig(ProductionConfig): + CONFIG_FILE = str(config_file) + LOG_FILE = str(tmp_path / "production.log") + ALLOWED_HOSTNAMES = {"example.com"} + RATELIMIT_STORAGE_URI = "redis://localhost:6379" + SECRET_KEY = secret + + with pytest.raises(expected_exception, match="SECRET_KEY"): + create_app(SecretKeyConfig) + + +def test_production_uses_persistent_configured_secret( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + # The test concerns secret-key persistence, not Redis initialization. + monkeypatch.setattr(LIMITER, "init_app", lambda app: None) + config_file = tmp_path / "production.cfg" + key = "a-fixed-key-with-32-plus-random-characters" + config_file.write_text(f"SECRET_KEY = {key!r}\n") + + class ConfiguredProduction(ProductionConfig): + CONFIG_FILE = str(config_file) + LOG_FILE = str(tmp_path / "production.log") + ALLOWED_HOSTNAMES = {"example.com"} + RATELIMIT_STORAGE_URI = "redis://localhost:6379" + + first = create_app(ConfiguredProduction) + second = create_app(ConfiguredProduction) + assert first.secret_key == key == second.secret_key + + +def test_production_accepts_environment_secret_override( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + config_file = tmp_path / "production.cfg" + config_file.write_text('SECRET_KEY = "REPLACE_WITH_A_LONG_RANDOM_SECRET"\n') + key = "another-long-persistent-secret-for-a-deployment" + monkeypatch.setenv("WEBMENTIONS_SSG_SECRET_KEY", key) + # Avoid requiring the optional Redis dependency for this configuration test. + monkeypatch.setattr(LIMITER, "init_app", lambda app: None) + + class EnvConfiguredProduction(ProductionConfig): + CONFIG_FILE = str(config_file) + LOG_FILE = str(tmp_path / "production.log") + ALLOWED_HOSTNAMES = {"example.com"} + RATELIMIT_STORAGE_URI = "redis://localhost:6379" + + app = create_app(EnvConfiguredProduction) + assert app.secret_key == key + + +def test_development_rejects_placeholder_even_with_debug(tmp_path: Path) -> None: + config_file = tmp_path / "development.cfg" + config_file.write_text('SECRET_KEY = "REPLACE_WITH_A_LONG_RANDOM_SECRET"\n') + + class LocalDevelopment(DevelopmentConfig): + CONFIG_FILE = str(config_file) + LOG_FILE = str(tmp_path / "development.log") + + with pytest.raises(RuntimeError, match="SECRET_KEY"): + create_app(LocalDevelopment) diff --git a/tests/test_models.py b/tests/test_models.py index 2fa2cb8..392b246 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -146,3 +146,19 @@ def test_source_repr() -> None: def test_sent_webmention_repr() -> None: webmention = SentWebmention(target="https://example.com/post", desired_revision=1) assert repr(webmention) == "<SentWebmention 'https://example.com/post'>" + + +def test_user_session_id_changes_when_password_hash_changes() -> None: + user = User(username="admin", password="a strong passphrase", id=42) + original_hash = user.password_hash + original_id = user.get_id() + + assert original_id.startswith("42:") + assert original_hash not in original_id + assert len(original_id.split(":", 1)[1]) == 64 + + # Even a reset to the same password rehashes with a new salt, revoking + # any old session token. + user.password = "a strong passphrase" + assert user.password_hash != original_hash + assert user.get_id() != original_id diff --git a/tests/test_views.py b/tests/test_views.py index fb12b8b..21a33bf 100644 --- a/tests/test_views.py +++ b/tests/test_views.py @@ -60,7 +60,7 @@ def log_in(app: Flask, client: FlaskClient) -> None: db.session.add(user) db.session.commit() - user_id = user.id + user_id = user.get_id() with client.session_transaction() as session: session["_user_id"] = str(user_id) @@ -422,7 +422,7 @@ def test_login_redirects_to_local_next_page( user = User(username="admin", password="test") db.session.add(user) db.session.commit() - user_id = user.id + user_id = user.get_id() mock_login_form(views_module, monkeypatch, valid=True) @@ -463,7 +463,7 @@ def test_login_rejects_unsafe_next_page( user = User(username="admin", password="test") db.session.add(user) db.session.commit() - user_id = user.id + user_id = user.get_id() mock_login_form(views_module, monkeypatch, valid=True) @@ -1173,7 +1173,7 @@ def test_admin_only_links_safe_existing_status_urls( user = User(username="admin", password="test") db.session.add(user) db.session.commit() - user_id = user.id + user_id = user.get_id() with client.session_transaction() as session: session["_user_id"] = str(user_id) |
