Skip to content
8 changes: 6 additions & 2 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
123 changes: 111 additions & 12 deletions backend/api/auth.py
Original file line number Diff line number Diff line change
@@ -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}"
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved


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")
Comment thread
seonghobae marked this conversation as resolved.
Resolved


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(
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
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
14 changes: 6 additions & 8 deletions backend/api/llm_providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"])
Expand Down Expand Up @@ -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()
Expand Down
22 changes: 14 additions & 8 deletions backend/api/runner_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -28,10 +28,12 @@ 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 _fingerprint(token: str | None) -> str | None:
Expand All @@ -43,9 +45,11 @@ 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),
):
workspace_id = auth_context.workspace_id
if auth_context.organization_id:
ensure_organization_access(auth_context, auth_context.organization_id)
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
result = await db.execute(
select(WorkspaceRunnerConfig).where(WorkspaceRunnerConfig.workspace_id == workspace_id)
)
Expand Down Expand Up @@ -73,9 +77,11 @@ 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),
):
workspace_id = auth_context.workspace_id
if auth_context.organization_id:
ensure_organization_access(auth_context, auth_context.organization_id)
result = await db.execute(
select(WorkspaceRunnerConfig).where(WorkspaceRunnerConfig.workspace_id == workspace_id)
)
Expand Down
7 changes: 5 additions & 2 deletions backend/api/tenant_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
34 changes: 34 additions & 0 deletions backend/db/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,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")

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

class PromptTemplate(Base):
__tablename__ = "prompt_templates"

Expand Down
63 changes: 62 additions & 1 deletion backend/tests/test_auth_real.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,71 @@
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():
# It should raise HTTP 401 when no auth is provided, rather than defaulting to "default".
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"
Loading
Loading