diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index a351f8743..891df14d9 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -72,8 +72,12 @@ SMTP/IMAP providers as documented in the current repo and physical replication/WAL restore remain future work per `docs/operations/postgresql-physical-replication.md`. -Authentication remains dummy `X-User-Id` header auth until mailbox ownership, -Keycloak/Casdoor evaluation, and key rotation are completed; see +Authentication still uses trusted request headers in local/dev, but the backend +now normalizes them into an auth context with `platform_admin`, +`organization_admin`, `group_admin`, and `member` roles plus optional +organization/group scope. This preserves the current `X-User-Id` development +flow while preparing the backend for future Keycloak/Casdoor claims and +organization-scoped resources that should not assume one workspace per user; see `docs/operations/auth-key-management.md`. The current Kubernetes ingress assumes NGINX, while Traefik is only an evaluated option in `docs/operations/traefik-evaluation.md`. diff --git a/README.md b/README.md index 286545aa8..a2947717a 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,7 @@ Errors should tell a contributor what failed and avoid leaking internals: ## Current scope contract -This repo still uses dummy header auth and does not persist an owner/mailbox key on email rows. Treat local data as single-user development data until a mailbox ownership migration is added. +This repo still uses trusted header auth in local/dev and does not persist an owner/mailbox key on email rows. The backend now derives an auth context with platform/organization/group/member scopes, but email data should still be treated as single-user development data until a mailbox ownership migration is added. ## Operations and release docs diff --git a/backend/api/auth.py b/backend/api/auth.py index 663495f57..4bc0b8773 100644 --- a/backend/api/auth.py +++ b/backend/api/auth.py @@ -1,25 +1,124 @@ +from dataclasses import dataclass +from typing import Literal, cast + from fastapi import Depends, Header, HTTPException + from core.config import settings -async def get_current_user(x_user_id: str | None = Header(None, alias="X-User-Id")) -> str: + +RoleName = Literal["platform_admin", "organization_admin", "group_admin", "member"] +SCOPED_ROLES: set[str] = {"platform_admin", "organization_admin", "group_admin", "member"} + + +@dataclass(frozen=True) +class AuthContext: + user_id: str + role: RoleName + organization_id: str | None + group_ids: tuple[str, ...] + workspace_id: str + + +def _normalize_header_value(value: object) -> str | None: + if not isinstance(value, str): + return None + normalized = value.strip() + return normalized or None + + +def _derive_role(user_id: str, requested_role: str | None) -> RoleName: + if not (settings.DEBUG or settings.TRUST_DEV_HEADERS): + return "member" + if requested_role in SCOPED_ROLES: + return cast(RoleName, requested_role) + return "organization_admin" if user_id == "admin" else "member" + + +def _parse_group_ids(group_ids_header: str | None) -> tuple[str, ...]: + if not group_ids_header: + return () + return tuple(group_id.strip() for group_id in group_ids_header.split(",") if group_id.strip()) + + +def _derive_workspace_id( + user_id: str, + organization_id: str | None, +) -> str: + if organization_id: + return f"workspace-{organization_id}" + return f"workspace-{user_id}" + + +def ensure_organization_access(auth_context: AuthContext, organization_id: str) -> None: + if auth_context.role == "platform_admin": + return + if auth_context.organization_id != organization_id: + raise HTTPException(status_code=403, detail="Resource belongs to a different organization") + + +async def get_auth_context( + x_user_id: str | None = Header(None, alias="X-User-Id"), + x_user_role: str | None = Header(None, alias="X-User-Role"), + x_organization_id: str | None = Header(None, alias="X-Organization-Id"), + x_group_ids: str | None = Header(None, alias="X-Group-Ids"), +) -> AuthContext: + return build_auth_context( + x_user_id=x_user_id, + x_user_role=x_user_role, + x_organization_id=x_organization_id, + x_group_ids=x_group_ids, + ) + + +def build_auth_context( + x_user_id: object, + x_user_role: object = None, + x_organization_id: object = None, + x_group_ids: object = None, +) -> AuthContext: """ - Extracts the user ID from the X-User-Id header. - In a real implementation, this should validate a JWT or Keycloak token. - For now, we enforce that it must be present. + Builds an auth context from the current request headers. + Today this still trusts local/dev headers, but the shape matches future + token-derived scope claims from Keycloak or Casdoor. """ - if not x_user_id: + user_id = _normalize_header_value(x_user_id) + if user_id is None: raise HTTPException(status_code=401, detail="Authentication required") - return x_user_id + organization_id = _normalize_header_value(x_organization_id) + role = _derive_role(user_id, _normalize_header_value(x_user_role)) + group_ids = _parse_group_ids(_normalize_header_value(x_group_ids)) + workspace_id = _derive_workspace_id(user_id, organization_id) -async def get_current_workspace_id(current_user: str = Depends(get_current_user)) -> str: - return f"workspace-{current_user}" + return AuthContext( + user_id=user_id, + role=role, + organization_id=organization_id, + group_ids=group_ids, + workspace_id=workspace_id, + ) + + +async def get_current_user( + x_user_id: str | None = Header(None, alias="X-User-Id"), + x_user_role: str | None = Header(None, alias="X-User-Role"), + x_organization_id: str | None = Header(None, alias="X-Organization-Id"), + x_group_ids: str | None = Header(None, alias="X-Group-Ids"), +) -> str: + return build_auth_context( + x_user_id=x_user_id, + x_user_role=x_user_role, + x_organization_id=x_organization_id, + x_group_ids=x_group_ids, + ).user_id + + +async def get_current_workspace_id(auth_context: AuthContext = Depends(get_auth_context)) -> str: + return auth_context.workspace_id async def get_current_user_role( - current_user: str = Depends(get_current_user), + auth_context: AuthContext = Depends(get_auth_context), ) -> str: - if not (settings.DEBUG or settings.TRUST_DEV_HEADERS): - return "member" - return "organization_admin" if current_user == "admin" else "member" + return auth_context.role diff --git a/backend/api/llm_providers.py b/backend/api/llm_providers.py index d4f78716f..ca9f7abe4 100644 --- a/backend/api/llm_providers.py +++ b/backend/api/llm_providers.py @@ -6,7 +6,7 @@ import datetime from db.session import get_db from db.models import LLMProvider, AuditLog -from api.auth import get_current_user +from api.auth import AuthContext, get_auth_context from pydantic import BaseModel router = APIRouter(prefix="/api/llm-providers", tags=["llm-providers"]) @@ -45,17 +45,15 @@ def _get_fingerprint(api_key: str | None) -> str | None: return f"***{api_key[-4:]}" return "***" -async def check_admin_access(user_id: str = Depends(get_current_user)): - # Mocking role claim check for now since auth.py just returns string - user_roles = ["admin"] if user_id == "admin" else [] - if "admin" not in user_roles: - raise HTTPException(status_code=403, detail="Admin access required") - return user_id +async def check_admin_access(auth_context: AuthContext = Depends(get_auth_context)): + if auth_context.role not in {"platform_admin", "organization_admin"}: + raise HTTPException(status_code=403, detail="Organization admin access required") + return auth_context.user_id @router.get("", response_model=List[LLMProviderResponse]) async def list_providers( db: AsyncSession = Depends(get_db), - user_id: str = Depends(get_current_user) + auth_context: AuthContext = Depends(get_auth_context) ): result = await db.execute(select(LLMProvider)) providers = result.scalars().all() diff --git a/backend/api/runner_config.py b/backend/api/runner_config.py index 19c56d013..ca3447ed2 100644 --- a/backend/api/runner_config.py +++ b/backend/api/runner_config.py @@ -7,7 +7,7 @@ from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession -from api.auth import get_current_user_role, get_current_workspace_id +from api.auth import AuthContext, ensure_organization_access, get_auth_context from db.models import WorkspaceRunnerConfig from db.session import get_db @@ -28,10 +28,18 @@ class RunnerRotateResponse(BaseModel): registration_token: str -def _check_org_admin(user_role: str = Depends(get_current_user_role)) -> str: - if user_role != "organization_admin": +def _check_org_admin(auth_context: AuthContext = Depends(get_auth_context)) -> AuthContext: + if auth_context.role not in {"platform_admin", "organization_admin"}: raise HTTPException(status_code=403, detail="Organization admin access required") - return user_role + if auth_context.role == "organization_admin" and not auth_context.organization_id: + raise HTTPException(status_code=403, detail="Organization scope is required") + return auth_context + + +def _get_target_organization_id(auth_context: AuthContext) -> str: + if not auth_context.organization_id: + raise HTTPException(status_code=403, detail="Organization scope is required") + return auth_context.organization_id def _fingerprint(token: str | None) -> str | None: @@ -43,11 +51,12 @@ def _fingerprint(token: str | None) -> str | None: @router.get("", response_model=RunnerConfigResponse) async def get_runner_config( db: AsyncSession = Depends(get_db), - _: str = Depends(_check_org_admin), - workspace_id: str = Depends(get_current_workspace_id), + auth_context: AuthContext = Depends(_check_org_admin), ): + organization_id = _get_target_organization_id(auth_context) + workspace_id = f"workspace-{organization_id}" result = await db.execute( - select(WorkspaceRunnerConfig).where(WorkspaceRunnerConfig.workspace_id == workspace_id) + select(WorkspaceRunnerConfig).where(WorkspaceRunnerConfig.organization_id == organization_id) ) config = result.scalar_one_or_none() @@ -55,6 +64,7 @@ async def get_runner_config( return RunnerConfigResponse(workspace_id=workspace_id, configured=False, fingerprint=None, updated_at=None) try: + ensure_organization_access(auth_context, config.organization_id) return RunnerConfigResponse( workspace_id=config.workspace_id, configured=bool(config.registration_token), @@ -73,19 +83,25 @@ async def get_runner_config( @router.post("/rotate", response_model=RunnerRotateResponse) async def rotate_runner_token( db: AsyncSession = Depends(get_db), - _: str = Depends(_check_org_admin), - workspace_id: str = Depends(get_current_workspace_id), + auth_context: AuthContext = Depends(_check_org_admin), ): + organization_id = _get_target_organization_id(auth_context) + workspace_id = f"workspace-{organization_id}" result = await db.execute( - select(WorkspaceRunnerConfig).where(WorkspaceRunnerConfig.workspace_id == workspace_id) + select(WorkspaceRunnerConfig).where(WorkspaceRunnerConfig.organization_id == organization_id) ) config = result.scalar_one_or_none() token = f"nrn_{secrets.token_urlsafe(24)}" if not config: - config = WorkspaceRunnerConfig(workspace_id=workspace_id, registration_token=token) + config = WorkspaceRunnerConfig( + organization_id=organization_id, + workspace_id=workspace_id, + registration_token=token, + ) db.add(config) else: + ensure_organization_access(auth_context, config.organization_id) config.registration_token = token try: diff --git a/backend/api/tenant_config.py b/backend/api/tenant_config.py index a7a113555..4f418f8b3 100644 --- a/backend/api/tenant_config.py +++ b/backend/api/tenant_config.py @@ -61,6 +61,9 @@ class TenantConfigResponse(BaseModel): "google_client_secret", } +MAILBOX_MANAGE_FORBIDDEN = "Mailbox settings are personal and can only be managed by the authenticated user" +MAILBOX_VIEW_FORBIDDEN = "Mailbox settings are personal and can only be viewed by the authenticated user" + @router.post("") async def create_or_update_config( @@ -69,7 +72,7 @@ async def create_or_update_config( current_user: str = Depends(get_current_user) ): if config.user_id != current_user: - raise HTTPException(status_code=403, detail="Not authorized") + raise HTTPException(status_code=403, detail=MAILBOX_MANAGE_FORBIDDEN) result = await db.execute( select(TenantConfig).where(TenantConfig.user_id == config.user_id) @@ -109,7 +112,7 @@ async def get_config( current_user: str = Depends(get_current_user) ): if user_id != current_user: - raise HTTPException(status_code=403, detail="Not authorized") + raise HTTPException(status_code=403, detail=MAILBOX_VIEW_FORBIDDEN) result = await db.execute( select(TenantConfig).where(TenantConfig.user_id == user_id) diff --git a/backend/db/models.py b/backend/db/models.py index 0160486ce..6b601eb68 100644 --- a/backend/db/models.py +++ b/backend/db/models.py @@ -84,6 +84,7 @@ class WorkspaceRunnerConfig(Base): __tablename__ = "workspace_runner_configs" id: Mapped[int] = mapped_column(primary_key=True) + organization_id: Mapped[str] = mapped_column(String, unique=True, index=True) workspace_id: Mapped[str] = mapped_column(String, unique=True, index=True) registration_token: Mapped[str | None] = mapped_column(EncryptedString, nullable=True) updated_at: Mapped[datetime.datetime] = mapped_column( @@ -91,6 +92,40 @@ class WorkspaceRunnerConfig(Base): ) +class Organization(Base): + __tablename__ = "organizations" + + id: Mapped[str] = mapped_column(String, primary_key=True) + name: Mapped[str | None] = mapped_column(String, nullable=True) + + groups: Mapped[list["OrganizationGroup"]] = relationship(back_populates="organization") + role_assignments: Mapped[list["ScopedRoleAssignment"]] = relationship(back_populates="organization") + + +class OrganizationGroup(Base): + __tablename__ = "organization_groups" + + id: Mapped[str] = mapped_column(String, primary_key=True) + organization_id: Mapped[str] = mapped_column(ForeignKey("organizations.id"), index=True) + name: Mapped[str | None] = mapped_column(String, nullable=True) + + organization: Mapped["Organization"] = relationship(back_populates="groups") + role_assignments: Mapped[list["ScopedRoleAssignment"]] = relationship(back_populates="group") + + +class ScopedRoleAssignment(Base): + __tablename__ = "scoped_role_assignments" + + id: Mapped[int] = mapped_column(primary_key=True) + user_id: Mapped[str] = mapped_column(String, index=True) + role: Mapped[str] = mapped_column(String, index=True) + organization_id: Mapped[str | None] = mapped_column(ForeignKey("organizations.id"), nullable=True, index=True) + group_id: Mapped[str | None] = mapped_column(ForeignKey("organization_groups.id"), nullable=True, index=True) + + organization: Mapped["Organization | None"] = relationship(back_populates="role_assignments") + group: Mapped["OrganizationGroup | None"] = relationship(back_populates="role_assignments") + + class PromptTemplate(Base): __tablename__ = "prompt_templates" diff --git a/backend/tests/test_auth_real.py b/backend/tests/test_auth_real.py index c39fecdd3..73afcb376 100644 --- a/backend/tests/test_auth_real.py +++ b/backend/tests/test_auth_real.py @@ -1,6 +1,16 @@ import pytest from fastapi import HTTPException -from api.auth import get_current_user +from api.auth import AuthContext, ensure_organization_access, get_auth_context, get_current_user +from core.config import settings + + +@pytest.fixture(autouse=True) +def restore_auth_flags(): + previous_debug = settings.DEBUG + previous_trust = settings.TRUST_DEV_HEADERS + yield + settings.DEBUG = previous_debug + settings.TRUST_DEV_HEADERS = previous_trust @pytest.mark.asyncio async def test_get_current_user_rejects_missing_auth(): @@ -8,3 +18,54 @@ async def test_get_current_user_rejects_missing_auth(): with pytest.raises(HTTPException) as exc: await get_current_user(x_user_id=None) assert exc.value.status_code == 401 + + +@pytest.mark.asyncio +async def test_get_auth_context_supports_scoped_enterprise_roles(): + settings.TRUST_DEV_HEADERS = True + + context = await get_auth_context( + x_user_id="alice", + x_user_role="group_admin", + x_organization_id="org-acme", + x_group_ids="group-1,group-2", + ) + + assert context == AuthContext( + user_id="alice", + role="group_admin", + organization_id="org-acme", + group_ids=("group-1", "group-2"), + workspace_id="workspace-org-acme", + ) + + +@pytest.mark.asyncio +async def test_get_auth_context_keeps_legacy_workspace_fallback_for_unscoped_dev_auth(): + settings.TRUST_DEV_HEADERS = True + + context = await get_auth_context( + x_user_id="root", + x_user_role="platform_admin", + ) + + assert context.role == "platform_admin" + assert context.organization_id is None + assert context.group_ids == () + assert context.workspace_id == "workspace-root" + + +def test_ensure_organization_access_rejects_cross_scope_resource(): + context = AuthContext( + user_id="alice", + role="organization_admin", + organization_id="org-acme", + group_ids=("group-1",), + workspace_id="workspace-org-acme", + ) + + with pytest.raises(HTTPException) as exc: + ensure_organization_access(context, "org-other") + + assert exc.value.status_code == 403 + assert exc.value.detail == "Resource belongs to a different organization" diff --git a/backend/tests/test_llm_providers_api.py b/backend/tests/test_llm_providers_api.py index 6055bc8e1..89af1abc6 100644 --- a/backend/tests/test_llm_providers_api.py +++ b/backend/tests/test_llm_providers_api.py @@ -1,124 +1,147 @@ +import datetime + import pytest from fastapi.testclient import TestClient -from main import app -from db.models import LLMProvider, AuditLog -from db.session import get_db + +from core.config import settings +from db.models import AuditLog, LLMProvider from db.session import get_db +from main import app + + +class MockScalars: + def __init__(self, items): + self._items = items + + def all(self): + return self._items + + def first(self): + return self._items[0] if self._items else None + + +class MockResult: + def __init__(self, items): + self._items = items + + def scalars(self): + return MockScalars(self._items) + class MockSession: def __init__(self): - self.items = [] - self.audits = [] + self.providers: list[LLMProvider] = [] + self.audits: list[AuditLog] = [] + async def execute(self, stmt): - class MockResult: - def scalars(self): - class MockScalars: - def all(self): - return self.items - def first(self): - if self.items: - return self.items[0] - return None - m = MockScalars() - - # Check for where filtering - filtered = self.parent_items - stmt_str = str(stmt).lower() - if "where" in stmt_str and "llm_providers.id =" in stmt_str: - # super hacky mock for tests - try: - import re - match = re.search(r"llm_providers.id = :id_1", stmt_str) - if match: - # We can just assume it's getting the last created provider id for these tests - pass - except Exception: - pass - - # Actually, simpler: Just filter if parameters are passed? - # We don't get parameters easily in this mock, so we'll just return the first item if first() is called - # unless we are looking for a specific ID. Let's just improve the mock slightly. - m.items = getattr(self, 'items', self.parent_items) - return m - res = MockResult() - res.parent_items = self.items - return res - - + stmt_str = str(stmt).lower() + if "llm_providers.id =" in stmt_str: + return MockResult(self.providers[:1]) + return MockResult(self.providers) + def add(self, obj): if isinstance(obj, LLMProvider): - obj.id = len(self.items) + 1 - obj.updated_at = "2026-05-11T00:00:00Z" - self.items.append(obj) + obj.id = len(self.providers) + 1 + obj.updated_at = datetime.datetime.now(datetime.timezone.utc) + self.providers.append(obj) elif isinstance(obj, AuditLog): self.audits.append(obj) - + + async def delete(self, obj): + self.providers = [provider for provider in self.providers if provider is not obj] + async def commit(self): - pass + return None + async def refresh(self, obj): - pass + return None + mock_session = MockSession() + +@pytest.fixture(autouse=True) +def enable_dev_headers(): + previous = settings.TRUST_DEV_HEADERS + settings.TRUST_DEV_HEADERS = True + yield + settings.TRUST_DEV_HEADERS = previous + + @pytest.fixture(autouse=True) def override_get_db(): - app.dependency_overrides[get_db] = lambda: mock_session + async def override_db(): + yield mock_session + + app.dependency_overrides[get_db] = override_db yield app.dependency_overrides.clear() - mock_session.items = [] + mock_session.providers = [] mock_session.audits = [] @pytest.fixture def admin_client(): - with TestClient(app, headers={"X-User-Id": "admin"}) as c: - yield c + with TestClient( + app, + headers={ + "X-User-Id": "admin", + "X-User-Role": "organization_admin", + "X-Organization-Id": "org-acme", + }, + ) as client: + yield client + @pytest.fixture def member_client(): - with TestClient(app, headers={"X-User-Id": "member"}) as c: - yield c + with TestClient( + app, + headers={ + "X-User-Id": "member", + "X-User-Role": "member", + "X-Organization-Id": "org-acme", + }, + ) as client: + yield client + def test_llm_provider_crud_admin(admin_client): - mock_session.items = [] - # Create - resp = admin_client.post("/api/llm-providers", json={ - "name": "Primary OpenAI", - "provider_type": "openai", - "api_key": "sk-12345" - }) - assert resp.status_code == 200, resp.text - data = resp.json() + response = admin_client.post( + "/api/llm-providers", + json={ + "name": "Primary OpenAI", + "provider_type": "openai", + "api_key": "sk-12345", + }, + ) + assert response.status_code == 200, response.text + data = response.json() assert data["name"] == "Primary OpenAI" assert data["configured"] is True assert data["fingerprint"] is not None assert "api_key" not in data - + provider_id = data["id"] - - # List - resp = admin_client.get("/api/llm-providers") - assert resp.status_code == 200 - assert len(resp.json()) >= 1 - - # Update - resp = admin_client.put(f"/api/llm-providers/{provider_id}", json={ - "is_active": True - }) - assert resp.status_code == 200 - assert resp.json()["is_active"] is True - - # Check AuditLog - # result = await db_session.execute(select(AuditLog).where(AuditLog.user_id == "admin")) - # logs = result.scalars().all() - pass + + response = admin_client.get("/api/llm-providers") + assert response.status_code == 200 + assert len(response.json()) == 1 + + response = admin_client.put(f"/api/llm-providers/{provider_id}", json={"is_active": True}) + assert response.status_code == 200 + assert response.json()["is_active"] is True + + response = admin_client.delete(f"/api/llm-providers/{provider_id}") + assert response.status_code == 204 + def test_llm_provider_member_rejected(member_client): - resp = member_client.get("/api/llm-providers") - assert resp.status_code == 200 - - resp = member_client.post("/api/llm-providers", json={ - "name": "Malicious", - "provider_type": "openai" - }) - assert resp.status_code == 403 + response = member_client.get("/api/llm-providers") + assert response.status_code == 200 + + response = member_client.post( + "/api/llm-providers", + json={"name": "Malicious", "provider_type": "openai"}, + ) + assert response.status_code == 403 diff --git a/backend/tests/test_runner_config_api.py b/backend/tests/test_runner_config_api.py index c0acaf76c..657ddb05e 100644 --- a/backend/tests/test_runner_config_api.py +++ b/backend/tests/test_runner_config_api.py @@ -53,9 +53,11 @@ async def override_get_db(): yield mock_db app.dependency_overrides[get_db] = override_get_db - with TestClient(app, headers={"X-User-Id": "testuser"}) as c: - yield c - app.dependency_overrides.clear() + try: + with TestClient(app, headers={"X-User-Id": "testuser", "X-Organization-Id": "org-acme"}) as c: + yield c + finally: + app.dependency_overrides.pop(get_db, None) @pytest.fixture @@ -64,9 +66,58 @@ async def override_get_db(): yield mock_db app.dependency_overrides[get_db] = override_get_db - with TestClient(app, headers={"X-User-Id": "admin"}) as c: - yield c - app.dependency_overrides.clear() + try: + with TestClient( + app, + headers={ + "X-User-Id": "admin", + "X-User-Role": "organization_admin", + "X-Organization-Id": "org-acme", + }, + ) as c: + yield c + finally: + app.dependency_overrides.pop(get_db, None) + + +@pytest.fixture +def second_org_admin_client(mock_db): + async def override_get_db(): + yield mock_db + + app.dependency_overrides[get_db] = override_get_db + try: + with TestClient( + app, + headers={ + "X-User-Id": "org-admin-2", + "X-User-Role": "organization_admin", + "X-Organization-Id": "org-acme", + }, + ) as c: + yield c + finally: + app.dependency_overrides.pop(get_db, None) + + +@pytest.fixture +def platform_admin_client(mock_db): + async def override_get_db(): + yield mock_db + + app.dependency_overrides[get_db] = override_get_db + try: + with TestClient( + app, + headers={ + "X-User-Id": "platform-root", + "X-User-Role": "platform_admin", + "X-Organization-Id": "org-acme", + }, + ) as c: + yield c + finally: + app.dependency_overrides.pop(get_db, None) def test_member_cannot_manage_runner_config(member_client): @@ -77,17 +128,44 @@ def test_member_cannot_manage_runner_config(member_client): assert response.status_code == 403 -def test_admin_can_rotate_and_read_runner_config(admin_client): +def test_org_scoped_runner_config_uses_shared_workspace(admin_client, second_org_admin_client, mock_db): rotate_response = admin_client.post("/api/runner-config/rotate") assert rotate_response.status_code == 200 rotate_data = rotate_response.json() - assert rotate_data["workspace_id"] == "workspace-admin" + assert rotate_data["workspace_id"] == "workspace-org-acme" assert rotate_data["registration_token"].startswith("nrn_") + assert mock_db.runner.organization_id == "org-acme" - read_response = admin_client.get("/api/runner-config") + read_response = second_org_admin_client.get("/api/runner-config") assert read_response.status_code == 200 read_data = read_response.json() - assert read_data["workspace_id"] == "workspace-admin" + assert read_data["workspace_id"] == "workspace-org-acme" assert read_data["configured"] is True assert read_data["fingerprint"] is not None assert "registration_token" not in read_data + + +def test_platform_admin_can_manage_runner_config(platform_admin_client): + rotate_response = platform_admin_client.post("/api/runner-config/rotate") + assert rotate_response.status_code == 200 + assert rotate_response.json()["workspace_id"] == "workspace-org-acme" + + +def test_org_admin_without_org_scope_is_rejected(mock_db): + async def override_get_db(): + yield mock_db + + app.dependency_overrides[get_db] = override_get_db + try: + with TestClient( + app, + headers={ + "X-User-Id": "admin", + "X-User-Role": "organization_admin", + }, + ) as client: + response = client.get("/api/runner-config") + assert response.status_code == 403 + assert response.json()["detail"] == "Organization scope is required" + finally: + app.dependency_overrides.pop(get_db, None) diff --git a/backend/tests/test_tenant_config_api.py b/backend/tests/test_tenant_config_api.py index d7f26ede1..ab06c67bf 100644 --- a/backend/tests/test_tenant_config_api.py +++ b/backend/tests/test_tenant_config_api.py @@ -71,3 +71,37 @@ def test_tenant_config_endpoint(client, mock_db): assert data["imap_port"] == 993 assert data["imap_username"] == "imap-user" assert data["google_client_secret"] is None + + +def test_tenant_config_stays_user_owned_even_for_admin_headers(client): + response = client.post( + "/api/config", + json={"user_id": "member-user", "smtp_server": "smtp.example.com"}, + headers={ + "X-User-Id": "admin", + "X-User-Role": "organization_admin", + "X-Organization-Id": "org-acme", + }, + ) + + assert response.status_code == 403 + assert response.json() == { + "detail": "Mailbox settings are personal and can only be managed by the authenticated user" + } + + +def test_tenant_config_get_rejects_cross_user_access(client): + response = client.get( + "/api/config", + params={"user_id": "member-user"}, + headers={ + "X-User-Id": "admin", + "X-User-Role": "platform_admin", + "X-Organization-Id": "org-acme", + }, + ) + + assert response.status_code == 403 + assert response.json() == { + "detail": "Mailbox settings are personal and can only be viewed by the authenticated user" + } diff --git a/docs/plans/2026-05-13-enterprise-rbac-and-responsive-workspace.md b/docs/plans/2026-05-13-enterprise-rbac-and-responsive-workspace.md new file mode 100644 index 000000000..c72fa4dc2 --- /dev/null +++ b/docs/plans/2026-05-13-enterprise-rbac-and-responsive-workspace.md @@ -0,0 +1,134 @@ +# Enterprise RBAC and Responsive Workspace Implementation Plan + +> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. + +**Goal:** Add a real enterprise-ready RBAC foundation and fix workspace responsiveness so the product matches the intended SaaS operating model and the provided UI design constraints. + +**Architecture:** Introduce a small but real authorization context around platform/organization/group/user scopes without breaking existing flows, then adjust the workspace shell so navigation and the relationship graph behave correctly across laptop zoom/resolution constraints. Keep compatibility fallbacks for the current header-based auth while preparing the backend for future Keycloak/Casdoor claims. + +**Tech Stack:** FastAPI, SQLAlchemy, Next.js App Router, TypeScript, existing workspace shell, pytest, Playwright. + +--- + +## Task 1: Formalize auth context and scoped roles + +**Files:** +- Modify: `backend/api/auth.py` +- Modify: `backend/db/models.py` +- Test: `backend/tests/test_auth_real.py` +- Test: `backend/tests/test_runner_config_api.py` + +**Step 1: Write failing tests** +- Add tests that define current role behavior for `platform_admin`, `organization_admin`, `group_admin`, `member`. +- Add tests that organization-scoped resources do not accept cross-scope access. + +**Step 2: Run test to verify failure** +Run: `cd backend && DISABLE_BACKGROUND_WORKERS=1 PYTHONWARNINGS=error python3 -m pytest tests/test_auth_real.py tests/test_runner_config_api.py -q` +Expected: FAIL because role model is not formalized. + +**Step 3: Implement minimal auth context** +- Add an `AuthContext` shape in `backend/api/auth.py` or equivalent helpers. +- Preserve current header auth fallback for local/dev. +- Encode clear scope derivation rules for organization and group access. + +**Step 4: Run tests to verify pass** +Run the same pytest command. +Expected: PASS. + +**Step 5: Commit** +`git add backend/api/auth.py backend/db/models.py backend/tests/test_auth_real.py backend/tests/test_runner_config_api.py && git commit -m "feat(auth): add scoped enterprise auth context"` + +## Task 2: Clarify settings scope and account ownership in UI/API + +**Files:** +- Modify: `frontend/src/app/settings/page.tsx` +- Modify: `backend/api/tenant_config.py` +- Test: `backend/tests/test_tenant_config_api.py` + +**Step 1: Write failing test / expected behavior** +- Define expected ownership validation for personal mailbox settings. +- Define explicit copy in settings UI for personal vs organization scope. + +**Step 2: Run backend test to verify any mismatch** +Run: `cd backend && DISABLE_BACKGROUND_WORKERS=1 PYTHONWARNINGS=error python3 -m pytest tests/test_tenant_config_api.py -q` +Expected: red on missing scoped behavior or copy mismatch if added. + +**Step 3: Implement minimal scope fixes** +- Ensure mailbox settings remain user-owned. +- Tighten API messages and UI labels if needed. + +**Step 4: Verify** +- `cd backend && DISABLE_BACKGROUND_WORKERS=1 PYTHONWARNINGS=error python3 -m pytest tests/test_tenant_config_api.py -q` +- `cd frontend && npm run build && npm run lint` + +**Step 5: Commit** +`git add frontend/src/app/settings/page.tsx backend/api/tenant_config.py backend/tests/test_tenant_config_api.py && git commit -m "fix(settings): clarify personal mailbox ownership scope"` + +## Task 3: Add sidebar scroll and preserve insight visibility + +**Files:** +- Modify: `frontend/src/components/DashboardLayout.tsx` +- Test: `frontend/src/components/DashboardLayout.test.tsx` + +**Step 1: Write/adjust failing tests** +- Add expectation that sidebar content is scrollable when vertical space is constrained. +- Add expectation that `오늘의 인사이트` remains reachable without 50% zoom hacks. + +**Step 2: Run test to verify failure** +Run: `cd frontend && npm test -- DashboardLayout.test.tsx` +Expected: FAIL. + +**Step 3: Implement minimal responsive fix** +- Make the sidebar middle region scroll independently. +- Keep footer/insight widget visible or reachable via scroll. +- Avoid collapsing the entire workspace into unusable layouts on laptop viewports. + +**Step 4: Verify** +Run: `cd frontend && npm test -- DashboardLayout.test.tsx && npm run build && npm run lint` +Expected: PASS. + +**Step 5: Commit** +`git add frontend/src/components/DashboardLayout.tsx frontend/src/components/DashboardLayout.test.tsx && git commit -m "fix(frontend): add sidebar scrolling for constrained workspace heights"` + +## Task 4: Make relationship graph responsive to viewport/zoom constraints + +**Files:** +- Modify: `frontend/src/components/NetworkGraph.tsx` +- Test: `frontend/src/components/NetworkGraph.test.tsx` + +**Step 1: Write failing test** +- Add or extend a test proving the graph container recomputes layout/fit when its viewport changes. + +**Step 2: Run test to verify failure** +Run: `cd frontend && npm test -- NetworkGraph.test.tsx` +Expected: FAIL. + +**Step 3: Implement minimal fix** +- Add resize handling and a safe `fit()` or equivalent vis-network resize path. +- Ensure graph width/height is not hard-coded in a way that ignores zoomed or constrained layouts. + +**Step 4: Verify** +Run: `cd frontend && npm test -- NetworkGraph.test.tsx && npm run build && npm run lint` +Expected: PASS. + +**Step 5: Commit** +`git add frontend/src/components/NetworkGraph.tsx frontend/src/components/NetworkGraph.test.tsx && git commit -m "fix(frontend): make relationship graph responsive to viewport changes"` + +## Task 5: Full verification and review loop + +**Files:** +- Modify as needed from review feedback + +**Step 1: Run backend suite** +Run: `cd backend && DISABLE_BACKGROUND_WORKERS=1 PYTHONWARNINGS=error python3 -m pytest -q` + +**Step 2: Run frontend suite** +Run: `cd frontend && npm test && npm run build && npm run lint` + +**Step 3: Run direct browser UAT** +- Verify settings roles and scopes +- Verify sidebar scroll on constrained viewport +- Verify graph responsiveness + +**Step 4: Commit final polish** +`git add && git commit -m "fix(workspace): polish enterprise auth and responsive shell"` diff --git a/frontend/src/components/DashboardLayout.test.tsx b/frontend/src/components/DashboardLayout.test.tsx index 320b974de..d2c427b94 100644 --- a/frontend/src/components/DashboardLayout.test.tsx +++ b/frontend/src/components/DashboardLayout.test.tsx @@ -71,4 +71,31 @@ describe("DashboardLayout", () => { expect(mobileMenuButton?.getAttribute("aria-expanded")).toBe("true"); }); + it("keeps the desktop sidebar content reachable through an independent scroll region", () => { + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + + act(() => { + root?.render( + +
Inbox workspace content
+
, + ); + }); + + const sidebar = container.querySelector('aside[aria-label="Naruon workspace sidebar"]'); + const scrollRegion = container.querySelector('[data-testid="sidebar-scroll-region"]'); + const insightHeading = Array.from(container.querySelectorAll("p")).find( + (element) => element.textContent === "오늘의 인사이트", + ); + + expect(sidebar?.className).toContain("overflow-hidden"); + expect(scrollRegion).not.toBeNull(); + expect(scrollRegion?.className).toContain("min-h-0"); + expect(scrollRegion?.className).toContain("overflow-y-auto"); + expect(scrollRegion?.textContent ?? "").toContain("오늘의 인사이트"); + expect(insightHeading?.closest('[data-testid="sidebar-scroll-region"]')).toBe(scrollRegion); + }); + }); diff --git a/frontend/src/components/DashboardLayout.tsx b/frontend/src/components/DashboardLayout.tsx index 1e8b69ac0..d10e567ad 100644 --- a/frontend/src/components/DashboardLayout.tsx +++ b/frontend/src/components/DashboardLayout.tsx @@ -143,7 +143,7 @@ export function DashboardLayout({ Skip to main content -