From c0d57d29ea9d2906d0b3aef29d09333d669be077 Mon Sep 17 00:00:00 2001 From: Martin Varga Date: Mon, 15 Jun 2026 14:26:16 +0200 Subject: [PATCH 01/24] Fixed session cookie gap for deactivated users - `load_user` now returns None for inactive users, so their session cookies are rejected by Flask-Login - @auth_required adds `is_active` check - anonymize() now explicitly sets active=False for defence-in-depth --- server/mergin/app.py | 4 +++- server/mergin/auth/app.py | 6 +++++- server/mergin/auth/models.py | 1 + server/mergin/tests/test_auth.py | 20 +++++++++++++++++++- 4 files changed, 28 insertions(+), 3 deletions(-) diff --git a/server/mergin/app.py b/server/mergin/app.py index e5eb42d5..77d5a5ac 100644 --- a/server/mergin/app.py +++ b/server/mergin/app.py @@ -188,7 +188,9 @@ def create_app(public_keys: List[str] = None) -> Flask: # adjust login manager @login_manager.user_loader def load_user(user_id): # pylint: disable=W0613,W0612 - return User.query.get(user_id) + user = User.query.get(user_id) + if user and user.active: + return user @login_manager.header_loader def load_user_from_header(header_val): # pylint: disable=W0613,W0612 diff --git a/server/mergin/auth/app.py b/server/mergin/auth/app.py index acfccf43..2f57bc73 100644 --- a/server/mergin/auth/app.py +++ b/server/mergin/auth/app.py @@ -61,7 +61,11 @@ def auth_required(f=None, permissions=None): @functools.wraps(f) def wrapped_func(*args, **kwargs): - if not current_user or not current_user.is_authenticated: + if ( + not current_user + or not current_user.is_authenticated + or not current_user.is_active + ): return "Authentication information is missing or invalid.", 401 if permissions: for check_permission in permissions: diff --git a/server/mergin/auth/models.py b/server/mergin/auth/models.py index 760ab740..390fbbe0 100644 --- a/server/mergin/auth/models.py +++ b/server/mergin/auth/models.py @@ -185,6 +185,7 @@ def anonymize(self): """Anonymize user object in database - remove personal information""" ts = round(datetime.datetime.utcnow().timestamp() * 1000) del_str = f"deleted_{ts}" + self.active = False self.username = del_str self.email = None self.passwd = None diff --git a/server/mergin/tests/test_auth.py b/server/mergin/tests/test_auth.py index ba7730c3..dc08cd57 100644 --- a/server/mergin/tests/test_auth.py +++ b/server/mergin/tests/test_auth.py @@ -94,6 +94,23 @@ def test_logout(client): assert resp.status_code == 200 +def test_deactivated_user_session_rejected(client): + """Session cookie for a deactivated account must be rejected.""" + user = add_user("testdeactivate", "testpassword") + login(client, "testdeactivate", "testpassword") + + # session works before deactivation + resp = client.get(f"/v1/user/{user.username}") + assert resp.status_code == 200 + + user.active = False + db.session.commit() + + # same session must now be rejected + resp = client.get(f"/v1/user/{user.username}") + assert resp.status_code == 401 + + # user registration tests test_user_reg_data = [ ("test@test.com", "#pwd1234", 201), # success @@ -469,7 +486,8 @@ def test_update_user(client): data=json.dumps(data), headers=json_headers, ) - assert resp.status_code == 403 + # user is deactivated, so session is rejected before permission check + assert resp.status_code == 401 def test_update_user_profile(client): From 26a0698e25aa0dd95e4719d6dc20bfd5bd15d566 Mon Sep 17 00:00:00 2001 From: Martin Varga Date: Mon, 15 Jun 2026 14:37:49 +0200 Subject: [PATCH 02/24] Add configurable bcrypt cost factor Existing passwords will be rehashed organically if needed. --- server/mergin/auth/app.py | 5 +++++ server/mergin/auth/config.py | 1 + server/mergin/auth/models.py | 15 ++++++++++++++- server/mergin/tests/test_auth.py | 22 ++++++++++++++++++++++ 4 files changed, 42 insertions(+), 1 deletion(-) diff --git a/server/mergin/auth/app.py b/server/mergin/auth/app.py index 2f57bc73..d62462da 100644 --- a/server/mergin/auth/app.py +++ b/server/mergin/auth/app.py @@ -91,12 +91,17 @@ def wrapped_func(*args, **kwargs): def authenticate(login, password): + from ..app import db + if "@" in login: query = func.lower(User.email) == func.lower(login) else: query = func.lower(User.username) == func.lower(login) user = User.query.filter(query).one_or_none() if user and user.check_password(password): + if user.needs_rehash(): + user.assign_password(password) + db.session.commit() return user diff --git a/server/mergin/auth/config.py b/server/mergin/auth/config.py index 07b5a05d..a04a4e82 100644 --- a/server/mergin/auth/config.py +++ b/server/mergin/auth/config.py @@ -13,3 +13,4 @@ class Configuration(object): "BEARER_TOKEN_EXPIRATION", default=3600 * 12, cast=int ) # in seconds ACCOUNT_EXPIRATION = config("ACCOUNT_EXPIRATION", default=5, cast=int) # in days + BCRYPT_LOG_ROUNDS = config("BCRYPT_LOG_ROUNDS", default=12, cast=int) diff --git a/server/mergin/auth/models.py b/server/mergin/auth/models.py index 390fbbe0..d20325e2 100644 --- a/server/mergin/auth/models.py +++ b/server/mergin/auth/models.py @@ -64,12 +64,25 @@ def check_password(self, password): def assign_password(self, password): if isinstance(password, str): password = password.encode("utf-8") + rounds = current_app.config.get("BCRYPT_LOG_ROUNDS", 12) self.passwd = ( - bcrypt.hashpw(password, bcrypt.gensalt()).decode("utf-8") + bcrypt.hashpw(password, bcrypt.gensalt(rounds)).decode("utf-8") if password else None ) + def needs_rehash(self): + """Return True if the stored hash was generated with a different cost factor than configured.""" + if self.passwd is None: + return False + rounds = current_app.config.get("BCRYPT_LOG_ROUNDS", 12) + try: + # bcrypt hash format: $2b$$ + hash_rounds = int(self.passwd.split("$")[2]) + return hash_rounds != rounds + except (IndexError, ValueError): + return False + @property def is_authenticated(self): """For Flask-Login""" diff --git a/server/mergin/tests/test_auth.py b/server/mergin/tests/test_auth.py index dc08cd57..ea91b3ca 100644 --- a/server/mergin/tests/test_auth.py +++ b/server/mergin/tests/test_auth.py @@ -94,6 +94,28 @@ def test_logout(client): assert resp.status_code == 200 +def test_bcrypt_lazy_rehash(app): + """Password is transparently rehashed on login when the cost factor changes.""" + import bcrypt + from ..auth.app import authenticate + + user = add_user("rehashuser", "rehashpassword") + # Store a hash with a low cost factor (4 is the minimum bcrypt allows) + low_rounds_hash = bcrypt.hashpw(b"rehashpassword", bcrypt.gensalt(4)).decode( + "utf-8" + ) + user.passwd = low_rounds_hash + db.session.commit() + + app.config["BCRYPT_LOG_ROUNDS"] = 5 + result = authenticate("rehashuser", "rehashpassword") + assert result is not None + + db.session.refresh(user) + hash_rounds = int(user.passwd.split("$")[2]) + assert hash_rounds == 5 + + def test_deactivated_user_session_rejected(client): """Session cookie for a deactivated account must be rejected.""" user = add_user("testdeactivate", "testpassword") From ce00ed3e1d3edd2d75bf1b2dbb5539c501bef955 Mon Sep 17 00:00:00 2001 From: Martin Varga Date: Wed, 17 Jun 2026 15:08:21 +0200 Subject: [PATCH 03/24] Add temporary account lockout --- server/mergin/auth/api.yaml | 8 +++ server/mergin/auth/app.py | 17 ++++- server/mergin/auth/config.py | 2 + server/mergin/auth/controller.py | 16 ++++- server/mergin/auth/errors.py | 21 ++++++ server/mergin/auth/models.py | 46 +++++++++++++ server/mergin/tests/test_auth.py | 69 +++++++++++++++++++ .../a3c8f2e1d947_add_login_lockout_fields.py | 42 +++++++++++ 8 files changed, 217 insertions(+), 4 deletions(-) create mode 100644 server/mergin/auth/errors.py create mode 100644 server/migrations/community/a3c8f2e1d947_add_login_lockout_fields.py diff --git a/server/mergin/auth/api.yaml b/server/mergin/auth/api.yaml index fa482a36..a4c7b637 100644 --- a/server/mergin/auth/api.yaml +++ b/server/mergin/auth/api.yaml @@ -360,6 +360,8 @@ paths: $ref: "#/components/responses/BadStatusResp" "401": $ref: "#/components/responses/UnauthorizedError" + "423": + $ref: "#/components/responses/LockedResp" /app/auth/logout: get: summary: Logout @@ -617,6 +619,8 @@ paths: $ref: "#/components/responses/NotFoundResp" "415": $ref: "#/components/responses/UnsupportedMediaType" + "423": + $ref: "#/components/responses/LockedResp" x-openapi-router-controller: mergin.auth.controller /app/admin/login: post: @@ -646,6 +650,8 @@ paths: $ref: "#/components/responses/UnauthorizedError" "403": $ref: "#/components/responses/Forbidden" + "423": + $ref: "#/components/responses/LockedResp" /v2/users: post: tags: @@ -718,6 +724,8 @@ components: description: Request could not be processed becuase of conflict in resources UnprocessableEntity: description: Request was correct and yet server could not process it + LockedResp: + description: Account is temporarily locked due to too many failed login attempts. NoContent: description: Success. No content returned. schemas: diff --git a/server/mergin/auth/app.py b/server/mergin/auth/app.py index d62462da..f9d1a038 100644 --- a/server/mergin/auth/app.py +++ b/server/mergin/auth/app.py @@ -12,6 +12,7 @@ from .commands import add_commands from .config import Configuration from .models import User +from .errors import AccountLockedError # signal for other versions to listen to user_account_closed = signal("user_account_closed") @@ -98,11 +99,25 @@ def authenticate(login, password): else: query = func.lower(User.username) == func.lower(login) user = User.query.filter(query).one_or_none() - if user and user.check_password(password): + if user is None: + return None + needs_commit = False + if user.is_locked_out(): + raise AccountLockedError(user.locked_until) + if user.check_password(password): + if user.failed_login_attempts or user.locked_until: + user.reset_lockout() + needs_commit = True if user.needs_rehash(): user.assign_password(password) + needs_commit = True + if needs_commit: db.session.commit() return user + else: + user.record_failed_login() + db.session.commit() + return None def generate_confirmation_token(app, email, salt): diff --git a/server/mergin/auth/config.py b/server/mergin/auth/config.py index a04a4e82..3d2215ee 100644 --- a/server/mergin/auth/config.py +++ b/server/mergin/auth/config.py @@ -14,3 +14,5 @@ class Configuration(object): ) # in seconds ACCOUNT_EXPIRATION = config("ACCOUNT_EXPIRATION", default=5, cast=int) # in days BCRYPT_LOG_ROUNDS = config("BCRYPT_LOG_ROUNDS", default=12, cast=int) + # Comma-separated "attempts:seconds" pairs, e.g. "5:300,10:3600" + LOCKOUT_POLICY = config("LOCKOUT_POLICY", default="5:300,10:3600") diff --git a/server/mergin/auth/controller.py b/server/mergin/auth/controller.py index 06859255..ed104641 100644 --- a/server/mergin/auth/controller.py +++ b/server/mergin/auth/controller.py @@ -25,6 +25,7 @@ ) from .bearer import encode_token from .models import User, LoginHistory +from .errors import AccountLockedError from .schemas import UserSchema, UserSearchSchema, UserProfileSchema, UserInfoSchema from .forms import ( LoginForm, @@ -137,7 +138,10 @@ def login_public(): # noqa: E501 """ form = ApiLoginForm() if form.validate(): - user = authenticate(form.login.data, form.password.data) + try: + user = authenticate(form.login.data, form.password.data) + except AccountLockedError as e: + return e.response(423) if user and user.active: expire = datetime.now(pytz.utc) + timedelta( seconds=current_app.config["BEARER_TOKEN_EXPIRATION"] @@ -221,7 +225,10 @@ def search_users(): # pylint: disable=W0613,W0612 def login(): # pylint: disable=W0613,W0612 form = LoginForm() if form.validate(): - user = authenticate(form.login.data, form.password.data) + try: + user = authenticate(form.login.data, form.password.data) + except AccountLockedError as e: + return e.response(423) if user and user.active: login_user(user) if not os.path.isfile(current_app.config["MAINTENANCE_FILE"]): @@ -238,7 +245,10 @@ def admin_login(): # pylint: disable=W0613,W0612 if not form.validate(): return jsonify(form.errors), 400 - user = authenticate(form.login.data, form.password.data) + try: + user = authenticate(form.login.data, form.password.data) + except AccountLockedError as e: + abort(423, f"Account temporarily locked until {e.locked_until.isoformat()}") if user: if user.active and user.is_admin: login_user(user) diff --git a/server/mergin/auth/errors.py b/server/mergin/auth/errors.py new file mode 100644 index 00000000..a337bb77 --- /dev/null +++ b/server/mergin/auth/errors.py @@ -0,0 +1,21 @@ +# Copyright (C) Lutra Consulting Limited +# +# SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-MerginMaps-Commercial + +import datetime +from typing import Dict + +from ..app import ResponseError + + +class AccountLockedError(Exception, ResponseError): + code = "AccountLocked" + detail = "Account temporarily locked due to too many failed login attempts" + + def __init__(self, locked_until: datetime.datetime): + self.locked_until = locked_until + + def to_dict(self) -> Dict: + data = super().to_dict() + data["locked_until"] = self.locked_until.isoformat() + return data diff --git a/server/mergin/auth/models.py b/server/mergin/auth/models.py index d20325e2..234fee44 100644 --- a/server/mergin/auth/models.py +++ b/server/mergin/auth/models.py @@ -13,10 +13,20 @@ from ..app import db from ..sync.models import ProjectUser from ..sync.utils import get_user_agent, get_ip, get_device_id, is_reserved_word +from .errors import AccountLockedError MAX_USERNAME_LENGTH = 50 +def _parse_lockout_policy(policy_str: str) -> list: + """Parse "5:300,10:3600" into [(5, 300), (10, 3600)] sorted ascending by threshold.""" + result = [] + for part in policy_str.split(","): + threshold, seconds = part.strip().split(":") + result.append((int(threshold), int(seconds))) + return sorted(result, key=lambda x: x[0]) + + class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), info={"label": "Username"}) @@ -33,6 +43,10 @@ class User(db.Model): default=datetime.datetime.utcnow, ) last_signed_in = db.Column(db.DateTime(), nullable=True) + failed_login_attempts = db.Column( + db.Integer, default=0, nullable=False, server_default="0" + ) + locked_until = db.Column(db.DateTime(), nullable=True) receive_notifications = db.Column( db.Boolean, default=True, nullable=False, index=True ) @@ -83,6 +97,38 @@ def needs_rehash(self): except (IndexError, ValueError): return False + def is_locked_out(self) -> bool: + """Return True if the account is currently under a temporary lockout.""" + if self.locked_until is None: + return False + now = datetime.datetime.utcnow() + if self.locked_until <= now: + # lockout has expired — clear it so subsequent queries see a clean state + self.locked_until = None + return False + return True + + def record_failed_login(self) -> None: + """Increment the failed-login counter and apply a lockout if a threshold is crossed.""" + self.failed_login_attempts = (self.failed_login_attempts or 0) + 1 + policy = _parse_lockout_policy( + current_app.config.get("LOCKOUT_POLICY", "5:300,10:3600") + ) + # find the highest applicable tier + duration = None + for threshold, seconds in policy: + if self.failed_login_attempts >= threshold: + duration = seconds + if duration is not None: + self.locked_until = datetime.datetime.utcnow() + datetime.timedelta( + seconds=duration + ) + + def reset_lockout(self) -> None: + """Clear lockout state after a successful login.""" + self.failed_login_attempts = 0 + self.locked_until = None + @property def is_authenticated(self): """For Flask-Login""" diff --git a/server/mergin/tests/test_auth.py b/server/mergin/tests/test_auth.py index ea91b3ca..dd52ebba 100644 --- a/server/mergin/tests/test_auth.py +++ b/server/mergin/tests/test_auth.py @@ -94,6 +94,75 @@ def test_logout(client): assert resp.status_code == 200 +def test_login_lockout(client): + """Test account lockout: progressive tiers, freeze during lock, reset on success. + + policy: 3 failures → 60s lock, 4 failures → 3600s lock + counter is never reset between lockouts, so tier-2 is reached after one + extra failure following the first expired tier-1 lock + """ + client.application.config["LOCKOUT_POLICY"] = "3:60,4:3600" + user = add_user("lockoutuser", "correctpassword") + + def assert_locked(): + resp = client.post( + url_for("/.mergin_auth_controller_login"), + json={"login": "lockoutuser", "password": "wrong"}, + ) + assert resp.status_code == 423 + assert resp.json["code"] == "AccountLocked" + assert "locked_until" in resp.json + + # tier 1: 3 failures → 60s lock + for _ in range(3): + resp = client.post( + url_for("/.mergin_auth_controller_login"), + json={"login": "lockoutuser", "password": "wrong"}, + ) + assert resp.status_code == 401 + + assert_locked() + + # correct password is also blocked while locked + resp = client.post( + url_for("/.mergin_auth_controller_login"), + json={"login": "lockoutuser", "password": "correctpassword"}, + ) + assert resp.status_code == 423 + + # counter stays frozen during lockout + assert user.failed_login_attempts == 3 + assert user.locked_until is not None + + # tier 2 escalation: one more failure after tier-1 expiry + # counter was at 3; one new failure pushes it to 4, crossing tier-2 threshold + + # expire_lock + user.locked_until = datetime.now(tz=timezone.utc) - timedelta(seconds=1) + db.session.commit() + + resp = client.post( + url_for("/.mergin_auth_controller_login"), + json={"login": "lockoutuser", "password": "wrong"}, + ) + # returns 401 (wrong password), but now locked for 3600s + assert resp.status_code == 401 + assert_locked() + assert user.locked_until > datetime.now(tz=timezone.utc) + timedelta(seconds=60) + assert user.failed_login_attempts == 4 + + # successful login after expiry resets everything + user.locked_until = datetime.now(tz=timezone.utc) - timedelta(seconds=1) + db.session.commit() + resp = client.post( + url_for("/.mergin_auth_controller_login"), + json={"login": "lockoutuser", "password": "correctpassword"}, + ) + assert resp.status_code == 200 + assert user.failed_login_attempts == 0 + assert user.locked_until is None + + def test_bcrypt_lazy_rehash(app): """Password is transparently rehashed on login when the cost factor changes.""" import bcrypt diff --git a/server/migrations/community/a3c8f2e1d947_add_login_lockout_fields.py b/server/migrations/community/a3c8f2e1d947_add_login_lockout_fields.py new file mode 100644 index 00000000..a4a453e1 --- /dev/null +++ b/server/migrations/community/a3c8f2e1d947_add_login_lockout_fields.py @@ -0,0 +1,42 @@ +"""Add failed_login_attempts and locked_until to user table + +Revision ID: a3c8f2e1d947 +Revises: f1d9e4a7b823 +Create Date: 2026-06-15 00:00:00.000000 + +""" + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = "a3c8f2e1d947" +down_revision = "a1b2c3d4e5f6" +branch_labels = None +depends_on = None + + +def upgrade(): + op.add_column( + "user", + sa.Column( + "failed_login_attempts", + sa.Integer(), + nullable=False, + server_default="0", + ), + ) + op.add_column( + "user", + sa.Column( + "locked_until", + sa.DateTime(), + nullable=True, + ), + ) + + +def downgrade(): + op.drop_column("user", "locked_until") + op.drop_column("user", "failed_login_attempts") From 33732207e74bfd3d238ef33879a09d6b60c542c7 Mon Sep 17 00:00:00 2001 From: Martin Varga Date: Fri, 19 Jun 2026 13:26:38 +0200 Subject: [PATCH 04/24] Fix tests --- server/mergin/tests/test_auth.py | 8 ++++---- .../community/a3c8f2e1d947_add_login_lockout_fields.py | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/server/mergin/tests/test_auth.py b/server/mergin/tests/test_auth.py index dd52ebba..a3ee168f 100644 --- a/server/mergin/tests/test_auth.py +++ b/server/mergin/tests/test_auth.py @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-MerginMaps-Commercial -from datetime import datetime, timedelta, timezone +from datetime import datetime, timedelta import time import itsdangerous import pytest @@ -138,7 +138,7 @@ def assert_locked(): # counter was at 3; one new failure pushes it to 4, crossing tier-2 threshold # expire_lock - user.locked_until = datetime.now(tz=timezone.utc) - timedelta(seconds=1) + user.locked_until = datetime.utcnow() - timedelta(seconds=1) db.session.commit() resp = client.post( @@ -148,11 +148,11 @@ def assert_locked(): # returns 401 (wrong password), but now locked for 3600s assert resp.status_code == 401 assert_locked() - assert user.locked_until > datetime.now(tz=timezone.utc) + timedelta(seconds=60) + assert user.locked_until > datetime.utcnow() + timedelta(seconds=60) assert user.failed_login_attempts == 4 # successful login after expiry resets everything - user.locked_until = datetime.now(tz=timezone.utc) - timedelta(seconds=1) + user.locked_until = datetime.utcnow() - timedelta(seconds=1) db.session.commit() resp = client.post( url_for("/.mergin_auth_controller_login"), diff --git a/server/migrations/community/a3c8f2e1d947_add_login_lockout_fields.py b/server/migrations/community/a3c8f2e1d947_add_login_lockout_fields.py index a4a453e1..bcd7f76a 100644 --- a/server/migrations/community/a3c8f2e1d947_add_login_lockout_fields.py +++ b/server/migrations/community/a3c8f2e1d947_add_login_lockout_fields.py @@ -12,7 +12,7 @@ # revision identifiers, used by Alembic. revision = "a3c8f2e1d947" -down_revision = "a1b2c3d4e5f6" +down_revision = "f1d9e4a7b823" branch_labels = None depends_on = None From f2708ce1cdd082d964cd6b0ea5ff85e516edfb02 Mon Sep 17 00:00:00 2001 From: Martin Varga Date: Fri, 19 Jun 2026 13:46:06 +0200 Subject: [PATCH 05/24] Add missing import --- server/mergin/tests/test_auth.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/mergin/tests/test_auth.py b/server/mergin/tests/test_auth.py index a3ee168f..2294de49 100644 --- a/server/mergin/tests/test_auth.py +++ b/server/mergin/tests/test_auth.py @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-MerginMaps-Commercial -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone import time import itsdangerous import pytest From 022e1a9a0780d5ba4033ade06f1bb6ee2e94744f Mon Sep 17 00:00:00 2001 From: Herman Snevajs Date: Mon, 22 Jun 2026 15:34:07 +0200 Subject: [PATCH 06/24] Support for whitelisting extensions/mimetype --- deployment/community/.env.template | 4 ++++ server/mergin/sync/config.py | 8 ++++++++ server/mergin/sync/files.py | 2 +- server/mergin/sync/utils.py | 4 ++++ server/mergin/tests/test_utils.py | 29 +++++++++++++++++++++++++++++ 5 files changed, 46 insertions(+), 1 deletion(-) diff --git a/deployment/community/.env.template b/deployment/community/.env.template index ea6b8ccc..8754d263 100644 --- a/deployment/community/.env.template +++ b/deployment/community/.env.template @@ -109,6 +109,10 @@ LOCAL_PROJECTS=/data #BLACKLIST='.mergin/, .DS_Store, .directory' # cast=Csv() +# extra file types to permit beyond the default block-list (e.g. scripts) +#UPLOAD_EXTENSIONS_WHITELIST='' # cast=Csv() +#UPLOAD_MIME_TYPES_WHITELIST='' # cast=Csv() + #FILE_EXPIRATION=48 * 3600 # for clean up of old files where diffs were applied, in seconds #LOCKFILE_EXPIRATION=300 # in seconds diff --git a/server/mergin/sync/config.py b/server/mergin/sync/config.py index 8a5081ec..3313bc7f 100644 --- a/server/mergin/sync/config.py +++ b/server/mergin/sync/config.py @@ -82,5 +82,13 @@ class Configuration(object): ) # files that should be ignored during extension and MIME type checks UPLOAD_FILES_WHITELIST = config("UPLOAD_FILES_WHITELIST", default="", cast=Csv()) + # extra extensions to permit beyond the default block-list + UPLOAD_EXTENSIONS_WHITELIST = config( + "UPLOAD_EXTENSIONS_WHITELIST", default="", cast=Csv() + ) + # extra MIME types to permit beyond the default block-list + UPLOAD_MIME_TYPES_WHITELIST = config( + "UPLOAD_MIME_TYPES_WHITELIST", default="", cast=Csv() + ) # max batch size for fetch projects in batch endpoint MAX_BATCH_SIZE = config("MAX_BATCH_SIZE", default=100, cast=int) diff --git a/server/mergin/sync/files.py b/server/mergin/sync/files.py index d22358d5..9326b30f 100644 --- a/server/mergin/sync/files.py +++ b/server/mergin/sync/files.py @@ -224,7 +224,7 @@ def validate(self, data, **kwargs): if not is_supported_extension(file_path): raise ValidationError( - f"Unsupported file type detected: '{file_path}'. " + f"stop Unsupported file type detected: '{file_path}'. " f"Please remove the file or try compressing it into a ZIP file before uploading.", ) # new checks must restrict only new files not to block existing projects diff --git a/server/mergin/sync/utils.py b/server/mergin/sync/utils.py index 48966457..5843595a 100644 --- a/server/mergin/sync/utils.py +++ b/server/mergin/sync/utils.py @@ -315,6 +315,8 @@ def is_supported_extension(filepath) -> bool: if check_skip_validation(filepath): return True ext = os.path.splitext(filepath)[1].lower() + if ext in {e.lower() for e in Configuration.UPLOAD_EXTENSIONS_WHITELIST}: + return True return ext and ext not in FORBIDDEN_EXTENSIONS @@ -493,6 +495,8 @@ def is_supported_type(filepath) -> bool: if check_skip_validation(filepath): return True mime_type = get_mimetype(filepath) + if mime_type in Configuration.UPLOAD_MIME_TYPES_WHITELIST: + return True return mime_type.startswith("image/") or mime_type not in FORBIDDEN_MIME_TYPES diff --git a/server/mergin/tests/test_utils.py b/server/mergin/tests/test_utils.py index 1f447875..8e4192a1 100644 --- a/server/mergin/tests/test_utils.py +++ b/server/mergin/tests/test_utils.py @@ -402,3 +402,32 @@ def test_mime_type_validation_skip(): # Should be forbidden assert not is_supported_type("other.js") + + +def test_allowed_extensions_override(): + """Extensions in UPLOAD_EXTENSIONS_WHITELIST are accepted even though they are in FORBIDDEN_EXTENSIONS.""" + with patch( + "mergin.sync.utils.Configuration.UPLOAD_EXTENSIONS_WHITELIST", [".py", ".sh"] + ): + # forbidden by default, now explicitly allowed + assert is_supported_extension("model.py") + assert is_supported_extension("scripts/deploy.sh") + # match is case-insensitive + assert is_supported_extension("MODEL.PY") + # extensions not in the override stay blocked + assert not is_supported_extension("malware.exe") + assert not is_supported_extension("app.js") + + +def test_allowed_mime_types_override(): + """MIME types in UPLOAD_MIME_TYPES_WHITELIST are accepted even though they are in FORBIDDEN_MIME_TYPES.""" + with patch("mergin.sync.utils.get_mimetype", return_value="text/x-shellscript"): + # blocked by default + with patch("mergin.sync.utils.Configuration.UPLOAD_MIME_TYPES_WHITELIST", []): + assert not is_supported_type("deploy.sh") + # explicitly allowed + with patch( + "mergin.sync.utils.Configuration.UPLOAD_MIME_TYPES_WHITELIST", + ["text/x-shellscript"], + ): + assert is_supported_type("deploy.sh") From c001c7ad5d9ff1c94ad4fa5e6d93b92a665d9e9f Mon Sep 17 00:00:00 2001 From: Herman Snevajs Date: Mon, 22 Jun 2026 15:49:50 +0200 Subject: [PATCH 07/24] rm debugging residue --- server/mergin/sync/files.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/mergin/sync/files.py b/server/mergin/sync/files.py index 9326b30f..d22358d5 100644 --- a/server/mergin/sync/files.py +++ b/server/mergin/sync/files.py @@ -224,7 +224,7 @@ def validate(self, data, **kwargs): if not is_supported_extension(file_path): raise ValidationError( - f"stop Unsupported file type detected: '{file_path}'. " + f"Unsupported file type detected: '{file_path}'. " f"Please remove the file or try compressing it into a ZIP file before uploading.", ) # new checks must restrict only new files not to block existing projects From 956e01b879559fd0efda552d682bbd5fd64102e6 Mon Sep 17 00:00:00 2001 From: Martin Varga Date: Wed, 1 Jul 2026 15:29:35 +0200 Subject: [PATCH 08/24] Remove locked_until from response and other minor fixes --- server/mergin/auth/app.py | 9 +++++++-- server/mergin/auth/controller.py | 2 +- server/mergin/auth/errors.py | 11 ----------- server/mergin/auth/models.py | 10 ++-------- server/mergin/tests/test_auth.py | 1 - 5 files changed, 10 insertions(+), 23 deletions(-) diff --git a/server/mergin/auth/app.py b/server/mergin/auth/app.py index f9d1a038..00575a5f 100644 --- a/server/mergin/auth/app.py +++ b/server/mergin/auth/app.py @@ -101,9 +101,14 @@ def authenticate(login, password): user = User.query.filter(query).one_or_none() if user is None: return None - needs_commit = False if user.is_locked_out(): - raise AccountLockedError(user.locked_until) + raise AccountLockedError() + needs_commit = False + # reset non-null locked_until as it has already expired + if user.locked_until is not None: + user.locked_until = None + needs_commit = True + if user.check_password(password): if user.failed_login_attempts or user.locked_until: user.reset_lockout() diff --git a/server/mergin/auth/controller.py b/server/mergin/auth/controller.py index ed104641..474696cc 100644 --- a/server/mergin/auth/controller.py +++ b/server/mergin/auth/controller.py @@ -248,7 +248,7 @@ def admin_login(): # pylint: disable=W0613,W0612 try: user = authenticate(form.login.data, form.password.data) except AccountLockedError as e: - abort(423, f"Account temporarily locked until {e.locked_until.isoformat()}") + return e.response(423) if user: if user.active and user.is_admin: login_user(user) diff --git a/server/mergin/auth/errors.py b/server/mergin/auth/errors.py index a337bb77..99907948 100644 --- a/server/mergin/auth/errors.py +++ b/server/mergin/auth/errors.py @@ -2,20 +2,9 @@ # # SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-MerginMaps-Commercial -import datetime -from typing import Dict - from ..app import ResponseError class AccountLockedError(Exception, ResponseError): code = "AccountLocked" detail = "Account temporarily locked due to too many failed login attempts" - - def __init__(self, locked_until: datetime.datetime): - self.locked_until = locked_until - - def to_dict(self) -> Dict: - data = super().to_dict() - data["locked_until"] = self.locked_until.isoformat() - return data diff --git a/server/mergin/auth/models.py b/server/mergin/auth/models.py index 234fee44..e8cfbd90 100644 --- a/server/mergin/auth/models.py +++ b/server/mergin/auth/models.py @@ -13,7 +13,6 @@ from ..app import db from ..sync.models import ProjectUser from ..sync.utils import get_user_agent, get_ip, get_device_id, is_reserved_word -from .errors import AccountLockedError MAX_USERNAME_LENGTH = 50 @@ -93,7 +92,7 @@ def needs_rehash(self): try: # bcrypt hash format: $2b$$ hash_rounds = int(self.passwd.split("$")[2]) - return hash_rounds != rounds + return hash_rounds < rounds except (IndexError, ValueError): return False @@ -101,12 +100,7 @@ def is_locked_out(self) -> bool: """Return True if the account is currently under a temporary lockout.""" if self.locked_until is None: return False - now = datetime.datetime.utcnow() - if self.locked_until <= now: - # lockout has expired — clear it so subsequent queries see a clean state - self.locked_until = None - return False - return True + return self.locked_until > datetime.datetime.utcnow() def record_failed_login(self) -> None: """Increment the failed-login counter and apply a lockout if a threshold is crossed.""" diff --git a/server/mergin/tests/test_auth.py b/server/mergin/tests/test_auth.py index 2294de49..3554152b 100644 --- a/server/mergin/tests/test_auth.py +++ b/server/mergin/tests/test_auth.py @@ -111,7 +111,6 @@ def assert_locked(): ) assert resp.status_code == 423 assert resp.json["code"] == "AccountLocked" - assert "locked_until" in resp.json # tier 1: 3 failures → 60s lock for _ in range(3): From 64a3844aa1e639a8be4ac83a02063c9cfe8f2349 Mon Sep 17 00:00:00 2001 From: Herman Snevajs Date: Thu, 2 Jul 2026 15:36:34 +0200 Subject: [PATCH 09/24] address @MarcelGeo comments - use check_skip_validation -> also skips mimetype check -> mime_type config var is not needed --- deployment/community/.env.template | 5 ++--- server/mergin/sync/config.py | 4 ---- server/mergin/sync/utils.py | 9 ++++----- server/mergin/tests/test_utils.py | 13 ++++++------- 4 files changed, 12 insertions(+), 19 deletions(-) diff --git a/deployment/community/.env.template b/deployment/community/.env.template index 8754d263..95497b68 100644 --- a/deployment/community/.env.template +++ b/deployment/community/.env.template @@ -109,9 +109,8 @@ LOCAL_PROJECTS=/data #BLACKLIST='.mergin/, .DS_Store, .directory' # cast=Csv() -# extra file types to permit beyond the default block-list (e.g. scripts) -#UPLOAD_EXTENSIONS_WHITELIST='' # cast=Csv() -#UPLOAD_MIME_TYPES_WHITELIST='' # cast=Csv() +# extra file extensions to permit beyond the default block-list, e.g. '.py, .sh' +#UPLOAD_EXTENSIONS_WHITELIST= #FILE_EXPIRATION=48 * 3600 # for clean up of old files where diffs were applied, in seconds diff --git a/server/mergin/sync/config.py b/server/mergin/sync/config.py index 3313bc7f..a5c8167a 100644 --- a/server/mergin/sync/config.py +++ b/server/mergin/sync/config.py @@ -86,9 +86,5 @@ class Configuration(object): UPLOAD_EXTENSIONS_WHITELIST = config( "UPLOAD_EXTENSIONS_WHITELIST", default="", cast=Csv() ) - # extra MIME types to permit beyond the default block-list - UPLOAD_MIME_TYPES_WHITELIST = config( - "UPLOAD_MIME_TYPES_WHITELIST", default="", cast=Csv() - ) # max batch size for fetch projects in batch endpoint MAX_BATCH_SIZE = config("MAX_BATCH_SIZE", default=100, cast=int) diff --git a/server/mergin/sync/utils.py b/server/mergin/sync/utils.py index 5843595a..6dd7abe1 100644 --- a/server/mergin/sync/utils.py +++ b/server/mergin/sync/utils.py @@ -315,8 +315,6 @@ def is_supported_extension(filepath) -> bool: if check_skip_validation(filepath): return True ext = os.path.splitext(filepath)[1].lower() - if ext in {e.lower() for e in Configuration.UPLOAD_EXTENSIONS_WHITELIST}: - return True return ext and ext not in FORBIDDEN_EXTENSIONS @@ -465,7 +463,10 @@ def check_skip_validation(file_path: str) -> bool: Some files are allowed even if they have forbidden extension or mime type. """ file_name = os.path.basename(file_path) - return file_name in Configuration.UPLOAD_FILES_WHITELIST + if file_name in Configuration.UPLOAD_FILES_WHITELIST: + return True + ext = os.path.splitext(file_path)[1].lower() + return ext in {e.lower() for e in Configuration.UPLOAD_EXTENSIONS_WHITELIST} FORBIDDEN_MIME_TYPES = { @@ -495,8 +496,6 @@ def is_supported_type(filepath) -> bool: if check_skip_validation(filepath): return True mime_type = get_mimetype(filepath) - if mime_type in Configuration.UPLOAD_MIME_TYPES_WHITELIST: - return True return mime_type.startswith("image/") or mime_type not in FORBIDDEN_MIME_TYPES diff --git a/server/mergin/tests/test_utils.py b/server/mergin/tests/test_utils.py index 8e4192a1..288577b0 100644 --- a/server/mergin/tests/test_utils.py +++ b/server/mergin/tests/test_utils.py @@ -419,15 +419,14 @@ def test_allowed_extensions_override(): assert not is_supported_extension("app.js") -def test_allowed_mime_types_override(): - """MIME types in UPLOAD_MIME_TYPES_WHITELIST are accepted even though they are in FORBIDDEN_MIME_TYPES.""" +def test_extension_whitelist_skips_mime_check(): + """A whitelisted extension also bypasses the MIME check via check_skip_validation.""" with patch("mergin.sync.utils.get_mimetype", return_value="text/x-shellscript"): - # blocked by default - with patch("mergin.sync.utils.Configuration.UPLOAD_MIME_TYPES_WHITELIST", []): + # blocked when the extension is not whitelisted + with patch("mergin.sync.utils.Configuration.UPLOAD_EXTENSIONS_WHITELIST", []): assert not is_supported_type("deploy.sh") - # explicitly allowed + # allowed once the extension is whitelisted with patch( - "mergin.sync.utils.Configuration.UPLOAD_MIME_TYPES_WHITELIST", - ["text/x-shellscript"], + "mergin.sync.utils.Configuration.UPLOAD_EXTENSIONS_WHITELIST", [".sh"] ): assert is_supported_type("deploy.sh") From f83a49ddd534afc8a843b24a459096be54d69f7f Mon Sep 17 00:00:00 2001 From: Herman Snevajs Date: Wed, 22 Jul 2026 12:17:49 +0200 Subject: [PATCH 10/24] Display whitespaces in delete dialogs --- .../lib/src/modules/dialog/components/ConfirmDialog.vue | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/web-app/packages/lib/src/modules/dialog/components/ConfirmDialog.vue b/web-app/packages/lib/src/modules/dialog/components/ConfirmDialog.vue index 087af8d8..e69030ea 100644 --- a/web-app/packages/lib/src/modules/dialog/components/ConfirmDialog.vue +++ b/web-app/packages/lib/src/modules/dialog/components/ConfirmDialog.vue @@ -9,7 +9,9 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-MerginMaps-Commercial Cover for confirm dialog {{ text }} {{ description }} - {{ hint }} + {{ + hint + }}
Date: Fri, 24 Jul 2026 11:35:54 +0200 Subject: [PATCH 11/24] Send email notification with self-service unlock link on account lockout Co-Authored-By: Claude Sonnet 5 --- deployment/community/.env.template | 3 + deployment/enterprise/.env.template | 3 + server/.test.env | 1 + server/mergin/.env | 1 + server/mergin/auth/api.yaml | 20 ++++ server/mergin/auth/app.py | 62 +++++++++++- server/mergin/auth/config.py | 1 + server/mergin/auth/controller.py | 21 ++++ server/mergin/auth/models.py | 8 +- .../templates/email/account_locked.html | 15 +++ .../templates/email/components/base.html | 2 + server/mergin/tests/test_auth.py | 95 ++++++++++++++++++- web-app/packages/app/src/router.ts | 8 ++ .../packages/lib/src/modules/user/routes.ts | 2 + .../packages/lib/src/modules/user/userApi.ts | 4 + .../modules/user/views/AccountUnlockView.vue | 65 +++++++++++++ .../lib/src/modules/user/views/index.ts | 1 + 17 files changed, 307 insertions(+), 5 deletions(-) create mode 100644 server/mergin/templates/email/account_locked.html create mode 100644 web-app/packages/lib/src/modules/user/views/AccountUnlockView.vue diff --git a/deployment/community/.env.template b/deployment/community/.env.template index 95497b68..cfb526ac 100644 --- a/deployment/community/.env.template +++ b/deployment/community/.env.template @@ -66,6 +66,9 @@ SECURITY_EMAIL_SALT=fixme #SECURITY_PASSWORD_SALT=NODEFAULT SECURITY_PASSWORD_SALT=fixme +#SECURITY_UNLOCK_SALT=NODEFAULT +SECURITY_UNLOCK_SALT=fixme + #WTF_CSRF_ENABLED=True #WTF_CSRF_TIME_LIMIT=3600 * 24 # in seconds diff --git a/deployment/enterprise/.env.template b/deployment/enterprise/.env.template index 49a235cc..ebdb8716 100644 --- a/deployment/enterprise/.env.template +++ b/deployment/enterprise/.env.template @@ -71,6 +71,9 @@ SECURITY_EMAIL_SALT=fixme #SECURITY_PASSWORD_SALT=NODEFAULT SECURITY_PASSWORD_SALT=fixme +#SECURITY_UNLOCK_SALT=NODEFAULT +SECURITY_UNLOCK_SALT=fixme + #WTF_CSRF_ENABLED=True #WTF_CSRF_TIME_LIMIT=3600 * 24 # in seconds diff --git a/server/.test.env b/server/.test.env index 7545a7ce..0ab2ce8a 100644 --- a/server/.test.env +++ b/server/.test.env @@ -23,6 +23,7 @@ GEODIFF_WORKING_DIR=/tmp/geodiff SECURITY_BEARER_SALT='bearer' SECURITY_EMAIL_SALT='email' SECURITY_PASSWORD_SALT='password' +SECURITY_UNLOCK_SALT='unlock' DIAGNOSTIC_LOGS_DIR=/tmp/diagnostic_logs GEVENT_WORKER=0 OTEL_ENABLED=0 \ No newline at end of file diff --git a/server/mergin/.env b/server/mergin/.env index 0ff3dc42..ec45d5a1 100644 --- a/server/mergin/.env +++ b/server/mergin/.env @@ -4,5 +4,6 @@ SECRET_KEY='top-secret' SECURITY_BEARER_SALT='top-secret' SECURITY_EMAIL_SALT='top-secret' SECURITY_PASSWORD_SALT='top-secret' +SECURITY_UNLOCK_SALT='top-secret' MAIL_DEFAULT_SENDER='' FLASK_DEBUG=0 diff --git a/server/mergin/auth/api.yaml b/server/mergin/auth/api.yaml index a4c7b637..fdcba129 100644 --- a/server/mergin/auth/api.yaml +++ b/server/mergin/auth/api.yaml @@ -472,6 +472,26 @@ paths: $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFoundResp" + /app/auth/unlock-account/{token}: + post: + summary: Unlock account + description: Clear an active lockout for the user encoded in the token + operationId: mergin.auth.controller.unlock_account + parameters: + - name: token + in: path + description: User token for account unlock verification + required: true + schema: + type: string + example: InRlc3RAbHV0cmFjb25zdWx0aW5nLmNvLnVrIg.YN2KRg.Vj1LSzSvQx9DcNnQFgZ0baS7LPU + responses: + "200": + description: OK + "400": + $ref: "#/components/responses/BadStatusResp" + "404": + $ref: "#/components/responses/NotFoundResp" /app/auth/confirm-email/{token}: post: summary: Email verified diff --git a/server/mergin/auth/app.py b/server/mergin/auth/app.py index 00575a5f..3b3788f8 100644 --- a/server/mergin/auth/app.py +++ b/server/mergin/auth/app.py @@ -120,8 +120,10 @@ def authenticate(login, password): db.session.commit() return user else: - user.record_failed_login() + duration = user.record_failed_login() db.session.commit() + if duration is not None: + send_account_locked_email(current_app, user, duration) return None @@ -163,3 +165,61 @@ def send_confirmation_email(app, user, url, template, header, **kwargs): "sender": app.config["MAIL_DEFAULT_SENDER"], } send_email_async.delay(**email_data) + + +def generate_unlock_token(app, user): + """Sign a token binding the current lock episode (email + locked_until) to the user.""" + serializer = URLSafeTimedSerializer(app.config["SECRET_KEY"]) + payload = { + "email": user.email, + "locked_until": user.locked_until.replace(microsecond=0).isoformat(), + } + return serializer.dumps(payload, salt=app.config["SECURITY_UNLOCK_SALT"]) + + +def confirm_unlock_token(token, expiration=24 * 3600): + serializer = URLSafeTimedSerializer(current_app.config["SECRET_KEY"]) + try: + payload = serializer.loads( + token, salt=current_app.config["SECURITY_UNLOCK_SALT"], max_age=expiration + ) + except Exception: + return None + return payload + + +def _format_lockout_duration(seconds: int) -> str: + """Humanize a lockout duration, e.g. 300 -> "5 minutes", 3600 -> "1 hour".""" + minutes, secs = divmod(int(seconds), 60) + hours, minutes = divmod(minutes, 60) + parts = [] + if hours: + parts.append(f"{hours} hour{'s' if hours != 1 else ''}") + if minutes: + parts.append(f"{minutes} minute{'s' if minutes != 1 else ''}") + if not parts: + parts.append(f"{secs} second{'s' if secs != 1 else ''}") + return " ".join(parts) + + +def send_account_locked_email(app, user, duration_seconds): + """Notify user their account was locked out and give them a link to unlock it.""" + from ..celery import send_email_async + + token = generate_unlock_token(app, user) + confirm_url = f"unlock-account/{token}" + html = render_template( + "email/account_locked.html", + subject="Account locked", + confirm_url=confirm_url, + user=user, + lockout_duration=_format_lockout_duration(duration_seconds), + locked_until=user.locked_until, + ) + email_data = { + "subject": "Account locked", + "html": html, + "recipients": [user.email], + "sender": app.config["MAIL_DEFAULT_SENDER"], + } + send_email_async.delay(**email_data) diff --git a/server/mergin/auth/config.py b/server/mergin/auth/config.py index 3d2215ee..0e9c81ca 100644 --- a/server/mergin/auth/config.py +++ b/server/mergin/auth/config.py @@ -9,6 +9,7 @@ class Configuration(object): SECURITY_BEARER_SALT = config("SECURITY_BEARER_SALT") SECURITY_EMAIL_SALT = config("SECURITY_EMAIL_SALT") SECURITY_PASSWORD_SALT = config("SECURITY_PASSWORD_SALT") + SECURITY_UNLOCK_SALT = config("SECURITY_UNLOCK_SALT") BEARER_TOKEN_EXPIRATION = config( "BEARER_TOKEN_EXPIRATION", default=3600 * 12, cast=int ) # in seconds diff --git a/server/mergin/auth/controller.py b/server/mergin/auth/controller.py index 474696cc..b0c06a21 100644 --- a/server/mergin/auth/controller.py +++ b/server/mergin/auth/controller.py @@ -18,6 +18,7 @@ send_confirmation_email, confirm_token, generate_confirmation_token, + confirm_unlock_token, user_created, user_account_closed, edit_profile_enabled, @@ -43,6 +44,7 @@ EMAIL_CONFIRMATION_EXPIRATION = 12 * 3600 +ACCOUNT_UNLOCK_TOKEN_EXPIRATION = 24 * 3600 # public endpoints @@ -363,6 +365,25 @@ def confirm_email(token): # pylint: disable=W0613,W0612 return "", 200 +def unlock_account(token): # pylint: disable=W0613,W0612 + payload = confirm_unlock_token(token, expiration=ACCOUNT_UNLOCK_TOKEN_EXPIRATION) + if not payload: + abort(400, "Invalid or expired link") + + user = User.query.filter_by(email=payload["email"]).first_or_404() + stale = ( + not user.is_locked_out() + or user.locked_until.replace(microsecond=0).isoformat() + != payload["locked_until"] + ) + if stale: + abort(400, "This unlock link is no longer valid") + + user.reset_lockout() + db.session.commit() + return "", 200 + + @auth_required @edit_profile_enabled def update_user_profile(): # pylint: disable=W0613,W0612 diff --git a/server/mergin/auth/models.py b/server/mergin/auth/models.py index e8cfbd90..e3f2ae90 100644 --- a/server/mergin/auth/models.py +++ b/server/mergin/auth/models.py @@ -102,8 +102,11 @@ def is_locked_out(self) -> bool: return False return self.locked_until > datetime.datetime.utcnow() - def record_failed_login(self) -> None: - """Increment the failed-login counter and apply a lockout if a threshold is crossed.""" + def record_failed_login(self) -> Optional[int]: + """Increment the failed-login counter and apply a lockout if a threshold is crossed. + + Returns the lockout duration in seconds if a new lock was just applied, else None. + """ self.failed_login_attempts = (self.failed_login_attempts or 0) + 1 policy = _parse_lockout_policy( current_app.config.get("LOCKOUT_POLICY", "5:300,10:3600") @@ -117,6 +120,7 @@ def record_failed_login(self) -> None: self.locked_until = datetime.datetime.utcnow() + datetime.timedelta( seconds=duration ) + return duration def reset_lockout(self) -> None: """Clear lockout state after a successful login.""" diff --git a/server/mergin/templates/email/account_locked.html b/server/mergin/templates/email/account_locked.html new file mode 100644 index 00000000..e94efc87 --- /dev/null +++ b/server/mergin/templates/email/account_locked.html @@ -0,0 +1,15 @@ + + +{% set base_url = config['MERGIN_BASE_URL'] %} +{% extends "email/components/content.html" %} +{% block html %} +

