Read-only mode: machine login optional, bouncer key is enough for /bans and /ip

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
un-oeil 2026-10-13 14:16:22 +02:00
parent 3eb933fc63
commit 353799ac2f
4 changed files with 60 additions and 15 deletions

View file

@ -5,8 +5,9 @@ ALLOWED_CHAT_IDS=8248249474
LAPI_URL=http://10.0.0.11:8080
# On the CrowdSec host: cscli bouncers add barbenoire
CROWDSEC_BOUNCER_KEY=
# On the CrowdSec host: cscli machines add barbenoire --password '<long random>'
CROWDSEC_MACHINE_ID=barbenoire
# OPTIONAL machine login (enables history, /unban, /stats). Leave empty for read-only mode.
# cscli machines add barbenoire --password '<long random>' -f /dev/null
CROWDSEC_MACHINE_ID=
CROWDSEC_MACHINE_PASSWORD=
# Kuma Push URL for the "Barbenoire" monitor (bot heartbeat every 60 s); empty = off
KUMA_PUSH_URL=

View file

@ -17,8 +17,18 @@ It only answers the chat IDs in `ALLOWED_CHAT_IDS`.
## CrowdSec credentials (on the CrowdSec host, LXC 101)
```bash
cscli bouncers add barbenoire # -> CROWDSEC_BOUNCER_KEY (read current decisions)
cscli machines add barbenoire --password '<long random>' -f /dev/null # -> machine login (history + unban)
cscli bouncers add barbenoire # -> CROWDSEC_BOUNCER_KEY (required, read-only)
```
**Read-only mode (default):** with only the bouncer key, `/bans` and `/ip` work (no country,
no history); `/unban` and `/stats` reply that they are turned off.
**Full mode (optional):** a machine login adds alert history, countries, `/stats` and
`/unban`. A machine can also *create* alerts and bans, so its password is sensitive.
```bash
cscli machines add barbenoire --password '<long random>' -f /dev/null
# then set CROWDSEC_MACHINE_ID / CROWDSEC_MACHINE_PASSWORD in .env and restart
```
The bot talks to the LAPI at `http://10.0.0.11:8080` (reachable from VM 107).

44
app.py
View file

