aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--tests/cli/test_mail.py (renamed from tests/test_cli.py)0
-rw-r--r--tests/cli/test_users.py237
-rw-r--r--webmentions_ssg/__init__.py81
-rw-r--r--webmentions_ssg/cli/__init__.py3
-rw-r--r--webmentions_ssg/cli/mail.py47
-rw-r--r--webmentions_ssg/cli/users.py105
6 files changed, 399 insertions, 74 deletions
diff --git a/tests/test_cli.py b/tests/cli/test_mail.py
index 0a2afce..0a2afce 100644
--- a/tests/test_cli.py
+++ b/tests/cli/test_mail.py
diff --git a/tests/cli/test_users.py b/tests/cli/test_users.py
new file mode 100644
index 0000000..24bab0a
--- /dev/null
+++ b/tests/cli/test_users.py
@@ -0,0 +1,237 @@
+# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+from unittest.mock import patch
+
+import pytest
+import sqlalchemy as sa
+from flask import Flask
+
+from webmentions_ssg import DATABASE
+from webmentions_ssg.models import User
+
+
+def _add_user(app: Flask, username: str, password: str = "original") -> None:
+ """Persist a user using the same model as the CLI."""
+ with app.app_context():
+ DATABASE.session.add(User(username=username, password=password))
+ DATABASE.session.commit()
+
+
+def _get_user(app: Flask, username: str) -> User | None:
+ with app.app_context():
+ return DATABASE.session.scalar(sa.select(User).where(User.username == username))
+
+
+def test_users_cli_help_lists_management_commands(app: Flask) -> None:
+ result = app.test_cli_runner().invoke(args=["users", "--help"])
+
+ assert result.exit_code == 0, result.output
+ for command in ("create", "list", "set-password", "delete"):
+ assert command in result.output
+
+
+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"
+ )
+
+ assert result.exit_code == 0, result.output
+ assert "Created user 'alice'." in result.output
+ assert "new-secret" 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"
+
+
+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",
+ )
+
+ assert result.exit_code == 0, result.output
+ assert _get_user(app, "alice") is not None
+
+
+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"]
+ )
+
+ assert result.exit_code != 0
+ assert "User 'alice' already exists." in result.output
+ user = _get_user(app, "alice")
+ assert user is not None
+ assert user.check_password("original")
+
+
+@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"]
+ )
+
+ assert result.exit_code != 0
+ assert "Username must not" in result.output
+
+
+def test_users_cli_create_rejects_empty_password(app: Flask) -> None:
+ result = app.test_cli_runner().invoke(
+ args=["users", "create", "--username", "alice", "--password", ""]
+ )
+
+ assert result.exit_code != 0
+ assert "Password must not be empty." in result.output
+ assert _get_user(app, "alice") is None
+
+
+def test_users_cli_list_empty(app: Flask) -> None:
+ result = app.test_cli_runner().invoke(args=["users", "list"])
+
+ assert result.exit_code == 0, result.output
+ assert "No users found." in result.output
+
+
+def test_users_cli_list_is_sorted_and_excludes_passwords(app: Flask) -> None:
+ _add_user(app, "zoe")
+ _add_user(app, "alice")
+
+ result = app.test_cli_runner().invoke(args=["users", "list"])
+
+ assert result.exit_code == 0, result.output
+ lines = result.output.splitlines()
+ assert lines[0] == "ID\tUSERNAME"
+ assert lines[1].endswith("\talice")
+ assert lines[2].endswith("\tzoe")
+ assert "original" not in result.output
+
+
+def test_users_cli_set_password_updates_hash(app: Flask) -> None:
+ _add_user(app, "alice")
+ 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"
+ )
+
+ assert result.exit_code == 0, result.output
+ assert "Updated password for user 'alice'." in result.output
+ assert "replacement" 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")
+
+
+def test_users_cli_set_password_missing_user(app: Flask) -> None:
+ result = app.test_cli_runner().invoke(
+ args=["users", "set-password", "missing", "--password", "replacement"]
+ )
+
+ assert result.exit_code != 0
+ assert "User 'missing' does not exist." in result.output
+
+
+def test_users_cli_set_password_rejects_empty_password(app: Flask) -> None:
+ _add_user(app, "alice")
+
+ result = app.test_cli_runner().invoke(
+ args=["users", "set-password", "alice", "--password", ""]
+ )
+
+ assert result.exit_code != 0
+ assert "Password must not be empty." in result.output
+ user = _get_user(app, "alice")
+ assert user is not None
+ assert user.check_password("original")
+
+
+def test_users_cli_delete_with_confirmation(app: Flask) -> None:
+ _add_user(app, "alice")
+
+ result = app.test_cli_runner().invoke(
+ args=["users", "delete", "alice"], input="y\n"
+ )
+
+ assert result.exit_code == 0, result.output
+ assert "Delete user 'alice'?" in result.output
+ assert "Deleted user 'alice'." in result.output
+ assert _get_user(app, "alice") is None
+
+
+def test_users_cli_delete_confirmation_rejected(app: Flask) -> None:
+ _add_user(app, "alice")
+
+ result = app.test_cli_runner().invoke(
+ args=["users", "delete", "alice"], input="n\n"
+ )
+
+ assert result.exit_code != 0
+ assert "Aborted" in result.output
+ assert _get_user(app, "alice") is not None
+
+
+def test_users_cli_delete_yes_only_deletes_target(app: Flask) -> None:
+ _add_user(app, "alice")
+ _add_user(app, "bob")
+
+ result = app.test_cli_runner().invoke(args=["users", "delete", "alice", "--yes"])
+
+ assert result.exit_code == 0, result.output
+ assert "Deleted user 'alice'." in result.output
+ assert _get_user(app, "alice") is None
+ assert _get_user(app, "bob") is not None
+
+
+def test_users_cli_delete_missing_user(app: Flask) -> None:
+ result = app.test_cli_runner().invoke(args=["users", "delete", "missing", "-y"])
+
+ assert result.exit_code != 0
+ assert "User 'missing' does not exist." in result.output
+
+
+def test_users_cli_delete_missing_blank_username(app: Flask) -> None:
+ result = app.test_cli_runner().invoke(args=["users", "delete", " ", "--yes"])
+
+ assert result.exit_code != 0
+ assert "User ' ' does not exist." in result.output
+
+
+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"]
+ )
+
+ assert reset.exit_code == 0, reset.output
+ user = _get_user(app, " alice ")
+ assert user is not None
+ assert user.check_password("replacement")
+
+ deleted = app.test_cli_runner().invoke(args=["users", "delete", " alice ", "--yes"])
+ assert deleted.exit_code == 0, deleted.output
+ assert _get_user(app, " alice ") is None
+
+
+def test_users_cli_create_rolls_back_on_duplicate_race(app: Flask) -> None:
+ database_error = sa.exc.IntegrityError("INSERT", {}, Exception("duplicate"))
+
+ with app.app_context():
+ with (
+ patch.object(DATABASE.session, "commit", side_effect=database_error),
+ patch.object(DATABASE.session, "rollback") as rollback,
+ ):
+ result = app.test_cli_runner().invoke(
+ args=["users", "create", "--username", "alice", "--password", "secret"]
+ )
+ rollback.assert_called_once()
+
+ assert result.exit_code != 0
+ assert "User 'alice' already exists." in result.output
diff --git a/webmentions_ssg/__init__.py b/webmentions_ssg/__init__.py
index 11bd632..3dda31b 100644
--- a/webmentions_ssg/__init__.py
+++ b/webmentions_ssg/__init__.py
@@ -7,13 +7,11 @@ import logging.handlers
import os
from pathlib import Path
-import click
import coloredlogs
-import sqlalchemy as sa
-from flask import Flask, current_app
+from flask import Flask
from flask.cli import AppGroup
from flask_bootstrap import Bootstrap5
-from flask_mail import Mail, Message
+from flask_mail import Mail
from flask_migrate import Migrate, upgrade
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf import CSRFProtect
@@ -38,9 +36,7 @@ MIGRATE = Migrate()
HUEY = Huey()
MAIL = Mail()
-USERS_CLI = AppGroup("users", help="Handle users")
DB_CLI = AppGroup("db", help="Handle database")
-MAIL_CLI = AppGroup("mail", help="Handle mail")
def create_app(config_class: type[DefaultConfig] | None = None) -> Flask:
@@ -130,39 +126,15 @@ def create_app(config_class: type[DefaultConfig] | None = None) -> Flask:
app.register_blueprint(root_page)
- app.cli.add_command(USERS_CLI)
- app.cli.add_command(MAIL_CLI)
-
- return app
-
-
-@USERS_CLI.command("create", help="Create or add users")
-@click.option("--username", prompt=True)
-@click.password_option(confirmation_prompt=True)
-def create_user(username: str, password: str) -> None:
- """
- Create a new user.
-
- :param username: Username of the user to create.
- :param password: Plain-text password to hash and store for the user.
- :raises click.ClickException: If a user with the given username already
- exists.
- """
+ from .cli.users import USERS_CLI
- from .models import User
-
- if (
- DATABASE.session.scalar(sa.select(User).where(User.username == username))
- is not None
- ):
- raise click.ClickException(f"User {username!r} already exists.")
+ app.cli.add_command(USERS_CLI)
- user = User(username=username, password=password)
+ from .cli.mail import MAIL_CLI
- DATABASE.session.add(user)
- DATABASE.session.commit()
+ app.cli.add_command(MAIL_CLI)
- click.echo(f"Created user {username!r}.")
+ return app
@DB_CLI.command("create")
@@ -171,42 +143,3 @@ def create_db() -> None:
Upgrade the database to the latest migration revision.
"""
upgrade()
-
-
-@MAIL_CLI.command("test", help="Send an email to test the SMTP configuration")
-@click.option(
- "--to", "recipient", help="Recipient address (defaults to NOTIFICATION_EMAIL)."
-)
-def send_test_mail(recipient: str | None) -> None:
- """
- Send a test email using the configured SMTP server.
-
- :param recipient: Optional recipient overriding NOTIFICATION_EMAIL.
- :raises click.ClickException: If configuration is missing or sending fails.
- """
- recipient = recipient or current_app.config.get("NOTIFICATION_EMAIL")
- if not recipient:
- raise click.ClickException(
- "No recipient specified. Set NOTIFICATION_EMAIL or pass --to."
- )
-
- sender = current_app.config.get("MAIL_DEFAULT_SENDER")
- if not sender:
- raise click.ClickException("MAIL_DEFAULT_SENDER is not configured.")
-
- message = Message(
- subject="webmentions-ssg: test email",
- sender=sender,
- recipients=[recipient],
- body=(
- "This is a test email from webmentions-ssg.\n\n"
- "If you received this message, the outgoing mail configuration works.\n"
- ),
- )
-
- try:
- MAIL.send(message)
- except Exception as exc:
- raise click.ClickException(f"Could not send test email: {exc}") from exc
-
- click.echo(f"Test email sent to {recipient}.")
diff --git a/webmentions_ssg/cli/__init__.py b/webmentions_ssg/cli/__init__.py
new file mode 100644
index 0000000..25d78d5
--- /dev/null
+++ b/webmentions_ssg/cli/__init__.py
@@ -0,0 +1,3 @@
+# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
+#
+# SPDX-License-Identifier: BSD-3-Clause
diff --git a/webmentions_ssg/cli/mail.py b/webmentions_ssg/cli/mail.py
new file mode 100644
index 0000000..07dc50b
--- /dev/null
+++ b/webmentions_ssg/cli/mail.py
@@ -0,0 +1,47 @@
+import click
+from flask import current_app
+from flask.cli import AppGroup
+from flask_mail import Message
+
+from .. import MAIL
+
+MAIL_CLI = AppGroup("mail", help="Handle mail")
+
+
+@MAIL_CLI.command("test", help="Send an email to test the SMTP configuration")
+@click.option(
+ "--to", "recipient", help="Recipient address (defaults to NOTIFICATION_EMAIL)."
+)
+def send_test_mail(recipient: str | None) -> None:
+ """
+ Send a test email using the configured SMTP server.
+
+ :param recipient: Optional recipient overriding NOTIFICATION_EMAIL.
+ :raises click.ClickException: If configuration is missing or sending fails.
+ """
+ recipient = recipient or current_app.config.get("NOTIFICATION_EMAIL")
+ if not recipient:
+ raise click.ClickException(
+ "No recipient specified. Set NOTIFICATION_EMAIL or pass --to."
+ )
+
+ sender = current_app.config.get("MAIL_DEFAULT_SENDER")
+ if not sender:
+ raise click.ClickException("MAIL_DEFAULT_SENDER is not configured.")
+
+ message = Message(
+ subject="webmentions-ssg: test email",
+ sender=sender,
+ recipients=[recipient],
+ body=(
+ "This is a test email from webmentions-ssg.\n\n"
+ "If you received this message, the outgoing mail configuration works.\n"
+ ),
+ )
+
+ try:
+ MAIL.send(message)
+ except Exception as exc:
+ raise click.ClickException(f"Could not send test email: {exc}") from exc
+
+ click.echo(f"Test email sent to {recipient}.")
diff --git a/webmentions_ssg/cli/users.py b/webmentions_ssg/cli/users.py
new file mode 100644
index 0000000..2dcb17e
--- /dev/null
+++ b/webmentions_ssg/cli/users.py
@@ -0,0 +1,105 @@
+import click
+import sqlalchemy as sa
+from flask.cli import AppGroup
+
+from .. import DATABASE
+
+USERS_CLI = AppGroup("users", help="Manage users.")
+
+
+def _require_user(username: str):
+ """Return a user by username or report a CLI-friendly error."""
+ from ..models import User
+
+ user = DATABASE.session.scalar(sa.select(User).where(User.username == username))
+ if user is None:
+ raise click.ClickException(f"User {username!r} does not exist.")
+ return user
+
+
+@USERS_CLI.command("create", help="Create a user.")
+@click.option("--username", prompt="Username", help="Username for the new user.")
+@click.password_option(confirmation_prompt=True)
+def create_user(username: str, password: str) -> None:
+ """
+ Create a user with a securely hashed password.
+
+ :param username: Username for the new user.
+ :param password: Plain-text password to hash and store.
+ :raises click.ClickException: If the credentials are invalid or the user exists.
+ """
+ from ..models import User
+
+ username = username.strip()
+ if not username:
+ raise click.ClickException("Username must not be empty.")
+
+ if not password:
+ raise click.ClickException("Password must not be empty.")
+
+ if DATABASE.session.scalar(sa.select(User).where(User.username == username)):
+ raise click.ClickException(f"User {username!r} already exists.")
+
+ DATABASE.session.add(User(username=username, password=password))
+ try:
+ DATABASE.session.commit()
+ except sa.exc.IntegrityError as exc:
+ DATABASE.session.rollback()
+ raise click.ClickException(f"User {username!r} already exists.") from exc
+
+ click.echo(f"Created user {username!r}.")
+
+
+@USERS_CLI.command("list", help="List registered users.")
+def list_users() -> None:
+ """List user IDs and usernames in alphabetical order."""
+ from ..models import User
+
+ users = DATABASE.session.scalars(sa.select(User).order_by(User.username)).all()
+ if not users:
+ click.echo("No users found.")
+ return
+
+ click.echo("ID\tUSERNAME")
+ for user in users:
+ click.echo(f"{user.id}\t{user.username}")
+
+
+@USERS_CLI.command("set-password", help="Reset a user's password.")
+@click.argument("username")
+@click.password_option(confirmation_prompt=True)
+def set_user_password(username: str, password: str) -> None:
+ """
+ Change a user's password without displaying it.
+
+ :param username: Username of the account to update.
+ :param password: New plain-text password to hash and store.
+ :raises click.ClickException: If the account is missing or the password is empty.
+ """
+ if not password:
+ raise click.ClickException("Password must not be empty.")
+
+ user = _require_user(username)
+ user.password = password
+ DATABASE.session.commit()
+ click.echo(f"Updated password for user {username!r}.")
+
+
+@USERS_CLI.command("delete", help="Delete a user.")
+@click.argument("username")
+@click.option("-y", "--yes", is_flag=True, help="Skip the deletion confirmation.")
+def delete_user(username: str, yes: bool) -> None:
+ """
+ Permanently delete a user after confirmation, unless --yes is passed.
+
+ :param username: Username of the account to remove.
+ :param yes: Whether to skip the confirmation prompt.
+ :raises click.ClickException: If the account does not exist.
+ """
+ user = _require_user(username)
+ if not yes:
+ click.confirm(f"Delete user {username!r}?", abort=True)
+
+ DATABASE.session.delete(user)
+ DATABASE.session.commit()
+ click.echo(f"Deleted user {username!r}.")