Skip to content

JWT payload: a UUID is encoded as a string but the string is not decoded as a UUID #144

Open

Description

@thibgc

I am trying out FastAdmin with SQLAlchemy and aiosqlite using the examples in the documentation, with a User model that has a UUID as its primary key, as suggested by some of the examples. After inserting a superuser directly into the database and signing in as that user, the POST to /admin/api/sign-in succeeds (200 and sets a JWT), but the next two GETs (which send the JWT) to /admin/api/me and /admin/api/configuration fail (500), ultimately with:

ERROR:fastadmin.api.frameworks.fastapi.app:Unhandled admin error: (builtins.AttributeError) 'str' object has no attribute 'hex'

In api/service.py, the sign_in method encodes a UUID into the JWT as a string (a 36-character string with hyphens). The JWT is produced only if the user ID is an integer or a UUID:

# ref: https://github.com/vsdudakov/fastadmin/blob/v0.10.0/fastadmin/api/service.py#L183-L199
        user_id = await authenticate_fn(payload.username, payload.password)


        if isinstance(user_id, bool) or not isinstance(user_id, int | UUID):
            raise AdminApiException(401, detail="Invalid credentials.")


        now = datetime.now(UTC)
        session_expired_at = now + timedelta(seconds=settings.ADMIN_SESSION_EXPIRED_AT)
        if isinstance(user_id, UUID):
            user_id = str(user_id)
        return jwt.encode(
            {
                "user_id": user_id,
                "session_expired_at": session_expired_at.isoformat(),
            },
            settings.ADMIN_SECRET_KEY,
            algorithm="HS256",
        )

On the way back, the get_user_id_from_session_id method does not turn it back into a UUID:

# ref: https://github.com/vsdudakov/fastadmin/blob/v0.10.0/fastadmin/api/service.py#L67-L81
    try:
        token_payload = jwt.decode(session_id, settings.ADMIN_SECRET_KEY, algorithms=["HS256"])
    except jwt.PyJWTError:
        return None


    session_expired_at = token_payload.get("session_expired_at")
    if not session_expired_at:
        return None


    if datetime.fromisoformat(session_expired_at).replace(tzinfo=UTC) < datetime.now(UTC):
        return None


    user_id = token_payload.get("user_id")
    if user_id is None:
        return None

The next line calls admin_model.get_obj(user_id) with this string:

# ref: https://github.com/vsdudakov/fastadmin/blob/v0.10.0/fastadmin/api/service.py#L83-L84
    if not await admin_model.get_obj(user_id):
        return None

