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:
@@ -27,6 +27,20 @@ def current_user() -> dict[str, Any]:
|
||||
return g.user
|
||||
|
||||
|
||||
def current_org_id() -> str:
|
||||
return getattr(g, "org_id", None) or (g.user or {}).get("org_id") or "org-default"
|
||||
|
||||
|
||||
def assert_tenant(org_id: str | None) -> None:
|
||||
"""Raise 403 if the object's org does not belong to the actor's tenant.
|
||||
|
||||
super_admin is the platform operator and is exempt (can see all orgs)."""
|
||||
if (g.user or {}).get("role") == "super_admin":
|
||||
return
|
||||
if (org_id or "org-default") != current_org_id():
|
||||
raise ApiError("permission denied", 403)
|
||||
|
||||
|
||||
def require_auth(fn: Callable) -> Callable:
|
||||
@functools.wraps(fn)
|
||||
def wrapper(*args, **kwargs):
|
||||
@@ -43,6 +57,9 @@ def require_auth(fn: Callable) -> Callable:
|
||||
raise ApiError("account is inactive", 401)
|
||||
g.user = user
|
||||
g.token_payload = payload
|
||||
# Tenant context: every request carries the actor's org id so downstream guards
|
||||
# can enforce per-org isolation without re-reading the user each time.
|
||||
g.org_id = (user or {}).get("org_id") or "org-default"
|
||||
return fn(*args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
Reference in New Issue
Block a user