fix: split LAPI auth — bouncer key for read, machine JWT for delete
All checks were successful
Deploy / deploy (push) Successful in 19s
All checks were successful
Deploy / deploy (push) Successful in 19s
LAPI does not let machine JWTs hit GET /v1/decisions even after the machine is validated (returns 403 access forbidden). Conversely, bouncer X-Api-Key does not satisfy DELETE /v1/decisions (returns 401 "cookie token is empty"). The webapp now holds both credentials and routes each call to the right authority. Adds LAPI_BOUNCER_KEY env var + Gitea secret. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -6,13 +6,16 @@
|
|||||||
# flight-radar.
|
# flight-radar.
|
||||||
#
|
#
|
||||||
# PREREQUISITES (one-time):
|
# PREREQUISITES (one-time):
|
||||||
# 1. Host LAPI machine registered:
|
# 1. Host LAPI machine registered (for DELETE auth):
|
||||||
# sudo cscli machines add crowdsec-admin --password '<PW>'
|
# sudo cscli machines add crowdsec-admin --password '<PW>' -f -
|
||||||
# 2. Repo secrets set in Gitea → Settings → Secrets:
|
# 2. Host LAPI bouncer registered (for GET auth):
|
||||||
|
# sudo cscli bouncers add crowdsec-admin
|
||||||
|
# 3. Repo secrets set in Gitea → Settings → Secrets:
|
||||||
# LAPI_MACHINE_ID=crowdsec-admin
|
# LAPI_MACHINE_ID=crowdsec-admin
|
||||||
# LAPI_MACHINE_PASSWORD=<PW>
|
# LAPI_MACHINE_PASSWORD=<PW>
|
||||||
# 3. DNS: crowdsec.domverse-berlin.eu → host IP.
|
# LAPI_BOUNCER_KEY=<bouncer key from step 2>
|
||||||
# 4. Authentik wildcard forward_domain already covers *.domverse-berlin.eu.
|
# 4. DNS: crowdsec.domverse-berlin.eu → host IP.
|
||||||
|
# 5. Authentik wildcard forward_domain already covers *.domverse-berlin.eu.
|
||||||
# ──────────────────────────────────────────────────────────────────────────────
|
# ──────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
name: Deploy
|
name: Deploy
|
||||||
@@ -39,6 +42,7 @@ jobs:
|
|||||||
cat > .env <<EOF
|
cat > .env <<EOF
|
||||||
LAPI_MACHINE_ID=${{ secrets.LAPI_MACHINE_ID }}
|
LAPI_MACHINE_ID=${{ secrets.LAPI_MACHINE_ID }}
|
||||||
LAPI_MACHINE_PASSWORD=${{ secrets.LAPI_MACHINE_PASSWORD }}
|
LAPI_MACHINE_PASSWORD=${{ secrets.LAPI_MACHINE_PASSWORD }}
|
||||||
|
LAPI_BOUNCER_KEY=${{ secrets.LAPI_BOUNCER_KEY }}
|
||||||
EOF
|
EOF
|
||||||
chmod 600 .env
|
chmod 600 .env
|
||||||
|
|
||||||
|
|||||||
28
README.md
28
README.md
@@ -16,26 +16,40 @@ Built so the admin can unban an IP without SSH when their own network routes cha
|
|||||||
|
|
||||||
LAPI lives on the host at `0.0.0.0:8080`. Container reaches it via `host.docker.internal:host-gateway`.
|
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.
|
**LAPI splits read vs write auth:**
|
||||||
|
|
||||||
|
| Endpoint | Auth | Notes |
|
||||||
|
|-------------------------------|-----------------------|------------------------------------------------|
|
||||||
|
| `GET /v1/decisions` | bouncer `X-Api-Key` | Machine JWT returns 403 even when validated. |
|
||||||
|
| `DELETE /v1/decisions[/{id}]` | machine `Bearer` JWT | Bouncer key returns 401 "cookie token is empty". |
|
||||||
|
|
||||||
|
So the app holds both credentials. JWT is acquired via `POST /v1/watchers/login`, cached ~13 min, auto-refreshed on 401. Bouncer key is used as-is.
|
||||||
|
|
||||||
## One-time setup
|
## One-time setup
|
||||||
|
|
||||||
1. **Register the machine on the host** (needs sudo, choose a strong password and save it in `secrets.yml`):
|
1. **Register the LAPI machine** on the host (for DELETE). Choose a strong password and save it in `secrets.yml`. `-f -` dumps creds to stdout instead of overwriting the local agent's credentials file.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo cscli machines add crowdsec-admin --password '<PW>'
|
sudo cscli machines add crowdsec-admin --password '<PW>' -f -
|
||||||
```
|
```
|
||||||
|
|
||||||
2. **Gitea repo secrets** (Settings → Secrets and variables → Actions):
|
2. **Register a bouncer** on the host (for GET). Save the key in `secrets.yml`.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo cscli bouncers add crowdsec-admin
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Gitea repo secrets** (Settings → Secrets and variables → Actions):
|
||||||
|
|
||||||
- `LAPI_MACHINE_ID=crowdsec-admin`
|
- `LAPI_MACHINE_ID=crowdsec-admin`
|
||||||
- `LAPI_MACHINE_PASSWORD=<PW from step 1>`
|
- `LAPI_MACHINE_PASSWORD=<PW from step 1>`
|
||||||
|
- `LAPI_BOUNCER_KEY=<key from step 2>`
|
||||||
|
|
||||||
3. **DNS**: `crowdsec.domverse-berlin.eu` → host IP.
|
4. **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. **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.
|
6. **First deploy**: push to `main` or trigger `workflow_dispatch`. Runner builds the image, brings the stack up, and reports health.
|
||||||
|
|
||||||
## Layout
|
## Layout
|
||||||
|
|
||||||
|
|||||||
29
app/app.py
29
app/app.py
@@ -2,7 +2,6 @@ import os
|
|||||||
import time
|
import time
|
||||||
import ipaddress
|
import ipaddress
|
||||||
import logging
|
import logging
|
||||||
from functools import wraps
|
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
from flask import Flask, render_template, request, jsonify, abort
|
from flask import Flask, render_template, request, jsonify, abort
|
||||||
@@ -10,9 +9,14 @@ from flask import Flask, render_template, request, jsonify, abort
|
|||||||
LAPI_URL = os.environ["LAPI_URL"].rstrip("/")
|
LAPI_URL = os.environ["LAPI_URL"].rstrip("/")
|
||||||
MACHINE_ID = os.environ["LAPI_MACHINE_ID"]
|
MACHINE_ID = os.environ["LAPI_MACHINE_ID"]
|
||||||
MACHINE_PW = os.environ["LAPI_MACHINE_PASSWORD"]
|
MACHINE_PW = os.environ["LAPI_MACHINE_PASSWORD"]
|
||||||
|
BOUNCER_KEY = os.environ["LAPI_BOUNCER_KEY"]
|
||||||
TRUSTED_HOPS = int(os.environ.get("TRUSTED_PROXY_HOPS", "1"))
|
TRUSTED_HOPS = int(os.environ.get("TRUSTED_PROXY_HOPS", "1"))
|
||||||
REQ_TIMEOUT = 5
|
REQ_TIMEOUT = 5
|
||||||
|
|
||||||
|
# LAPI splits read vs write:
|
||||||
|
# GET /v1/decisions → bouncer X-Api-Key
|
||||||
|
# DELETE /v1/decisions → machine Bearer JWT (from /v1/watchers/login)
|
||||||
|
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
logging.basicConfig(level=logging.INFO)
|
logging.basicConfig(level=logging.INFO)
|
||||||
log = app.logger
|
log = app.logger
|
||||||
@@ -27,10 +31,7 @@ def _login():
|
|||||||
timeout=REQ_TIMEOUT,
|
timeout=REQ_TIMEOUT,
|
||||||
)
|
)
|
||||||
r.raise_for_status()
|
r.raise_for_status()
|
||||||
data = r.json()
|
_token["jwt"] = r.json()["token"]
|
||||||
_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
|
_token["exp"] = time.time() + 60 * 13
|
||||||
return _token["jwt"]
|
return _token["jwt"]
|
||||||
|
|
||||||
@@ -41,7 +42,13 @@ def _jwt():
|
|||||||
return _token["jwt"]
|
return _token["jwt"]
|
||||||
|
|
||||||
|
|
||||||
def _lapi(method, path, **kw):
|
def _bouncer(method, path, **kw):
|
||||||
|
headers = kw.pop("headers", {})
|
||||||
|
headers["X-Api-Key"] = BOUNCER_KEY
|
||||||
|
return requests.request(method, f"{LAPI_URL}{path}", headers=headers, timeout=REQ_TIMEOUT, **kw)
|
||||||
|
|
||||||
|
|
||||||
|
def _machine(method, path, **kw):
|
||||||
headers = kw.pop("headers", {})
|
headers = kw.pop("headers", {})
|
||||||
headers["Authorization"] = f"Bearer {_jwt()}"
|
headers["Authorization"] = f"Bearer {_jwt()}"
|
||||||
r = requests.request(method, f"{LAPI_URL}{path}", headers=headers, timeout=REQ_TIMEOUT, **kw)
|
r = requests.request(method, f"{LAPI_URL}{path}", headers=headers, timeout=REQ_TIMEOUT, **kw)
|
||||||
@@ -88,7 +95,7 @@ def list_decisions():
|
|||||||
if not valid_ip(q):
|
if not valid_ip(q):
|
||||||
return render_template("_decisions.html", error="invalid IP", decisions=[]), 400
|
return render_template("_decisions.html", error="invalid IP", decisions=[]), 400
|
||||||
params["ip"] = q
|
params["ip"] = q
|
||||||
r = _lapi("GET", "/v1/decisions", params=params)
|
r = _bouncer("GET", "/v1/decisions", params=params)
|
||||||
if r.status_code != 200:
|
if r.status_code != 200:
|
||||||
return render_template("_decisions.html", error=f"LAPI {r.status_code}: {r.text[:200]}", decisions=[]), 502
|
return render_template("_decisions.html", error=f"LAPI {r.status_code}: {r.text[:200]}", decisions=[]), 502
|
||||||
decisions = r.json() or []
|
decisions = r.json() or []
|
||||||
@@ -102,11 +109,11 @@ def unban():
|
|||||||
if decision_id:
|
if decision_id:
|
||||||
if not decision_id.isdigit():
|
if not decision_id.isdigit():
|
||||||
return "invalid id", 400
|
return "invalid id", 400
|
||||||
r = _lapi("DELETE", f"/v1/decisions/{decision_id}")
|
r = _machine("DELETE", f"/v1/decisions/{decision_id}")
|
||||||
elif ip:
|
elif ip:
|
||||||
if not valid_ip(ip):
|
if not valid_ip(ip):
|
||||||
return "invalid IP", 400
|
return "invalid IP", 400
|
||||||
r = _lapi("DELETE", "/v1/decisions", params={"ip": ip})
|
r = _machine("DELETE", "/v1/decisions", params={"ip": ip})
|
||||||
else:
|
else:
|
||||||
return "need id or ip", 400
|
return "need id or ip", 400
|
||||||
if r.status_code not in (200, 204):
|
if r.status_code not in (200, 204):
|
||||||
@@ -118,7 +125,7 @@ def unban():
|
|||||||
@app.post("/unban-me")
|
@app.post("/unban-me")
|
||||||
def unban_me():
|
def unban_me():
|
||||||
ip = caller_ip()
|
ip = caller_ip()
|
||||||
r = _lapi("DELETE", "/v1/decisions", params={"ip": ip})
|
r = _machine("DELETE", "/v1/decisions", params={"ip": ip})
|
||||||
if r.status_code not in (200, 204):
|
if r.status_code not in (200, 204):
|
||||||
return f"LAPI {r.status_code}: {r.text[:200]}", 502
|
return f"LAPI {r.status_code}: {r.text[:200]}", 502
|
||||||
log.info("unban-me by=%s", ip)
|
log.info("unban-me by=%s", ip)
|
||||||
@@ -128,7 +135,7 @@ def unban_me():
|
|||||||
@app.get("/healthz")
|
@app.get("/healthz")
|
||||||
def healthz():
|
def healthz():
|
||||||
try:
|
try:
|
||||||
r = _lapi("GET", "/v1/decisions", params={"limit": 1})
|
r = _bouncer("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
|
return jsonify(ok=r.status_code == 200, lapi_status=r.status_code), 200 if r.status_code == 200 else 503
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return jsonify(ok=False, error=str(e)), 503
|
return jsonify(ok=False, error=str(e)), 503
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ services:
|
|||||||
- LAPI_URL=http://host.docker.internal:8080
|
- LAPI_URL=http://host.docker.internal:8080
|
||||||
- LAPI_MACHINE_ID=${LAPI_MACHINE_ID}
|
- LAPI_MACHINE_ID=${LAPI_MACHINE_ID}
|
||||||
- LAPI_MACHINE_PASSWORD=${LAPI_MACHINE_PASSWORD}
|
- LAPI_MACHINE_PASSWORD=${LAPI_MACHINE_PASSWORD}
|
||||||
|
- LAPI_BOUNCER_KEY=${LAPI_BOUNCER_KEY}
|
||||||
- TRUSTED_PROXY_HOPS=1
|
- TRUSTED_PROXY_HOPS=1
|
||||||
labels:
|
labels:
|
||||||
- "traefik.enable=true"
|
- "traefik.enable=true"
|
||||||
|
|||||||
Reference in New Issue
Block a user