Skip to content

Sec/refresh tokens - #2849

Open
nhoening wants to merge 34 commits into
mainfrom
sec/refresh-tokens
Open

nhoening wants to merge 34 commits into
mainfrom
sec/refresh-tokens

Conversation

@nhoening

@nhoening nhoening commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

Description

Closes #2229

The

  • Clients can opt in to get refresh tokens with the eisting ndpoint for auth token access
  • Clients can rotate tokens
  • Clients can revoke a token family.
  • New fields use kebab-case; the existing auth_token, user_id, and access-token lifetime remain compatible.
  • Added changelog item in documentation/changelog.rst

Look & Feel

Check the new documentation and API endpoints.

How to test

Here is a bash script:

uv run --no-project --with requests python - <<'PY'
import getpass
import requests

base = "http://localhost:5000"
email = input("Email: ")
password = getpass.getpass("Password: ")

# Log in and opt in to refresh tokens.
response = requests.post(
    f"{base}/api/requestAuthToken",
    json={
        "email": email,
        "password": password,
        "include-refresh-token": True,
    },
    timeout=30,
)
response.raise_for_status()
first = response.json()
print("Login succeeded; access token lifetime:", first["expires-in"], "seconds")

# Exchange the refresh token.
response = requests.post(
    f"{base}/api/refreshAuthToken",
    json={"refresh-token": first["refresh-token"]},
    timeout=30,
)
response.raise_for_status()
second = response.json()
assert second["refresh-token"] != first["refresh-token"]
print("Refresh succeeded; a replacement refresh token was issued.")

# Use the new access token for an ordinary API request.
response = requests.get(
    f"{base}/api/v3_0/users/{second['user_id']}",
    headers={"Authorization": second["auth_token"]},
    timeout=30,
)
response.raise_for_status()
print("The new access token works.")

# Reuse of the old refresh token must fail and revoke the family.
response = requests.post(
    f"{base}/api/refreshAuthToken",
    json={"refresh-token": first["refresh-token"]},
    timeout=30,
)
assert response.status_code == 401, response.text
response = requests.post(
    f"{base}/api/refreshAuthToken",
    json={"refresh-token": second["refresh-token"]},
    timeout=30,
)
assert response.status_code == 401, response.text
print("Replay was rejected and the refresh-token family was revoked.")
PY

Future work

The client needs to support this, as well. See FlexMeasures/flexmeasures-client#291

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.
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.
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.
Context:
- Issue #2229 adds renewable API credentials.

Change:
- Describe refresh-token rotation, expiry and revocation while retaining legacy access-token authentication.
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.
@nhoening nhoening self-assigned this Nov 9, 2026
@nhoening nhoening added this to the 1.2.0 milestone Nov 9, 2026
@joyshmitz

Copy link
Copy Markdown
Collaborator

Heads-up: #2842, merged today, rewrote the same bullets in documentation/concepts/security_auth.rst, so this branch now conflicts with main there. The other files merge cleanly.

In case it saves you a step, this is how I would resolve it, checked in a local merge of main into df93c49: keep main's bullets on passwords and 2FA, and merge the token bullet like this:

* 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.
  Access tokens are signed (with the itsdangerous library) and carry the time they were issued, which is how they expire.
  To change their maximum age, set ``SECURITY_TOKEN_MAX_AGE`` to the number of seconds after which tokens should expire, in the config file (it is not read from an environment variable).
  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.

It keeps your introductory wording and refresh-token text, and from main how access tokens expire and that SECURITY_TOKEN_MAX_AGE is not loaded from the environment, which still holds on this branch (flexmeasures/utils/config_utils.py).

@nhoening

Copy link
Copy Markdown
Member Author

Heads-up: #2842, merged today, rewrote the same bullets in documentation/concepts/security_auth.rst, so this branch now conflicts with main there. The other files merge cleanly.

Thanks @joyshmitz - I was just contemplating that you might be the right reviewer for this PR as you are looking into security issues just now - can I add you?

@joyshmitz

Copy link
Copy Markdown
Collaborator

Yes, happy to. I'll go through the token lifecycle (rotation, reuse of a rotated token, family revocation), the migration and the tests, and run it against a local database.

@nhoening

nhoening commented Nov 10, 2026 •

Copy link
Copy Markdown
Member Author

I added you as collaborator, @joyshmitz (so I can officially ask you for reviews :) )

By the way, you're very welcome to the 30-minute TSC call on FlexMeasures Thursday 9am CET

Comment thread documentation/changelog.rst Resolved
Signed-off-by: Nicolas Höning <iam@nicolashoening.de>
@nhoening
nhoening requested a review from joyshmitz November 10, 2026 14:20
@nhoening

Copy link
Copy Markdown
Member Author

(I am working out the corresponding PR on the FM-client)

@joyshmitz joyshmitz left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reviewed c212713 as promised: the token lifecycle, the migration, the tests, and a run against a local PostgreSQL 18.

The lifecycle holds. I found no sequence in which a refresh token that should be dead still yields an access token.

  • The 31 tests in test_refresh_tokens_fresh_db.py pass locally.
  • Against four separate server processes sharing one migrated database, I sent the same refresh token from 8 clients at once, five rounds. Every round gave exactly one 200 and seven 401, and the winner's replacement token was rejected afterwards, as the reuse rule requires.
  • I removed the safeguards one at a time to see whether a test notices. Removing the same-instant revocation check, the family revocation on reuse, the row locks, the listener on the user, or the password re-check before issuance each turns at least one test red.
  • remove_cookie_and_token_access, set_random_password and deactivating a user each revoke the user's families, and reactivating does not bring them back.
  • The migration upgrades from bf22b21d0990, downgrades without leaving anything behind, and upgrades again. After the merge of main there is one Alembic head.

Six things I would change, none of which lets a dead token live. The first two are about behaviour, the rest are small. Edited: fixes for points 1, 4, 5 and 6 are in #2853.

1. Deleting a user can deadlock with a refresh of that user's token.
A refresh locks the user row and then the family row (auth/datastore.py:20-33). delete_user goes the other way: the ORM cascade on the new relationship (models/refresh_tokens.py:34) deletes the family rows first and the user row after. I reproduced it on PostgreSQL by pausing a refresh between its two locks and starting delete_user in that window, three times out of three:

(psycopg.errors.DeadlockDetected) deadlock detected
Process 1219891: DELETE FROM fm_user WHERE fm_user.id = $1::INTEGER
Process 1219838: SELECT refresh_token_tracker.id, ... FOR UPDATE

PostgreSQL aborted the deletion each time, so the user stayed and the refresh succeeded. The window is narrow, and the cost is a failed flexmeasures delete user or delete account that has to be run again, for exactly the user one may be in a hurry to remove.
Edited: I first suggested passive_deletes=True on the backref here. That is not enough: it only helps while the user's families are not loaded in the session. With user.refresh_trackers loaded, the ORM still deletes the families before the user, and the same reproduction deadlocks again. Locking the user row at the start of delete_user holds in both cases, and that is what #2853 does.

2. Families pile up per user, and each login with include-refresh-token gets slower.
new_refresh_tracker in Flask-Security walks all of the user's families on every issuance, and by default removes only those past their absolute expiry of 90 days. Revoked families and families that went idle stay until then. A client that logs in with include-refresh-token on every run, without ever refreshing, adds a row each time. Issuance for one user, measured locally (best of three):

families kept for the user issuance
0 2.6 ms
1,000 12 ms
10,000 295 ms
50,000 1,221 ms

That time is spent while holding the lock on the user row. One login per minute reaches 10,000 rows in a week.
Setting SECURITY_REFRESH_TOKEN_CLEANUP_REVOKED to true covers the revoked ones. Neither cleanup flag covers the idle ones, so a limit on live families per user, or advice in the docs to store and reuse the refresh token, would be needed for those.