Dear {{ user.username }},


+

Your account has been temporarily locked for {{ lockout_duration }} after several failed login attempts. If this wasn't you, someone may be trying to access your account - consider changing your password once you're back in.

+

You will be able to log in again at {{ locked_until.strftime('%Y-%m-%d %H:%M') }} UTC, or you can unlock your account right now by following this link:

+

{{ base_url }}/{{ confirm_url }}

+{% endblock %} +{% block notifications_footer %}{% endblock %} diff --git a/server/mergin/templates/email/components/base.html b/server/mergin/templates/email/components/base.html index ec1d066c..4fc8d222 100644 --- a/server/mergin/templates/email/components/base.html +++ b/server/mergin/templates/email/components/base.html @@ -221,6 +221,7 @@

+ {% block notifications_footer %}
@@ -230,6 +231,7 @@

+ {% endblock %} diff --git a/server/mergin/tests/test_auth.py b/server/mergin/tests/test_auth.py index 3554152b..483c33c6 100644 --- a/server/mergin/tests/test_auth.py +++ b/server/mergin/tests/test_auth.py @@ -3,6 +3,7 @@ # SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-MerginMaps-Commercial from datetime import datetime, timedelta, timezone +from types import SimpleNamespace import time import itsdangerous import pytest @@ -13,7 +14,11 @@ from ..auth.bearer import decode_token, encode_token from ..auth.forms import ResetPasswordForm -from ..auth.app import generate_confirmation_token, confirm_token +from ..auth.app import ( + generate_confirmation_token, + confirm_token, + generate_unlock_token, +) from ..auth.models import User, LoginHistory from ..auth.tasks import anonymize_removed_users from ..app import db @@ -94,7 +99,8 @@ def test_logout(client): assert resp.status_code == 200 -def test_login_lockout(client): +@patch("mergin.celery.send_email_async.apply_async") +def test_login_lockout(send_email_mock, client): """Test account lockout: progressive tiers, freeze during lock, reset on success. policy: 3 failures → 60s lock, 4 failures → 3600s lock @@ -120,6 +126,9 @@ def assert_locked(): ) assert resp.status_code == 401 + # lockout email dispatched exactly once, at the moment the lock triggers + assert send_email_mock.call_count == 1 + assert_locked() # correct password is also blocked while locked @@ -133,6 +142,9 @@ def assert_locked(): assert user.failed_login_attempts == 3 assert user.locked_until is not None + # no further emails while already locked out (attempts above were all 423s) + assert send_email_mock.call_count == 1 + # tier 2 escalation: one more failure after tier-1 expiry # counter was at 3; one new failure pushes it to 4, crossing tier-2 threshold @@ -150,6 +162,9 @@ def assert_locked(): assert user.locked_until > datetime.utcnow() + timedelta(seconds=60) assert user.failed_login_attempts == 4 + # second lockout email dispatched for the tier-2 re-lock + assert send_email_mock.call_count == 2 + # successful login after expiry resets everything user.locked_until = datetime.utcnow() - timedelta(seconds=1) db.session.commit() @@ -161,6 +176,82 @@ def assert_locked(): assert user.failed_login_attempts == 0 assert user.locked_until is None + # no email on successful login + assert send_email_mock.call_count == 2 + + +@patch("mergin.celery.send_email_async.apply_async") +def test_unlock_account(send_email_mock, client, app): + """Test the self-service unlock-account link: valid use, reuse, natural + expiry, and cross-tier reuse, per the token-binding design.""" + client.application.config["LOCKOUT_POLICY"] = "3:60,4:3600" + user = add_user("unlockuser", "correctpassword") + + def unlock(token): + return client.post( + url_for("/.mergin_auth_controller_unlock_account", token=token) + ) + + def lock_out(): + for _ in range(3): + client.post( + url_for("/.mergin_auth_controller_login"), + json={"login": "unlockuser", "password": "wrong"}, + ) + + # unknown user -> 404 + fake_user = SimpleNamespace(email="nope@x.com", locked_until=datetime.utcnow()) + resp = unlock(generate_unlock_token(app, fake_user)) + assert resp.status_code == 404 + + # tamper with a valid-looking token -> 400 + resp = unlock("not-a-real-token") + assert resp.status_code == 400 + + # trigger tier-1 lock and capture its token + lock_out() + assert user.is_locked_out() + tier1_token = generate_unlock_token(app, user) + + # valid token unlocks successfully + resp = unlock(tier1_token) + assert resp.status_code == 200 + assert user.failed_login_attempts == 0 + assert user.locked_until is None + + # reuse of the same (now-consumed) token fails + resp = unlock(tier1_token) + assert resp.status_code == 400 + + # naturally-expired lock: token itself still cryptographically valid, + # but the lock episode it points to is no longer active + lock_out() + assert user.is_locked_out() + stale_token = generate_unlock_token(app, user) + user.locked_until = datetime.utcnow() - timedelta(seconds=1) + db.session.commit() + resp = unlock(stale_token) + assert resp.status_code == 400 + + # cross-tier reuse: a token minted for one lock episode must not unlock + # a later, different lock episode for the same user + user.locked_until = None + user.failed_login_attempts = 0 + db.session.commit() + lock_out() + tier1_token_2 = generate_unlock_token(app, user) + # escalate to tier 2 with a new locked_until + user.locked_until = datetime.utcnow() - timedelta(seconds=1) + db.session.commit() + client.post( + url_for("/.mergin_auth_controller_login"), + json={"login": "unlockuser", "password": "wrong"}, + ) + assert user.failed_login_attempts == 4 + assert user.locked_until > datetime.utcnow() + timedelta(seconds=60) + resp = unlock(tier1_token_2) + assert resp.status_code == 400 + def test_bcrypt_lazy_rehash(app): """Password is transparently rehashed on login when the cost factor changes.""" diff --git a/web-app/packages/app/src/router.ts b/web-app/packages/app/src/router.ts index 4fb00555..04888ba0 100644 --- a/web-app/packages/app/src/router.ts +++ b/web-app/packages/app/src/router.ts @@ -3,6 +3,7 @@ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-MerginMaps-Commercial import { + AccountUnlockView, ChangePasswordView, FileBrowserView, FileVersionDetailView, @@ -81,6 +82,13 @@ export const createRouter = (pinia: Pinia) => { props: true, meta: { public: true } }, + { + path: '/unlock-account/:token', + name: UserRouteName.UnlockAccount, + component: AccountUnlockView, + props: true, + meta: { public: true } + }, { path: '/dashboard', name: DashboardRouteName.Dashboard, diff --git a/web-app/packages/lib/src/modules/user/routes.ts b/web-app/packages/lib/src/modules/user/routes.ts index d2a52edd..6a562e55 100644 --- a/web-app/packages/lib/src/modules/user/routes.ts +++ b/web-app/packages/lib/src/modules/user/routes.ts @@ -16,6 +16,7 @@ export enum UserRouteName { Login = 'login', ConfirmEmail = 'confirm_email', ChangePassword = 'change_password', + UnlockAccount = 'unlock_account', UserProfile = 'user_profile' } @@ -29,6 +30,7 @@ export const getUserTitle = (route: RouteLocationNormalizedLoaded) => { ], [UserRouteName.ConfirmEmail]: ['Confirm email address', DEFAULT_PAGE_TITLE], [UserRouteName.ChangePassword]: ['Change password', DEFAULT_PAGE_TITLE], + [UserRouteName.UnlockAccount]: ['Account unlock', DEFAULT_PAGE_TITLE], [UserRouteName.UserProfile]: ['Your profile'] } return titles[name] diff --git a/web-app/packages/lib/src/modules/user/userApi.ts b/web-app/packages/lib/src/modules/user/userApi.ts index 1ecab091..bd9cb169 100644 --- a/web-app/packages/lib/src/modules/user/userApi.ts +++ b/web-app/packages/lib/src/modules/user/userApi.ts @@ -72,6 +72,10 @@ export const UserApi = { return UserModule.httpService.get('/app/auth/resend-confirm-email') }, + unlockAccount: (token: string): Promise> => { + return UserModule.httpService.post(`/app/auth/unlock-account/${token}`) + }, + login: (data: LoginData): Promise> => UserModule.httpService.post('/app/auth/login', data), diff --git a/web-app/packages/lib/src/modules/user/views/AccountUnlockView.vue b/web-app/packages/lib/src/modules/user/views/AccountUnlockView.vue new file mode 100644 index 00000000..66186fc8 --- /dev/null +++ b/web-app/packages/lib/src/modules/user/views/AccountUnlockView.vue @@ -0,0 +1,65 @@ + + + + + + + diff --git a/web-app/packages/lib/src/modules/user/views/index.ts b/web-app/packages/lib/src/modules/user/views/index.ts index 44df67bf..2498d990 100644 --- a/web-app/packages/lib/src/modules/user/views/index.ts +++ b/web-app/packages/lib/src/modules/user/views/index.ts @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-MerginMaps-Commercial +export { default as AccountUnlockView } from './AccountUnlockView.vue' export { default as ChangePasswordView } from './ChangePasswordView.vue' export { default as LoginViewTemplate } from './LoginViewTemplate.vue' export { default as ProfileViewTemplate } from './ProfileViewTemplate.vue' From 56626f645a2b39cba891303329a0f9a4c5100a64 Mon Sep 17 00:00:00 2001 From: Martin Varga Date: Mon, 27 Jul 2026 08:42:16 +0200 Subject: [PATCH 12/24] fix account lockout component --- .../packages/lib/src/modules/user/routes.ts | 2 +- .../modules/user/views/AccountUnlockView.vue | 42 ++++++++----------- 2 files changed, 18 insertions(+), 26 deletions(-) diff --git a/web-app/packages/lib/src/modules/user/routes.ts b/web-app/packages/lib/src/modules/user/routes.ts index 6a562e55..d31a7062 100644 --- a/web-app/packages/lib/src/modules/user/routes.ts +++ b/web-app/packages/lib/src/modules/user/routes.ts @@ -30,7 +30,7 @@ export const getUserTitle = (route: RouteLocationNormalizedLoaded) => { ], [UserRouteName.ConfirmEmail]: ['Confirm email address', DEFAULT_PAGE_TITLE], [UserRouteName.ChangePassword]: ['Change password', DEFAULT_PAGE_TITLE], - [UserRouteName.UnlockAccount]: ['Account unlock', DEFAULT_PAGE_TITLE], + [UserRouteName.UnlockAccount]: ['Unlock your account', DEFAULT_PAGE_TITLE], [UserRouteName.UserProfile]: ['Your profile'] } return titles[name] diff --git a/web-app/packages/lib/src/modules/user/views/AccountUnlockView.vue b/web-app/packages/lib/src/modules/user/views/AccountUnlockView.vue index 66186fc8..05bec944 100644 --- a/web-app/packages/lib/src/modules/user/views/AccountUnlockView.vue +++ b/web-app/packages/lib/src/modules/user/views/AccountUnlockView.vue @@ -7,7 +7,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-MerginMaps-Commercial