From 836ae8d9374c2d5b07a3c39ee449ee69660906d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Sun, 8 Nov 2026 00:18:15 +0100 Subject: [PATCH 01/33] auth: persist refresh-token families and serialize lifecycle changes Context: - Refresh-token rotation needs durable state and protection against concurrent use. Change: - Add the tracker model and migration, lock user and family rows consistently, and revoke families on credential changes or deactivation. --- flexmeasures/auth/__init__.py | 11 +++- flexmeasures/auth/datastore.py | 33 +++++++++++ ...af36c80d214e_add_refresh_token_trackers.py | 45 +++++++++++++++ flexmeasures/data/models/refresh_tokens.py | 57 +++++++++++++++++++ 4 files changed, 144 insertions(+), 2 deletions(-) create mode 100644 flexmeasures/auth/datastore.py create mode 100644 flexmeasures/data/migrations/versions/af36c80d214e_add_refresh_token_trackers.py create mode 100644 flexmeasures/data/models/refresh_tokens.py diff --git a/flexmeasures/auth/__init__.py b/flexmeasures/auth/__init__.py index 946fb81aa5..73a4876dd0 100644 --- a/flexmeasures/auth/__init__.py +++ b/flexmeasures/auth/__init__.py @@ -5,7 +5,6 @@ from flask import Flask from flask_security import ( Security, - SQLAlchemySessionUserDatastore, password_reset, password_changed, reset_password_instructions_sent, @@ -42,7 +41,15 @@ def register_at(app: Flask): FlexMeasuresForgotPasswordForm, ) - user_datastore = SQLAlchemySessionUserDatastore(db.session, User, Role) + from flexmeasures.auth.datastore import FlexMeasuresUserDatastore + from flexmeasures.data.models.refresh_tokens import RefreshTokenTracker + + user_datastore = FlexMeasuresUserDatastore( + db.session, User, Role, refresh_tracker_model=RefreshTokenTracker + ) + # API token issuance opts in explicitly and uses the tracker helpers directly. + # Keep Flask-Security's global REFRESH_TOKEN flag at its default: enabling it + # also changes browser login/logout and exposes its own refresh endpoint. app.security = Security( app, user_datastore, diff --git a/flexmeasures/auth/datastore.py b/flexmeasures/auth/datastore.py new file mode 100644 index 0000000000..55f4397381 --- /dev/null +++ b/flexmeasures/auth/datastore.py @@ -0,0 +1,33 @@ +"""Serialize validation and rotation of a refresh-token family.""" + +from flask_security import SQLAlchemySessionUserDatastore +from sqlalchemy import select + +from flexmeasures.data.models.refresh_tokens import RefreshTokenTracker +from flexmeasures.data.models.user import User + + +class FlexMeasuresUserDatastore(SQLAlchemySessionUserDatastore): + def find_refresh_tracker(self, refresh_family: str) -> RefreshTokenTracker | None: + user_id = self.db.session.scalar( + select(RefreshTokenTracker.user_id).where( + RefreshTokenTracker.refresh_family == refresh_family + ) + ) + if user_id is None: + return None + # Always lock user before family, matching credential changes and issuance. + self.db.session.scalar( + select(User) + .where(User.id == user_id) + .with_for_update() + .execution_options(populate_existing=True) + ) + # Hold the lock until the endpoint commits, including reuse revocation. + # Refresh ORM state too: another transaction may have rotated this family. + return self.db.session.scalar( + select(RefreshTokenTracker) + .where(RefreshTokenTracker.refresh_family == refresh_family) + .with_for_update() + .execution_options(populate_existing=True) + ) diff --git a/flexmeasures/data/migrations/versions/af36c80d214e_add_refresh_token_trackers.py b/flexmeasures/data/migrations/versions/af36c80d214e_add_refresh_token_trackers.py new file mode 100644 index 0000000000..8c63d866f7 --- /dev/null +++ b/flexmeasures/data/migrations/versions/af36c80d214e_add_refresh_token_trackers.py @@ -0,0 +1,45 @@ +"""Add refresh-token family tracking. + +Revision ID: af36c80d214e +Revises: bf22b21d0990 +""" + +from alembic import op +import sqlalchemy as sa + +revision = "af36c80d214e" +down_revision = "bf22b21d0990" +branch_labels = None +depends_on = None + + +def upgrade(): + op.create_table( + "refresh_token_tracker", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column( + "user_id", + sa.Integer(), + sa.ForeignKey("fm_user.id", ondelete="CASCADE"), + nullable=False, + ), + sa.Column("refresh_family", sa.String(64), nullable=False, unique=True), + sa.Column("gen", sa.Integer(), nullable=False), + sa.Column("name", sa.String(64), nullable=False), + sa.Column("expires_at", sa.DateTime(), nullable=False), + sa.Column("last_used_at", sa.DateTime(), nullable=False), + sa.Column("revoked_at", sa.DateTime()), + sa.Column( + "create_datetime", + sa.DateTime(), + server_default=sa.func.now(), + nullable=False, + ), + ) + op.create_index( + "ix_refresh_token_tracker_user_id", "refresh_token_tracker", ["user_id"] + ) + + +def downgrade(): + op.drop_table("refresh_token_tracker") diff --git a/flexmeasures/data/models/refresh_tokens.py b/flexmeasures/data/models/refresh_tokens.py new file mode 100644 index 0000000000..2ba4f94431 --- /dev/null +++ b/flexmeasures/data/models/refresh_tokens.py @@ -0,0 +1,57 @@ +"""Persistent refresh-token families, using Flask-Security's rotation protocol.""" + +from flask_security import RefreshTrackerMixin +from sqlalchemy import event, inspect + +from flexmeasures.data import db +from flexmeasures.data.models.user import User + + +class RefreshTokenTracker(db.Model, RefreshTrackerMixin): + __tablename__ = "refresh_token_tracker" + + id = db.Column(db.Integer, primary_key=True) + user_id = db.Column( + db.Integer, + db.ForeignKey("fm_user.id", ondelete="CASCADE"), + nullable=False, + index=True, + ) + refresh_family = db.Column(db.String(64), unique=True, nullable=False) + gen = db.Column(db.Integer, nullable=False) + name = db.Column(db.String(64), nullable=False) + # Flask-Security's datetime_factory uses naive UTC datetimes. + expires_at = db.Column(db.DateTime, nullable=False) + last_used_at = db.Column(db.DateTime, nullable=False) + revoked_at = db.Column(db.DateTime) + create_datetime = db.Column( + db.DateTime, nullable=False, server_default=db.func.now() + ) + user = db.relationship( + User, + backref=db.backref( + "refresh_trackers", + cascade="all, delete-orphan", + order_by="RefreshTokenTracker.id", + ), + ) + + +@event.listens_for(User, "after_update") +def revoke_refresh_tokens_on_identity_change(mapper, connection, user): + """Do not revive refresh access when a disabled user is reactivated.""" + # The user UPDATE already holds the user-row lock. Token endpoints acquire + # this same lock before touching families, so issuance cannot race this sweep. + state = inspect(user) + disabled = state.attrs.active.history.has_changes() and not user.active + credentials_changed = any( + state.attrs[field].history.has_changes() + for field in ("password", "fs_uniquifier") + ) + if disabled or credentials_changed: + connection.execute( + RefreshTokenTracker.__table__.update() + .where(RefreshTokenTracker.user_id == user.id) + .where(RefreshTokenTracker.revoked_at.is_(None)) + .values(revoked_at=db.func.timezone("UTC", db.func.now())) + ) From 39b2425b6cc025c684d30ac449b7819ab3a56bab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Sun, 8 Nov 2026 00:19:09 +0100 Subject: [PATCH 02/33] api: add opt-in refresh-token issuance, rotation and revocation Context: - Integrations need renewable credentials without changing existing access-token clients. Change: - Add JSON refresh and revocation endpoints with kebab-case fields, lifetime reporting, replay protection and immediate revocation. - Preserve legacy response fields and token lifetime; reject inactive users and prevent caching token responses. --- flexmeasures/api/__init__.py | 44 ++++++++++-- flexmeasures/api/refresh_tokens.py | 111 +++++++++++++++++++++++++++++ flexmeasures/api/v3_0/users.py | 9 +++ flexmeasures/auth/tokens.py | 84 ++++++++++++++++++++++ 4 files changed, 244 insertions(+), 4 deletions(-) create mode 100644 flexmeasures/api/refresh_tokens.py create mode 100644 flexmeasures/auth/tokens.py diff --git a/flexmeasures/api/__init__.py b/flexmeasures/api/__init__.py index 564b1f33a8..a320c62d82 100644 --- a/flexmeasures/api/__init__.py +++ b/flexmeasures/api/__init__.py @@ -8,7 +8,7 @@ from flask_json import as_json from flask_login import current_user from webargs.flaskparser import use_args -from sqlalchemy.exc import IntegrityError +from sqlalchemy.exc import IntegrityError, SQLAlchemyError from sqlalchemy import select from flexmeasures.data import db @@ -59,10 +59,19 @@ def request_auth_token(args) -> tuple[dict, int]: schema: type: object properties: - authentication_token: + auth_token: type: string description: | - Short-lived authentication token, which can be used in request headers using `{"Authorization": authentication_token}`. + Short-lived access token, used as `{"Authorization": auth_token}`. + user_id: + type: integer + refresh-token: + type: string + description: Returned only when include-refresh-token is true. + expires-in: + type: integer + nullable: true + description: Access-token lifetime in seconds (null if unlimited), returned with refresh-token. 400: description: INVALID_REQUEST 401: @@ -97,9 +106,27 @@ def request_auth_token(args) -> tuple[dict, int]: return {"errors": ["Please provide the 'password' parameter."]}, 400 if not verify_password(request.json["password"], user.password): return {"errors": ["User password does not match."]}, 401 + if args["include-refresh-token"]: + # Serialize issuance with deactivation/password changes, then verify + # credentials again against the locked, up-to-date user record. + user = db.session.scalar( + select(User) + .where(User.id == user.id) + .with_for_update() + .execution_options(populate_existing=True) + ) + if not user or not verify_password(args["password"], user.password): + return {"errors": ["User password does not match."]}, 401 + if not user.active: + return {"errors": ["User is inactive."]}, 401 + if args["include-refresh-token"]: + from flexmeasures.auth.tokens import issue_refresh_token + + return issue_refresh_token(user) token = user.get_auth_token() return {"auth_token": token, "user_id": user.id} - except Exception as e: + except SQLAlchemyError as e: + db.session.rollback() current_app.logger.error(f"Exception in /requestAuthToken endpoint: {e}") return {"errors": ["An internal error has occurred."]}, 500 @@ -166,6 +193,8 @@ def register_at(app: Flask): rate_limiting.register_at(app) + from flexmeasures.api import refresh_tokens # noqa: F401 + app.register_blueprint( flexmeasures_api, url_prefix="/api" ) # now registering the blueprint will affect all endpoints @@ -173,6 +202,13 @@ def register_at(app: Flask): # Add version headers to all API responses @app.after_request def add_version_headers(response): + if request.endpoint in { + "flexmeasures_api.request_auth_token", + "flexmeasures_api.refresh_auth_token", + "flexmeasures_api.revoke_refresh_token", + }: + response.headers["Cache-Control"] = "no-store" + response.headers["Pragma"] = "no-cache" if request.path.startswith("/api/"): response.headers["FlexMeasures-Version"] = flexmeasures_version if request.path.startswith("/api/v3_0"): diff --git a/flexmeasures/api/refresh_tokens.py b/flexmeasures/api/refresh_tokens.py new file mode 100644 index 0000000000..b41c1dadb1 --- /dev/null +++ b/flexmeasures/api/refresh_tokens.py @@ -0,0 +1,111 @@ +"""Refresh-token endpoints. These accept JSON credentials, never browser cookies.""" + +from flask_json import as_json +from marshmallow import Schema, fields, validate +from webargs.flaskparser import use_args + +from flexmeasures.api import flexmeasures_api +from flexmeasures.auth.tokens import exchange_refresh_token + + +class RefreshTokenRequestSchema(Schema): + refresh_token = fields.Str( + data_key="refresh-token", + attribute="refresh-token", + required=True, + validate=validate.Length(min=1), + metadata={ + "description": "The current refresh token.", + "example": "", + }, + ) + + +@flexmeasures_api.route("/refreshAuthToken", methods=["POST"]) +@use_args(RefreshTokenRequestSchema, location="json") +@as_json +def refresh_auth_token(args): + """ + .. :quickref: Auth; Exchange a refresh token + --- + post: + summary: Rotate a refresh token and obtain a new access token. + description: | + No access token or password is required. Save the returned refresh token + atomically and serialize refresh requests. Reuse revokes the token family. + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [refresh-token] + properties: + refresh-token: + type: string + responses: + 200: + description: New access and refresh token pair. + content: + application/json: + schema: + type: object + properties: + auth_token: + type: string + user_id: + type: integer + refresh-token: + type: string + expires-in: + type: integer + nullable: true + description: Access-token lifetime in seconds, or null if unlimited. + 400: + description: Invalid request. + 401: + description: Invalid, expired or revoked refresh token. Authenticate again. + tags: + - Auth + """ + return exchange_refresh_token(args["refresh-token"]) + + +@flexmeasures_api.route("/revokeRefreshToken", methods=["POST"]) +@use_args(RefreshTokenRequestSchema, location="json") +@as_json +def revoke_refresh_token(args): + """ + .. :quickref: Auth; Revoke a refresh-token family + --- + post: + summary: Revoke this refresh-token family. + description: Existing access tokens remain valid until expiry or invalidation. + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [refresh-token] + properties: + refresh-token: + type: string + responses: + 200: + description: Refresh-token family revoked. + content: + application/json: + schema: + type: object + properties: + revoked: + type: boolean + 400: + description: Invalid request. + 401: + description: Invalid, expired or revoked refresh token. + tags: + - Auth + """ + return exchange_refresh_token(args["refresh-token"], revoke=True) diff --git a/flexmeasures/api/v3_0/users.py b/flexmeasures/api/v3_0/users.py index a1a0871483..eedefdcfed 100644 --- a/flexmeasures/api/v3_0/users.py +++ b/flexmeasures/api/v3_0/users.py @@ -42,6 +42,15 @@ class AuthRequestSchema(Schema): + include_refresh_token = fields.Bool( + data_key="include-refresh-token", + attribute="include-refresh-token", + load_default=False, + metadata={ + "description": "Also issue a rotating refresh token and access-token expires-in (seconds).", + "example": True, + }, + ) email = fields.Str( required=True, metadata={"description": "The user's email address."} ) diff --git a/flexmeasures/auth/tokens.py b/flexmeasures/auth/tokens.py new file mode 100644 index 0000000000..215f459e8c --- /dev/null +++ b/flexmeasures/auth/tokens.py @@ -0,0 +1,84 @@ +"""JSON API token lifecycle backed by Flask-Security refresh trackers.""" + +import time + +from flask import current_app +from flask_security.tokens import ( + new_refresh_tracker, + get_refresh_token, + verify_refresh_token, + RefreshTokenErrors, +) +from flask_security.signals import refresh_tracker_revoked + +from flexmeasures.data import db + + +def token_response(user, refresh_token: str) -> dict: + """Report the effective lifetime, including a deployment's per-token expiry.""" + security = current_app.extensions["security"] + access_token = user.get_auth_token() + data, issued_at = security.remember_token_serializer.loads( + access_token, return_timestamp=True + ) + max_age = current_app.config["SECURITY_TOKEN_MAX_AGE"].total_seconds() + deadlines = [] + if max_age: + deadlines.append(issued_at.timestamp() + max_age) + if data.get("exp"): + deadlines.append(data["exp"]) + # None explicitly denotes a deployment configured with non-expiring tokens. + expires_in = max(0, int(min(deadlines) - time.time())) if deadlines else None + return { + "auth_token": access_token, + "user_id": user.id, + "refresh-token": refresh_token, + "expires-in": expires_in, + } + + +def issue_refresh_token(user) -> dict: + """Caller must hold the user lock and have verified their credentials.""" + _, refresh_token = new_refresh_tracker(user, name="api") + payload = token_response(user, refresh_token) + db.session.commit() + return payload + + +def exchange_refresh_token(token: str, *, revoke: bool = False) -> tuple[dict, int]: + """Validate, rotate or revoke within one transaction holding the family lock.""" + security = current_app.extensions["security"] + datastore = security.datastore + tracker, error, uid = verify_refresh_token(token) + # Revocation is immediate. Upstream compares revoked_at < now, which permits + # reuse at the same clock instant (or when worker clocks differ slightly). + if tracker is not None and tracker.revoked_at is not None: + error = RefreshTokenErrors.REVOKED + user = ( + datastore.find_user(**{datastore.get_token_uniquifier_name(): uid}) + if uid + else None + ) + if tracker is not None and (revoke or error == RefreshTokenErrors.GEN_MISMATCH): + datastore.revoke_refresh_tracker(tracker) + refresh_tracker_revoked.send( + current_app._get_current_object(), + _async_wrapper=current_app.ensure_sync, + user=user, + refresh_tracker=tracker, + refresh_errors=error, + ) + if error or user is None or not user.active: + # Commit replay revocation even though authentication failed. + db.session.commit() + return { + "error": "invalid_refresh_token", + "errors": ["Refresh token is invalid or expired. Authenticate again."], + }, 401 + if revoke: + db.session.commit() + return {"revoked": True}, 200 + datastore.exchange_refresh_tracker(tracker) + payload = token_response(user, get_refresh_token(tracker, user)) + db.session.commit() + return payload, 200 From 3c62aa9fae16f7d0e93b97bb7ff9bcb40b023d23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Sun, 8 Nov 2026 00:20:38 +0100 Subject: [PATCH 03/33] tests: cover refresh-token security and legacy authentication Context: - Authentication lifecycle changes need regression coverage using real token validation. Change: - Cover rotation, concurrent reuse, expiry, revocation and credential changes. - Correct naming checks for the existing auth_token and user_id response contract without allowing new snake-case fields. --- .../api/tests/test_refresh_tokens_fresh_db.py | 321 ++++++++++++++++++ .../data/schemas/tests/test_field_naming.py | 16 +- 2 files changed, 334 insertions(+), 3 deletions(-) create mode 100644 flexmeasures/api/tests/test_refresh_tokens_fresh_db.py diff --git a/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py b/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py new file mode 100644 index 0000000000..ddbc7e6d24 --- /dev/null +++ b/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py @@ -0,0 +1,321 @@ +"""Exercise token lifecycle endpoints with real Flask-Security authentication.""" + +from concurrent.futures import ThreadPoolExecutor +from datetime import timedelta +from threading import Barrier +import time + +import pytest +from flask import g, url_for +from sqlalchemy import select + +from flexmeasures.data.models.user import User + + +@pytest.fixture(autouse=True) +def patch_check_token(): + """Use real token validation, including expiry and inactive-user checks.""" + + +@pytest.fixture +def token_user(fresh_db, setup_roles_users_fresh_db): + user = fresh_db.session.scalar( + select(User).filter_by(email="test_admin_user@seita.nl") + ) + fresh_db.session.commit() + return user + + +def login(client, **kwargs): + if "include_refresh_token" in kwargs: + kwargs["include-refresh-token"] = kwargs.pop("include_refresh_token") + return client.post( + "/api/requestAuthToken", + json={"email": "test_admin_user@seita.nl", "password": "testtest", **kwargs}, + ) + + +def refresh(client, token): + return client.post("/api/refreshAuthToken", json={"refresh-token": token}) + + +def clear_auth(): + # The session-scoped app context otherwise caches authentication across requests. + for key in ("_login_user", "fs_authn_via", "fs_paa", "csrf_valid"): + g.pop(key, None) + + +def assert_pair(response, user_id): + assert response.status_code == 200, response.json + assert { + "auth_token", + "user_id", + "refresh-token", + "expires-in", + } <= response.json.keys() + assert not {"refresh_token", "expires_in"} & response.json.keys() + assert response.json["user_id"] == user_id + assert isinstance(response.json["auth_token"], str) + assert isinstance(response.json["refresh-token"], str) + assert response.json["auth_token"] != response.json["refresh-token"] + assert isinstance(response.json["expires-in"], int) + assert response.json["expires-in"] > 0 + assert "no-store" in response.headers["Cache-Control"] + return response.json + + +@pytest.mark.parametrize("options", [{}, {"include_refresh_token": False}]) +def test_legacy_token_response(client, token_user, options): + response = login(client, **options) + assert response.status_code == 200 + assert set(response.json) == {"auth_token", "user_id", "status"} + assert response.json["user_id"] == token_user.id + clear_auth() + response = client.get( + url_for("AssetAPI:index"), + headers={"Authorization": response.json["auth_token"]}, + ) + assert response.status_code == 200 + + +def test_issue_and_rotate_tokens(client, token_user): + pair = assert_pair(login(client, include_refresh_token=True), token_user.id) + rotated = assert_pair(refresh(client, pair["refresh-token"]), token_user.id) + assert rotated["refresh-token"] != pair["refresh-token"] + clear_auth() + assert ( + client.get( + url_for("AssetAPI:index"), headers={"Authorization": rotated["auth_token"]} + ).status_code + == 200 + ) + + +def test_refresh_token_cannot_authenticate_api_request(client, token_user): + pair = assert_pair(login(client, include_refresh_token=True), token_user.id) + clear_auth() + assert ( + client.get( + url_for("AssetAPI:index"), headers={"Authorization": pair["refresh-token"]} + ).status_code + == 401 + ) + + +def test_access_token_cannot_be_refreshed(client, token_user): + pair = assert_pair(login(client, include_refresh_token=True), token_user.id) + assert refresh(client, pair["auth_token"]).status_code == 401 + + +def test_reuse_revokes_rotated_token_family(client, token_user): + pair = assert_pair(login(client, include_refresh_token=True), token_user.id) + rotated = assert_pair(refresh(client, pair["refresh-token"]), token_user.id) + assert refresh(client, pair["refresh-token"]).status_code == 401 + assert refresh(client, rotated["refresh-token"]).status_code == 401 + + +def test_revoke_refresh_token(client, token_user): + pair = assert_pair(login(client, include_refresh_token=True), token_user.id) + response = client.post( + "/api/revokeRefreshToken", json={"refresh-token": pair["refresh-token"]} + ) + assert response.status_code == 200 + assert refresh(client, pair["refresh-token"]).status_code == 401 + + +@pytest.mark.parametrize("include_refresh_token", [False, True]) +def test_disabled_user_cannot_obtain_tokens( + client, fresh_db, token_user, include_refresh_token +): + token_user.active = False + fresh_db.session.commit() + options = {"include_refresh_token": True} if include_refresh_token else {} + assert login(client, **options).status_code == 401 + + +def test_disabled_user_cannot_refresh(client, fresh_db, token_user): + pair = assert_pair(login(client, include_refresh_token=True), token_user.id) + token_user.active = False + fresh_db.session.commit() + assert refresh(client, pair["refresh-token"]).status_code == 401 + token_user.active = True + fresh_db.session.commit() + assert refresh(client, pair["refresh-token"]).status_code == 401 + + +@pytest.mark.parametrize("path", ["/api/refreshAuthToken", "/api/revokeRefreshToken"]) +@pytest.mark.parametrize( + "payload", [{}, {"refresh-token": None}, {"refresh-token": 12}] +) +def test_malformed_refresh_requests(client, token_user, path, payload): + assert client.post(path, json=payload).status_code in (400, 422) + + +@pytest.mark.parametrize("path", ["/api/refreshAuthToken", "/api/revokeRefreshToken"]) +def test_invalid_refresh_token(client, token_user, path): + assert client.post(path, json={"refresh-token": "invalid"}).status_code == 401 + + +@pytest.fixture +def token_clock(app, monkeypatch): + """Advance both token signatures and refresh tracker clocks together.""" + security = app.extensions["security"] + initial = security.datetime_factory() + wall_time = time.time() + + def advance(seconds): + monkeypatch.setattr( + security, "datetime_factory", lambda: initial + timedelta(seconds=seconds) + ) + monkeypatch.setattr(time, "time", lambda: wall_time + seconds) + + return advance + + +def test_expired_access_token_can_be_refreshed( + app, client, token_user, token_clock, monkeypatch +): + monkeypatch.setitem(app.config, "SECURITY_TOKEN_MAX_AGE", timedelta(seconds=5)) + pair = assert_pair(login(client, include_refresh_token=True), token_user.id) + # Remaining lifetime is rounded down to avoid overstating validity. + assert 0 < pair["expires-in"] <= 5 + token_clock(10) + clear_auth() + assert ( + client.get( + url_for("AssetAPI:index"), headers={"Authorization": pair["auth_token"]} + ).status_code + == 401 + ) + assert_pair(refresh(client, pair["refresh-token"]), token_user.id) + + +def test_refresh_idle_expiry(app, client, token_user, token_clock, monkeypatch): + monkeypatch.setitem( + app.config, "SECURITY_REFRESH_TOKEN_MAX_IDLE", timedelta(seconds=10) + ) + pair = assert_pair(login(client, include_refresh_token=True), token_user.id) + token_clock(11) + assert refresh(client, pair["refresh-token"]).status_code == 401 + + +def test_rotation_preserves_absolute_expiry( + app, client, token_user, token_clock, monkeypatch +): + monkeypatch.setitem( + app.config, "SECURITY_REFRESH_TOKEN_MAX_AGE", timedelta(seconds=20) + ) + monkeypatch.setitem( + app.config, "SECURITY_REFRESH_TOKEN_MAX_IDLE", timedelta(seconds=15) + ) + pair = assert_pair(login(client, include_refresh_token=True), token_user.id) + token_clock(10) + pair = assert_pair(refresh(client, pair["refresh-token"]), token_user.id) + token_clock(21) + assert refresh(client, pair["refresh-token"]).status_code == 401 + + +def test_independent_login_has_independent_token_family(client, token_user): + first = assert_pair(login(client, include_refresh_token=True), token_user.id) + second = assert_pair(login(client, include_refresh_token=True), token_user.id) + assert first["refresh-token"] != second["refresh-token"] + client.post( + "/api/revokeRefreshToken", json={"refresh-token": first["refresh-token"]} + ) + assert_pair(refresh(client, second["refresh-token"]), token_user.id) + + +def test_wrong_password_cannot_obtain_refresh_token(client, fresh_db, token_user): + response = login(client, include_refresh_token=True, password="incorrect") + assert response.status_code == 401 + assert "refresh-token" not in response.json + fresh_db.session.refresh(token_user) + assert not token_user.refresh_trackers + + +def test_changed_token_identity_revokes_refresh(client, fresh_db, token_user): + pair = assert_pair(login(client, include_refresh_token=True), token_user.id) + token_user.fs_uniquifier = "changed-token-identity" + fresh_db.session.commit() + assert refresh(client, pair["refresh-token"]).status_code == 401 + + +def test_concurrent_refresh_revokes_family(app, client, token_user): + """Only one racing refresh succeeds, and replay revokes its replacement.""" + pair = assert_pair(login(client, include_refresh_token=True), token_user.id) + barrier = Barrier(2) + + def exchange(): + with app.app_context(), app.test_client() as concurrent_client: + barrier.wait(timeout=10) + response = refresh(concurrent_client, pair["refresh-token"]) + return response.status_code, response.json + + with ThreadPoolExecutor(max_workers=2) as executor: + futures = [executor.submit(exchange) for _ in range(2)] + responses = [future.result(timeout=20) for future in futures] + assert sorted(status for status, _ in responses) == [200, 401] + replacement = next( + body["refresh-token"] for status, body in responses if status == 200 + ) + assert refresh(client, replacement).status_code == 401 + + +@pytest.mark.parametrize("change", ["password", "deactivate"]) +def test_security_change_revokes_without_refresh_attempt( + client, fresh_db, token_user, change +): + pair = assert_pair(login(client, include_refresh_token=True), token_user.id) + if change == "password": + token_user.password = "changed-password-hash" + else: + token_user.active = False + fresh_db.session.commit() + if change == "deactivate": + token_user.active = True + fresh_db.session.commit() + assert refresh(client, pair["refresh-token"]).status_code == 401 + + +def test_per_token_expiry_limits_reported_lifetime( + app, client, token_user, monkeypatch +): + monkeypatch.setitem( + app.config, "SECURITY_TOKEN_EXPIRE_TIMESTAMP", lambda user: time.time() + 30 + ) + pair = assert_pair(login(client, include_refresh_token=True), token_user.id) + assert 0 < pair["expires-in"] <= 30 + + +def test_unlimited_access_token_lifetime(app, client, token_user, monkeypatch): + monkeypatch.setitem(app.config, "SECURITY_TOKEN_MAX_AGE", timedelta(0)) + monkeypatch.setitem(app.config, "SECURITY_TOKEN_EXPIRE_TIMESTAMP", lambda user: 0) + response = login(client, include_refresh_token=True) + assert response.status_code == 200 + assert response.json["expires-in"] is None + + +def test_revocation_at_same_instant(client, token_user, token_clock): + """Revocation is immediate, even when two requests share a clock timestamp.""" + token_clock(0) + pair = assert_pair(login(client, include_refresh_token=True), token_user.id) + response = client.post( + "/api/revokeRefreshToken", json={"refresh-token": pair["refresh-token"]} + ) + assert response.status_code == 200 + assert response.json["revoked"] is True + assert refresh(client, pair["refresh-token"]).status_code == 401 + + +def test_session_cannot_replace_password_for_refresh_issuance(client, token_user): + with client.session_transaction() as session: + session["_user_id"] = token_user.get_id() + session["_fresh"] = True + clear_auth() + # Preserve the existing signed-in access-token flow, but require the password + # before issuing a new long-lived refresh credential. + assert login(client, password="incorrect").status_code == 200 + clear_auth() + response = login(client, password="incorrect", include_refresh_token=True) + assert response.status_code == 401 + assert "refresh-token" not in response.json diff --git a/flexmeasures/data/schemas/tests/test_field_naming.py b/flexmeasures/data/schemas/tests/test_field_naming.py index b01f84a77d..82d82c59df 100644 --- a/flexmeasures/data/schemas/tests/test_field_naming.py +++ b/flexmeasures/data/schemas/tests/test_field_naming.py @@ -31,7 +31,6 @@ "account_id", "account_roles", "active_user_id", - "authentication_token", "all_accessible", "asset_type", "belief_horizon", @@ -111,6 +110,15 @@ } ) +# requestAuthToken has always returned these keys; its old OpenAPI description +# incorrectly called the token authentication_token and omitted user_id. Keep +# the real legacy response contract (also used by refreshAuthToken), without +# allowing these spellings on new domain APIs or expanding the global debt list. +LEGACY_AUTH_RESPONSE_FIELDS = { + "auth_token": {"/api/requestAuthToken", "/api/refreshAuthToken"}, + "user_id": {"/api/requestAuthToken", "/api/refreshAuthToken"}, +} + def _flexmeasures_schemas() -> list[type[Schema]]: """Every Marshmallow schema FlexMeasures defines, found by importing and walking subclasses.""" @@ -373,9 +381,11 @@ def test_a_body_property_in_the_openapi_specs_is_kebab_case(): This catches a response field documented on its endpoint, whose payload is built as a plain dict rather than dumped by a schema. """ offenders = { - name: sorted(places) + name: sorted(places - LEGACY_AUTH_RESPONSE_FIELDS.get(name, set())) for name, places in _openapi_property_names(_openapi_specs()).items() - if "_" in name and name not in KNOWN_SNAKE_CASE_WIRE_NAMES + if "_" in name + and name not in KNOWN_SNAKE_CASE_WIRE_NAMES + and places - LEGACY_AUTH_RESPONSE_FIELDS.get(name, set()) } assert not offenders, ( From 64a6695de274f4f9e54aaef1dbcccc8419e88243 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Sun, 8 Nov 2026 00:21:18 +0100 Subject: [PATCH 04/33] changelog: announce optional API refresh tokens Context: - Issue #2229 adds renewable API credentials. Change: - Describe refresh-token rotation, expiry and revocation while retaining legacy access-token authentication. --- documentation/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/documentation/changelog.rst b/documentation/changelog.rst index b51fcfe824..553fccc5e8 100644 --- a/documentation/changelog.rst +++ b/documentation/changelog.rst @@ -12,6 +12,8 @@ v1.2.0 | December xx, 2026 New features ------------- +* Add opt-in rotating refresh tokens for API clients, with expiry and revocation while preserving existing access-token authentication [see `issue #2229 `_] + Infrastructure / Support ------------------------- * Speed up preparing a schedule for a flex-model with many devices, such as one device per charging session, by reading each commitment's constant values once instead of off each of its thousands of one-row sub-commitments [see `PR #2516 `_] From df93c491ba1b5ad8bdf0bb39100dd38003806518 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Sun, 8 Nov 2026 00:22:05 +0100 Subject: [PATCH 05/33] docs: explain the refresh-token lifecycle and API contract Context: - New clients need a complete flow and guidance for safe rotation and recovery. Change: - Document opt-in authentication, exchange, revocation, expiry and deployment requirements with curl and Python examples. - Update generated OpenAPI definitions to match the actual authentication responses. --- documentation/api/introduction.rst | 150 +++++++++++++++++++++- documentation/concepts/security_auth.rst | 2 +- flexmeasures/ui/static/openapi-specs.json | 141 +++++++++++++++++++- 3 files changed, 288 insertions(+), 5 deletions(-) diff --git a/documentation/api/introduction.rst b/documentation/api/introduction.rst index 328dc06e05..b11273945d 100644 --- a/documentation/api/introduction.rst +++ b/documentation/api/introduction.rst @@ -109,7 +109,155 @@ which gives a response like this if the credentials are correct: "user_id": "" } -.. note:: Each access token has a limited lifetime, see :ref:`api_auth`. +Access tokens expire after six hours by default; the host can configure a different lifetime. +The existing request and response above remain unchanged. Authenticate again with your +email and password when the token expires, or opt in to refresh tokens as described below. +Use the token directly in the ``Authorization`` header, without a ``Bearer`` prefix. + +.. _api_refresh_tokens: + +Refresh tokens +^^^^^^^^^^^^^^ + +A refresh token lets an integration obtain a new access token without sending the user's +password again. It is a long-lived credential: protect it as carefully as a password. +These JSON endpoints extend FlexMeasures authentication; they are not an OAuth implementation +and do not change browser login sessions. + +To opt in, add ``"include-refresh-token": true`` to ``POST /api/requestAuthToken``: + +.. code-block:: json + + { + "email": "user@example.com", + "password": "", + "include-refresh-token": true + } + +A successful response has HTTP status 200: + +.. code-block:: json + + { + "auth_token": "", + "user_id": 1, + "refresh-token": "", + "expires-in": 21600 + } + +``auth_token`` is the access token used for ordinary API requests. ``expires-in`` is its +lifetime in seconds, reflecting the host's configuration. The example uses the default +six hours. A refresh token cannot authenticate an ordinary API request. +If the host has configured access tokens without an expiry, ``expires-in`` is ``null``. +Responses also include FlexMeasures' usual ``status`` field. + +To replace the access token, send ``POST /api/refreshAuthToken`` with this JSON body: + +.. code-block:: json + + {"refresh-token": ""} + +No password or access token is required, so refresh also works after the access token +expires. A successful refresh returns the same four fields as the opt-in login response, +including a replacement refresh token. Save both replacement tokens together before making +another refresh request. + +Each refresh token can be used only once. All replacement tokens descended from a login +form a *token family*. Reusing an already exchanged token revokes that family, including +its newest refresh token. Serialize refresh requests across workers that share credentials. +If a refresh response is lost, authenticate again with email and password; blindly retrying +the old token may revoke the family. + +To stop future refreshes, send ``POST /api/revokeRefreshToken`` with the current refresh +token in the same JSON format. It returns HTTP status 200 with ``{"revoked": true}`` +and revokes the family. Already issued access tokens remain usable until they expire or +are invalidated, for example by a password change. Disabled users cannot authenticate. +Password changes and user deactivation revoke existing refresh-token families. +Reactivating a user does not restore those families. Revocation does not log out +an existing browser session. + +By default, a refresh-token family expires 90 days after its initial login, or after +7 days without a successful refresh, whichever happens first. Rotation does not extend +the absolute lifetime. Hosts configure these limits with ``SECURITY_REFRESH_TOKEN_MAX_AGE`` +and ``SECURITY_REFRESH_TOKEN_MAX_IDLE``. After expiry or revocation, authenticate again +with email and password. +These settings take Python ``datetime.timedelta`` values. API refresh support does not +require enabling Flask-Security's global ``SECURITY_REFRESH_TOKEN`` flag, which also +changes browser authentication. Apply the database migration before running the upgraded server. + +Malformed requests return HTTP status 400 with validation errors. An invalid, expired, +revoked, or reused refresh token returns HTTP status 401 with ``error`` set to +``"invalid_refresh_token"`` and an ``errors`` list. On that response, authenticate again; +do not retry the rejected token. Ordinary API authorization still depends on the user's +permissions, and refreshing a token does not grant additional permissions. + +Use HTTPS, keep passwords and tokens out of logs, and store them in a protected credential +store. Token responses include ``Cache-Control: no-store``. The following examples use +placeholders; do not put real credentials in shell history. + +Example requests with curl (``--fail-with-body`` reports HTTP failures): + +.. code-block:: bash + + curl --fail-with-body https://company.flexmeasures.io/api/requestAuthToken \ + -H 'Content-Type: application/json' \ + -d '{"email":"user@example.com","password":"","include-refresh-token":true}' + + curl --fail-with-body https://company.flexmeasures.io/api/v3_0/users/1 \ + -H 'Authorization: ' + + curl --fail-with-body https://company.flexmeasures.io/api/refreshAuthToken \ + -H 'Content-Type: application/json' \ + -d '{"refresh-token":""}' + + curl --fail-with-body https://company.flexmeasures.io/api/revokeRefreshToken \ + -H 'Content-Type: application/json' \ + -d '{"refresh-token":""}' + +The equivalent Python sequence logs in, accesses the API, refreshes, accesses the API +with the replacement token, and revokes the refresh-token family. This single-process +example keeps tokens in memory; a persistent client should save replacements atomically. +It deliberately does not automatically retry failed refresh requests. + +.. code-block:: python + + import getpass + import requests + + base_url = "https://company.flexmeasures.io" + + def post_token(endpoint, body): + response = requests.post( + f"{base_url}/api/{endpoint}", json=body, timeout=30 + ) + if response.status_code == 401: + raise RuntimeError("Authentication failed; sign in again.") + response.raise_for_status() + return response.json() + + tokens = post_token("requestAuthToken", { + "email": input("Email: "), + "password": getpass.getpass(), + "include-refresh-token": True, + }) + + def get_user(tokens): + response = requests.get( + f"{base_url}/api/v3_0/users/{tokens['user_id']}", + headers={"Authorization": tokens["auth_token"]}, + timeout=30, + ) + response.raise_for_status() + return response.json() + + user = get_user(tokens) + tokens = post_token("refreshAuthToken", { + "refresh-token": tokens["refresh-token"], + }) + user = get_user(tokens) + post_token("revokeRefreshToken", { + "refresh-token": tokens["refresh-token"], + }) .. _api_see_other: diff --git a/documentation/concepts/security_auth.rst b/documentation/concepts/security_auth.rst index 9630b77423..1620eeced3 100644 --- a/documentation/concepts/security_auth.rst +++ b/documentation/concepts/security_auth.rst @@ -33,7 +33,7 @@ Authentication This involves a username/password combination ("credentials") or an access token. * No user passwords are stored in clear text on any server - the FlexMeasures platform only stores the hashed passwords (encrypted with the `bcrypt hashing algorithm `_). If an attacker steals these password hashes, they cannot compute the passwords from them in a practical amount of time. -* In the API, access tokens are used so that the sending of usernames and passwords is limited (even if they are encrypted via https, see above) when dealing with the part of the FlexMeasures platform which sees the most traffic: the API functionality. Tokens thus have use cases for some scenarios, where developers want to treat authentication information with a little less care than credentials should be treated with, e.g. sharing among computers. However, they also expire fast, which is a common industry practice (by making them short-lived and requiring refresh, FlexMeasures limits the time an attacker can abuse a stolen token). At the moment, the access tokens on FlexMeasures platform expire after six hours. Access tokens are encrypted and validated with the `sha256_crypt algorithm `_, and `the functionality to expire tokens is realised by storing the seconds since January 1, 2011 in the token `_. The maximum age of access tokens in FlexMeasures can be altered by setting the env variable `SECURITY_TOKEN_MAX_AGE` to the number of seconds after which tokens should expire. +* In the API, access tokens limit how often clients need to send a username and password. Treat tokens as secrets and transmit them only over HTTPS. Access tokens expire after six hours by default; hosts can configure their lifetime with ``SECURITY_TOKEN_MAX_AGE`` (seconds). Clients can opt in to rotating refresh tokens to obtain replacement access tokens without resending the password. Refresh tokens are longer-lived credentials and need the same protection as passwords. See :ref:`api_auth` for the existing login flow and :ref:`api_refresh_tokens` for expiry, rotation, revocation, and client examples. * In the UI, FlexMeasures uses two-factor authentication (2FA). This means that the knowledge of the password to your FlexMeasures account is not sufficient to gain access ― you also need a second piece of knowledge, which requires you to also have access to an independent system or device (e.g. a token sent to your email address). .. note:: Authentication (and authorization, see below) affects the FlexMeasures API and UI. The CLI (command line interface) can only be used if the user is already on the server and can execute ``flexmeasures`` commands, thus we can safely assume they are admins. diff --git a/flexmeasures/ui/static/openapi-specs.json b/flexmeasures/ui/static/openapi-specs.json index 6be8b491e3..84896c9bdf 100644 --- a/flexmeasures/ui/static/openapi-specs.json +++ b/flexmeasures/ui/static/openapi-specs.json @@ -7,7 +7,7 @@ }, "termsOfService": null, "title": "FlexMeasures", - "version": "1.1.0" + "version": "1.1.1" }, "externalDocs": { "description": "FlexMeasures runs on the open source FlexMeasures technology. Read the docs here.", @@ -36,9 +36,21 @@ "schema": { "type": "object", "properties": { - "authentication_token": { + "auth_token": { "type": "string", - "description": "Short-lived authentication token, which can be used in request headers using `{\"Authorization\": authentication_token}`.\n" + "description": "Short-lived access token, used as `{\"Authorization\": auth_token}`.\n" + }, + "user_id": { + "type": "integer" + }, + "refresh-token": { + "type": "string", + "description": "Returned only when include-refresh-token is true." + }, + "expires-in": { + "type": "integer", + "nullable": true, + "description": "Access-token lifetime in seconds (null if unlimited), returned with refresh-token." } } } @@ -103,6 +115,123 @@ ] } }, + "/api/refreshAuthToken": { + "post": { + "summary": "Rotate a refresh token and obtain a new access token.", + "description": "No access token or password is required. Save the returned refresh token\natomically and serialize refresh requests. Reuse revokes the token family.\n", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "refresh-token" + ], + "properties": { + "refresh-token": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "New access and refresh token pair.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "auth_token": { + "type": "string" + }, + "user_id": { + "type": "integer" + }, + "refresh-token": { + "type": "string" + }, + "expires-in": { + "type": "integer", + "nullable": true, + "description": "Access-token lifetime in seconds, or null if unlimited." + } + } + } + } + } + }, + "400": { + "description": "Invalid request." + }, + "401": { + "description": "Invalid, expired or revoked refresh token. Authenticate again." + }, + "429": { + "description": "TOO_MANY_REQUESTS - You called the API more often than your rate limit allows. Wait for as long as the Retry-After header says, then try again." + } + }, + "tags": [ + "Auth" + ] + } + }, + "/api/revokeRefreshToken": { + "post": { + "summary": "Revoke this refresh-token family.", + "description": "Existing access tokens remain valid until expiry or invalidation.", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "refresh-token" + ], + "properties": { + "refresh-token": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Refresh-token family revoked.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "revoked": { + "type": "boolean" + } + } + } + } + } + }, + "400": { + "description": "Invalid request." + }, + "401": { + "description": "Invalid, expired or revoked refresh token." + }, + "429": { + "description": "TOO_MANY_REQUESTS - You called the API more often than your rate limit allows. Wait for as long as the Retry-After header says, then try again." + } + }, + "tags": [ + "Auth" + ] + } + }, "/api/ops/ping": {}, "/api/ops/getLatestTaskRun": {}, "/api/ops/postLatestTaskRun": {}, @@ -7125,6 +7254,12 @@ "AuthRequestSchema": { "type": "object", "properties": { + "include-refresh-token": { + "type": "boolean", + "default": false, + "description": "Also issue a rotating refresh token and access-token expires-in (seconds).", + "example": true + }, "email": { "type": "string", "description": "The user's email address." From c212713af01ffda75476dfa5017d002ff9e179ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Tue, 10 Nov 2026 14:33:03 +0100 Subject: [PATCH 06/33] Apply suggestion from @nhoening MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Nicolas Höning --- documentation/changelog.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/documentation/changelog.rst b/documentation/changelog.rst index a063a04ed1..f239b53c74 100644 --- a/documentation/changelog.rst +++ b/documentation/changelog.rst @@ -12,7 +12,7 @@ v1.2.0 | December xx, 2026 New features ------------- -* Add opt-in rotating refresh tokens for API clients, with expiry and revocation while preserving existing access-token authentication [see `issue #2229 `_] +* Add opt-in rotating refresh tokens for API clients, with expiry and revocation while preserving existing access-token authentication [see `PR #2849 `_] Infrastructure / Support ------------------------- From bf52eab8b92e03468794f7a94edb5b4b8f887a8b Mon Sep 17 00:00:00 2001 From: Serhii Date: Fri, 20 Nov 2026 15:13:59 +0200 Subject: [PATCH 07/33] Fix the review findings on refresh tokens that need no design decision (#2853) * auth: lock the user before deleting their refresh-token families Refreshing a token locks the user row and then the family row. Deleting a user let the ORM delete the family rows first and the user row after, so the two could deadlock, and PostgreSQL then aborted the deletion. Take the lock on the user row at the start of delete_user, without autoflush, so that both paths lock in the same order, also when the session holds pending changes to the families. Signed-off-by: Serhii * migration: name the refresh-token index after the naming convention The model's index=True yields refresh_token_tracker_user_id_idx under the project's naming convention, while the migration created ix_refresh_token_tracker_user_id, so flexmeasures db check reported the index as removed and added. Signed-off-by: Serhii * docs: state the status codes the refresh-token endpoints return for bad requests A request that fails validation, such as a missing, null, empty or non-string refresh-token, returns 422, as validation errors do elsewhere in the API. Only JSON that cannot be parsed returns 400. Signed-off-by: Serhii * tests: cover the deletion lock order, the status codes and two unguarded safeguards Removing the inactive-user check from the token exchange, or the commit after an explicit revocation, left all tests green. The first is now covered by deactivating a user with a bulk update, which skips the listener that revokes the families. The second by rolling back the shared session after revoking, so that a later request cannot commit the pending revocation. Signed-off-by: Serhii --------- Signed-off-by: Serhii --- documentation/api/introduction.rst | 3 +- flexmeasures/api/refresh_tokens.py | 8 +- .../api/tests/test_refresh_tokens_fresh_db.py | 75 ++++++++++++++++++- ...af36c80d214e_add_refresh_token_trackers.py | 2 +- flexmeasures/data/services/users.py | 6 ++ flexmeasures/ui/static/openapi-specs.json | 10 ++- 6 files changed, 95 insertions(+), 9 deletions(-) diff --git a/documentation/api/introduction.rst b/documentation/api/introduction.rst index 3f6822cbab..7d38887137 100644 --- a/documentation/api/introduction.rst +++ b/documentation/api/introduction.rst @@ -185,7 +185,8 @@ These settings take Python ``datetime.timedelta`` values. API refresh support do require enabling Flask-Security's global ``SECURITY_REFRESH_TOKEN`` flag, which also changes browser authentication. Apply the database migration before running the upgraded server. -Malformed requests return HTTP status 400 with validation errors. An invalid, expired, +A request that fails validation, for instance one without a usable ``refresh-token`` field, returns HTTP status 422 with validation errors, +and a JSON body that cannot be parsed returns HTTP status 400. An invalid, expired, revoked, or reused refresh token returns HTTP status 401 with ``error`` set to ``"invalid_refresh_token"`` and an ``errors`` list. On that response, authenticate again; do not retry the rejected token. Ordinary API authorization still depends on the user's diff --git a/flexmeasures/api/refresh_tokens.py b/flexmeasures/api/refresh_tokens.py index b41c1dadb1..ad4e24df95 100644 --- a/flexmeasures/api/refresh_tokens.py +++ b/flexmeasures/api/refresh_tokens.py @@ -62,9 +62,11 @@ def refresh_auth_token(args): nullable: true description: Access-token lifetime in seconds, or null if unlimited. 400: - description: Invalid request. + description: The JSON in the request body cannot be parsed. 401: description: Invalid, expired or revoked refresh token. Authenticate again. + 422: + description: UNPROCESSABLE_ENTITY tags: - Auth """ @@ -102,9 +104,11 @@ def revoke_refresh_token(args): revoked: type: boolean 400: - description: Invalid request. + description: The JSON in the request body cannot be parsed. 401: description: Invalid, expired or revoked refresh token. + 422: + description: UNPROCESSABLE_ENTITY tags: - Auth """ diff --git a/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py b/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py index ddbc7e6d24..ecd5fc17a0 100644 --- a/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py +++ b/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py @@ -7,9 +7,11 @@ import pytest from flask import g, url_for -from sqlalchemy import select +from sqlalchemy import event, select +from flexmeasures.data.models.refresh_tokens import RefreshTokenTracker from flexmeasures.data.models.user import User +from flexmeasures.data.services.users import delete_user @pytest.fixture(autouse=True) @@ -123,6 +125,17 @@ def test_revoke_refresh_token(client, token_user): assert refresh(client, pair["refresh-token"]).status_code == 401 +def test_revocation_is_committed_by_the_revoking_request(client, fresh_db, token_user): + """The tests share one database session, so without the rollback here, the next request would commit a pending revocation.""" + pair = assert_pair(login(client, include_refresh_token=True), token_user.id) + response = client.post( + "/api/revokeRefreshToken", json={"refresh-token": pair["refresh-token"]} + ) + assert response.status_code == 200 + fresh_db.session.rollback() + assert refresh(client, pair["refresh-token"]).status_code == 401 + + @pytest.mark.parametrize("include_refresh_token", [False, True]) def test_disabled_user_cannot_obtain_tokens( client, fresh_db, token_user, include_refresh_token @@ -143,12 +156,68 @@ def test_disabled_user_cannot_refresh(client, fresh_db, token_user): assert refresh(client, pair["refresh-token"]).status_code == 401 +def test_user_disabled_outside_the_orm_cannot_refresh(client, fresh_db, token_user): + """A bulk update skips the listener that revokes the families, so the exchange itself has to refuse an inactive user.""" + pair = assert_pair(login(client, include_refresh_token=True), token_user.id) + fresh_db.session.execute( + User.__table__.update().where(User.id == token_user.id).values(active=False) + ) + fresh_db.session.commit() + assert refresh(client, pair["refresh-token"]).status_code == 401 + + +@pytest.mark.parametrize("families", ["not loaded", "loaded", "modified"]) +def test_deleting_a_user_locks_the_user_before_the_families( + app, client, fresh_db, token_user, families +): + """Refreshing locks the user before the family, so deleting has to lock in that order as well, or the two can deadlock.""" + assert_pair(login(client, include_refresh_token=True), token_user.id) + if families != "not loaded": + assert len(token_user.refresh_trackers) == 1 + if families == "modified": + token_user.refresh_trackers[0].name = "renamed" + statements = [] + + def record(conn, cursor, statement, parameters, context, executemany): + statements.append(statement) + + event.listen(fresh_db.engine, "before_cursor_execute", record) + try: + with app.test_request_context(): + delete_user(token_user) + fresh_db.session.commit() + finally: + event.remove(fresh_db.engine, "before_cursor_execute", record) + first_write = next( + i for i, s in enumerate(statements) if s.startswith(("DELETE", "UPDATE")) + ) + assert any( + "FROM fm_user" in s and "FOR UPDATE" in s for s in statements[:first_write] + ) + assert any(s.startswith("DELETE FROM fm_user") for s in statements) + assert not fresh_db.session.scalars(select(RefreshTokenTracker)).all() + + @pytest.mark.parametrize("path", ["/api/refreshAuthToken", "/api/revokeRefreshToken"]) @pytest.mark.parametrize( - "payload", [{}, {"refresh-token": None}, {"refresh-token": 12}] + "payload", + [ + {}, + {"refresh-token": None}, + {"refresh-token": 12}, + {"refresh-token": ""}, + {"refresh-token": "token", "refresh_token": "token"}, + ], ) def test_malformed_refresh_requests(client, token_user, path, payload): - assert client.post(path, json=payload).status_code in (400, 422) + assert client.post(path, json=payload).status_code == 422 + + +@pytest.mark.parametrize("path", ["/api/refreshAuthToken", "/api/revokeRefreshToken"]) +def test_refresh_request_with_unparsable_json(client, token_user, path): + """Only JSON that cannot be parsed is a 400, whereas a body that fails validation is a 422.""" + response = client.post(path, data="{", content_type="application/json") + assert response.status_code == 400 @pytest.mark.parametrize("path", ["/api/refreshAuthToken", "/api/revokeRefreshToken"]) diff --git a/flexmeasures/data/migrations/versions/af36c80d214e_add_refresh_token_trackers.py b/flexmeasures/data/migrations/versions/af36c80d214e_add_refresh_token_trackers.py index 8c63d866f7..64a738bc83 100644 --- a/flexmeasures/data/migrations/versions/af36c80d214e_add_refresh_token_trackers.py +++ b/flexmeasures/data/migrations/versions/af36c80d214e_add_refresh_token_trackers.py @@ -37,7 +37,7 @@ def upgrade(): ), ) op.create_index( - "ix_refresh_token_tracker_user_id", "refresh_token_tracker", ["user_id"] + "refresh_token_tracker_user_id_idx", "refresh_token_tracker", ["user_id"] ) diff --git a/flexmeasures/data/services/users.py b/flexmeasures/data/services/users.py index aa9e8c5948..d13e3ac324 100644 --- a/flexmeasures/data/services/users.py +++ b/flexmeasures/data/services/users.py @@ -235,6 +235,12 @@ def delete_user(user: User): if hasattr(current_user, "id") and user.id == current_user.id: raise Exception("You cannot delete yourself.") + # Lock the user before the ORM writes to their refresh-token families. + # Refreshing a token locks the user first and the family second, so writing in the opposite order could deadlock with it. + # Without autoflush, as that would write pending changes to the families before the lock is taken. + with db.session.no_autoflush: + db.session.execute(select(User.id).where(User.id == user.id).with_for_update()) + user_datastore = SQLAlchemySessionUserDatastore(db.session, User, Role) user_datastore.delete_user(user) db.session.execute(delete(User).filter_by(id=user.id)) diff --git a/flexmeasures/ui/static/openapi-specs.json b/flexmeasures/ui/static/openapi-specs.json index 2ed8182864..f24bc6885d 100644 --- a/flexmeasures/ui/static/openapi-specs.json +++ b/flexmeasures/ui/static/openapi-specs.json @@ -165,11 +165,14 @@ } }, "400": { - "description": "Invalid request." + "description": "The JSON in the request body cannot be parsed." }, "401": { "description": "Invalid, expired or revoked refresh token. Authenticate again." }, + "422": { + "description": "UNPROCESSABLE_ENTITY" + }, "429": { "description": "TOO_MANY_REQUESTS - You called the API more often than your rate limit allows. Wait for as long as the Retry-After header says, then try again." } @@ -218,11 +221,14 @@ } }, "400": { - "description": "Invalid request." + "description": "The JSON in the request body cannot be parsed." }, "401": { "description": "Invalid, expired or revoked refresh token." }, + "422": { + "description": "UNPROCESSABLE_ENTITY" + }, "429": { "description": "TOO_MANY_REQUESTS - You called the API more often than your rate limit allows. Wait for as long as the Retry-After header says, then try again." } From 91c1182b9032dcee25869afef26d3d2a95938f5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Fri, 20 Nov 2026 15:40:44 +0100 Subject: [PATCH 08/33] migrations: merge refresh-token and automation heads --- ...merge_refresh_token_and_automation_heads.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 flexmeasures/data/migrations/versions/c8d4193f27a6_merge_refresh_token_and_automation_heads.py diff --git a/flexmeasures/data/migrations/versions/c8d4193f27a6_merge_refresh_token_and_automation_heads.py b/flexmeasures/data/migrations/versions/c8d4193f27a6_merge_refresh_token_and_automation_heads.py new file mode 100644 index 0000000000..996b98c616 --- /dev/null +++ b/flexmeasures/data/migrations/versions/c8d4193f27a6_merge_refresh_token_and_automation_heads.py @@ -0,0 +1,18 @@ +"""Merge refresh-token and automation-monitoring migrations. + +Revision ID: c8d4193f27a6 +Revises: af36c80d214e, e8a3f6c2b917 +""" + +revision = "c8d4193f27a6" +down_revision = ("af36c80d214e", "e8a3f6c2b917") +branch_labels = None +depends_on = None + + +def upgrade(): + pass + + +def downgrade(): + pass From bb275f7531d2ada3097c3e5c703317b5e80b6989 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Fri, 20 Nov 2026 17:20:37 +0100 Subject: [PATCH 09/33] auth: report zero access-token lifetime accurately --- flexmeasures/auth/tokens.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/flexmeasures/auth/tokens.py b/flexmeasures/auth/tokens.py index 215f459e8c..3511fbe9de 100644 --- a/flexmeasures/auth/tokens.py +++ b/flexmeasures/auth/tokens.py @@ -22,13 +22,11 @@ def token_response(user, refresh_token: str) -> dict: access_token, return_timestamp=True ) max_age = current_app.config["SECURITY_TOKEN_MAX_AGE"].total_seconds() - deadlines = [] - if max_age: - deadlines.append(issued_at.timestamp() + max_age) + deadlines = [issued_at.timestamp() + max_age] + # Flask-Security uses a zero exp value to mean no additional token deadline. if data.get("exp"): deadlines.append(data["exp"]) - # None explicitly denotes a deployment configured with non-expiring tokens. - expires_in = max(0, int(min(deadlines) - time.time())) if deadlines else None + expires_in = max(0, int(min(deadlines) - time.time())) return { "auth_token": access_token, "user_id": user.id, From 48291cc5d68a91ff4ea24bcc97891df15b9770d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Fri, 20 Nov 2026 17:21:18 +0100 Subject: [PATCH 10/33] tests: cover zero and per-token access expiry --- .../api/tests/test_refresh_tokens_fresh_db.py | 56 +++++++++++++++++-- 1 file changed, 50 insertions(+), 6 deletions(-) diff --git a/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py b/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py index ecd5fc17a0..7ce3d8cc62 100644 --- a/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py +++ b/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py @@ -347,21 +347,65 @@ def test_security_change_revokes_without_refresh_attempt( def test_per_token_expiry_limits_reported_lifetime( - app, client, token_user, monkeypatch + app, client, token_user, token_clock, monkeypatch ): + token_clock(0) monkeypatch.setitem( - app.config, "SECURITY_TOKEN_EXPIRE_TIMESTAMP", lambda user: time.time() + 30 + app.config, "SECURITY_TOKEN_EXPIRE_TIMESTAMP", lambda user: time.time() + 5 ) pair = assert_pair(login(client, include_refresh_token=True), token_user.id) - assert 0 < pair["expires-in"] <= 30 + assert 0 < pair["expires-in"] <= 5 + clear_auth() + assert ( + client.get( + url_for("AssetAPI:index"), headers={"Authorization": pair["auth_token"]} + ).status_code + == 200 + ) + token_clock(10) + clear_auth() + assert ( + client.get( + url_for("AssetAPI:index"), headers={"Authorization": pair["auth_token"]} + ).status_code + == 401 + ) -def test_unlimited_access_token_lifetime(app, client, token_user, monkeypatch): +@pytest.mark.parametrize("per_token_expiry", [0, 30]) +def test_zero_access_token_lifetime( + app, client, token_user, token_clock, monkeypatch, per_token_expiry +): + """Zero max age is not unlimited, even with a later per-token deadline.""" + token_clock(0) monkeypatch.setitem(app.config, "SECURITY_TOKEN_MAX_AGE", timedelta(0)) - monkeypatch.setitem(app.config, "SECURITY_TOKEN_EXPIRE_TIMESTAMP", lambda user: 0) + monkeypatch.setitem( + app.config, + "SECURITY_TOKEN_EXPIRE_TIMESTAMP", + lambda user: time.time() + per_token_expiry if per_token_expiry else 0, + ) response = login(client, include_refresh_token=True) assert response.status_code == 200 - assert response.json["expires-in"] is None + pair = response.json + assert pair["expires-in"] == 0 + clear_auth() + assert ( + client.get( + url_for("AssetAPI:index"), headers={"Authorization": pair["auth_token"]} + ).status_code + == 200 + ) + token_clock(2) + clear_auth() + assert ( + client.get( + url_for("AssetAPI:index"), headers={"Authorization": pair["auth_token"]} + ).status_code + == 401 + ) + replacement = refresh(client, pair["refresh-token"]) + assert replacement.status_code == 200 + assert replacement.json["expires-in"] == 0 def test_revocation_at_same_instant(client, token_user, token_clock): From 84538ea84006fbe70bb8e3406d4e2621c81cc197 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Fri, 20 Nov 2026 17:21:55 +0100 Subject: [PATCH 11/33] docs: clarify access-token expiry responses --- documentation/api/introduction.rst | 3 ++- flexmeasures/api/__init__.py | 3 +-- flexmeasures/api/refresh_tokens.py | 3 +-- flexmeasures/ui/static/openapi-specs.json | 6 ++---- 4 files changed, 6 insertions(+), 9 deletions(-) diff --git a/documentation/api/introduction.rst b/documentation/api/introduction.rst index 7d38887137..db1875054f 100644 --- a/documentation/api/introduction.rst +++ b/documentation/api/introduction.rst @@ -148,7 +148,8 @@ A successful response has HTTP status 200: ``auth_token`` is the access token used for ordinary API requests. ``expires-in`` is its lifetime in seconds, reflecting the host's configuration. The example uses the default six hours. A refresh token cannot authenticate an ordinary API request. -If the host has configured access tokens without an expiry, ``expires-in`` is ``null``. +``expires-in`` is rounded down to whole seconds; zero means no whole seconds of +validity remain. Setting ``SECURITY_TOKEN_MAX_AGE`` to zero does not disable expiry. Responses also include FlexMeasures' usual ``status`` field. To replace the access token, send ``POST /api/refreshAuthToken`` with this JSON body: diff --git a/flexmeasures/api/__init__.py b/flexmeasures/api/__init__.py index a320c62d82..e903c4223c 100644 --- a/flexmeasures/api/__init__.py +++ b/flexmeasures/api/__init__.py @@ -70,8 +70,7 @@ def request_auth_token(args) -> tuple[dict, int]: description: Returned only when include-refresh-token is true. expires-in: type: integer - nullable: true - description: Access-token lifetime in seconds (null if unlimited), returned with refresh-token. + description: Access-token lifetime in seconds, returned with refresh-token. 400: description: INVALID_REQUEST 401: diff --git a/flexmeasures/api/refresh_tokens.py b/flexmeasures/api/refresh_tokens.py index ad4e24df95..75b090fe0e 100644 --- a/flexmeasures/api/refresh_tokens.py +++ b/flexmeasures/api/refresh_tokens.py @@ -59,8 +59,7 @@ def refresh_auth_token(args): type: string expires-in: type: integer - nullable: true - description: Access-token lifetime in seconds, or null if unlimited. + description: Access-token lifetime in seconds. 400: description: The JSON in the request body cannot be parsed. 401: diff --git a/flexmeasures/ui/static/openapi-specs.json b/flexmeasures/ui/static/openapi-specs.json index 15f90f603f..ca789e5f5d 100644 --- a/flexmeasures/ui/static/openapi-specs.json +++ b/flexmeasures/ui/static/openapi-specs.json @@ -49,8 +49,7 @@ }, "expires-in": { "type": "integer", - "nullable": true, - "description": "Access-token lifetime in seconds (null if unlimited), returned with refresh-token." + "description": "Access-token lifetime in seconds, returned with refresh-token." } } } @@ -156,8 +155,7 @@ }, "expires-in": { "type": "integer", - "nullable": true, - "description": "Access-token lifetime in seconds, or null if unlimited." + "description": "Access-token lifetime in seconds." } } } From dcb37c967ec4d8650241f43e7da6221f60fc5b41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Fri, 20 Nov 2026 23:40:11 +0100 Subject: [PATCH 12/33] auth: limit and clean up refresh-token families --- flexmeasures/auth/datastore.py | 63 ++++++++++++++++++++++++++- flexmeasures/auth/tokens.py | 22 +++++++++- flexmeasures/utils/config_defaults.py | 1 + flexmeasures/utils/config_utils.py | 16 ++++++- 4 files changed, 97 insertions(+), 5 deletions(-) diff --git a/flexmeasures/auth/datastore.py b/flexmeasures/auth/datastore.py index 55f4397381..f423816334 100644 --- a/flexmeasures/auth/datastore.py +++ b/flexmeasures/auth/datastore.py @@ -1,13 +1,72 @@ -"""Serialize validation and rotation of a refresh-token family.""" +"""Store refresh-token families without loading a user's full tracker collection.""" +from uuid import uuid4 + +from flask import current_app from flask_security import SQLAlchemySessionUserDatastore -from sqlalchemy import select +from sqlalchemy import delete, or_, select from flexmeasures.data.models.refresh_tokens import RefreshTokenTracker from flexmeasures.data.models.user import User class FlexMeasuresUserDatastore(SQLAlchemySessionUserDatastore): + def _delete_refresh_trackers(self, user, *conditions): + """Delete matching trackers for one user and invalidate any loaded collection.""" + self.db.session.execute( + delete(RefreshTokenTracker) + .where(RefreshTokenTracker.user_id == user.id, *conditions) + .execution_options(synchronize_session="fetch") + ) + self.db.session.expire(user, ["refresh_trackers"]) + + def cleanup_refresh_trackers(self, user, expired=True, revoked=False): + """Preserve Flask-Security's cleanup options without hydrating every tracker.""" + self.put(user) + # Flask-Security may call this outside the API; keep the same user-before-family lock order there too. + with self.db.session.no_autoflush: + if user.id is None: + return + self.db.session.scalar( + select(User.id).where(User.id == user.id).with_for_update() + ) + now = current_app.extensions["security"].datetime_factory() + conditions = [] + if expired: + conditions.append(RefreshTokenTracker.expires_at < now) + if revoked: + conditions.append(RefreshTokenTracker.revoked_at.is_not(None)) + if conditions: + self._delete_refresh_trackers(user, or_(*conditions)) + + def cleanup_inactive_api_refresh_trackers(self, user): + """Remove only API families which can no longer be refreshed.""" + now = current_app.extensions["security"].datetime_factory() + idle_before = now - current_app.config["SECURITY_REFRESH_TOKEN_MAX_IDLE"] + self._delete_refresh_trackers( + user, + RefreshTokenTracker.name == "api", + or_( + RefreshTokenTracker.revoked_at.is_not(None), + RefreshTokenTracker.expires_at < now, + RefreshTokenTracker.last_used_at < idle_before, + ), + ) + + def create_refresh_tracker(self, user, name, expires_at, **kwargs): + """Create a tracker without loading the user's other families.""" + tracker = RefreshTokenTracker( + user=user, + gen=1, + name=name, + expires_at=expires_at, + refresh_family=uuid4().hex, + last_used_at=current_app.extensions["security"].datetime_factory(), + **kwargs, + ) + self.put(tracker) + return tracker + def find_refresh_tracker(self, refresh_family: str) -> RefreshTokenTracker | None: user_id = self.db.session.scalar( select(RefreshTokenTracker.user_id).where( diff --git a/flexmeasures/auth/tokens.py b/flexmeasures/auth/tokens.py index 3511fbe9de..754f986b3d 100644 --- a/flexmeasures/auth/tokens.py +++ b/flexmeasures/auth/tokens.py @@ -10,8 +10,10 @@ RefreshTokenErrors, ) from flask_security.signals import refresh_tracker_revoked +from sqlalchemy import func, select from flexmeasures.data import db +from flexmeasures.data.models.refresh_tokens import RefreshTokenTracker def token_response(user, refresh_token: str) -> dict: @@ -35,12 +37,28 @@ def token_response(user, refresh_token: str) -> dict: } -def issue_refresh_token(user) -> dict: +def issue_refresh_token(user) -> tuple[dict, int]: """Caller must hold the user lock and have verified their credentials.""" + datastore = current_app.extensions["security"].datastore + datastore.cleanup_inactive_api_refresh_trackers(user) + active_families = db.session.scalar( + select(func.count(RefreshTokenTracker.id)).where( + RefreshTokenTracker.user_id == user.id, + RefreshTokenTracker.name == "api", + ) + ) + if active_families >= current_app.config["FLEXMEASURES_REFRESH_TOKEN_FAMILY_LIMIT"]: + db.session.commit() + return { + "error": "refresh_token_family_limit", + "errors": [ + "Refresh-token family limit reached. Revoke an unused family before signing in again." + ], + }, 409 _, refresh_token = new_refresh_tracker(user, name="api") payload = token_response(user, refresh_token) db.session.commit() - return payload + return payload, 200 def exchange_refresh_token(token: str, *, revoke: bool = False) -> tuple[dict, int]: diff --git a/flexmeasures/utils/config_defaults.py b/flexmeasures/utils/config_defaults.py index b35291c4eb..64c4092b1a 100644 --- a/flexmeasures/utils/config_defaults.py +++ b/flexmeasures/utils/config_defaults.py @@ -70,6 +70,7 @@ class Config(object): SECURITY_RESET_PASSWORD_TEMPLATE: str = "admin/reset_password.html" SECURITY_TOKEN_AUTHENTICATION_HEADER: str = "Authorization" SECURITY_TOKEN_MAX_AGE: int = 60 * 60 * 6 # six hours + FLEXMEASURES_REFRESH_TOKEN_FAMILY_LIMIT: int = 1000 SECURITY_TRACKABLE: bool = False # this is more in line with modern privacy law SECURITY_PASSWORD_SALT: str | None = None FLEXMEASURES_SECRETS_ENCRYPTION_KEYS: dict[str, str] | None = None diff --git a/flexmeasures/utils/config_utils.py b/flexmeasures/utils/config_utils.py index 0788d8fc1f..726cfd5f77 100644 --- a/flexmeasures/utils/config_utils.py +++ b/flexmeasures/utils/config_utils.py @@ -203,6 +203,7 @@ def read_config(app: Flask, custom_path_to_config: str | None): pin_database_driver(app) normalize_security_durations(app) check_rate_limit_settings(app) + check_refresh_token_family_limit(app) # Check for missing values. # Again, tests and documentation run fine without them. @@ -296,6 +297,7 @@ def read_env_vars(app: Flask): "MAPBOX_ACCESS_TOKEN", "SENTRY_DSN", "FLEXMEASURES_SENTRY_DAILY_RATE_LIMIT", + "FLEXMEASURES_REFRESH_TOKEN_FAMILY_LIMIT", "FLEXMEASURES_PLUGINS", "FLEXMEASURES_JSON_COMPACT", "SECURITY_TWO_FACTOR", @@ -307,7 +309,10 @@ def read_env_vars(app: Flask): continue if isinstance(getattr(DefaultConfig, var, None), bool): value = parse_bool_env(value) - elif var == "FLEXMEASURES_SENTRY_DAILY_RATE_LIMIT": + elif var in ( + "FLEXMEASURES_SENTRY_DAILY_RATE_LIMIT", + "FLEXMEASURES_REFRESH_TOKEN_FAMILY_LIMIT", + ): try: value = int(value) except ValueError: @@ -420,6 +425,15 @@ def normalize_security_durations(app: Flask) -> None: app.config[setting] = parse_duration_setting(setting, value) +def check_refresh_token_family_limit(app: Flask) -> None: + """Reject a refresh-token family limit that is not a positive integer.""" + value = app.config["FLEXMEASURES_REFRESH_TOKEN_FAMILY_LIMIT"] + if isinstance(value, bool) or not isinstance(value, int) or value < 1: + raise ValueError( + "FLEXMEASURES_REFRESH_TOKEN_FAMILY_LIMIT must be a positive integer" + ) + + def check_rate_limit_settings(app: Flask) -> None: """Refuse a server-wide rate limit we cannot make sense of, or one which holds several limits. From abb0df6a407c0dc2ef6738b5ecb72d9f32ca7055 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Fri, 20 Nov 2026 23:40:43 +0100 Subject: [PATCH 13/33] tests: cover refresh-family cleanup and limits --- .../api/tests/test_refresh_tokens_fresh_db.py | 321 +++++++++++++++++- flexmeasures/utils/tests/test_config_utils.py | 39 ++- 2 files changed, 358 insertions(+), 2 deletions(-) diff --git a/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py b/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py index 7ce3d8cc62..3ee514c394 100644 --- a/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py +++ b/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py @@ -2,13 +2,17 @@ from concurrent.futures import ThreadPoolExecutor from datetime import timedelta -from threading import Barrier +from threading import Barrier, Event, local import time +from uuid import uuid4 import pytest from flask import g, url_for +from flask_security.tokens import new_refresh_tracker +from flask_security.utils import hash_password from sqlalchemy import event, select +from flexmeasures.auth import tokens as auth_tokens from flexmeasures.data.models.refresh_tokens import RefreshTokenTracker from flexmeasures.data.models.user import User from flexmeasures.data.services.users import delete_user @@ -294,6 +298,321 @@ def test_independent_login_has_independent_token_family(client, token_user): assert_pair(refresh(client, second["refresh-token"]), token_user.id) +def test_login_cleans_dead_api_families_without_weakening_replay_detection( + app, client, fresh_db, token_user, token_clock +): + """Prune only this user's dead API families and retain live family history.""" + token_clock(0) + first = assert_pair(login(client, include_refresh_token=True), token_user.id) + rotated = assert_pair(refresh(client, first["refresh-token"]), token_user.id) + expired = assert_pair(login(client, include_refresh_token=True), token_user.id) + idle = assert_pair(login(client, include_refresh_token=True), token_user.id) + revoked = assert_pair(login(client, include_refresh_token=True), token_user.id) + security = app.extensions["security"] + + def family(pair): + return security.refresh_token_serializer.loads(pair["refresh-token"])["family"] + + now = security.datetime_factory() + trackers = { + tracker.refresh_family: tracker + for tracker in fresh_db.session.scalars( + select(RefreshTokenTracker).where( + RefreshTokenTracker.user_id == token_user.id + ) + ) + } + trackers[family(expired)].expires_at = now - timedelta(seconds=1) + trackers[family(idle)].last_used_at = ( + now - app.config["SECURITY_REFRESH_TOKEN_MAX_IDLE"] - timedelta(seconds=1) + ) + trackers[family(revoked)].revoked_at = now + other_user = fresh_db.session.scalar( + select(User).where(User.id != token_user.id).limit(1) + ) + other_family = uuid4().hex + browser_family = uuid4().hex + for user_id, name, key in ( + (other_user.id, "api", other_family), + (token_user.id, "browser", browser_family), + ): + fresh_db.session.add( + RefreshTokenTracker( + user_id=user_id, + name=name, + refresh_family=key, + gen=1, + expires_at=now + timedelta(days=1), + last_used_at=now, + revoked_at=now, + ) + ) + fresh_db.session.commit() + + fresh = assert_pair(login(client, include_refresh_token=True), token_user.id) + remaining = set( + fresh_db.session.scalars(select(RefreshTokenTracker.refresh_family)) + ) + assert {family(first), family(fresh), other_family, browser_family} <= remaining + assert not {family(expired), family(idle), family(revoked)} & remaining + for pair in (expired, idle, revoked): + assert refresh(client, pair["refresh-token"]).status_code == 401 + assert refresh(client, first["refresh-token"]).status_code == 401 + assert refresh(client, rotated["refresh-token"]).status_code == 401 + + +def test_family_limit_rejects_new_login_without_revoking_existing_tokens( + app, client, fresh_db, token_user, monkeypatch +): + monkeypatch.setitem(app.config, "FLEXMEASURES_REFRESH_TOKEN_FAMILY_LIMIT", 2) + first = assert_pair(login(client, include_refresh_token=True), token_user.id) + second = assert_pair(login(client, include_refresh_token=True), token_user.id) + now = app.extensions["security"].datetime_factory() + stale = RefreshTokenTracker( + user_id=token_user.id, + name="api", + refresh_family=uuid4().hex, + gen=1, + expires_at=now + timedelta(days=1), + last_used_at=now, + revoked_at=now, + ) + fresh_db.session.add(stale) + fresh_db.session.commit() + stale_id = stale.id + denied = login(client, include_refresh_token=True) + assert denied.status_code == 409 + assert denied.json["error"] == "refresh_token_family_limit" + assert "refresh-token" not in denied.json + assert "no-store" in denied.headers["Cache-Control"] + fresh_db.session.rollback() + assert fresh_db.session.get(RefreshTokenTracker, stale_id) is None + assert len(fresh_db.session.scalars(select(RefreshTokenTracker)).all()) == 2 + assert login(client).status_code == 200 + replacement = assert_pair(refresh(client, first["refresh-token"]), token_user.id) + assert ( + client.post( + "/api/revokeRefreshToken", json={"refresh-token": second["refresh-token"]} + ).status_code + == 200 + ) + assert_pair(login(client, include_refresh_token=True), token_user.id) + assert_pair(refresh(client, replacement["refresh-token"]), token_user.id) + + +def test_family_limit_is_per_user(app, client, token_user, monkeypatch): + monkeypatch.setitem(app.config, "FLEXMEASURES_REFRESH_TOKEN_FAMILY_LIMIT", 1) + assert_pair(login(client, include_refresh_token=True), token_user.id) + other = client.post( + "/api/requestAuthToken", + json={ + "email": "test_prosumer_user@seita.nl", + "password": "testtest", + "include-refresh-token": True, + }, + ) + assert other.status_code == 200 + assert "refresh-token" in other.json + assert login(client, include_refresh_token=True).status_code == 409 + + +@pytest.mark.parametrize("expiry", ["absolute", "idle"]) +def test_cleanup_preserves_family_at_exact_expiry_boundary( + app, client, fresh_db, token_user, token_clock, monkeypatch, expiry +): + token_clock(0) + monkeypatch.setitem(app.config, "FLEXMEASURES_REFRESH_TOKEN_FAMILY_LIMIT", 1) + if expiry == "idle": + monkeypatch.setitem( + app.config, "SECURITY_REFRESH_TOKEN_MAX_IDLE", timedelta(seconds=10) + ) + pair = assert_pair(login(client, include_refresh_token=True), token_user.id) + if expiry == "absolute": + tracker = fresh_db.session.scalar(select(RefreshTokenTracker)) + tracker.expires_at = app.extensions["security"].datetime_factory() + timedelta( + seconds=10 + ) + fresh_db.session.commit() + token_clock(10) + assert login(client, include_refresh_token=True).status_code == 409 + token_clock(11) + assert_pair(login(client, include_refresh_token=True), token_user.id) + assert refresh(client, pair["refresh-token"]).status_code == 401 + + +def test_family_limit_serializes_concurrent_logins( + app, client, fresh_db, token_user, monkeypatch +): + monkeypatch.setitem(app.config, "FLEXMEASURES_REFRESH_TOKEN_FAMILY_LIMIT", 2) + existing = assert_pair(login(client, include_refresh_token=True), token_user.id) + first_inside = Event() + release_first = Event() + second_query = Event() + second_inside = Event() + thread_state = local() + original_create = auth_tokens.new_refresh_tracker + + def paused_create(user, name): + if getattr(thread_state, "second", False): + second_inside.set() + else: + first_inside.set() + assert release_first.wait(timeout=10) + return original_create(user, name) + + def record(conn, cursor, statement, parameters, context, executemany): + if ( + getattr(thread_state, "second", False) + and "FROM fm_user" in statement + and "WHERE fm_user.id" in statement + ): + second_query.set() + + monkeypatch.setattr(auth_tokens, "new_refresh_tracker", paused_create) + + def issue(second=False): + thread_state.second = second + with app.app_context(), app.test_client() as concurrent_client: + response = login(concurrent_client, include_refresh_token=True) + return response.status_code + + event.listen(fresh_db.engine, "before_cursor_execute", record) + try: + with ThreadPoolExecutor(max_workers=2) as executor: + first = executor.submit(issue) + try: + assert first_inside.wait(timeout=10) + second = executor.submit(issue, True) + assert second_query.wait(timeout=10) + assert not second_inside.wait(timeout=1) + finally: + release_first.set() + assert sorted((first.result(timeout=20), second.result(timeout=20))) == [ + 200, + 409, + ] + finally: + event.remove(fresh_db.engine, "before_cursor_execute", record) + assert len(fresh_db.session.scalars(select(RefreshTokenTracker)).all()) == 2 + assert_pair(refresh(client, existing["refresh-token"]), token_user.id) + + +def test_issuing_a_family_does_not_load_the_tracker_collection( + app, client, fresh_db, token_user +): + assert_pair(login(client, include_refresh_token=True), token_user.id) + fresh_db.session.expire_all() + clear_auth() + statements = [] + + def record(conn, cursor, statement, parameters, context, executemany): + statements.append(statement) + + event.listen(fresh_db.engine, "before_cursor_execute", record) + try: + assert_pair(login(client, include_refresh_token=True), token_user.id) + finally: + event.remove(fresh_db.engine, "before_cursor_execute", record) + assert not any( + statement.lstrip().upper().startswith("SELECT") + and "FROM refresh_token_tracker" in statement + and "count(" not in statement.lower() + for statement in statements + ) + + +@pytest.mark.parametrize( + "expired,revoked,expected", + [ + (False, False, {"expired", "revoked"}), + (True, False, {"revoked"}), + (False, True, {"expired"}), + (True, True, set()), + ], +) +def test_flask_security_cleanup_options_are_preserved( + app, fresh_db, token_user, expired, revoked, expected +): + """The optimized datastore still honors Flask-Security's cleanup flags.""" + security = app.extensions["security"] + now = security.datetime_factory() + for family, expires_at, revoked_at in ( + ("expired", now - timedelta(seconds=1), None), + ("revoked", now + timedelta(days=1), now), + ): + fresh_db.session.add( + RefreshTokenTracker( + user_id=token_user.id, + name="default", + refresh_family=family, + gen=1, + expires_at=expires_at, + last_used_at=now, + revoked_at=revoked_at, + ) + ) + fresh_db.session.commit() + security.datastore.cleanup_refresh_trackers( + token_user, expired=expired, revoked=revoked + ) + fresh_db.session.commit() + assert ( + set(fresh_db.session.scalars(select(RefreshTokenTracker.refresh_family))) + == expected + ) + + +def test_flask_security_cleanup_locks_user_before_pending_tracker_write( + app, client, fresh_db, token_user +): + assert_pair(login(client, include_refresh_token=True), token_user.id) + token_user.refresh_trackers[0].name = "modified" + statements = [] + + def record(conn, cursor, statement, parameters, context, executemany): + statements.append(statement) + + event.listen(fresh_db.engine, "before_cursor_execute", record) + try: + app.extensions["security"].datastore.cleanup_refresh_trackers(token_user) + fresh_db.session.commit() + finally: + event.remove(fresh_db.engine, "before_cursor_execute", record) + first_write = next( + i + for i, statement in enumerate(statements) + if statement.startswith(("UPDATE", "DELETE")) + ) + assert any( + "FROM fm_user" in statement and "FOR UPDATE" in statement + for statement in statements[:first_write] + ) + + +@pytest.mark.parametrize("transient", [False, True]) +def test_flask_security_can_issue_a_family_for_a_new_user( + app, fresh_db, token_user, transient +): + """Pending and transient users can still receive a Flask-Security refresh tracker.""" + security = app.extensions["security"] + user = security.datastore.create_user( + email="refresh-new-user@example.com", + username="refresh-new-user", + password=hash_password("testtest"), + account_id=token_user.account_id, + ) + if transient: + fresh_db.session.expunge(user) + tracker, token = new_refresh_tracker(user, name="default") + fresh_db.session.commit() + assert tracker.user_id == user.id + assert ( + security.refresh_token_serializer.loads(token)["family"] + == tracker.refresh_family + ) + assert [item.id for item in user.refresh_trackers] == [tracker.id] + + def test_wrong_password_cannot_obtain_refresh_token(client, fresh_db, token_user): response = login(client, include_refresh_token=True, password="incorrect") assert response.status_code == 401 diff --git a/flexmeasures/utils/tests/test_config_utils.py b/flexmeasures/utils/tests/test_config_utils.py index b1c69fd376..c410dad95a 100644 --- a/flexmeasures/utils/tests/test_config_utils.py +++ b/flexmeasures/utils/tests/test_config_utils.py @@ -6,9 +6,14 @@ from werkzeug.sansio.utils import host_is_trusted from flexmeasures.utils import config_utils -from flexmeasures.utils.config_defaults import DevelopmentConfig, ProductionConfig +from flexmeasures.utils.config_defaults import ( + DevelopmentConfig, + ProductionConfig, + TestingConfig, +) from flexmeasures.utils.config_utils import ( + check_refresh_token_family_limit, check_rate_limit_settings, get_config_warnings, normalize_security_durations, @@ -94,6 +99,38 @@ def test_read_env_vars_parses_sentry_daily_rate_limit(monkeypatch): assert app.config["FLEXMEASURES_SENTRY_DAILY_RATE_LIMIT"] == 100 +def test_read_env_vars_parses_refresh_token_family_limit(monkeypatch): + monkeypatch.setenv("FLEXMEASURES_REFRESH_TOKEN_FAMILY_LIMIT", "25") + app = Flask(__name__) + read_env_vars(app) + assert app.config["FLEXMEASURES_REFRESH_TOKEN_FAMILY_LIMIT"] == 25 + check_refresh_token_family_limit(app) + + +@pytest.mark.parametrize("value", [0, -1, True, None, "many", 1.5]) +def test_refresh_token_family_limit_must_be_a_positive_integer(value): + app = Flask(__name__) + app.config["FLEXMEASURES_REFRESH_TOKEN_FAMILY_LIMIT"] = value + with pytest.raises(ValueError, match="FLEXMEASURES_REFRESH_TOKEN_FAMILY_LIMIT"): + check_refresh_token_family_limit(app) + + +def test_refresh_token_family_limit_default_is_valid(): + app = Flask(__name__) + app.config.from_object(ProductionConfig) + assert app.config["FLEXMEASURES_REFRESH_TOKEN_FAMILY_LIMIT"] == 1000 + check_refresh_token_family_limit(app) + + +def test_invalid_refresh_token_family_limit_is_rejected_at_startup(monkeypatch): + monkeypatch.setattr(TestingConfig, "FLEXMEASURES_REFRESH_TOKEN_FAMILY_LIMIT", 0) + app = Flask(__name__) + app.testing = True + app.config["FLEXMEASURES_ENV"] = "testing" + with pytest.raises(ValueError, match="FLEXMEASURES_REFRESH_TOKEN_FAMILY_LIMIT"): + config_utils.read_config(app, custom_path_to_config=None) + + def test_read_env_vars_reads_trusted_hosts(monkeypatch): monkeypatch.setenv("TRUSTED_HOSTS", "flexmeasures.example.com") app = Flask(__name__) From 1f04c8a3afa6b075698e35225af5d020e9680747 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Fri, 20 Nov 2026 23:41:16 +0100 Subject: [PATCH 14/33] docs: explain refresh-token family limits --- documentation/api/introduction.rst | 12 +++++++++++- documentation/configuration.rst | 13 +++++++++++++ flexmeasures/api/__init__.py | 14 ++++++++++++++ flexmeasures/ui/static/openapi-specs.json | 22 ++++++++++++++++++++++ 4 files changed, 60 insertions(+), 1 deletion(-) diff --git a/documentation/api/introduction.rst b/documentation/api/introduction.rst index db1875054f..997eb590ca 100644 --- a/documentation/api/introduction.rst +++ b/documentation/api/introduction.rst @@ -169,6 +169,14 @@ its newest refresh token. Serialize refresh requests across workers that share c If a refresh response is lost, authenticate again with email and password; blindly retrying the old token may revoke the family. +Store the current refresh token securely and reuse it between runs, rather than creating +a new family on every run. A user can have up to 1,000 active API refresh-token families +by default; hosts can change :ref:`FLEXMEASURES_REFRESH_TOKEN_FAMILY_LIMIT `. +At the limit, an opt-in login returns HTTP 409 with ``error`` set to +``"refresh_token_family_limit"``. Existing families are not revoked and the ordinary +access-token login remains available. Revoke an unused family before creating another; +if the tokens have been lost, wait for their idle expiry or ask the host to adjust the limit. + To stop future refreshes, send ``POST /api/revokeRefreshToken`` with the current refresh token in the same JSON format. It returns HTTP status 200 with ``{"revoked": true}`` and revokes the family. Already issued access tokens remain usable until they expire or @@ -181,7 +189,9 @@ By default, a refresh-token family expires 90 days after its initial login, or a 7 days without a successful refresh, whichever happens first. Rotation does not extend the absolute lifetime. Hosts configure these limits with ``SECURITY_REFRESH_TOKEN_MAX_AGE`` and ``SECURITY_REFRESH_TOKEN_MAX_IDLE``. After expiry or revocation, authenticate again -with email and password. +with email and password. On a new opt-in login, the server removes that user's revoked, +absolutely expired and idle-expired API families before checking the limit. Families that +are still active are retained so that reuse of an older token still revokes the family. These settings take Python ``datetime.timedelta`` values. API refresh support does not require enabling Flask-Security's global ``SECURITY_REFRESH_TOKEN`` flag, which also changes browser authentication. Apply the database migration before running the upgraded server. diff --git a/documentation/configuration.rst b/documentation/configuration.rst index 82347bfcf7..3bf4b0d30d 100644 --- a/documentation/configuration.rst +++ b/documentation/configuration.rst @@ -659,6 +659,19 @@ Maximal age of security tokens in seconds. Default: ``60 * 60 * 6`` (six hours) +.. _refresh_token_family_limit: + +FLEXMEASURES_REFRESH_TOKEN_FAMILY_LIMIT +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Maximum number of active API refresh-token families per user. Each opt-in login creates +one family; rotating its refresh token does not create another. Revoked or expired API +families are removed when that user next opts in. A login at the limit returns HTTP 409 +without revoking existing families. The value must be a positive integer and can also be +set as an environment variable. See :ref:`api_refresh_tokens` for client guidance. + +Default: ``1000`` + SECURITY_TRACKABLE ^^^^^^^^^^^^^^^^^^ diff --git a/flexmeasures/api/__init__.py b/flexmeasures/api/__init__.py index e903c4223c..a3c2b6f5a2 100644 --- a/flexmeasures/api/__init__.py +++ b/flexmeasures/api/__init__.py @@ -75,6 +75,20 @@ def request_auth_token(args) -> tuple[dict, int]: description: INVALID_REQUEST 401: description: UNAUTHORIZED + 409: + description: The user's active API refresh-token family limit has been reached. + content: + application/json: + schema: + type: object + properties: + error: + type: string + example: refresh_token_family_limit + errors: + type: array + items: + type: string tags: - Auth """ diff --git a/flexmeasures/ui/static/openapi-specs.json b/flexmeasures/ui/static/openapi-specs.json index ca789e5f5d..ac36e988e1 100644 --- a/flexmeasures/ui/static/openapi-specs.json +++ b/flexmeasures/ui/static/openapi-specs.json @@ -62,6 +62,28 @@ "401": { "description": "UNAUTHORIZED" }, + "409": { + "description": "The user's active API refresh-token family limit has been reached.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string", + "example": "refresh_token_family_limit" + }, + "errors": { + "type": "array", + "items": { + "type": "string" + } + } + } + } + } + } + }, "429": { "description": "TOO_MANY_REQUESTS - You called the API more often than your rate limit allows. Wait for as long as the Retry-After header says, then try again." } From de0fd3b38e5543d36cd131c10d2b9b2ff8ee40eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Fri, 20 Nov 2026 23:41:38 +0100 Subject: [PATCH 15/33] changelog: mention refresh-token family limits --- documentation/changelog.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/documentation/changelog.rst b/documentation/changelog.rst index f8e88db55b..73cedaa245 100644 --- a/documentation/changelog.rst +++ b/documentation/changelog.rst @@ -13,7 +13,7 @@ New features ------------- * Hosts can be emailed a digest of the automation runs that failed, got stuck or could not be queued, with ``flexmeasures monitor automations``, run from cron; each run is reported once, repeated failures are collapsed per automation, with the new ``FLEXMEASURES_BASE_URL`` setting each automation links to its *Automations* page, hosts can have the admins and consultants of each organisation emailed, too, and admins can switch an automation's monitoring off [see `PR #2671 `_, `PR #2702 `_ and `PR #2703 `_] -* Add opt-in rotating refresh tokens for API clients, with expiry and revocation while preserving existing access-token authentication [see `PR #2849 `_] +* Add opt-in rotating refresh tokens for API clients, with expiry, revocation and a configurable per-user family limit while preserving existing access-token authentication [see `PR #2849 `_] Infrastructure / Support ------------------------- From 939aaaa04e71633ead54a7470bc9a1857719e934 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Fri, 20 Nov 2026 23:43:28 +0100 Subject: [PATCH 16/33] tests: cover invalid refresh-token login option --- flexmeasures/api/tests/test_refresh_tokens_fresh_db.py | 6 ++++++ tests/documentation/test_openapi_spec.py | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py b/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py index 3ee514c394..db57c9a2e3 100644 --- a/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py +++ b/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py @@ -84,6 +84,12 @@ def test_legacy_token_response(client, token_user, options): assert response.status_code == 200 +@pytest.mark.parametrize("value", ["not-a-boolean", None, [], {}]) +def test_login_rejects_invalid_refresh_opt_in(client, token_user, value): + response = login(client, include_refresh_token=value) + assert response.status_code == 422 + + def test_issue_and_rotate_tokens(client, token_user): pair = assert_pair(login(client, include_refresh_token=True), token_user.id) rotated = assert_pair(refresh(client, pair["refresh-token"]), token_user.id) diff --git a/tests/documentation/test_openapi_spec.py b/tests/documentation/test_openapi_spec.py index f51be63bf4..350d277c6d 100644 --- a/tests/documentation/test_openapi_spec.py +++ b/tests/documentation/test_openapi_spec.py @@ -19,6 +19,12 @@ } +def test_openapi_documents_invalid_refresh_opt_in(): + spec = json.loads(OPENAPI_SPEC_PATH.read_text()) + responses = spec["paths"]["/api/requestAuthToken"]["post"]["responses"] + assert "422" in responses + + def _collect_type_values(node, path=""): """Yield (json_path, type_value) for every 'type' key found anywhere in *node*.""" if isinstance(node, dict): From 645dce9270d5c889d9417a03a6288d3aa35fcbb4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Fri, 20 Nov 2026 23:44:10 +0100 Subject: [PATCH 17/33] docs: describe invalid refresh-token login option --- documentation/api/introduction.rst | 5 +++-- flexmeasures/api/__init__.py | 2 ++ flexmeasures/ui/static/openapi-specs.json | 3 +++ 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/documentation/api/introduction.rst b/documentation/api/introduction.rst index 997eb590ca..2a91d20ba8 100644 --- a/documentation/api/introduction.rst +++ b/documentation/api/introduction.rst @@ -196,8 +196,9 @@ These settings take Python ``datetime.timedelta`` values. API refresh support do require enabling Flask-Security's global ``SECURITY_REFRESH_TOKEN`` flag, which also changes browser authentication. Apply the database migration before running the upgraded server. -A request that fails validation, for instance one without a usable ``refresh-token`` field, returns HTTP status 422 with validation errors, -and a JSON body that cannot be parsed returns HTTP status 400. An invalid, expired, +A request that fails validation, for instance a login with an invalid ``include-refresh-token`` +value or a refresh request without a usable ``refresh-token`` field, returns HTTP status 422 +with validation errors. A JSON body that cannot be parsed returns HTTP status 400. An invalid, expired, revoked, or reused refresh token returns HTTP status 401 with ``error`` set to ``"invalid_refresh_token"`` and an ``errors`` list. On that response, authenticate again; do not retry the rejected token. Ordinary API authorization still depends on the user's diff --git a/flexmeasures/api/__init__.py b/flexmeasures/api/__init__.py index a3c2b6f5a2..70c279d2c6 100644 --- a/flexmeasures/api/__init__.py +++ b/flexmeasures/api/__init__.py @@ -89,6 +89,8 @@ def request_auth_token(args) -> tuple[dict, int]: type: array items: type: string + 422: + description: Invalid request fields, such as an invalid include-refresh-token value. tags: - Auth """ diff --git a/flexmeasures/ui/static/openapi-specs.json b/flexmeasures/ui/static/openapi-specs.json index ac36e988e1..942a655eff 100644 --- a/flexmeasures/ui/static/openapi-specs.json +++ b/flexmeasures/ui/static/openapi-specs.json @@ -84,6 +84,9 @@ } } }, + "422": { + "description": "Invalid request fields, such as an invalid include-refresh-token value." + }, "429": { "description": "TOO_MANY_REQUESTS - You called the API more often than your rate limit allows. Wait for as long as the Retry-After header says, then try again." } From b70fda7633520d6cc2642ec12d56c130e1c5c5f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Tue, 24 Nov 2026 11:49:40 +0100 Subject: [PATCH 18/33] run black MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Nicolas Höning --- flexmeasures/api/__init__.py | 4 ++-- flexmeasures/utils/config_utils.py | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/flexmeasures/api/__init__.py b/flexmeasures/api/__init__.py index dd2998fd68..8c227245c2 100644 --- a/flexmeasures/api/__init__.py +++ b/flexmeasures/api/__init__.py @@ -169,7 +169,7 @@ def request_auth_token(args) -> tuple[dict, int]: # Serialize issuance with deactivation/password changes, then verify # credentials again against the locked, up-to-date user record. from flexmeasures.auth.tokens import issue_refresh_token - + user = db.session.scalar( select(User) .where(User.id == user.id) @@ -179,7 +179,7 @@ def request_auth_token(args) -> tuple[dict, int]: if not user or not verify_password(args["password"], user.password): return {"errors": ["User password does not match."]}, 401 return issue_refresh_token(user) - + token = user.get_auth_token() log_authentication_event( f"auth token issued to user {user.id} (by {issued_by})" diff --git a/flexmeasures/utils/config_utils.py b/flexmeasures/utils/config_utils.py index 45c45f2ab5..7c7d2431bb 100644 --- a/flexmeasures/utils/config_utils.py +++ b/flexmeasures/utils/config_utils.py @@ -436,7 +436,8 @@ def check_refresh_token_family_limit(app: Flask) -> None: raise ValueError( "FLEXMEASURES_REFRESH_TOKEN_FAMILY_LIMIT must be a positive integer" ) - + + COOKIE_SECURITY_SETTINGS = ("SESSION_COOKIE_SECURE", "REMEMBER_COOKIE_SECURE") From f09ab43d4093a3b27a2c75ffcc97805f450a42bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Sun, 6 Dec 2026 02:10:56 +0100 Subject: [PATCH 19/33] migrations: merge refresh-token and automation heads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Nicolas Höning --- ...erge_refresh_token_and_automation_heads.py | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 flexmeasures/data/migrations/versions/e949b5dbfdf6_merge_refresh_token_and_automation_heads.py diff --git a/flexmeasures/data/migrations/versions/e949b5dbfdf6_merge_refresh_token_and_automation_heads.py b/flexmeasures/data/migrations/versions/e949b5dbfdf6_merge_refresh_token_and_automation_heads.py new file mode 100644 index 0000000000..9640319b6f --- /dev/null +++ b/flexmeasures/data/migrations/versions/e949b5dbfdf6_merge_refresh_token_and_automation_heads.py @@ -0,0 +1,21 @@ +"""merge refresh token and automation heads + +Revision ID: e949b5dbfdf6 +Revises: c8d4193f27a6, d5b8f3a1c962 +Create Date: 2026-12-06 02:10:09.896175 + +""" + +# revision identifiers, used by Alembic. +revision = "e949b5dbfdf6" +down_revision = ("c8d4193f27a6", "d5b8f3a1c962") +branch_labels = None +depends_on = None + + +def upgrade(): + pass + + +def downgrade(): + pass From 7c729d78f4be2e0411507efe9209375b8c75231d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Sun, 6 Dec 2026 02:12:22 +0100 Subject: [PATCH 20/33] api: require an active user under the refresh issuance lock MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Nicolas Höning --- flexmeasures/api/__init__.py | 2 ++ .../api/tests/test_refresh_tokens_fresh_db.py | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/flexmeasures/api/__init__.py b/flexmeasures/api/__init__.py index 7f402946a7..6f3fb2ed02 100644 --- a/flexmeasures/api/__init__.py +++ b/flexmeasures/api/__init__.py @@ -63,6 +63,8 @@ def _issue_api_token( ) if not user or not verify_password(password, user.password): return {"errors": ["User password does not match."]}, 401 + if not user.active: + return {"errors": ["This user is deactivated."]}, 401 return issue_refresh_token(user) token = user.get_auth_token() diff --git a/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py b/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py index db57c9a2e3..99a931a4c6 100644 --- a/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py +++ b/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py @@ -3,6 +3,8 @@ from concurrent.futures import ThreadPoolExecutor from datetime import timedelta from threading import Barrier, Event, local +from types import SimpleNamespace +from unittest.mock import Mock import time from uuid import uuid4 @@ -12,6 +14,7 @@ from flask_security.utils import hash_password from sqlalchemy import event, select +from flexmeasures.api import _issue_api_token from flexmeasures.auth import tokens as auth_tokens from flexmeasures.data.models.refresh_tokens import RefreshTokenTracker from flexmeasures.data.models.user import User @@ -103,6 +106,21 @@ def test_issue_and_rotate_tokens(client, token_user): ) +def test_refresh_issuance_requires_an_active_locked_user( + fresh_db, token_user, monkeypatch +): + inactive_user = SimpleNamespace(active=False, password=token_user.password) + monkeypatch.setattr(fresh_db.session, "scalar", lambda query: inactive_user) + issue_refresh_token = Mock(return_value=({}, 200)) + monkeypatch.setattr(auth_tokens, "issue_refresh_token", issue_refresh_token) + + payload, status = _issue_api_token(token_user, "testtest", True, "password") + + assert status == 401 + assert payload == {"errors": ["This user is deactivated."]} + issue_refresh_token.assert_not_called() + + def test_refresh_token_cannot_authenticate_api_request(client, token_user): pair = assert_pair(login(client, include_refresh_token=True), token_user.id) clear_auth() From 37c7035703040a8de0bd99a499a530332aace48a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Sun, 6 Dec 2026 02:12:30 +0100 Subject: [PATCH 21/33] tests: require the password for both session token modes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Nicolas Höning --- .../api/tests/test_refresh_tokens_fresh_db.py | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py b/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py index 99a931a4c6..0360cf4823 100644 --- a/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py +++ b/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py @@ -763,15 +763,23 @@ def test_revocation_at_same_instant(client, token_user, token_clock): assert refresh(client, pair["refresh-token"]).status_code == 401 -def test_session_cannot_replace_password_for_refresh_issuance(client, token_user): +@pytest.mark.parametrize("include_refresh_token", [False, True]) +def test_session_cannot_replace_password_for_token_issuance( + client, token_user, include_refresh_token +): with client.session_transaction() as session: session["_user_id"] = token_user.get_id() session["_fresh"] = True clear_auth() - # Preserve the existing signed-in access-token flow, but require the password - # before issuing a new long-lived refresh credential. - assert login(client, password="incorrect").status_code == 200 - clear_auth() - response = login(client, password="incorrect", include_refresh_token=True) + response = login( + client, password="incorrect", include_refresh_token=include_refresh_token + ) assert response.status_code == 401 + assert "auth_token" not in response.json assert "refresh-token" not in response.json + + clear_auth() + response = login(client, include_refresh_token=include_refresh_token) + assert response.status_code == 200 + assert "auth_token" in response.json + assert ("refresh-token" in response.json) == include_refresh_token From eb643c0dfa037134501832362ce6d714b7334fb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Sun, 6 Dec 2026 02:12:36 +0100 Subject: [PATCH 22/33] api: verify the password once before token issuance MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Nicolas Höning --- flexmeasures/api/__init__.py | 58 ++++++++++++++++++------------------ 1 file changed, 29 insertions(+), 29 deletions(-) diff --git a/flexmeasures/api/__init__.py b/flexmeasures/api/__init__.py index 6f3fb2ed02..917db84ab9 100644 --- a/flexmeasures/api/__init__.py +++ b/flexmeasures/api/__init__.py @@ -150,14 +150,11 @@ def request_auth_token(args) -> tuple[dict, int]: if "password" not in request.json: return {"errors": ["Please provide the 'password' parameter."]}, 400 - email = request.json["email"] + email = args["email"] + password = args["password"] if current_user.is_authenticated and current_user.email == email: user = current_user issued_by = "session" - # A session alone does not get a token: that would turn a copied session cookie into a portable credential - if not verify_password(request.json["password"], user.password): - user.track_failed_authn("password") - return {"errors": ["User password does not match."]}, 401 else: issued_by = "password" user = db.session.execute( @@ -165,35 +162,38 @@ def request_auth_token(args) -> tuple[dict, int]: ).scalar_one_or_none() if not user: log_authentication_event( - f"token requested for an unknown email address (hash {email_fingerprint(str(email))})", + f"token requested for an unknown email address (hash {email_fingerprint(email)})", failed=True, ) - # Answer as for a wrong password, and take as long, so the answer does not tell which email addresses have an account - hash_password(str(request.json["password"])) - return {"errors": ["User password does not match."]}, 401 - if not verify_password(request.json["password"], user.password): - # Counts against the user's failed attempts, and is logged, through Flask-Security's user_failed_authn signal - # (see flexmeasures.auth.login_throttling and flexmeasures.auth.event_logging) - user.track_failed_authn("password") + # Take as long as a wrong password so the response does not reveal which email addresses have a user. + hash_password(password) return {"errors": ["User password does not match."]}, 401 - if _requires_second_factor(user) and not current_app.config.get( + + # A session alone does not get a token: that would turn a copied session cookie into a portable credential. + if not verify_password(password, user.password): + # The user_failed_authn signal records the failed attempt in the authentication log. + user.track_failed_authn("password") + return {"errors": ["User password does not match."]}, 401 + + if ( + issued_by == "password" + and _requires_second_factor(user) + and not current_app.config.get( "FLEXMEASURES_ALLOW_PASSWORD_TOKENS_WITH_2FA", False - ): - return ( - { - "errors": [ - "This user logs in with two-factor authentication, so a password alone cannot get a token." - " Log in (with your second factor) and request a token from that session." - ] - }, - 401, - ) - if "password" not in request.json: - return {"errors": ["Please provide the 'password' parameter."]}, 400 - if not verify_password(request.json["password"], user.password): - return {"errors": ["User password does not match."]}, 401 + ) + ): + return ( + { + "errors": [ + "This user logs in with two-factor authentication, so a password alone cannot get a token." + " Log in (with your second factor) and request a token from that session." + ] + }, + 401, + ) + return _issue_api_token( - user, args["password"], args["include-refresh-token"], issued_by + user, password, args["include-refresh-token"], issued_by ) except SQLAlchemyError as e: db.session.rollback() From 2bae92cb283db7257fe7c84c80df1b315e2df779 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Sun, 6 Dec 2026 02:13:50 +0100 Subject: [PATCH 23/33] auth: clear failure counts for verified family-limit conflicts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Nicolas Höning --- flexmeasures/auth/login_throttling.py | 19 +++++++---- .../auth/tests/test_login_throttling.py | 32 ++++++++++++++++++- 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/flexmeasures/auth/login_throttling.py b/flexmeasures/auth/login_throttling.py index 123594a9ac..b9e855c1f7 100644 --- a/flexmeasures/auth/login_throttling.py +++ b/flexmeasures/auth/login_throttling.py @@ -218,12 +218,19 @@ def clear_failed_authentications(sender, user=None, **kwargs): def clear_after_issuing_a_token(response): - """Start the counts afresh once a token was issued (the token endpoint does not log the user in).""" - if ( - request.method == "POST" - and request.endpoint == TOKEN_ENDPOINT - and response.status_code == 200 - ): + """Clear failures once the token request's credentials have been verified.""" + if request.method != "POST" or request.endpoint != TOKEN_ENDPOINT: + return response + + credentials_verified = response.status_code == 200 + if response.status_code == 409: + # A family-limit conflict can only occur after the password was verified. + payload = response.get_json(silent=True) + credentials_verified = ( + isinstance(payload, dict) + and payload.get("error") == "refresh_token_family_limit" + ) + if credentials_verified: _clear(_submitted_email()) return response diff --git a/flexmeasures/auth/tests/test_login_throttling.py b/flexmeasures/auth/tests/test_login_throttling.py index 0cbff02c12..ef18faeab2 100644 --- a/flexmeasures/auth/tests/test_login_throttling.py +++ b/flexmeasures/auth/tests/test_login_throttling.py @@ -1,11 +1,14 @@ """Failed attempts to authenticate are limited per email address (and client address), and password recovery requests per email address.""" +from unittest.mock import Mock + import pytest -from flask import Flask, request, session, url_for +from flask import Flask, jsonify, request, session, url_for from flask_login import logout_user from sqlalchemy import select from flexmeasures.api.common.rate_limiting import limiter +from flexmeasures.auth import login_throttling from flexmeasures.data.models.user import User EMAIL = "test_prosumer_user@seita.nl" @@ -206,6 +209,33 @@ def test_successful_token_requests_are_not_held_against_the_user( assert response.status_code == 200 and "auth_token" in response.json +@pytest.mark.parametrize( + "status, payload, clears_failures", + [ + (200, {}, True), + (409, {"error": "refresh_token_family_limit"}, True), + (409, {"error": "other_conflict"}, False), + (401, {"errors": ["User password does not match."]}, False), + ], +) +def test_token_response_clears_only_verified_attempts( + app, monkeypatch, status, payload, clears_failures +): + clear = Mock() + monkeypatch.setattr(login_throttling, "_clear", clear) + with app.test_request_context( + "/api/requestAuthToken", method="POST", json={"email": EMAIL} + ): + response = jsonify(payload) + response.status_code = status + assert login_throttling.clear_after_issuing_a_token(response) is response + + if clears_failures: + clear.assert_called_once_with(EMAIL) + else: + clear.assert_not_called() + + def test_concurrent_attempts_cannot_exceed_the_limit( app, client, setup_roles_users, low_limits, monkeypatch ): From c38ab42098e24aa8cb96df861bea339db3f6e009 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Sun, 6 Dec 2026 02:13:59 +0100 Subject: [PATCH 24/33] api: log successful opt-in token issuance MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Nicolas Höning --- flexmeasures/api/__init__.py | 7 ++++++- .../api/tests/test_refresh_tokens_fresh_db.py | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/flexmeasures/api/__init__.py b/flexmeasures/api/__init__.py index 917db84ab9..5a5b9a034d 100644 --- a/flexmeasures/api/__init__.py +++ b/flexmeasures/api/__init__.py @@ -65,7 +65,12 @@ def _issue_api_token( return {"errors": ["User password does not match."]}, 401 if not user.active: return {"errors": ["This user is deactivated."]}, 401 - return issue_refresh_token(user) + payload, status = issue_refresh_token(user) + if status == 200: + log_authentication_event( + f"access and refresh tokens issued to user {payload['user_id']} (by {issued_by})" + ) + return payload, status token = user.get_auth_token() log_authentication_event(f"auth token issued to user {user.id} (by {issued_by})") diff --git a/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py b/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py index 0360cf4823..6697516c6c 100644 --- a/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py +++ b/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py @@ -2,6 +2,7 @@ from concurrent.futures import ThreadPoolExecutor from datetime import timedelta +import logging from threading import Barrier, Event, local from types import SimpleNamespace from unittest.mock import Mock @@ -106,6 +107,23 @@ def test_issue_and_rotate_tokens(client, token_user): ) +def test_successful_refresh_token_issuance_is_logged( + app, client, token_user, monkeypatch, caplog +): + monkeypatch.setitem(app.config, "FLEXMEASURES_REFRESH_TOKEN_FAMILY_LIMIT", 1) + caplog.set_level(logging.INFO, logger=app.logger.name) + event = f"access and refresh tokens issued to user {token_user.id} (by password)" + + pair = assert_pair(login(client, include_refresh_token=True), token_user.id) + assert sum(event in message for message in caplog.messages) == 1 + assert pair["refresh-token"] not in caplog.text + assert pair["auth_token"] not in caplog.text + + caplog.clear() + assert login(client, include_refresh_token=True).status_code == 409 + assert all(event not in message for message in caplog.messages) + + def test_refresh_issuance_requires_an_active_locked_user( fresh_db, token_user, monkeypatch ): From 37e11a5ebf612b9cddc9ac3d2e5dadfb158fda7b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Sun, 6 Dec 2026 02:14:05 +0100 Subject: [PATCH 25/33] auth: explain how to proceed at the refresh family limit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Nicolas Höning --- flexmeasures/auth/tokens.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/flexmeasures/auth/tokens.py b/flexmeasures/auth/tokens.py index 754f986b3d..aec68d7948 100644 --- a/flexmeasures/auth/tokens.py +++ b/flexmeasures/auth/tokens.py @@ -52,7 +52,8 @@ def issue_refresh_token(user) -> tuple[dict, int]: return { "error": "refresh_token_family_limit", "errors": [ - "Refresh-token family limit reached. Revoke an unused family before signing in again." + "Refresh-token family limit reached. Request an access token without " + "include-refresh-token, or wait for an unused family to expire after inactivity." ], }, 409 _, refresh_token = new_refresh_tracker(user, name="api") From 3669bcd4844445c0b42ccec238680e12de53b7ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Sun, 6 Dec 2026 02:14:14 +0100 Subject: [PATCH 26/33] tests: count API refresh families independently of browser families MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Nicolas Höning --- .../api/tests/test_refresh_tokens_fresh_db.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py b/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py index 6697516c6c..0475d03f0b 100644 --- a/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py +++ b/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py @@ -458,6 +458,19 @@ def test_family_limit_is_per_user(app, client, token_user, monkeypatch): assert login(client, include_refresh_token=True).status_code == 409 +def test_family_limit_counts_only_api_families( + app, client, fresh_db, token_user, monkeypatch +): + monkeypatch.setitem(app.config, "FLEXMEASURES_REFRESH_TOKEN_FAMILY_LIMIT", 1) + browser_family, _ = new_refresh_tracker(token_user, name="browser") + fresh_db.session.commit() + browser_family_id = browser_family.id + + assert_pair(login(client, include_refresh_token=True), token_user.id) + assert login(client, include_refresh_token=True).status_code == 409 + assert fresh_db.session.get(RefreshTokenTracker, browser_family_id) is not None + + @pytest.mark.parametrize("expiry", ["absolute", "idle"]) def test_cleanup_preserves_family_at_exact_expiry_boundary( app, client, fresh_db, token_user, token_clock, monkeypatch, expiry From d10c8e59ae0c3f693fc1f2f293eb3ca7fcb8aad9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Sun, 6 Dec 2026 02:15:00 +0100 Subject: [PATCH 27/33] docs: restore the session cookie configuration heading MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Nicolas Höning --- documentation/configuration.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/documentation/configuration.rst b/documentation/configuration.rst index b6dd90d7ef..9cc1211da7 100644 --- a/documentation/configuration.rst +++ b/documentation/configuration.rst @@ -707,6 +707,7 @@ without revoking existing families. The value must be a positive integer and can set as an environment variable. See :ref:`api_refresh_tokens` for client guidance. Default: ``1000`` + SESSION_COOKIE_SECURE, SESSION_COOKIE_SAMESITE, REMEMBER_COOKIE_SECURE, REMEMBER_COOKIE_SAMESITE, REMEMBER_COOKIE_DURATION ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ From ee386f80bc58afcc05b010743948b86e4d619c29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Sun, 6 Dec 2026 02:15:06 +0100 Subject: [PATCH 28/33] docs: record refresh-token issuance, rotation and revocation in the API changelog MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Nicolas Höning --- documentation/api/change_log.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/documentation/api/change_log.rst b/documentation/api/change_log.rst index 8f3febf8c5..00b9bc9143 100644 --- a/documentation/api/change_log.rst +++ b/documentation/api/change_log.rst @@ -8,6 +8,8 @@ API change log v3.0-38 | December xx, 2026 """""""""""""""""""""""""""" +- ``POST /api/requestAuthToken`` accepts ``include-refresh-token`` to return a rotating refresh token and the access token's remaining lifetime in seconds. Use ``POST /api/refreshAuthToken`` to rotate the refresh token and issue a new access token, and ``POST /api/revokeRefreshToken`` to revoke its family. An opt-in request returns ``409`` with ``refresh_token_family_limit`` when the user's active API refresh-token families reach the configured limit. See :ref:`api_refresh_tokens`. + - A storage flex-model without ``soc-min`` gets a lower bound of 0 again, as it did before FlexMeasures v1.0.0. - Fixed: when a sequential schedule (triggered with ``"sequential": true`` on `/assets/(id)/schedules/trigger <../api/v3_0.html#post--api-v3_0-assets-id-schedules-trigger>`_ (POST)) cannot schedule one of its devices, and the scheduler defines no fallback scheduler, the job whose id was returned now reaches a terminal failed state, rather than staying deferred indefinitely. ``GET /api/v3_0/jobs/`` answers such a job with ``422 Unprocessable Entity``, a ``FAILED`` status and a ``message`` naming the device that could not be scheduled, the devices that were consequently not scheduled either, and the devices that were scheduled before it; ``GET /sensors//schedules/`` answers with ``UNKNOWN_SCHEDULE`` and the same reason. - ``POST /api/v3_0/sensors`` and ``PATCH /api/v3_0/sensors/`` validate the sensor attribute ``cell-method`` (``sum``, ``mean``, ``maximum``, ``minimum`` or ``point``), and refuse misspellings of its name such as ``cell_method``. ``POST /api/v3_0/sensors/data`` resamples by ``cell-method`` in any unit: ``sum`` is split and summed, ``mean`` repeated and averaged, ``maximum`` and ``minimum`` repeated and aggregated by maximum or minimum, and ``point`` repeated, keeping the last value per interval. From e866f1787fdaeff5390b1052294ff9a801f47991 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Sun, 6 Dec 2026 02:15:12 +0100 Subject: [PATCH 29/33] auth: keep refresh-token comment sentences together MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Nicolas Höning --- flexmeasures/api/__init__.py | 4 ++-- flexmeasures/auth/__init__.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/flexmeasures/api/__init__.py b/flexmeasures/api/__init__.py index 5a5b9a034d..885c0791fa 100644 --- a/flexmeasures/api/__init__.py +++ b/flexmeasures/api/__init__.py @@ -51,8 +51,8 @@ def _issue_api_token( # Flask-Security would refuse the token anyway; do not issue it return {"errors": ["This user is deactivated."]}, 401 if include_refresh_token: - # Serialize issuance with deactivation/password changes, then verify - # credentials again against the locked, up-to-date user record. + # Lock the user row to serialize issuance with deactivation and password changes. + # Recheck the credentials using the locked, up-to-date record. from flexmeasures.auth.tokens import issue_refresh_token user = db.session.scalar( diff --git a/flexmeasures/auth/__init__.py b/flexmeasures/auth/__init__.py index dbf4d9edb9..63868994b4 100644 --- a/flexmeasures/auth/__init__.py +++ b/flexmeasures/auth/__init__.py @@ -49,8 +49,8 @@ def register_at(app: Flask): db.session, User, Role, refresh_tracker_model=RefreshTokenTracker ) # API token issuance opts in explicitly and uses the tracker helpers directly. - # Keep Flask-Security's global REFRESH_TOKEN flag at its default: enabling it - # also changes browser login/logout and exposes its own refresh endpoint. + # Leave Flask-Security's global REFRESH_TOKEN flag at its default. + # Enabling it would change browser login and logout and expose Flask-Security's own refresh endpoint. app.security = Security( app, user_datastore, From cb59e6baff31561ba0e9ed353265e04f266c4a93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Sun, 6 Dec 2026 23:18:21 +0100 Subject: [PATCH 30/33] tests: verify refresh issuance reloads the locked user MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Nicolas Höning --- .../api/tests/test_refresh_tokens_fresh_db.py | 42 +++++++++++++++---- 1 file changed, 34 insertions(+), 8 deletions(-) diff --git a/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py b/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py index 0475d03f0b..83e0f463e1 100644 --- a/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py +++ b/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py @@ -4,7 +4,6 @@ from datetime import timedelta import logging from threading import Barrier, Event, local -from types import SimpleNamespace from unittest.mock import Mock import time from uuid import uuid4 @@ -14,6 +13,7 @@ from flask_security.tokens import new_refresh_tracker from flask_security.utils import hash_password from sqlalchemy import event, select +from sqlalchemy.orm.attributes import set_committed_value from flexmeasures.api import _issue_api_token from flexmeasures.auth import tokens as auth_tokens @@ -124,18 +124,44 @@ def test_successful_refresh_token_issuance_is_logged( assert all(event not in message for message in caplog.messages) -def test_refresh_issuance_requires_an_active_locked_user( - fresh_db, token_user, monkeypatch +@pytest.mark.parametrize( + "changed_field, expected_error", + [ + ("active", "This user is deactivated."), + ("password", "User password does not match."), + ], +) +def test_refresh_issuance_checks_the_current_locked_user( + fresh_db, token_user, monkeypatch, changed_field, expected_error ): - inactive_user = SimpleNamespace(active=False, password=token_user.password) - monkeypatch.setattr(fresh_db.session, "scalar", lambda query: inactive_user) - issue_refresh_token = Mock(return_value=({}, 200)) + previous_value = getattr(token_user, changed_field) + current_value = ( + False if changed_field == "active" else hash_password("new test password") + ) + setattr(token_user, changed_field, current_value) + fresh_db.session.commit() + fresh_db.session.refresh(token_user) + + # Seed a stale value in the identity map without writing it to PostgreSQL. + set_committed_value(token_user, changed_field, previous_value) + issue_refresh_token = Mock(side_effect=AssertionError("Unexpected token issuance")) monkeypatch.setattr(auth_tokens, "issue_refresh_token", issue_refresh_token) + locked_reads = [] + + def observe_user_lock(conn, cursor, statement, parameters, context, executemany): + if "FROM fm_user" in statement and "FOR UPDATE" in statement: + locked_reads.append(statement) - payload, status = _issue_api_token(token_user, "testtest", True, "password") + connection = fresh_db.session.connection() + event.listen(connection, "before_cursor_execute", observe_user_lock) + try: + payload, status = _issue_api_token(token_user, "testtest", True, "password") + finally: + event.remove(connection, "before_cursor_execute", observe_user_lock) + assert len(locked_reads) == 1 assert status == 401 - assert payload == {"errors": ["This user is deactivated."]} + assert payload == {"errors": [expected_error]} issue_refresh_token.assert_not_called() From 9d4c857614e9858a126fc66cf520feb32f7d4ae8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Sun, 6 Dec 2026 23:18:37 +0100 Subject: [PATCH 31/33] tests: cover token requests from signed-in two-factor users MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Nicolas Höning --- .../api/tests/test_refresh_tokens_fresh_db.py | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py b/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py index 83e0f463e1..9378debd54 100644 --- a/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py +++ b/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py @@ -840,3 +840,27 @@ def test_session_cannot_replace_password_for_token_issuance( assert response.status_code == 200 assert "auth_token" in response.json assert ("refresh-token" in response.json) == include_refresh_token + + +@pytest.mark.parametrize("include_refresh_token", [False, True]) +def test_two_factor_user_can_request_tokens_from_a_signed_in_session( + app, client, token_user, monkeypatch, include_refresh_token +): + monkeypatch.setitem(app.config, "SECURITY_TWO_FACTOR", True) + monkeypatch.setitem( + app.config, "FLEXMEASURES_ALLOW_PASSWORD_TOKENS_WITH_2FA", False + ) + assert token_user.tf_primary_method + assert token_user.tf_totp_secret + + # Represent a browser session after the second factor has been completed. + with client.session_transaction() as session: + session["_user_id"] = token_user.get_id() + session["_fresh"] = True + clear_auth() + + response = login(client, include_refresh_token=include_refresh_token) + assert response.status_code == 200, response.json + assert response.json["user_id"] == token_user.id + assert response.json["auth_token"] + assert ("refresh-token" in response.json) == include_refresh_token From f6f6c0e9cc2dbee567529af7178b20f0db395d7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Sun, 6 Dec 2026 23:19:38 +0100 Subject: [PATCH 32/33] docs: document the refresh-token migration and reflow token text MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Nicolas Höning --- documentation/changelog.rst | 1 + flexmeasures/api/refresh_tokens.py | 5 +++-- flexmeasures/auth/tokens.py | 4 ++-- flexmeasures/data/models/refresh_tokens.py | 4 ++-- flexmeasures/data/schemas/tests/test_field_naming.py | 7 +++---- flexmeasures/ui/static/openapi-specs.json | 2 +- 6 files changed, 12 insertions(+), 11 deletions(-) diff --git a/documentation/changelog.rst b/documentation/changelog.rst index d895d945ea..6cf3ba4d1b 100644 --- a/documentation/changelog.rst +++ b/documentation/changelog.rst @@ -12,6 +12,7 @@ v1.2.0 | December xx, 2026 .. warning:: Upgrading to this version requires running ``flexmeasures db upgrade`` (you can create a backup first with ``flexmeasures db-ops dump``). The migrations add automation dependencies, rename the automation's ``schedule_revision`` to ``revision``, flag automations as critical or not monitored, and record runs started on demand, when each automation's recurrence started, and when a failed run was reported by ``flexmeasures monitor automations``. + They also create the ``refresh_token_tracker`` table for API refresh-token families. New features ------------- diff --git a/flexmeasures/api/refresh_tokens.py b/flexmeasures/api/refresh_tokens.py index 75b090fe0e..8e602d2712 100644 --- a/flexmeasures/api/refresh_tokens.py +++ b/flexmeasures/api/refresh_tokens.py @@ -31,8 +31,9 @@ def refresh_auth_token(args): post: summary: Rotate a refresh token and obtain a new access token. description: | - No access token or password is required. Save the returned refresh token - atomically and serialize refresh requests. Reuse revokes the token family. + No access token or password is required. + Save the returned refresh token atomically and serialize refresh requests. + Reuse revokes the token family. requestBody: required: true content: diff --git a/flexmeasures/auth/tokens.py b/flexmeasures/auth/tokens.py index aec68d7948..8ecc1bed6c 100644 --- a/flexmeasures/auth/tokens.py +++ b/flexmeasures/auth/tokens.py @@ -67,8 +67,8 @@ def exchange_refresh_token(token: str, *, revoke: bool = False) -> tuple[dict, i security = current_app.extensions["security"] datastore = security.datastore tracker, error, uid = verify_refresh_token(token) - # Revocation is immediate. Upstream compares revoked_at < now, which permits - # reuse at the same clock instant (or when worker clocks differ slightly). + # Treat a family as revoked as soon as revoked_at is set. + # The upstream time comparison can miss revocation at the same instant or on a worker with a slower clock. if tracker is not None and tracker.revoked_at is not None: error = RefreshTokenErrors.REVOKED user = ( diff --git a/flexmeasures/data/models/refresh_tokens.py b/flexmeasures/data/models/refresh_tokens.py index 2ba4f94431..26ce04b099 100644 --- a/flexmeasures/data/models/refresh_tokens.py +++ b/flexmeasures/data/models/refresh_tokens.py @@ -40,8 +40,8 @@ class RefreshTokenTracker(db.Model, RefreshTrackerMixin): @event.listens_for(User, "after_update") def revoke_refresh_tokens_on_identity_change(mapper, connection, user): """Do not revive refresh access when a disabled user is reactivated.""" - # The user UPDATE already holds the user-row lock. Token endpoints acquire - # this same lock before touching families, so issuance cannot race this sweep. + # The user UPDATE already holds the user-row lock. + # Token endpoints also lock the user row before touching families, which serializes issuance with this sweep. state = inspect(user) disabled = state.attrs.active.history.has_changes() and not user.active credentials_changed = any( diff --git a/flexmeasures/data/schemas/tests/test_field_naming.py b/flexmeasures/data/schemas/tests/test_field_naming.py index 196e879db1..f5031af16e 100644 --- a/flexmeasures/data/schemas/tests/test_field_naming.py +++ b/flexmeasures/data/schemas/tests/test_field_naming.py @@ -112,10 +112,9 @@ } ) -# requestAuthToken has always returned these keys; its old OpenAPI description -# incorrectly called the token authentication_token and omitted user_id. Keep -# the real legacy response contract (also used by refreshAuthToken), without -# allowing these spellings on new domain APIs or expanding the global debt list. +# requestAuthToken has always returned these keys. +# Its old OpenAPI description incorrectly called the token authentication_token and omitted user_id. +# Scope these exceptions to the token endpoints that use the legacy response fields. LEGACY_AUTH_RESPONSE_FIELDS = { "auth_token": {"/api/requestAuthToken", "/api/refreshAuthToken"}, "user_id": {"/api/requestAuthToken", "/api/refreshAuthToken"}, diff --git a/flexmeasures/ui/static/openapi-specs.json b/flexmeasures/ui/static/openapi-specs.json index 0eb282fd14..91e33081e3 100644 --- a/flexmeasures/ui/static/openapi-specs.json +++ b/flexmeasures/ui/static/openapi-specs.json @@ -143,7 +143,7 @@ "/api/refreshAuthToken": { "post": { "summary": "Rotate a refresh token and obtain a new access token.", - "description": "No access token or password is required. Save the returned refresh token\natomically and serialize refresh requests. Reuse revokes the token family.\n", + "description": "No access token or password is required.\nSave the returned refresh token atomically and serialize refresh requests.\nReuse revokes the token family.\n", "requestBody": { "required": true, "content": { From 25b01c524f52a63b4bd9b50c9db27f51d46061b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20H=C3=B6ning?= Date: Sun, 6 Dec 2026 23:19:55 +0100 Subject: [PATCH 33/33] auth: audit refresh-token rotation and reuse revocation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Nicolas Höning --- .../api/tests/test_refresh_tokens_fresh_db.py | 20 ++++++++++++++++--- flexmeasures/auth/tokens.py | 12 +++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py b/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py index 9378debd54..dd18b46df7 100644 --- a/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py +++ b/flexmeasures/api/tests/test_refresh_tokens_fresh_db.py @@ -181,12 +181,26 @@ def test_access_token_cannot_be_refreshed(client, token_user): assert refresh(client, pair["auth_token"]).status_code == 401 -def test_reuse_revokes_rotated_token_family(client, token_user): - pair = assert_pair(login(client, include_refresh_token=True), token_user.id) - rotated = assert_pair(refresh(client, pair["refresh-token"]), token_user.id) +def test_reuse_revokes_rotated_token_family(app, client, token_user, caplog): + caplog.set_level(logging.INFO, logger=app.logger.name) + user_id = token_user.id + pair = assert_pair(login(client, include_refresh_token=True), user_id) + rotated = assert_pair(refresh(client, pair["refresh-token"]), user_id) assert refresh(client, pair["refresh-token"]).status_code == 401 assert refresh(client, rotated["refresh-token"]).status_code == 401 + rotation = f"refresh token rotated for user {user_id}" + reuse = f"refresh token reuse revoked a family for user {user_id}" + assert [r.levelno for r in caplog.records if rotation in r.getMessage()] == [ + logging.INFO + ] + assert [r.levelno for r in caplog.records if reuse in r.getMessage()] == [ + logging.WARNING + ] + for tokens in (pair, rotated): + assert tokens["auth_token"] not in caplog.text + assert tokens["refresh-token"] not in caplog.text + def test_revoke_refresh_token(client, token_user): pair = assert_pair(login(client, include_refresh_token=True), token_user.id) diff --git a/flexmeasures/auth/tokens.py b/flexmeasures/auth/tokens.py index 8ecc1bed6c..e8af085a17 100644 --- a/flexmeasures/auth/tokens.py +++ b/flexmeasures/auth/tokens.py @@ -12,6 +12,7 @@ from flask_security.signals import refresh_tracker_revoked from sqlalchemy import func, select +from flexmeasures.auth.event_logging import log_authentication_event from flexmeasures.data import db from flexmeasures.data.models.refresh_tokens import RefreshTokenTracker @@ -86,8 +87,18 @@ def exchange_refresh_token(token: str, *, revoke: bool = False) -> tuple[dict, i refresh_errors=error, ) if error or user is None or not user.active: + reuse_user_id = ( + tracker.user_id + if tracker is not None and error == RefreshTokenErrors.GEN_MISMATCH + else None + ) # Commit replay revocation even though authentication failed. db.session.commit() + if reuse_user_id is not None: + log_authentication_event( + f"refresh token reuse revoked a family for user {reuse_user_id}", + failed=True, + ) return { "error": "invalid_refresh_token", "errors": ["Refresh token is invalid or expired. Authenticate again."], @@ -98,4 +109,5 @@ def exchange_refresh_token(token: str, *, revoke: bool = False) -> tuple[dict, i datastore.exchange_refresh_tracker(tracker) payload = token_response(user, get_refresh_token(tracker, user)) db.session.commit() + log_authentication_event(f"refresh token rotated for user {payload['user_id']}") return payload, 200