🙌 OpenHands: AI-Driven Development
feat(api-keys): add optional active window (not_before & expires_at) (#15085)
Tim O'Farrell66941d2ad23f
diff --git a/enterprise/migrations/versions/127_add_execution_status_to_conversation_metadata.py b/enterprise/migrations/versions/127_add_execution_status_to_conversation_metadata.pyindex 037933591e..4414fea2d5 100644--- a/enterprise/migrations/versions/127_add_execution_status_to_conversation_metadata.py+++ b/enterprise/migrations/versions/127_add_execution_status_to_conversation_metadata.py@@ -24,22 +24,50 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:- with op.batch_alter_table('conversation_metadata') as batch_op:- batch_op.add_column(- sa.Column(- 'execution_status',- sa.String(),- nullable=True,+ bind = op.get_bind()+ inspector = sa.inspect(bind)+ columns = {+ column['name'] for column in inspector.get_columns('conversation_metadata')+ }+ indexes = {+ index['name'] for index in inspector.get_indexes('conversation_metadata')+ }++ if 'execution_status' not in columns:+ with op.batch_alter_table('conversation_metadata') as batch_op:+ batch_op.add_column(+ sa.Column(+ 'execution_status',+ sa.String(),+ nullable=True,+ ))- )- batch_op.create_index(++ if 'ix_conversation_metadata_execution_status' not in indexes:+ op.create_index('ix_conversation_metadata_execution_status',- 'execution_status',+ 'conversation_metadata',+ ['execution_status'],unique=False,)def downgrade() -> None:- with op.batch_alter_table('conversation_metadata') as batch_op:- batch_op.drop_index('ix_conversation_metadata_execution_status')- batch_op.drop_column('execution_status')+ bind = op.get_bind()+ inspector = sa.inspect(bind)+ columns = {+ column['name'] for column in inspector.get_columns('conversation_metadata')+ }+ indexes = {+ index['name'] for index in inspector.get_indexes('conversation_metadata')+ }++ if 'ix_conversation_metadata_execution_status' in indexes:+ op.drop_index(+ 'ix_conversation_metadata_execution_status',+ table_name='conversation_metadata',+ )++ if 'execution_status' in columns:+ with op.batch_alter_table('conversation_metadata') as batch_op:+ batch_op.drop_column('execution_status')diff --git a/enterprise/migrations/versions/128_add_not_before_to_api_keys.py b/enterprise/migrations/versions/128_add_not_before_to_api_keys.pynew file mode 100644index 0000000000..355ee83862--- /dev/null+++ b/enterprise/migrations/versions/128_add_not_before_to_api_keys.py@@ -0,0 +1,38 @@+"""Add not_before column to api_keys table.++Adds an optional ``not_before`` timestamp representing the earliest moment at+which an API key becomes valid. Combined with the existing ``expires_at``+column, this lets users define an explicit active window for a key+(``not_before <= now < expires_at``). Both bounds remain independently+optional and additive: existing rows get ``NULL`` (immediately valid) so+behaviour is unchanged for every key created before this migration.++Revision ID: 128+Revises: 127+Create Date: 2026-06-05 00:00:00.000000+"""++from typing import Sequence, Union++import sqlalchemy as sa+from alembic import op++revision: str = '128'+down_revision: Union[str, None] = '127'+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ op.add_column('api_keys', sa.Column('not_before', sa.DateTime(), nullable=True))+ op.create_index(+ op.f('ix_api_keys_not_before'),+ 'api_keys',+ ['not_before'],+ unique=False,+ )+++def downgrade() -> None:+ op.drop_index(op.f('ix_api_keys_not_before'), table_name='api_keys')+ op.drop_column('api_keys', 'not_before')diff --git a/enterprise/server/routes/api_keys.py b/enterprise/server/routes/api_keys.pyindex d647c35ddb..6483910175 100644--- a/enterprise/server/routes/api_keys.py+++ b/enterprise/server/routes/api_keys.py@@ -3,7 +3,7 @@ from typing import castfrom uuid import UUIDfrom fastapi import APIRouter, Depends, HTTPException, Request, status-from pydantic import BaseModel, SecretStr, field_validator+from pydantic import BaseModel, SecretStr, field_validator, model_validatorfrom server.auth.org_context import EFFECTIVE_ORG_IDfrom server.auth.saas_user_auth import SaasUserAuthfrom storage.api_key import ApiKey@@ -114,6 +114,7 @@ api_key_store = ApiKeyStore.get_instance()class ApiKeyCreate(BaseModel):name: str | None = None+ not_before: datetime | None = Noneexpires_at: datetime | None = None@field_validator('expires_at')@@ -122,12 +123,23 @@ class ApiKeyCreate(BaseModel):raise ValueError('Expiration date cannot be in the past')return v+ @model_validator(mode='after')+ def validate_active_window(self):+ if (+ self.not_before is not None+ and self.expires_at is not None+ and self.not_before >= self.expires_at+ ):+ raise ValueError('not_before must be earlier than expires_at')+ return self+class ApiKeyResponse(BaseModel):id: intname: str | None = Nonecreated_at: datetimelast_used_at: datetime | None = None+ not_before: datetime | None = Noneexpires_at: datetime | None = None@@ -164,6 +176,7 @@ def api_key_to_response(key: ApiKey) -> ApiKeyResponse:name=key.name,created_at=key.created_at,last_used_at=key.last_used_at,+ not_before=key.not_before,expires_at=key.expires_at,)@@ -200,7 +213,8 @@ async def create_api_key(api_key = await api_key_store.create_api_key(user_id,key_data.name,- key_data.expires_at,+ expires_at=key_data.expires_at,+ not_before=key_data.not_before,org_id=effective_org_id,)# Get the created key details@@ -213,6 +227,7 @@ async def create_api_key(key=api_key,created_at=key.created_at,last_used_at=key.last_used_at,+ not_before=key.not_before,expires_at=key.expires_at,)except Exception:diff --git a/enterprise/storage/api_key.py b/enterprise/storage/api_key.pyindex afc4b41516..74c15f6caf 100644--- a/enterprise/storage/api_key.py+++ b/enterprise/storage/api_key.py@@ -28,6 +28,7 @@ class ApiKey(Base):DateTime, server_default=text('CURRENT_TIMESTAMP'), nullable=False)last_used_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)+ not_before: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)expires_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)# Relationshipsdiff --git a/enterprise/storage/api_key_store.py b/enterprise/storage/api_key_store.pyindex ce83e392c6..483314e5ff 100644--- a/enterprise/storage/api_key_store.py+++ b/enterprise/storage/api_key_store.py@@ -24,6 +24,30 @@ class ApiKeyValidationResult:key_name: str | None+def _as_naive(value: datetime | None) -> datetime | None:+ """Strip tzinfo so a value can be written to a `TIMESTAMP WITHOUT TIME ZONE`+ column. Naive values are passed through unchanged; values already in UTC+ are returned naive without conversion (i.e. we trust the caller's value).++ TODO: switch the api_keys columns to TIMESTAMP WITH TIME ZONE and drop this.+ """+ if value is None or value.tzinfo is None:+ return value+ return value.astimezone(UTC)+++def _as_utc_aware(value: datetime | None) -> datetime | None:+ """Re-attach UTC tzinfo to a value that was stored as naive in a+ `TIMESTAMP WITHOUT TIME ZONE` column. Already-aware values are returned+ unchanged.++ TODO: switch the api_keys columns to TIMESTAMP WITH TIME ZONE and drop this.+ """+ if value is None:+ return None+ return value if value.tzinfo is not None else value.replace(tzinfo=UTC)++@dataclassclass ApiKeyStore:API_KEY_PREFIX = 'sk-oh-'@@ -55,6 +79,7 @@ class ApiKeyStore:user_id: str,name: str | None = None,expires_at: datetime | None = None,+ not_before: datetime | None = None,org_id: UUID | None = None,) -> str:"""Create a new API key for a user.@@ -64,6 +89,9 @@ class ApiKeyStore:name: Optional name for the keyexpires_at: Expiration datetime in UTC. Timezone info is stripped beforewriting to the TIMESTAMP WITHOUT TIME ZONE column.+ 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 backto the user's persisted ``current_org_id``. Callers inrequest context should pass the effective org id (see@@ -80,8 +108,8 @@ class ApiKeyStore: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:- expires_at = expires_at.replace(tzinfo=None)+ expires_at = _as_naive(expires_at)+ not_before = _as_naive(not_before)async with a_session_maker() as session:key_record = ApiKey(@@ -89,6 +117,7 @@ class ApiKeyStore:user_id=user_id,org_id=org_id,name=name,+ not_before=not_before,expires_at=expires_at,)session.add(key_record)@@ -139,11 +168,9 @@ class ApiKeyStore:# Check if expiredif existing_key.expires_at:now = datetime.now(UTC)- expires_at = existing_key.expires_at- if expires_at.tzinfo is None:- expires_at = expires_at.replace(tzinfo=UTC)+ expires_at = _as_utc_aware(existing_key.expires_at)- if expires_at < now:+ if expires_at and expires_at < now:# Key is expired, delete it and create new onelogger.info('System API key expired, re-issuing',@@ -206,6 +233,11 @@ class ApiKeyStore:async def validate_api_key(self, api_key: str) -> ApiKeyValidationResult | None:"""Validate an API key and return the associated user_id and org_id if valid.+ A key is valid only when ``not_before <= now < expires_at``. Both bounds+ are optional and independent: a ``NULL`` bound means the key is+ unconstrained in that direction. Out-of-window keys are rejected and+ ``last_used_at`` is not updated.+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.@@ -219,21 +251,24 @@ class ApiKeyStore:if not key_record:return None- # expires_at is stored as naive UTC; re-attach tzinfo for comparison.- if key_record.expires_at:- expires_at = key_record.expires_at- if expires_at.tzinfo is None:- expires_at = expires_at.replace(tzinfo=UTC)+ # not_before / expires_at are stored as naive UTC; re-attach tzinfo+ # for comparison. The two checks are independent and combined with+ # AND semantics.+ not_before = _as_utc_aware(key_record.not_before)+ if not_before and now < not_before:+ logger.info(f'API key not yet active: {key_record.id}')+ return None- if expires_at < now:- logger.info(f'API key has expired: {key_record.id}')- return None+ expires_at = _as_utc_aware(key_record.expires_at)+ if expires_at and expires_at < now:+ logger.info(f'API key has expired: {key_record.id}')+ return None# Update last_used_at timestampawait session.execute(update(ApiKey).where(ApiKey.id == key_record.id)- .values(last_used_at=now.replace(tzinfo=None))+ .values(last_used_at=_as_naive(now)))await session.commit()@@ -319,13 +354,23 @@ class ApiKeyStore:))keys = result.scalars().all()+# Filter out system keys and MCP_API_KEY- return [+ keys = [keyfor key in keysif key.name != 'MCP_API_KEY' and not self.is_system_key_name(key.name)]+ # Set timezones+ for key in keys:+ key.created_at = _as_utc_aware(key.created_at)+ key.last_used_at = _as_utc_aware(key.last_used_at)+ key.not_before = _as_utc_aware(key.not_before)+ key.expires_at = _as_utc_aware(key.expires_at)++ return keys+async def retrieve_mcp_api_key(self, user_id: str, org_id: UUID | None = None) -> str | None:diff --git a/enterprise/tests/unit/server/routes/test_api_keys.py b/enterprise/tests/unit/server/routes/test_api_keys.pyindex 010c523ac8..4bc8f5fe1b 100644--- a/enterprise/tests/unit/server/routes/test_api_keys.py+++ b/enterprise/tests/unit/server/routes/test_api_keys.py@@ -1,6 +1,7 @@"""Unit tests for API keys routes, focusing on BYOR key validation and retrieval."""import uuid+from datetime import UTC, datetime, timedeltafrom unittest.mock import AsyncMock, MagicMock, patchimport httpx@@ -554,3 +555,84 @@ class TestGetCurrentApiKey:assert exc_info.value.status_code == 400assert 'created before organization support' in exc_info.value.detail+++class TestApiKeyCreateValidation:+ """Test the ApiKeyCreate Pydantic model's active-window validators."""++ def test_accepts_no_window(self):+ """A request with neither bound set is valid (legacy behaviour)."""+ from server.routes.api_keys import ApiKeyCreate++ model = ApiKeyCreate(name='legacy-style')+ assert model.not_before is None+ assert model.expires_at is None++ def test_accepts_not_before_only(self):+ """A request with only not_before is valid."""+ from server.routes.api_keys import ApiKeyCreate++ future = datetime.now(UTC) + timedelta(days=1)+ model = ApiKeyCreate(name='future-key', not_before=future)+ assert model.not_before == future+ assert model.expires_at is None++ def test_accepts_expires_at_only(self):+ """A request with only expires_at is valid."""+ from server.routes.api_keys import ApiKeyCreate++ future = datetime.now(UTC) + timedelta(days=1)+ model = ApiKeyCreate(name='expiring-key', expires_at=future)+ assert model.not_before is None+ assert model.expires_at == future++ def test_accepts_valid_window(self):+ """A request with not_before < expires_at is valid."""+ from server.routes.api_keys import ApiKeyCreate++ not_before = datetime.now(UTC) + timedelta(days=1)+ expires_at = not_before + timedelta(days=30)+ model = ApiKeyCreate(+ name='window-key', not_before=not_before, expires_at=expires_at+ )+ assert model.not_before == not_before+ assert model.expires_at == expires_at++ def test_rejects_expires_at_in_past(self):+ from pydantic import ValidationError+ from server.routes.api_keys import ApiKeyCreate++ with pytest.raises(ValidationError) as exc_info:+ ApiKeyCreate(+ name='past-key',+ expires_at=datetime.now(UTC) - timedelta(days=1),+ )+ assert 'Expiration' in str(exc_info.value)++ def test_rejects_inverted_window(self):+ from pydantic import ValidationError+ from server.routes.api_keys import ApiKeyCreate++ not_before = datetime.now(UTC) + timedelta(days=10)+ expires_at = datetime.now(UTC) + timedelta(days=1)+ with pytest.raises(ValidationError) as exc_info:+ ApiKeyCreate(+ name='inverted-key',+ not_before=not_before,+ expires_at=expires_at,+ )+ assert 'not_before must be earlier than expires_at' in str(exc_info.value)++ def test_rejects_equal_window(self):+ """not_before == expires_at is rejected (degenerate window)."""+ from pydantic import ValidationError+ from server.routes.api_keys import ApiKeyCreate++ same = datetime.now(UTC) + timedelta(days=1)+ with pytest.raises(ValidationError) as exc_info:+ ApiKeyCreate(+ name='equal-key',+ not_before=same,+ expires_at=same,+ )+ assert 'not_before must be earlier than expires_at' in str(exc_info.value)diff --git a/enterprise/tests/unit/test_api_key_store.py b/enterprise/tests/unit/test_api_key_store.pyindex c57f63f2ae..7cbf53e85d 100644--- a/enterprise/tests/unit/test_api_key_store.py+++ b/enterprise/tests/unit/test_api_key_store.py@@ -77,6 +77,32 @@ async def test_create_api_key_strips_timezone_from_expires_at(assert record.expires_at == aware_expiry.replace(tzinfo=None)+@patch('storage.api_key_store.UserStore.get_user_by_id')+async def test_create_api_key_strips_timezone_from_not_before(+ mock_get_user, api_key_store, async_session_maker, mock_user+):+ """Timezone-aware not_before must be stored as naive UTC without shifting the value."""+ user_id = str(uuid.uuid4())+ aware_not_before = datetime.now(UTC) + timedelta(days=7)+ mock_get_user.return_value = mock_user++ with patch('storage.api_key_store.a_session_maker', async_session_maker):+ key = await api_key_store.create_api_key(+ user_id, name='nb-key', not_before=aware_not_before+ )++ async with async_session_maker() as session:+ result = await session.execute(select(ApiKey).filter(ApiKey.key == key))+ record = result.scalars().first()++ assert record.not_before is not None+ assert record.not_before.tzinfo is None+ assert record.not_before == aware_not_before.replace(tzinfo=None)+ # expires_at should still be None when only not_before is provided+ assert record.expires_at is None++@pytest.mark.asyncio@patch('storage.api_key_store.UserStore.get_user_by_id')async def test_create_api_key(@@ -260,6 +286,119 @@ async def test_validate_api_key_legacy_without_org_id(assert result.org_id is None+async def test_validate_api_key_not_yet_active(api_key_store, async_session_maker):+ """A key whose not_before is in the future must be rejected."""+ user_id = str(uuid.uuid4())+ org_id = uuid.uuid4()+ api_key_value = 'test-not-yet-active-key'++ async with async_session_maker() as session:+ key_record = ApiKey(+ key=api_key_value,+ user_id=user_id,+ org_id=org_id,+ name='Scheduled Key',+ not_before=datetime.now(UTC) + timedelta(days=1),+ )+ session.add(key_record)+ await session.commit()+ key_id = key_record.id++ with patch('storage.api_key_store.a_session_maker', async_session_maker):+ result = await api_key_store.validate_api_key(api_key_value)++ assert result is None++ # Rejected keys must NOT have last_used_at updated.+ async with async_session_maker() as session:+ stored = await session.execute(select(ApiKey).filter(ApiKey.id == key_id))+ assert stored.scalars().first().last_used_at is None+++async def test_validate_api_key_not_yet_active_timezone_naive(+ api_key_store, async_session_maker+):+ """A naive-UTC not_before in the future must also be rejected."""+ user_id = str(uuid.uuid4())+ org_id = uuid.uuid4()+ api_key_value = 'test-not-yet-active-naive'++ async with async_session_maker() as session:+ key_record = ApiKey(+ key=api_key_value,+ user_id=user_id,+ org_id=org_id,+ name='Scheduled Key Naive',+ not_before=datetime.now() + timedelta(days=1),+ )+ session.add(key_record)+ await session.commit()++ with patch('storage.api_key_store.a_session_maker', async_session_maker):+ result = await api_key_store.validate_api_key(api_key_value)++ assert result is None+++async def test_validate_api_key_active_window_inside(+ api_key_store, async_session_maker+):+ """A key with both bounds set is accepted when now is inside the window."""+ user_id = str(uuid.uuid4())+ org_id = uuid.uuid4()+ api_key_value = 'test-active-window-inside'++ async with async_session_maker() as session:+ key_record = ApiKey(+ key=api_key_value,+ user_id=user_id,+ org_id=org_id,+ name='Window Key',+ not_before=datetime.now(UTC) - timedelta(hours=1),+ expires_at=datetime.now(UTC) + timedelta(hours=1),+ )+ session.add(key_record)+ await session.commit()++ with patch('storage.api_key_store.a_session_maker', async_session_maker):+ result = await api_key_store.validate_api_key(api_key_value)++ assert isinstance(result, ApiKeyValidationResult)+ assert result.user_id == user_id+ assert result.org_id == org_id+++async def test_validate_api_key_only_not_before_past(+ api_key_store, async_session_maker+):+ """A key with only not_before in the past and no expires_at is accepted."""+ user_id = str(uuid.uuid4())+ org_id = uuid.uuid4()+ api_key_value = 'test-only-not-before'++ async with async_session_maker() as session:+ key_record = ApiKey(+ key=api_key_value,+ user_id=user_id,+ org_id=org_id,+ name='No Expiry Key',+ not_before=datetime.now(UTC) - timedelta(minutes=1),+ expires_at=None,+ )+ session.add(key_record)+ await session.commit()++ with patch('storage.api_key_store.a_session_maker', async_session_maker):+ result = await api_key_store.validate_api_key(api_key_value)++ assert isinstance(result, ApiKeyValidationResult)+ assert result.user_id == user_id++@pytest.mark.asyncioasync def test_validate_api_key_not_found(api_key_store, async_session_maker):"""Test validating a non-existent API key."""diff --git a/enterprise/tests/unit/test_saas_user_auth.py b/enterprise/tests/unit/test_saas_user_auth.pyindex 2b7e7a16b3..523b79629b 100644--- a/enterprise/tests/unit/test_saas_user_auth.py+++ b/enterprise/tests/unit/test_saas_user_auth.py@@ -688,6 +688,23 @@ async def test_saas_user_auth_from_bearer_invalid_api_key():mock_api_key_store.validate_api_key.assert_called_once_with('test_api_key')+async def test_saas_user_auth_from_bearer_key_outside_active_window():+ """A key that validate_api_key rejects (e.g. not yet active) must not produce auth."""+ mock_request = MagicMock()+ mock_request.headers = {'Authorization': 'Bearer scheduled_key'}++ with patch('server.auth.saas_user_auth.ApiKeyStore') as mock_api_key_store_cls:+ mock_api_key_store = MagicMock()+ # Simulate what validate_api_key returns when not_before is in the future.+ mock_api_key_store.validate_api_key = AsyncMock(return_value=None)+ mock_api_key_store_cls.get_instance.return_value = mock_api_key_store++ result = await saas_user_auth_from_bearer(mock_request)++ assert result is None++@pytest.mark.asyncioasync def test_saas_user_auth_from_bearer_exception():"""Test that saas_user_auth_from_bearer raises BearerTokenError on exception."""diff --git a/frontend/src/api/api-keys.ts b/frontend/src/api/api-keys.tsindex cfcad2fede..ecb3d78c34 100644--- a/frontend/src/api/api-keys.ts+++ b/frontend/src/api/api-keys.ts@@ -6,6 +6,8 @@ export interface ApiKey {prefix: string;created_at: string;last_used_at: string | null;+ not_before: string | null;+ expires_at: string | null;}export interface CreateApiKeyResponse {@@ -14,6 +16,14 @@ export interface CreateApiKeyResponse {key: string; // Full key, only returned once upon creationprefix: string;created_at: string;+ not_before: string | null;+ expires_at: 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}class ApiKeysClient {@@ -28,11 +38,15 @@ class ApiKeysClient {/*** Create a new API key- * @param name - A descriptive name for the API key+ * @param input - Key name plus optional active-window bounds*/- static async createApiKey(name: string): Promise<CreateApiKeyResponse> {+ static async createApiKey(+ input: CreateApiKeyInput,+ ): Promise<CreateApiKeyResponse> {const { data } = await openHands.post<CreateApiKeyResponse>("/api/keys", {- name,+ name: input.name,+ not_before: input.not_before ?? undefined,+ expires_at: input.expires_at ?? undefined,});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.tsxnew file mode 100644index 0000000000..5cd641f159--- /dev/null+++ b/frontend/src/components/features/settings/api-keys-manager.test.tsx@@ -0,0 +1,105 @@+import { render, screen } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { ApiKeysManager } from "./api-keys-manager";+import { ApiKey } from "#/api/api-keys";++const mockApiKeys: ApiKey[] = vi.hoisted(() => [+ {+ id: "1",+ name: "Active Key",+ prefix: "oh_active_",+ created_at: "2026-05-01T10:00:00Z",+ last_used_at: "2026-05-15T10:00:00Z",+ not_before: null,+ expires_at: null,+ },+ {+ id: "2",+ name: "Pending Key",+ prefix: "oh_pending_",+ created_at: "2026-05-01T10:00:00Z",+ last_used_at: null,+ not_before: "2099-01-01T00:00:00Z",+ expires_at: "2099-12-31T00:00:00Z",+ },+ {+ id: "3",+ 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",+ },+]);++vi.mock("#/hooks/query/use-api-keys", () => ({+ useApiKeys: () => ({ data: mockApiKeys, isLoading: false, error: null }),+}));++vi.mock("#/hooks/query/use-llm-api-key", () => ({+ useLlmApiKey: () => ({+ data: undefined,+ isLoading: true,+ isPaymentRequired: false,+ }),+}));++vi.mock("#/hooks/mutation/use-refresh-llm-api-key", () => ({+ useRefreshLlmApiKey: () => ({ mutateAsync: vi.fn(), isPending: false }),+}));++const renderManager = () =>+ render(+ <QueryClientProvider client={new QueryClient()}>+ <ApiKeysManager />+ </QueryClientProvider>,+ );++describe("ApiKeysManager - status column", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("renders a Status column header", () => {+ renderManager();+ expect(+ screen.getByRole("columnheader", { name: "SETTINGS$API_KEY_STATUS" }),+ ).toBeInTheDocument();+ });++ it("shows the correct status for an active key", () => {+ renderManager();+ const row = screen.getByText("Active Key").closest("tr");+ expect(row).not.toBeNull();+ expect(row!.querySelector('[class*="bg-green"]')).toBeInTheDocument();+ expect(row!.textContent).toContain("SETTINGS$API_KEY_STATUS_ACTIVE");+ });++ it("shows pending status and dims the row for a future-window key", () => {+ renderManager();+ const row = screen.getByText("Pending Key").closest("tr");+ expect(row).not.toBeNull();+ expect(row!.className).toContain("opacity-60");+ expect(row!.textContent).toContain("SETTINGS$API_KEY_STATUS_PENDING");+ expect(row!.querySelector('[class*="bg-yellow"]')).toBeInTheDocument();+ });++ it("shows expired status and dims the row for a past-expiry key", () => {+ renderManager();+ const row = screen.getByText("Expired Key").closest("tr");+ expect(row).not.toBeNull();+ expect(row!.className).toContain("opacity-60");+ expect(row!.textContent).toContain("SETTINGS$API_KEY_STATUS_EXPIRED");+ expect(row!.querySelector('[class*="bg-red"]')).toBeInTheDocument();+ });++ it("displays the active-window timestamps when set", () => {+ renderManager();+ const row = screen.getByText("Pending Key").closest("tr");+ expect(row).not.toBeNull();+ expect(row!.textContent).toContain("SETTINGS$API_KEY_NOT_BEFORE");+ expect(row!.textContent).toContain("SETTINGS$API_KEY_EXPIRES_AT");+ });+});diff --git a/frontend/src/components/features/settings/api-keys-manager.tsx b/frontend/src/components/features/settings/api-keys-manager.tsxindex 94128b6e6d..3766d24759 100644--- a/frontend/src/components/features/settings/api-keys-manager.tsx+++ b/frontend/src/components/features/settings/api-keys-manager.tsx@@ -157,6 +157,42 @@ function LlmApiKeyManager({);}+type ApiKeyStatus = "active" | "pending" | "expired";++const getApiKeyStatus = (key: ApiKey): ApiKeyStatus => {+ const now = Date.now();+ if (key.expires_at && new Date(key.expires_at).getTime() < now) {+ return "expired";+ }+ if (key.not_before && new Date(key.not_before).getTime() > now) {+ return "pending";+ }+ return "active";+};++const STATUS_BADGE_CLASSES: Record<ApiKeyStatus, string> = {+ active: "bg-green-500/20 text-green-300",+ pending: "bg-yellow-500/20 text-yellow-300",+ expired: "bg-red-500/20 text-red-300",+};++function ApiKeyStatusBadge({ status }: { status: ApiKeyStatus }) {+ const { t } = useTranslation();+ const labelKey = {+ active: I18nKey.SETTINGS$API_KEY_STATUS_ACTIVE,+ pending: I18nKey.SETTINGS$API_KEY_STATUS_PENDING,+ expired: I18nKey.SETTINGS$API_KEY_STATUS_EXPIRED,+ }[status];++ return (+ <span+ className={`inline-block px-2 py-0.5 rounded text-xs font-medium ${STATUS_BADGE_CLASSES[status]}`}+ >+ {t(labelKey)}+ </span>+ );+}+interface ApiKeysTableProps {apiKeys: ApiKey[];isLoading: boolean;@@ -167,7 +203,7 @@ function ApiKeysTable({ apiKeys, isLoading, onDeleteKey }: ApiKeysTableProps) {const { t } = useTranslation();const formatDate = (dateString: string | null) => {- if (!dateString) return "Never";+ if (!dateString) return "—";return new Date(dateString).toLocaleString();};@@ -197,34 +233,65 @@ function ApiKeysTable({ apiKeys, isLoading, onDeleteKey }: ApiKeysTableProps) {<th className="text-left p-3 text-sm font-medium">{t(I18nKey.SETTINGS$LAST_USED)}</th>+ <th className="text-left p-3 text-sm font-medium">+ {t(I18nKey.SETTINGS$API_KEY_STATUS)}+ </th><th className="text-right p-3 text-sm font-medium">{t(I18nKey.SETTINGS$ACTIONS)}</th></tr></thead><tbody>- {apiKeys.map((key) => (- <tr key={key.id} className="border-t border-tertiary">- <td- className="p-3 text-sm truncate max-w-[160px]"- title={key.name}- >- {key.name}- </td>- <td className="p-3 text-sm">{formatDate(key.created_at)}</td>- <td className="p-3 text-sm">{formatDate(key.last_used_at)}</td>- <td className="p-3 text-right">- <button- type="button"- onClick={() => onDeleteKey(key)}- aria-label={`Delete ${key.name}`}- className="cursor-pointer"+ {apiKeys.map((key) => {+ const status = getApiKeyStatus(key);+ const dimmed =+ status === "expired" || status === "pending" ? "opacity-60" : "";+ return (+ <tr key={key.id} className={`border-t border-tertiary ${dimmed}`}>+ <td+ className="p-3 text-sm truncate max-w-[160px]"+ title={key.name}>- <FaTrash size={16} />- </button>- </td>- </tr>- ))}+ {key.name}+ </td>+ <td className="p-3 text-sm">{formatDate(key.created_at)}</td>+ <td className="p-3 text-sm">{formatDate(key.last_used_at)}</td>+ <td className="p-3 text-sm">+ <div className="flex flex-col gap-1">+ <ApiKeyStatusBadge status={status} />+ {key.not_before && (+ <span+ className="text-xs text-gray-400"+ title={t(I18nKey.SETTINGS$API_KEY_NOT_BEFORE)}+ >+ {t(I18nKey.SETTINGS$API_KEY_NOT_BEFORE)}:{" "}+ {formatDate(key.not_before)}+ </span>+ )}+ {key.expires_at && (+ <span+ className="text-xs text-gray-400"+ title={t(I18nKey.SETTINGS$API_KEY_EXPIRES_AT)}+ >+ {t(I18nKey.SETTINGS$API_KEY_EXPIRES_AT)}:{" "}+ {formatDate(key.expires_at)}+ </span>+ )}+ </div>+ </td>+ <td className="p-3 text-right">+ <button+ type="button"+ onClick={() => onDeleteKey(key)}+ aria-label={`Delete ${key.name}`}+ className="cursor-pointer"+ >+ <FaTrash size={16} />+ </button>+ </td>+ </tr>+ );+ })}</tbody></table></div>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.tsxnew file mode 100644index 0000000000..0e65af4756--- /dev/null+++ b/frontend/src/components/features/settings/create-api-key-modal.test.tsx@@ -0,0 +1,160 @@+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { CreateApiKeyModal } from "./create-api-key-modal";+import { displayErrorToast } from "#/utils/custom-toast-handlers";++const mockState = vi.hoisted(() => ({+ mutateAsync: vi.fn(),+ invalidateQueries: vi.fn(),+ isPending: false,+}));++vi.mock("#/hooks/mutation/use-create-api-key", () => ({+ useCreateApiKey: () => ({+ mutateAsync: mockState.mutateAsync,+ isPending: mockState.isPending,+ }),+}));++vi.mock("#/utils/custom-toast-handlers", () => ({+ displayErrorToast: vi.fn(),+ displaySuccessToast: vi.fn(),+}));++const renderModal = (props: {+ onKeyCreated?: (key: unknown) => void;+ onClose?: () => void;+}) =>+ render(+ <QueryClientProvider client={new QueryClient()}>+ <CreateApiKeyModal+ isOpen+ onClose={props.onClose ?? vi.fn()}+ onKeyCreated={props.onKeyCreated ?? vi.fn()}+ />+ </QueryClientProvider>,+ );++describe("CreateApiKeyModal", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockState.mutateAsync.mockResolvedValue({+ id: "1",+ name: "Test",+ key: "sk-oh-test",+ prefix: "oh_1_",+ created_at: "2026-06-01T00:00:00Z",+ not_before: null,+ expires_at: null,+ });+ });++ it("renders the new active-window date inputs", () => {+ renderModal({});+ expect(screen.getByTestId("api-key-not-before-input")).toBeInTheDocument();+ expect(screen.getByTestId("api-key-expires-at-input")).toBeInTheDocument();+ });++ it("submits with name only when no dates are set", async () => {+ const onKeyCreated = vi.fn();+ renderModal({ onKeyCreated });++ fireEvent.change(screen.getByTestId("api-key-name-input"), {+ target: { value: "My Key" },+ });+ fireEvent.click(screen.getByRole("button", { name: "BUTTON$CREATE" }));++ await waitFor(() => {+ expect(mockState.mutateAsync).toHaveBeenCalledWith({+ name: "My Key",+ not_before: undefined,+ expires_at: undefined,+ });+ });+ expect(onKeyCreated).toHaveBeenCalled();+ });++ it("submits with name + active window when both dates are set", async () => {+ const onKeyCreated = vi.fn();+ renderModal({ onKeyCreated });++ fireEvent.change(screen.getByTestId("api-key-name-input"), {+ target: { value: "Windowed" },+ });+ fireEvent.change(screen.getByTestId("api-key-not-before-input"), {+ target: { value: "2026-07-01T10:00" },+ });+ fireEvent.change(screen.getByTestId("api-key-expires-at-input"), {+ target: { value: "2026-08-01T10:00" },+ });+ fireEvent.click(screen.getByRole("button", { name: "BUTTON$CREATE" }));++ await waitFor(() => {+ expect(mockState.mutateAsync).toHaveBeenCalled();+ });+ const payload = mockState.mutateAsync.mock.calls[0][0];+ expect(payload.name).toBe("Windowed");+ expect(typeof payload.not_before).toBe("string");+ expect(typeof payload.expires_at).toBe("string");+ expect(new Date(payload.not_before).toISOString()).toBe(+ new Date("2026-07-01T10:00").toISOString(),+ );+ expect(new Date(payload.expires_at).toISOString()).toBe(+ new Date("2026-08-01T10:00").toISOString(),+ );+ expect(onKeyCreated).toHaveBeenCalled();+ });++ it("shows an error toast and does not submit when not_before >= expires_at", async () => {+ renderModal({});++ fireEvent.change(screen.getByTestId("api-key-name-input"), {+ target: { value: "Bad Window" },+ });+ fireEvent.change(screen.getByTestId("api-key-not-before-input"), {+ target: { value: "2026-08-01T10:00" },+ });+ fireEvent.change(screen.getByTestId("api-key-expires-at-input"), {+ target: { value: "2026-07-01T10:00" },+ });+ fireEvent.click(screen.getByRole("button", { name: "BUTTON$CREATE" }));++ await waitFor(() => {+ expect(displayErrorToast).toHaveBeenCalledWith(+ "SETTINGS$API_KEY_WINDOW_INVALID",+ );+ });+ expect(mockState.mutateAsync).not.toHaveBeenCalled();+ });++ it("resets all three fields after a successful creation", async () => {+ const onClose = vi.fn();+ renderModal({ onClose });++ fireEvent.change(screen.getByTestId("api-key-name-input"), {+ target: { value: "Test" },+ });+ fireEvent.change(screen.getByTestId("api-key-not-before-input"), {+ target: { value: "2026-07-01T10:00" },+ });+ fireEvent.click(screen.getByRole("button", { name: "BUTTON$CREATE" }));++ await waitFor(() => {+ expect(+ (screen.getByTestId("api-key-name-input") as HTMLInputElement).value,+ ).toBe("");+ });+ expect(+ (screen.getByTestId("api-key-not-before-input") as HTMLInputElement)+ .value,+ ).toBe("");+ expect(+ (screen.getByTestId("api-key-expires-at-input") as HTMLInputElement)+ .value,+ ).toBe("");+ // Modal should NOT auto-close: the parent decides when to switch to+ // the "newly-created key" modal.+ expect(onClose).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/components/features/settings/create-api-key-modal.tsx b/frontend/src/components/features/settings/create-api-key-modal.tsxindex b933314aea..5d37924af1 100644--- a/frontend/src/components/features/settings/create-api-key-modal.tsx+++ b/frontend/src/components/features/settings/create-api-key-modal.tsx@@ -16,6 +16,15 @@ interface CreateApiKeyModalProps {onKeyCreated: (newKey: CreateApiKeyResponse) => void;}+// 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 => {+ if (!value) return undefined;+ const date = new Date(value);+ if (Number.isNaN(date.getTime())) return undefined;+ return date.toISOString();+};+export function CreateApiKeyModal({isOpen,onClose,@@ -23,6 +32,8 @@ export function CreateApiKeyModal({}: CreateApiKeyModalProps) {const { t } = useTranslation();const [newKeyName, setNewKeyName] = useState("");+ const [notBefore, setNotBefore] = useState("");+ const [expiresAt, setExpiresAt] = useState("");const createApiKeyMutation = useCreateApiKey();@@ -32,19 +43,43 @@ export function CreateApiKeyModal({return;}- const newKey = await mutateWithToast(createApiKeyMutation, newKeyName, {- success: t(I18nKey.SETTINGS$API_KEY_CREATED),- error: t(I18nKey.ERROR$GENERIC),- }).catch(() => null);+ const notBeforeIso = localDateTimeToIso(notBefore);+ const expiresAtIso = localDateTimeToIso(expiresAt);++ if (+ notBeforeIso &&+ expiresAtIso &&+ new Date(notBeforeIso) >= new Date(expiresAtIso)+ ) {+ displayErrorToast(t(I18nKey.SETTINGS$API_KEY_WINDOW_INVALID));+ return;+ }++ const newKey = await mutateWithToast(+ createApiKeyMutation,+ {+ name: newKeyName.trim(),+ not_before: notBeforeIso,+ expires_at: expiresAtIso,+ },+ {+ success: t(I18nKey.SETTINGS$API_KEY_CREATED),+ error: t(I18nKey.ERROR$GENERIC),+ },+ ).catch(() => null);if (newKey) {onKeyCreated(newKey);setNewKeyName("");+ setNotBefore("");+ setExpiresAt("");}};const handleCancel = () => {setNewKeyName("");+ setNotBefore("");+ setExpiresAt("");onClose();};@@ -94,6 +129,29 @@ export function CreateApiKeyModal({className="w-full mt-4"type="text"/>+ <p className="text-sm text-gray-300 mt-6">+ {t(I18nKey.SETTINGS$API_KEY_ACTIVE_WINDOW)}+ </p>+ <div className="flex flex-col gap-4 mt-2">+ <SettingsInput+ testId="api-key-not-before-input"+ label={t(I18nKey.SETTINGS$API_KEY_NOT_BEFORE)}+ value={notBefore}+ onChange={(value) => setNotBefore(value)}+ className="w-full"+ type="datetime-local"+ showOptionalTag+ />+ <SettingsInput+ testId="api-key-expires-at-input"+ label={t(I18nKey.SETTINGS$API_KEY_EXPIRES_AT)}+ value={expiresAt}+ onChange={(value) => setExpiresAt(value)}+ className="w-full"+ type="datetime-local"+ showOptionalTag+ />+ </div></div></ApiKeyModalBase>);diff --git a/frontend/src/hooks/mutation/use-create-api-key.ts b/frontend/src/hooks/mutation/use-create-api-key.tsindex 4ab31b53df..61a5d20033 100644--- a/frontend/src/hooks/mutation/use-create-api-key.ts+++ b/frontend/src/hooks/mutation/use-create-api-key.ts@@ -1,5 +1,8 @@import { useMutation, useQueryClient } from "@tanstack/react-query";-import ApiKeysClient, { CreateApiKeyResponse } from "#/api/api-keys";+import ApiKeysClient, {+ CreateApiKeyInput,+ CreateApiKeyResponse,+} from "#/api/api-keys";import { API_KEYS_QUERY_KEY } from "#/hooks/query/use-api-keys";import { useSelectedOrganizationId } from "#/context/use-selected-organization";@@ -8,8 +11,9 @@ export function useCreateApiKey() {const { organizationId } = useSelectedOrganizationId();return useMutation({- mutationFn: async (name: string): Promise<CreateApiKeyResponse> =>- ApiKeysClient.createApiKey(name),+ mutationFn: async (+ input: CreateApiKeyInput,+ ): Promise<CreateApiKeyResponse> => ApiKeysClient.createApiKey(input),onSuccess: () => {// Invalidate the API keys query to trigger a refetchqueryClient.invalidateQueries({diff --git a/frontend/src/i18n/declaration.ts b/frontend/src/i18n/declaration.tsindex 77fd0fe2f4..f51d70b94f 100644--- a/frontend/src/i18n/declaration.ts+++ b/frontend/src/i18n/declaration.ts@@ -687,6 +687,15 @@ export enum I18nKey {SETTINGS$API_KEY_COPIED = "SETTINGS$API_KEY_COPIED",SETTINGS$API_KEY_REFRESHED = "SETTINGS$API_KEY_REFRESHED",SETTINGS$API_KEY_NAME_PLACEHOLDER = "SETTINGS$API_KEY_NAME_PLACEHOLDER",+ SETTINGS$API_KEY_ACTIVE_WINDOW = "SETTINGS$API_KEY_ACTIVE_WINDOW",+ SETTINGS$API_KEY_NOT_BEFORE = "SETTINGS$API_KEY_NOT_BEFORE",+ SETTINGS$API_KEY_EXPIRES_AT = "SETTINGS$API_KEY_EXPIRES_AT",+ SETTINGS$API_KEY_STATUS = "SETTINGS$API_KEY_STATUS",+ SETTINGS$API_KEY_STATUS_ACTIVE = "SETTINGS$API_KEY_STATUS_ACTIVE",+ SETTINGS$API_KEY_STATUS_PENDING = "SETTINGS$API_KEY_STATUS_PENDING",+ 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",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.jsonindex dfc44b4f00..613f98aee4 100644--- a/frontend/src/i18n/translation.json+++ b/frontend/src/i18n/translation.json@@ -11678,6 +11678,159 @@"tr": "API Anahtarım","ca": "La meva clau d'API"},+ "SETTINGS$API_KEY_ACTIVE_WINDOW": {+ "en": "Active window (optional)",+ "uk": "Активне вікно (необов'язково)",+ "ja": "有効期間(任意)",+ "zh-CN": "有效窗口(可选)",+ "zh-TW": "有效視窗(可選)",+ "ko-KR": "활성 기간 (선택 사항)",+ "no": "Aktivt vindu (valgfritt)",+ "ar": "نافذة النشاط (اختياري)",+ "de": "Aktives Zeitfenster (optional)",+ "fr": "Fenêtre d'activité (facultatif)",+ "it": "Finestra attiva (facoltativa)",+ "pt": "Janela ativa (opcional)",+ "es": "Ventana activa (opcional)",+ "tr": "Aktif pencere (isteğe bağlı)",+ "ca": "Finestra activa (opcional)"+ },+ "SETTINGS$API_KEY_NOT_BEFORE": {+ "en": "Active from",+ "uk": "Активний з",+ "ja": "有効開始",+ "zh-CN": "生效时间",+ "zh-TW": "生效時間",+ "ko-KR": "활성 시작",+ "no": "Aktiv fra",+ "ar": "نشط من",+ "de": "Aktiv ab",+ "fr": "Actif à partir du",+ "it": "Attivo dal",+ "pt": "Ativo a partir de",+ "es": "Activo desde",+ "tr": "Şu tarihten itibaren aktif",+ "ca": "Actiu des de"+ },+ "SETTINGS$API_KEY_EXPIRES_AT": {+ "en": "Expires at",+ "uk": "Діє до",+ "ja": "有効期限",+ "zh-CN": "过期时间",+ "zh-TW": "過期時間",+ "ko-KR": "만료 시간",+ "no": "Utløper",+ "ar": "تنتهي في",+ "de": "Läuft ab am",+ "fr": "Expire le",+ "it": "Scade il",+ "pt": "Expira em",+ "es": "Caduca el",+ "tr": "Son kullanma",+ "ca": "Caduca el"+ },+ "SETTINGS$API_KEY_STATUS": {+ "en": "Status",+ "uk": "Статус",+ "ja": "ステータス",+ "zh-CN": "状态",+ "zh-TW": "狀態",+ "ko-KR": "상태",+ "no": "Status",+ "ar": "الحالة",+ "de": "Status",+ "fr": "Statut",+ "it": "Stato",+ "pt": "Status",+ "es": "Estado",+ "tr": "Durum",+ "ca": "Estat"+ },+ "SETTINGS$API_KEY_STATUS_ACTIVE": {+ "en": "Active",+ "uk": "Активний",+ "ja": "有効",+ "zh-CN": "有效",+ "zh-TW": "有效",+ "ko-KR": "활성",+ "no": "Aktiv",+ "ar": "نشط",+ "de": "Aktiv",+ "fr": "Actif",+ "it": "Attivo",+ "pt": "Ativo",+ "es": "Activo",+ "tr": "Aktif",+ "ca": "Actiu"+ },+ "SETTINGS$API_KEY_STATUS_PENDING": {+ "en": "Pending",+ "uk": "Очікує",+ "ja": "保留中",+ "zh-CN": "待激活",+ "zh-TW": "待啟用",+ "ko-KR": "대기 중",+ "no": "Venter",+ "ar": "معلق",+ "de": "Ausstehend",+ "fr": "En attente",+ "it": "In attesa",+ "pt": "Pendente",+ "es": "Pendiente",+ "tr": "Beklemede",+ "ca": "Pendent"+ },+ "SETTINGS$API_KEY_STATUS_EXPIRED": {+ "en": "Expired",+ "uk": "Прострочений",+ "ja": "期限切れ",+ "zh-CN": "已过期",+ "zh-TW": "已過期",+ "ko-KR": "만료됨",+ "no": "Utløpt",+ "ar": "منتهي الصلاحية",+ "de": "Abgelaufen",+ "fr": "Expiré",+ "it": "Scaduto",+ "pt": "Expirado",+ "es": "Caducado",+ "tr": "Süresi dolmuş",+ "ca": "Caducat"+ },+ "SETTINGS$API_KEY_WINDOW_INVALID": {+ "en": "“Active from” must be earlier than “Expires at”.",+ "uk": "«Активний з» має бути раніше за «Діє до».",+ "ja": "「有効開始」は「有効期限」より前である必要があります。",+ "zh-CN": "“生效时间”必须早于“过期时间”。",+ "zh-TW": "“生效時間”必須早於“過期時間”。",+ "ko-KR": "“활성 시작”은 “만료 시간”보다 빨라야 합니다.",+ "no": "«Aktiv fra» må være tidligere enn «Utløper».",+ "ar": "يجب أن يكون \"نشط من\" قبل \"تنتهي في\".",+ "de": "„Aktiv ab“ muss vor „Läuft ab am“ liegen.",+ "fr": "« Actif à partir du » doit être antérieur à « Expire le ».",+ "it": "“Attivo dal” deve essere precedente a “Scade il”.",+ "pt": "“Ativo a partir de” deve ser anterior a “Expira em”.",+ "es": "“Activo desde” debe ser anterior a “Caduca el”.",+ "tr": "“Şu tarihten itibaren aktif”, “Son kullanma” tarihinden önce olmalıdır.",+ "ca": "“Actiu des de” ha de ser anterior a “Caduca el”."+ },+ "SETTINGS$API_KEY_NOT_YET_ACTIVE": {+ "en": "Not yet active",+ "uk": "Ще не активний",+ "ja": "まだ有効ではありません",+ "zh-CN": "尚未生效",+ "zh-TW": "尚未生效",+ "ko-KR": "아직 활성화되지 않음",+ "no": "Ikke aktiv ennå",+ "ar": "غير نشط بعد",+ "de": "Noch nicht aktiv",+ "fr": "Pas encore actif",+ "it": "Non ancora attivo",+ "pt": "Ainda não está ativo",+ "es": "Aún no activo",+ "tr": "Henüz etkin değil",+ "ca": "Encara no actiu"+ },"BUTTON$CREATE": {"en": "Create","uk": "Створити",diff --git a/frontend/src/mocks/api-keys-handlers.ts b/frontend/src/mocks/api-keys-handlers.tsindex 339eee26de..60e779089d 100644--- a/frontend/src/mocks/api-keys-handlers.ts+++ b/frontend/src/mocks/api-keys-handlers.ts@@ -10,13 +10,26 @@ const DEFAULT_API_KEYS: ApiKey[] = [prefix: "oh_dev_",created_at: "2025-12-01T10:00:00Z",last_used_at: "2026-02-18T14:30:00Z",+ not_before: null,+ expires_at: null,},{id: "2",- name: "CI/CD Pipeline",- prefix: "oh_ci_",- created_at: "2026-01-15T08:00:00Z",+ name: "Scheduled Migration",+ prefix: "oh_sched_",+ created_at: "2026-05-01T08:00:00Z",last_used_at: null,+ not_before: "2026-07-01T00:00:00Z",+ expires_at: "2026-08-01T00:00:00Z",+ },+ {+ id: "3",+ name: "Expired CI Token",+ prefix: "oh_ci_old_",+ created_at: "2025-06-15T08:00:00Z",+ last_used_at: "2025-12-01T09:00:00Z",+ not_before: null,+ expires_at: "2026-01-01T00:00:00Z",},];@@ -24,18 +37,35 @@ const apiKeys = new Map<string, ApiKey>(DEFAULT_API_KEYS.map((key) => [key.id, key]),);+interface CreateApiKeyBody {+ name?: string;+ not_before?: string;+ expires_at?: string;+}+export const API_KEYS_HANDLERS = [// GET /api/keys - List all API keyshttp.get("/api/keys", () => HttpResponse.json(Array.from(apiKeys.values()))),// POST /api/keys - Create a new API keyhttp.post("/api/keys", async ({ request }) => {- const body = (await request.json()) as { name: string };+ const body = (await request.json()) as CreateApiKeyBody;if (!body?.name?.trim()) {return HttpResponse.json({ error: "Name is required" }, { status: 400 });}+ if (+ body.not_before &&+ body.expires_at &&+ new Date(body.not_before) >= new Date(body.expires_at)+ ) {+ return HttpResponse.json(+ { error: "not_before must be earlier than expires_at" },+ { status: 400 },+ );+ }+nextId += 1;const id = String(nextId);const newKey: ApiKey = {@@ -44,6 +74,8 @@ export const API_KEYS_HANDLERS = [prefix: `oh_${id}_`,created_at: new Date().toISOString(),last_used_at: null,+ not_before: body.not_before ?? null,+ expires_at: body.expires_at ?? null,};apiKeys.set(id, newKey);@@ -53,6 +85,8 @@ export const API_KEYS_HANDLERS = [key: `oh_${id}_sk_mock_${Math.random().toString(36).slice(2, 14)}`,prefix: newKey.prefix,created_at: newKey.created_at,+ not_before: newKey.not_before,+ expires_at: newKey.expires_at,};return HttpResponse.json(response);