AI & Agent Dev Bug Sandbox logo
AI & Agent Dev Bug Sandbox
Back to Radar

PIIMiddleware Only Inspects Newest Message, Allowing Earlier PII To Bypass Detection

PIIMiddleware's state hooks scan only the most recent message of each type, so PII in earlier human messages, tool results, or assistant messages is passed to the model unredacted and 'block' strategy does not raise. This can leak sensitive data when history is supplied by external systems or multi-agent handoffs.

highConfidence 95%LangchainAffected V1.4.2

Origin Analysis

The middleware's before_model and after_model methods use backward/forward scans that stop after finding the newest message of the target type, so earlier messages are never examined.
1. Instantiate PIIMiddleware with strategy='block' and apply_to_input=True. 2. Pass a conversation history containing an early HumanMessage with an email address and a later HumanMessage without PII. 3. Invoke create_agent with this history. 4. Observe no PIIDetectionError and the model prompt contains the raw email. Similar failures occur for apply_to_tool_results with earlier ToolMessage and apply_to_output with earlier AIMessage.

Fixing Code Block

Edge Case Audit

Performance: scanning all messages on every hook call may increase overhead for very long conversations; consider tracking processed message IDs or limiting to new messages. Concurrency: if state messages are mutated concurrently, scanning all messages could lead to race conditions; ensure state updates are serialized. Rollback: reverting this fix will reintroduce the vulnerability; do not downgrade to affected versions. Upgrade: applications that previously relied on passing pre-redacted history may now trigger block exceptions if that history still contains PII; ensure all history is already redacted or adjust strategy. Cross-platform: model_copy requires Pydantic v2, which is standard in current LangChain; if using a different version, a fallback is needed. Async: async variants of these hooks, if any, must be updated similarly. Test with checkpointer: the fix should work with existing redacted histories due to idempotent redaction.

Ecosystem Topology