feat: initial scaffold of CrowdSec admin webapp
All checks were successful
Deploy / deploy (push) Successful in 39s
All checks were successful
Deploy / deploy (push) Successful in 39s
Flask + htmx mini-app to list and delete CrowdSec decisions from a browser, gated behind Authentik. Talks to host LAPI via host.docker.internal:8080 using machine JWT auth (bouncer X-Api-Key is read-only). Gitea Actions CI/CD on push to main: runner rebuilds image and brings the stack up via docker compose on the host (same pattern as flight-radar). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
57
.gitea/workflows/deploy.yml
Normal file
57
.gitea/workflows/deploy.yml
Normal file
@@ -0,0 +1,57 @@
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
# CrowdSec Admin — Gitea Actions CI/CD
|
||||
#
|
||||
# Triggers on push to main. Runner builds image + brings stack up via docker
|
||||
# compose on the host. Image stays local (no registry push), same pattern as
|
||||
# flight-radar.
|
||||
#
|
||||
# PREREQUISITES (one-time):
|
||||
# 1. Host LAPI machine registered:
|
||||
# sudo cscli machines add crowdsec-admin --password '<PW>'
|
||||
# 2. Repo secrets set in Gitea → Settings → Secrets:
|
||||
# LAPI_MACHINE_ID=crowdsec-admin
|
||||
# LAPI_MACHINE_PASSWORD=<PW>
|
||||
# 3. DNS: crowdsec.domverse-berlin.eu → host IP.
|
||||
# 4. Authentik wildcard forward_domain already covers *.domverse-berlin.eu.
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
name: Deploy
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
COMPOSE_PROJECT: crowdsec-admin
|
||||
COMPOSE_FILE: docker-compose.yml
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Write .env for compose
|
||||
run: |
|
||||
cat > .env <<EOF
|
||||
LAPI_MACHINE_ID=${{ secrets.LAPI_MACHINE_ID }}
|
||||
LAPI_MACHINE_PASSWORD=${{ secrets.LAPI_MACHINE_PASSWORD }}
|
||||
EOF
|
||||
chmod 600 .env
|
||||
|
||||
- name: Deploy with docker compose
|
||||
run: |
|
||||
echo "=== Deploying commit ${{ gitea.sha }} to ${{ gitea.ref_name }} ==="
|
||||
docker compose -f "$COMPOSE_FILE" -p "$COMPOSE_PROJECT" up --build -d --remove-orphans
|
||||
|
||||
- name: Show health
|
||||
run: |
|
||||
sleep 3
|
||||
docker compose -f "$COMPOSE_FILE" -p "$COMPOSE_PROJECT" ps
|
||||
docker exec "$COMPOSE_PROJECT" python -c "import urllib.request; print(urllib.request.urlopen('http://127.0.0.1:8000/healthz', timeout=3).read().decode())" || true
|
||||
|
||||
- name: Prune dangling images
|
||||
run: docker image prune -f
|
||||
7
.gitignore
vendored
Normal file
7
.gitignore
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
.env
|
||||
__pycache__/
|
||||
*.pyc
|
||||
*.pyo
|
||||
.venv/
|
||||
.vscode/
|
||||
.idea/
|
||||
74
README.md
Normal file
74
README.md
Normal file
@@ -0,0 +1,74 @@
|
||||
# crowdsec-admin
|
||||
|
||||
Tiny Flask + htmx webapp to list and delete CrowdSec decisions (bans) from a browser, gated behind Authentik.
|
||||
|
||||
Built so the admin can unban an IP without SSH when their own network routes change. Source of truth: this Gitea repo. Push to `main` → Gitea Actions runner rebuilds and redeploys via `docker compose` on the host.
|
||||
|
||||
## Routes
|
||||
|
||||
- `GET /` — UI
|
||||
- `GET /decisions` — list active decisions (htmx fragment), optional `?ip=`
|
||||
- `POST /unban` — delete by decision `id` or by `ip`
|
||||
- `POST /unban-me` — delete decisions for the caller's IP (uses `X-Forwarded-For`)
|
||||
- `GET /healthz` — JSON, returns 503 if LAPI unreachable
|
||||
|
||||
## How it talks to CrowdSec
|
||||
|
||||
LAPI lives on the host at `0.0.0.0:8080`. Container reaches it via `host.docker.internal:host-gateway`.
|
||||
|
||||
LAPI `DELETE /v1/decisions` requires **machine JWT** (bouncers are read-only). App registers as machine via `cscli machines add`, logs in to `/v1/watchers/login`, caches the JWT ~13 minutes, and refreshes on 401.
|
||||
|
||||
## One-time setup
|
||||
|
||||
1. **Register the machine on the host** (needs sudo, choose a strong password and save it in `secrets.yml`):
|
||||
|
||||
```bash
|
||||
sudo cscli machines add crowdsec-admin --password '<PW>'
|
||||
```
|
||||
|
||||
2. **Gitea repo secrets** (Settings → Secrets and variables → Actions):
|
||||
|
||||
- `LAPI_MACHINE_ID=crowdsec-admin`
|
||||
- `LAPI_MACHINE_PASSWORD=<PW from step 1>`
|
||||
|
||||
3. **DNS**: `crowdsec.domverse-berlin.eu` → host IP.
|
||||
|
||||
4. **Authentik**: nothing — the existing wildcard `forward_domain` provider covers `*.domverse-berlin.eu`, and the `authentik@docker` label in `docker-compose.yml` gates the router.
|
||||
|
||||
5. **First deploy**: push to `main` or trigger `workflow_dispatch`. Runner builds the image, brings the stack up, and reports health.
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
crowdsec-admin/
|
||||
├── .gitea/workflows/deploy.yml # CI/CD on push to main
|
||||
├── docker-compose.yml # Traefik labels + Kuma + authentik@docker
|
||||
├── app/
|
||||
│ ├── Dockerfile # python:3.12-slim + gunicorn
|
||||
│ ├── requirements.txt
|
||||
│ ├── app.py # Flask, ~120 LOC
|
||||
│ └── templates/
|
||||
│ ├── index.html # full page
|
||||
│ ├── _decisions.html # htmx fragment
|
||||
│ └── _unban_me.html # htmx fragment
|
||||
└── README.md
|
||||
```
|
||||
|
||||
## Local dev
|
||||
|
||||
```bash
|
||||
docker compose up --build -d
|
||||
# or, on the host:
|
||||
LAPI_URL=http://localhost:8080 LAPI_MACHINE_ID=... LAPI_MACHINE_PASSWORD=... \
|
||||
python -m flask --app app/app.py run --port 8000
|
||||
```
|
||||
|
||||
## Security notes
|
||||
|
||||
- Authentik is the only auth gate. Admin compromise = unban anything.
|
||||
- App never `exec`s shell. Only LAPI HTTP. IP inputs validated with `ipaddress.ip_address`. Decision-id input validated `isdigit()`.
|
||||
- `TRUSTED_PROXY_HOPS=1` picks the IP Traefik saw. Increase if a second proxy sits in front.
|
||||
|
||||
## Pattern note
|
||||
|
||||
This stack is **not Portainer-managed** — it follows the same convention as the `flight-radar` repo: source in Gitea, runner brings the stack up on the host via `docker compose`. Other (non-CI) stacks are deployed via Portainer API per the infra rule.
|
||||
14
app/Dockerfile
Normal file
14
app/Dockerfile
Normal file
@@ -0,0 +1,14 @@
|
||||
FROM python:3.12-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY app.py .
|
||||
COPY templates/ templates/
|
||||
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
EXPOSE 8000
|
||||
|
||||
CMD ["gunicorn", "-b", "0.0.0.0:8000", "-w", "2", "--access-logfile", "-", "app:app"]
|
||||
134
app/app.py
Normal file
134
app/app.py
Normal file
@@ -0,0 +1,134 @@
|
||||
import os
|
||||
import time
|
||||
import ipaddress
|
||||
import logging
|
||||
from functools import wraps
|
||||
|
||||
import requests
|
||||
from flask import Flask, render_template, request, jsonify, abort
|
||||
|
||||
LAPI_URL = os.environ["LAPI_URL"].rstrip("/")
|
||||
MACHINE_ID = os.environ["LAPI_MACHINE_ID"]
|
||||
MACHINE_PW = os.environ["LAPI_MACHINE_PASSWORD"]
|
||||
TRUSTED_HOPS = int(os.environ.get("TRUSTED_PROXY_HOPS", "1"))
|
||||
REQ_TIMEOUT = 5
|
||||
|
||||
app = Flask(__name__)
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
log = app.logger
|
||||
|
||||
_token = {"jwt": None, "exp": 0.0}
|
||||
|
||||
|
||||
def _login():
|
||||
r = requests.post(
|
||||
f"{LAPI_URL}/v1/watchers/login",
|
||||
json={"machine_id": MACHINE_ID, "password": MACHINE_PW},
|
||||
timeout=REQ_TIMEOUT,
|
||||
)
|
||||
r.raise_for_status()
|
||||
data = r.json()
|
||||
_token["jwt"] = data["code"] if "code" in data and isinstance(data["code"], str) else data.get("token")
|
||||
if not _token["jwt"]:
|
||||
_token["jwt"] = data.get("code") or data.get("token")
|
||||
_token["exp"] = time.time() + 60 * 13
|
||||
return _token["jwt"]
|
||||
|
||||
|
||||
def _jwt():
|
||||
if not _token["jwt"] or time.time() >= _token["exp"]:
|
||||
return _login()
|
||||
return _token["jwt"]
|
||||
|
||||
|
||||
def _lapi(method, path, **kw):
|
||||
headers = kw.pop("headers", {})
|
||||
headers["Authorization"] = f"Bearer {_jwt()}"
|
||||
r = requests.request(method, f"{LAPI_URL}{path}", headers=headers, timeout=REQ_TIMEOUT, **kw)
|
||||
if r.status_code == 401:
|
||||
_token["exp"] = 0
|
||||
headers["Authorization"] = f"Bearer {_jwt()}"
|
||||
r = requests.request(method, f"{LAPI_URL}{path}", headers=headers, timeout=REQ_TIMEOUT, **kw)
|
||||
return r
|
||||
|
||||
|
||||
def caller_ip():
|
||||
xff = request.headers.get("X-Forwarded-For", "")
|
||||
chain = [p.strip() for p in xff.split(",") if p.strip()]
|
||||
if chain and TRUSTED_HOPS > 0:
|
||||
idx = max(0, len(chain) - TRUSTED_HOPS)
|
||||
candidate = chain[idx]
|
||||
else:
|
||||
candidate = request.remote_addr
|
||||
try:
|
||||
ipaddress.ip_address(candidate)
|
||||
except (ValueError, TypeError):
|
||||
abort(400, "could not determine caller ip")
|
||||
return candidate
|
||||
|
||||
|
||||
def valid_ip(s):
|
||||
try:
|
||||
ipaddress.ip_address(s)
|
||||
return True
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
@app.get("/")
|
||||
def index():
|
||||
return render_template("index.html", my_ip=caller_ip())
|
||||
|
||||
|
||||
@app.get("/decisions")
|
||||
def list_decisions():
|
||||
q = request.args.get("ip", "").strip()
|
||||
params = {}
|
||||
if q:
|
||||
if not valid_ip(q):
|
||||
return render_template("_decisions.html", error="invalid IP", decisions=[]), 400
|
||||
params["ip"] = q
|
||||
r = _lapi("GET", "/v1/decisions", params=params)
|
||||
if r.status_code != 200:
|
||||
return render_template("_decisions.html", error=f"LAPI {r.status_code}: {r.text[:200]}", decisions=[]), 502
|
||||
decisions = r.json() or []
|
||||
return render_template("_decisions.html", decisions=decisions, error=None)
|
||||
|
||||
|
||||
@app.post("/unban")
|
||||
def unban():
|
||||
ip = request.form.get("ip", "").strip()
|
||||
decision_id = request.form.get("id", "").strip()
|
||||
if decision_id:
|
||||
if not decision_id.isdigit():
|
||||
return "invalid id", 400
|
||||
r = _lapi("DELETE", f"/v1/decisions/{decision_id}")
|
||||
elif ip:
|
||||
if not valid_ip(ip):
|
||||
return "invalid IP", 400
|
||||
r = _lapi("DELETE", "/v1/decisions", params={"ip": ip})
|
||||
else:
|
||||
return "need id or ip", 400
|
||||
if r.status_code not in (200, 204):
|
||||
return f"LAPI {r.status_code}: {r.text[:200]}", 502
|
||||
log.info("unbanned by=%s ip=%s id=%s", caller_ip(), ip, decision_id)
|
||||
return list_decisions()
|
||||
|
||||
|
||||
@app.post("/unban-me")
|
||||
def unban_me():
|
||||
ip = caller_ip()
|
||||
r = _lapi("DELETE", "/v1/decisions", params={"ip": ip})
|
||||
if r.status_code not in (200, 204):
|
||||
return f"LAPI {r.status_code}: {r.text[:200]}", 502
|
||||
log.info("unban-me by=%s", ip)
|
||||
return render_template("_unban_me.html", ip=ip, result=r.json() if r.text else {})
|
||||
|
||||
|
||||
@app.get("/healthz")
|
||||
def healthz():
|
||||
try:
|
||||
r = _lapi("GET", "/v1/decisions", params={"limit": 1})
|
||||
return jsonify(ok=r.status_code == 200, lapi_status=r.status_code), 200 if r.status_code == 200 else 503
|
||||
except Exception as e:
|
||||
return jsonify(ok=False, error=str(e)), 503
|
||||
3
app/requirements.txt
Normal file
3
app/requirements.txt
Normal file
@@ -0,0 +1,3 @@
|
||||
flask==3.0.3
|
||||
requests==2.32.3
|
||||
gunicorn==22.0.0
|
||||
31
app/templates/_decisions.html
Normal file
31
app/templates/_decisions.html
Normal file
@@ -0,0 +1,31 @@
|
||||
{% if error %}
|
||||
<p class="err">{{ error }}</p>
|
||||
{% endif %}
|
||||
{% if decisions %}
|
||||
<table>
|
||||
<thead>
|
||||
<tr><th>ID</th><th>IP / value</th><th>Scope</th><th>Type</th><th>Reason</th><th>Until</th><th>Origin</th><th></th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for d in decisions %}
|
||||
<tr>
|
||||
<td><code>{{ d.id }}</code></td>
|
||||
<td><code>{{ d.value }}</code></td>
|
||||
<td>{{ d.scope }}</td>
|
||||
<td>{{ d.type }}</td>
|
||||
<td>{{ d.scenario }}</td>
|
||||
<td>{{ d.until }}</td>
|
||||
<td>{{ d.origin }}</td>
|
||||
<td>
|
||||
<form hx-post="/unban" hx-target="#decisions" hx-swap="innerHTML" hx-confirm="Delete decision {{ d.id }} for {{ d.value }}?">
|
||||
<input type="hidden" name="id" value="{{ d.id }}">
|
||||
<button class="danger" type="submit">Unban</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
{% else %}
|
||||
{% if not error %}<p>No active decisions.</p>{% endif %}
|
||||
{% endif %}
|
||||
1
app/templates/_unban_me.html
Normal file
1
app/templates/_unban_me.html
Normal file
@@ -0,0 +1 @@
|
||||
<p>Requested unban for <code>{{ ip }}</code>. LAPI: <code>{{ result }}</code></p>
|
||||
55
app/templates/index.html
Normal file
55
app/templates/index.html
Normal file
@@ -0,0 +1,55 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>CrowdSec Admin</title>
|
||||
<script src="https://unpkg.com/htmx.org@1.9.12"></script>
|
||||
<style>
|
||||
:root { color-scheme: dark; }
|
||||
body { font-family: system-ui, sans-serif; max-width: 1100px; margin: 2rem auto; padding: 0 1rem; background:#111; color:#ddd; }
|
||||
h1 { margin-top: 0; }
|
||||
table { border-collapse: collapse; width: 100%; margin-top: 1rem; }
|
||||
th, td { padding: .4rem .6rem; border-bottom: 1px solid #333; text-align: left; font-size: 0.9rem; }
|
||||
th { background: #222; }
|
||||
tr:hover { background: #1a1a1a; }
|
||||
button, input[type=submit] { background:#3a6; color:#fff; border:0; padding:.4rem .7rem; border-radius:4px; cursor:pointer; }
|
||||
button.danger { background:#c44; }
|
||||
button.warn { background:#a82; }
|
||||
input[type=text] { background:#222; color:#ddd; border:1px solid #444; padding:.4rem .6rem; border-radius:4px; }
|
||||
.row { display:flex; gap:.6rem; align-items:center; flex-wrap:wrap; }
|
||||
.pill { background:#333; padding:.15rem .5rem; border-radius:99px; font-size:.8rem; }
|
||||
.me { background:#2a4; }
|
||||
section { margin-top: 1.5rem; padding: 1rem; background:#181818; border-radius:6px; }
|
||||
.err { color:#f88; }
|
||||
code { background:#222; padding:.1rem .3rem; border-radius:3px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>CrowdSec Admin</h1>
|
||||
<div class="row">
|
||||
<span class="pill me">Your IP: <code>{{ my_ip }}</code></span>
|
||||
<form hx-post="/unban-me" hx-target="#unban-me-result" hx-swap="innerHTML" hx-confirm="Unban {{ my_ip }}?">
|
||||
<button class="warn" type="submit">Unban my IP</button>
|
||||
</form>
|
||||
</div>
|
||||
<div id="unban-me-result"></div>
|
||||
|
||||
<section>
|
||||
<h2>Active decisions</h2>
|
||||
<form hx-get="/decisions" hx-target="#decisions" hx-trigger="submit, load delay:200ms" hx-swap="innerHTML" class="row">
|
||||
<input type="text" name="ip" placeholder="Filter by IP (optional)">
|
||||
<button type="submit">Search</button>
|
||||
<button type="button" hx-get="/decisions" hx-target="#decisions" hx-swap="innerHTML">Refresh all</button>
|
||||
</form>
|
||||
<div id="decisions">Loading…</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Unban by IP</h2>
|
||||
<form hx-post="/unban" hx-target="#decisions" hx-swap="innerHTML" hx-confirm="Unban entered IP?" class="row">
|
||||
<input type="text" name="ip" placeholder="e.g. 1.2.3.4" required>
|
||||
<button class="danger" type="submit">Unban IP</button>
|
||||
</form>
|
||||
</section>
|
||||
</body>
|
||||
</html>
|
||||
40
docker-compose.yml
Normal file
40
docker-compose.yml
Normal file
@@ -0,0 +1,40 @@
|
||||
services:
|
||||
crowdsec-admin:
|
||||
build:
|
||||
context: ./app
|
||||
image: crowdsec-admin:local
|
||||
container_name: crowdsec-admin
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- domverse
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
environment:
|
||||
- TZ=Europe/Berlin
|
||||
- LAPI_URL=http://host.docker.internal:8080
|
||||
- LAPI_MACHINE_ID=${LAPI_MACHINE_ID}
|
||||
- LAPI_MACHINE_PASSWORD=${LAPI_MACHINE_PASSWORD}
|
||||
- TRUSTED_PROXY_HOPS=1
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8000/healthz', timeout=3).status==200 else 1)"]
|
||||
interval: 60s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
- "traefik.http.routers.crowdsec-admin.rule=Host(`crowdsec.domverse-berlin.eu`)"
|
||||
- "traefik.http.routers.crowdsec-admin.entrypoints=https"
|
||||
- "traefik.http.routers.crowdsec-admin.tls.certresolver=http"
|
||||
- "traefik.http.routers.crowdsec-admin.middlewares=authentik@docker"
|
||||
- "traefik.http.services.crowdsec-admin.loadbalancer.server.port=8000"
|
||||
|
||||
- "kuma.crowdsec-admin.http.name=CrowdSec Admin"
|
||||
- "kuma.crowdsec-admin.http.url=https://crowdsec.domverse-berlin.eu"
|
||||
- "kuma.crowdsec-admin.http.interval=120"
|
||||
- "kuma.crowdsec-admin.http.max_retries=2"
|
||||
- "kuma.crowdsec-admin.http.retry_interval=60"
|
||||
- "kuma.crowdsec-admin.http.accepted_statuscodes=[\"200-399\"]"
|
||||
|
||||
networks:
|
||||
domverse:
|
||||
external: true
|
||||
Reference in New Issue
Block a user