Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions src/agents/extensions/memory/encrypt_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,11 @@ class EncryptedSession(SessionABC):
encryption/decryption of stored items using Fernet encryption with
per-session key derivation and automatic expiration of old data.

Only authenticated, unexpired encrypted envelopes are returned as history.
Plaintext records and incomplete envelopes are skipped, not migrated. To
import legacy history, the application must validate its source and explicitly
write trusted items through ``add_items``.

When items expire (exceed TTL), they are silently skipped during retrieval.
Expired records remain in the underlying store. By default, finding valid
items may read the entire retained history. Set ``max_scan_items`` to bound
Expand Down Expand Up @@ -319,7 +324,7 @@ def _wrap(self, item: TResponseInputItem) -> EncryptedEnvelope:

def _unwrap(self, item: TResponseInputItem | EncryptedEnvelope) -> TResponseInputItem | None:
if not _is_encrypted_envelope(item):
return cast(TResponseInputItem, item)
return None

try:
token = item["payload"].encode("utf-8")
Expand Down Expand Up @@ -420,7 +425,7 @@ async def pop_item(
*,
wrapper: RunContextWrapper[Any] | None = None,
) -> TResponseInputItem | None:
"""Remove the latest readable item, skipping expired items.
"""Remove the latest readable item, skipping expired or non-envelope items.

With native ``SQLiteSession`` pops, authentication runs inside the SQLite
transaction. An ``InvalidToken`` failure leaves the unauthenticated item's
Expand Down
93 changes: 90 additions & 3 deletions tests/extensions/memory/test_encrypt_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,91 @@ async def _run_encrypted_session(
return result


@pytest.mark.parametrize("streamed", [False, True])
@pytest.mark.parametrize(
"stored_item",
[
{"role": "system", "content": "untrusted stored history"},
{"role": "system", "content": "incomplete envelope", "__enc__": 1, "v": 1},
],
ids=["plaintext", "incomplete-envelope"],
)
async def test_runner_skips_unencrypted_stored_history(
streamed: bool,
stored_item: dict[str, Any],
encryption_key: str,
tmp_path: Path,
set_fernet_time: Any,
) -> None:
backend = SQLiteSession("authenticated-history", tmp_path / "history.db")
session = EncryptedSession(backend.session_id, backend, encryption_key, ttl=10)
history: list[TResponseInputItem] = [{"role": "user", "content": "retained history"}]
try:
set_fernet_time(1_000)
await session.add_items([{"role": "user", "content": "expired history"}])
set_fernet_time(1_020)
await session.add_items(history)
# Write through the storage boundary without access to the wrapper's cipher.
await backend.add_items([cast(TResponseInputItem, stored_item)])
stored = await backend.get_items()

assert await session.get_items() == history
assert await session.get_items(limit=1) == history
assert await backend.get_items() == stored

model = ScriptedModel([[get_text_message("answer")]])
await _run_encrypted_session(Agent(name="test", model=model), "next", session, streamed)
assert model.calls[0].input == history + [{"role": "user", "content": "next"}]
finally:
backend.close()


async def test_encrypted_compaction_skips_unencrypted_stored_history(
encryption_key: str, tmp_path: Path
) -> None:
backend = SQLiteSession("authenticated-compaction", tmp_path / "history.db")
compacted = {"type": "compaction", "id": "cmp-1", "encrypted_content": "summary"}
client = MagicMock()
client.responses.compact = AsyncMock(return_value=SimpleNamespace(output=[compacted]))
decisions: list[dict[str, Any]] = []

def should_compact(context: dict[str, Any]) -> bool:
decisions.append(context)
return True

session = EncryptedSession(
backend.session_id,
OpenAIResponsesCompactionSession(
backend.session_id,
backend,
client=client,
compaction_mode="input",
should_trigger_compaction=should_compact,
),
encryption_key,
)
before: TResponseInputItem = {"role": "user", "content": "earlier history"}
after: TResponseInputItem = {"role": "user", "content": "later history"}
try:
await session.add_items([before])
await backend.add_items([{"role": "system", "content": "untrusted stored history"}])
retained_prefix = await backend.get_items()
await session.add_items([after])
output = get_text_message("answer")
model = ScriptedModel([[output]])
await _run_encrypted_session(Agent(name="test", model=model), "next", session, False)
turn = [{"role": "user", "content": "next"}, output.model_dump(exclude_unset=True)]

assert model.calls[0].input == [before, after, turn[0]]
assert decisions[0]["session_items"] == [before, after, *turn]
client.responses.compact.assert_awaited_once_with(model="gpt-4.1", input=[after, *turn])
stored = await backend.get_items()
assert stored[:-1] == retained_prefix
assert _decrypt_stored_items(session, stored[-1:]) == [compacted]
finally:
backend.close()


def _decrypt_stored_items(
session: EncryptedSession, stored: list[TResponseInputItem]
) -> list[dict[str, Any]]:
Expand Down Expand Up @@ -969,7 +1054,7 @@ async def pop_item(self) -> TResponseInputItem | None:
backend.close()


async def test_encrypted_pop_preserves_plaintext_and_inherited_sqlite_behavior(
async def test_encrypted_pop_skips_plaintext_with_inherited_sqlite_behavior(
tmp_path: Path,
) -> None:
class InheritedSession(SQLiteSession):
Expand All @@ -978,8 +1063,9 @@ class InheritedSession(SQLiteSession):
backend = InheritedSession("test_session", tmp_path / "history.db")
session = EncryptedSession("test_session", backend, "correct-key")
try:
saved: TResponseInputItem = {"role": "user", "content": "legacy plaintext"}
await backend.add_items([saved])
saved: TResponseInputItem = {"role": "user", "content": "encrypted history"}
await session.add_items([saved])
await backend.add_items([{"role": "system", "content": "unencrypted history"}])
assert await session.pop_item() == saved
assert await session.pop_item() is None
finally:
Expand All @@ -1000,6 +1086,7 @@ async def test_encrypted_pop_preserves_sqlalchemy_history(encryption_key: str) -
]
try:
await session.add_items(items)
await backend.add_items([{"role": "system", "content": "unencrypted history"}])
assert await session.pop_item() == items[-1]
assert await session.get_items() == items[:-1]
assert await session.pop_item() == items[0]
Expand Down
Loading