The signature of get_obj() allows this (UUID | int | str), but it fails, at least in my case. This is the tail end of the stack trace, starting at the get_obj call at line 83 https://github.com/vsdudakov/fastadmin/blob/v0.10.0/fastadmin/api/service.py#L83:

  File "/home/user/.cache/pypoetry/virtualenvs/myproject-nnjsnp-d-py3.14/lib/python3.14/site-packages/fastadmin/api/service.py", line 83, in get_user_id_from_session_id
    if not await admin_model.get_obj(user_id):
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/user/.cache/pypoetry/virtualenvs/myproject-nnjsnp-d-py3.14/lib/python3.14/site-packages/fastadmin/models/base.py", line 571, in get_obj
    obj = await self.orm_get_obj(id)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/user/.cache/pypoetry/virtualenvs/myproject-nnjsnp-d-py3.14/lib/python3.14/site-packages/fastadmin/models/orms/sqlalchemy.py", line 441, in orm_get_obj
    return await session.get(self.model_cls, id)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/user/.cache/pypoetry/virtualenvs/myproject-nnjsnp-d-py3.14/lib/python3.14/site-packages/sqlalchemy/ext/asyncio/session.py", line 807, in get
    return await greenlet_spawn(
           ^^^^^^^^^^^^^^^^^^^^^
    ...<8 lines>...
    )
    ^
  File "/home/user/.cache/pypoetry/virtualenvs/myproject-nnjsnp-d-py3.14/lib/python3.14/site-packages/sqlalchemy/util/concurrency.py", line 212, in greenlet_spawn
    result = context.switch(value)
  File "/home/user/.cache/pypoetry/virtualenvs/myproject-nnjsnp-d-py3.14/lib/python3.14/site-packages/sqlalchemy/orm/session.py", line 3845, in get
    return self._get_impl(
           ~~~~~~~~~~~~~~^
        entity,
        ^^^^^^^
    ...<7 lines>...
        bind_arguments=bind_arguments,
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "/home/user/.cache/pypoetry/virtualenvs/myproject-nnjsnp-d-py3.14/lib/python3.14/site-packages/sqlalchemy/orm/session.py", line 4032, in _get_impl
    return db_load_fn(
        self,
    ...<5 lines>...
        bind_arguments=bind_arguments,
    )
  File "/home/user/.cache/pypoetry/virtualenvs/myproject-nnjsnp-d-py3.14/lib/python3.14/site-packages/sqlalchemy/orm/loading.py", line 702, in _load_on_pk_identity
    session.execute(
    ~~~~~~~~~~~~~~~^
        q,
        ^^
    ...<2 lines>...
        bind_arguments=bind_arguments,
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "/home/user/.cache/pypoetry/virtualenvs/myproject-nnjsnp-d-py3.14/lib/python3.14/site-packages/sqlalchemy/orm/session.py", line 2473, in execute
    return self._execute_internal(
           ~~~~~~~~~~~~~~~~~~~~~~^
        statement,
        ^^^^^^^^^^
    ...<4 lines>...
        _add_event=_add_event,
        ^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "/home/user/.cache/pypoetry/virtualenvs/myproject-nnjsnp-d-py3.14/lib/python3.14/site-packages/sqlalchemy/orm/session.py", line 2363, in _execute_internal
    compile_state_cls.orm_execute_statement(
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
        self,
        ^^^^^
    ...<4 lines>...
        conn,
        ^^^^^
    )
    ^
  File "/home/user/.cache/pypoetry/virtualenvs/myproject-nnjsnp-d-py3.14/lib/python3.14/site-packages/sqlalchemy/orm/context.py", line 316, in orm_execute_statement
    result = conn.execute(
        statement, params or {}, execution_options=execution_options
    )
  File "/home/user/.cache/pypoetry/virtualenvs/myproject-nnjsnp-d-py3.14/lib/python3.14/site-packages/sqlalchemy/engine/base.py", line 1458, in execute
    return meth(
        self,
        distilled_parameters,
        execution_options or NO_OPTIONS,
    )
  File "/home/user/.cache/pypoetry/virtualenvs/myproject-nnjsnp-d-py3.14/lib/python3.14/site-packages/sqlalchemy/sql/elements.py", line 533, in _execute_on_connection
    return connection._execute_clauseelement(
           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
        self, distilled_params, execution_options
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "/home/user/.cache/pypoetry/virtualenvs/myproject-nnjsnp-d-py3.14/lib/python3.14/site-packages/sqlalchemy/engine/base.py", line 1678, in _execute_clauseelement
    ret = self._execute_context(
        dialect,
    ...<9 lines>...
        param_dict=param_dict,
    )
  File "/home/user/.cache/pypoetry/virtualenvs/myproject-nnjsnp-d-py3.14/lib/python3.14/site-packages/sqlalchemy/engine/base.py", line 1807, in _execute_context
    self._handle_dbapi_exception(
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
        e, str(statement), parameters, None, None
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "/home/user/.cache/pypoetry/virtualenvs/myproject-nnjsnp-d-py3.14/lib/python3.14/site-packages/sqlalchemy/engine/base.py", line 2342, in _handle_dbapi_exception
    raise sqlalchemy_exception.with_traceback(exc_info[2]) from e
  File "/home/user/.cache/pypoetry/virtualenvs/myproject-nnjsnp-d-py3.14/lib/python3.14/site-packages/sqlalchemy/engine/base.py", line 1801, in _execute_context
    context = constructor(
        dialect, self, conn, execution_options, *args, **kw
    )
  File "/home/user/.cache/pypoetry/virtualenvs/myproject-nnjsnp-d-py3.14/lib/python3.14/site-packages/sqlalchemy/engine/default.py", line 1750, in _init_compiled
    flattened_processors[key](compiled_params[key])
    ~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^
  File "/home/user/.cache/pypoetry/virtualenvs/myproject-nnjsnp-d-py3.14/lib/python3.14/site-packages/sqlalchemy/sql/sqltypes.py", line 3941, in process
    value = value.hex
            ^^^^^^^^^
sqlalchemy.exc.StatementError: (builtins.AttributeError) 'str' object has no attribute 'hex'
[SQL: SELECT users.username, users.display_name, users.email, users.id, users.hashed_password, users.is_active, users.is_admin, users.is_superuser 
FROM users 
WHERE users.id = ?]
[parameters: [{'pk_1': 'ed619d32-82df-426f-98b4-2439944aed6e'}]]

It thinks the user ID is a UUID, I presume thanks to the model definition that labels it as a SQLAlchemy Uuid, and applies .hex to it to get the (32-character) string needed by SQLite/aiosqlite, but it's really a (36-character) string which does not have .hex.

I presume it would be intended that what comes out of the JWT, if it is a string, is meant to be parsed as a UUID again, because although the call to get_obj does allow for a string, the get_user_id_from_session_id method's return type does not, it is declared as -> UUID | int | None:

# ref: https://github.com/vsdudakov/fastadmin/blob/v0.10.0/fastadmin/api/service.py#L49-L54
async def get_user_id_from_session_id(session_id: str | None) -> UUID | int | None:
    """This method is used to get user id from session_id.


    :param session_id: A session id.
    :return: A user id or None.
    """

yet immediately after the call to get_obj, it returns the user ID, which in this case is still a string:

# ref: https://github.com/vsdudakov/fastadmin/blob/v0.10.0/fastadmin/api/service.py#L86
    return user_id

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions