Files
rengine/shared/services/api_key/async_api_key.py
T
Yogesh OjhaandClaude Opus 5 66c7501558 fix(ui): the interface obeyed none of the style rules the AI prompt enforces
reports/narrate/ai.py instructs the model: no marketing language, no hedging,
no filler, never an em dash, never a rhetorical question. The product broke all
three. There was a house style in this repository and it applied only to the
machine.

The activity feed printed Python dictionary keys. stage_count_summary rendered
key.replace('_', ' ') over StageResult.counts, so a live scan read "12 waf,
340 checked", "88 ptr", "412 http assets", "56 alive". _STAGE_COUNT_LABELS now
covers all 31 count keys with singular and plural, and an unlabelled key is
dropped rather than printed raw, so a new stage can never leak one again.

Errors had three registers: "Failed to X" (121), "Could not X" (28), and
"Couldn't X - try again" (6), alongside a passive form the result tables already
used. All of it is now "<Subject> could not be <verbed>", which names the thing
that failed before the failure. The rate limiter reads the key's TTL and says
how long to wait instead of "Please wait a moment".

Onboarding fired confetti and a party popper, opened with "Let's get your
instance set up", and asked an operator to tick "I've saved my backup codes".
confetti.ts is deleted.

Casing was split down the middle: the sidebar group read "Attack surface" while
the item under it read "Scheduled Scans", and page headings restated the nav in
Title Case. Sentence case throughout now, including SURFACE_LABELS, so the
backend and its mirror agree.

The KEV sentence in generated reports claimed a listing "means working exploit
code is public". It means exploitation has been observed in the wild. That one
printed under a client's letterhead.

Also: 18 "This action cannot be undone" in three spellings removed in favour of
the concrete consequence; every em dash, contraction and "Please" out of user
copy; surface vocabulary applied to alerts and the notification settings, not
only the result tables; the "X, not Y" antithesis thinned from ten uses to the
two that carry a real distinction; advice copy ("fix first", "worth a look",
"Add to renewal watchlist", which named a feature that does not exist) reduced
to the fact.

Nine rules are written up in the audit linked below and hold for new copy.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LM9TbCGhGb4s6nag6PsuaT
2026-09-06 18:26:29 +05:30

207 lines
7.4 KiB
Python