3. expires-in is null for a zero SECURITY_TOKEN_MAX_AGE, but the access token expires at once.
token_response skips the deadline when max_age is zero (auth/tokens.py:26) and reports null, which the docs describe as "without an expiry" (introduction.rst:151, api/__init__.py:74, api/refresh_tokens.py:63). Flask-Security passes that zero on as max_age=0.0 when it checks the token (flask_security/utils.py, parse_auth_token). With timedelta(0) configured, I got expires-in: null, a 200 with the token in the same second, and a 401 two seconds later. test_unlimited_access_token_lifetime only checks the reported field. As far as I can see, Flask-Security 5.9 has no setting that makes access tokens unlimited, so the null case could go, or zero could be reported as 0.

4. Malformed requests return 422, the docs say 400.
introduction.rst:188 and the docstrings of both endpoints (api/refresh_tokens.py:64 and :104) promise 400. A missing, null, empty or non-string refresh-token returns 422 with "status": "UNPROCESSABLE_ENTITY", and so does a non-boolean include-refresh-token. test_malformed_refresh_requests accepts either status, so it does not pin this down.
Edited: 400 does occur, but only for JSON that cannot be parsed. #2853 documents and tests both.

5. The index name in the migration differs from the one the model produces.
The migration creates ix_refresh_token_tracker_user_id (line 40). With the naming convention in data/models/__init__.py:12, index=True on the model yields refresh_token_tracker_user_id_idx. After upgrading, flexmeasures db check reports:

Detected removed index 'ix_refresh_token_tracker_user_id' on 'refresh_token_tracker'
Detected added index 'refresh_token_tracker_user_id_idx' on '('user_id',)'

f3d8e2c9a741 next to it uses the _idx form.

6. Two safeguards that no test protects.

  • Without not user.active in exchange_refresh_token (auth/tokens.py:71), all 31 tests still pass, because the listener has already revoked the family by then. A user deactivated by a direct SQL update is the case that check is for.
  • Without the db.session.commit() after an explicit revocation (auth/tokens.py:79), all 31 tests still pass. The tests share one session, so the next request sees the pending change and commits it. Against the separate server processes the revocation did persist, so the code is right and only the test is blind here.

nhoening and others added 8 commits November 19, 2026 15:07
#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 <jshmitz@me.com>

* 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 <jshmitz@me.com>

* 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 <jshmitz@me.com>

* 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 <jshmitz@me.com>

---------

Signed-off-by: Serhii <jshmitz@me.com>
@nhoening
nhoening requested a review from joyshmitz November 20, 2026 23:09
Signed-off-by: Nicolas Höning <nicolas@seita.nl>
Signed-off-by: Nicolas Höning <nicolas@seita.nl>

@joyshmitz joyshmitz left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for taking on the family limit and the zero-lifetime report, and for merging #2853. I re-reviewed what changed since my first review (bb275f7…645dce927, 91c1182, and the merge of main in 4756f39) on b70fda7, against a migrated PostgreSQL database and the test suite.

From the first review, now resolved

  • Families no longer slow down token issuance. With 50,000 leftover revoked families, the first opt-in login cleans them up in 87 ms, and later logins take 4–11 ms. The first review measured 1.2 s at 50,000. At 999 live families, login and rotation stay at about 10 ms and 4 ms. The 1,000th family is refused with 409.
  • expires-in is accurate. It is 0 with SECURITY_TOKEN_MAX_AGE = 0, and it honours a per-token exp.
  • The delete_user deadlock fix survived the merges. The reproduction script still ends with refresh 200 and delete committed, with and without the families loaded.
  • The new tests are strong. Breaking the cleanup, the limit or the boundaries one at a time, 11 of 12 mutations fail a test. The exception is in point 8.

