Skip to content

🙌 OpenHands: AI-Driven Development

feat(api-keys): make 'unbound' org scope an explicit, first-class option (#15096)

Tim O'Farrell387d2b86b62b
diff --git a/enterprise/server/auth/authorization.py b/enterprise/server/auth/authorization.py
index 1d8469e8c1..b773148196 100644
--- a/enterprise/server/auth/authorization.py
+++ b/enterprise/server/auth/authorization.py
@@ -343,8 +343,10 @@ async def get_api_key_org_id_from_request(request: Request) -> UUID | None:
"""Get the org_id bound to the API key used for authentication.
Returns None if:
- - Not authenticated via API key (cookie auth)
- - API key is a legacy key without org binding
+ - Not authenticated via API key (cookie auth), or
+ - The API key is *unbound* -- the request's effective org is then
+ resolved per-request via the ``X-Org-Id`` header or the caller's
+ ``user.current_org_id`` (see ``SaasUserAuth._resolve_org_id``).
"""
user_auth = getattr(request.state, 'user_auth', None)
if user_auth and hasattr(user_auth, 'get_api_key_org_id'):
diff --git a/enterprise/server/auth/saas_user_auth.py b/enterprise/server/auth/saas_user_auth.py
index 419beb040e..17fa3eadf0 100644
--- a/enterprise/server/auth/saas_user_auth.py
+++ b/enterprise/server/auth/saas_user_auth.py
@@ -94,8 +94,11 @@ class SaasUserAuth(UserAuth):
"""Get the organization ID bound to the API key used for authentication.
Returns:
- The org_id if authenticated via API key with org binding, None otherwise
- (cookie auth or legacy API keys without org binding).
+ The org_id if authenticated via an API key with an explicit org
+ binding; ``None`` for cookie auth or for *unbound* API keys (in
+ which case the request's effective org is resolved per-request
+ via the ``X-Org-Id`` header or, as a fallback, the caller's
+ ``user.current_org_id`` -- see :meth:`_resolve_org_id`).
"""
return self.api_key_org_id
diff --git a/enterprise/server/routes/api_keys.py b/enterprise/server/routes/api_keys.py
index 6483910175..b5f189479c 100644
--- a/enterprise/server/routes/api_keys.py
+++ b/enterprise/server/routes/api_keys.py
@@ -4,6 +4,7 @@ from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Request, status
from pydantic import BaseModel, SecretStr, field_validator, model_validator
+from server.auth.authorization import get_user_super_role
from server.auth.org_context import EFFECTIVE_ORG_ID
from server.auth.saas_user_auth import SaasUserAuth
from storage.api_key import ApiKey
@@ -116,6 +117,11 @@ class ApiKeyCreate(BaseModel):
name: str | None = None
not_before: datetime | None = None
expires_at: datetime | None = None
+ # Org the key is bound to. ``None`` (or omitted) creates an *unbound*
+ # key whose effective org is resolved per-request via the ``X-Org-Id``
+ # header or, as a fallback, the caller's ``user.current_org_id``. When
+ # set, the caller must be a member of the requested org.
+ org_id: UUID | None = None
@field_validator('expires_at')
def validate_expiration(cls, v):
@@ -141,6 +147,8 @@ class ApiKeyResponse(BaseModel):
last_used_at: datetime | None = None
not_before: datetime | None = None
expires_at: datetime | None = None
+ # ``None`` denotes an unbound key (scoped per-request via ``X-Org-Id``).
+ org_id: UUID | None = None
class ApiKeyCreateResponse(ApiKeyResponse):
@@ -160,11 +168,19 @@ class MessageResponse(BaseModel):
class CurrentApiKeyResponse(BaseModel):
- """Response model for the current API key endpoint."""
+ """Response model for the current API key endpoint.
+
+ ``org_id`` is the *effective* org id of the current request: the
+ key's bound org for org-bound keys, or the resolved org (from the
+ ``X-Org-Id`` header or ``user.current_org_id``) for unbound keys.
+ ``bound_org_id`` distinguishes the two cases -- it is the org
+ persisted on the key, or ``None`` when the key is unbound.
+ """
id: int
name: str | None
org_id: str
+ bound_org_id: str | None
user_id: str
auth_type: str
@@ -178,6 +194,7 @@ def api_key_to_response(key: ApiKey) -> ApiKeyResponse:
last_used_at=key.last_used_at,
not_before=key.not_before,
expires_at=key.expires_at,
+ org_id=key.org_id,
)
@@ -208,19 +225,72 @@ async def create_api_key(
user_id: str = Depends(get_user_id),
effective_org_id: UUID = EFFECTIVE_ORG_ID,
) -> ApiKeyCreateResponse:
- """Create a new API key bound to the request's effective org."""
+ """Create a new API key for the authenticated user.
+
+ The new key is bound to ``key_data.org_id`` when provided. An *omitted*
+ ``org_id`` falls back to the request's effective org (preserving the
+ pre-existing API). An *explicit* ``org_id: null`` creates an unbound
+ key whose effective org is resolved per-request via the ``X-Org-Id``
+ header or, as a fallback, the caller's ``user.current_org_id``. When a
+ specific ``org_id`` is supplied, the caller must be a member of that
+ org (or hold a super role).
+ """
+ if 'org_id' in key_data.model_fields_set:
+ # Caller expressed an explicit org choice -- ``null`` is meaningful
+ # (unbound key), an UUID requires a membership check.
+ target_org_id = key_data.org_id
+ else:
+ # Backwards-compatible default: bind to the effective org.
+ target_org_id = effective_org_id
+
+ if target_org_id is not None:
+ # Verify the caller is allowed to bind a key to this org.
+ try:
+ user_uuid = UUID(user_id)
+ except (TypeError, ValueError):
+ logger.warning('create_api_key_invalid_user_id', extra={'user_id': user_id})
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail='Invalid user id',
+ )
+
+ member = await OrgMemberStore.get_org_member(target_org_id, user_uuid)
+ if member is None:
+ # Super-role bypass mirrors ``_resolve_org_id``: a user with a
+ # cross-org "super" role can bind keys on behalf of orgs they
+ # have not joined. The route still requires the explicit
+ # ``org_id`` in the request body for this to apply.
+ super_role = await get_user_super_role(user_id)
+ if super_role is None:
+ logger.warning(
+ 'create_api_key_not_a_member',
+ extra={'user_id': user_id, 'org_id': str(target_org_id)},
+ )
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail='User is not a member of the requested organization',
+ )
+
try:
api_key = await api_key_store.create_api_key(
user_id,
key_data.name,
expires_at=key_data.expires_at,
not_before=key_data.not_before,
- org_id=effective_org_id,
+ org_id=target_org_id,
+ # We've already decided the binding above (explicit null for
+ # unbound, the supplied UUID, or the effective org when omitted)
+ # so disable the store's current-org fallback.
+ use_current_org_fallback=False,
)
- # Get the created key details
- keys = await api_key_store.list_api_keys(user_id, org_id=effective_org_id)
+ # Look up the row we just inserted so the response reflects the
+ # persisted ``org_id`` (which may be ``None`` for unbound keys).
+ # ``list_api_keys`` returns both bound keys for ``target_org_id`` and
+ # any unbound keys; matching by name+org disambiguates when the
+ # caller reuses a name across different org scopes.
+ keys = await api_key_store.list_api_keys(user_id, org_id=target_org_id)
for key in keys:
- if key.name == key_data.name:
+ if key.name == key_data.name and key.org_id == target_org_id:
return ApiKeyCreateResponse(
id=key.id,
name=key.name,
@@ -229,7 +299,10 @@ async def create_api_key(
last_used_at=key.last_used_at,
not_before=key.not_before,
expires_at=key.expires_at,
+ org_id=key.org_id,
)
+ except HTTPException:
+ raise
except Exception:
logger.exception('Error creating API key')
raise HTTPException(
@@ -304,9 +377,9 @@ async def get_current_api_key(
) -> CurrentApiKeyResponse:
"""Get information about the currently authenticated API key.
- This endpoint returns metadata about the API key used for the current request,
- including the org_id associated with the key. This is useful for API key
- callers who need to know which organization context their key operates in.
+ Returns the key's bound org (``bound_org_id``, ``None`` for unbound
+ keys) and the request's effective org (``org_id``, resolved from the
+ ``X-Org-Id`` header or ``user.current_org_id`` for unbound keys).
Returns 400 if not authenticated via API key (e.g., using cookie auth).
"""
@@ -322,20 +395,23 @@ async def get_current_api_key(
# In SaaS context, bearer auth always produces SaasUserAuth
saas_user_auth = cast(SaasUserAuth, user_auth)
- if saas_user_auth.api_key_org_id is None:
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail='This API key was created before organization support. Please regenerate your API key to use this endpoint.',
- )
if saas_user_auth.api_key_id is None:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='This endpoint requires API key authentication.',
)
+ # Resolve the effective org so unbound keys report the org they're
+ # actually operating in for this request.
+ effective_org_id = await saas_user_auth.get_effective_org_id()
return CurrentApiKeyResponse(
id=saas_user_auth.api_key_id,
name=saas_user_auth.api_key_name,
- org_id=str(saas_user_auth.api_key_org_id),
+ org_id=str(effective_org_id) if effective_org_id is not None else '',
+ bound_org_id=(
+ str(saas_user_auth.api_key_org_id)
+ if saas_user_auth.api_key_org_id is not None
+ else None
+ ),
user_id=user_id,
auth_type=saas_user_auth.auth_type.value,
)
diff --git a/enterprise/storage/api_key_store.py b/enterprise/storage/api_key_store.py
index 2d421e2f70..7ae4de19bc 100644
--- a/enterprise/storage/api_key_store.py
+++ b/enterprise/storage/api_key_store.py
@@ -19,7 +19,10 @@ class ApiKeyValidationResult:
"""Result of API key validation containing user and organization info."""
user_id: str
- org_id: UUID | None # None for legacy API keys without org binding
+ # None when the key is unbound (scoped to the caller via X-Org-Id at
+ # request time, or defaulting to user.current_org_id when no header is
+ # supplied). See ``SaasUserAuth._resolve_org_id`` for the full precedence.
+ org_id: UUID | None
key_id: int
key_name: str | None
@@ -81,6 +84,8 @@ class ApiKeyStore:
expires_at: datetime | None = None,
not_before: datetime | None = None,
org_id: UUID | None = None,
+ *,
+ use_current_org_fallback: bool = True,
) -> str:
"""Create a new API key for a user.
@@ -92,16 +97,23 @@ class ApiKeyStore:
not_before: Optional earliest activation datetime in UTC. The key is
rejected at validation time when ``now < not_before``. Timezone
info is stripped before writing, mirroring ``expires_at``.
- 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``).
+ org_id: Org binding for the new key. ``None`` creates an
+ *unbound* key (resolved per-request via ``X-Org-Id`` or the
+ caller's ``user.current_org_id``). When
+ ``use_current_org_fallback`` is ``True`` (the default,
+ preserved for backwards compatibility with internal callers),
+ a ``None`` ``org_id`` is replaced with the user's
+ ``current_org_id`` instead. Callers that have already decided
+ the binding should pass ``use_current_org_fallback=False``
+ so an explicit ``None`` is stored verbatim.
+ use_current_org_fallback: See ``org_id``. Defaults to ``True``
+ for backward compatibility.
Returns:
The generated API key
"""
api_key = self.generate_api_key()
- if org_id is None:
+ if org_id is None and use_current_org_fallback:
user = await UserStore.get_user_by_id(user_id)
if user is None:
raise ValueError(f'User not found: {user_id}')
@@ -240,7 +252,9 @@ class ApiKeyStore:
Returns:
ApiKeyValidationResult if the key is valid, None otherwise.
- The org_id may be None for legacy API keys that weren't bound to an organization.
+ The ``org_id`` is ``None`` for *unbound* keys (see
+ ``create_api_key``); such keys are scoped per-request via the
+ ``X-Org-Id`` header or the caller's current org id.
"""
now = datetime.now(UTC)
@@ -328,17 +342,18 @@ class ApiKeyStore:
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.
+ """List user-visible API keys for a user.
+
+ Returns keys that are either bound to ``org_id`` **or** unbound
+ (``org_id IS NULL`` -- visible from any org context). Internal keys
+ (system keys and ``MCP_API_KEY``) are excluded.
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
+ the user's persisted ``current_org_id``. Request-context
+ callers should pass the effective org id so the user's
+ current selection is honored.
"""
if org_id is None:
user = await UserStore.get_user_by_id(user_id)
@@ -350,7 +365,9 @@ class ApiKeyStore:
result = await session.execute(
select(ApiKey).filter(
ApiKey.user_id == user_id,
- ApiKey.org_id == org_id,
+ # Bound to the requested org OR unbound (visible
+ # regardless of which org the user is currently in).
+ (ApiKey.org_id == org_id) | (ApiKey.org_id.is_(None)),
)
)
keys = result.scalars().all()
diff --git a/enterprise/tests/unit/server/routes/test_api_keys.py b/enterprise/tests/unit/server/routes/test_api_keys.py
index 4bc8f5fe1b..c4d1479990 100644
--- a/enterprise/tests/unit/server/routes/test_api_keys.py
+++ b/enterprise/tests/unit/server/routes/test_api_keys.py
@@ -485,7 +485,7 @@ class TestGetCurrentApiKey:
@pytest.mark.asyncio
@patch('server.routes.api_keys.get_user_auth')
async def test_returns_api_key_info_for_bearer_auth(self, mock_get_user_auth):
- """Test that API key metadata including org_id is returned for bearer token auth."""
+ """Org-bound API key reports its bound org in both fields."""
# Arrange
user_id = 'user-123'
org_id = uuid.uuid4()
@@ -499,6 +499,8 @@ class TestGetCurrentApiKey:
api_key_id=42,
api_key_name='My Production Key',
)
+ # Bound keys resolve to their bound org in all contexts.
+ user_auth.get_effective_org_id = AsyncMock(return_value=org_id)
mock_get_user_auth.return_value = user_auth
# Act
@@ -507,6 +509,7 @@ class TestGetCurrentApiKey:
# Assert
assert isinstance(result, CurrentApiKeyResponse)
assert result.org_id == str(org_id)
+ assert result.bound_org_id == str(org_id)
assert result.id == 42
assert result.name == 'My Production Key'
assert result.user_id == user_id
@@ -533,40 +536,67 @@ class TestGetCurrentApiKey:
@pytest.mark.asyncio
@patch('server.routes.api_keys.get_user_auth')
- async def test_returns_400_when_api_key_org_id_is_none(self, mock_get_user_auth):
- """Test that 400 is returned when API key has no org_id (legacy key)."""
+ async def test_unbound_key_reports_effective_org(self, mock_get_user_auth):
+ """An unbound API key reports the resolved effective org and None bound."""
# Arrange
user_id = 'user-123'
+ effective_org = uuid.uuid4()
mock_request = MagicMock()
user_auth = SaasUserAuth(
refresh_token=SecretStr('mock-token'),
user_id=user_id,
auth_type=AuthType.BEARER,
- api_key_org_id=None, # No org_id - legacy key
+ api_key_org_id=None, # Unbound key
api_key_id=42,
- api_key_name='Legacy Key',
+ api_key_name='Multi-org Key',
)
+ # Unbound keys resolve to the request's effective org (X-Org-Id or
+ # user.current_org_id).
+ user_auth.get_effective_org_id = AsyncMock(return_value=effective_org)
mock_get_user_auth.return_value = user_auth
- # Act & Assert
- with pytest.raises(HTTPException) as exc_info:
- await get_current_api_key(request=mock_request, user_id=user_id)
+ # Act
+ result = await get_current_api_key(request=mock_request, user_id=user_id)
- assert exc_info.value.status_code == 400
- assert 'created before organization support' in exc_info.value.detail
+ # Assert
+ assert isinstance(result, CurrentApiKeyResponse)
+ assert result.org_id == str(effective_org)
+ assert result.bound_org_id is None
+ assert result.id == 42
+ assert result.name == 'Multi-org Key'
class TestApiKeyCreateValidation:
- """Test the ApiKeyCreate Pydantic model's active-window validators."""
+ """Test the ApiKeyCreate Pydantic model's validators."""
def test_accepts_no_window(self):
- """A request with neither bound set is valid (legacy behaviour)."""
+ """A request with neither bound set is valid."""
from server.routes.api_keys import ApiKeyCreate
- model = ApiKeyCreate(name='legacy-style')
+ model = ApiKeyCreate(name='unbound-style')
assert model.not_before is None
assert model.expires_at is None
+ assert model.org_id is None
+
+ def test_accepts_explicit_unbound_org_id(self):
+ """An explicit ``org_id=None`` is preserved as a model-field-set signal."""
+ from server.routes.api_keys import ApiKeyCreate
+
+ model = ApiKeyCreate(name='unbound-style', org_id=None)
+ assert model.org_id is None
+ # ``org_id`` is in ``model_fields_set`` even when set to ``None``;
+ # the route uses this to distinguish "explicit unbound" from
+ # "field omitted -> fall back to effective org".
+ assert 'org_id' in model.model_fields_set
+
+ def test_accepts_specific_org_id(self):
+ """An explicit ``org_id=<UUID>`` binds the new key to that org."""
+ from server.routes.api_keys import ApiKeyCreate
+
+ bound_org = uuid.uuid4()
+ model = ApiKeyCreate(name='bound-style', org_id=bound_org)
+ assert model.org_id == bound_org
def test_accepts_not_before_only(self):
"""A request with only not_before is valid."""
@@ -636,3 +666,130 @@ class TestApiKeyCreateValidation:
expires_at=same,
)
assert 'not_before must be earlier than expires_at' in str(exc_info.value)
+
+
+class TestCreateApiKeyRoute:
+ """End-to-end tests for the ``POST /api/keys`` route."""
+
+ @pytest.mark.asyncio
+ async def test_unbound_org_id_creates_unbound_key(self):
+ """Regression: ``org_id=None`` must produce an unbound (org_id NULL) row.
+
+ The route previously delegated to ``ApiKeyStore.create_api_key``
+ with ``org_id=None``; the store then silently rebound to
+ ``user.current_org_id``, so the row inserted never matched the
+ route's ``name + org_id is None`` lookup and the route returned
+ 500. The store now accepts ``use_current_org_fallback=False`` and
+ the route passes that flag.
+ """
+ from server.routes.api_keys import ApiKeyCreate, create_api_key
+
+ # A row the route will "find" after insert: an unbound key with
+ # the matching name. This is what the (now fixed) route expects
+ # ``list_api_keys`` to surface.
+ matching_key = MagicMock()
+ matching_key.id = 1
+ matching_key.name = 'AllOrgs'
+ matching_key.org_id = None
+ matching_key.created_at = datetime.now(UTC)
+ matching_key.last_used_at = None
+ matching_key.not_before = None
+ matching_key.expires_at = None
+
+ captured: dict = {}
+
+ async def fake_create_api_key(
+ user_id,
+ name,
+ expires_at=None,
+ not_before=None,
+ org_id=...,
+ **kwargs,
+ ):
+ # The store should be called with the route's explicit
+ # ``None`` and the fallback disabled.
+ captured['org_id'] = org_id
+ captured['use_current_org_fallback'] = kwargs.get(
+ 'use_current_org_fallback'
+ )
+ return 'sk-oh-fake'
+
+ with (
+ patch(
+ 'server.routes.api_keys.api_key_store.create_api_key',
+ AsyncMock(side_effect=fake_create_api_key),
+ ),
+ patch(
+ 'server.routes.api_keys.api_key_store.list_api_keys',
+ AsyncMock(return_value=[matching_key]),
+ ),
+ ):
+ result = await create_api_key(
+ key_data=ApiKeyCreate(name='AllOrgs', org_id=None),
+ user_id=str(uuid.uuid4()),
+ effective_org_id=uuid.uuid4(),
+ )
+
+ assert captured['org_id'] is None
+ assert captured['use_current_org_fallback'] is False
+ assert result.org_id is None
+ assert result.name == 'AllOrgs'
+
+ @pytest.mark.asyncio
+ async def test_omitted_org_id_falls_back_to_effective_org(self):
+ """An *omitted* ``org_id`` binds the new key to the effective org."""
+ from server.routes.api_keys import ApiKeyCreate, create_api_key
+
+ effective_org = uuid.uuid4()
+ bound_key = MagicMock()
+ bound_key.id = 2
+ bound_key.name = 'Bound'
+ bound_key.org_id = effective_org
+ bound_key.created_at = datetime.now(UTC)
+ bound_key.last_used_at = None
+ bound_key.not_before = None
+ bound_key.expires_at = None
+
+ captured: dict = {}
+
+ async def fake_create_api_key(
+ user_id,
+ name,
+ expires_at=None,
+ not_before=None,
+ org_id=...,
+ **kwargs,
+ ):
+ captured['org_id'] = org_id
+ captured['use_current_org_fallback'] = kwargs.get(
+ 'use_current_org_fallback'
+ )
+ return 'sk-oh-fake'
+
+ with (
+ patch(
+ 'server.routes.api_keys.api_key_store.create_api_key',
+ AsyncMock(side_effect=fake_create_api_key),
+ ),
+ patch(
+ 'server.routes.api_keys.api_key_store.list_api_keys',
+ AsyncMock(return_value=[bound_key]),
+ ),
+ patch(
+ # Membership check on the effective org -- return a non-None
+ # member so the route passes the check.
+ 'server.routes.api_keys.OrgMemberStore.get_org_member',
+ AsyncMock(return_value=MagicMock()),
+ ),
+ ):
+ result = await create_api_key(
+ key_data=ApiKeyCreate(name='Bound'), # no org_id
+ user_id=str(uuid.uuid4()),
+ effective_org_id=effective_org,
+ )
+
+ # Route forwards the effective org to the store, and disables the
+ # fallback so the store doesn't double-rebind.
+ assert captured['org_id'] == effective_org
+ assert captured['use_current_org_fallback'] is False
+ assert result.org_id == effective_org
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 dcaaf2d0b9..12344f67e5 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
@@ -1091,15 +1091,17 @@ class TestApiKeyOrgIdHandling:
)
@pytest.mark.asyncio
- async def test_legacy_api_key_without_org_uses_user_current_org(
+ async def test_unbound_api_key_without_org_uses_user_current_org(
self,
async_session_with_users: AsyncSession,
):
- """Test that legacy API keys (without org_id) fall back to user's current org.
+ """An unbound API key falls back to the user's current org.
- Legacy API keys created before the org_id feature was added will have
- api_key_org_id = None. In this case, we should fall back to the user's
- current_org_id.
+ An unbound key (``api_key_org_id = None``) is explicitly supported:
+ the effective org is resolved per-request from the ``X-Org-Id``
+ header or, as a fallback, the caller's ``user.current_org_id``.
+ The mock here returns ``None`` from ``get_effective_org_id`` so the
+ injector falls back to the persisted ``user.current_org_id``.
"""
from dataclasses import dataclass
@@ -1107,7 +1109,7 @@ class TestApiKeyOrgIdHandling:
StoredConversationMetadataSaas,
)
- # Create a mock UserAuth with API key but NO org_id (legacy key)
+ # Create a mock UserAuth with an unbound API key.
@dataclass
class MockUserAuth:
user_id: str
@@ -1132,10 +1134,10 @@ class TestApiKeyOrgIdHandling:
async def get_user_id(self) -> str | None:
return await self.user_auth.get_user_id()
- # Create service with mock auth context where API key has NO org_id
+ # Create service with mock auth context where API key is unbound.
mock_user_auth = MockUserAuth(
user_id=str(USER1_ID),
- api_key_org_id=None, # Legacy key without org binding
+ api_key_org_id=None, # Unbound key
)
mock_context = MockAuthUserContext(user_auth=mock_user_auth)
@@ -1149,8 +1151,8 @@ class TestApiKeyOrgIdHandling:
conv_info = AppConversationInfo(
id=conv_id,
created_by_user_id=str(USER1_ID),
- sandbox_id='sandbox_legacy_key_test',
- title='Legacy API Key Conversation',
+ sandbox_id='sandbox_unbound_key_test',
+ title='Unbound API Key Conversation',
)
await service.save_app_conversation_info(conv_info)
@@ -1164,7 +1166,7 @@ class TestApiKeyOrgIdHandling:
assert saas_metadata is not None, 'SAAS metadata should be created'
assert saas_metadata.user_id == USER1_ID
assert saas_metadata.org_id == ORG1_ID, (
- 'Legacy key should fall back to user current org (ORG1)'
+ 'Unbound key should fall back to user current org (ORG1)'
)
@pytest.mark.asyncio
diff --git a/enterprise/tests/unit/test_api_key_store.py b/enterprise/tests/unit/test_api_key_store.py
index 7cbf53e85d..0770380e10 100644
--- a/enterprise/tests/unit/test_api_key_store.py
+++ b/enterprise/tests/unit/test_api_key_store.py
@@ -134,6 +134,71 @@ async def test_create_api_key(
assert api_key.org_id == mock_user.current_org_id
+@patch('storage.api_key_store.UserStore.get_user_by_id')
+async def test_create_api_key_unbound_with_fallback_disabled(
+ mock_get_user, api_key_store, async_session_maker, mock_user
+):
+ """Explicit ``org_id=None`` is stored verbatim when fallback is disabled.
+
+ Regression: previously, ``create_api_key(user, name, org_id=None)``
+ silently rebound to ``user.current_org_id``, so the "All orgs" / unbound
+ key flow in ``POST /api/keys`` returned 500 -- the route inserted
+ with ``None`` matching nothing.
+ """
+ user_id = str(uuid.uuid4())
+ name = 'Unbound Key'
+ # If the fallback were still active, the store would look up the user
+ # and rebind ``org_id`` to ``mock_user.current_org_id``.
+ mock_get_user.return_value = mock_user
+
+ with patch('storage.api_key_store.a_session_maker', async_session_maker):
+ result = await api_key_store.create_api_key(
+ user_id,
+ name,
+ org_id=None,
+ use_current_org_fallback=False,
+ )
+
+ assert result.startswith('sk-oh-')
+ # The user must NOT be looked up when the caller has already decided
+ # the binding -- that's the whole point of opting out of the fallback.
+ mock_get_user.assert_not_called()
+
+ async with async_session_maker() as session:
+ result_db = await session.execute(
+ select(ApiKey).filter(ApiKey.user_id == user_id)
+ )
+ api_key = result_db.scalars().first()
+ assert api_key is not None
+ assert api_key.name == name
+ assert api_key.org_id is None # stored verbatim
+
+
+@patch('storage.api_key_store.UserStore.get_user_by_id')
+async def test_create_api_key_default_fallback_still_works(
+ mock_get_user, api_key_store, async_session_maker, mock_user
+):
+ """Default (fallback) behavior is preserved for existing internal callers."""
+ user_id = str(uuid.uuid4())
+ name = 'Legacy-style Key'
+ mock_get_user.return_value = mock_user
+
+ with patch('storage.api_key_store.a_session_maker', async_session_maker):
+ # No ``use_current_org_fallback`` argument -- the default kicks in.
+ await api_key_store.create_api_key(user_id, name, org_id=None)
+
+ mock_get_user.assert_called_once_with(user_id)
+ async with async_session_maker() as session:
+ result_db = await session.execute(
+ select(ApiKey).filter(ApiKey.user_id == user_id)
+ )
+ api_key = result_db.scalars().first()
+ assert api_key is not None
+ assert api_key.org_id == mock_user.current_org_id
+
+
@pytest.mark.asyncio
async def test_validate_api_key_valid(api_key_store, async_session_maker):
"""Test validating a valid API key returns user_id and org_id."""
@@ -257,20 +322,25 @@ async def test_validate_api_key_valid_timezone_naive(
@pytest.mark.asyncio
-async def test_validate_api_key_legacy_without_org_id(
+async def test_validate_api_key_unbound_returns_none_org_id(
api_key_store, async_session_maker
):
- """Test validating a legacy API key without org_id returns None for org_id."""
+ """An unbound API key validates successfully and reports ``org_id=None``.
+
+ The effective org for an unbound key is resolved per-request by
+ ``SaasUserAuth`` (from ``X-Org-Id`` or ``user.current_org_id``); the
+ store layer only reflects the persisted binding.
+ """
# Arrange
user_id = str(uuid.uuid4())
- api_key_value = 'test-legacy-key-no-org'
+ api_key_value = 'test-unbound-key-no-org'
async with async_session_maker() as session:
key_record = ApiKey(
key=api_key_value,
user_id=user_id,
- org_id=None, # Legacy key without org binding
- name='Legacy Key',
+ org_id=None, # Unbound key
+ name='Multi-org Key',
)
session.add(key_record)
await session.commit()
diff --git a/enterprise/tests/unit/test_authorization.py b/enterprise/tests/unit/test_authorization.py
index cb17137c50..78e04ae5dd 100644
--- a/enterprise/tests/unit/test_authorization.py
+++ b/enterprise/tests/unit/test_authorization.py
@@ -920,11 +920,17 @@ class TestApiKeyOrgValidation:
)
@pytest.mark.asyncio
- async def test_allows_access_for_legacy_api_key_without_org_binding(self):
+ async def test_allows_access_for_unbound_api_key_without_org_binding(self):
"""
- GIVEN: Legacy API key without org_id binding (org_id is None)
+ GIVEN: Unbound API key (api_key_org_id is None)
WHEN: Permission checker is called
- THEN: Falls through to normal permission check (backward compatible)
+ THEN: Falls through to the normal permission check.
+
+ Unbound keys are explicitly supported: the effective org is
+ resolved per-request via ``X-Org-Id`` or
+ ``user.current_org_id``; here the explicit path ``{org_id}``
+ parameter is what the route uses, so the unbound key does not
+ impose any additional check beyond the regular role lookup.
"""
# Arrange
user_id = str(uuid4())
diff --git a/frontend/src/api/api-keys.ts b/frontend/src/api/api-keys.ts
index ecb3d78c34..478e7ec6c9 100644
--- a/frontend/src/api/api-keys.ts
+++ b/frontend/src/api/api-keys.ts
@@ -8,6 +8,12 @@ export interface ApiKey {
last_used_at: string | null;
not_before: string | null;
expires_at: string | null;
+ /**
+ * Org the key is bound to. ``null`` means the key is *unbound* and can be
+ * scoped per-request via the ``X-Org-Id`` header (falling back to the
+ * user's current org when the header is absent).
+ */
+ org_id: string | null;
}
export interface CreateApiKeyResponse {
@@ -18,17 +24,29 @@ export interface CreateApiKeyResponse {
created_at: string;
not_before: string | null;
expires_at: string | null;
+ org_id: string | null;
}
export interface CreateApiKeyInput {
name: string;
not_before?: string | null; // ISO 8601 UTC; omit to activate immediately
expires_at?: string | null; // ISO 8601 UTC; omit for no expiration
+ /**
+ * Org to bind the new key to.
+ * - ``null`` (explicit): unbound key -- usable against any org via
+ * ``X-Org-Id`` or the caller's current org.
+ * - ``undefined`` (omitted): bind to the request's effective org.
+ * - UUID string: bind to the specified org (caller must be a member).
+ */
+ org_id?: string | null;
}
class ApiKeysClient {
/**
- * Get all API keys for the current user
+ * Get all API keys for the current user.
+ *
+ * Returns keys that are either bound to the effective org or unbound
+ * (``org_id: null`` -- visible regardless of the active org context).
*/
static async getApiKeys(): Promise<ApiKey[]> {
const { data } = await openHands.get<unknown>("/api/keys");
@@ -38,16 +56,26 @@ class ApiKeysClient {
/**
* Create a new API key
- * @param input - Key name plus optional active-window bounds
+ * @param input - Key name, optional active-window bounds, and optional
+ * org binding (see ``CreateApiKeyInput.org_id``).
*/
static async createApiKey(
input: CreateApiKeyInput,
): Promise<CreateApiKeyResponse> {
- const { data } = await openHands.post<CreateApiKeyResponse>("/api/keys", {
+ // Forward the raw ``org_id`` field as-is so that an explicit ``null``
+ // ("All orgs" / unbound key) is preserved through the JSON request.
+ const body: Record<string, unknown> = {
name: input.name,
not_before: input.not_before ?? undefined,
expires_at: input.expires_at ?? undefined,
- });
+ };
+ if ("org_id" in input) {
+ body.org_id = input.org_id;
+ }
+ const { data } = await openHands.post<CreateApiKeyResponse>(
+ "/api/keys",
+ body,
+ );
return data;
}
diff --git a/frontend/src/components/features/settings/api-keys-manager.test.tsx b/frontend/src/components/features/settings/api-keys-manager.test.tsx
index 5cd641f159..824d7e3795 100644
--- a/frontend/src/components/features/settings/api-keys-manager.test.tsx
+++ b/frontend/src/components/features/settings/api-keys-manager.test.tsx
@@ -13,6 +13,7 @@ const mockApiKeys: ApiKey[] = vi.hoisted(() => [
last_used_at: "2026-05-15T10:00:00Z",
not_before: null,
expires_at: null,
+ org_id: null,
},
{
id: "2",
@@ -22,15 +23,50 @@ const mockApiKeys: ApiKey[] = vi.hoisted(() => [
last_used_at: null,
not_before: "2099-01-01T00:00:00Z",
expires_at: "2099-12-31T00:00:00Z",
+ org_id: null,
},
{
id: "3",
+ name: "Acme Key",
+ prefix: "oh_acme_",
+ created_at: "2025-01-01T10:00:00Z",
+ last_used_at: "2025-12-01T10:00:00Z",
+ not_before: null,
+ expires_at: null,
+ org_id: "org-acme",
+ },
+ {
+ id: "4",
+ name: "Personal Key",
+ prefix: "oh_personal_",
+ created_at: "2025-01-01T10:00:00Z",
+ last_used_at: null,
+ not_before: null,
+ expires_at: null,
+ org_id: "org-personal",
+ },
+ {
+ id: "5",
+ name: "Orphaned Key",
+ prefix: "oh_orphan_",
+ created_at: "2025-01-01T10:00:00Z",
+ last_used_at: null,
+ not_before: null,
+ expires_at: null,
+ org_id: "org-no-longer-a-member",
+ },
+ {
+ // The expired-status test below expects a key whose name is
+ // "Expired Key" and whose expires_at is in the past; restore
+ // that row so the status tests still find it.
+ id: "6",
name: "Expired Key",
prefix: "oh_expired_",
created_at: "2025-01-01T10:00:00Z",
last_used_at: "2025-12-01T10:00:00Z",
not_before: null,
expires_at: "2025-12-31T00:00:00Z",
+ org_id: "org-acme",
},
]);
@@ -50,6 +86,22 @@ vi.mock("#/hooks/mutation/use-refresh-llm-api-key", () => ({
useRefreshLlmApiKey: () => ({ mutateAsync: vi.fn(), isPending: false }),
}));
+vi.mock("#/hooks/query/use-organizations", () => ({
+ useOrganizations: () => ({
+ data: {
+ organizations: [
+ // Order matters: the test for "Personal Key" expects the
+ // localized "Personal Workspace" label, matching the
+ // ``is_personal: true`` flag.
+ { id: "org-acme", name: "Acme Inc.", is_personal: false },
+ { id: "org-personal", name: "ignored", is_personal: true },
+ ],
+ currentOrgId: "org-acme",
+ },
+ isLoading: false,
+ }),
+}));
+
const renderManager = () =>
render(
<QueryClientProvider client={new QueryClient()}>
@@ -103,3 +155,64 @@ describe("ApiKeysManager - status column", () => {
expect(row!.textContent).toContain("SETTINGS$API_KEY_EXPIRES_AT");
});
});
+
+describe("ApiKeysManager - scope column", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("renders a Scope column header", () => {
+ renderManager();
+ expect(
+ screen.getByRole("columnheader", { name: "SETTINGS$API_KEY_SCOPE" }),
+ ).toBeInTheDocument();
+ });
+
+ it("labels unbound keys (org_id=null) with the 'All orgs' badge", () => {
+ renderManager();
+ const row = screen.getByText("Active Key").closest("tr");
+ expect(row).not.toBeNull();
+ expect(row!.textContent).toContain("SETTINGS$API_KEY_SCOPE_ALL_ORGS");
+ // Unbound badges use the blue accent color.
+ expect(row!.querySelector('[class*="bg-blue"]')).toBeInTheDocument();
+ });
+
+ it("labels bound keys with the org's display name", () => {
+ renderManager();
+ const row = screen.getByText("Acme Key").closest("tr");
+ expect(row).not.toBeNull();
+ // The bound badge shows the org name, not the generic "Bound to
+ // current org" string. The tooltip carries the descriptive label.
+ expect(row!.textContent).toContain("Acme Inc.");
+ expect(row!.textContent).not.toContain("SETTINGS$API_KEY_SCOPE_BOUND");
+ // The bound-badge span (gray "tertiary" background) carries the
+ // explanatory tooltip; assert on it specifically rather than the
+ // generic [title] selector which would also match the name cell.
+ const badge = row!.querySelector('span[title^="SETTINGS$API_KEY_SCOPE"]');
+ expect(badge?.getAttribute("title")).toBe(
+ "SETTINGS$API_KEY_SCOPE_BOUND_TITLE",
+ );
+ // Bound badges do not use the blue accent color.
+ expect(row!.querySelector('[class*="bg-blue"]')).toBeNull();
+ });
+
+ it("renders 'Personal Workspace' for keys bound to the personal org", () => {
+ renderManager();
+ const row = screen.getByText("Personal Key").closest("tr");
+ expect(row).not.toBeNull();
+ // The badge uses the localized "Personal Workspace" label rather
+ // than the underlying org name, matching the create modal and the
+ // header org selector.
+ expect(row!.textContent).toContain("ORG$PERSONAL_WORKSPACE");
+ expect(row!.textContent).not.toContain("ignored");
+ });
+
+ it("falls back to a short id when the bound org is no longer visible", () => {
+ renderManager();
+ const row = screen.getByText("Orphaned Key").closest("tr");
+ expect(row).not.toBeNull();
+ // The user is no longer a member of this org so we have no
+ // display name; show a short id prefix and the descriptive title.
+ expect(row!.textContent).toContain("org-no-l");
+ });
+});
diff --git a/frontend/src/components/features/settings/api-keys-manager.tsx b/frontend/src/components/features/settings/api-keys-manager.tsx
index 3766d24759..5ab1581f70 100644
--- a/frontend/src/components/features/settings/api-keys-manager.tsx
+++ b/frontend/src/components/features/settings/api-keys-manager.tsx
@@ -1,4 +1,4 @@
-import React, { useState } from "react";
+import React, { useMemo, useState } from "react";
import { useTranslation, Trans } from "react-i18next";
import { useNavigate } from "react-router";
import { FaTrash, FaEye, FaEyeSlash, FaCopy } from "react-icons/fa6";
@@ -17,6 +17,7 @@ import { NewApiKeyModal } from "./new-api-key-modal";
import { useApiKeys } from "#/hooks/query/use-api-keys";
import { useLlmApiKey } from "#/hooks/query/use-llm-api-key";
import { useRefreshLlmApiKey } from "#/hooks/mutation/use-refresh-llm-api-key";
+import { useOrganizations } from "#/hooks/query/use-organizations";
interface LlmApiKeyManagerProps {
llmApiKey: { key: string | null } | undefined;
@@ -199,8 +200,69 @@ interface ApiKeysTableProps {
onDeleteKey: (key: ApiKey) => void;
}
+function ApiKeyScopeBadge({
+ orgId,
+ orgLabel,
+}: {
+ orgId: string | null;
+ orgLabel: string;
+}) {
+ const { t } = useTranslation();
+ if (orgId === null) {
+ // Unbound key -- usable against any org via X-Org-Id.
+ return (
+ <span
+ className="inline-block px-2 py-0.5 rounded text-xs font-medium bg-blue-500/20 text-blue-300"
+ title={t(I18nKey.SETTINGS$API_KEY_ORG_ALL_ORGS_DESCRIPTION)}
+ >
+ {t(I18nKey.SETTINGS$API_KEY_SCOPE_ALL_ORGS)}
+ </span>
+ );
+ }
+ // Bound key -- show the org's display name (or the fallback label
+ // when the org is no longer in the user's membership list).
+ return (
+ <span
+ className="inline-block px-2 py-0.5 rounded text-xs font-medium bg-tertiary text-gray-300"
+ title={t(I18nKey.SETTINGS$API_KEY_SCOPE_BOUND_TITLE)}
+ >
+ {orgLabel}
+ </span>
+ );
+}
+
function ApiKeysTable({ apiKeys, isLoading, onDeleteKey }: ApiKeysTableProps) {
const { t } = useTranslation();
+ const { data: organizationsData } = useOrganizations();
+
+ // Map org id -> display label. Personal workspaces are rendered using
+ // the same "Personal Workspace" string as the create modal so the
+ // list, modal and header all read the same way.
+ const orgLabelsById = useMemo(() => {
+ const map = new Map<string, string>();
+ for (const org of organizationsData?.organizations ?? []) {
+ map.set(
+ org.id,
+ org.is_personal ? t(I18nKey.ORG$PERSONAL_WORKSPACE) : org.name,
+ );
+ }
+ return map;
+ }, [organizationsData, t]);
+
+ const resolveOrgLabel = (orgId: string | null): string => {
+ if (orgId === null) {
+ // Unbound keys are rendered as their own badge; this shouldn't
+ // be reached but keep a sensible fallback.
+ return t(I18nKey.SETTINGS$API_KEY_SCOPE_ALL_ORGS);
+ }
+ return (
+ orgLabelsById.get(orgId) ??
+ // Fallback when the user can no longer see the org (e.g. they
+ // left it). The id is short and unambiguous; the title carries
+ // the full sentence.
+ orgId.slice(0, 8)
+ );
+ };
const formatDate = (dateString: string | null) => {
if (!dateString) return "—";
@@ -236,6 +298,9 @@ function ApiKeysTable({ apiKeys, isLoading, onDeleteKey }: ApiKeysTableProps) {
<th className="text-left p-3 text-sm font-medium">
{t(I18nKey.SETTINGS$API_KEY_STATUS)}
</th>
+ <th className="text-left p-3 text-sm font-medium">
+ {t(I18nKey.SETTINGS$API_KEY_SCOPE)}
+ </th>
<th className="text-right p-3 text-sm font-medium">
{t(I18nKey.SETTINGS$ACTIONS)}
</th>
@@ -279,6 +344,12 @@ function ApiKeysTable({ apiKeys, isLoading, onDeleteKey }: ApiKeysTableProps) {
)}
</div>
</td>
+ <td className="p-3 text-sm">
+ <ApiKeyScopeBadge
+ orgId={key.org_id}
+ orgLabel={resolveOrgLabel(key.org_id)}
+ />
+ </td>
<td className="p-3 text-right">
<button
type="button"
diff --git a/frontend/src/components/features/settings/create-api-key-modal.test.tsx b/frontend/src/components/features/settings/create-api-key-modal.test.tsx
index 0e65af4756..3d51519dac 100644
--- a/frontend/src/components/features/settings/create-api-key-modal.test.tsx
+++ b/frontend/src/components/features/settings/create-api-key-modal.test.tsx
@@ -8,6 +8,13 @@ const mockState = vi.hoisted(() => ({
mutateAsync: vi.fn(),
invalidateQueries: vi.fn(),
isPending: false,
+ organizations: {
+ organizations: [
+ { id: "org-a", name: "Org A", is_personal: false },
+ { id: "org-b", name: "Personal Workspace", is_personal: true },
+ ],
+ currentOrgId: "org-a",
+ },
}));
vi.mock("#/hooks/mutation/use-create-api-key", () => ({
@@ -17,6 +24,17 @@ vi.mock("#/hooks/mutation/use-create-api-key", () => ({
}),
}));
+vi.mock("#/hooks/query/use-organizations", () => ({
+ useOrganizations: () => ({
+ data: mockState.organizations,
+ isLoading: false,
+ }),
+}));
+
+vi.mock("#/context/use-selected-organization", () => ({
+ useSelectedOrganizationId: () => ({ organizationId: "org-a" }),
+}));
+
vi.mock("#/utils/custom-toast-handlers", () => ({
displayErrorToast: vi.fn(),
displaySuccessToast: vi.fn(),
@@ -47,6 +65,7 @@ describe("CreateApiKeyModal", () => {
created_at: "2026-06-01T00:00:00Z",
not_before: null,
expires_at: null,
+ org_id: null,
});
});
@@ -56,7 +75,17 @@ describe("CreateApiKeyModal", () => {
expect(screen.getByTestId("api-key-expires-at-input")).toBeInTheDocument();
});
- it("submits with name only when no dates are set", async () => {
+ it("renders the org selector with the org selector label", () => {
+ renderModal({});
+ expect(screen.getByTestId("api-key-org-selector")).toBeInTheDocument();
+ // The label above the selector makes the "Organization" intent clear.
+ expect(screen.getByText("SETTINGS$API_KEY_ORG_LABEL")).toBeInTheDocument();
+ // The help text mentions the "All orgs" / "X-Org-Id" trade-off so
+ // users discover the new option.
+ expect(screen.getByText("SETTINGS$API_KEY_ORG_HELP")).toBeInTheDocument();
+ });
+
+ it("submits with name + explicit org_id=null (unbound) when 'All orgs' is selected", async () => {
const onKeyCreated = vi.fn();
renderModal({ onKeyCreated });
@@ -70,6 +99,7 @@ describe("CreateApiKeyModal", () => {
name: "My Key",
not_before: undefined,
expires_at: undefined,
+ org_id: null,
});
});
expect(onKeyCreated).toHaveBeenCalled();
@@ -95,6 +125,7 @@ describe("CreateApiKeyModal", () => {
});
const payload = mockState.mutateAsync.mock.calls[0][0];
expect(payload.name).toBe("Windowed");
+ expect(payload.org_id).toBeNull();
expect(typeof payload.not_before).toBe("string");
expect(typeof payload.expires_at).toBe("string");
expect(new Date(payload.not_before).toISOString()).toBe(
diff --git a/frontend/src/components/features/settings/create-api-key-modal.tsx b/frontend/src/components/features/settings/create-api-key-modal.tsx
index 5d37924af1..0ff642d589 100644
--- a/frontend/src/components/features/settings/create-api-key-modal.tsx
+++ b/frontend/src/components/features/settings/create-api-key-modal.tsx
@@ -1,4 +1,4 @@
-import React, { useState } from "react";
+import React, { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { I18nKey } from "#/i18n/declaration";
import { BrandButton } from "#/components/features/settings/brand-button";
@@ -9,6 +9,10 @@ import { displayErrorToast } from "#/utils/custom-toast-handlers";
import { mutateWithToast } from "#/utils/mutate-with-toast";
import { ApiKeyModalBase } from "./api-key-modal-base";
import { useCreateApiKey } from "#/hooks/mutation/use-create-api-key";
+import { useOrganizations } from "#/hooks/query/use-organizations";
+import { useSelectedOrganizationId } from "#/context/use-selected-organization";
+import { Dropdown } from "#/ui/dropdown/dropdown";
+import { DropdownOption } from "#/ui/dropdown/types";
interface CreateApiKeyModalProps {
isOpen: boolean;
@@ -16,6 +20,12 @@ interface CreateApiKeyModalProps {
onKeyCreated: (newKey: CreateApiKeyResponse) => void;
}
+// Sentinel value used in the dropdown UI to represent an unbound
+// ("All orgs") selection. Distinct from any real org id and from
+// ``null`` / ``undefined`` to keep the explicit-vs-omitted distinction
+// intact on the wire.
+const ALL_ORGS_VALUE = "__all_orgs__";
+
// Converts a `datetime-local` input value ("2026-01-31T14:30") to a UTC ISO
// string. Returns undefined when the input is empty.
const localDateTimeToIso = (value: string): string | undefined => {
@@ -34,8 +44,34 @@ export function CreateApiKeyModal({
const [newKeyName, setNewKeyName] = useState("");
const [notBefore, setNotBefore] = useState("");
const [expiresAt, setExpiresAt] = useState("");
+ const [selectedOrg, setSelectedOrg] = useState<string>(ALL_ORGS_VALUE);
const createApiKeyMutation = useCreateApiKey();
+ const { data: organizationsData, isLoading: isLoadingOrganizations } =
+ useOrganizations();
+ const { organizationId: currentOrgId } = useSelectedOrganizationId();
+
+ const orgOptions: DropdownOption[] = useMemo(() => {
+ const orgs = organizationsData?.organizations ?? [];
+ return [
+ // "All orgs" maps to an unbound API key.
+ {
+ value: ALL_ORGS_VALUE,
+ label: t(I18nKey.SETTINGS$API_KEY_ALL_ORGS),
+ },
+ ...orgs.map((org) => ({
+ value: org.id,
+ label: org.is_personal ? t(I18nKey.ORG$PERSONAL_WORKSPACE) : org.name,
+ })),
+ ];
+ }, [organizationsData, t]);
+
+ const selectedOption = useMemo(
+ () =>
+ orgOptions.find((option) => option.value === selectedOrg) ??
+ orgOptions[0],
+ [orgOptions, selectedOrg],
+ );
const handleCreateKey = async () => {
if (!newKeyName.trim()) {
@@ -55,12 +91,19 @@ export function CreateApiKeyModal({
return;
}
+ // ``null`` (explicit) creates an unbound key. The chosen org id maps
+ // directly to a bound key. We forward ``org_id`` only when the user
+ // has made an explicit choice so omitting the field falls back to the
+ // server's effective-org default.
+ const orgIdForApi = selectedOrg === ALL_ORGS_VALUE ? null : selectedOrg;
+
const newKey = await mutateWithToast(
createApiKeyMutation,
{
name: newKeyName.trim(),
not_before: notBeforeIso,
expires_at: expiresAtIso,
+ org_id: orgIdForApi,
},
{
success: t(I18nKey.SETTINGS$API_KEY_CREATED),
@@ -73,6 +116,9 @@ export function CreateApiKeyModal({
setNewKeyName("");
setNotBefore("");
setExpiresAt("");
+ // Reset to the user's currently selected org on success so the next
+ // open of the modal does not surprise the user with the last choice.
+ setSelectedOrg(currentOrgId ?? ALL_ORGS_VALUE);
}
};
@@ -80,6 +126,7 @@ export function CreateApiKeyModal({
setNewKeyName("");
setNotBefore("");
setExpiresAt("");
+ setSelectedOrg(currentOrgId ?? ALL_ORGS_VALUE);
onClose();
};
@@ -90,7 +137,11 @@ export function CreateApiKeyModal({
variant="primary"
className="grow"
onClick={handleCreateKey}
- isDisabled={createApiKeyMutation.isPending || !newKeyName.trim()}
+ isDisabled={
+ createApiKeyMutation.isPending ||
+ isLoadingOrganizations ||
+ !newKeyName.trim()
+ }
>
{createApiKeyMutation.isPending ? (
<LoadingSpinner size="small" />
@@ -129,6 +180,29 @@ export function CreateApiKeyModal({
className="w-full mt-4"
type="text"
/>
+ <div className="mt-6">
+ <label
+ htmlFor="api-key-org-selector"
+ className="text-sm text-gray-300 mb-2 block"
+ >
+ {t(I18nKey.SETTINGS$API_KEY_ORG_LABEL)}
+ </label>
+ <Dropdown
+ testId="api-key-org-selector"
+ defaultValue={selectedOption}
+ options={orgOptions}
+ loading={isLoadingOrganizations}
+ placeholder={t(I18nKey.SETTINGS$API_KEY_ORG_PLACEHOLDER)}
+ onChange={(item) => {
+ if (item) {
+ setSelectedOrg(item.value);
+ }
+ }}
+ />
+ <p className="text-xs text-gray-400 mt-2">
+ {t(I18nKey.SETTINGS$API_KEY_ORG_HELP)}
+ </p>
+ </div>
<p className="text-sm text-gray-300 mt-6">
{t(I18nKey.SETTINGS$API_KEY_ACTIVE_WINDOW)}
</p>
diff --git a/frontend/src/i18n/declaration.ts b/frontend/src/i18n/declaration.ts
index f51d70b94f..28b2dd4d15 100644
--- a/frontend/src/i18n/declaration.ts
+++ b/frontend/src/i18n/declaration.ts
@@ -696,6 +696,15 @@ export enum I18nKey {
SETTINGS$API_KEY_STATUS_EXPIRED = "SETTINGS$API_KEY_STATUS_EXPIRED",
SETTINGS$API_KEY_WINDOW_INVALID = "SETTINGS$API_KEY_WINDOW_INVALID",
SETTINGS$API_KEY_NOT_YET_ACTIVE = "SETTINGS$API_KEY_NOT_YET_ACTIVE",
+ SETTINGS$API_KEY_ALL_ORGS = "SETTINGS$API_KEY_ALL_ORGS",
+ SETTINGS$API_KEY_ORG_LABEL = "SETTINGS$API_KEY_ORG_LABEL",
+ SETTINGS$API_KEY_ORG_PLACEHOLDER = "SETTINGS$API_KEY_ORG_PLACEHOLDER",
+ SETTINGS$API_KEY_ORG_HELP = "SETTINGS$API_KEY_ORG_HELP",
+ SETTINGS$API_KEY_ORG_ALL_ORGS_DESCRIPTION = "SETTINGS$API_KEY_ORG_ALL_ORGS_DESCRIPTION",
+ SETTINGS$API_KEY_SCOPE_ALL_ORGS = "SETTINGS$API_KEY_SCOPE_ALL_ORGS",
+ SETTINGS$API_KEY_SCOPE_BOUND = "SETTINGS$API_KEY_SCOPE_BOUND",
+ SETTINGS$API_KEY_SCOPE_BOUND_TITLE = "SETTINGS$API_KEY_SCOPE_BOUND_TITLE",
+ SETTINGS$API_KEY_SCOPE = "SETTINGS$API_KEY_SCOPE",
BUTTON$CREATE = "BUTTON$CREATE",
BUTTON$DELETE = "BUTTON$DELETE",
BUTTON$COPY_TO_CLIPBOARD = "BUTTON$COPY_TO_CLIPBOARD",
diff --git a/frontend/src/i18n/translation.json b/frontend/src/i18n/translation.json
index 613f98aee4..c6f0925dda 100644
--- a/frontend/src/i18n/translation.json
+++ b/frontend/src/i18n/translation.json
@@ -11831,6 +11831,159 @@
"tr": "Henüz etkin değil",
"ca": "Encara no actiu"
},
+ "SETTINGS$API_KEY_ALL_ORGS": {
+ "en": "All orgs",
+ "uk": "Усі організації",
+ "ja": "すべての組織",
+ "zh-CN": "所有组织",
+ "zh-TW": "所有組織",
+ "ko-KR": "모든 조직",
+ "no": "Alle organisasjoner",
+ "ar": "جميع المنظمات",
+ "de": "Alle Organisationen",
+ "fr": "Toutes les organisations",
+ "it": "Tutte le organizzazioni",
+ "pt": "Todas as organizações",
+ "es": "Todas las organizaciones",
+ "tr": "Tüm kuruluşlar",
+ "ca": "Totes les organitzacions"
+ },
+ "SETTINGS$API_KEY_ORG_LABEL": {
+ "en": "Organization",
+ "uk": "Організація",
+ "ja": "組織",
+ "zh-CN": "组织",
+ "zh-TW": "組織",
+ "ko-KR": "조직",
+ "no": "Organisasjon",
+ "ar": "المنظمة",
+ "de": "Organisation",
+ "fr": "Organisation",
+ "it": "Organizzazione",
+ "pt": "Organização",
+ "es": "Organización",
+ "tr": "Kuruluş",
+ "ca": "Organització"
+ },
+ "SETTINGS$API_KEY_ORG_PLACEHOLDER": {
+ "en": "Select an organization",
+ "uk": "Виберіть організацію",
+ "ja": "組織を選択",
+ "zh-CN": "选择组织",
+ "zh-TW": "選擇組織",
+ "ko-KR": "조직 선택",
+ "no": "Velg en organisasjon",
+ "ar": "اختر منظمة",
+ "de": "Organisation auswählen",
+ "fr": "Sélectionner une organisation",
+ "it": "Seleziona un'organizzazione",
+ "pt": "Selecione uma organização",
+ "es": "Seleccionar una organización",
+ "tr": "Bir kuruluş seçin",
+ "ca": "Seleccioneu una organització"
+ },
+ "SETTINGS$API_KEY_ORG_HELP": {
+ "en": "Choose \"All orgs\" to create an unbound key you can scope per-request via the X-Org-Id header. Pick a specific org to bind the key to that org only.",
+ "uk": "Виберіть \"Усі організації\", щоб створити незв'язаний ключ, який можна обмежити для кожного запиту через заголовок X-Org-Id. Виберіть конкретну організацію, щоб прив'язати ключ лише до неї.",
+ "ja": "「すべての組織」を選択すると、X-Org-Idヘッダーでリクエストごとにスコープを設定できる非バインドキーを作成できます。特定の組織を選択すると、その組織だけにキーがバインドされます。",
+ "zh-CN": "选择“所有组织”以创建一个未绑定的密钥,您可以通过 X-Org-Id 标头按请求范围限定。选择特定组织以将密钥仅绑定到该组织。",
+ "zh-TW": "選擇「所有組織」以建立未綁定金鑰,您可以透過 X-Org-Id 標頭按請求範圍限定。選擇特定組織以僅將金鑰綁定到該組織。",
+ "ko-KR": "\"모든 조직\"을 선택하면 X-Org-Id 헤더를 통해 요청별로 범위를 지정할 수 있는 바인딩되지 않은 키를 만들 수 있습니다. 특정 조직을 선택하면 해당 조직에만 키가 바인딩됩니다.",
+ "no": "Velg \"Alle organisasjoner\" for å opprette en ubundet nøkkel som kan avgrenses per forespørsel via X-Org-Id-headeren. Velg en bestemt organisasjon for å binde nøkkelen kun til den organisasjonen.",
+ "ar": "اختر \"جميع المنظمات\" لإنشاء مفتاح غير مربوط يمكنك تحديد نطاقه لكل طلب عبر رأس X-Org-Id. اختر مؤسسة معينة لربط المفتاح بتلك المؤسسة فقط.",
+ "de": "Wählen Sie \"Alle Organisationen\", um einen ungebundenen Schlüssel zu erstellen, den Sie pro Anfrage über den X-Org-Id-Header einschränken können. Wählen Sie eine bestimmte Organisation, um den Schlüssel nur an diese zu binden.",
+ "fr": "Choisissez « Toutes les organisations » pour créer une clé non liée que vous pouvez limiter par requête via l'en-tête X-Org-Id. Sélectionnez une organisation spécifique pour lier la clé à cette seule organisation.",
+ "it": "Scegli \"Tutte le organizzazioni\" per creare una chiave non vincolata che puoi limitare per richiesta tramite l'intestazione X-Org-Id. Seleziona un'organizzazione specifica per vincolare la chiave solo a quella.",
+ "pt": "Escolha \"Todas as organizações\" para criar uma chave não vinculada que pode ser limitada por solicitação através do cabeçalho X-Org-Id. Selecione uma organização específica para vincular a chave apenas a ela.",
+ "es": "Elija \"Todas las organizaciones\" para crear una clave no vinculada que puede acotar por solicitud mediante el encabezado X-Org-Id. Seleccione una organización específica para vincular la clave solo a esa.",
+ "tr": "\"Tüm kuruluşlar\" seçeneğini belirleyerek X-Org-Id başlığı aracılığıyla istek başına kapsamı daraltılabilecek bağlanmamış bir anahtar oluşturun. Anahtarı yalnızca belirli bir kuruluşa bağlamak için o kuruluşu seçin.",
+ "ca": "Trieu \"Totes les organitzacions\" per crear una clau no vinculada que podeu acotar per sol·licitud mitjançant la capçalera X-Org-Id. Seleccioneu una organització específica per vincular la clau només a aquesta."
+ },
+ "SETTINGS$API_KEY_ORG_ALL_ORGS_DESCRIPTION": {
+ "en": "Unbound key — usable against any org you belong to via the X-Org-Id header.",
+ "uk": "Незв'язаний ключ — може використовуватися для будь-якої організації, до якої ви належите, через заголовок X-Org-Id.",
+ "ja": "非バインドキー — X-Org-Idヘッダー経由であなたが所属する任意の組織に対して使用可能。",
+ "zh-CN": "未绑定密钥 — 可通过 X-Org-Id 标头对您所属的任何组织使用。",
+ "zh-TW": "未綁定金鑰 — 可透過 X-Org-Id 標頭對您所屬的任何組織使用。",
+ "ko-KR": "바인딩되지 않은 키 — X-Org-Id 헤더를 통해 귀하가 속한 모든 조직에 대해 사용 가능.",
+ "no": "Ubundet nøkkel — kan brukes mot enhver organisasjon du tilhører via X-Org-Id-headeren.",
+ "ar": "مفتاح غير مربوط — قابل للاستخدام مع أي مؤسسة تنتمي إليها عبر رأس X-Org-Id.",
+ "de": "Ungebundener Schlüssel — nutzbar für jede Organisation, der Sie angehören, über den X-Org-Id-Header.",
+ "fr": "Clé non liée — utilisable pour toute organisation à laquelle vous appartenez via l'en-tête X-Org-Id.",
+ "it": "Chiave non vincolata — utilizzabile per qualsiasi organizzazione a cui appartieni tramite l'intestazione X-Org-Id.",
+ "pt": "Chave não vinculada — utilizável em qualquer organização à qual você pertence através do cabeçalho X-Org-Id.",
+ "es": "Clave no vinculada — utilizable para cualquier organización a la que pertenezca mediante el encabezado X-Org-Id.",
+ "tr": "Bağlanmamış anahtar — X-Org-Id başlığı aracılığıyla üyesi olduğunuz herhangi bir kuruluş için kullanılabilir.",
+ "ca": "Clau no vinculada — utilitzable per a qualsevol organització a la qual pertanyeu mitjançant la capçalera X-Org-Id."
+ },
+ "SETTINGS$API_KEY_SCOPE_ALL_ORGS": {
+ "en": "All orgs",
+ "uk": "Усі організації",
+ "ja": "すべての組織",
+ "zh-CN": "所有组织",
+ "zh-TW": "所有組織",
+ "ko-KR": "모든 조직",
+ "no": "Alle organisasjoner",
+ "ar": "جميع المنظمات",
+ "de": "Alle Organisationen",
+ "fr": "Toutes les organisations",
+ "it": "Tutte le organizzazioni",
+ "pt": "Todas as organizações",
+ "es": "Todas las organizaciones",
+ "tr": "Tüm kuruluşlar",
+ "ca": "Totes les organitzacions"
+ },
+ "SETTINGS$API_KEY_SCOPE_BOUND": {
+ "en": "Bound to current org",
+ "uk": "Прив'язано до поточної організації",
+ "ja": "現在の組織にバインド",
+ "zh-CN": "绑定到当前组织",
+ "zh-TW": "綁定到目前組織",
+ "ko-KR": "현재 조직에 바인딩",
+ "no": "Bundet til gjeldende organisasjon",
+ "ar": "مربوط بالمنظمة الحالية",
+ "de": "An aktuelle Organisation gebunden",
+ "fr": "Liée à l'organisation actuelle",
+ "it": "Vincolata all'organizzazione corrente",
+ "pt": "Vinculada à organização atual",
+ "es": "Vinculada a la organización actual",
+ "tr": "Geçerli kuruluşa bağlı",
+ "ca": "Vinculada a l'organització actual"
+ },
+ "SETTINGS$API_KEY_SCOPE_BOUND_TITLE": {
+ "en": "Bound to a specific organization",
+ "uk": "Прив'язано до конкретної організації",
+ "ja": "特定の組織にバインド",
+ "zh-CN": "绑定到特定组织",
+ "zh-TW": "綁定到特定組織",
+ "ko-KR": "특정 조직에 바인딩",
+ "no": "Bundet til en bestemt organisasjon",
+ "ar": "مربوط بمؤسسة محددة",
+ "de": "An eine bestimmte Organisation gebunden",
+ "fr": "Liée à une organisation spécifique",
+ "it": "Vincolata a un'organizzazione specifica",
+ "pt": "Vinculada a uma organização específica",
+ "es": "Vinculada a una organización específica",
+ "tr": "Belirli bir kuruluşa bağlı",
+ "ca": "Vinculada a una organització específica"
+ },
+ "SETTINGS$API_KEY_SCOPE": {
+ "en": "Scope",
+ "uk": "Область",
+ "ja": "スコープ",
+ "zh-CN": "范围",
+ "zh-TW": "範圍",
+ "ko-KR": "범위",
+ "no": "Omfang",
+ "ar": "النطاق",
+ "de": "Bereich",
+ "fr": "Portée",
+ "it": "Ambito",
+ "pt": "Escopo",
+ "es": "Alcance",
+ "tr": "Kapsam",
+ "ca": "Abast"
+ },
"BUTTON$CREATE": {
"en": "Create",
"uk": "Створити",
diff --git a/frontend/src/mocks/api-keys-handlers.ts b/frontend/src/mocks/api-keys-handlers.ts
index 60e779089d..5e8b96bad9 100644
--- a/frontend/src/mocks/api-keys-handlers.ts
+++ b/frontend/src/mocks/api-keys-handlers.ts
@@ -12,6 +12,7 @@ const DEFAULT_API_KEYS: ApiKey[] = [
last_used_at: "2026-02-18T14:30:00Z",
not_before: null,
expires_at: null,
+ org_id: null,
},
{
id: "2",
@@ -21,6 +22,7 @@ const DEFAULT_API_KEYS: ApiKey[] = [
last_used_at: null,
not_before: "2026-07-01T00:00:00Z",
expires_at: "2026-08-01T00:00:00Z",
+ org_id: null,
},
{
id: "3",
@@ -30,6 +32,7 @@ const DEFAULT_API_KEYS: ApiKey[] = [
last_used_at: "2025-12-01T09:00:00Z",
not_before: null,
expires_at: "2026-01-01T00:00:00Z",
+ org_id: null,
},
];
@@ -41,6 +44,7 @@ interface CreateApiKeyBody {
name?: string;
not_before?: string;
expires_at?: string;
+ org_id?: string | null;
}
export const API_KEYS_HANDLERS = [
@@ -68,6 +72,9 @@ export const API_KEYS_HANDLERS = [
nextId += 1;
const id = String(nextId);
+ // ``org_id`` is honored verbatim: an explicit ``null`` creates an
+ // unbound ("All orgs") key, an UUID string binds the key.
+ const orgId = body.org_id ?? null;
const newKey: ApiKey = {
id,
name: body.name,
@@ -76,6 +83,7 @@ export const API_KEYS_HANDLERS = [
last_used_at: null,
not_before: body.not_before ?? null,
expires_at: body.expires_at ?? null,
+ org_id: orgId,
};
apiKeys.set(id, newKey);
@@ -87,6 +95,7 @@ export const API_KEYS_HANDLERS = [
created_at: newKey.created_at,
not_before: newKey.not_before,
expires_at: newKey.expires_at,
+ org_id: orgId,
};
return HttpResponse.json(response);