Skip to content

πŸ™Œ OpenHands: AI-Driven Development

Add X-Org-Id header validation and effective-org resolution (#14381)

chuckbutkusc1120203e082
diff --git a/enterprise/integrations/stripe_service.py b/enterprise/integrations/stripe_service.py
index 1e51c3d83f..c4075f518d 100644
--- a/enterprise/integrations/stripe_service.py
+++ b/enterprise/integrations/stripe_service.py
@@ -34,21 +34,48 @@ async def find_customer_id_by_org_id(org_id: UUID) -> str | None:
return data[0].id # type: ignore [attr-defined]
-async def find_customer_id_by_user_id(user_id: str) -> str | None:
- # First search our own DB...
+async def _resolve_org_for_user(user_id: str, org_id: UUID | None) -> Org | None:
+ """Resolve an explicit ``org_id`` to an Org, or fall back to the
+ user's current org. Returns ``None`` if neither resolves.
+ """
+ if org_id is not None:
+ org = await OrgStore.get_org_by_id(org_id)
+ if not org:
+ logger.warning(
+ 'stripe_org_not_found_for_id',
+ extra={'user_id': user_id, 'org_id': str(org_id)},
+ )
+ return org
org = await OrgStore.get_current_org_from_keycloak_user_id(user_id)
if not org:
logger.warning(f'Org not found for user {user_id}')
+ return org
+
+
+async def find_customer_id_by_user_id(
+ user_id: str, org_id: UUID | None = None
+) -> str | None:
+ """Look up the Stripe customer id for the user's billing org.
+
+ ``org_id`` should be the request's effective org (X-Org-Id / API-key
+ binding). When ``None``, falls back to the user's persisted current
+ org for backwards compatibility with non-request contexts.
+ """
+ org = await _resolve_org_for_user(user_id, org_id)
+ if not org:
return None
- customer_id = await find_customer_id_by_org_id(org.id)
- return customer_id
+ return await find_customer_id_by_org_id(org.id)
-async def find_or_create_customer_by_user_id(user_id: str) -> dict | None:
- # Get the current org for the user
- org = await OrgStore.get_current_org_from_keycloak_user_id(user_id)
+async def find_or_create_customer_by_user_id(
+ user_id: str, org_id: UUID | None = None
+) -> dict | None:
+ """Find or create the Stripe customer for the user's billing org.
+
+ See :func:`find_customer_id_by_user_id` for the ``org_id`` semantics.
+ """
+ org = await _resolve_org_for_user(user_id, org_id)
if not org:
- logger.warning(f'Org not found for user {user_id}')
return None
customer_id = await find_customer_id_by_org_id(org.id)
@@ -87,8 +114,10 @@ async def find_or_create_customer_by_user_id(user_id: str) -> dict | None:
return {'customer_id': customer.id, 'org_id': str(org.id)}
-async def has_payment_method_by_user_id(user_id: str) -> bool:
- customer_id = await find_customer_id_by_user_id(user_id)
+async def has_payment_method_by_user_id(
+ user_id: str, org_id: UUID | None = None
+) -> bool:
+ customer_id = await find_customer_id_by_user_id(user_id, org_id=org_id)
if customer_id is None:
return False
payment_methods = await stripe.Customer.list_payment_methods_async(
diff --git a/enterprise/server/auth/authorization.py b/enterprise/server/auth/authorization.py
index 628f4fb56d..196b836906 100644
--- a/enterprise/server/auth/authorization.py
+++ b/enterprise/server/auth/authorization.py
@@ -297,6 +297,18 @@ def require_permission(permission: Permission):
detail='API key is not authorized for this organization',
)
+ # If the route does not carry an ``{org_id}`` path parameter,
+ # resolve the effective org for the request β€” which honors any
+ # ``X-Org-Id`` header override (and validates membership /
+ # API-key binding in the process). This keeps endpoints that
+ # implicitly operate on the "current org" consistent with the
+ # rest of the codebase.
+ if org_id is None:
+ # Local import to avoid circular import via saas_user_auth.
+ from server.auth.org_context import maybe_resolve_effective_org_id
+
+ org_id = await maybe_resolve_effective_org_id(request)
+
user_role = await get_user_org_role(user_id, org_id)
if not user_role:
diff --git a/enterprise/server/auth/org_context.py b/enterprise/server/auth/org_context.py
new file mode 100644
index 0000000000..c6b366551a
--- /dev/null
+++ b/enterprise/server/auth/org_context.py
@@ -0,0 +1,153 @@
+"""Resolve the *effective* organization ID for the current request.
+
+Precedence (highest first):
+
+1. ``api_key_org_id`` β€” org bound to the API key used for authentication.
+ The key is pinned to that org and cannot be overridden. If an
+ ``X-Org-Id`` header is also present and differs, the request is
+ rejected with 403.
+
+2. ``X-Org-Id`` header β€” explicit, per-request override sent by the
+ client. Validated against the authenticated user's org memberships;
+ rejected with 403 if the user is not a member of that org.
+
+3. ``user.current_org_id`` β€” the user's currently selected org (as
+ mutated by ``POST /api/organizations/{org_id}/switch``). Default
+ fallback when neither of the above is supplied.
+
+The resolution is cached on ``SaasUserAuth`` for the duration of a
+single request so that downstream callers (route handlers, services,
+SAAS conversation/pending-message injectors) all see a consistent value
+without paying for the membership lookup more than once.
+"""
+
+from __future__ import annotations
+
+from uuid import UUID
+
+from fastapi import Depends, Header, HTTPException, Request, status
+from server.auth.saas_user_auth import SaasUserAuth
+from server.logger import logger
+
+from openhands.app_server.user_auth import get_user_auth
+
+X_ORG_ID_HEADER = 'X-Org-Id'
+
+
+async def resolve_effective_org_id(request: Request) -> UUID:
+ """FastAPI dependency that returns the effective org id for this request.
+
+ Raises:
+ HTTPException 400: ``X-Org-Id`` header is present but is not a UUID.
+ HTTPException 403: User is not a member of the requested org, or
+ the request authenticates with an org-bound API key whose
+ org does not match the ``X-Org-Id`` header.
+ HTTPException 404: No effective org could be determined (e.g.
+ user has no current org and did not supply the header).
+ """
+ user_auth = await get_user_auth(request)
+ if not isinstance(user_auth, SaasUserAuth):
+ # Non-SAAS deployments do not have multi-org context.
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail='Organizations are not available in this deployment',
+ )
+
+ effective_org_id = await user_auth.get_effective_org_id()
+ if effective_org_id is None:
+ logger.warning(
+ 'effective_org_id_unavailable',
+ extra={'user_id': user_auth.user_id},
+ )
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail='No current organization for user',
+ )
+ return effective_org_id
+
+
+async def maybe_resolve_effective_org_id(request: Request) -> UUID | None:
+ """Variant of :func:`resolve_effective_org_id` that returns ``None``
+ rather than 404 when no effective org can be determined.
+
+ Still raises 400/403 for malformed or unauthorized ``X-Org-Id`` headers.
+ """
+ user_auth = await get_user_auth(request)
+ if not isinstance(user_auth, SaasUserAuth):
+ return None
+ return await user_auth.get_effective_org_id()
+
+
+async def reject_x_org_id_path_mismatch(
+ request: Request,
+ x_org_id: str | None = Header(default=None, alias=X_ORG_ID_HEADER),
+) -> None:
+ """Guard for routes with ``{org_id}`` in the path.
+
+ These routes already pin the org via the URL: ``require_permission``
+ runs against the path org, and the handlers do not consult the
+ effective-org resolver. That makes any ``X-Org-Id`` header on such
+ a request *redundant at best, contradictory at worst*. We silently
+ accepted the conflict before, which masked client-state bugs (e.g.
+ a stale org selector in the frontend sending the previous org's id
+ while the user navigates to a new org's page). This dependency
+ converts that into an immediate, actionable 400.
+
+ Behavior:
+
+ * Header absent ............................. pass
+ * Header present, valid UUID, matches path .. pass
+ * Header present, valid UUID, != path ....... 400
+ * Header present, not a UUID ................ 400
+ * Path ``org_id`` itself malformed .......... pass (FastAPI's own
+ type coercion will 422 the request before the handler runs)
+
+ Attach via ``dependencies=[REJECT_X_ORG_ID_PATH_MISMATCH]`` on each
+ path-org route's decorator, or at router-level when *every* route
+ on the router has ``{org_id}`` in its prefix.
+ """
+ if x_org_id is None:
+ return
+
+ path_org_id_raw = request.path_params.get('org_id')
+ if path_org_id_raw is None:
+ # Dep was attached to a route without ``{org_id}``. Treat as a
+ # no-op so this can be attached at the router level to routers
+ # that contain routes with and without ``{org_id}`` in the path.
+ return
+
+ try:
+ header_uuid = UUID(x_org_id)
+ except (ValueError, TypeError, AttributeError):
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=f'{X_ORG_ID_HEADER} header is not a valid UUID',
+ )
+
+ try:
+ path_uuid = (
+ path_org_id_raw
+ if isinstance(path_org_id_raw, UUID)
+ else UUID(str(path_org_id_raw))
+ )
+ except (ValueError, TypeError, AttributeError):
+ # If the path UUID is malformed FastAPI's own coercion will
+ # 422 before we reach the handler. Don't shadow that error.
+ return
+
+ if header_uuid != path_uuid:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=(
+ f'{X_ORG_ID_HEADER} header ({header_uuid}) does not match '
+ f'the org in the request path ({path_uuid}). '
+ 'Remove the header or set it to the same value.'
+ ),
+ )
+
+
+# Module-level Depends shortcuts so call sites read tidily:
+# effective_org_id: UUID = EFFECTIVE_ORG_ID,
+EFFECTIVE_ORG_ID = Depends(resolve_effective_org_id)
+MAYBE_EFFECTIVE_ORG_ID = Depends(maybe_resolve_effective_org_id)
+REJECT_X_ORG_ID_PATH_MISMATCH = Depends(reject_x_org_id_path_mismatch)
diff --git a/enterprise/server/auth/saas_user_auth.py b/enterprise/server/auth/saas_user_auth.py
index 1dabc31d8b..f974833023 100644
--- a/enterprise/server/auth/saas_user_auth.py
+++ b/enterprise/server/auth/saas_user_auth.py
@@ -4,7 +4,7 @@ from types import MappingProxyType
from uuid import UUID
import jwt
-from fastapi import Request
+from fastapi import HTTPException, Request
from keycloak.exceptions import KeycloakError
from pydantic import SecretStr
from server.auth.auth_error import (
@@ -76,6 +76,13 @@ class SaasUserAuth(UserAuth):
_role: str | None = None
_permissions: list[str] | None = None
_org_info_loaded: bool = False
+ # Per-request `X-Org-Id` header (raw, unvalidated); see
+ # `enterprise/server/auth/org_context.py` for resolution rules.
+ _x_org_id_header: str | None = None
+ # Cached result of `get_effective_org_id()`. The `_resolved` flag is
+ # needed to distinguish "not yet computed" from "computed and None".
+ _effective_org_id: UUID | None = None
+ _effective_org_id_resolved: bool = False
def get_api_key_org_id(self) -> UUID | None:
"""Get the organization ID bound to the API key used for authentication.
@@ -86,6 +93,105 @@ class SaasUserAuth(UserAuth):
"""
return self.api_key_org_id
+ async def get_effective_org_id(self) -> UUID | None:
+ """Resolve the effective organization ID for this request.
+
+ Precedence (highest first):
+
+ 1. ``api_key_org_id`` β€” if the request is authenticated with an
+ org-bound API key, that org wins. If the caller also sent an
+ ``X-Org-Id`` header that disagrees, raise 403.
+ 2. ``X-Org-Id`` header β€” explicit, per-request override. The
+ authenticated user must be a member of that org or we raise
+ 403. Malformed UUIDs raise 400.
+ 3. ``user.current_org_id`` β€” server-side default.
+
+ The resolved value is cached on the auth instance for the rest
+ of the request, so callers can invoke this freely.
+
+ Raises:
+ HTTPException: 400 for a malformed header, 403 for
+ membership / API-key conflicts.
+ """
+ if self._effective_org_id_resolved:
+ return self._effective_org_id
+
+ # Import locally to avoid a circular import via authorization.py.
+ from fastapi import status
+ from storage.org_member_store import OrgMemberStore
+
+ header_value = self._x_org_id_header
+ requested: UUID | None = None
+ if header_value:
+ try:
+ requested = UUID(header_value)
+ except ValueError as exc:
+ logger.warning(
+ 'x_org_id_invalid',
+ extra={'user_id': self.user_id, 'header': header_value},
+ )
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail='Invalid X-Org-Id header (must be a UUID)',
+ ) from exc
+
+ # Case 1: API key binds the org.
+ if self.api_key_org_id is not None:
+ if requested is not None and requested != self.api_key_org_id:
+ logger.warning(
+ 'x_org_id_api_key_mismatch',
+ extra={
+ 'user_id': self.user_id,
+ 'api_key_org_id': str(self.api_key_org_id),
+ 'x_org_id': str(requested),
+ },
+ )
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail='API key is not authorized for this organization',
+ )
+ self._effective_org_id = self.api_key_org_id
+ self._effective_org_id_resolved = True
+ return self._effective_org_id
+
+ # Case 2: X-Org-Id override; verify membership.
+ if requested is not None:
+ try:
+ user_uuid = UUID(self.user_id)
+ except ValueError as exc:
+ # Shouldn't happen, but treat as not-a-member.
+ logger.error(
+ 'x_org_id_invalid_user_id',
+ extra={'user_id': self.user_id},
+ )
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail='User is not a member of the requested organization',
+ ) from exc
+ member = await OrgMemberStore.get_org_member(requested, user_uuid)
+ if member is None:
+ logger.warning(
+ 'x_org_id_not_a_member',
+ extra={
+ 'user_id': self.user_id,
+ 'x_org_id': str(requested),
+ },
+ )
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail='User is not a member of the requested organization',
+ )
+ self._effective_org_id = requested
+ self._effective_org_id_resolved = True
+ return self._effective_org_id
+
+ # Case 3: Fall back to the user's currently-selected org.
+ user = await UserStore.get_user_by_id(self.user_id)
+ if user is not None:
+ self._effective_org_id = user.current_org_id
+ self._effective_org_id_resolved = True
+ return self._effective_org_id
+
async def get_user_id(self) -> str | None:
return self.user_id
@@ -152,7 +258,15 @@ class SaasUserAuth(UserAuth):
secrets_store = self.secrets_store
if secrets_store:
return secrets_store
- secrets_store = await SaasSecretsStore.get_instance(self.user_id)
+ # Scope secrets to the request's effective org so that callers
+ # using an API key bound to org A β€” or supplying an X-Org-Id
+ # header β€” read/write secrets under that org, not under whatever
+ # `user.current_org_id` happens to point at.
+ effective_org_id = await self.get_effective_org_id()
+ secrets_store = await SaasSecretsStore.get_instance(
+ self.user_id,
+ effective_org_id=effective_org_id,
+ )
self.secrets_store = secrets_store
return secrets_store
@@ -255,16 +369,34 @@ class SaasUserAuth(UserAuth):
settings_store = self.settings_store
if settings_store:
return settings_store
- settings_store = SaasSettingsStore(self.user_id)
+ # Scope settings to the request's effective org. See
+ # `get_secrets_store` for the same rationale: the store mutates
+ # the resolved Org row (and per-member overrides), so the
+ # effective org must flow through here rather than letting the
+ # store fall back to `user.current_org_id`.
+ effective_org_id = await self.get_effective_org_id()
+ settings_store = SaasSettingsStore(
+ self.user_id, effective_org_id=effective_org_id
+ )
self.settings_store = settings_store
return settings_store
async def get_mcp_api_key(self) -> str:
api_key_store = ApiKeyStore.get_instance()
- mcp_api_key = await api_key_store.retrieve_mcp_api_key(self.user_id)
+ # Scope MCP_API_KEY to the request's effective org so that an
+ # X-Org-Id override or API-key binding produces an MCP key in
+ # the correct org context. Falls back to user.current_org_id
+ # when no SAAS auth or effective org can be resolved.
+ effective_org_id = await self.get_effective_org_id()
+ mcp_api_key = await api_key_store.retrieve_mcp_api_key(
+ self.user_id, org_id=effective_org_id
+ )
if not mcp_api_key:
mcp_api_key = await api_key_store.create_api_key(
- self.user_id, 'MCP_API_KEY', None
+ self.user_id,
+ 'MCP_API_KEY',
+ None,
+ org_id=effective_org_id,
)
return mcp_api_key
@@ -274,17 +406,19 @@ class SaasUserAuth(UserAuth):
This key is automatically generated on first access and stored as a system
key that users cannot delete or modify. It is used for automations and
integrations.
+
+ The key is scoped to the request's *effective* organization (honoring
+ an ``X-Org-Id`` override or API-key binding) rather than the user's
+ persisted ``current_org_id``.
"""
- user = await UserStore.get_user_by_id(self.user_id)
- if user is None:
- raise ValueError(f'User not found: {self.user_id}')
- if user.current_org_id is None:
+ effective_org_id = await self.get_effective_org_id()
+ if effective_org_id is None:
raise ValueError(f'User {self.user_id} has no current organization')
api_key_store = ApiKeyStore.get_instance()
openhands_api_key = await api_key_store.get_or_create_system_api_key(
user_id=self.user_id,
- org_id=user.current_org_id,
+ org_id=effective_org_id,
name='OPENHANDS_API_KEY',
)
return openhands_api_key
@@ -315,22 +449,26 @@ class SaasUserAuth(UserAuth):
self._org_info_loaded = True
try:
- # Get user and their current org
- user = await UserStore.get_user_by_id(self.user_id)
- if not user:
- logger.warning(f'User {self.user_id} not found for org info')
+ # Use the effective org id so that requests carrying an
+ # X-Org-Id override (or an org-bound API key) see info for
+ # the org they're actually operating in, not the user's
+ # persisted current_org_id.
+ effective_org_id = await self.get_effective_org_id()
+ if effective_org_id is None:
+ logger.warning(
+ f'No effective org for user {self.user_id} in get_org_info'
+ )
return None
- # Get the current org
- org = await OrgStore.get_org_by_id(user.current_org_id)
+ org = await OrgStore.get_org_by_id(effective_org_id)
if not org:
logger.warning(
- f'Organization {user.current_org_id} not found for user {self.user_id}'
+ f'Organization {effective_org_id} not found for user {self.user_id}'
)
return None
- # Get user's role in the current org
- role = await get_user_org_role(self.user_id, user.current_org_id)
+ # Get user's role in that org
+ role = await get_user_org_role(self.user_id, effective_org_id)
role_name = role.name if role else None
# Get permissions for the role
@@ -340,7 +478,7 @@ class SaasUserAuth(UserAuth):
permissions = [p.value for p in role_permissions]
# Cache the results
- self._org_id = str(user.current_org_id)
+ self._org_id = str(effective_org_id)
self._org_name = org.name
self._role = role_name
self._permissions = permissions
@@ -351,6 +489,9 @@ class SaasUserAuth(UserAuth):
'role': self._role,
'permissions': self._permissions,
}
+ except HTTPException:
+ # Propagate validation errors raised by get_effective_org_id().
+ raise
except Exception as e:
logger.error(f'Error fetching org info for user {self.user_id}: {e}')
return None
@@ -367,6 +508,10 @@ class SaasUserAuth(UserAuth):
if instance is None:
logger.debug('saas_user_auth_get_instance:no_credentials')
raise NoCredentialsError('failed to authenticate')
+ # Capture the raw X-Org-Id header (if any) so it can be validated
+ # lazily by `get_effective_org_id()` the first time the request
+ # needs an org context. See `server.auth.org_context`.
+ instance._x_org_id_header = request.headers.get('X-Org-Id')
if not getattr(request.state, 'user_rate_limit_processed', False):
user_id = await instance.get_user_id()
if user_id:
diff --git a/enterprise/server/routes/api_keys.py b/enterprise/server/routes/api_keys.py
index b11e1a9aa5..83af3e8967 100644
--- a/enterprise/server/routes/api_keys.py
+++ b/enterprise/server/routes/api_keys.py
@@ -1,8 +1,10 @@
from datetime import UTC, datetime
from typing import cast
+from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Request, status
from pydantic import BaseModel, field_validator
+from server.auth.org_context import EFFECTIVE_ORG_ID
from server.auth.saas_user_auth import SaasUserAuth
from storage.api_key import ApiKey
from storage.api_key_store import ApiKeyStore
@@ -18,54 +20,49 @@ from openhands.app_server.utils.logger import openhands_logger as logger
# Helper functions for BYOR API key management
-async def get_byor_key_from_db(user_id: str) -> str | None:
- """Get the BYOR key from the database for a user."""
+async def get_byor_key_from_db(user_id: str, org_id: UUID) -> str | None:
+ """Get the BYOR key from the database for a user in a specific org."""
user = await UserStore.get_user_by_id(user_id)
if not user:
return None
- current_org_id = user.current_org_id
- current_org_member: OrgMember | None = None
- for org_member in user.org_members:
- if org_member.org_id == current_org_id:
- current_org_member = org_member
+ org_member: OrgMember | None = None
+ for member in user.org_members:
+ if member.org_id == org_id:
+ org_member = member
break
- if not current_org_member:
+ if not org_member:
return None
- if current_org_member.llm_api_key_for_byor:
- return current_org_member.llm_api_key_for_byor.get_secret_value()
+ if org_member.llm_api_key_for_byor:
+ return org_member.llm_api_key_for_byor.get_secret_value()
return None
-async def store_byor_key_in_db(user_id: str, key: str) -> None:
- """Store the BYOR key in the database for a user."""
+async def store_byor_key_in_db(user_id: str, org_id: UUID, key: str) -> None:
+ """Store the BYOR key in the database for a user in a specific org."""
user = await UserStore.get_user_by_id(user_id)
if not user:
return None
- current_org_id = user.current_org_id
- current_org_member: OrgMember | None = None
- for org_member in user.org_members:
- if org_member.org_id == current_org_id:
- current_org_member = org_member
+ org_member: OrgMember | None = None
+ for member in user.org_members:
+ if member.org_id == org_id:
+ org_member = member
break
- if not current_org_member:
+ if not org_member:
return None
- current_org_member.llm_api_key_for_byor = key
- await OrgMemberStore.update_org_member(current_org_member)
+ org_member.llm_api_key_for_byor = key
+ await OrgMemberStore.update_org_member(org_member)
-async def generate_byor_key(user_id: str) -> str | None:
- """Generate a new BYOR key for a user."""
+async def generate_byor_key(user_id: str, org_id: UUID) -> str | None:
+ """Generate a new BYOR key for a user in a specific org."""
try:
- user = await UserStore.get_user_by_id(user_id)
- if not user:
- return None
- current_org_id = str(user.current_org_id)
+ org_id_str = str(org_id)
key = await LiteLlmManager.generate_key(
user_id,
- current_org_id,
- f'BYOR Key - user {user_id}, org {current_org_id}',
+ org_id_str,
+ f'BYOR Key - user {user_id}, org {org_id_str}',
{'type': 'byor'},
)
@@ -86,19 +83,16 @@ async def generate_byor_key(user_id: str) -> str | None:
return None
-async def delete_byor_key_from_litellm(user_id: str, byor_key: str) -> bool:
+async def delete_byor_key_from_litellm(
+ user_id: str, org_id: UUID, byor_key: str
+) -> bool:
"""Delete the BYOR key from LiteLLM using the key directly.
Also attempts to delete by key alias if the key is not found,
to clean up orphaned aliases that could block key regeneration.
"""
try:
- # Get user to construct the key alias
- user = await UserStore.get_user_by_id(user_id)
- key_alias = None
- if user and user.current_org_id:
- key_alias = f'BYOR Key - user {user_id}, org {user.current_org_id}'
-
+ key_alias = f'BYOR Key - user {user_id}, org {org_id}'
await LiteLlmManager.delete_key(byor_key, key_alias=key_alias)
logger.info(
'Successfully deleted BYOR key from LiteLLM',
@@ -177,10 +171,13 @@ def api_key_to_response(key: ApiKey) -> ApiKeyResponse:
@api_router.get('/llm/byor/permitted', tags=['Keys'])
async def check_byor_permitted(
user_id: str = Depends(get_user_id),
+ effective_org_id: UUID = EFFECTIVE_ORG_ID,
) -> ByorPermittedResponse:
- """Check if BYOR key export is permitted for the user's current org."""
+ """Check if BYOR key export is permitted for the request's effective org."""
try:
- permitted = await OrgService.check_byor_export_enabled(user_id)
+ permitted = await OrgService.check_byor_export_enabled(
+ user_id, org_id=effective_org_id
+ )
return ByorPermittedResponse(permitted=permitted)
except Exception as e:
logger.exception(
@@ -194,15 +191,20 @@ async def check_byor_permitted(
@api_router.post('', tags=['Keys'])
async def create_api_key(
- key_data: ApiKeyCreate, user_id: str = Depends(get_user_id)
+ key_data: ApiKeyCreate,
+ user_id: str = Depends(get_user_id),
+ effective_org_id: UUID = EFFECTIVE_ORG_ID,
) -> ApiKeyCreateResponse:
- """Create a new API key for the authenticated user."""
+ """Create a new API key bound to the request's effective org."""
try:
api_key = await api_key_store.create_api_key(
- user_id, key_data.name, key_data.expires_at
+ user_id,
+ key_data.name,
+ key_data.expires_at,
+ org_id=effective_org_id,
)
# Get the created key details
- keys = await api_key_store.list_api_keys(user_id)
+ keys = await api_key_store.list_api_keys(user_id, org_id=effective_org_id)
for key in keys:
if key.name == key_data.name:
return ApiKeyCreateResponse(
@@ -222,10 +224,13 @@ async def create_api_key(
@api_router.get('', tags=['Keys'])
-async def list_api_keys(user_id: str = Depends(get_user_id)) -> list[ApiKeyResponse]:
- """List all API keys for the authenticated user."""
+async def list_api_keys(
+ user_id: str = Depends(get_user_id),
+ effective_org_id: UUID = EFFECTIVE_ORG_ID,
+) -> list[ApiKeyResponse]:
+ """List API keys for the authenticated user in the effective org."""
try:
- keys = await api_key_store.list_api_keys(user_id)
+ keys = await api_key_store.list_api_keys(user_id, org_id=effective_org_id)
return [api_key_to_response(key) for key in keys]
except Exception:
logger.exception('Error listing API keys')
@@ -237,12 +242,14 @@ async def list_api_keys(user_id: str = Depends(get_user_id)) -> list[ApiKeyRespo
@api_router.delete('/{key_id}', tags=['Keys'])
async def delete_api_key(
- key_id: int, user_id: str = Depends(get_user_id)
+ key_id: int,
+ user_id: str = Depends(get_user_id),
+ effective_org_id: UUID = EFFECTIVE_ORG_ID,
) -> MessageResponse:
- """Delete an API key."""
+ """Delete an API key, scoped to the effective org."""
try:
- # First, verify the key belongs to the user
- keys = await api_key_store.list_api_keys(user_id)
+ # First, verify the key belongs to the user in this org.
+ keys = await api_key_store.list_api_keys(user_id, org_id=effective_org_id)
key_to_delete = None
for key in keys:
@@ -318,25 +325,28 @@ async def get_current_api_key(
@api_router.get('/llm/byor', tags=['Keys'])
async def get_llm_api_key_for_byor(
user_id: str = Depends(get_user_id),
+ effective_org_id: UUID = EFFECTIVE_ORG_ID,
) -> LlmApiKeyResponse:
- """Get the LLM API key for BYOR (Bring Your Own Runtime) for the authenticated user.
+ """Get the LLM API key for BYOR (Bring Your Own Runtime).
This endpoint validates that the key exists in LiteLLM before returning it.
If validation fails, it automatically generates a new key to ensure users
always receive a working key.
- Returns 402 Payment Required if BYOR export is not enabled for the user's org.
+ Returns 402 Payment Required if BYOR export is not enabled for the
+ request's effective org.
"""
try:
- # Check if BYOR export is enabled for the user's org
- if not await OrgService.check_byor_export_enabled(user_id):
+ if not await OrgService.check_byor_export_enabled(
+ user_id, org_id=effective_org_id
+ ):
raise HTTPException(
status_code=status.HTTP_402_PAYMENT_REQUIRED,
detail='BYOR key export is not enabled. Purchase credits to enable this feature.',
)
# Check if the BYOR key exists in the database
- byor_key = await get_byor_key_from_db(user_id)
+ byor_key = await get_byor_key_from_db(user_id, effective_org_id)
if byor_key:
# Validate that the key is actually registered in LiteLLM
is_valid = await LiteLlmManager.verify_key(byor_key, user_id)
@@ -354,14 +364,14 @@ async def get_llm_api_key_for_byor(
},
)
# Delete the invalid key from LiteLLM (best effort, don't fail if it doesn't exist)
- await delete_byor_key_from_litellm(user_id, byor_key)
+ await delete_byor_key_from_litellm(user_id, effective_org_id, byor_key)
# Fall through to generate a new key
# Generate a new key for BYOR (either no key exists or validation failed)
- key = await generate_byor_key(user_id)
+ key = await generate_byor_key(user_id, effective_org_id)
if key:
# Store the key in the database
- await store_byor_key_in_db(user_id, key)
+ await store_byor_key_in_db(user_id, effective_org_id, key)
logger.info(
'Successfully generated and stored new BYOR key',
extra={'user_id': user_id},
@@ -391,28 +401,31 @@ async def get_llm_api_key_for_byor(
@api_router.post('/llm/byor/refresh', tags=['Keys'])
async def refresh_llm_api_key_for_byor(
user_id: str = Depends(get_user_id),
+ effective_org_id: UUID = EFFECTIVE_ORG_ID,
) -> LlmApiKeyResponse:
- """Refresh the LLM API key for BYOR (Bring Your Own Runtime) for the authenticated user.
+ """Refresh the LLM API key for BYOR (Bring Your Own Runtime).
- Returns 402 Payment Required if BYOR export is not enabled for the user's org.
+ Returns 402 Payment Required if BYOR export is not enabled for the
+ request's effective org.
"""
logger.info('Starting BYOR LLM API key refresh', extra={'user_id': user_id})
try:
- # Check if BYOR export is enabled for the user's org
- if not await OrgService.check_byor_export_enabled(user_id):
+ if not await OrgService.check_byor_export_enabled(
+ user_id, org_id=effective_org_id
+ ):
raise HTTPException(
status_code=status.HTTP_402_PAYMENT_REQUIRED,
detail='BYOR key export is not enabled. Purchase credits to enable this feature.',
)
# Get the existing BYOR key from the database
- existing_byor_key = await get_byor_key_from_db(user_id)
+ existing_byor_key = await get_byor_key_from_db(user_id, effective_org_id)
# If we have an existing key, delete it from LiteLLM
if existing_byor_key:
delete_success = await delete_byor_key_from_litellm(
- user_id, existing_byor_key
+ user_id, effective_org_id, existing_byor_key
)
if not delete_success:
logger.warning(
@@ -426,7 +439,7 @@ async def refresh_llm_api_key_for_byor(
)
# Generate a new key
- key = await generate_byor_key(user_id)
+ key = await generate_byor_key(user_id, effective_org_id)
if not key:
logger.error(
'Failed to generate new BYOR LLM API key',
@@ -438,7 +451,7 @@ async def refresh_llm_api_key_for_byor(
)
# Store the key in the database
- await store_byor_key_in_db(user_id, key)
+ await store_byor_key_in_db(user_id, effective_org_id, key)
logger.info(
'BYOR LLM API key refresh completed successfully',
diff --git a/enterprise/server/routes/billing.py b/enterprise/server/routes/billing.py
index 0bd8ecf55a..b1fc6ead39 100644
--- a/enterprise/server/routes/billing.py
+++ b/enterprise/server/routes/billing.py
@@ -3,12 +3,14 @@ import typing
from datetime import UTC, datetime
from decimal import Decimal
from enum import Enum
+from uuid import UUID
import stripe
from fastapi import APIRouter, Depends, HTTPException, Request, status
from fastapi.responses import RedirectResponse
from integrations import stripe_service
from pydantic import BaseModel
+from server.auth.org_context import EFFECTIVE_ORG_ID
from server.constants import STRIPE_API_KEY
from server.logger import logger
from server.utils.url_utils import get_web_url
@@ -86,17 +88,17 @@ def calculate_credits(user_info: LiteLlmUserInfo) -> float:
# Endpoint to retrieve the current organization's credit balance
@billing_router.get('/credits')
-async def get_credits(user_id: str = Depends(get_user_id)) -> GetCreditsResponse:
+async def get_credits(
+ user_id: str = Depends(get_user_id),
+ effective_org_id: UUID = EFFECTIVE_ORG_ID,
+) -> GetCreditsResponse:
if not stripe_service.STRIPE_API_KEY:
return GetCreditsResponse()
- user = await UserStore.get_user_by_id(user_id)
- if user is None:
- raise HTTPException(status.HTTP_404_NOT_FOUND, detail='User not found')
user_team_info = await LiteLlmManager.get_user_team_info(
- user_id, str(user.current_org_id)
+ user_id, str(effective_org_id)
)
max_budget, spend = LiteLlmManager.get_budget_from_team_info(
- user_team_info, user_id, str(user.current_org_id)
+ user_team_info, user_id, str(effective_org_id)
)
credits = max(max_budget - spend, 0)
return GetCreditsResponse(credits=Decimal('{:.2f}'.format(credits)))
@@ -132,19 +134,28 @@ async def get_subscription_access(
# Endpoint to check if a user has entered a payment method into stripe
@billing_router.post('/has-payment-method')
-async def has_payment_method(user_id: str = Depends(get_user_id)) -> bool:
+async def has_payment_method(
+ user_id: str = Depends(get_user_id),
+ effective_org_id: UUID = EFFECTIVE_ORG_ID,
+) -> bool:
if not user_id:
raise HTTPException(status.HTTP_401_UNAUTHORIZED)
- return await stripe_service.has_payment_method_by_user_id(user_id)
+ return await stripe_service.has_payment_method_by_user_id(
+ user_id, org_id=effective_org_id
+ )
# Endpoint to create a new setup intent in stripe
@billing_router.post('/create-customer-setup-session')
async def create_customer_setup_session(
- request: Request, user_id: str = Depends(get_user_id)
+ request: Request,
+ user_id: str = Depends(get_user_id),
+ effective_org_id: UUID = EFFECTIVE_ORG_ID,
) -> CreateBillingSessionResponse:
await validate_billing_enabled()
- customer_info = await stripe_service.find_or_create_customer_by_user_id(user_id)
+ customer_info = await stripe_service.find_or_create_customer_by_user_id(
+ user_id, org_id=effective_org_id
+ )
if not customer_info:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
@@ -167,10 +178,13 @@ async def create_checkout_session(
body: CreateCheckoutSessionRequest,
request: Request,
user_id: str = Depends(get_user_id),
+ effective_org_id: UUID = EFFECTIVE_ORG_ID,
) -> CreateBillingSessionResponse:
await validate_billing_enabled()
base_url = get_web_url(request)
- customer_info = await stripe_service.find_or_create_customer_by_user_id(user_id)
+ customer_info = await stripe_service.find_or_create_customer_by_user_id(
+ user_id, org_id=effective_org_id
+ )
if not customer_info:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
diff --git a/enterprise/server/routes/org_invitations.py b/enterprise/server/routes/org_invitations.py
index 5b6ebade9e..f04ec035f9 100644
--- a/enterprise/server/routes/org_invitations.py
+++ b/enterprise/server/routes/org_invitations.py
@@ -4,6 +4,7 @@ from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Request, status
from fastapi.responses import RedirectResponse
+from server.auth.org_context import REJECT_X_ORG_ID_PATH_MISMATCH
from server.routes.org_invitation_models import (
AcceptInvitationRequest,
AcceptInvitationResponse,
@@ -26,10 +27,19 @@ from openhands.analytics import get_analytics_service
from openhands.app_server.user_auth import get_user_id
from openhands.app_server.utils.logger import openhands_logger as logger
-# Router for invitation operations on an organization (requires org_id)
-invitation_router = APIRouter(prefix='/api/organizations/{org_id}/members')
+# Router for invitation operations on an organization (requires org_id).
+# Every route under this prefix has ``{org_id}`` in its path, so we
+# attach REJECT_X_ORG_ID_PATH_MISMATCH at the router level β€” a request
+# with a conflicting ``X-Org-Id`` is rejected before any handler runs.
+invitation_router = APIRouter(
+ prefix='/api/organizations/{org_id}/members',
+ dependencies=[REJECT_X_ORG_ID_PATH_MISMATCH],
+)
-# Router for accepting invitations (no org_id required)
+# Router for accepting invitations (no org_id in path; the target org
+# is encoded in the invitation token). X-Org-Id has no meaning here
+# and must not influence which invitation is accepted, so the guard
+# is intentionally NOT attached.
accept_router = APIRouter(prefix='/api/organizations/members/invite')
diff --git a/enterprise/server/routes/orgs.py b/enterprise/server/routes/orgs.py
index 541a9cb176..2e2e614559 100644
--- a/enterprise/server/routes/orgs.py
+++ b/enterprise/server/routes/orgs.py
@@ -7,6 +7,7 @@ from server.auth.authorization import (
require_financial_data_access,
require_permission,
)
+from server.auth.org_context import EFFECTIVE_ORG_ID, REJECT_X_ORG_ID_PATH_MISMATCH
from server.email_validation import get_admin_user_id
from server.routes.org_models import (
CannotModifySelfError,
@@ -55,7 +56,11 @@ from openhands.app_server.user_auth import get_user_id
from openhands.app_server.utils.logger import openhands_logger as logger
# Initialize API router
-org_router = APIRouter(prefix='/api/organizations', tags=['Orgs'])
+org_router = APIRouter(
+ prefix='/api/organizations',
+ tags=['Orgs'],
+ dependencies=[REJECT_X_ORG_ID_PATH_MISMATCH],
+)
# Create injector instance and dependency at module level
_org_app_settings_injector = OrgAppSettingsServiceInjector()
@@ -222,7 +227,10 @@ async def create_org(
)
-@org_router.get('/{org_id}/settings', response_model=OrgDefaultsSettingsResponse)
+@org_router.get(
+ '/{org_id}/settings',
+ response_model=OrgDefaultsSettingsResponse,
+)
async def get_org_defaults_settings(
org_id: UUID,
user_id: str = Depends(require_permission(Permission.VIEW_ORG_SETTINGS)),
@@ -247,7 +255,10 @@ async def get_org_defaults_settings(
)
-@org_router.patch('/{org_id}/settings', response_model=OrgDefaultsSettingsResponse)
+@org_router.patch(
+ '/{org_id}/settings',
+ response_model=OrgDefaultsSettingsResponse,
+)
async def update_org_defaults_settings(
org_id: UUID,
settings: OrgUpdate,
@@ -310,14 +321,16 @@ async def update_org_defaults_settings(
deprecated=True,
)
async def get_legacy_org_defaults_settings(
+ effective_org_id: UUID = EFFECTIVE_ORG_ID,
user_id: str = Depends(require_permission(Permission.VIEW_LLM_SETTINGS)),
) -> OrgDefaultsSettingsResponse:
- """Get org-default settings through the deprecated ``/llm`` wrapper."""
+ """Get org-default settings through the deprecated ``/llm`` wrapper.
+
+ The org is the request's *effective* org (``X-Org-Id`` > API-key
+ binding > ``user.current_org_id``).
+ """
try:
- org = await OrgStore.get_current_org_from_keycloak_user_id(user_id)
- if not org:
- raise OrgNotFoundError('current')
- return await get_org_defaults_settings(org_id=org.id, user_id=user_id)
+ return await get_org_defaults_settings(org_id=effective_org_id, user_id=user_id)
except OrgNotFoundError as e:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
@@ -343,17 +356,18 @@ async def get_legacy_org_defaults_settings(
)
async def update_legacy_org_defaults_settings(
settings: OrgUpdate,
+ effective_org_id: UUID = EFFECTIVE_ORG_ID,
user_id: str = Depends(require_permission(Permission.EDIT_LLM_SETTINGS)),
) -> OrgDefaultsSettingsResponse:
"""Update org-default settings through the deprecated ``/llm`` wrapper."""
try:
- org = await OrgStore.get_current_org_from_keycloak_user_id(user_id)
- if not org:
- raise OrgNotFoundError('current')
if not settings.has_updates():
+ org = await OrgStore.get_org_by_id(effective_org_id)
+ if not org:
+ raise OrgNotFoundError(str(effective_org_id))
return OrgDefaultsSettingsResponse.from_org(org)
return await update_org_defaults_settings(
- org_id=org.id,
+ org_id=effective_org_id,
settings=settings,
user_id=user_id,
)
@@ -507,7 +521,10 @@ async def get_org(
)
-@org_router.get('/{org_id}/me', response_model=MeResponse)
+@org_router.get(
+ '/{org_id}/me',
+ response_model=MeResponse,
+)
async def get_me(
org_id: UUID,
user_id: str = Depends(get_user_id),
@@ -566,7 +583,10 @@ async def get_me(
)
-@org_router.delete('/{org_id}', status_code=status.HTTP_200_OK)
+@org_router.delete(
+ '/{org_id}',
+ status_code=status.HTTP_200_OK,
+)
async def delete_org(
org_id: UUID,
user_id: str = Depends(require_permission(Permission.DELETE_ORGANIZATION)),
@@ -675,7 +695,10 @@ async def delete_org(
)
-@org_router.patch('/{org_id}', response_model=OrgResponse)
+@org_router.patch(
+ '/{org_id}',
+ response_model=OrgResponse,
+)
async def update_org(
org_id: UUID,
update_data: OrgUpdate,
@@ -760,7 +783,9 @@ async def update_org(
)
-@org_router.get('/{org_id}/members')
+@org_router.get(
+ '/{org_id}/members',
+)
async def get_org_members(
org_id: UUID,
page_id: Annotated[
@@ -863,7 +888,9 @@ async def get_org_members(
)
-@org_router.get('/{org_id}/members/count')
+@org_router.get(
+ '/{org_id}/members/count',
+)
async def get_org_members_count(
org_id: UUID,
email: Annotated[
@@ -1019,7 +1046,9 @@ async def get_org_members_financial(
)
-@org_router.delete('/{org_id}/members/{user_id}')
+@org_router.delete(
+ '/{org_id}/members/{user_id}',
+)
async def remove_org_member(
org_id: UUID,
user_id: str,
@@ -1096,7 +1125,9 @@ async def remove_org_member(
@org_router.post(
- '/{org_id}/switch', response_model=OrgResponse, status_code=status.HTTP_200_OK
+ '/{org_id}/switch',
+ response_model=OrgResponse,
+ status_code=status.HTTP_200_OK,
)
async def switch_org(
org_id: UUID,
@@ -1192,7 +1223,10 @@ async def switch_org(
)
-@org_router.patch('/{org_id}/members/{user_id}', response_model=OrgMemberResponse)
+@org_router.patch(
+ '/{org_id}/members/{user_id}',
+ response_model=OrgMemberResponse,
+)
async def update_org_member(
org_id: UUID,
user_id: str,
diff --git a/enterprise/server/services/org_app_settings_service.py b/enterprise/server/services/org_app_settings_service.py
index 432d11ab4c..16387ea87b 100644
--- a/enterprise/server/services/org_app_settings_service.py
+++ b/enterprise/server/services/org_app_settings_service.py
@@ -15,6 +15,7 @@ from server.routes.org_models import (
OrgAppSettingsUpdate,
OrgNotFoundError,
)
+from storage.org import Org
from storage.org_app_settings_store import OrgAppSettingsStore
from openhands.app_server.errors import AuthError
@@ -30,6 +31,37 @@ class OrgAppSettingsService:
store: OrgAppSettingsStore
user_context: UserContext
+ async def _resolve_effective_org(self) -> tuple[str, Org]:
+ """Resolve the request's effective organization.
+
+ Honors ``X-Org-Id`` / API-key binding via
+ ``SaasUserAuth.get_effective_org_id`` and falls back to
+ ``user.current_org_id`` for non-SAAS deployments.
+
+ Returns:
+ Tuple of (user_id, org).
+
+ Raises:
+ AuthError: User not authenticated.
+ OrgNotFoundError: No org could be resolved for the user.
+ """
+ user_id = await self.user_context.get_user_id()
+ if not user_id:
+ raise AuthError('User not authenticated')
+
+ user_auth = getattr(self.user_context, 'user_auth', None)
+ effective_org_id = None
+ if user_auth is not None and hasattr(user_auth, 'get_effective_org_id'):
+ effective_org_id = await user_auth.get_effective_org_id()
+
+ if effective_org_id is not None:
+ org = await self.store.get_org_by_id(effective_org_id)
+ else:
+ org = await self.store.get_current_org_by_user_id(user_id)
+ if not org:
+ raise OrgNotFoundError('current')
+ return user_id, org
+
async def get_org_app_settings(self) -> OrgAppSettingsResponse:
"""Get organization app settings.
@@ -39,23 +71,15 @@ class OrgAppSettingsService:
OrgAppSettingsResponse: The organization's app settings
Raises:
- OrgNotFoundError: If current organization is not found
+ OrgNotFoundError: If effective organization is not found
AuthError: If user is not authenticated
"""
- user_id = await self.user_context.get_user_id()
- if not user_id:
- raise AuthError('User not authenticated')
+ user_id, org = await self._resolve_effective_org()
logger.info(
'Getting organization app settings',
- extra={'user_id': user_id},
+ extra={'user_id': user_id, 'org_id': str(org.id)},
)
-
- org = await self.store.get_current_org_by_user_id(user_id)
-
- if not org:
- raise OrgNotFoundError('current')
-
return OrgAppSettingsResponse.from_org(org)
async def update_org_app_settings(
@@ -78,21 +102,13 @@ class OrgAppSettingsService:
OrgNotFoundError: If current organization is not found
AuthError: If user is not authenticated
"""
- user_id = await self.user_context.get_user_id()
- if not user_id:
- raise AuthError('User not authenticated')
+ user_id, org = await self._resolve_effective_org()
logger.info(
'Updating organization app settings',
- extra={'user_id': user_id},
+ extra={'user_id': user_id, 'org_id': str(org.id)},
)
- # Get current org first
- org = await self.store.get_current_org_by_user_id(user_id)
-
- if not org:
- raise OrgNotFoundError('current')
-
# Check if any fields are provided
update_dict = update_data.model_dump(exclude_unset=True)
diff --git a/enterprise/server/utils/saas_app_conversation_info_injector.py b/enterprise/server/utils/saas_app_conversation_info_injector.py
index e99cd8e87c..dbc523c0b5 100644
--- a/enterprise/server/utils/saas_app_conversation_info_injector.py
+++ b/enterprise/server/utils/saas_app_conversation_info_injector.py
@@ -53,7 +53,9 @@ class SaasSQLAppConversationInfoService(SQLAppConversationInfoService):
Filters conversations by:
- user_id: Only show conversations belonging to the current user
- - org_id: Only show conversations belonging to the user's current organization
+ - org_id: Only show conversations belonging to the request's
+ *effective* organization (honors ``X-Org-Id`` and API-key org
+ binding; falls back to ``user.current_org_id``).
Args:
query: SQLAlchemy query to apply filters to
@@ -78,15 +80,29 @@ class SaasSQLAppConversationInfoService(SQLAppConversationInfoService):
user_id_uuid = UUID(user_id_str)
query = query.where(StoredConversationMetadataSaas.user_id == user_id_uuid)
- # Filter by organization ID to ensure conversations are isolated per organization
- user = await self._get_current_user()
- if user and user.current_org_id is not None:
+ # Filter by the *effective* organization id (X-Org-Id override or
+ # API-key binding take precedence over user.current_org_id).
+ effective_org_id = await self._get_effective_org_id()
+ if effective_org_id is not None:
query = query.where(
- StoredConversationMetadataSaas.org_id == user.current_org_id
+ StoredConversationMetadataSaas.org_id == effective_org_id
)
return query
+ async def _get_effective_org_id(self) -> UUID | None:
+ """Resolve the effective org id for the active user context.
+
+ Returns the request's effective org id (X-Org-Id > api_key_org_id >
+ user.current_org_id) when the user is authenticated via SAAS auth,
+ otherwise falls back to the user's persisted current_org_id.
+ """
+ user_auth = getattr(self.user_context, 'user_auth', None)
+ if user_auth is not None and hasattr(user_auth, 'get_effective_org_id'):
+ return await user_auth.get_effective_org_id()
+ user = await self._get_current_user()
+ return user.current_org_id if user else None
+
async def _secure_select(self):
query = (
select(StoredConversationMetadata)
@@ -354,16 +370,18 @@ class SaasSQLAppConversationInfoService(SQLAppConversationInfoService):
user = user_result.scalar_one_or_none()
assert user
- # Determine org_id: prefer API key's org_id if authenticated via API key
- org_id = user.current_org_id # Default fallback
- if hasattr(self.user_context, 'user_auth'):
- user_auth = self.user_context.user_auth
- if hasattr(user_auth, 'get_api_key_org_id'):
- api_key_org_id = user_auth.get_api_key_org_id()
- if api_key_org_id is not None:
- org_id = api_key_org_id
-
- # Override with resolver org_id if set (from git org claim resolution)
+ # Determine org_id. The effective org id resolver handles
+ # the X-Org-Id > api_key_org_id > current_org_id precedence;
+ # we fall back to user.current_org_id for the ADMIN/webhook
+ # path where no user_auth is attached.
+ org_id = await self._get_effective_org_id()
+ if org_id is None:
+ org_id = user.current_org_id
+
+ # Override with resolver org_id if set (from git org claim resolution).
+ # This intentionally trumps the effective org because resolver
+ # conversations are authored against a webhook-resolved org,
+ # not the caller's session org.
resolver_org_id = getattr(self.user_context, 'resolver_org_id', None)
if resolver_org_id is not None:
org_id = resolver_org_id
diff --git a/enterprise/server/utils/saas_pending_message_injector.py b/enterprise/server/utils/saas_pending_message_injector.py
index fa47152801..a6f07b3e83 100644
--- a/enterprise/server/utils/saas_pending_message_injector.py
+++ b/enterprise/server/utils/saas_pending_message_injector.py
@@ -51,6 +51,18 @@ class SaasSQLPendingMessageService(SQLPendingMessageService):
)
return result.scalars().first()
+ async def _get_effective_org_id(self) -> UUID | None:
+ """Resolve the effective org id for the active user context.
+
+ Prefers the X-Org-Id / API-key-bound org, falling back to the
+ user's persisted current_org_id when no SAAS auth is present.
+ """
+ user_auth = getattr(self.user_context, 'user_auth', None)
+ if user_auth is not None and hasattr(user_auth, 'get_effective_org_id'):
+ return await user_auth.get_effective_org_id()
+ user = await self._get_current_user()
+ return user.current_org_id if user else None
+
async def _validate_conversation_ownership(self, conversation_id: str) -> None:
"""Validate that the current user owns the conversation.
@@ -92,10 +104,14 @@ class SaasSQLPendingMessageService(SQLPendingMessageService):
if saas_metadata.user_id != user_id_uuid:
raise AuthError('You do not have access to this conversation')
- # Verify organization ownership if applicable
- user = await self._get_current_user()
- if user and user.current_org_id is not None:
- if saas_metadata.org_id != user.current_org_id:
+ # Verify the conversation belongs to the request's *effective*
+ # organization (honors X-Org-Id / API-key binding) rather than
+ # the user's persisted current_org_id. This unblocks API-key
+ # callers whose key was minted before the user last switched
+ # orgs.
+ effective_org_id = await self._get_effective_org_id()
+ if effective_org_id is not None:
+ if saas_metadata.org_id != effective_org_id:
raise AuthError('Conversation belongs to a different organization')
async def add_message(
diff --git a/enterprise/storage/api_key_store.py b/enterprise/storage/api_key_store.py
index e26bfe2f10..ce83e392c6 100644
--- a/enterprise/storage/api_key_store.py
+++ b/enterprise/storage/api_key_store.py
@@ -51,7 +51,11 @@ class ApiKeyStore:
return f'{cls.SYSTEM_KEY_NAME_PREFIX}{name}'
async def create_api_key(
- self, user_id: str, name: str | None = None, expires_at: datetime | None = None
+ self,
+ user_id: str,
+ name: str | None = None,
+ expires_at: datetime | None = None,
+ org_id: UUID | None = None,
) -> str:
"""Create a new API key for a user.
@@ -60,15 +64,20 @@ class ApiKeyStore:
name: Optional name for the key
expires_at: Expiration datetime in UTC. Timezone info is stripped before
writing to the TIMESTAMP WITHOUT TIME ZONE column.
+ org_id: Optional explicit org binding. When omitted, falls back
+ to the user's persisted ``current_org_id``. Callers in
+ request context should pass the effective org id (see
+ ``SaasUserAuth.get_effective_org_id``).
Returns:
The generated API key
"""
api_key = self.generate_api_key()
- user = await UserStore.get_user_by_id(user_id)
- if user is None:
- raise ValueError(f'User not found: {user_id}')
- org_id = user.current_org_id
+ if org_id is None:
+ user = await UserStore.get_user_by_id(user_id)
+ if user is None:
+ raise ValueError(f'User not found: {user_id}')
+ org_id = user.current_org_id
# Column is TIMESTAMP WITHOUT TIME ZONE; strip tzinfo before writing.
if expires_at is not None and expires_at.tzinfo is not None:
@@ -281,17 +290,26 @@ class ApiKeyStore:
return True
- async def list_api_keys(self, user_id: str) -> list[ApiKey]:
- """List all user-visible API keys for a user.
+ async def list_api_keys(
+ self, user_id: str, org_id: UUID | None = None
+ ) -> list[ApiKey]:
+ """List all user-visible API keys for a user in the given org.
+
+ Args:
+ user_id: User to list keys for.
+ org_id: Explicit org to scope to. When omitted, falls back to
+ the user's persisted ``current_org_id`` (legacy behavior).
+ Request-context callers should pass the effective org id.
This excludes:
- System keys (name starts with __SYSTEM__:) - created by internal services
- MCP_API_KEY - internal MCP key
"""
- user = await UserStore.get_user_by_id(user_id)
- if user is None:
- raise ValueError(f'User not found: {user_id}')
- org_id = user.current_org_id
+ if org_id is None:
+ user = await UserStore.get_user_by_id(user_id)
+ if user is None:
+ raise ValueError(f'User not found: {user_id}')
+ org_id = user.current_org_id
async with a_session_maker() as session:
result = await session.execute(
@@ -308,11 +326,14 @@ class ApiKeyStore:
if key.name != 'MCP_API_KEY' and not self.is_system_key_name(key.name)
]
- async def retrieve_mcp_api_key(self, user_id: str) -> str | None:
- user = await UserStore.get_user_by_id(user_id)
- if user is None:
- raise ValueError(f'User not found: {user_id}')
- org_id = user.current_org_id
+ async def retrieve_mcp_api_key(
+ self, user_id: str, org_id: UUID | None = None
+ ) -> str | None:
+ if org_id is None:
+ user = await UserStore.get_user_by_id(user_id)
+ if user is None:
+ raise ValueError(f'User not found: {user_id}')
+ org_id = user.current_org_id
async with a_session_maker() as session:
result = await session.execute(
diff --git a/enterprise/storage/org_app_settings_store.py b/enterprise/storage/org_app_settings_store.py
index 4819c5d7be..44c76c697a 100644
--- a/enterprise/storage/org_app_settings_store.py
+++ b/enterprise/storage/org_app_settings_store.py
@@ -47,13 +47,21 @@ class OrgAppSettingsStore:
if not org_id:
return None
- # Get the organization
+ return await self.get_org_by_id(org_id)
+
+ async def get_org_by_id(self, org_id: UUID) -> Org | None:
+ """Get an organization by its id, validating the org version.
+
+ Args:
+ org_id: The organization's UUID.
+
+ Returns:
+ Org: The organization object, or None if not found.
+ """
org_result = await self.db_session.execute(select(Org).filter(Org.id == org_id))
org = org_result.scalars().first()
-
if not org:
return None
-
return await self._validate_org_version(org)
async def _validate_org_version(self, org: Org) -> Org:
diff --git a/enterprise/storage/org_service.py b/enterprise/storage/org_service.py
index ef3a5eb36b..4d9c085bfb 100644
--- a/enterprise/storage/org_service.py
+++ b/enterprise/storage/org_service.py
@@ -818,23 +818,27 @@ class OrgService:
raise OrgDatabaseError(f'Failed to delete organization: {str(e)}')
@staticmethod
- async def check_byor_export_enabled(user_id: str) -> bool:
- """Check if BYOR export is enabled for the user's current org.
-
- Returns True if the user's current org has byor_export_enabled set to True.
- Returns False if the user is not found, has no current org, or the flag is False.
+ async def check_byor_export_enabled(
+ user_id: str, org_id: UUID | None = None
+ ) -> bool:
+ """Check if BYOR export is enabled for an organization.
Args:
- user_id: User ID to check
+ user_id: User ID (used only as fallback to look up the user's
+ ``current_org_id`` when ``org_id`` is omitted).
+ org_id: Explicit org id. Request-context callers should pass
+ the effective org id from ``SaasUserAuth.get_effective_org_id``.
Returns:
- bool: True if BYOR export is enabled, False otherwise
+ bool: True if BYOR export is enabled, False otherwise.
"""
- user = await UserStore.get_user_by_id(user_id)
- if not user or not user.current_org_id:
- return False
+ if org_id is None:
+ user = await UserStore.get_user_by_id(user_id)
+ if not user or not user.current_org_id:
+ return False
+ org_id = user.current_org_id
- org = await OrgStore.get_org_by_id(user.current_org_id)
+ org = await OrgStore.get_org_by_id(org_id)
if not org:
return False
diff --git a/enterprise/storage/saas_secrets_store.py b/enterprise/storage/saas_secrets_store.py
index 91d3a2c5ee..17d6f03d57 100644
--- a/enterprise/storage/saas_secrets_store.py
+++ b/enterprise/storage/saas_secrets_store.py
@@ -1,6 +1,7 @@
from __future__ import annotations
from dataclasses import dataclass, field
+from uuid import UUID
from sqlalchemy import delete, select
from storage.database import a_session_maker
@@ -17,12 +18,18 @@ from openhands.app_server.utils.logger import openhands_logger as logger
class SaasSecretsStore(SecretsStore):
user_id: str
_jwt_svc: JwtService = field(repr=False)
+ # When set, overrides the user's `current_org_id` for both load and
+ # store. Used to honor a request's effective org (api_key_org_id >
+ # X-Org-Id header > user.current_org_id). Secrets are stored per
+ # (user_id, org_id), so the effective org must flow through here for
+ # the right rows to be read/written.
+ effective_org_id: UUID | None = None
async def load(self) -> Secrets | None:
if not self.user_id:
return None
user = await UserStore.get_user_by_id(self.user_id)
- org_id = user.current_org_id if user else None
+ org_id = self.effective_org_id or (user.current_org_id if user else None)
async with a_session_maker() as session:
# Fetch all secrets for the given user ID
@@ -52,12 +59,13 @@ class SaasSecretsStore(SecretsStore):
user = await UserStore.get_user_by_id(self.user_id)
if user is None:
raise ValueError(f'User not found: {self.user_id}')
- org_id = user.current_org_id
+ org_id = self.effective_org_id or user.current_org_id
async with a_session_maker() as session:
# Incoming secrets are always the most updated ones
# Delete existing records for this user AND organization only
- # Note: user.current_org_id is non-nullable, so org_id is always set
+ # org_id is always set: it's either the effective org from
+ # the request or the user's non-nullable current_org_id.
delete_query = delete(StoredCustomSecrets).filter(
StoredCustomSecrets.keycloak_user_id == self.user_id,
StoredCustomSecrets.org_id == org_id,
@@ -117,15 +125,28 @@ class SaasSecretsStore(SecretsStore):
kwargs[key] = self._jwt_svc.encrypt_value(value)
@classmethod
- async def get_instance(
+ async def get_instance( # type: ignore[override]
cls,
- user_id: str, # type: ignore[override]
+ user_id: str,
+ effective_org_id: UUID | None = None,
) -> SaasSecretsStore:
"""Get a SaasSecretsStore instance for the given user.
+ Args:
+ user_id: Keycloak user id.
+ effective_org_id: Optional org id resolved from the request
+ (see SaasUserAuth.get_effective_org_id). When None the
+ store falls back to ``user.current_org_id`` to preserve
+ legacy behavior for background / non-request callers
+ (e.g. webhook resolvers).
+
TODO: This method should be replaced with dependency injection.
"""
logger.debug(f'saas_secrets_store.get_instance::{user_id}')
from storage.encrypt_utils import get_jwt_service
- return SaasSecretsStore(user_id, get_jwt_service())
+ return SaasSecretsStore(
+ user_id,
+ get_jwt_service(),
+ effective_org_id=effective_org_id,
+ )
diff --git a/enterprise/storage/saas_settings_store.py b/enterprise/storage/saas_settings_store.py
index 1a771219f2..a8c55b3329 100644
--- a/enterprise/storage/saas_settings_store.py
+++ b/enterprise/storage/saas_settings_store.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import uuid
from dataclasses import dataclass
from typing import Any
+from uuid import UUID
from pydantic import SecretStr
from server.auth.token_manager import TokenManager
@@ -30,6 +31,23 @@ from openhands.app_server.utils.llm import is_openhands_model
@dataclass
class SaasSettingsStore(SettingsStore):
user_id: str
+ # When set, overrides the user's `current_org_id` for both `load()` and
+ # `store()`. Used to honor a request's effective org (api_key_org_id >
+ # X-Org-Id header > user.current_org_id) so an API key minted for org A
+ # used by a user whose `current_org_id` later switched to B still
+ # reads/writes settings under org A.
+ effective_org_id: UUID | None = None
+
+ def _resolve_org_id(self, user: User) -> UUID:
+ """Return the effective org id for this request, or the user's
+ current org id as a fallback. The caller still needs to verify
+ that the user is a member of the returned org (handled in load/
+ store by the existing org_members lookup).
+
+ `user.current_org_id` is non-nullable on the ORM model, so the
+ result is always a UUID.
+ """
+ return self.effective_org_id or user.current_org_id
async def _get_user_settings_by_keycloak_id_async(
self, keycloak_user_id: str, session=None
@@ -84,7 +102,7 @@ class SaasSettingsStore(SettingsStore):
logger.error(f'User not found for ID {self.user_id}')
return None
- org_id = user.current_org_id
+ org_id = self._resolve_org_id(user)
org_member: OrgMember | None = None
for om in user.org_members:
if om.org_id == org_id:
@@ -189,7 +207,7 @@ class SaasSettingsStore(SettingsStore):
logger.error(f'User not found for ID {self.user_id}')
return None
- org_id = user.current_org_id
+ org_id = self._resolve_org_id(user)
org_member: OrgMember | None = None
for om in user.org_members:
@@ -293,16 +311,24 @@ class SaasSettingsStore(SettingsStore):
await session.commit()
@classmethod
- async def get_instance(
+ async def get_instance( # type: ignore[override]
cls,
- user_id: str, # type: ignore[override]
+ user_id: str,
+ effective_org_id: UUID | None = None,
) -> SaasSettingsStore:
"""Get a SaasSettingsStore instance for the given user.
+ Args:
+ user_id: Keycloak user id.
+ effective_org_id: Optional org id resolved from the request
+ (see SaasUserAuth.get_effective_org_id). When None the
+ store falls back to ``user.current_org_id`` to preserve
+ legacy behavior for background / non-request callers.
+
TODO: This method should be replaced with dependency injection.
"""
logger.debug(f'saas_settings_store.get_instance::{user_id}')
- return SaasSettingsStore(user_id)
+ return SaasSettingsStore(user_id, effective_org_id=effective_org_id)
async def _ensure_api_key(
self, item: Settings, org_id: str, openhands_type: bool = False
diff --git a/enterprise/tests/unit/server/auth/test_reject_x_org_id_path_mismatch.py b/enterprise/tests/unit/server/auth/test_reject_x_org_id_path_mismatch.py
new file mode 100644
index 0000000000..79e8ea12f0
--- /dev/null
+++ b/enterprise/tests/unit/server/auth/test_reject_x_org_id_path_mismatch.py
@@ -0,0 +1,161 @@
+"""Unit tests for the ``reject_x_org_id_path_mismatch`` FastAPI dependency.
+
+The guard's job is narrow: when a route has ``{org_id}`` in its path
+*and* the request carries an ``X-Org-Id`` header, the two must agree.
+Everything else is a pass-through.
+
+These tests drive the dependency through a minimal FastAPI app rather
+than calling the function directly β€” that way we exercise the same
+header-parsing / path-param-resolution machinery that real requests
+go through, and we catch wiring regressions (e.g. someone renaming
+the header alias) that a direct call would silently tolerate.
+"""
+
+from __future__ import annotations
+
+from uuid import UUID, uuid4
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from server.auth.org_context import (
+ REJECT_X_ORG_ID_PATH_MISMATCH,
+ X_ORG_ID_HEADER,
+)
+
+
+def app() -> FastAPI:
+ """Build a tiny app with one path-org route and one non-path route,
+ both guarded by the dependency. The non-path route asserts that a
+ misconfigured attachment is a no-op (not a 500)."""
+ app = FastAPI()
+
+ @app.get(
+ '/orgs/{org_id}/things',
+ dependencies=[REJECT_X_ORG_ID_PATH_MISMATCH],
+ )
+ def path_org_route(org_id: UUID) -> dict:
+ return {'org_id': str(org_id)}
+
+ @app.get(
+ '/no-path-org',
+ dependencies=[REJECT_X_ORG_ID_PATH_MISMATCH],
+ )
+ def no_path_org_route() -> dict:
+ return {'ok': True}
+
+ return app
+
+
+def client(app: FastAPI) -> TestClient:
+ return TestClient(app)
+
+
+def org_id() -> UUID:
+ return uuid4()
+
+
+# --------------------------------------------------------------------- #
+# Pass-through cases
+# --------------------------------------------------------------------- #
+
+
+def test_no_header_passes_through(client: TestClient, org_id: UUID):
+ r = client.get(f'/orgs/{org_id}/things')
+ assert r.status_code == 200
+ assert r.json() == {'org_id': str(org_id)}
+
+
+def test_matching_header_passes_through(client: TestClient, org_id: UUID):
+ r = client.get(
+ f'/orgs/{org_id}/things',
+ headers={X_ORG_ID_HEADER: str(org_id)},
+ )
+ assert r.status_code == 200
+
+
+def test_matching_header_case_insensitive_uuid(client: TestClient, org_id: UUID):
+ """UUIDs compare value-wise, not string-wise β€” uppercase header
+ must match lowercase path."""
+ r = client.get(
+ f'/orgs/{org_id}/things',
+ headers={X_ORG_ID_HEADER: str(org_id).upper()},
+ )
+ assert r.status_code == 200
+
+
+def test_empty_header_value_passes_through(client: TestClient, org_id: UUID):
+ """An empty string header is treated as 'not present' by FastAPI's
+ Header dependency. We document the behavior here so a future change
+ that starts treating ``X-Org-Id: ''`` as a malformed UUID is
+ caught."""
+ r = client.get(
+ f'/orgs/{org_id}/things',
+ headers={X_ORG_ID_HEADER: ''},
+ )
+ # Empty header β†’ either passes through (current Starlette behavior)
+ # or 400. Either is defensible; what we must NEVER do is leak it
+ # through to the handler with a falsy-but-truthy "did the user
+ # request an override?" signal.
+ assert r.status_code in (200, 400)
+
+
+# --------------------------------------------------------------------- #
+# Rejection cases
+# --------------------------------------------------------------------- #
+
+
+def test_conflicting_header_rejected_with_400(client: TestClient, org_id: UUID):
+ other = uuid4()
+ r = client.get(
+ f'/orgs/{org_id}/things',
+ headers={X_ORG_ID_HEADER: str(other)},
+ )
+ assert r.status_code == 400
+ body = r.json()
+ detail = body.get('detail', '')
+ # Error message must name both ids so an operator reading logs can
+ # immediately tell which side is stale.
+ assert str(other) in detail
+ assert str(org_id) in detail
+
+
+def test_malformed_header_rejected_with_400(client: TestClient, org_id: UUID):
+ r = client.get(
+ f'/orgs/{org_id}/things',
+ headers={X_ORG_ID_HEADER: 'not-a-uuid'},
+ )
+ assert r.status_code == 400
+ assert 'not a valid UUID' in r.json().get('detail', '')
+
+
+# --------------------------------------------------------------------- #
+# Misconfiguration safety
+# --------------------------------------------------------------------- #
+
+
+def test_dep_on_non_path_route_is_noop(client: TestClient):
+ """If a developer attaches the dep to a route that has no ``{org_id}``
+ path param, the dep should NOT raise β€” even when the header is
+ present. (A 500 here would be worse than the silent miswiring that
+ we'd catch in dev when no behavior changed.)"""
+ r = client.get(
+ '/no-path-org',
+ headers={X_ORG_ID_HEADER: str(uuid4())},
+ )
+ assert r.status_code == 200
+ assert r.json() == {'ok': True}
+
+
+def test_dep_on_non_path_route_ignores_malformed_header(client: TestClient):
+ """Same as above, but with a junk header β€” still no-op, NOT 400.
+ The dep should only complain about path-vs-header conflicts; if
+ there's no path to compare against, it stays silent."""
+ r = client.get(
+ '/no-path-org',
+ headers={X_ORG_ID_HEADER: 'not-a-uuid'},
+ )
+ assert r.status_code == 200
diff --git a/enterprise/tests/unit/server/auth/test_saas_user_auth_effective_org.py b/enterprise/tests/unit/server/auth/test_saas_user_auth_effective_org.py
new file mode 100644
index 0000000000..4183e95f98
--- /dev/null
+++ b/enterprise/tests/unit/server/auth/test_saas_user_auth_effective_org.py
@@ -0,0 +1,258 @@
+"""Unit tests for SaasUserAuth.get_effective_org_id().
+
+Validates the precedence rules:
+
+1. ``api_key_org_id`` (API key binding) β€” cannot be overridden; an
+ ``X-Org-Id`` header that disagrees produces a 403.
+2. ``X-Org-Id`` header β€” validated against the user's org memberships;
+ non-member raises 403, malformed UUID raises 400.
+3. ``user.current_org_id`` β€” fallback when neither of the above is set.
+"""
+
+import uuid
+from unittest.mock import patch
+
+import pytest
+from fastapi import HTTPException
+from pydantic import SecretStr
+from server.auth.saas_user_auth import SaasUserAuth
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
+from sqlalchemy.pool import StaticPool
+from storage.base import Base
+from storage.org import Org
+from storage.org_member import OrgMember
+from storage.role import Role
+from storage.user import User
+
+
+async def async_engine():
+ engine = create_async_engine(
+ 'sqlite+aiosqlite:///:memory:',
+ poolclass=StaticPool,
+ connect_args={'check_same_thread': False},
+ )
+ return engine
+
+
+async def async_session_maker(async_engine):
+ session_maker = async_sessionmaker(
+ bind=async_engine,
+ class_=AsyncSession,
+ expire_on_commit=False,
+ )
+ async with async_engine.begin() as conn:
+ await conn.run_sync(Base.metadata.create_all)
+ return session_maker
+
+
+def user_id():
+ return str(uuid.uuid4())
+
+
+def org_id():
+ return uuid.uuid4()
+
+
+def other_org_id():
+ return uuid.uuid4()
+
+
+async def _seed_minimal(session_maker, user_id_str, current_org_id, *extra_org_ids):
+ """Create a role, org(s), user, and org_member rows in the in-memory DB."""
+ async with session_maker() as session:
+ role = Role(name='member', rank=3)
+ session.add(role)
+ await session.flush()
+
+ all_org_ids = [current_org_id, *extra_org_ids]
+ for o in all_org_ids:
+ session.add(
+ Org(
+ id=o,
+ name=f'Org {o}',
+ org_version=1,
+ enable_proactive_conversation_starters=True,
+ )
+ )
+ await session.flush()
+
+ session.add(
+ User(
+ id=uuid.UUID(user_id_str),
+ current_org_id=current_org_id,
+ user_consents_to_analytics=True,
+ )
+ )
+ await session.flush()
+
+ for o in all_org_ids:
+ session.add(
+ OrgMember(
+ org_id=o,
+ user_id=uuid.UUID(user_id_str),
+ role_id=role.id,
+ status='active',
+ llm_api_key='test-api-key',
+ )
+ )
+ await session.commit()
+
+
+def _stores_patched(async_session_maker):
+ """Return the standard set of patches used by SaasUserAuth helpers."""
+ return (
+ patch('storage.user_store.a_session_maker', async_session_maker),
+ patch('storage.org_store.a_session_maker', async_session_maker),
+ patch('storage.org_member_store.a_session_maker', async_session_maker),
+ patch('storage.role_store.a_session_maker', async_session_maker),
+ )
+
+
+class TestGetEffectiveOrgId:
+ @pytest.mark.asyncio
+ async def test_no_header_falls_back_to_current_org_id(
+ self, async_session_maker, user_id, org_id
+ ):
+ await _seed_minimal(async_session_maker, user_id, org_id)
+ user_auth = SaasUserAuth(
+ user_id=user_id,
+ refresh_token=SecretStr('mock'),
+ )
+ with (
+ _stores_patched(async_session_maker)[0],
+ _stores_patched(async_session_maker)[2],
+ ):
+ effective = await user_auth.get_effective_org_id()
+
+ assert effective == org_id
+
+ @pytest.mark.asyncio
+ async def test_header_overrides_when_user_is_member(
+ self, async_session_maker, user_id, org_id, other_org_id
+ ):
+ await _seed_minimal(async_session_maker, user_id, org_id, other_org_id)
+ user_auth = SaasUserAuth(
+ user_id=user_id,
+ refresh_token=SecretStr('mock'),
+ _x_org_id_header=str(other_org_id),
+ )
+ with (
+ _stores_patched(async_session_maker)[0],
+ _stores_patched(async_session_maker)[2],
+ ):
+ effective = await user_auth.get_effective_org_id()
+
+ assert effective == other_org_id
+
+ @pytest.mark.asyncio
+ async def test_header_with_non_member_org_raises_403(
+ self, async_session_maker, user_id, org_id, other_org_id
+ ):
+ # Seed the user as a member of `org_id` only, not `other_org_id`.
+ await _seed_minimal(async_session_maker, user_id, org_id)
+ # `other_org_id` org exists but the user isn't a member.
+ async with async_session_maker() as session:
+ session.add(
+ Org(
+ id=other_org_id,
+ name='Outside Org',
+ org_version=1,
+ enable_proactive_conversation_starters=True,
+ )
+ )
+ await session.commit()
+
+ user_auth = SaasUserAuth(
+ user_id=user_id,
+ refresh_token=SecretStr('mock'),
+ _x_org_id_header=str(other_org_id),
+ )
+ with (
+ _stores_patched(async_session_maker)[0],
+ _stores_patched(async_session_maker)[2],
+ ):
+ with pytest.raises(HTTPException) as exc_info:
+ await user_auth.get_effective_org_id()
+
+ assert exc_info.value.status_code == 403
+
+ @pytest.mark.asyncio
+ async def test_malformed_header_raises_400(self, async_session_maker, user_id):
+ user_auth = SaasUserAuth(
+ user_id=user_id,
+ refresh_token=SecretStr('mock'),
+ _x_org_id_header='not-a-uuid',
+ )
+ with pytest.raises(HTTPException) as exc_info:
+ await user_auth.get_effective_org_id()
+
+ assert exc_info.value.status_code == 400
+
+ @pytest.mark.asyncio
+ async def test_api_key_org_id_wins_over_user_current_org(
+ self, async_session_maker, user_id, org_id, other_org_id
+ ):
+ # User's persisted current_org is `org_id`, but API key is pinned
+ # to `other_org_id`. Effective org must be `other_org_id`.
+ await _seed_minimal(async_session_maker, user_id, org_id)
+ user_auth = SaasUserAuth(
+ user_id=user_id,
+ refresh_token=SecretStr('mock'),
+ api_key_org_id=other_org_id,
+ )
+ effective = await user_auth.get_effective_org_id()
+ assert effective == other_org_id
+
+ @pytest.mark.asyncio
+ async def test_api_key_org_id_mismatch_with_header_raises_403(
+ self, async_session_maker, user_id, org_id, other_org_id
+ ):
+ user_auth = SaasUserAuth(
+ user_id=user_id,
+ refresh_token=SecretStr('mock'),
+ api_key_org_id=org_id,
+ _x_org_id_header=str(other_org_id),
+ )
+ with pytest.raises(HTTPException) as exc_info:
+ await user_auth.get_effective_org_id()
+
+ assert exc_info.value.status_code == 403
+
+ @pytest.mark.asyncio
+ async def test_api_key_org_id_matching_header_is_allowed(
+ self, async_session_maker, user_id, org_id
+ ):
+ user_auth = SaasUserAuth(
+ user_id=user_id,
+ refresh_token=SecretStr('mock'),
+ api_key_org_id=org_id,
+ _x_org_id_header=str(org_id),
+ )
+ effective = await user_auth.get_effective_org_id()
+ assert effective == org_id
+
+ @pytest.mark.asyncio
+ async def test_result_is_cached_across_calls(
+ self, async_session_maker, user_id, org_id, other_org_id
+ ):
+ await _seed_minimal(async_session_maker, user_id, org_id, other_org_id)
+ user_auth = SaasUserAuth(
+ user_id=user_id,
+ refresh_token=SecretStr('mock'),
+ _x_org_id_header=str(other_org_id),
+ )
+ with (
+ _stores_patched(async_session_maker)[0],
+ _stores_patched(async_session_maker)[2],
+ ):
+ first = await user_auth.get_effective_org_id()
+
+ # Drop the patches; if cache works the second call must not touch DB.
+ second = await user_auth.get_effective_org_id()
+ assert first == second == other_org_id
+ assert user_auth._effective_org_id_resolved is True
diff --git a/enterprise/tests/unit/server/routes/test_api_keys.py b/enterprise/tests/unit/server/routes/test_api_keys.py
index 35f35d7d1f..010c523ac8 100644
--- a/enterprise/tests/unit/server/routes/test_api_keys.py
+++ b/enterprise/tests/unit/server/routes/test_api_keys.py
@@ -202,6 +202,7 @@ class TestGetLlmApiKeyForByor:
"""Test that when no key exists in database, a new one is generated."""
# Arrange
user_id = 'user-123'
+ org_id = uuid.uuid4()
new_key = 'sk-new-generated-key'
mock_check_enabled.return_value = True
mock_get_key.return_value = None
@@ -209,14 +210,16 @@ class TestGetLlmApiKeyForByor:
mock_store_key.return_value = None
# Act
- result = await get_llm_api_key_for_byor(user_id=user_id)
+ result = await get_llm_api_key_for_byor(
+ user_id=user_id, effective_org_id=org_id
+ )
# Assert
assert result == LlmApiKeyResponse(key=new_key)
- mock_check_enabled.assert_called_once_with(user_id)
- mock_get_key.assert_called_once_with(user_id)
- mock_generate_key.assert_called_once_with(user_id)
- mock_store_key.assert_called_once_with(user_id, new_key)
+ mock_check_enabled.assert_called_once_with(user_id, org_id=org_id)
+ mock_get_key.assert_called_once_with(user_id, org_id)
+ mock_generate_key.assert_called_once_with(user_id, org_id)
+ mock_store_key.assert_called_once_with(user_id, org_id, new_key)
@pytest.mark.asyncio
@patch('storage.org_service.OrgService.check_byor_export_enabled')
@@ -228,18 +231,21 @@ class TestGetLlmApiKeyForByor:
"""Test that when a valid key exists in database, it is returned."""
# Arrange
user_id = 'user-123'
+ org_id = uuid.uuid4()
existing_key = 'sk-existing-valid-key'
mock_check_enabled.return_value = True
mock_get_key.return_value = existing_key
mock_verify_key.return_value = True
# Act
- result = await get_llm_api_key_for_byor(user_id=user_id)
+ result = await get_llm_api_key_for_byor(
+ user_id=user_id, effective_org_id=org_id
+ )
# Assert
assert result == LlmApiKeyResponse(key=existing_key)
- mock_check_enabled.assert_called_once_with(user_id)
- mock_get_key.assert_called_once_with(user_id)
+ mock_check_enabled.assert_called_once_with(user_id, org_id=org_id)
+ mock_get_key.assert_called_once_with(user_id, org_id)
mock_verify_key.assert_called_once_with(existing_key, user_id)
@pytest.mark.asyncio
@@ -261,6 +267,7 @@ class TestGetLlmApiKeyForByor:
"""Test that when an invalid key exists in database, it is regenerated."""
# Arrange
user_id = 'user-123'
+ org_id = uuid.uuid4()
invalid_key = 'sk-invalid-key'
new_key = 'sk-new-generated-key'
mock_check_enabled.return_value = True
@@ -271,16 +278,18 @@ class TestGetLlmApiKeyForByor:
mock_store_key.return_value = None
# Act
- result = await get_llm_api_key_for_byor(user_id=user_id)
+ result = await get_llm_api_key_for_byor(
+ user_id=user_id, effective_org_id=org_id
+ )
# Assert
assert result == LlmApiKeyResponse(key=new_key)
- mock_check_enabled.assert_called_once_with(user_id)
- mock_get_key.assert_called_once_with(user_id)
+ mock_check_enabled.assert_called_once_with(user_id, org_id=org_id)
+ mock_get_key.assert_called_once_with(user_id, org_id)
mock_verify_key.assert_called_once_with(invalid_key, user_id)
- mock_delete_key.assert_called_once_with(user_id, invalid_key)
- mock_generate_key.assert_called_once_with(user_id)
- mock_store_key.assert_called_once_with(user_id, new_key)
+ mock_delete_key.assert_called_once_with(user_id, org_id, invalid_key)
+ mock_generate_key.assert_called_once_with(user_id, org_id)
+ mock_store_key.assert_called_once_with(user_id, org_id, new_key)
@pytest.mark.asyncio
@patch('storage.org_service.OrgService.check_byor_export_enabled')
@@ -301,6 +310,7 @@ class TestGetLlmApiKeyForByor:
"""Test that even if deletion fails, regeneration still proceeds."""
# Arrange
user_id = 'user-123'
+ org_id = uuid.uuid4()
invalid_key = 'sk-invalid-key'
new_key = 'sk-new-generated-key'
mock_check_enabled.return_value = True
@@ -311,14 +321,16 @@ class TestGetLlmApiKeyForByor:
mock_store_key.return_value = None
# Act
- result = await get_llm_api_key_for_byor(user_id=user_id)
+ result = await get_llm_api_key_for_byor(
+ user_id=user_id, effective_org_id=org_id
+ )
# Assert
assert result == LlmApiKeyResponse(key=new_key)
- mock_check_enabled.assert_called_once_with(user_id)
- mock_delete_key.assert_called_once_with(user_id, invalid_key)
- mock_generate_key.assert_called_once_with(user_id)
- mock_store_key.assert_called_once_with(user_id, new_key)
+ mock_check_enabled.assert_called_once_with(user_id, org_id=org_id)
+ mock_delete_key.assert_called_once_with(user_id, org_id, invalid_key)
+ mock_generate_key.assert_called_once_with(user_id, org_id)
+ mock_store_key.assert_called_once_with(user_id, org_id, new_key)
@pytest.mark.asyncio
@patch('storage.org_service.OrgService.check_byor_export_enabled')
@@ -381,92 +393,34 @@ class TestDeleteByorKeyFromLitellm:
@pytest.mark.asyncio
@patch('storage.lite_llm_manager.LiteLlmManager.delete_key')
- @patch('storage.user_store.UserStore.get_user_by_id')
- async def test_delete_constructs_alias_from_user(
- self, mock_get_user, mock_delete_key
- ):
- """Test that delete_byor_key_from_litellm constructs key alias from user."""
+ async def test_delete_constructs_alias_from_org(self, mock_delete_key):
+ """Test that delete_byor_key_from_litellm builds the key alias from the effective org."""
# Arrange
user_id = 'user-123'
- org_id = 'org-456'
+ org_id = uuid.uuid4()
byor_key = 'sk-byor-key-to-delete'
expected_alias = f'BYOR Key - user {user_id}, org {org_id}'
-
- mock_user = MagicMock()
- mock_user.current_org_id = org_id
- mock_get_user.return_value = mock_user
mock_delete_key.return_value = None
# Act
- result = await delete_byor_key_from_litellm(user_id, byor_key)
+ result = await delete_byor_key_from_litellm(user_id, org_id, byor_key)
# Assert
assert result is True
- mock_get_user.assert_called_once_with(user_id)
mock_delete_key.assert_called_once_with(byor_key, key_alias=expected_alias)
@pytest.mark.asyncio
@patch('storage.lite_llm_manager.LiteLlmManager.delete_key')
- @patch('storage.user_store.UserStore.get_user_by_id')
- async def test_delete_without_user_passes_no_alias(
- self, mock_get_user, mock_delete_key
- ):
- """Test that when user is not found, no alias is passed."""
- # Arrange
- user_id = 'user-123'
- byor_key = 'sk-byor-key-to-delete'
-
- mock_get_user.return_value = None
- mock_delete_key.return_value = None
-
- # Act
- result = await delete_byor_key_from_litellm(user_id, byor_key)
-
- # Assert
- assert result is True
- mock_delete_key.assert_called_once_with(byor_key, key_alias=None)
-
- @pytest.mark.asyncio
- @patch('storage.lite_llm_manager.LiteLlmManager.delete_key')
- @patch('storage.user_store.UserStore.get_user_by_id')
- async def test_delete_without_org_id_passes_no_alias(
- self, mock_get_user, mock_delete_key
- ):
- """Test that when user has no current_org_id, no alias is passed."""
- # Arrange
- user_id = 'user-123'
- byor_key = 'sk-byor-key-to-delete'
-
- mock_user = MagicMock()
- mock_user.current_org_id = None
- mock_get_user.return_value = mock_user
- mock_delete_key.return_value = None
-
- # Act
- result = await delete_byor_key_from_litellm(user_id, byor_key)
-
- # Assert
- assert result is True
- mock_delete_key.assert_called_once_with(byor_key, key_alias=None)
-
- @pytest.mark.asyncio
- @patch('storage.lite_llm_manager.LiteLlmManager.delete_key')
- @patch('storage.user_store.UserStore.get_user_by_id')
- async def test_delete_returns_false_on_exception(
- self, mock_get_user, mock_delete_key
- ):
+ async def test_delete_returns_false_on_exception(self, mock_delete_key):
"""Test that exceptions during deletion return False."""
# Arrange
user_id = 'user-123'
+ org_id = uuid.uuid4()
byor_key = 'sk-byor-key-to-delete'
-
- mock_user = MagicMock()
- mock_user.current_org_id = 'org-456'
- mock_get_user.return_value = mock_user
mock_delete_key.side_effect = Exception('LiteLLM API error')
# Act
- result = await delete_byor_key_from_litellm(user_id, byor_key)
+ result = await delete_byor_key_from_litellm(user_id, org_id, byor_key)
# Assert
assert result is False
@@ -481,14 +435,15 @@ class TestCheckByorPermitted:
"""Test that permitted=True is returned when BYOR export is enabled."""
# Arrange
user_id = 'user-123'
+ org_id = uuid.uuid4()
mock_check_enabled.return_value = True
# Act
- result = await check_byor_permitted(user_id=user_id)
+ result = await check_byor_permitted(user_id=user_id, effective_org_id=org_id)
# Assert
assert result == ByorPermittedResponse(permitted=True)
- mock_check_enabled.assert_called_once_with(user_id)
+ mock_check_enabled.assert_called_once_with(user_id, org_id=org_id)
@pytest.mark.asyncio
@patch('storage.org_service.OrgService.check_byor_export_enabled')
@@ -496,14 +451,15 @@ class TestCheckByorPermitted:
"""Test that permitted=False is returned when BYOR export is disabled."""
# Arrange
user_id = 'user-123'
+ org_id = uuid.uuid4()
mock_check_enabled.return_value = False
# Act
- result = await check_byor_permitted(user_id=user_id)
+ result = await check_byor_permitted(user_id=user_id, effective_org_id=org_id)
# Assert
assert result == ByorPermittedResponse(permitted=False)
- mock_check_enabled.assert_called_once_with(user_id)
+ mock_check_enabled.assert_called_once_with(user_id, org_id=org_id)
@pytest.mark.asyncio
@patch('storage.org_service.OrgService.check_byor_export_enabled')
@@ -511,11 +467,12 @@ class TestCheckByorPermitted:
"""Test that an exception raises 500 error."""
# Arrange
user_id = 'user-123'
+ org_id = uuid.uuid4()
mock_check_enabled.side_effect = Exception('Database error')
# Act & Assert
with pytest.raises(HTTPException) as exc_info:
- await check_byor_permitted(user_id=user_id)
+ await check_byor_permitted(user_id=user_id, effective_org_id=org_id)
assert exc_info.value.status_code == 500
assert 'Failed to check BYOR export permission' in exc_info.value.detail
diff --git a/enterprise/tests/unit/server/services/test_org_app_settings_service.py b/enterprise/tests/unit/server/services/test_org_app_settings_service.py
index 6c4b3b2f34..2b93bfec71 100644
--- a/enterprise/tests/unit/server/services/test_org_app_settings_service.py
+++ b/enterprise/tests/unit/server/services/test_org_app_settings_service.py
@@ -41,8 +41,15 @@ def mock_store():
@pytest.fixture
def mock_user_context(user_id):
- """Create a mock UserContext that returns the user_id."""
+ """Create a mock UserContext that returns the user_id.
+
+ Explicitly sets ``user_auth = None`` so the service's effective-org
+ resolver falls back to the legacy ``get_current_org_by_user_id``
+ path; otherwise ``MagicMock`` would auto-create a ``user_auth``
+ attribute whose ``get_effective_org_id`` would not be awaitable.
+ """
context = MagicMock()
+ context.user_auth = None
context.get_user_id = AsyncMock(return_value=user_id)
return context
diff --git a/enterprise/tests/unit/storage/test_saas_sql_app_conversation_info_service.py b/enterprise/tests/unit/storage/test_saas_sql_app_conversation_info_service.py
index a2541fd987..06f72b8826 100644
--- a/enterprise/tests/unit/storage/test_saas_sql_app_conversation_info_service.py
+++ b/enterprise/tests/unit/storage/test_saas_sql_app_conversation_info_service.py
@@ -1031,6 +1031,12 @@ class TestApiKeyOrgIdHandling:
def get_api_key_org_id(self) -> UUID | None:
return self.api_key_org_id
+ async def get_effective_org_id(self) -> UUID | None:
+ # Mirror SaasUserAuth precedence: API-key binding wins
+ # over the user's current_org_id. Returning None lets the
+ # injector fall back to user.current_org_id.
+ return self.api_key_org_id
+
# Create a mock UserContext that wraps the MockUserAuth
@dataclass
class MockAuthUserContext:
@@ -1113,6 +1119,12 @@ class TestApiKeyOrgIdHandling:
def get_api_key_org_id(self) -> UUID | None:
return self.api_key_org_id
+ async def get_effective_org_id(self) -> UUID | None:
+ # Mirror SaasUserAuth precedence: API-key binding wins
+ # over the user's current_org_id. Returning None lets the
+ # injector fall back to user.current_org_id.
+ return self.api_key_org_id
+
@dataclass
class MockAuthUserContext:
user_auth: MockUserAuth
@@ -1227,6 +1239,12 @@ class TestApiKeyOrgIdHandling:
def get_api_key_org_id(self) -> UUID | None:
return self.api_key_org_id
+ async def get_effective_org_id(self) -> UUID | None:
+ # Mirror SaasUserAuth precedence: API-key binding wins
+ # over the user's current_org_id. Returning None lets the
+ # injector fall back to user.current_org_id.
+ return self.api_key_org_id
+
@dataclass
class MockAuthUserContext:
user_auth: MockUserAuth
diff --git a/enterprise/tests/unit/storage/test_saas_stores_effective_org.py b/enterprise/tests/unit/storage/test_saas_stores_effective_org.py
new file mode 100644
index 0000000000..85e8f4cb11
--- /dev/null
+++ b/enterprise/tests/unit/storage/test_saas_stores_effective_org.py
@@ -0,0 +1,382 @@
+"""Unit tests for ``effective_org_id`` plumbing through the SaaS stores.
+
+The SaaS settings / secrets stores have historically scoped all reads
+and writes to ``user.current_org_id``. That made every API-key-driven
+request load the *user's last-selected* org's data β€” even when the
+caller was authenticated via an API key bound to a *different* org.
+
+These tests verify that:
+
+* When ``effective_org_id`` is supplied to the store constructor or
+ ``get_instance``, the store uses it instead of ``user.current_org_id``.
+* When it is not supplied, the store still falls back to
+ ``user.current_org_id`` so background callers (webhook resolvers,
+ CLI flows) keep working.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from unittest.mock import AsyncMock, MagicMock, patch
+from uuid import UUID
+
+import pytest
+from storage.saas_secrets_store import SaasSecretsStore
+from storage.saas_settings_store import SaasSettingsStore
+
+USER_ID = '00000000-0000-0000-0000-00000000aaaa'
+CURRENT_ORG_ID = UUID('00000000-0000-0000-0000-00000000bbbb')
+EFFECTIVE_ORG_ID = UUID('00000000-0000-0000-0000-00000000cccc')
+
+
+# --------------------------------------------------------------------- #
+# Lightweight fakes β€” we explicitly do NOT spin up SQLite for these
+# tests. We're verifying which org_id is *chosen* by the store, not the
+# SQL it emits. Hitting the DB would test SQLAlchemy more than the
+# resolver, and would tie the test to schema details unrelated to the
+# bug we're guarding against.
+# --------------------------------------------------------------------- #
+
+
+@dataclass
+class FakeOrgMember:
+ org_id: UUID
+
+
+@dataclass
+class FakeUser:
+ """Minimal stand-in for ``storage.user.User`` covering only the
+ attributes the stores touch on the happy path of load().
+ """
+
+ current_org_id: UUID
+ org_members: list[FakeOrgMember] = field(default_factory=list)
+
+
+# ----------------------------- SettingsStore --------------------------- #
+
+
+def test_settings_store_default_effective_org_id_is_none():
+ """The new field must default to None so existing constructions
+ (e.g. ``SaasSettingsStore(user_id)``) keep working unchanged."""
+ store = SaasSettingsStore(user_id=USER_ID)
+ assert store.effective_org_id is None
+
+
+def test_settings_store_resolve_org_id_prefers_effective_over_current():
+ user = FakeUser(current_org_id=CURRENT_ORG_ID)
+ store = SaasSettingsStore(user_id=USER_ID, effective_org_id=EFFECTIVE_ORG_ID)
+ assert store._resolve_org_id(user) == EFFECTIVE_ORG_ID
+
+
+def test_settings_store_resolve_org_id_falls_back_to_current_org():
+ user = FakeUser(current_org_id=CURRENT_ORG_ID)
+ store = SaasSettingsStore(user_id=USER_ID) # no effective_org_id
+ assert store._resolve_org_id(user) == CURRENT_ORG_ID
+
+
+async def test_settings_store_load_returns_none_when_user_not_member_of_effective_org():
+ """If the request resolved an effective org the user isn't a member
+ of, the store must NOT silently fall back to current_org_id β€” it
+ must refuse the load (the upstream resolver is responsible for
+ rejecting unauthorized X-Org-Id values; this is defense-in-depth)."""
+ user = FakeUser(
+ current_org_id=CURRENT_ORG_ID,
+ org_members=[FakeOrgMember(org_id=CURRENT_ORG_ID)],
+ )
+ store = SaasSettingsStore(user_id=USER_ID, effective_org_id=EFFECTIVE_ORG_ID)
+
+ with patch(
+ 'storage.saas_settings_store.UserStore.get_user_by_id',
+ new=AsyncMock(return_value=user),
+ ):
+ result = await store.load()
+
+ assert result is None
+
+
+async def test_settings_store_get_instance_propagates_effective_org_id():
+ store = await SaasSettingsStore.get_instance(
+ USER_ID, effective_org_id=EFFECTIVE_ORG_ID
+ )
+ assert isinstance(store, SaasSettingsStore)
+ assert store.user_id == USER_ID
+ assert store.effective_org_id == EFFECTIVE_ORG_ID
+
+
+async def test_settings_store_get_instance_defaults_to_none():
+ """Webhook resolvers call ``get_instance(user_id)`` without an org;
+ that path must remain legal."""
+ store = await SaasSettingsStore.get_instance(USER_ID)
+ assert store.effective_org_id is None
+
+
+# ----------------------------- SecretsStore ---------------------------- #
+
+
+def _make_secrets_store(effective_org_id: UUID | None = None) -> SaasSecretsStore:
+ return SaasSecretsStore(
+ user_id=USER_ID,
+ _jwt_svc=MagicMock(),
+ effective_org_id=effective_org_id,
+ )
+
+
+def test_secrets_store_default_effective_org_id_is_none():
+ store = _make_secrets_store()
+ assert store.effective_org_id is None
+
+
+ 'effective_org_id,expected_org_id',
+ [
+ (EFFECTIVE_ORG_ID, EFFECTIVE_ORG_ID), # uses effective override
+ (None, CURRENT_ORG_ID), # falls back to user.current_org_id
+ ],
+)
+async def test_secrets_store_load_filters_by_resolved_org_id(
+ effective_org_id, expected_org_id
+):
+ """``load()`` builds a query of the shape
+ ``SELECT … WHERE keycloak_user_id = :u AND org_id = :o`` β€” assert
+ the org id bound into that filter matches the resolved org."""
+ user = FakeUser(current_org_id=CURRENT_ORG_ID)
+
+ captured_queries: list[object] = []
+
+ class _Result:
+ def scalars(self):
+ return self
+
+ def all(self):
+ return []
+
+ class _FakeSession:
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *exc):
+ return False
+
+ async def execute(self, query):
+ captured_queries.append(query)
+ return _Result()
+
+ store = _make_secrets_store(effective_org_id=effective_org_id)
+
+ with (
+ patch(
+ 'storage.saas_secrets_store.UserStore.get_user_by_id',
+ new=AsyncMock(return_value=user),
+ ),
+ patch(
+ 'storage.saas_secrets_store.a_session_maker',
+ return_value=_FakeSession(),
+ ),
+ ):
+ result = await store.load()
+
+ assert result is not None
+ assert captured_queries, 'load() should have executed at least one query'
+
+ # Compile the SELECT with literal binds so we can read the org id
+ # value out of the WHERE clause without needing a real DB driver.
+ # SQLAlchemy renders UUID literals as the 32-char hex form (no
+ # hyphens), so compare against `.hex` rather than `str(...)`.
+ compiled = str(captured_queries[-1].compile(compile_kwargs={'literal_binds': True}))
+ assert expected_org_id.hex in compiled, (
+ f'Expected query to filter by org_id={expected_org_id!s} '
+ f'(hex={expected_org_id.hex}), compiled SQL was: {compiled}'
+ )
+
+
+async def test_secrets_store_store_uses_effective_org_id_when_set():
+ """``store()`` must delete/insert under the effective org, not the
+ user's current org. We capture the org id by intercepting the
+ ``StoredCustomSecrets`` row that would be inserted."""
+
+ captured_org_ids: list[UUID] = []
+ user = FakeUser(current_org_id=CURRENT_ORG_ID)
+
+ class _FakeSession:
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *exc):
+ return False
+
+ async def execute(self, _query):
+ return MagicMock()
+
+ def add(self, row):
+ captured_org_ids.append(row.org_id)
+
+ async def commit(self):
+ return None
+
+ # Build a Secrets object with one custom secret. We use the real
+ # model so encryption / model_dump behave correctly.
+ from pydantic import SecretStr
+
+ from openhands.app_server.integrations.provider import CustomSecret
+ from openhands.app_server.secrets.secrets_models import Secrets
+
+ item = Secrets(
+ custom_secrets={
+ 'API_KEY': CustomSecret(secret=SecretStr('shh'), description='example'),
+ }
+ )
+
+ store = _make_secrets_store(effective_org_id=EFFECTIVE_ORG_ID)
+
+ with (
+ patch(
+ 'storage.saas_secrets_store.UserStore.get_user_by_id',
+ new=AsyncMock(return_value=user),
+ ),
+ patch(
+ 'storage.saas_secrets_store.a_session_maker',
+ return_value=_FakeSession(),
+ ),
+ ):
+ await store.store(item)
+
+ assert captured_org_ids == [
+ EFFECTIVE_ORG_ID
+ ], f'store() wrote under {captured_org_ids[0]!s}, expected {EFFECTIVE_ORG_ID!s}'
+
+
+async def test_secrets_store_store_falls_back_to_current_org_when_unset():
+ """The legacy/webhook code path (no effective org supplied) must
+ keep writing under user.current_org_id."""
+ captured_org_ids: list[UUID] = []
+ user = FakeUser(current_org_id=CURRENT_ORG_ID)
+
+ class _FakeSession:
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *exc):
+ return False
+
+ async def execute(self, _query):
+ return MagicMock()
+
+ def add(self, row):
+ captured_org_ids.append(row.org_id)
+
+ async def commit(self):
+ return None
+
+ from pydantic import SecretStr
+
+ from openhands.app_server.integrations.provider import CustomSecret
+ from openhands.app_server.secrets.secrets_models import Secrets
+
+ item = Secrets(
+ custom_secrets={
+ 'API_KEY': CustomSecret(secret=SecretStr('shh'), description='example'),
+ }
+ )
+
+ store = _make_secrets_store() # no effective org
+
+ with (
+ patch(
+ 'storage.saas_secrets_store.UserStore.get_user_by_id',
+ new=AsyncMock(return_value=user),
+ ),
+ patch(
+ 'storage.saas_secrets_store.a_session_maker',
+ return_value=_FakeSession(),
+ ),
+ ):
+ await store.store(item)
+
+ assert captured_org_ids == [CURRENT_ORG_ID]
+
+
+async def test_secrets_store_get_instance_propagates_effective_org_id():
+ with patch(
+ 'storage.encrypt_utils.get_jwt_service',
+ return_value=MagicMock(),
+ ):
+ store = await SaasSecretsStore.get_instance(
+ USER_ID, effective_org_id=EFFECTIVE_ORG_ID
+ )
+ assert store.effective_org_id == EFFECTIVE_ORG_ID
+
+
+async def test_secrets_store_get_instance_defaults_to_none():
+ with patch(
+ 'storage.encrypt_utils.get_jwt_service',
+ return_value=MagicMock(),
+ ):
+ store = await SaasSecretsStore.get_instance(USER_ID)
+ assert store.effective_org_id is None
+
+
+# ----------------- SaasUserAuth -> store wiring ----------------------- #
+
+
+def _make_saas_user_auth():
+ """``SaasUserAuth`` requires a refresh_token; tests don't exercise
+ it, so a dummy SecretStr is sufficient."""
+ from pydantic import SecretStr
+ from server.auth.saas_user_auth import SaasUserAuth
+
+ return SaasUserAuth(refresh_token=SecretStr('test-refresh'), user_id=USER_ID)
+
+
+async def test_saas_user_auth_get_user_settings_store_passes_effective_org():
+ """The auth helper must pull the effective org from
+ ``get_effective_org_id()`` and hand it to the settings store."""
+ from server.auth.saas_user_auth import SaasUserAuth
+
+ auth = _make_saas_user_auth()
+
+ with patch.object(
+ SaasUserAuth,
+ 'get_effective_org_id',
+ new=AsyncMock(return_value=EFFECTIVE_ORG_ID),
+ ):
+ store = await auth.get_user_settings_store()
+
+ assert isinstance(store, SaasSettingsStore)
+ assert store.effective_org_id == EFFECTIVE_ORG_ID
+
+ # Second call returns the cached instance, doesn't re-resolve.
+ cached = await auth.get_user_settings_store()
+ assert cached is store
+
+
+async def test_saas_user_auth_get_secrets_store_passes_effective_org():
+ from server.auth.saas_user_auth import SaasUserAuth
+
+ auth = _make_saas_user_auth()
+
+ with (
+ patch.object(
+ SaasUserAuth,
+ 'get_effective_org_id',
+ new=AsyncMock(return_value=EFFECTIVE_ORG_ID),
+ ),
+ patch(
+ 'storage.encrypt_utils.get_jwt_service',
+ return_value=MagicMock(),
+ ),
+ ):
+ store = await auth.get_secrets_store()
+
+ assert isinstance(store, SaasSecretsStore)
+ assert store.effective_org_id == EFFECTIVE_ORG_ID
diff --git a/enterprise/tests/unit/test_billing.py b/enterprise/tests/unit/test_billing.py
index b6ed0b9575..d3c8e5d1c8 100644
--- a/enterprise/tests/unit/test_billing.py
+++ b/enterprise/tests/unit/test_billing.py
@@ -187,7 +187,10 @@ async def test_create_checkout_session_stripe_error(
patch('server.routes.billing.validate_billing_enabled'),
):
await create_checkout_session(
- CreateCheckoutSessionRequest(amount=25), mock_checkout_request, 'mock_user'
+ CreateCheckoutSessionRequest(amount=25),
+ mock_checkout_request,
+ 'mock_user',
+ test_org.id,
)
@@ -214,7 +217,10 @@ async def test_create_checkout_session_success(
patch('server.routes.billing.validate_billing_enabled'),
):
result = await create_checkout_session(
- CreateCheckoutSessionRequest(amount=25), mock_checkout_request, 'mock_user'
+ CreateCheckoutSessionRequest(amount=25),
+ mock_checkout_request,
+ 'mock_user',
+ test_org.id,
)
assert isinstance(result, CreateBillingSessionResponse)
@@ -552,28 +558,34 @@ async def test_cancel_callback_success(async_session_maker, test_org, test_user)
@pytest.mark.asyncio
async def test_has_payment_method_with_payment_method():
"""Test has_payment_method returns True when user has a payment method."""
+ effective_org_id = uuid.uuid4()
mock_has_payment_method = AsyncMock(return_value=True)
with patch(
'server.routes.billing.stripe_service.has_payment_method_by_user_id',
mock_has_payment_method,
):
- result = await has_payment_method('mock_user')
+ result = await has_payment_method('mock_user', effective_org_id)
assert result is True
- mock_has_payment_method.assert_called_once_with('mock_user')
+ mock_has_payment_method.assert_called_once_with(
+ 'mock_user', org_id=effective_org_id
+ )
@pytest.mark.asyncio
async def test_has_payment_method_without_payment_method():
"""Test has_payment_method returns False when user has no payment method."""
+ effective_org_id = uuid.uuid4()
mock_has_payment_method = AsyncMock(return_value=False)
with patch(
'server.routes.billing.stripe_service.has_payment_method_by_user_id',
mock_has_payment_method,
):
mock_has_payment_method.return_value = False
- result = await has_payment_method('mock_user')
+ result = await has_payment_method('mock_user', effective_org_id)
assert result is False
- mock_has_payment_method.assert_called_once_with('mock_user')
+ mock_has_payment_method.assert_called_once_with(
+ 'mock_user', org_id=effective_org_id
+ )
@pytest.mark.asyncio
@@ -589,6 +601,7 @@ async def test_create_customer_setup_session_success():
)
mock_request._url = URL('http://test.com/')
+ effective_org_id = uuid.uuid4()
mock_customer_info = {'customer_id': 'mock-customer-id', 'org_id': 'mock-org-id'}
mock_session = MagicMock()
mock_session.url = 'https://checkout.stripe.com/test-session'
@@ -602,7 +615,9 @@ async def test_create_customer_setup_session_success():
patch('stripe.checkout.Session.create_async', mock_create),
patch('server.routes.billing.validate_billing_enabled'),
):
- result = await create_customer_setup_session(mock_request, 'mock_user')
+ result = await create_customer_setup_session(
+ mock_request, 'mock_user', effective_org_id
+ )
assert isinstance(result, billing.CreateBillingSessionResponse)
assert result.redirect_url == 'https://checkout.stripe.com/test-session'
diff --git a/enterprise/tests/unit/test_saas_user_auth.py b/enterprise/tests/unit/test_saas_user_auth.py
index 605f4e7b85..9daaa13d46 100644
--- a/enterprise/tests/unit/test_saas_user_auth.py
+++ b/enterprise/tests/unit/test_saas_user_auth.py
@@ -371,19 +371,28 @@ async def test_get_provider_tokens_cached(mock_token_manager):
@pytest.mark.asyncio
async def test_get_user_settings_store():
"""Test that get_user_settings_store returns a settings store."""
- with patch('server.auth.saas_user_auth.SaasSettingsStore') as mock_store_cls:
+ user_id = str(uuid.uuid4())
+ org_id = uuid.uuid4()
+ mock_user = MagicMock()
+ mock_user.current_org_id = org_id
+
+ with (
+ patch('server.auth.saas_user_auth.SaasSettingsStore') as mock_store_cls,
+ patch('server.auth.saas_user_auth.UserStore') as mock_user_store,
+ ):
mock_store = MagicMock()
mock_store_cls.return_value = mock_store
+ mock_user_store.get_user_by_id = AsyncMock(return_value=mock_user)
user_auth = SaasUserAuth(
- user_id='test_user_id',
+ user_id=user_id,
refresh_token=SecretStr('refresh_token'),
)
result = await user_auth.get_user_settings_store()
assert result == mock_store
- mock_store_cls.assert_called_once()
+ mock_store_cls.assert_called_once_with(user_id, effective_org_id=org_id)
assert user_auth.settings_store == mock_store
@@ -966,7 +975,13 @@ class TestOpenHandsApiKey:
@pytest.mark.asyncio
async def test_get_openhands_api_key_raises_for_missing_user(self):
- """Test that _get_openhands_api_key raises ValueError if user not found."""
+ """Test that _get_openhands_api_key raises ValueError if user not found.
+
+ The error message now collapses ``user not found`` and
+ ``user without org`` into a single ``has no current organization``
+ case, since both ultimately mean we cannot resolve an effective
+ org for the request.
+ """
user_id = 'nonexistent_user'
user_auth = SaasUserAuth(
@@ -978,7 +993,9 @@ class TestOpenHandsApiKey:
mock_user_store.get_user_by_id = AsyncMock(return_value=None)
# Act & Assert
- with pytest.raises(ValueError, match=f'User not found: {user_id}'):
+ with pytest.raises(
+ ValueError, match=f'User {user_id} has no current organization'
+ ):
await user_auth._get_openhands_api_key()
@pytest.mark.asyncio