Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

4.2 KB
Raw Blame
"""
Shared utilities for resolving the current user's DB password under FastAPI.

``get_user_password`` retrieves the user's password from the FastAPI session
password store.

The Flask-era version of this helper had a 3-source fallback chain
(session_password_store → Flask g.user_password → temp_auth_store).
The Flask sources became dead after the FastAPI migration:
``has_request_context()`` always returns False without Flask running,
and there is no FastAPI middleware that mirrors password into a
contextvar-accessible "g". Under FastAPI, the password is written to
``session_password_store`` directly during login (auth.py) keyed by
``session_id``, so Source 1 covers every authenticated request path.

``resolve_user_password`` builds on it with the encryption-aware guard the
research entry points share: it returns ``(password, session_expired)`` so
a caller can reject a run when an encrypted DB has no available password.
"""

from typing import Optional, Tuple

from loguru import logger


def get_user_password(username: str) -> Optional[str]:
    """Retrieve the user's database password for the current request.

    Reads ``session_id`` from the contextvar populated by
    ``DatabaseMiddleware`` and looks up the password in
    ``session_password_store``. If the contextvar's username doesn't
    match the requested one (cross-user service call), returns None
    rather than widening to a different session.

    Returns ``None`` when no password can be found — callers must decide
    whether that is acceptable (e.g. non-encrypted databases) or an
    error (encrypted databases → 401).
    """
    from ...database.session_passwords import session_password_store
    from ...utilities.request_context import (
        get_current_session_id,
        get_current_username,
    )

    current_session_id = get_current_session_id()
    if not current_session_id:
        return None

    # If a service call passes a different username than what's in the
    # request context, don't use the contextvar's session_id — it
    # belongs to a different user. Returning None here is intentional:
    # widening to "any session for this user" would be a cross-session
    # leak (e.g. mid-password-change a stale password could be returned
    # for the wrong session).
    ctx_username = get_current_username()
    if ctx_username is not None and ctx_username != username:
        return None

    return session_password_store.get_session_password(  # gitleaks:allow
        username, current_session_id
    )


def resolve_user_password(username: str) -> Tuple[Optional[str], bool]:
    """Resolve the user's DB password for starting a research run.

    Returns ``(password, session_expired)``:

    - ``session_expired`` is ``True`` only when the database is encrypted
      and no password is available. The caller MUST reject the request
      (e.g. a 401 telling the user to log back in) because the research's
      background DB and metric writes would otherwise be silently dropped
      (issue #4457) — research would appear to run while every metric write
      fails. Trigger: session-password-store TTL expiry or a server/
      container restart while the session cookie is still valid.
    - For unencrypted databases ``session_expired`` is always ``False``;
      the returned ``password`` may legitimately be ``None``.

    Centralises the guard that the direct (``/start_research``), follow-up,
    and chat research entry points all need, so the encryption-aware
    decision and its logging live in one place instead of being copied
    (and risking divergence) across routes. Each route still formats its
    own error response, because their frontends expect different shapes.
    """
    from ...database.encrypted_db import db_manager

    password = get_user_password(username)  # gitleaks:allow
    if not password and db_manager.has_encryption:
        logger.error(
            f"No password available for user {username} with encrypted "
            "database - cannot start research (session password expired or "
            "lost after server restart)"
        )
        return None, True
    if not password:
        logger.warning(
            f"No password available for metrics access for user {username} "
            "(unencrypted database)"
        )
    return password, False