vincbeck commented on code in PR #77138:
URL: https://github.com/apache/airflow/pull/77138#discussion_r4601568767
##########
providers/fab/src/airflow/providers/fab/auth_manager/fab_auth_manager.py:
##########
@@ -183,6 +185,31 @@
}
CACHE_TTL = conf.getint("fab", "cache_ttl", fallback=30)
+# A token is accepted only while this claim matches the user's current
password fingerprint.
+PASSWORD_FINGERPRINT_CLAIM = "password_fingerprint"
+PASSWORD_FINGERPRINT_HEX_LENGTH = 32
+
+
+def _compute_password_fingerprint(user: User | AnonymousUser) -> str:
+ """
+ Return a fingerprint of the user's current password.
+
+ It changes whenever the password is changed or reset. Users without a
local password share a
+ constant fingerprint.
+ """
+ password_hash = getattr(user, "password", None) or ""
+ return hmac.new(
+ conf.get_mandatory_value("api", "secret_key").encode(),
Review Comment:
This now runs on every API request, and Airflow config does not cache `_cmd`
/ `_secret` values. With `AIRFLOW__API__SECRET_KEY_CMD` or `secret_key_secret`
set, each request runs a subprocess or calls the secrets backend, on the event
loop. Can we read the key once?
##########
providers/fab/src/airflow/providers/fab/auth_manager/fab_auth_manager.py:
##########
@@ -310,23 +337,37 @@ def get_user(self) -> User:
def session(self):
return self.appbuilder.session
- @cachedmethod(lambda self: self.cache, key=lambda _, token:
int(token["sub"]))
def deserialize_user(self, token: dict[str, Any]) -> User:
user_id = int(token["sub"])
+ fingerprint = token.get(PASSWORD_FINGERPRINT_CLAIM)
+ user = self._get_active_user(user_id)
+ if not _is_password_fingerprint_matching(fingerprint, user):
+ # The cached user may predate a password change. Re-read it so a
token issued after the
+ # change is accepted without waiting for the cache entry to expire.
+ user = self._fetch_active_user(user_id)
+ self.cache[user_id] = user
+ if not _is_password_fingerprint_matching(fingerprint, user):
+ raise ValueError(f"Token of user with id {user_id} was not
issued for their current password")
Review Comment:
That is a breaking change. Tokens issued before the upgrade have no
`password_fingerprint` claim, so every user and API client is logged out when
upgrading the FAB provider. These tokens expire anyway (24h by default), could
we accept a missing claim? Otherwise please add a note in
`providers/fab/docs/changelog.rst`.
##########
providers/fab/tests/unit/fab/auth_manager/test_fab_auth_manager.py:
##########
@@ -288,13 +301,94 @@ def test_deserialize_user_not_found_not_cached(self,
flask_app, auth_manager_wit
# If the exception were cached, this would still raise ValueError.
# Instead it should succeed because exceptions are not cached.
- result = auth_manager_with_appbuilder.deserialize_user({"sub":
str(user.id)})
+ result = auth_manager_with_appbuilder.deserialize_user(
+ auth_manager_with_appbuilder.serialize_user(user)
+ )
assert user.get_id() == result.get_id()
+ def test_deserialize_user_rejects_token_without_password_fingerprint(
+ self, flask_app, auth_manager_with_appbuilder
+ ):
+ """A token issued before fingerprints existed cannot be tied to the
current password."""
+ user = create_user(flask_app, "test_no_fingerprint")
+ auth_manager_with_appbuilder.cache.clear()
+
+ with pytest.raises(ValueError, match="was not issued for their current
password"):
+ auth_manager_with_appbuilder.deserialize_user({"sub":
str(user.id)})
+
+ def test_password_change_rejects_tokens_issued_before_it(self, flask_app,
auth_manager_with_appbuilder):
+ """Changing the password through the user API ends the tokens issued
before the change."""
+ user = create_user(flask_app, "test_password_change")
+ user_id, old_token = user.id,
auth_manager_with_appbuilder.serialize_user(user)
+
+ with flask_app.app_context():
+ FABAuthManagerUsers.update_user(
+ "test_password_change",
UserPatchBody(password="new-password"), update_mask="password"
+ )
+
+ self._assert_only_tokens_issued_after_update_accepted(
+ flask_app, auth_manager_with_appbuilder, user_id, old_token
+ )
+
+ def test_password_reset_rejects_tokens_issued_before_it(self, flask_app,
auth_manager_with_appbuilder):
+ """Resetting the password, as the CLI and the reset form do, ends the
tokens issued before."""
+ user = create_user(flask_app, "test_password_reset")
+ user_id, old_token = user.id,
auth_manager_with_appbuilder.serialize_user(user)
+
+ with flask_app.app_context():
+ assert
auth_manager_with_appbuilder.security_manager.reset_password(user_id,
"new-password")
+
+ self._assert_only_tokens_issued_after_update_accepted(
+ flask_app, auth_manager_with_appbuilder, user_id, old_token
+ )
+
+ @staticmethod
+ def _assert_only_tokens_issued_after_update_accepted(flask_app,
auth_manager, user_id, old_token):
+ with flask_app.app_context():
+ user = auth_manager.security_manager.get_user_by_id(user_id)
+ new_token = auth_manager.serialize_user(user)
+ # Tokens are checked against a user cached for ``[fab] cache_ttl``;
start from its expiry.
+ auth_manager.cache.clear()
+
+ with pytest.raises(ValueError, match="was not issued for their current
password"):
+ auth_manager.deserialize_user(old_token)
+ assert auth_manager.deserialize_user(new_token).id == user_id
+
+ def test_deserialize_user_accepts_new_token_while_cached_user_is_stale(
+ self, flask_app, auth_manager_with_appbuilder
+ ):
+ """A token issued right after a password change works before the user
cache expires."""
+ user = create_user(flask_app, "test_stale_cache")
+ auth_manager_with_appbuilder.cache.clear()
+ old_token = auth_manager_with_appbuilder.serialize_user(user)
+ auth_manager_with_appbuilder.deserialize_user(old_token)
+
+ # The lookup above detached ``user`` from the scoped session, so write
the new hash directly.
+ with create_session() as session:
+ session.execute(update(User).where(User.id ==
user.id).values(password="new-password-hash"))
+ user.password = "new-password-hash"
Review Comment:
This test passes even without the re-fetch in `deserialize_user`. `user` is
the same object as the cached one (both come from the scoped session), so
setting `user.password` also updates the cache and the new token matches on the
first check. Fix: don't touch `user`, build `new_token` from a freshly loaded
user instead.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]