Spaces:
Running

WorkPilot-AI / core /memory /secure.py
Aynkhn's picture
Deploy WorkPilot demo
fd5dd94 verified
Raw History Blame Contribute Delete
7.85 kB
"""OWASP-style controls applied to every long-term memory write (memory poisoning, ASI06).
``prepare_write`` runs, in order:
1. **forbidden-content lint**: memory must never hold live business data. Values (and keys)
that look like order statuses, stock levels, amounts/prices or payment states are
rejected: those facts are always read live from the system of record through tools;
2. **PII redaction** (``core.privacy.redact``): CNIC, phone, email, IBAN, card numbers;
3. **size cap** on the serialized value (``WP_MEMORY_MAX_BYTES``);
4. **expiry**: every item gets ``expires_at`` (default TTL, capped at the max TTL);
5. **checksum**: sha256 over (namespace, key, value), stored with the row and verified on
every read, so a row edited outside this module (tampering, poisoning through another
path) is detected and not returned.
"""
from __future__ import annotations
import re
from collections.abc import Iterable
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from typing import Any
from core.config import get_settings
from core.privacy.redact import redact_value
from core.tools.preview import canonical_json, sha256_hex
class MemoryRejected(ValueError):
"""A write that violates a memory control. ``reasons`` says which."""
def __init__(self, reasons: Iterable[str]) -> None:
self.reasons = list(reasons)
super().__init__("; ".join(self.reasons))
class MemoryIntegrityError(Exception):
"""A stored item whose checksum does not match its content."""
# --------------------------------------------------------------- forbidden-content lint
_ORDER_STATUS_WORDS = (
r"pending|confirmed|processing|shipped|dispatched|delivered|cancell?ed|returned|"
r"in[ -]transit|out for delivery|on hold|failed delivery|rto|returned to origin"
)
_PAYMENT_WORDS = (
r"paid|unpaid|refunded|partially refunded|remitted|collected|outstanding|overdue|"
r"pending|failed|due|received|declined|captured|"
r"payment (?:pending|failed|received|due|declined|captured|confirmed)|"
r"cod (?:pending|collected|remitted|unpaid)"
)
_FORBIDDEN_TEXT: list[tuple[str, re.Pattern[str]]] = [
(
"amount",
re.compile(
r"(?:\b(?:rs|pkr|inr|usd|aed|sar)\.?\s*[0-9][0-9,]*(?:\.\d+)?)"
r"|(?:[$€£₹]\s*[0-9][0-9,]*)"
r"|(?:\b[0-9][0-9,]*(?:\.\d+)?\s*(?:rs|rupees?|pkr|dollars?|usd)\b)"
r"|(?:\b(?:price|amount|total|balance|cost|refund(?:ed)? amount)\s*(?:is|was|of|:|=)"
r"\s*[0-9])",
re.IGNORECASE,
),
),
(
"stock level",
re.compile(
r"\b(?:in stock|out of stock|stock(?:[ -]level| count| left)?\s*(?:is|was|of|:|=)"
r"|low stock|sold out|back in stock"
r"|[0-9]+\s*(?:units?|pcs|pieces|items?)\s*(?:left|in stock|available|remaining))\b",
re.IGNORECASE,
),
),
(
"order status",
re.compile(
rf"\b(?:order|parcel|shipment|package|ord-\d+|#\d{{3,}})\b[^.\n]{{0,40}}?"
rf"\b(?:is|was|has been|got|status\s*[:=]?)\s*(?:now\s+)?(?:{_ORDER_STATUS_WORDS})\b"
rf"|\b(?:order|delivery|tracking|fulfil?lment) status\b",
re.IGNORECASE,
),
),
(
"payment state",
re.compile(
rf"\b(?:payment|invoice|cod|order|bill)\b[^.\n]{{0,40}}?\b(?:is|was|has been|"
rf"status\s*[:=]?)\s*(?:now\s+)?(?:{_PAYMENT_WORDS})\b"
rf"|\bpayment status\b|\bpayment (?:pending|failed|received|due|declined|captured)\b"
r"|\bcod (?:pending|collected|remitted|unpaid|received)\b",
re.IGNORECASE,
),
),
]
# Keys that carry live data no matter what their value looks like.
_FORBIDDEN_KEYS: dict[str, str] = {
"amount": "amount",
"price": "amount",
"total": "amount",
"subtotal": "amount",
"balance": "amount",
"cost": "amount",
"refund_amount": "amount",
"order_total": "amount",
"stock": "stock level",
"stock_level": "stock level",
"quantity": "stock level",
"qty": "stock level",
"inventory": "stock level",
"on_hand": "stock level",
"status": "order status",
"order_status": "order status",
"fulfillment_status": "order status",
"delivery_status": "order status",
"tracking_status": "order status",
"payment_status": "payment state",
"payment_state": "payment state",
"paid": "payment state",
"financial_status": "payment state",
}
def lint_forbidden(value: Any, path: str = "") -> list[str]:
"""Reasons the value may not be stored in memory (empty list: allowed)."""
found: list[str] = []
if isinstance(value, dict):
for k, v in value.items():
key = str(k)
label = _FORBIDDEN_KEYS.get(key.lower())
if label is not None:
found.append(f"{label} in key '{path}{key}'")
found.extend(lint_forbidden(v, f"{path}{key}."))
elif isinstance(value, list | tuple):
for i, v in enumerate(value):
found.extend(lint_forbidden(v, f"{path}{i}."))
elif isinstance(value, str):
for label, pattern in _FORBIDDEN_TEXT:
if pattern.search(value):
found.append(f"{label} in '{path.rstrip('.') or 'value'}'")
return found
# ---------------------------------------------------------------------- write policy
def checksum(namespace: tuple[str, ...], key: str, value: dict[str, Any]) -> str:
return sha256_hex(canonical_json({"ns": list(namespace), "key": key, "value": value}))
@dataclass(frozen=True)
class MemoryPolicy:
max_bytes: int
default_ttl: timedelta
max_ttl: timedelta
@classmethod
def from_settings(cls) -> MemoryPolicy:
s = get_settings()
return cls(
max_bytes=s.memory_max_bytes,
default_ttl=timedelta(days=s.memory_default_ttl_days),
max_ttl=timedelta(days=s.memory_max_ttl_days),
)
@dataclass(frozen=True)
class PreparedWrite:
value: dict[str, Any] # redacted
checksum: str
size_bytes: int
expires_at: datetime
def prepare_write(
namespace: tuple[str, ...],
key: str,
value: dict[str, Any],
*,
ttl_minutes: float | None = None,
policy: MemoryPolicy | None = None,
now: datetime | None = None,
) -> PreparedWrite:
"""Validate and normalize one write. Raises ``MemoryRejected``."""
policy = policy or MemoryPolicy.from_settings()
if not isinstance(value, dict):
raise MemoryRejected(["value must be a JSON object"])
reasons = lint_forbidden(value)
if reasons:
raise MemoryRejected(
[f"forbidden live data ({r}); read it from the system of record" for r in reasons]
)
clean: dict[str, Any] = redact_value(value)
size = len(canonical_json(clean).encode())
if size > policy.max_bytes:
raise MemoryRejected([f"value is {size} bytes, over the {policy.max_bytes} byte cap"])
ttl = policy.default_ttl if ttl_minutes is None else timedelta(minutes=float(ttl_minutes))
if ttl <= timedelta(0):
raise MemoryRejected(["ttl must be positive"])
ttl = min(ttl, policy.max_ttl)
at = (now or datetime.now(UTC)) + ttl
return PreparedWrite(
value=clean, checksum=checksum(namespace, key, clean), size_bytes=size, expires_at=at
)
def verify(namespace: tuple[str, ...], key: str, value: dict[str, Any], stored: str) -> None:
if checksum(namespace, key, value) != stored:
raise MemoryIntegrityError(f"checksum mismatch for {'.'.join(namespace)}/{key}")