@ -22,8 +22,9 @@ PUSH_URL = os.environ.get("KUMA_PUSH_URL", "").strip()
lapi = Lapi(
url=os.environ.get("LAPI_URL", "http://10.0.0.11:8080"),
bouncer_key=os.environ["CROWDSEC_BOUNCER_KEY"],
machine_id=os.environ["CROWDSEC_MACHINE_ID"],
machine_password=os.environ["CROWDSEC_MACHINE_PASSWORD"],
# Optional: without a machine login the bot is read-only (no history, /unban, /stats)
machine_id=os.environ.get("CROWDSEC_MACHINE_ID", "").strip(),
machine_password=os.environ.get("CROWDSEC_MACHINE_PASSWORD", "").strip(),
)
logging.basicConfig(format="%(asctime)s %(levelname)s %(name)s: %(message)s", level=logging.INFO)
@ -74,6 +75,10 @@ def ip_links(ip: str) -> InlineKeyboardMarkup:
]])
READ_ONLY = ("🔒 Turned off: this bot only has a read-only CrowdSec key. "
"Add a machine login to its .env to enable it.")
async def reply(update: Update, text: str, markup=None):
await update.effective_message.reply_text(
text, parse_mode=ParseMode.HTML, disable_web_page_preview=True, reply_markup=markup)
@ -87,25 +92,32 @@ async def cmd_help(update: Update, context: ContextTypes.DEFAULT_TYPE):
"/ip &lt;address&gt;: is it banned, and its history\n"
"/unban &lt;address&gt;: lift a ban (asks to confirm)\n"
"/stats: bans over the last 24 h and 7 days"
+ ("" if lapi.has_machine else "\n\n🔒 Read-only mode: /unban, /stats and history are off.")
))
@restricted
async def cmd_bans(update: Update, context: ContextTypes.DEFAULT_TYPE):
alerts = await lapi.alerts(has_active_decision="true")
rows = []
for a in alerts:
src = a.get("source") or {}
for d in a.get("decisions") or []:
if lapi.has_machine: # alerts carry the country and the creation time
for a in await lapi.alerts(has_active_decision="true"):
src = a.get("source") or {}
for d in a.get("decisions") or []:
if d.get("type") == "ban":
rows.append((a.get("created_at", ""), d.get("value"), src.get("cn"),
d.get("scenario") or a.get("scenario"), short_duration(d.get("duration"))))
else: # bouncer key: current decisions only, newest id first
for d in await lapi.local_decisions():
if d.get("type") == "ban":
rows.append((a.get("created_at", ""), d.get("value"), src.get("cn"), d.get("scenario") or a.get("scenario"),
rows.append((d.get("id", 0), d.get("value"), None, d.get("scenario"),
short_duration(d.get("duration"))))
if not rows:
await reply(update, "✅ No active bans from your CrowdSec (community blocklist not counted).")
return
rows.sort(reverse=True)
lines = [f"🚫 <b>{len(rows)} active ban(s)</b>, latest first:"]
lines += [f"{flag(cn)} <code>{esc(ip)}</code> · {esc(sc)} · {left} left" for _, ip, cn, sc, left in rows[:10]]
lines += [(f"{flag(cn)} " if cn else "🚫 ") + f"<code>{esc(ip)}</code> · {esc(sc)} · {left} left"
for _, ip, cn, sc, left in rows[:10]]
if len(rows) > 10:
lines.append(f"… and {len(rows) - 10} more")
await reply(update, "\n".join(lines))
@ -121,7 +133,7 @@ async def cmd_ip(update: Update, context: ContextTypes.DEFAULT_TYPE):
await reply(update, "Usage: /ip &lt;address&gt;")
return
decisions = await lapi.decisions_for_ip(ip)
history = await lapi.alerts(ip=ip, limit=10)
history = await lapi.alerts(ip=ip, limit=10) if lapi.has_machine else None
lines = [f"🔎 <code>{esc(ip)}</code>"]
if decisions:
for d in decisions:
@ -136,6 +148,8 @@ async def cmd_ip(update: Update, context: ContextTypes.DEFAULT_TYPE):
for a in history:
lines.append(f"• {esc(a.get('created_at', '')[:16].replace('T', ' '))} · {esc(a.get('scenario'))} "
f"· {a.get('events_count', '?')} events")
elif history is None:
lines.append("<i>History needs a machine login (read-only mode).</i>")
else:
lines.append("No alerts from your CrowdSec for this address.")
await reply(update, "\n".join(lines), markup=ip_links(ip))
@ -143,6 +157,9 @@ async def cmd_ip(update: Update, context: ContextTypes.DEFAULT_TYPE):
@restricted
async def cmd_unban(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not lapi.has_machine:
await reply(update, READ_ONLY)
return
try:
ip = valid_ip(context.args[0]) if context.args else None
except ValueError:
@ -170,6 +187,9 @@ async def on_button(update: Update, context: ContextTypes.DEFAULT_TYPE):
await query.edit_message_text("Cancelled.")
return
if query.data.startswith("unban:"):
if not lapi.has_machine:
await query.edit_message_text(READ_ONLY)
return
ip = valid_ip(query.data.split(":", 1)[1])
n = await lapi.delete_decisions(ip)
log.info("unbanned %s (%d decision(s)) on request of %s", ip, n, update.effective_user.id)
@ -179,6 +199,9 @@ async def on_button(update: Update, context: ContextTypes.DEFAULT_TYPE):
@restricted
async def cmd_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not lapi.has_machine:
await reply(update, READ_ONLY)
return
lines = ["📊 <b>CrowdSec</b> (local detections, community blocklist not counted)"]
for label, since in (("24 h", "24h"), ("7 days", "168h")):
alerts = await lapi.alerts(since=since, limit=5000)
@ -208,7 +231,8 @@ def main():
app.add_handler(CallbackQueryHandler(on_button))
if PUSH_URL:
app.job_queue.run_repeating(job_heartbeat, interval=60, first=5, name="heartbeat")
log.info("Barbenoire starting (heartbeat=%s)", "on" if PUSH_URL else "off")
log.info("Barbenoire starting (mode=%s, heartbeat=%s)",
"full" if lapi.has_machine else "read-only", "on" if PUSH_URL else "off")
app.run_polling(allowed_updates=Update.ALL_TYPES)

12
lapi.py
View file

@ -21,7 +21,7 @@ def valid_ip(value: str) -> str:
class Lapi:
def __init__(self, url: str, bouncer_key: str, machine_id: str, machine_password: str):
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
@ -29,6 +29,11 @@ class Lapi:
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={
@ -53,6 +58,11 @@ class Lapi:
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)