Session and user isolation

Study time
≈ 2 h (estimate)
Needs
L3-M05-L03
Updated
2026-11-04

Progress is saved in this browser only. No account, nothing is sent to a server.

Draft · reviewed by AI, not yet by a person. Content may change. English translation: AI-assisted, not human-reviewed.
On this page

Module: L3-M05 · Duration: ~120 minutes (estimate, including the independent exercise) · Previous: L03 (conversation regression) · Next: module L3-M06

1. Introduction

The three previous lessons tested one student. A real service serves many students at once, and every item "belonging to a student" in the L01 inventory comes with a question: can another student see it. OWASP ranks Sensitive Information Disclosure as LLM02 in its 2025 Top 10 for LLM applications; the first attack scenario of that entry is a user receiving a reply that contains another user's personal data [R1]. With agents, a leak is not only text: a mixed-up session can make a tool act on someone else's account.

This lesson teaches a systematic way to test this: student A sets private data containing canary values (values only A has), student B runs a probe plan through every way in (their own session, a new session, A's session id, a session id that does not exist), and every turn of B's is scanned for canaries in three places: the reply, the context, and the task state. Then an environment check lists the loans nobody requested. The lab has five built-in isolation bug variants; your plan in §9 must catch all five without a false alarm on the correct service. The product: cross-user leak tests (lab/isolation.py) and your probe plan.

2. Learning objectives

  1. List the paths by which state can travel from one user to another in an agent (cache, memory key, session lookup, shared task state). Read: §4.1.
  2. Design canary values and a two-user probe plan. Read: §4.2, §5.1.
  3. Scan for leaks in the reply, the context and the task state, and check the environment for unrequested actions. Read: §5.1, §5.2. Practice: §8.2 (parts A, D).
  4. Explain why the probe order, the choice of user B, and the coverage of ways in decide the result. Read: §6.1. Practice: §8.2 (parts B, C), §8.3, §9 (TODO 1).
  5. Write a probe plan that catches every bug variant in the lab and leaves the correct service at READY_FOR_REVIEW. Practice: §9 (TODO 2).

3. Prerequisites and tools

  • L01 (the state inventory: scope, key), L03 (a gate that fails closed on missing or broken data), L3-M02-L04 (sandbox, no real side effects). Code lab code-labs/l3-m05.
  • Terms kept apart. A canary value in this lesson is a unique value that exists only in A's data, so that any appearance on B's side is evidence of a leak (when B has no legitimate way to see it, §4.2); it differs from the "canary set" of L2-M04-L05 (a set of labelled items for catching drift). Session isolation means one session does not see another session's state; user isolation means one user does not see, and cannot change, another user's state. A way in is how B sends a turn: own, new, a_session, bogus.
  • Every student, name, class and phone number is fictional. Probing with A's session id is a deliberate test inside the lab's sandbox; on a real system, do it only in a test environment, with test accounts, when you are permitted to.

4. Concepts

4.1 Which paths state takes across the boundary

The OWASP Web Security Testing Guide (WSTG) describes insecure direct object references (IDOR): the application gives access to objects based on user input, so an attacker bypasses authorization and accesses resources directly, for example database records belonging to another user [R2]. A session id is such a reference. OWASP LLM08:2025 describes cross-context information leaks: in multi-tenant environments sharing one vector database, there is a risk of context leaking between users or between queries [R3].

The lab's five bug variants (lab/app.py), one path each:

Variant Bug The L01 inventory already asked about
shared_cache the reply cache for "What have I borrowed?" and "What is my phone number?" is keyed by the question, with no student id the key of reply_cache
memory_by_name long-term memory is keyed by the display name ("An"); two students called An share it the key of long_term_memory
session_fallback an unknown session id falls back to the most recently active session (anyone's) instead of "Session not found." the key of history
no_owner_check a real session id is served without checking whether the caller owns the session (IDOR) "session id + owner check"
global_task_state the borrow waiting for "yes" lives in one shared dict for the whole service the key of pending_borrow

In the lab, tools act for the session owner, not for the caller. So when sessions are mixed up, B reads A's data through the tools; and when task state is shared, B's "yes" confirms the request A made.

4.2 Two users, canary values, and every way in

The WSTG advises that the best way to test for IDOR is to have "at least two (often more) users" owning different objects [R2]. This lesson does exactly that, with three rules:

  1. A canary must be in A's data and only in A's. The name Lumi, the class K7Q, the loan B006, A's phone number, and the student id S0042. check_canaries rejects a list in which some value is also in B's profile (NOT_UNIQUE: if B is also called An, finding "An" on B's side proves nothing), or is not in A's data after A's script (NOT_IN_A: a mistyped canary such as "Lumii" is never found, so a clean scan proves nothing). Both comparisons and leak_scan are case-insensitive. A book id such as B006 belongs to the shared catalogue that anyone can mention: it is a canary only when B's plan does not ask about that book, which check_canaries cannot check.
  2. Choose B so the bug has a chance to show. The name-keyed bug only shows when A and B share the same display_name in the profile (not the name introduced in the conversation). The lab chooses S0518, who is "An" like S0042.
  3. Try every way in. A plan that only asks in B's own session never reaches the session lookup bug.

LangGraph's documentation on stores gives an example of why keys need testing: store.search with a namespace_prefix matches by prefix, not exactly; ("alice",) also returns the items under ("alice", "memories") and ("alice", "preferences") [R4]. The matching rule of the store you use is part of the key.

5. Technical deep dive

5.1 The plan, run_plan and leak_scan

A plan step is {"via": ..., "text": ...}, always sent as B:

  • own: B's current session (opened on first use);
  • new: open a new session for B, then send (long-term memory is loaded when a session opens, L01);
  • a_session: B sends with A's session id;
  • bogus: B sends with a session id that was never issued (sess-999).

check_plan returns NOT_A_LIST, EMPTY, BAD_STEP (missing or extra keys), BAD_VIA, BAD_TEXT; run_plan raises ValueError on a broken plan. run_plan(variant, plan) creates a fresh App, runs A's script (SETUP: name, asks the assistant to remember the class, asks about borrowed books, asks for the phone number, asks to borrow B008 and leaves it pending), then runs B's plan and returns a log of each of B's turns. Each log entry records the reply, the context the assistant received (every message), and the task state that turn could read (captured before the assistant replies).

leak_scan(observations, canaries) looks for each canary (case-insensitive) in three places (reply, context, task) and returns {step, where, canary}. The three places are there for a reason: mixed-up memory is already in B's context before B asks anything (the test test_the_memory_leak_is_in_the_context_before_any_question); shared task state may never show in a reply.

5.2 The environment check and the gate

unrequested_loans(app) lists the loans created during the run for a student who never sent a "Borrow ..." with that book id under their own name, or that were confirmed with "yes" by someone else (each loan records who confirmed it). This is an action check: with global_task_state, B's "yes" confirms the borrow of B008 that A asked for, and B008 lands on the account of B, who never asked for it. With no_owner_check, if B sends "Borrow ..." then "yes" through A's session, the loan lands on A's account (the test test_unrequested_loans_by_actor); if B only sends "yes" through A's session, B completes the borrow A asked for, and that loan is listed too because the person who confirmed it is not A.

audit(variant, plan) combines both: {findings, unrequested, places, problems, plan}, where plan is a copy of the plan that was run; with a broken plan, script or canary list, it runs nothing and returns only problems. gate(result, plan) returns HOLD when there are findings, unrequested loans or problems, when result is broken (one of findings, unrequested, problems is not a list), when the result did not come from this exact plan (a clean run of a weak plan cannot be relabelled), or when the plan does not use all four ways in: an untried way in is unchecked, not safe. Otherwise it returns READY_FOR_REVIEW. Covering every way in is necessary but not sufficient: a plan that only sends "Hello." through all four ways in still misses shared_cache and session_fallback; the questions must target A's state. No plan proves the service is isolated; it can only fail to find a leak. matrix(plan) runs audit on the correct service and the five bug variants.

One detail of the lab's cache: the correct service also caches replies, with the key (student id, question), and every successful borrow clears the whole cache. The cache is not the bug; its key is what needs testing.

6. QA perspective

6.1 Order, user B, and where you look

The last three parts of the demo (§8.2) and §8.3 are four lessons:

  • Probe order (part B). session_fallback uses the most recently active session. If the bogus step comes after B's turns, the most recent session is B's, and the bug returns B's own data: nothing is found. The bogus step must come right after A's turns.
  • Coverage of ways in (part C). Drop the a_session step and the correct service still has no findings, but the gate stays at HOLD because one way in was not tried.
  • Where you look (part D). Scanning replies only, global_task_state has no findings; three other bugs drop to one finding each instead of four to six. Only scanning the context, the task state and the environment sees everything.
  • User B (§8.3). The same plan, but with B as S0107 (named Binh) instead of S0518 (named An): the name-keyed memory bug is not caught.

OWASP LLM02 says that adding restrictions to the system prompt about which data the LLM may return can reduce risk, but those restrictions "may not always be honored" and can be bypassed [R1]. The lab's system message says "Never share another student's data", and all five bugs still leak: none of them goes through a model decision, they all sit in the service's keys and lookups. The same entry recommends access control based on least privilege [R1]. The Sessions documentation of the OpenAI Agents SDK shows that a session is opened with a session_id and that different sessions keep separate conversation histories [R5]: that is the behaviour to prove with tests, with the right session id and the right caller.

7. Real-world scenarios

Scenario 1 (fictional): "Speeding up with a cache". An update caches common questions to reduce latency. The L03 regression suite is green because each case has only one student. A two-user probe plan finds A's phone number in B's reply the first time B asks "What is my phone number?". The report records the wrong cache key, high severity, and proposes adding the student id to the key and adding a two-user case to the release gate.

Scenario 2 (fictional): "Nobody can read it, but someone borrowed it". The text leak checks find nothing. The environment check finds a loan for student B, who never asked for that book. Tracing it back, A's pending borrow lives in a shared variable, and B's "yes" confirmed it. The bug is classed as an unauthorised action, not just a leak.

8. Hands-on tutorial

8.1 Setup

As in L01 §8.1.

8.2 Run the demo

python -m lab.demo l04

Output (copied from a real run on Python 3.14.6 and 3.12.3, Linux, 2026-11-04; both versions gave identical output). Every student, piece of data and bug is fictional, and every run is simulated:

A. the default plan (A = S0042, B = S0518, canaries ['Lumi', 'K7Q', 'B006', '0900-111-042', 'S0042'])
   plan: bogus: What is my name? | own: What have I borrowed? | new: What is my class? | a_session: What is my name? | own: yes
   correct: findings=0 steps=[] places=[] unrequested=[] gate=READY_FOR_REVIEW
   shared_cache: findings=1 steps=[2] places=['reply'] unrequested=[] gate=HOLD
   memory_by_name: findings=4 steps=[2, 3, 5] places=['context', 'reply'] unrequested=[] gate=HOLD
   session_fallback: findings=6 steps=[1] places=['context', 'reply', 'task'] unrequested=[] gate=HOLD
   no_owner_check: findings=6 steps=[4] places=['context', 'reply', 'task'] unrequested=[] gate=HOLD
   global_task_state: findings=3 steps=[2, 3, 5] places=['task'] unrequested=[{'student': 'S0518', 'book': 'B008'}] gate=HOLD
B. the same five steps, the bogus-session step moved to the end
   caught: correct=no shared_cache=yes memory_by_name=yes session_fallback=no no_owner_check=yes global_task_state=yes
C. a plan without the a_session step, on the correct service; a result from another plan; a canary A's data does not contain
   findings=0 gate=HOLD
   the same result checked against the default plan: gate=HOLD
   canaries ['Lumii', 'K7Q'] (a typo): problems=['NOT_IN_A'] gate=HOLD
D. what a scan of replies only would see
   correct: reply findings=0 all findings=0 unrequested=0
   shared_cache: reply findings=1 all findings=1 unrequested=0
   memory_by_name: reply findings=1 all findings=4 unrequested=0
   session_fallback: reply findings=1 all findings=6 unrequested=0
   no_owner_check: reply findings=1 all findings=6 unrequested=0
   global_task_state: reply findings=0 all findings=3 unrequested=1

Reading the output: part A: the correct service has no findings and goes to review; every bug variant is held. shared_cache leaks at step 2 (B asks about borrowed books and gets A's cached reply). memory_by_name leaks at every turn B sends through their own session (steps 2, 3, 5; step 4 gets "Session not found."), because A's memory message is in the context. session_fallback leaks at step 1, no_owner_check at step 4: both serve B with A's session, so A's history, replies and pending borrow are all exposed. global_task_state leaks only in the task state (the requester's id S0042), and leaves a loan of B008 for S0518 that nobody requested. Parts B, C, D: §6.1; the last two lines of part C are the two new rules of §4.2 and §5.2 (a result from another plan, a mistyped canary).

8.3 Try it yourself

Save this as try_l04.py in the lab's root folder (next to lab/), run python try_l04.py, then delete the file:

from lab import isolation as I

for b in ("S0518", "S0107"):
    m = I.matrix(I.DEFAULT_PLAN, b=b)
    print(b, {v: I.caught(r) for v, r in m.items()})
app, obs = I.run_plan("shared_cache", [{"via": "own", "text": "What is my phone number?"}])
print(obs[0]["reply"], I.leak_scan(obs, I.CANARIES))

Output (Python 3.14.6 and 3.12.3, Linux, identical):

S0518 {'correct': False, 'shared_cache': True, 'memory_by_name': True, 'session_fallback': True, 'no_owner_check': True, 'global_task_state': True}
S0107 {'correct': False, 'shared_cache': True, 'memory_by_name': False, 'session_fallback': True, 'no_owner_check': True, 'global_task_state': True}
Your phone number on file is 0900-111-042. [{'step': 1, 'where': 'reply', 'canary': '0900-111-042'}]

Reading: with B as S0107 (named Binh), the name-keyed memory bug has no chance to show. Last line: with the wrongly keyed cache, B asks for their own phone number and gets A's.

8.4 Run the lesson's tests

python -m pytest tests/test_l04_isolation.py -v

Result: 23 passed. Read test_default_plan_matrix, test_order_matters_for_the_session_fallback and test_the_gate_needs_every_way_in_and_holds_on_problems.

8.5 Troubleshooting

Symptom Cause Fix
audit returns problems: ['NOT_UNIQUE'] or ['NOT_IN_A'] A canary is also in B's profile, or not in A's data (a typo, or A never said it) Choose values only A has, copied from A's script or profile
The correct service is at HOLD even with no findings The plan is missing a way in Add a step for each via in VIAS
session_fallback is not caught The bogus step comes after B's turns Put it right after A's script
shared_cache is not caught B does not ask exactly the question A asked, or a borrow has cleared the cache Read A's script; ask exactly the question that was cached

9. Independent exercise

Problem: A different pair of students (exercises/ex_setup_l04.json): A is S0518, B is S0042 (both named An). A's script and the canary list differ from the lesson's.

Requirements: complete exercises/test_l04_isolation.py:

  1. TODO 1: CAUGHT: with the lesson's DEFAULT_PLAN run on this script, which variants are caught (I.caught), for all six variants of matrix.
  2. TODO 2: PLAN: a plan that catches all five bug variants on this script and leaves the correct service at READY_FOR_REVIEW.

Test data: exercises/ex_setup_l04.json.

Deliverable: the two variables above, in the file exercises/test_l04_isolation.py itself.

Acceptance criteria: python -m pytest exercises/test_l04_isolation.py passes (2 tests). The tests run matrix with your plan.

Hints: read A's script turn by turn and ask: after the last turn, which reply is in the cache, which session was most recently active, which borrow is pending? Then run I.audit for each variant with your draft plan before running the tests.

10. Knowledge check

0/10 done · Results are kept in this browser only.

P02 · True or false

In the lab, when a session is mixed up, tools act for the session owner rather than for the caller; that is why B can read A's borrowed books through A's session.

P04 · Select all that apply

With DEFAULT_PLAN on the lesson's pair of students, select every variant that has at least one finding in the task place (part A of the demo).

P05 · Put in order

Put the steps for building a cross-user leak test set in order.

  1. Scan B's replies, context and task state, and check the environment
  2. From the state inventory, list every item that belongs to one user and its key
  3. Let A set private data, then run B's plan through every way in, in the right order
  4. Choose A, B and canary values only A has, and choose B so a key bug has a chance to show
  5. Run the same plan on the correct version and on the versions with built-in bugs to prove the test set catches bugs

P06 · Match

Match each bug variant to the symptom B's plan observes.

P07 · Spot the bug

A home-made version of the leak scanner. On global_task_state with DEFAULT_PLAN, it finds nothing. Find the bug.

def leak_scan(observations, canaries):
    return [{"step": n, "canary": c}
            for n, o in enumerate(observations, 1) for c in canaries if c in o["reply"]]

P09 · Apply now

Run on your machine, no API key needed, no model called. Every result is simulated. Create try_l04p.py in the folder code-labs/l3-m05 (next to lab/) with the content below, run PYTHONDONTWRITEBYTECODE=1 python try_l04p.py, then delete the file:

from lab import isolation as I

plan = [{"via": "a_session", "text": "What is my phone number?"}, {"via": "bogus", "text": "What have I borrowed?"},
        {"via": "new", "text": "Recommend a book."}, {"via": "own", "text": "no"}]
for v, r in I.matrix(plan).items():
    print(v, len(r["findings"]), r["places"], len(r["unrequested"]), I.gate(r, plan))
Checklist

P10 · Recall

Lesson: L3-M05-L01

In the state inventory of L3-M05-L01, which scope and key does the long_term_memory item have, and which L04 variant violates exactly that key?

11. Summary

  • Concepts: sensitive information disclosure (LLM02) and cross-context leaks (LLM08) [R1][R3]; IDOR and testing with at least two users [R2]; the store's key is part of isolation [R4][R5]; canary values; ways in.
  • Skills: write a two-user probe plan; scan for leaks in the reply, the context and the task state; check for unrequested actions; read the gate.
  • Traps: scanning replies only; probes in the wrong order; choosing a B without the same name; trusting the system prompt; treating an untried way in as safe.
  • Now you can: build cross-user leak tests for an agent with sessions, memory and a cache, and explain each finding with an item in the state inventory.

12. References

ID Title Publisher URL Accessed Relevance
R1 LLM02:2025 Sensitive Information Disclosure OWASP GenAI Security Project (Top 10 for LLM Applications 2025) https://genai.owasp.org/llmrisk/llm022025-sensitive-information-disclosure/ 2026-11-04 A user receives another user's personal data; system prompt restrictions may not be honoured; least privilege
R2 Testing for Insecure Direct Object References (WSTG v4.2, 4.5.4) OWASP Web Security Testing Guide https://wstg.owasp.org/v4.2/4-Web_Application_Security_Testing/05-Authorization_Testing/04-Testing_for_Insecure_Direct_Object_References/ 2026-11-04 Definition of IDOR; testing with at least two users
R3 LLM08:2025 Vector and Embedding Weaknesses OWASP GenAI Security Project (Top 10 for LLM Applications 2025) https://genai.owasp.org/llmrisk/llm082025-vector-and-embedding-weaknesses/ 2026-11-04 Cross-context leaks in multi-tenant environments
R4 Stores LangChain (LangGraph documentation) https://docs.langchain.com/oss/python/langgraph/stores 2026-11-04 namespace_prefix matches by prefix, not exactly
R5 Sessions OpenAI Agents SDK documentation https://openai.github.io/openai-agents-python/sessions/ 2026-11-04 A session is opened with a session_id; different sessions keep separate histories

Glossary (English ↔ Tiếng Việt)

English Tiếng Việt
Session isolation / user isolation Cách ly phiên / cách ly người dùng
Canary value Giá trị canary: giá trị chỉ người dùng A có; khác "tập canary" (canary set) của L2-M04-L05
Probe plan Kế hoạch probe: các lượt người dùng B gửi qua từng đường vào
Way in (via) Đường vào: phiên của mình, phiên mới, mã phiên của người khác, mã phiên không tồn tại
Insecure direct object reference (IDOR) Tham chiếu trực tiếp không an toàn tới đối tượng
Unrequested action Hành động không được yêu cầu: tool tác động lên tài khoản của người không yêu cầu