barbenoire/lapi.py

82 lines
3.7 KiB
Python
Raw Normal View History

"""Minimal async client for the CrowdSec Local API (LAPI).
Reading current decisions uses a bouncer API key. Alert history and deleting decisions
need a machine (watcher) login, which returns a JWT that we refresh when it expires.
"""
from __future__ import annotations
import ipaddress
from datetime import datetime, timedelta, timezone
import httpx
class LapiError(Exception):
pass
def valid_ip(value: str) -> str:
"""Return the normalised IP or raise ValueError (no ranges, single addresses only)."""
return str(ipaddress.ip_address(value.strip()))
class Lapi:
def __init__(self, url: str, bouncer_key: str, machine_id: str = "", machine_password: str = ""):
self.client = httpx.AsyncClient(base_url=url.rstrip("/"), timeout=15)
self.bouncer_key = bouncer_key
self.machine_id = machine_id
self.machine_password = machine_password
self._jwt: str | None = None
self._jwt_expire = datetime.min.replace(tzinfo=timezone.utc)
@property
def has_machine(self) -> bool:
"""Machine login is optional: without it the bot is read-only (no history, no unban)."""
return bool(self.machine_id and self.machine_password)
async def _machine_headers(self) -> dict[str, str]:
if self._jwt is None or datetime.now(timezone.utc) > self._jwt_expire - timedelta(minutes=2):
r = await self.client.post("/v1/watchers/login", json={
"machine_id": self.machine_id, "password": self.machine_password, "scenarios": []})
if r.status_code != 200:
raise LapiError(f"machine login failed: HTTP {r.status_code} {r.text[:200]}")
data = r.json()
self._jwt = data["token"]
try:
self._jwt_expire = datetime.fromisoformat(data["expire"].replace("Z", "+00:00"))
except (KeyError, ValueError):
self._jwt_expire = datetime.now(timezone.utc) + timedelta(minutes=30)
return {"Authorization": f"Bearer {self._jwt}"}
async def _get(self, path: str, params: dict, machine: bool):
headers = await self._machine_headers() if machine else {"X-Api-Key": self.bouncer_key}
r = await self.client.get(path, params=params, headers=headers)
if r.status_code == 401 and machine: # token revoked/expired early: retry once
self._jwt = None
r = await self.client.get(path, params=params, headers=await self._machine_headers())
if r.status_code != 200:
raise LapiError(f"GET {path}: HTTP {r.status_code} {r.text[:200]}")
return r.json() or []
async def local_decisions(self) -> list[dict]:
"""Active decisions made by this CrowdSec (detections + cscli), not the community blocklist."""
decisions = await self._get("/v1/decisions", {"origins": "crowdsec,cscli"}, machine=False)
return [d for d in decisions if d.get("origin") in ("crowdsec", "cscli")]
async def decisions_for_ip(self, ip: str) -> list[dict]:
"""Active decisions for one IP (all origins, including the community blocklist)."""
return await self._get("/v1/decisions", {"ip": ip}, machine=False)
async def alerts(self, **params) -> list[dict]:
"""Alerts from the local engine (CAPI blocklist excluded)."""
params.setdefault("include_capi", "false")
params.setdefault("limit", 500)
return await self._get("/v1/alerts", params, machine=True)
async def delete_decisions(self, ip: str) -> int:
headers = await self._machine_headers()
r = await self.client.delete("/v1/decisions", params={"ip": ip}, headers=headers)
if r.status_code != 200:
raise LapiError(f"DELETE decisions: HTTP {r.status_code} {r.text[:200]}")
return int(r.json().get("nbDeleted", 0))