Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

Expire registration keys after 90 days unless chosen otherwise

Petr Bauch19318b2b3d1e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 589f16f6f..52d45e7a9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -91,6 +91,14 @@ version of their own to them without also giving them a release of their own.
however active they are. A session still ends after 24 hours without a
refresh. Sessions from before this release count from when their cookie
was issued.
+- **Registration keys expire.** A registration key made under API keys
+ worked until someone deleted it. A new key now expires after 90 days by
+ default; when creating it you can choose 1 year instead, or **Never**,
+ which warns that the key keeps working if it leaks. `POST /api-keys`
+ takes `expires_in_days` (1 to 365, or `"never"`; 90 when left out), the
+ key list shows each key's expiry or **No expiry**, and an expired key is
+ refused with 401 wherever keys are accepted. Keys made before this release,
+ agents' own keys and the deployment's bootstrap key do not expire.
- **Messages with files attached are checked by Switch Trust.** A message with
a file used to skip the check entirely, typed text included, both from a
person on a chat platform and from an agent sending files. Now the text is
diff --git a/core/switch_core/bridges/agent/api/handlers.py b/core/switch_core/bridges/agent/api/handlers.py
index a768b875f..6628c9164 100644
--- a/core/switch_core/bridges/agent/api/handlers.py
+++ b/core/switch_core/bridges/agent/api/handlers.py
@@ -167,6 +167,8 @@ async def _resolve_registration_user_id(
key = await api_key_store.get_by_hash(session, token_hash)
if key is None or key.type not in REGISTRATION_KEY_TYPES:
raise HTTPException(status_code=401, detail="Invalid registration token")
+ if key.expired(datetime.now(UTC)):
+ raise HTTPException(status_code=401, detail="Registration token has expired")
# Which credential this was is worth keeping: a deployment bootstrapping
# its first agents through the shared key and a user minting a key of
# their own are different moments in adoption, and the key type is the
diff --git a/core/switch_core/bridges/agent/auth.py b/core/switch_core/bridges/agent/auth.py
index 92428eb5f..42fb5569b 100644
--- a/core/switch_core/bridges/agent/auth.py
+++ b/core/switch_core/bridges/agent/auth.py
@@ -5,6 +5,7 @@ import json
import logging
import re
from dataclasses import dataclass
+from datetime import UTC, datetime
from typing import Protocol
import jwt
@@ -38,6 +39,14 @@ from switch_core.tenant_context import tenant_scope
logger = logging.getLogger(__name__)
+class ApiKeyExpired(Exception):
+ """A presented API key matched a row whose `expires_at` has passed."""
+
+ def __init__(self, api_key: ApiKey) -> None:
+ super().__init__(f"API key {api_key.id} expired at {api_key.expires_at}")
+ self.api_key = api_key
+
+
# Path prefixes that bypass the Bearer middleware entirely. These are either
# public (health, OAuth flow, external webhooks) or use their own auth scheme
# (gateway uses cookie-based JWT).
@@ -281,7 +290,17 @@ class BearerAuthMiddleware:
# Single ApiKey lookup. If the row exists, branch on its type:
# agent token → resolve to Agent; registration token → pass through.
# If no row exists, fall through to OIDC (where applicable).
- api_key, agent = await self._resolve_api_key(token)
+ try:
+ api_key, agent = await self._resolve_api_key(token)
+ except ApiKeyExpired as exc:
+ logger.warning(
+ "Refused API key %s (%s): it expired at %s",
+ exc.api_key.id,
+ exc.api_key.type,
+ exc.api_key.expires_at,
+ )
+ await _unauthorized(scope, receive, send, "API key expired")
+ return
if agent is None and api_key is None and self._oidc_validator is not None:
agent = await self._try_oidc(token)
@@ -491,11 +510,15 @@ class BearerAuthMiddleware:
A resolved agent is memoised for a few seconds (see
:class:`ApiKeyCache`); everything else — an unknown token, a
registration token, an agent key with no agent — always reads the
- database.
+ database. A key past its ``expires_at`` raises :class:`ApiKeyExpired`,
+ whether it was read or remembered.
"""
token_hash = hashlib.sha256(token.encode()).hexdigest()
cached = self._api_key_cache.get(token_hash)
if cached is not None:
+ if cached[0].expired(datetime.now(UTC)):
+ self._api_key_cache.invalidate(token_hash)
+ raise ApiKeyExpired(cached[0])
return cached
# Two steps, because a credential's tenant has to be known before its
@@ -521,6 +544,8 @@ class BearerAuthMiddleware:
if found is None:
return None, None
api_key, agent = found
+ if api_key.expired(datetime.now(UTC)):
+ raise ApiKeyExpired(api_key)
if api_key.type != "agent":
agent = None
session.expunge_all()
diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.py
index 2257856d7..da234f549 100644
--- a/core/switch_core/db/models.py
+++ b/core/switch_core/db/models.py
@@ -483,6 +483,15 @@ class ApiKey(TenantScoped, Base):
created_at: Mapped[str] = mapped_column(
DateTime(timezone=True), server_default=func.now(), nullable=False
)
+ # NULL never expires: keys from before expiry existed, agent keys,
+ # the bootstrap key, controller credentials, and a key its owner asked
+ # to keep.
+ expires_at: Mapped[datetime | None] = mapped_column(
+ DateTime(timezone=True), nullable=True
+ )
+
+ def expired(self, now: datetime) -> bool:
+ return self.expires_at is not None and self.expires_at <= now
class ProviderConnection(TenantScoped, Base):
diff --git a/core/switch_core/gateway/api_keys.py b/core/switch_core/gateway/api_keys.py
index 29eedc2a8..e739f8211 100644
--- a/core/switch_core/gateway/api_keys.py
+++ b/core/switch_core/gateway/api_keys.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import hashlib
import logging
import secrets
+from datetime import UTC, datetime, timedelta
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException
@@ -64,6 +65,7 @@ async def list_api_keys(
type=k.type,
key_prefix=k.key_hash[:12],
created_at=str(k.created_at),
+ expires_at=k.expires_at,
)
for k in keys
]
@@ -79,6 +81,11 @@ async def create_api_key(
) -> CreateApiKeyResponse:
plaintext = secrets.token_urlsafe(32)
key_hash = hashlib.sha256(plaintext.encode()).hexdigest()
+ expires_at = (
+ None
+ if req.expires_in_days == "never"
+ else datetime.now(UTC) + timedelta(days=req.expires_in_days)
+ )
key = ApiKey(
user_id=user.id,
@@ -86,6 +93,7 @@ async def create_api_key(
encrypted_key=config.keyring.encrypt(plaintext),
label=req.label,
type="registration",
+ expires_at=expires_at,
)
await api_key_store.create(session, key)
await record_audit_event(
@@ -95,7 +103,11 @@ async def create_api_key(
action=AuditAction.API_KEY_CREATED,
target_type="api_key",
target_id=key.id,
- details={"label": key.label, "type": key.type},
+ details={
+ "label": key.label,
+ "type": key.type,
+ "expires_at": None if expires_at is None else expires_at.isoformat(),
+ },
)
await session.commit()
@@ -108,6 +120,7 @@ async def create_api_key(
label=key.label,
key=plaintext,
created_at=str(key.created_at),
+ expires_at=key.expires_at,
)
diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.py
index a9c41a128..4d30a2419 100644
--- a/core/switch_core/gateway/schemas.py
+++ b/core/switch_core/gateway/schemas.py
@@ -601,8 +601,22 @@ class RegisterAgentResponse(BaseModel):
# ── API Keys ────────────────────────────────────────────────────────────────
+API_KEY_DEFAULT_LIFETIME_DAYS = 90
+API_KEY_MAX_LIFETIME_DAYS = 365
+
+
class CreateApiKeyRequest(BaseModel):
label: str
+ expires_in_days: (
+ Annotated[int, Field(ge=1, le=API_KEY_MAX_LIFETIME_DAYS)] | Literal["never"]
+ ) = Field(
+ default=API_KEY_DEFAULT_LIFETIME_DAYS,
+ description=(
+ "Days until the key stops working, at most "
+ f"{API_KEY_MAX_LIFETIME_DAYS}, or `never` for a key that does not "
+ "expire."
+ ),
+ )
class ApiKeyDetail(BaseModel):
@@ -611,6 +625,7 @@ class ApiKeyDetail(BaseModel):
type: str
key_prefix: str
created_at: str
+ expires_at: datetime | None
class CreateApiKeyResponse(BaseModel):
@@ -618,6 +633,7 @@ class CreateApiKeyResponse(BaseModel):
label: str
key: str
created_at: str
+ expires_at: datetime | None
class RevealKeyResponse(BaseModel):
diff --git a/core/switch_core/migrations/versions/f3a8d1c6b927_api_key_expiry.py b/core/switch_core/migrations/versions/f3a8d1c6b927_api_key_expiry.py
new file mode 100644
index 000000000..e51b4b6ee
--- /dev/null
+++ b/core/switch_core/migrations/versions/f3a8d1c6b927_api_key_expiry.py
@@ -0,0 +1,35 @@
+"""api key expiry: ``api_keys.expires_at``
+
+A key whose ``expires_at`` has passed is refused wherever keys are checked.
+NULL never expires, which is what every existing key keeps.
+
+Expand only: a process from before this revision neither writes nor reads the
+column, so the keys it mints never expire, as before.
+
+Revision ID: f3a8d1c6b927
+Revises: c7b2e9f4a1d6
+Create Date: 2026-11-06 00:00:00.000000
+
+"""
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+revision: str = "f3a8d1c6b927"
+down_revision: str | None = "c7b2e9f4a1d6"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+expand_only: bool = True
+
+
+def upgrade() -> None:
+ op.add_column(
+ "api_keys",
+ sa.Column("expires_at", sa.DateTime(timezone=True), nullable=True),
+ )
+
+
+def downgrade() -> None:
+ op.drop_column("api_keys", "expires_at")
diff --git a/core/tests/switch_core/bridges/agent/test_api_key_expiry.py b/core/tests/switch_core/bridges/agent/test_api_key_expiry.py
new file mode 100644
index 000000000..64410a544
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/test_api_key_expiry.py
@@ -0,0 +1,177 @@
+"""A key past its `api_keys.expires_at` is refused wherever keys are checked:
+the bearer middleware, whether the key is read or remembered in the
+`ApiKeyCache`, and the registration endpoint's own check."""
+
+from __future__ import annotations
+
+import hashlib
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import pytest
+from fastapi import HTTPException
+from sqlalchemy import update
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.bridges.agent import auth as bearer_auth
+from switch_core.bridges.agent.api.handlers import _resolve_registration_user_id
+from switch_core.bridges.agent.api_key_cache import ApiKeyCache
+from switch_core.bridges.agent.auth import BearerAuthMiddleware
+from switch_core.db.models import ApiKey
+from switch_core.db.stores.agent_store import AgentStore
+from switch_core.db.stores.api_key_store import ApiKeyStore
+from tests.switch_core.bridges.agent.test_bearer_auth_tenant_binding import (
+ _seed_agent,
+ _seed_registration_key,
+)
+
+TENANT = "api-key-expiry-tenant"
+_PAST = datetime.now(UTC) - timedelta(minutes=1)
+
+
+def _hash(token: str) -> str:
+ return hashlib.sha256(token.encode()).hexdigest()
+
+
+async def _expire(
+ session_factory: async_sessionmaker[AsyncSession], token: str, at: datetime
+) -> None:
+ async with session_factory() as session:
+ await session.execute(
+ update(ApiKey).where(ApiKey.key_hash == _hash(token)).values(expires_at=at)
+ )
+ await session.commit()
+
+
+def _middleware(
+ session_factory: async_sessionmaker[AsyncSession], cache: ApiKeyCache
+) -> tuple[BearerAuthMiddleware, list[str]]:
+ reached: list[str] = []
+
+ async def _app(scope: Any, receive: Any, send: Any) -> None:
+ reached.append(scope["path"])
+
+ return (
+ BearerAuthMiddleware(
+ _app,
+ agent_store=AgentStore(),
+ api_key_store=ApiKeyStore(),
+ api_key_cache=cache,
+ session_factory=session_factory,
+ ),
+ reached,
+ )
+
+
+async def _dispatch(
+ mw: BearerAuthMiddleware, token: str, path: str = "/agents/whatever"
+) -> list[dict]:
+ async def receive() -> dict:
+ return {"type": "http.request"}
+
+ sent: list[dict] = []
+
+ async def send(message: dict) -> None:
+ sent.append(message)
+
+ await mw(
+ {
+ "type": "http",
+ "path": path,
+ "headers": [(b"authorization", f"Bearer {token}".encode())],
+ },
+ receive,
+ send,
+ )
+ return sent
+
+
+def _refusal(sent: list[dict]) -> tuple[int, bytes]:
+ return sent[0]["status"], sent[1]["body"]
+
+
+async def test_an_expired_agent_key_is_refused(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ await _seed_agent(session_factory, "agent-tok", TENANT)
+ await _expire(session_factory, "agent-tok", _PAST)
+ cache = ApiKeyCache(ttl_seconds=5, max_entries=8)
+ mw, reached = _middleware(session_factory, cache)
+
+ sent = await _dispatch(mw, "agent-tok")
+
+ assert reached == []
+ assert _refusal(sent) == (401, b"API key expired")
+ assert cache.get(_hash("agent-tok")) is None
+
+
+async def test_a_remembered_key_is_refused_once_it_expires(
+ session_factory: async_sessionmaker[AsyncSession],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ await _seed_agent(session_factory, "agent-tok", TENANT)
+ expiry = datetime.now(UTC) + timedelta(hours=1)
+ await _expire(session_factory, "agent-tok", expiry)
+ cache = ApiKeyCache(ttl_seconds=5, max_entries=8)
+ mw, reached = _middleware(session_factory, cache)
+ assert await _dispatch(mw, "agent-tok") == []
+ assert cache.get(_hash("agent-tok")) is not None
+
+ class _Later(datetime):
+ @classmethod
+ def now(cls, tz: Any = None) -> datetime: # type: ignore[override]
+ return expiry + timedelta(seconds=1)
+
+ monkeypatch.setattr(bearer_auth, "datetime", _Later)
+ sent = await _dispatch(mw, "agent-tok")
+
+ assert reached == ["/agents/whatever"]
+ assert _refusal(sent) == (401, b"API key expired")
+ assert cache.get(_hash("agent-tok")) is None
+
+
+async def test_a_key_before_its_expiry_still_works(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ await _seed_agent(session_factory, "agent-tok", TENANT)
+ await _expire(session_factory, "agent-tok", datetime.now(UTC) + timedelta(days=1))
+ mw, reached = _middleware(
+ session_factory, ApiKeyCache(ttl_seconds=0, max_entries=8)
+ )
+
+ assert await _dispatch(mw, "agent-tok") == []
+ assert reached == ["/agents/whatever"]
+
+
+async def test_an_expired_registration_key_is_refused_at_the_door(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ await _seed_registration_key(session_factory, "reg-tok", TENANT)
+ await _expire(session_factory, "reg-tok", _PAST)
+ mw, reached = _middleware(
+ session_factory, ApiKeyCache(ttl_seconds=5, max_entries=8)
+ )
+
+ sent = await _dispatch(mw, "reg-tok", path="/agents/register")
+
+ assert reached == []
+ assert _refusal(sent) == (401, b"API key expired")
+
+
+async def test_the_registration_endpoint_refuses_an_expired_key(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ await _seed_registration_key(session_factory, "reg-tok", TENANT)
+ await _expire(session_factory, "reg-tok", _PAST)
+
+ async with session_factory() as session:
+ with pytest.raises(HTTPException) as refused:
+ await _resolve_registration_user_id(
+ "Bearer reg-tok",
+ session,
+ ApiKeyStore(),
+ protocol=None, # type: ignore[arg-type]
+ )
+
+ assert refused.value.status_code == 401
+ assert refused.value.detail == "Registration token has expired"
diff --git a/core/tests/switch_core/gateway/test_api_key_expiry.py b/core/tests/switch_core/gateway/test_api_key_expiry.py
new file mode 100644
index 000000000..11aa82b25
--- /dev/null
+++ b/core/tests/switch_core/gateway/test_api_key_expiry.py
@@ -0,0 +1,133 @@
+"""A registration key made in the dashboard expires: after 90 days unless its
+owner chooses up to a year, or explicitly never."""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+
+import httpx
+import pytest
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.db.models import ApiKey, AuditEvent
+from tests.switch_core.gateway.test_api_keys_hash_only import _app
+from tests.switch_core.management.harness import add_member, cookies_for
+
+
+async def _create(
+ session_factory: async_sessionmaker[AsyncSession], body: dict
+) -> httpx.Response:
+ owner = await add_member(session_factory, "keymaker")
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=_app(session_factory)),
+ base_url="http://test",
+ cookies=cookies_for(owner),
+ ) as client:
+ return await client.post("/api-keys", json=body)
+
+
+async def _stored_expiry(
+ session_factory: async_sessionmaker[AsyncSession], key_id: str
+) -> datetime | None:
+ async with session_factory() as session:
+ return await session.scalar(
+ select(ApiKey.expires_at).where(ApiKey.id == key_id)
+ )
+
+
+ ("body", "days"),
+ [
+ ({"label": "default"}, 90),
+ ({"label": "a year", "expires_in_days": 365}, 365),
+ ({"label": "a day", "expires_in_days": 1}, 1),
+ ],
+)
+async def test_a_new_key_expires_after_its_lifetime(
+ session_factory: async_sessionmaker[AsyncSession], body: dict, days: int
+) -> None:
+ before = datetime.now(UTC)
+ created = await _create(session_factory, body)
+
+ assert created.status_code == 200, created.text
+ stored = await _stored_expiry(session_factory, created.json()["id"])
+ assert stored is not None
+ assert (
+ before + timedelta(days=days)
+ <= stored
+ <= datetime.now(UTC) + timedelta(days=days)
+ )
+ assert datetime.fromisoformat(created.json()["expires_at"]) == stored
+
+
+async def test_a_key_can_be_made_to_never_expire(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ created = await _create(
+ session_factory, {"label": "forever", "expires_in_days": "never"}
+ )
+
+ assert created.status_code == 200, created.text
+ assert created.json()["expires_at"] is None
+ assert await _stored_expiry(session_factory, created.json()["id"]) is None
+ async with session_factory() as session:
+ details = await session.scalar(
+ select(AuditEvent.details).where(
+ AuditEvent.target_id == created.json()["id"]
+ )
+ )
+ assert details == {"label": "forever", "type": "registration", "expires_at": None}
+
+
[email protected]("lifetime", [0, -1, 366, "forever", None])
+async def test_a_lifetime_outside_a_year_is_refused(
+ session_factory: async_sessionmaker[AsyncSession], lifetime: object
+) -> None:
+ created = await _create(
+ session_factory, {"label": "too long", "expires_in_days": lifetime}
+ )
+
+ assert created.status_code == 422, created.text
+ async with session_factory() as session:
+ assert await session.scalar(select(ApiKey.id)) is None
+
+
+async def test_the_list_shows_each_keys_expiry(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ owner = await add_member(session_factory, "lister")
+ expiry = datetime(2027, 2, 4, 12, tzinfo=UTC)
+ async with session_factory() as session:
+ session.add_all(
+ [
+ ApiKey(
+ user_id=owner.id,
+ key_hash="expiring",
+ encrypted_key="enc",
+ label="expiring",
+ type="registration",
+ expires_at=expiry,
+ ),
+ ApiKey(
+ user_id=owner.id,
+ key_hash="lasting",
+ encrypted_key="enc",
+ label="lasting",
+ type="agent",
+ ),
+ ]
+ )
+ await session.commit()
+
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=_app(session_factory)),
+ base_url="http://test",
+ cookies=cookies_for(owner),
+ ) as client:
+ listed = await client.get("/api-keys")
+
+ assert listed.status_code == 200, listed.text
+ expiries = {key["label"]: key["expires_at"] for key in listed.json()}
+ assert expiries["lasting"] is None
+ assert datetime.fromisoformat(expiries["expiring"]) == expiry
diff --git a/gateway/src/data/api.test.ts b/gateway/src/data/api.test.ts
index f9e22925c..17aa12a62 100644
--- a/gateway/src/data/api.test.ts
+++ b/gateway/src/data/api.test.ts
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import {
ApiError,
addBridgeToTeam,
+ createApiKey,
createUser,
errorText,
fetchSession,
@@ -240,3 +241,23 @@ describe("signOutEverywhere", () => {
await expect(signOutEverywhere()).rejects.toBeInstanceOf(ApiError);
});
});
+
+describe("createApiKey", () => {
+ afterEach(() => vi.unstubAllGlobals());
+
+ it.each([[90], [365], ["never" as const]])("sends the chosen lifetime %s", async (lifetime) => {
+ const fetchMock = vi.fn(
+ async () =>
+ new Response(
+ JSON.stringify({ id: "k", label: "l", key: "s", created_at: "c", expires_at: null }),
+ { status: 200 },
+ ),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ await createApiKey("l", lifetime);
+
+ const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
+ expect(JSON.parse(init.body as string)).toEqual({ label: "l", expires_in_days: lifetime });
+ });
+});
diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.ts
index 3cd9bca14..26ab7cc8e 100644
--- a/gateway/src/data/api.ts
+++ b/gateway/src/data/api.ts
@@ -764,6 +764,8 @@ export interface ApiKeyDetail {
type: string;
key_prefix: string;
created_at: string;
+ /** `null` for a key that never expires. */
+ expires_at: string | null;
}
export interface CreateApiKeyResult {
@@ -771,18 +773,25 @@ export interface CreateApiKeyResult {
label: string;
key: string;
created_at: string;
+ expires_at: string | null;
}
+/** Days until a new key stops working, or `"never"`. The server allows 1–365. */
+export type ApiKeyLifetime = number | "never";
+
export async function fetchApiKeys(): Promise<ApiKeyDetail[] | null> {
return fetchJson<ApiKeyDetail[]>("/api-keys");
}
-export async function createApiKey(label: string): Promise<CreateApiKeyResult> {
+export async function createApiKey(
+ label: string,
+ expiresInDays: ApiKeyLifetime,
+): Promise<CreateApiKeyResult> {
const res = await fetch(`${BASE}/api-keys`, {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
- body: JSON.stringify({ label }),
+ body: JSON.stringify({ label, expires_in_days: expiresInDays }),
});
if (!res.ok) {
const body = await res.json().catch(() => null);
diff --git a/gateway/src/pages/registration-keys/CreateKeyDialog.tsx b/gateway/src/pages/registration-keys/CreateKeyDialog.tsx
index bd7baf206..85124abd3 100644
--- a/gateway/src/pages/registration-keys/CreateKeyDialog.tsx
+++ b/gateway/src/pages/registration-keys/CreateKeyDialog.tsx
@@ -9,11 +9,19 @@ import {
DialogTitle,
IconButton,
InputAdornment,
+ MenuItem,
Stack,
TextField,
} from "@mui/material";
import { useCallback, useState } from "react";
-import { createApiKey } from "../../data/api";
+import { type ApiKeyLifetime, createApiKey } from "../../data/api";
+import { formatKeyExpiry } from "./keyExpiry";
+
+const LIFETIMES: { value: ApiKeyLifetime; label: string }[] = [
+ { value: 90, label: "90 days" },
+ { value: 365, label: "1 year" },
+ { value: "never", label: "Never" },
+];
interface Props {
open: boolean;
@@ -23,13 +31,17 @@ interface Props {
export default function CreateKeyDialog({ open, onClose, onCreated }: Props) {
const [label, setLabel] = useState("");
+ const [lifetime, setLifetime] = useState<ApiKeyLifetime>(90);
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
- const [result, setResult] = useState<{ key: string } | null>(null);
+ const [result, setResult] = useState<{ key: string; expiresAt: string | null } | null>(
+ null,
+ );
const [copied, setCopied] = useState(false);
const reset = useCallback(() => {
setLabel("");
+ setLifetime(90);
setSubmitting(false);
setError(null);
setResult(null);
@@ -47,14 +59,14 @@ export default function CreateKeyDialog({ open, onClose, onCreated }: Props) {
setSubmitting(true);
setError(null);
try {
- const res = await createApiKey(label);
- setResult({ key: res.key });
+ const res = await createApiKey(label, lifetime);
+ setResult({ key: res.key, expiresAt: res.expires_at });
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to create key.");
} finally {
setSubmitting(false);
}
- }, [label]);
+ }, [label, lifetime]);
const handleCopy = useCallback(() => {
if (!result) return;
@@ -101,7 +113,13 @@ export default function CreateKeyDialog({ open, onClose, onCreated }: Props) {
),
},
}}
- helperText={copied ? "Copied!" : undefined}
+ helperText={
+ copied
+ ? "Copied!"
+ : result.expiresAt === null
+ ? "This key does not expire."
+ : `Expires ${formatKeyExpiry(result.expiresAt, new Date())}.`
+ }
/>
</>
) : (
@@ -115,6 +133,28 @@ export default function CreateKeyDialog({ open, onClose, onCreated }: Props) {
required
placeholder="e.g. My ADK connector"
/>
+ <TextField
+ select
+ label="Expires after"
+ value={String(lifetime)}
+ onChange={(e) =>
+ setLifetime(e.target.value === "never" ? "never" : Number(e.target.value))
+ }
+ fullWidth
+ >
+ {LIFETIMES.map((option) => (
+ <MenuItem key={String(option.value)} value={String(option.value)}>
+ {option.label}
+ </MenuItem>
+ ))}
+ </TextField>
+ {lifetime === "never" && (
+ <Alert severity="warning">
+ A key that never expires keeps working until you delete it,
+ including if it leaks. Choose an expiry unless something
+ depends on this key and cannot be given a new one.
+ </Alert>
+ )}
</>
)}
</Stack>
diff --git a/gateway/src/pages/registration-keys/RegistrationKeysPage.tsx b/gateway/src/pages/registration-keys/RegistrationKeysPage.tsx
index 8d5bc07c2..6a25e9baa 100644
--- a/gateway/src/pages/registration-keys/RegistrationKeysPage.tsx
+++ b/gateway/src/pages/registration-keys/RegistrationKeysPage.tsx
@@ -26,6 +26,7 @@ import { type ApiKeyDetail, deleteApiKey, revealApiKey } from "../../data/api";
import { useApiKeys } from "../../data/hooks";
import { MONO_SX, formatDate } from "../../theme/hootFormat";
import CreateKeyDialog from "./CreateKeyDialog";
+import { formatKeyExpiry } from "./keyExpiry";
export default function RegistrationKeysPage() {
const { data: keys, loading, refetch } = useApiKeys();
@@ -104,6 +105,13 @@ export default function RegistrationKeysPage() {
minWidth: 140,
valueFormatter: (value) => formatDate(value as string),
},
+ {
+ field: "expires_at",
+ headerName: "Expires",
+ flex: 1,
+ minWidth: 140,
+ valueFormatter: (value) => formatKeyExpiry(value as string | null, new Date()),
+ },
{
field: "actions",
headerName: "",
@@ -151,6 +159,13 @@ export default function RegistrationKeysPage() {
minWidth: 140,
valueFormatter: (value) => formatDate(value as string),
},
+ {
+ field: "expires_at",
+ headerName: "Expires",
+ flex: 1,
+ minWidth: 140,
+ valueFormatter: (value) => formatKeyExpiry(value as string | null, new Date()),
+ },
{
field: "actions",
headerName: "",
diff --git a/gateway/src/pages/registration-keys/keyExpiry.test.ts b/gateway/src/pages/registration-keys/keyExpiry.test.ts
new file mode 100644
index 000000000..5b1aec3e0
--- /dev/null
+++ b/gateway/src/pages/registration-keys/keyExpiry.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from "vitest";
+import { formatKeyExpiry } from "./keyExpiry";
+
+const NOW = new Date("2026-11-06T12:00:00Z");
+
+describe("formatKeyExpiry", () => {
+ it("says a key without an expiry never expires", () => {
+ expect(formatKeyExpiry(null, NOW)).toBe("No expiry");
+ });
+
+ it("shows the day a key expires", () => {
+ expect(formatKeyExpiry("2027-02-04T12:00:00+00:00", NOW)).toBe("2027-02-04");
+ });
+
+ it("marks a key that has already expired", () => {
+ expect(formatKeyExpiry("2026-11-01T12:00:00+00:00", NOW)).toBe("Expired 2026-11-01");
+ });
+});
diff --git a/gateway/src/pages/registration-keys/keyExpiry.ts b/gateway/src/pages/registration-keys/keyExpiry.ts
new file mode 100644
index 000000000..e4ce82d92
--- /dev/null
+++ b/gateway/src/pages/registration-keys/keyExpiry.ts
@@ -0,0 +1,8 @@
+import { formatDate } from "../../theme/hootFormat";
+
+/** How the key list shows when a key stops working. */
+export function formatKeyExpiry(expiresAt: string | null, now: Date): string {
+ if (expiresAt === null) return "No expiry";
+ const formatted = formatDate(expiresAt);
+ return new Date(expiresAt) <= now ? `Expired ${formatted}` : formatted;
+}