Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
836ae8d
auth: persist refresh-token families and serialize lifecycle changes
nhoening Nov 7, 2026
39b2425
api: add opt-in refresh-token issuance, rotation and revocation
nhoening Nov 7, 2026
3c62aa9
tests: cover refresh-token security and legacy authentication
nhoening Nov 7, 2026
64a6695
changelog: announce optional API refresh tokens
nhoening Nov 7, 2026
df93c49
docs: explain the refresh-token lifecycle and API contract
nhoening Nov 7, 2026
e1c9bc3
Merge origin/main into sec/refresh-tokens
nhoening Nov 10, 2026
c212713
Apply suggestion from @nhoening
nhoening Nov 10, 2026
e519411
Merge branch 'main' into sec/refresh-tokens
nhoening Nov 19, 2026
bf52eab
Fix the review findings on refresh tokens that need no design decisio…
joyshmitz Nov 20, 2026
d0d6263
Merge origin/main into sec/refresh-tokens
nhoening Nov 20, 2026
91c1182
migrations: merge refresh-token and automation heads
nhoening Nov 20, 2026
bb275f7
auth: report zero access-token lifetime accurately
nhoening Nov 20, 2026
48291cc
tests: cover zero and per-token access expiry
nhoening Nov 20, 2026
84538ea
docs: clarify access-token expiry responses
nhoening Nov 20, 2026
dcb37c9
auth: limit and clean up refresh-token families
nhoening Nov 20, 2026
abb0df6
tests: cover refresh-family cleanup and limits
nhoening Nov 20, 2026
1f04c8a
docs: explain refresh-token family limits
nhoening Nov 20, 2026
de0fd3b
changelog: mention refresh-token family limits
nhoening Nov 20, 2026
939aaaa
tests: cover invalid refresh-token login option
nhoening Nov 20, 2026
645dce9
docs: describe invalid refresh-token login option
nhoening Nov 20, 2026
4756f39
Merge branch 'main' into sec/refresh-tokens
nhoening Nov 24, 2026
b70fda7
run black
nhoening Nov 24, 2026
56ad65d
Merge origin/main into sec/refresh-tokens
nhoening Dec 6, 2026
f09ab43
migrations: merge refresh-token and automation heads
nhoening Dec 6, 2026
7c729d7
api: require an active user under the refresh issuance lock
nhoening Dec 6, 2026
37c7035
tests: require the password for both session token modes
nhoening Dec 6, 2026
eb643c0
api: verify the password once before token issuance
nhoening Dec 6, 2026
2bae92c
auth: clear failure counts for verified family-limit conflicts
nhoening Dec 6, 2026
c38ab42
api: log successful opt-in token issuance
nhoening Dec 6, 2026
37e11a5
auth: explain how to proceed at the refresh family limit
nhoening Dec 6, 2026
3669bcd
tests: count API refresh families independently of browser families
nhoening Dec 6, 2026
d10c8e5
docs: restore the session cookie configuration heading
nhoening Dec 6, 2026
ee386f8
docs: record refresh-token issuance, rotation and revocation in the A…
nhoening Dec 6, 2026
e866f17
auth: keep refresh-token comment sentences together
nhoening Dec 6, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions documentation/api/change_log.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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/<uuid>`` 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/<id>/schedules/<uuid>`` answers with ``UNKNOWN_SCHEDULE`` and the same reason.
- ``POST /api/v3_0/sensors`` and ``PATCH /api/v3_0/sensors/<id>`` 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.
Expand Down
163 changes: 162 additions & 1 deletion documentation/api/introduction.rst
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,168 @@ which gives a response like this if the credentials are correct:
"user_id": "<ID of the user>"
}

.. 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": "<user password>",
"include-refresh-token": true
}

A successful response has HTTP status 200:

.. code-block:: json

{
"auth_token": "<access token>",
"user_id": 1,
"refresh-token": "<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.
``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:

.. code-block:: json

{"refresh-token": "<current 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.

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 <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
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. 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.

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
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":"<password>","include-refresh-token":true}'

curl --fail-with-body https://company.flexmeasures.io/api/v3_0/users/1 \
-H 'Authorization: <access token>'

curl --fail-with-body https://company.flexmeasures.io/api/refreshAuthToken \
-H 'Content-Type: application/json' \
-d '{"refresh-token":"<current refresh token>"}'

curl --fail-with-body https://company.flexmeasures.io/api/revokeRefreshToken \
-H 'Content-Type: application/json' \
-d '{"refresh-token":"<replacement 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:

Expand Down
2 changes: 2 additions & 0 deletions documentation/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ New features
* ``search_beliefs`` (on sensors and assets), ``TimedBelief.search`` and the ``chart`` methods of sensors and assets accept ``events_occurring_after`` and ``events_occurring_before``, clearer names for ``event_starts_after`` and ``event_ends_before`` with the same meaning: events that occur, at least in part, after or before the given time [see `PR #2925 <https://www.github.com/FlexMeasures/flexmeasures/pull/2925>`_ and `issue #484 <https://www.github.com/FlexMeasures/flexmeasures/issues/484>`_]
* The ``AggregatorReporter`` saves a sum that includes a forecast as a forecast, under a ``forecaster``-type source (or one that includes a schedule as a schedule), so that, for instance, a forecast of a community's sum is not trained on the sum of its members' forecasts; a reporter can be set up again from such a source, and the sources a data generator computed under can be listed with the new ``data-generator`` filter of ``GET /api/v3_0/sources`` [see `PR #2804 <https://www.github.com/FlexMeasures/flexmeasures/pull/2804>`_]

* 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 <https://github.com/FlexMeasures/flexmeasures/pull/2849>`_]

Infrastructure / Support
-------------------------
* Upgrade to pandas 3 (pandas 2 remains supported), with daily data still following local calendar days across DST changes [see `PR #2955 <https://www.github.com/FlexMeasures/flexmeasures/pull/2955>`_ and `PR #2932 <https://www.github.com/FlexMeasures/flexmeasures/pull/2932>`_]
Expand Down
3 changes: 2 additions & 1 deletion documentation/concepts/security_auth.rst
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,10 @@ 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, hashed with the Argon2 algorithm (the default of Flask-Security, which FlexMeasures uses for authentication). 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.
* 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.
* In the UI, FlexMeasures supports two-factor authentication (2FA), which is off by default.
When it is on, 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).
We strongly advise turning it on in production with :ref:`security_two_factor` (see :ref:`installation_two_factor`).
Expand Down
13 changes: 13 additions & 0 deletions documentation/configuration.rst
Original file line number Diff line number Diff line change
Expand Up @@ -695,6 +695,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``

SESSION_COOKIE_SECURE, SESSION_COOKIE_SAMESITE, REMEMBER_COOKIE_SECURE, REMEMBER_COOKIE_SAMESITE, REMEMBER_COOKIE_DURATION
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Expand Down
Loading
Loading