feat(saas): multi-tenant isolation (Phase 1) + rate-limit/audit/org-scoped export (Phase 2)

Phase 1 (tenant isolation):
- g.org_id set on require_auth; assert_tenant()/current_org_id() choke-point helpers.
- Multi-org provisioning: POST /api/admin/users {new_org:true} (super_admin) creates a
  new org + its first admin; GET /api/admin/orgs (super_admin sees all, admin own).
- Fixed latent create_org double-id bug (dict id != store key).
- test_saas_tenant.py: org2 admin blocked from org1 group (403), can't list org1
  groups/users, sees only own org; super_admin sees all.

Phase 2 (hardening):
- Rate limit login (per-IP + per-username) + chat send (per-user) to protect LLM cost
  and slow brute force; services/rate_limit.py (in-memory + disk, no external deps).
- Audit log data/audit/audit.jsonl on org.create, user.promote_super_admin, analytics.export.
- CSV export now org-scoped (admin exports only own org).
All 8 backend suites pass.
This commit is contained in:
Macky
2026-08-09 09:35:26 +07:00
parent e1d61e1e1e
commit 056753e8cb
9 changed files with 312 additions and 8 deletions

View File

@@ -19,6 +19,30 @@ def _stores():
}
def _log_audit(action: str, subject: str, *, detail: dict | None = None) -> None:
import json
import time
from ..config import Config
from .helpers import current_user as _cu
actor = _cu()
entry = {
"ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"actor": (actor or {}).get("username") or (actor or {}).get("id"),
"action": action,
"subject": subject,
"detail": detail or {},
}
try:
log_dir = Config.DATA_DIR / "audit"
log_dir.mkdir(parents=True, exist_ok=True)
with open(log_dir / "audit.jsonl", "a", encoding="utf-8") as fh:
fh.write(json.dumps(entry, ensure_ascii=False) + "\n")
except Exception:
pass
def _parse_date_iso(value: str | None, *, end: bool = False) -> str | None:
"""Parse a YYYY-MM-DD into an ISO datetime bound for created_at filtering."""
if not value:
@@ -124,11 +148,14 @@ def export_csv():
from flask import Response, current_app
s = _stores()
actor = current_user()
# Tenant: an admin exports only their own org's sessions; super_admin sees all.
export_org = actor.get("org_id") if actor.get("role") != "super_admin" else None
users = {}
try:
user_store = current_app.extensions.get("user_store")
if user_store and hasattr(user_store, "list_users"):
for rec in user_store.list_users():
for rec in user_store.list_users(org_id=export_org):
users[rec.get("id") or rec.get("username")] = rec.get("username") or rec.get("id")
except Exception:
pass
@@ -138,9 +165,9 @@ def export_csv():
grp_store = s["groups"]
sess_store = s["sessions"]
if hasattr(grp_store, "groups"):
group_ids = [g.get("id") for g in grp_store.groups.all()]
group_ids = [g.get("id") for g in grp_store.groups.all() if export_org is None or g.get("org_id") == export_org]
elif hasattr(grp_store, "all"):
group_ids = [g.get("id") for g in grp_store.all()]
group_ids = [g.get("id") for g in grp_store.all() if export_org is None or g.get("org_id") == export_org]
else:
group_ids = []
for gid in group_ids:
@@ -154,6 +181,8 @@ def export_csv():
except Exception:
pass
_log_audit("analytics.export", actor.get("org_id") or "?", detail={"rows": len(sessions)})
buf = io.StringIO()
w = csv.writer(buf)
w.writerow(["username", "persona", "scenario", "outcome", "score", "created_at"])