Needs fixing

  1. Two Alembic heads.

    • flexmeasures db heads on the PR head lists 5c0f3e7a9b21 and c8d4193f27a6. Both merge e8a3f6c2b917: the first with main's d4b7e2a91c36, the second with af36c80d214e. The Docker job fails on this: "Multiple head revisions are present".
    • c8d4193f27a6 is not released yet, so it could take 5c0f3e7a9b21 as its parent in place of e8a3f6c2b917. Alternatively, add one more merge revision.
  2. The merge dropped the active check on the locked user row.

    • Before the merge, the opt-in branch locked the user and then checked user.active (645dce9, api/__init__.py:127-136). Now the only check is main's, at api/__init__.py:165, before the lock at :173-178. After the lock, only the password is checked again.
    • I committed a deactivation from a second connection just before the login takes that lock. The login returned 200 with a refresh token, and the deactivated user was left with an unrevoked family. After reactivation, that token refreshed with 200, while the docs say "Reactivating a user does not restore those families".
    • Fix: check user.active again after the lock.
  3. A test still expects the behaviour v1.1.2 removed.

    • test_session_cannot_replace_password_for_refresh_issuance (test_refresh_tokens_fresh_db.py:755) expects a logged-in session with a wrong password to get an access token (200). Since v1.1.2, the endpoint requires the password from a session too, so the test fails with 401.
    • It is the only failure on the PR head that does not also fail on main for me. CI did not get that far, because flake8 failed first (see 4).
  4. flake8 C901, and the password is checked three times.

    • request_auth_token has complexity 17 against the limit of 13 (.flake8).
    • Part of that is a block the merge kept from both sides: api/__init__.py:161-164 repeats the password check of :131 and :144-148 (main has one check per branch). So every password login hashes the password twice, and an opt-in login three times, counting the check on the locked row at :179.
    • Dropping :161-164 removes the extra hash.
  5. 409s count as failed authentications, and lock out the documented fallback.

    • login_throttling counts every token request before it runs, and clears the counts only on a 200.
    • With FLEXMEASURES_AUTHENTICATION_FAILURE_LIMIT = "3 per 15 minutes" and a family limit of 1, five opt-in logins gave 200, 409, 409, 409, 429. After that, an ordinary login without opt-in also got 429. With the default limit, the same happens after ten 409s within 15 minutes.
    • The docs offer the ordinary access-token login as the way out of the family limit. Clearing the counts on this 409, as on a 200, would keep that way open: the 409 is only returned once the credentials have been verified.
  6. Opt-in logins are missing from the authentication event log.

    • The opt-in branch returns at api/__init__.py:181, before log_authentication_event at :184-186. An ordinary token is logged as issued; a login that gets a refresh token, a longer-lived credential, is not.

Smaller things

  1. The 409 message. It says "Revoke an unused family before signing in again". That does not help a client that lost its tokens. Pointing to the idle expiry, or to the ordinary login, as the docs at introduction.rst:179-180 already do, would.
  2. One test gap. Counting all families, not only name == "api" (tokens.py:45-48), passes every test, because the limit tests seed only API families. A browser family in the limit test would catch it.
  3. A section of the configuration docs disappears. documentation/configuration.rst:709 (from 1f04c8a) has no blank line between "Default: 1000" and the SESSION_COOKIE_SECURE, … heading. docutils silently merges that heading into the paragraph, so the cookie section is gone, and there is no warning to catch it.
  4. No API changelog entry. documentation/api/change_log.rst does not mention refreshAuthToken, revokeRefreshToken, include-refresh-token or the 409.
  5. Comment line breaks. The comments at api/__init__.py:169-170 and auth/__init__.py:51-53 break mid-phrase, which docstrings.instructions.md asks to avoid.

The 7 other failures I see on the PR head fail on main too: sorting under a C.UTF-8 collation, test_numerical_errors[cbc], and test_closest_sensor. The DCO check reports 16 commits without a sign-off.

Reconcile the token response descriptions and regenerate the merged OpenAPI specification. Extract token issuance so the merged route passes the repository complexity check without altering its authentication decisions.

Signed-off-by: Nicolas Höning <nicolas@seita.nl>
Signed-off-by: Nicolas Höning <nicolas@seita.nl>
Signed-off-by: Nicolas Höning <nicolas@seita.nl>
Signed-off-by: Nicolas Höning <nicolas@seita.nl>
Signed-off-by: Nicolas Höning <nicolas@seita.nl>
Signed-off-by: Nicolas Höning <nicolas@seita.nl>
Signed-off-by: Nicolas Höning <nicolas@seita.nl>
Signed-off-by: Nicolas Höning <nicolas@seita.nl>
Signed-off-by: Nicolas Höning <nicolas@seita.nl>
Signed-off-by: Nicolas Höning <nicolas@seita.nl>
…PI changelog

