Skip to course content
Free LangChain course

LangChain for LLM Applications and RAG

Unit 08.02: Keeping one user's state out of another's

Session state keyed on a session id alone is session state a guessed id can read.

Key on user and session together

The lookup takes both, and the user id comes from your authenticated session rather than from the request.

The code shows two users with the same session id and no crossover.

SESSIONS = {}


def get_history(session_id, user_id):
    """Key on BOTH -- a session id alone is guessable or reusable."""
    key = (user_id, session_id)
    return SESSIONS.setdefault(key, [])


get_history("s-1", "user-a").append("user A: my account is ACC-1187")
get_history("s-1", "user-b").append("user B: my account is ACC-9002")

for (user, session), history in SESSIONS.items():
    print(f"{user} / {session}: {history}")

leaked = get_history("s-1", "user-b")
print(f"\nuser-b sees user-a's history: "
      f"{'user A: my account is ACC-1187' in leaked}")

# Keying on session id alone means a guessed or reused id reads another user's
# conversation -- including whatever account numbers it contains. The user id
# must come from your authenticated session, never from the request body.

Both users used session s-1 and neither sees the other's history, because the key is the pair. Keyed on the session alone, user B would read user A's conversation - including the account number in it.

The important half is where the user id comes from. Taken from the request body it is not an authentication check, it is a suggestion - and an attacker supplies whichever value they like.

The mistake this prevents

The mistake is using a long random session id and treating unguessability as the control. Session ids leak: they appear in URLs, in logs, in screenshots, in support tickets. The user id from your authenticated session is what actually enforces the boundary.

Takeaway

Key session state on the authenticated user id and the session id together. Never take the user id from the request, and never rely on an id being hard to guess.