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:
@@ -16,6 +16,43 @@ def _store():
|
||||
return current_app.extensions["user_store"]
|
||||
|
||||
|
||||
def _log_audit(action: str, subject: str, *, detail: dict | None = None) -> None:
|
||||
"""Append a line to the audit log (sensitive platform actions)."""
|
||||
import json
|
||||
import time
|
||||
from ..config import Config
|
||||
|
||||
entry = {
|
||||
"ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||
"actor": (current_user() or {}).get("username") or (current_user() 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:
|
||||
# Audit logging must never break the request.
|
||||
pass
|
||||
|
||||
|
||||
@admin_bp.get("/orgs")
|
||||
@require_auth
|
||||
@require_roles("admin")
|
||||
def list_orgs():
|
||||
"""Platform view: all organizations (super_admin). Admin sees only their own."""
|
||||
actor = current_user()
|
||||
if actor.get("role") == "super_admin":
|
||||
orgs = list(_store().orgs.all())
|
||||
return jsonify({"orgs": orgs})
|
||||
# plain admin: only their own org
|
||||
org = _store().orgs.get_or_none(actor.get("org_id"))
|
||||
return jsonify({"orgs": [org] if org else []})
|
||||
|
||||
|
||||
@admin_bp.post("/users")
|
||||
@require_auth
|
||||
@require_roles("admin")
|
||||
@@ -36,13 +73,26 @@ def create_user():
|
||||
actor_role = current_user().get("role")
|
||||
if role in ("admin", "super_admin") and actor_role != "super_admin":
|
||||
raise ApiError("only super_admin can grant admin roles", 403)
|
||||
|
||||
# Multi-tenant: provisioning a brand-new org (super_admin only). The created user
|
||||
# becomes that org's first admin (tenant owner). Everything is isolated per org.
|
||||
new_org = bool(data.get("new_org"))
|
||||
if new_org:
|
||||
if actor_role != "super_admin":
|
||||
raise ApiError("only super_admin can create a new organization", 403)
|
||||
if role != "admin":
|
||||
raise ApiError("new-org first user must be role=admin", 400)
|
||||
org = _store().create_org(name or username)
|
||||
org_id = org["id"]
|
||||
_log_audit("org.create", org_id, detail={"name": name or username})
|
||||
|
||||
try:
|
||||
user = _store().create_user(
|
||||
org_id=org_id, username=username, password=password, name=name, role=role
|
||||
)
|
||||
except AuthError as exc:
|
||||
raise ApiError(str(exc))
|
||||
return jsonify({"user": _store().public_user(user)}), 201
|
||||
return jsonify({"user": _store().public_user(user), "org_id": org_id}), 201
|
||||
|
||||
|
||||
@admin_bp.get("/users")
|
||||
@@ -76,6 +126,8 @@ def update_user(username: str):
|
||||
if actor.get("role") != "super_admin":
|
||||
raise ApiError("only super_admin can change roles")
|
||||
_store().set_role(username, role)
|
||||
if role == "super_admin":
|
||||
_log_audit("user.promote_super_admin", username)
|
||||
|
||||
if "active" in data:
|
||||
if actor.get("role") != "super_admin":
|
||||
|
||||
Reference in New Issue
Block a user