Spaces:
Running
Running
File size: 7,847 Bytes
fd5dd94 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 | """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}")
|