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

@@ -220,6 +220,13 @@ def send_message(gid: str, pid: str):
if len(text) > 2000:
raise ApiError("message too long")
# Protect LLM cost: per-user chat-send window.
from ..services.rate_limit import check as ratelimit
actor_rl = current_user()
if not ratelimit("chat:user", actor_rl.get("id") or actor_rl.get("username") or "?", limit=30, window=60):
raise ApiError("slow down — too many messages", 429)
group = s["groups"].get_or_none(gid)
persona = s["groups"].get_persona(gid, pid) if group else None
if not group or not persona: