Bind stove API keys to configured client IP
This commit is contained in:
+26
-1
@@ -3,7 +3,7 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
import db
|
||||
import stove_cache
|
||||
@@ -18,10 +18,25 @@ router = APIRouter(prefix="/api/admin/v2/stove-api", tags=["stove-api-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)
|
||||
@@ -45,11 +60,21 @@ async def overview():
|
||||
@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)
|
||||
|
||||
Reference in New Issue
Block a user