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.

5.7 KB
Raw Blame
"""
Session-based password storage for metrics access.

This module provides a way to temporarily store passwords in memory
for the duration of a user's session, allowing background threads
to access encrypted databases for metrics writing.

SECURITY NOTES:
1. Passwords are only stored in memory, never on disk
2. Passwords are stored in plain text in memory (encryption removed as it
   provided no real security benefit - see issue #593)
3. Passwords are automatically cleared on logout
4. This is only used for metrics/logging, not user data access
"""

from typing import Optional

from loguru import logger

from .credential_store_base import CredentialStoreBase


class SessionPasswordStore(CredentialStoreBase):
    """
    Stores passwords temporarily for active sessions.
    Used to allow background threads to write metrics to encrypted databases.
    """

    def __init__(self, ttl_hours: int = 24):
        """
        Initialize the session password store.

        Args:
            ttl_hours: How long to keep passwords (default 24 hours)
        """
        super().__init__(ttl_hours * 3600)  # Convert to seconds

    def store_session_password(
        self, username: str, session_id: str, password: str
    ) -> None:
        """
        Store a password for an active session.

        Args:
            username: The username
            session_id: The Flask session ID
            password: The password to store
        """
        key = (username, session_id)
        self._store_credentials(
            key, {"username": username, "password": password}
        )
        logger.debug(f"Stored session password for {username}")

    def get_session_password(
        self, username: str, session_id: str
    ) -> Optional[str]:
        """
        Retrieve a password for an active session.

        Args:
            username: The username
            session_id: The Flask session ID

        Returns:
            The decrypted password or None if not found/expired
        """
        key = (username, session_id)
        result = self._retrieve_credentials(key, remove=False)
        return result[1] if result else None

    def clear_session(self, username: str, session_id: str) -> None:
        """
        Clear password for a specific session (on logout).

        Args:
            username: The username
            session_id: The Flask session ID
        """
        key = (username, session_id)
        self.clear_entry(key)
        logger.debug(f"Cleared session password for {username}")

    def get_any_session_password(self, username: str) -> Optional[str]:
        """
        Retrieve a password from any active session for this user.

        Used by FastAPI routes where the session_id is not easily
        accessible (no Flask request context). Checks all stored
        sessions for the user and returns the first valid password.

        Args:
            username: The username

        Returns:
            The decrypted password or None if not found/expired
        """
        import time

        with self._lock:
            for key in list(self._store.keys()):
                if key[0] == username:
                    entry = self._store.get(key)
                    if entry and time.time() <= entry["expires_at"]:
                        return entry["password"]
                    if entry:
                        # Expired — clean up
                        del self._store[key]
        return None

    def clear_all_for_user(self, username: str) -> None:
        """Remove all stored passwords for a user (idle connection cleanup)."""
        with self._lock:
            keys_to_remove = [k for k in self._store if k[0] == username]
            for k in keys_to_remove:
                del self._store[k]

    # Implement abstract methods for compatibility
    def store(self, username: str, session_id: str, password: str) -> None:
        """Alias for store_session_password."""
        self.store_session_password(username, session_id, password)

    def retrieve(self, username: str, session_id: str) -> Optional[str]:
        """Alias for get_session_password."""
        return self.get_session_password(username, session_id)


# Global instance
session_password_store = SessionPasswordStore()


def capture_request_db_password(username: str) -> Optional[str]:
    """Best-effort capture of the encrypted-DB password from the request
    thread.

    ``ThreadPoolExecutor.submit`` does NOT copy the calling thread's
    ``ContextVar`` snapshot, so background workers cannot recover the
    password through the usual request-context probes. Callers that need
    to hand a password to a worker (or to a service like the RAG factory
    that must open the encrypted DB to read index config) capture it here
    while still on the request thread and pass it explicitly.

    Returns ``None`` if the password cannot be located — on encrypted-DB
    installs the caller should then skip the DB-touching work rather than
    fail loudly.
    """
    try:
        from ..utilities.request_context import get_current_session_id

        session_id = get_current_session_id()
        if not session_id:
            # No request context on this thread. Main returned None here,
            # and that contract matters: falling back to a username-wide
            # scan would hand a caller with no session whatsoever a live
            # password scavenged from any other open session. Callers that
            # legitimately need a password off-request must capture it on
            # the request thread and pass it explicitly.
            return None
        return session_password_store.get_session_password(username, session_id)
    except Exception:
        logger.debug(
            "Failed to capture DB password from request context",
            exc_info=True,
        )
    return None