import uuid
from fastapi import HTTPException, status
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from sqlmodel import select
from shared.definitions.mode_features import provider_allowed
from shared.enums.api_key import APIProvider
from shared.enums.instance import InstanceMode
from shared.models.api_key import (
API_PROVIDER_META,
APIKey,
APIKeyCreate,
APIKeyRead,
APIKeyUpdate,
ProviderInfo,
)
from shared.models.instance_settings import InstanceSettings
from shared.utils.crypto import encrypt_secret, try_decrypt
from shared.utils.datetime import utc_now
class APIKeyService:
def __init__(self, session: AsyncSession):
self.session = session
async def _instance_mode(self) -> str:
result = await self.session.execute(
select(InstanceSettings.mode).where(
InstanceSettings.singleton_key == "instance"
)
)
return result.scalar_one_or_none() or InstanceMode.BUG_BOUNTY.value
def _mask_key(self, key_value: str) -> str:
if len(key_value) <= 4: # noqa: PLR2004
return "****"
return f"****{key_value[-4:]}"
def _to_read(self, api_key: APIKey) -> APIKeyRead:
return APIKeyRead(
id=api_key.id,
provider=api_key.provider,
key_value_masked=self._mask_key(
try_decrypt(api_key.key_value) or api_key.key_value
),
key_meta=api_key.key_meta,
is_enabled=api_key.is_enabled,
usage_counter=api_key.usage_counter,
last_used_at=api_key.last_used_at,
created_at=api_key.created_at,
updated_at=api_key.updated_at,
meta=API_PROVIDER_META.get(api_key.provider, {}),
)
async def list_keys(self) -> list[APIKeyRead]:
result = await self.session.execute(select(APIKey).order_by(APIKey.provider))
return [self._to_read(k) for k in result.scalars().all()]
async def list_providers(self) -> list[ProviderInfo]:
result = await self.session.execute(select(APIKey))
configured = {k.provider: k for k in result.scalars().all()}
providers = []
for provider, meta in API_PROVIDER_META.items():
key = configured.get(provider)
providers.append(
ProviderInfo(
provider=provider,
name=meta["name"],
description=meta["description"],
docs_url=meta["docs_url"],
icon=meta.get("icon", "package"),
color=meta.get("color", "#64748b"),
requires_username=meta.get("requires_username", False),
configured=key is not None,
is_enabled=key.is_enabled if key else False,
)
)
mode = await self._instance_mode()
return [p for p in providers if provider_allowed(mode, p.provider.value)]
async def create_key(self, data: APIKeyCreate) -> APIKeyRead:
mode = await self._instance_mode()
if not provider_allowed(mode, data.provider.value):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=(
f"The {data.provider.value} integration is only available in "
"Bug bounty mode."
),
)
if API_PROVIDER_META.get(data.provider, {}).get("requires_username"):
username = (data.key_meta or {}).get("username")
if not username or not str(username).strip():
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"The {data.provider.value} integration requires a username",
)
existing = await self.session.execute(
select(APIKey).where(
APIKey.provider == data.provider,
)
)
if existing.scalar_one_or_none():
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=f"API key for {data.provider.value} already exists in this project",
)
api_key = APIKey(
provider=data.provider,
key_value=encrypt_secret(data.key_value),
key_meta=data.key_meta,
)
self.session.add(api_key)
try:
await self.session.commit()
except IntegrityError as e:
await self.session.rollback()
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=f"API key for {data.provider.value} already exists in this project",
) from e
await self.session.refresh(api_key)
return self._to_read(api_key)
async def update_key(self, key_id: str, data: APIKeyUpdate) -> APIKeyRead:
api_key = await self._get_key_or_404(key_id)
if data.key_value is not None:
api_key.key_value = encrypt_secret(data.key_value)
if data.is_enabled is not None:
api_key.is_enabled = data.is_enabled
if data.key_meta is not None:
api_key.key_meta = data.key_meta
api_key.updated_at = utc_now()
self.session.add(api_key)
await self.session.commit()
await self.session.refresh(api_key)
return self._to_read(api_key)
async def delete_key(self, key_id: str) -> None:
api_key = await self._get_key_or_404(key_id)
await self.session.delete(api_key)
await self.session.commit()
async def get_key_for_provider(self, provider: APIProvider) -> str | None:
result = await self.session.execute(
select(APIKey).where(
APIKey.provider == provider,
APIKey.is_enabled == True, # noqa: E712
)
)
api_key = result.scalar_one_or_none()
if not api_key:
return None
return try_decrypt(api_key.key_value) or api_key.key_value
async def increment_usage(self, provider: APIProvider) -> None:
result = await self.session.execute(
select(APIKey).where(
APIKey.provider == provider,
)
)
api_key = result.scalar_one_or_none()
if api_key:
api_key.usage_counter += 1
api_key.last_used_at = utc_now()
self.session.add(api_key)
await self.session.commit()
async def disable_key(self, provider: APIProvider) -> None:
result = await self.session.execute(
select(APIKey).where(
APIKey.provider == provider,
)
)
api_key = result.scalar_one_or_none()
if api_key:
api_key.is_enabled = False
api_key.updated_at = utc_now()
self.session.add(api_key)
await self.session.commit()
async def _get_key_or_404(self, key_id: str) -> APIKey:
try:
uuid_id = uuid.UUID(key_id)
except ValueError as e:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Invalid key ID",
) from e
result = await self.session.execute(select(APIKey).where(APIKey.id == uuid_id))
api_key = result.scalar_one_or_none()
if not api_key:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="API key not found",
)
return api_key