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

@@ -0,0 +1,64 @@
"""Lightweight server-side rate limiter (no external deps).
Per-key (user/IP + action) sliding-window counter, persisted to disk so restarts
don't fully reset abuse protection. In-memory fast path + on-disk snapshot.
"""
from __future__ import annotations
import json
import os
import threading
import time
from ..config import Config
_lock = threading.Lock()
_mem: dict[str, list[float]] = {} # key -> list of recent timestamps
def _key(action: str, ident: str) -> str:
return f"{action}:{ident}"
def _load():
p = Config.DATA_DIR / "ratelimit.json"
try:
if p.exists():
with open(p, encoding="utf-8") as fh:
return json.load(fh)
except Exception:
pass
return {}
def _save():
try:
p = Config.DATA_DIR / "ratelimit.json"
p.parent.mkdir(parents=True, exist_ok=True)
tmp = p.with_suffix(".json.tmp")
with open(tmp, "w", encoding="utf-8") as fh:
json.dump(_mem, fh)
os.replace(tmp, p)
except Exception:
pass
def check(action: str, ident: str, *, limit: int, window: int) -> bool:
"""Return True if allowed; False if the limit in `window` seconds was exceeded."""
key = _key(action, ident)
now = time.time()
with _lock:
rec = list(_mem.get(key) or _load().get(key) or [])
rec = [t for t in rec if now - t < window]
if len(rec) >= limit:
_mem[key] = rec
return False
rec.append(now)
_mem[key] = rec
# opportunistically persist (bounded writes)
try:
if int(now) % 5 == 0:
_save()
except Exception:
pass
return True