Spaces:
Running

WorkPilot-AI / core /ops /retention.py
Aynkhn's picture
Deploy WorkPilot demo
fd5dd94 verified
Raw History Blame Contribute Delete
11.7 kB
"""Retention: purge old audit rows and redact old customer messages, per tenant.
Run as the **owner** role (``python -m core.cli purge-retention``, e.g. a nightly cron). The
app role cannot do this: ``audit_log`` is append-only for it (migration 0001).
Audit log and the hash chain
----------------------------
Each tenant's audit log is a hash chain from ``GENESIS``. Deleting old rows removes the head
of the chain, so the oldest remaining row's ``prev_hash`` no longer equals ``GENESIS``. To keep
the rest verifiable, a purge only ever deletes a **prefix** of the chain (every row with
``seq <= through_seq``) and then appends a **retention marker** row *to the same chain*:
tool = "core.retention.purge"
reason = 'retention:{"anchor_hash": <row_hash of row through_seq>, "through_seq": N, ...}'
The marker is itself hash-chained, so the purge is tamper-evident: removing or editing the
marker breaks the chain, and the anchor it records must equal the ``prev_hash`` of the oldest
remaining row. :func:`verify_chain_anchored` starts from that anchor instead of ``GENESIS``.
A later purge that deletes the old marker appends a new one, so the newest marker always
describes the current head. ``core.gateway.audit.verify_chain`` (GENESIS only) still works for
tenants that were never purged.
Messages
--------
Old message rows are **redacted**, not deleted (other pack rows reference them by foreign
key, and counts stay intact for reports): ``body``/``subject`` emptied, ``template_params``
cleared and the addresses blanked, for rows in a final state (never ``queued``/``sending``/
``draft``). Tables are named in ``WP_RETENTION_MESSAGE_TABLES`` (core never imports packs).
"""
from __future__ import annotations
import json
import uuid
from dataclasses import dataclass, field
from datetime import UTC, datetime, timedelta
from typing import Any
from sqlalchemy import bindparam, select, text
from sqlalchemy.ext.asyncio import AsyncSession
from core.config import Settings
from core.db.session import Database
from core.gateway.audit import GENESIS, AuditEntry, ChainReport, append, compute_hash
from core.gateway.models import AuditLog
from core.tenancy.models import Tenant
MARKER_TOOL = "core.retention.purge"
MARKER_PREFIX = "retention:"
_ACTIVE_MESSAGE_STATES = ("queued", "sending", "draft")
_REDACT_COLUMNS = {
"body": "''",
"subject": "NULL",
"template_params": "'{}'::jsonb",
"to_address": "''",
"from_address": "NULL",
}
@dataclass(frozen=True)
class RetentionPolicy:
audit_log_days: int # 0 = keep forever
messages_days: int # 0 = keep forever
@dataclass
class TenantPurge:
tenant_id: uuid.UUID
policy: RetentionPolicy
audit_deleted: int = 0
anchor_seq: int | None = None
messages_redacted: dict[str, int] = field(default_factory=dict)
def as_dict(self) -> dict[str, Any]:
return {
"tenant_id": str(self.tenant_id),
"audit_log_days": self.policy.audit_log_days,
"messages_days": self.policy.messages_days,
"audit_deleted": self.audit_deleted,
"anchor_seq": self.anchor_seq,
"messages_redacted": self.messages_redacted,
}
def policy_for(settings: Settings, tenant_settings: dict[str, Any] | None) -> RetentionPolicy:
"""Tenant ``settings["retention"]`` over the deployment defaults. The audit floor wins
over a shorter tenant value (0, "keep forever", is always allowed)."""
r = dict((tenant_settings or {}).get("retention") or {})
audit = int(r.get("audit_log_days", settings.retention_audit_log_days))
if audit > 0:
audit = max(audit, settings.retention_audit_log_min_days)
messages = int(r.get("messages_days", settings.retention_messages_days))
return RetentionPolicy(audit_log_days=max(audit, 0), messages_days=max(messages, 0))
# ------------------------------------------------------------------ audit log
async def purge_audit(session: AsyncSession, tenant_id: uuid.UUID, cutoff: datetime) -> TenantPurge:
"""Delete the chain prefix older than ``cutoff`` and append an anchored marker row.
``session`` must be an owner-role session bound to ``tenant_id``, inside a transaction."""
out = TenantPurge(tenant_id, RetentionPolicy(0, 0))
# Same lock as core.gateway.audit.append: no concurrent writer can fork the chain.
await session.execute(
text("SELECT pg_advisory_xact_lock(hashtext(:k))"), {"k": f"audit:{tenant_id}"}
)
last = (
await session.execute(
select(AuditLog.seq, AuditLog.row_hash)
.where(AuditLog.tenant_id == tenant_id, AuditLog.at < cutoff)
.order_by(AuditLog.seq.desc())
.limit(1)
)
).first()
if last is None:
return out
through_seq, anchor_hash = int(last[0]), str(last[1])
newest = (
await session.execute(
select(AuditLog.seq)
.where(AuditLog.tenant_id == tenant_id)
.order_by(AuditLog.seq.desc())
.limit(1)
)
).scalar_one()
res = await session.execute(
text("DELETE FROM audit_log WHERE tenant_id = :t AND seq <= :s"),
{"t": tenant_id, "s": through_seq},
)
out.audit_deleted = int(getattr(res, "rowcount", 0) or 0)
detail = {
"anchor_hash": anchor_hash,
"through_seq": through_seq,
"deleted": out.audit_deleted,
"cutoff": cutoff.astimezone(UTC).isoformat(),
"chain_continues": newest > through_seq,
}
await append(
session,
AuditEntry(
tenant_id=tenant_id,
actor="system:retention",
tool=MARKER_TOOL,
args={},
taint={},
decision="retention_purge",
policy_version="retention",
reason=MARKER_PREFIX + json.dumps(detail, sort_keys=True),
),
)
out.anchor_seq = through_seq
return out
def _marker(row: AuditLog) -> dict[str, Any] | None:
if row.tool != MARKER_TOOL or not (row.reason or "").startswith(MARKER_PREFIX):
return None
try:
value = json.loads((row.reason or "")[len(MARKER_PREFIX) :])
except ValueError:
return None
return value if isinstance(value, dict) else None
async def verify_chain_anchored(session: AsyncSession, tenant_id: uuid.UUID) -> ChainReport:
"""Like ``core.gateway.audit.verify_chain``, but accepts a purged head when the newest
retention marker in the chain anchors the oldest remaining row."""
rows = list(
(
await session.execute(
select(AuditLog).where(AuditLog.tenant_id == tenant_id).order_by(AuditLog.seq)
)
).scalars()
)
if not rows:
return ChainReport(ok=True, checked=0)
prev = GENESIS
first = rows[0]
if first.prev_hash != GENESIS:
markers = [m for m in (_marker(r) for r in rows) if m is not None]
anchor = markers[-1] if markers else None
if (
anchor is None
or anchor.get("anchor_hash") != first.prev_hash
or int(anchor.get("through_seq", -1)) >= first.seq
):
return ChainReport(ok=False, checked=1, broken_at_seq=first.seq)
prev = first.prev_hash
for n, row in enumerate(rows, start=1):
if row.prev_hash != prev or compute_hash(prev, row) != row.row_hash:
return ChainReport(ok=False, checked=n, broken_at_seq=row.seq)
prev = row.row_hash
return ChainReport(ok=True, checked=len(rows))
# ------------------------------------------------------------------- messages
async def _columns(session: AsyncSession, table: str) -> set[str]:
rows = await session.execute(
text(
"SELECT column_name FROM information_schema.columns "
"WHERE table_schema = current_schema() AND table_name = :t"
),
{"t": table},
)
return {r[0] for r in rows}
async def redact_messages(
session: AsyncSession, tenant_id: uuid.UUID, cutoff: datetime, tables: list[str]
) -> dict[str, int]:
out: dict[str, int] = {}
for table in tables:
cols = await _columns(session, table)
if not {"tenant_id", "created_at", "status", "body"} <= cols:
continue # pack not installed (or not a message table): nothing to do
sets = ", ".join(f'"{c}" = {v}' for c, v in _REDACT_COLUMNS.items() if c in cols)
res = await session.execute(
text(
f'UPDATE "{table}" SET {sets} ' # noqa: S608 (identifiers from catalog/settings)
"WHERE tenant_id = :t AND created_at < :cutoff "
"AND status NOT IN :active AND body <> ''"
).bindparams(bindparam("active", expanding=True)),
{"t": tenant_id, "cutoff": cutoff, "active": _ACTIVE_MESSAGE_STATES},
)
out[table] = int(getattr(res, "rowcount", 0) or 0)
return out
# -------------------------------------------------------------------- driver
async def known_tenants(owner_db: Database) -> list[uuid.UUID]:
"""Tenants visible to the owner role's admin policies (the owner cannot list ``tenants``
under FORCE RLS): any tenant that ever had a run, approval, event, schedule or channel."""
async with owner_db.session() as s:
rows = await s.execute(
text(
"SELECT tenant_id FROM runs UNION SELECT tenant_id FROM approvals "
"UNION SELECT tenant_id FROM events UNION SELECT tenant_id FROM schedules "
"UNION SELECT tenant_id FROM channel_accounts"
)
)
return sorted({r[0] for r in rows}, key=str)
async def purge_tenant(
owner_db: Database,
settings: Settings,
tenant_id: uuid.UUID,
*,
now: datetime | None = None,
dry_run: bool = False,
) -> TenantPurge:
now = now or datetime.now(UTC)
out = TenantPurge(tenant_id, RetentionPolicy(0, 0))
try:
async with owner_db.session(tenant_id=tenant_id) as s, s.begin():
tenant_settings = (
await s.execute(select(Tenant.settings).where(Tenant.id == tenant_id))
).scalar_one_or_none()
out.policy = policy_for(settings, tenant_settings)
if out.policy.audit_log_days:
cutoff = now - timedelta(days=out.policy.audit_log_days)
audit = await purge_audit(s, tenant_id, cutoff)
out.audit_deleted, out.anchor_seq = audit.audit_deleted, audit.anchor_seq
if out.policy.messages_days:
out.messages_redacted = await redact_messages(
s,
tenant_id,
now - timedelta(days=out.policy.messages_days),
list(settings.retention_message_tables),
)
if dry_run:
raise _DryRun # roll the whole tenant transaction back
except _DryRun:
pass
return out
class _DryRun(Exception):
pass
async def purge_all(
owner_db: Database,
settings: Settings,
tenants: list[uuid.UUID] | None = None,
*,
now: datetime | None = None,
dry_run: bool = False,
) -> list[TenantPurge]:
ids = tenants if tenants is not None else await known_tenants(owner_db)
return [await purge_tenant(owner_db, settings, t, now=now, dry_run=dry_run) for t in ids]