126 lines
4.8 KiB
Python
126 lines
4.8 KiB
Python
"""Operator controls for the stove API. All routes inherit the admin dependency."""
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
from fastapi import APIRouter, Depends, HTTPException, Request
|
|
from pydantic import BaseModel, Field, field_validator
|
|
|
|
import db
|
|
import stove_cache
|
|
import stove_guard
|
|
import stove_history
|
|
import stove_keys
|
|
from admin_auth import require_admin
|
|
|
|
router = APIRouter(prefix="/api/admin/v2/stove-api", tags=["stove-api-admin"],
|
|
dependencies=[Depends(require_admin)])
|
|
|
|
|
|
class NewKey(BaseModel):
|
|
name: str = Field(min_length=1, max_length=100)
|
|
allowed_ip: str
|
|
note: str = Field(default="", max_length=500)
|
|
limit_day: int = Field(default=1000, ge=0, le=100000)
|
|
ai_budget_rub_day: float = Field(default=300, ge=0, le=10000)
|
|
|
|
@field_validator("allowed_ip")
|
|
@classmethod
|
|
def valid_ip(cls, value: str) -> str:
|
|
return stove_keys.normalize_allowed_ip(value)
|
|
|
|
|
|
class AllowedIP(BaseModel):
|
|
allowed_ip: str
|
|
|
|
@field_validator("allowed_ip")
|
|
@classmethod
|
|
def valid_ip(cls, value: str) -> str:
|
|
return stove_keys.normalize_allowed_ip(value)
|
|
|
|
|
|
class Limits(BaseModel):
|
|
limit_day: int | None = Field(default=None, ge=0, le=100000)
|
|
ai_budget_rub_day: float | None = Field(default=None, ge=0, le=10000)
|
|
|
|
|
|
def _audit(request: Request, action: str, detail: str):
|
|
db.log_action(require_admin(request), action, request.method, str(request.url.path),
|
|
detail=detail, ip=request.client.host if request.client else None, status_code=200)
|
|
|
|
|
|
@router.get("")
|
|
async def overview():
|
|
keys, bad = await asyncio.gather(asyncio.to_thread(stove_keys.list_keys),
|
|
asyncio.to_thread(stove_guard.bad_key_stats))
|
|
return {"enabled": await asyncio.to_thread(stove_keys.api_enabled),
|
|
"keys": keys, "invalid_keys": bad,
|
|
"history": await asyncio.to_thread(stove_history.list_requests, limit=25)}
|
|
|
|
|
|
@router.post("/keys")
|
|
async def create_key(request: Request, body: NewKey):
|
|
made = await asyncio.to_thread(stove_keys.create_key, name=body.name, note=body.note,
|
|
allowed_ip=body.allowed_ip,
|
|
limit_day=body.limit_day, ai_budget_rub_day=body.ai_budget_rub_day)
|
|
await asyncio.to_thread(_audit, request, "stove_api.key_create", f"id={made['id']}")
|
|
return made # secret appears only once
|
|
|
|
|
|
@router.patch("/keys/{key_id}/allowed-ip")
|
|
async def allowed_ip(key_id: int, request: Request, body: AllowedIP):
|
|
made = await asyncio.to_thread(stove_keys.set_allowed_ip, key_id, body.allowed_ip)
|
|
if not made:
|
|
raise HTTPException(404, "Ключ не найден или отозван")
|
|
await asyncio.to_thread(_audit, request, "stove_api.key_allowed_ip", f"id={key_id},allowed_ip={body.allowed_ip}")
|
|
return made
|
|
|
|
|
|
@router.post("/keys/{key_id}/disabled")
|
|
async def disabled(key_id: int, request: Request, disabled: bool = True):
|
|
ok = await asyncio.to_thread(stove_keys.set_disabled, key_id, disabled)
|
|
if not ok:
|
|
raise HTTPException(404, "Ключ не найден")
|
|
await asyncio.to_thread(_audit, request, "stove_api.key_disabled", f"id={key_id},disabled={disabled}")
|
|
return {"ok": True}
|
|
|
|
|
|
@router.post("/keys/{key_id}/revoke")
|
|
async def revoke(key_id: int, request: Request):
|
|
ok = await asyncio.to_thread(stove_keys.revoke_key, key_id)
|
|
if not ok:
|
|
raise HTTPException(404, "Ключ не найден")
|
|
await asyncio.to_thread(_audit, request, "stove_api.key_revoke", f"id={key_id}")
|
|
return {"ok": True}
|
|
|
|
|
|
@router.patch("/keys/{key_id}/limits")
|
|
async def limits(key_id: int, request: Request, body: Limits):
|
|
if body.limit_day is None and body.ai_budget_rub_day is None:
|
|
raise HTTPException(400, "Укажите хотя бы один лимит")
|
|
made = await asyncio.to_thread(stove_keys.set_limit, key_id, limit_day=body.limit_day,
|
|
ai_budget_rub_day=body.ai_budget_rub_day)
|
|
if not made:
|
|
raise HTTPException(404, "Ключ не найден")
|
|
await asyncio.to_thread(_audit, request, "stove_api.key_limits", f"id={key_id}")
|
|
return made
|
|
|
|
|
|
@router.post("/enabled")
|
|
async def enabled(request: Request, enabled: bool):
|
|
await asyncio.to_thread(stove_keys.set_api_enabled, enabled)
|
|
await asyncio.to_thread(_audit, request, "stove_api.switch", f"enabled={enabled}")
|
|
return {"enabled": enabled}
|
|
|
|
|
|
@router.get("/requests")
|
|
async def requests(key_id: int | None = None, limit: int = 50, offset: int = 0):
|
|
return await asyncio.to_thread(stove_history.list_requests, key_id, limit=limit, offset=offset)
|
|
|
|
|
|
@router.get("/requests/{request_id}")
|
|
async def request_detail(request_id: str):
|
|
item = await asyncio.to_thread(stove_history.get_request, request_id)
|
|
if item is None:
|
|
raise HTTPException(404, "Запрос не найден")
|
|
return item
|