Signed-off-by: Nicolas Höning <nicolas@seita.nl>
Signed-off-by: Nicolas Höning <nicolas@seita.nl>
@nhoening
nhoening requested a review from joyshmitz December 6, 2026 01:30

@joyshmitz joyshmitz left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for working through all of round 2; one commit per point made it easy to check. I re-reviewed the twelve new commits (56ad65d…e866f1787) on e866f17, against a PostgreSQL database migrated from its round-2 state, the test suite, and two race scripts.

All eleven points are fixed

  1. There is one Alembic head, e949b5dbfdf6. The round-2 database, with both old heads applied, upgrades with a plain flexmeasures db upgrade through main's new migrations to it.
  2. The deactivation race now gets 401, and the user is left without a family.
  3. test_session_cannot_replace_password_for_token_issuance passes in both modes.
  4. flake8 passes, and request_auth_token is at complexity 10. A login verifies the password once, and an opt-in login once more on the locked row.
  5. With "3 per 15 minutes" and a family limit of 1, five opt-in logins give 200, 409, 409, 409, 409, and an ordinary login after them gets 200. Wrong passwords still end in 429.
  6. An opt-in login is logged once, without token material, and a 409 is not logged as an issuance.
  7. The 409 message now points to the ordinary login and to the idle expiry.
  8. test_family_limit_counts_only_api_families fails when browser families are counted.
  9. docutils reads the SESSION_COOKIE_SECURE, … heading as a section again.
  10. The API changelog entry covers the three endpoints and the 409.
  11. Both comments now break at the end of a sentence.

Breaking the new and moved code one piece at a time, 12 of 16 mutations fail a test. Of the four that pass, one drops the dummy hash for unknown email addresses, which is about timing and hard to test; the other three are in points 1 and 2 below.

Still worth doing

  1. No test runs the locked read itself.

    • test_refresh_issuance_requires_an_active_locked_user replaces db.session.scalar, so the SELECT … FOR UPDATE never runs. Dropping .execution_options(populate_existing=True) (api/__init__.py:62) passes all the token and authentication tests, and so does dropping the password check on the locked row (:64).
    • Both matter. Without populate_existing, the locked SELECT returns the user object already in the session, with its values from before the lock. A deactivation committed from a second connection just before the lock then gets 200 and a family, which refreshes again after reactivation, and a password change in the same window leaves the old password with a family that refreshes. Without the password check, the password change has the same result. On e866f17, both get 401 and leave no family.
    • A test that commits the change from a second connection when the FOR UPDATE statement is about to run (a before_cursor_execute listener can do it) would cover the check, the reload and the password check at once. I'm happy to share the scripts.
  2. No test has a 2FA user get a token from their session.

    • Since eb643c0, the condition issued_by == "password" (api/__init__.py:184) is what keeps the 2FA refusal off the session path, which the docstring gives 2FA users as their way to a token. Dropping that condition also passes all the token and authentication tests, because no test logs a 2FA user in and asks for a token.
  3. Four more comments break mid-phrase. In round 2 I only listed two. The others are at auth/tokens.py:70, data/models/refresh_tokens.py:43, data/schemas/tests/test_field_naming.py:115-117, and in the OpenAPI description at api/refresh_tokens.py:34, which carries the break into openapi-specs.json.

  4. The v1.2.0 upgrade warning (documentation/changelog.rst:12-14) lists what the migrations add, but not the refresh-token table.

  5. Optional, perhaps as a follow-up: rotations and reuse are not in the authentication log, as neither auth/tokens.py nor api/refresh_tokens.py logs anything. A reuse that revokes a family is the event an admin would most want to see.

The full suite on e866f17, with the dependencies from uv.lock (pandas 3.1.2), gives 4602 passed, 7 failed and 5 xfailed. The same 7 tests fail on main (ab9b901) in the same environment: sorting under a C.UTF-8 collation, test_numerical_errors[cbc] and test_closest_sensor.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Refresh tokens

2 participants