Open-source personal finance manager. Self-hosted, privacy-first.
fix(admin): let REGISTRATION_ENABLED decide until an administrator saves a value (#1277)
Pedro Henrique Fernandes565f209f75a2
diff --git a/.env.example b/.env.exampleindex 7425cac6..af0044cb 100644--- a/.env.example+++ b/.env.example@@ -1,6 +1,10 @@# RequiredSECRET_KEY=change-me-in-production+# Public sign-up (optional). Applies until an administrator saves the toggle+# on the admin settings page, whose saved value then wins.+# REGISTRATION_ENABLED=false+# Bank sync: Pluggy (https://pluggy.ai)## 1. Create an account at https://dashboard.pluggy.ai## 2. Copy your Client ID and Client Secretdiff --git a/backend/.env.example b/backend/.env.exampleindex 063ce9e7..5fb12ee5 100644--- a/backend/.env.example+++ b/backend/.env.example@@ -37,6 +37,8 @@ OIDC_AUTO_REGISTER=trueOIDC_REQUIRE_VERIFIED_EMAIL=true# Set to false only with OIDC_ENABLED=true, OIDC_CLIENT_ID, and OIDC_DISCOVERY_URL configuredLOCAL_AUTH_ENABLED=true+# Public sign-up; an administrator's saved toggle wins over it.+# REGISTRATION_ENABLED=falseOIDC_SYNC_ROLES=falseOIDC_ROLES_CLAIM=groupsOIDC_ADMIN_ROLES=diff --git a/backend/alembic/versions/099_registration_setting_follows_env.py b/backend/alembic/versions/099_registration_setting_follows_env.pynew file mode 100644index 00000000..7d7c3ed2--- /dev/null+++ b/backend/alembic/versions/099_registration_setting_follows_env.py@@ -0,0 +1,37 @@+"""let REGISTRATION_ENABLED decide until an administrator does++Migration 020 seeded `registration_enabled = 'true'` into app_settings.+A saved setting wins over the environment, the same way the saved+timezone wins over TZ, so the seeded row meant REGISTRATION_ENABLED was+never read on any install: setting it to false left registration open.++Only the seeded value goes. A row saying 'false' can only have been+written by an administrator, so it stays. A row saying 'true' looks the+same whether 020 or an administrator wrote it; dropping it changes+nothing unless REGISTRATION_ENABLED is false, which is exactly the+install that asked for registration to be closed.+"""+from alembic import op++revision = "099"+down_revision = "098"+branch_labels = None+depends_on = None+++def upgrade() -> None:+ op.execute(+ "DELETE FROM app_settings "+ "WHERE key = 'registration_enabled' AND LOWER(value) = 'true'"+ )+++def downgrade() -> None:+ # Put the seed back where nothing has been saved since, so the+ # schema at 098 sees the row it always had.+ op.execute(+ "INSERT INTO app_settings (key, value) "+ "SELECT 'registration_enabled', 'true' "+ "WHERE NOT EXISTS "+ "(SELECT 1 FROM app_settings WHERE key = 'registration_enabled')"+ )diff --git a/backend/app/services/admin_service.py b/backend/app/services/admin_service.pyindex 1ea3dbae..16bbfc3d 100644--- a/backend/app/services/admin_service.py+++ b/backend/app/services/admin_service.py@@ -247,10 +247,13 @@ async def set_app_setting(session: AsyncSession, key: str, value: str) -> AppSetasync def is_registration_enabled(session: AsyncSession) -> bool:+ """Whether public sign-up is open.++ The value an administrator saved wins; with nothing saved, the+ REGISTRATION_ENABLED environment variable decides."""setting = await get_app_setting(session, "registration_enabled")if setting:return setting.value.lower() == "true"- # Fall back to env varreturn get_settings().registration_enableddiff --git a/backend/tests/test_admin_api.py b/backend/tests/test_admin_api.pyindex 43db893c..0c483dbb 100644--- a/backend/tests/test_admin_api.py+++ b/backend/tests/test_admin_api.py@@ -3,11 +3,13 @@ import uuidimport pytestfrom httpx import AsyncClient+from sqlalchemy import deletefrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.models.app_settings import AppSettingfrom app.models.user import Userfrom app.core.auth import get_jwt_strategy+from app.core.config import get_settingspytestmark = pytest.mark.asyncio@@ -344,6 +346,24 @@ class TestRegistrationToggle:assert response.status_code == 200assert "enabled" in response.json()+ async def test_env_var_closes_registration_when_nothing_is_saved(+ self, client: AsyncClient, session: AsyncSession, monkeypatch+ ):+ # The database is shared by the worker, and another test may have+ # saved the toggle: start from nothing saved.+ await session.execute(delete(AppSetting).where(AppSetting.key == "registration_enabled"))+ await session.commit()+ monkeypatch.setattr(get_settings(), "registration_enabled", False)++ status_response = await client.get("/api/admin/registration-status")+ assert status_response.json()["enabled"] is False++ reg_response = await client.post(+ "/api/auth/register",+ json={"email": "[email protected]", "password": "password123"},+ )+ assert reg_response.status_code == 403+async def test_disable_registration(self, client: AsyncClient, admin_auth_headers: dict, test_superuser: User, session: AsyncSession):diff --git a/backend/tests/test_admin_service.py b/backend/tests/test_admin_service.pyindex e0e0c27c..95e404c9 100644--- a/backend/tests/test_admin_service.py+++ b/backend/tests/test_admin_service.py@@ -5,6 +5,7 @@ from decimal import Decimalimport pytestfrom sqlalchemy.ext.asyncio import AsyncSession+from app.core.config import get_settingsfrom app.models.account import Accountfrom app.models.asset import Assetfrom app.models.asset_value import AssetValue@@ -424,11 +425,19 @@ async def test_is_registration_enabled_from_setting(session: AsyncSession, cleanassert await is_registration_enabled(session) is False-async def test_is_registration_enabled_fallback_to_env(session: AsyncSession, clean_db):- """When no DB setting exists, falls back to env config."""- result = await is_registration_enabled(session)- # Should not raise; returns the env default- assert isinstance(result, bool)[email protected]("env_value", [True, False])+async def test_is_registration_enabled_fallback_to_env(+ session: AsyncSession, clean_db, monkeypatch, env_value+):+ """When no DB setting exists, REGISTRATION_ENABLED decides."""+ monkeypatch.setattr(get_settings(), "registration_enabled", env_value)+ assert await is_registration_enabled(session) is env_value+++async def test_saved_setting_wins_over_env(session: AsyncSession, clean_db, monkeypatch):+ monkeypatch.setattr(get_settings(), "registration_enabled", False)+ await set_app_setting(session, "registration_enabled", "true")+ assert await is_registration_enabled(session) is True# ---------------------------------------------------------------------------diff --git a/backend/tests/test_registration_setting_migration.py b/backend/tests/test_registration_setting_migration.pynew file mode 100644index 00000000..7508603b--- /dev/null+++ b/backend/tests/test_registration_setting_migration.py@@ -0,0 +1,65 @@+import importlib.util+from pathlib import Path++import pytest+import sqlalchemy as sa+from alembic.migration import MigrationContext+from alembic.operations import Operations+++# Found by name rather than by number, so renumbering the migration to land+# after another one does not break this test.+(_MIGRATION_PATH,) = (+ Path(__file__).resolve().parent.parent / "alembic" / "versions"+).glob("*_registration_setting_follows_env.py")+_SPEC = importlib.util.spec_from_file_location("registration_setting_migration", _MIGRATION_PATH)+assert _SPEC is not None and _SPEC.loader is not None+migration = importlib.util.module_from_spec(_SPEC)+_SPEC.loader.exec_module(migration)+++def _run(direction: str, saved: str | None) -> str | None:+ """Run the migration over an app_settings table holding `saved`, and+ return what registration_enabled holds afterwards."""+ engine = sa.create_engine("sqlite://")+ try:+ return _run_on(engine, direction, saved)+ finally:+ # CI runs with -W error: a connection left to the garbage collector+ # raises ResourceWarning in whichever test happens to be running.+ engine.dispose()+++def _run_on(engine: sa.Engine, direction: str, saved: str | None) -> str | None:+ with engine.begin() as conn:+ conn.execute(sa.text(+ "CREATE TABLE app_settings (key VARCHAR(255) PRIMARY KEY, value VARCHAR(2000) NOT NULL)"+ ))+ conn.execute(sa.text("INSERT INTO app_settings (key, value) VALUES ('timezone', 'UTC')"))+ if saved is not None:+ conn.execute(+ sa.text("INSERT INTO app_settings (key, value) VALUES ('registration_enabled', :v)"),+ {"v": saved},+ )+ with Operations.context(MigrationContext.configure(conn)):+ getattr(migration, direction)()+ timezone = conn.execute(+ sa.text("SELECT value FROM app_settings WHERE key = 'timezone'")+ ).scalar_one()+ assert timezone == "UTC"+ return conn.execute(+ sa.text("SELECT value FROM app_settings WHERE key = 'registration_enabled'")+ ).scalar_one_or_none()+++def test_upgrade_drops_the_seeded_true_so_the_env_var_decides():+ assert _run("upgrade", "true") is None+++def test_upgrade_keeps_a_false_an_administrator_saved():+ assert _run("upgrade", "false") == "false"++[email protected](("saved", "after"), [(None, "true"), ("false", "false"), ("true", "true")])+def test_downgrade_restores_the_seed_only_where_nothing_is_saved(saved, after):+ assert _run("downgrade", saved) == afterdiff --git a/docker-compose.prod.yml b/docker-compose.prod.ymlindex da32b546..dd760518 100644--- a/docker-compose.prod.yml+++ b/docker-compose.prod.yml@@ -36,6 +36,8 @@ x-backend-env: &backend-envOIDC_ADMIN_ROLES: ${OIDC_ADMIN_ROLES:-}OIDC_WORKSPACE_ROLE_MAP: ${OIDC_WORKSPACE_ROLE_MAP:-}LOCAL_AUTH_ENABLED: ${LOCAL_AUTH_ENABLED:-true}+ # No default, so an unset value leaves backend/.env and the app default to decide.+ REGISTRATION_ENABLED:OPENEXCHANGERATES_APP_ID: ${OPENEXCHANGERATES_APP_ID:-}FX_SYNC_MODE: ${FX_SYNC_MODE:-on_demand}TESOURO_DIRETO_ENABLED: ${TESOURO_DIRETO_ENABLED:-true}diff --git a/docker-compose.yml b/docker-compose.ymlindex e8870ec8..bd787720 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -43,6 +43,8 @@ x-backend-env: &backend-envOIDC_ADMIN_ROLES: ${OIDC_ADMIN_ROLES:-}OIDC_WORKSPACE_ROLE_MAP: ${OIDC_WORKSPACE_ROLE_MAP:-}LOCAL_AUTH_ENABLED: ${LOCAL_AUTH_ENABLED:-true}+ # No default, so an unset value leaves backend/.env and the app default to decide.+ REGISTRATION_ENABLED:REDIS_URL: redis://redis:6379/0BANK_SYNC_MIN_INTERVAL_HOURS: ${BANK_SYNC_MIN_INTERVAL_HOURS:-4}OPENEXCHANGERATES_APP_ID: ${OPENEXCHANGERATES_APP_ID:-}diff --git a/frontend/src/pages/admin/settings.tsx b/frontend/src/pages/admin/settings.tsxindex 355e4121..b7f164a9 100644--- a/frontend/src/pages/admin/settings.tsx+++ b/frontend/src/pages/admin/settings.tsx@@ -108,9 +108,11 @@ export default function AdminSettingsPage() {},})- const { data: regSetting, isLoading: settingsLoading } = useQuery({+ // The effective state, not the saved row: with nothing saved,+ // REGISTRATION_ENABLED decides.+ const { data: regStatus, isLoading: settingsLoading } = useQuery({queryKey: ['admin', 'settings', 'registration_enabled'],- queryFn: () => adminApi.getSetting('registration_enabled'),+ queryFn: () => adminApi.registrationStatus(),})const updateSettingMutation = useMutation({@@ -275,7 +277,7 @@ export default function AdminSettingsPage() {const users = usersData?.items ?? []const isSelf = (u: AdminUser) => u.id === currentUser?.id- const isEnabled = regSetting?.value === 'true'+ const isEnabled = regStatus?.enabled === trueconst filteredUsers = users