initial - add implementation for simple crowdsec app to list and delete non-CAPI decisions

This commit is contained in:
Viktor Barzin 2025-10-14 19:21:36 +00:00
commit 9aaf3d32d0
No known key found for this signature in database
GPG key ID: 4056458DBDBF8863
7 changed files with 349 additions and 0 deletions

22
app/api.py Normal file
View file

@ -0,0 +1,22 @@
from fastapi import APIRouter, HTTPException
from app.crowdsec_api import list_decisions, delete_decision
router = APIRouter()
@router.get("/decisions")
async def get_decisions():
try:
decisions = await list_decisions()
return {"decisions": decisions}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@router.delete("/decisions/{ip}")
async def remove_decision(ip: str):
try:
await delete_decision(ip)
return {"status": "deleted", "ip": ip}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))

47
app/crowdsec_api.py Normal file
View file

@ -0,0 +1,47 @@
import httpx
from typing import List, Dict
import os
API_URL = os.environ["CS_API_URL"] # e.g http://127.0.0.1:8080/v1
API_KEY = os.environ["CS_API_KEY"] # cscli bouncers add <bouncer_name>
MACHINE_ID = os.environ["CS_MACHINE_ID"]
PASSWORD = os.environ["CS_MACHINE_PASSWORD"]
async def list_decisions() -> List[Dict]:
"""
Get all current decisions from CrowdSec API.
"""
async with httpx.AsyncClient() as client:
resp = await client.get(
f"{API_URL}/decisions",
headers={
"X-Api-Key": API_KEY,
"Content-Type": "application/json",
},
)
resp.raise_for_status()
decisions = resp.json() or []
decisions = [d for d in decisions if d["origin"] != "CAPI"]
return decisions
async def delete_decision(ip: str) -> None:
"""
Delete a decision by IP.
"""
async with httpx.AsyncClient() as client:
login = await client.post(
f"{API_URL}/watchers/login",
json={
"machine_id": MACHINE_ID,
"password": PASSWORD,
},
headers={"Content-Type": "application/json"},
)
response = login.json()
token = response["token"]
resp = await client.delete(
f"{API_URL}/decisions?ip={ip}", headers={"Authorization": f"Bearer {token}"}
)
resp.raise_for_status()

21
app/main.py Normal file
View file

@ -0,0 +1,21 @@
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from app.api import router as api_router
from app.crowdsec_api import list_decisions
app = FastAPI(title="CrowdSec Web UI")
# Include API
app.include_router(api_router, prefix="/api")
# Templates
templates = Jinja2Templates(directory="app/templates")
@app.get("/", response_class=HTMLResponse)
async def index(request: Request):
decisions = await list_decisions()
return templates.TemplateResponse(
"index.html", {"request": request, "decisions": decisions}
)

44
app/templates/index.html Normal file
View file

@ -0,0 +1,44 @@
<!DOCTYPE html>
<html>
<head>
<title>CrowdSec Web UI</title>
<script>
async function deleteDecision(ip) {
const response = await fetch(`/api/decisions/${ip}`, { method: 'DELETE' });
if (response.ok) {
location.reload();
} else {
alert("Failed to delete decision");
}
}
</script>
</head>
<body>
<h1>CrowdSec Decisions</h1>
<table border="1" cellpadding="5">
<tr>
<th>IP</th>
<th>Scope</th>
<th>Type</th>
<th>Expiration</th>
<th>Source</th>
<th>Scenario</th>
<th>Actions</th>
</tr>
{% for d in decisions %}
<tr>
<td>{{ d.value }}</td>
<td>{{ d.scope }}</td>
<td>{{ d.type }}</td>
<td>{{ d.duration }}</td>
<td>{{ d.origin }}</td>
<td>{{ d.scenario }}</td>
<td><button onclick="deleteDecision('{{ d.value }}')">Delete</button></td>
</tr>
{% endfor %}
</table>
</body>
</html>