diff --git a/.github/scripts/lapi-matrix/run-live-tests.sh b/.github/scripts/lapi-matrix/run-live-tests.sh new file mode 100755 index 000000000..37dac6204 --- /dev/null +++ b/.github/scripts/lapi-matrix/run-live-tests.sh @@ -0,0 +1,251 @@ +#!/usr/bin/env bash +# Run the crowdsec-client live E2E suite against several CrowdSec LAPI +# versions in Docker. Used by .github/workflows/client-live-matrix.yml, and +# usable locally. +# +# Usage: +# ./run-live-tests.sh # .github/scripts/lapi-matrix/versions.txt, all modes, HTTP+TLS +# ./run-live-tests.sh v1.0.0 v1.8.2 # explicit tags +# MODES="bouncer" ./run-live-tests.sh # only the bouncer scenarios +# TLS=0 ./run-live-tests.sh # HTTP only +# BASE_PORT=29100 BASE_TLS_PORT=29200 ./run-live-tests.sh ... +# +# Modes: both (watcher + bouncer), watcher (JWT only), bouncer (API key only). +# TLS is terminated by an nginx proxy with a temporary self-signed certificate. +# +# Output is streamed: no result file and no per-run log is written. +set -uo pipefail + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +repo_root="$(cd "$here/../../.." && pwd)" +base_port="${BASE_PORT:-29100}" +base_tls_port="${BASE_TLS_PORT:-29200}" +network="${DOCKER_NETWORK:-cs-live-net}" +tls_enabled="${TLS:-1}" +tls_strict="${TLS_STRICT:-1}" +work_dir="$(mktemp -d)" +tls_dir="$work_dir/tls" +containers=() +created_network="" + +cleanup() { + if [[ "${#containers[@]}" -gt 0 ]]; then + docker rm -f "${containers[@]}" >/dev/null 2>&1 || true + fi + if [[ -n "$created_network" ]]; then + docker network rm "$network" >/dev/null 2>&1 || true + fi + rm -rf "$work_dir" +} +trap cleanup EXIT + +versions_file="${VERSIONS_FILE:-$repo_root/.github/scripts/lapi-matrix/versions.txt}" +if [[ "$#" -gt 0 ]]; then + versions=("$@") +else + if [[ ! -f "$versions_file" ]]; then + echo "versions file not found: $versions_file" >&2 + exit 2 + fi + versions=() + while IFS= read -r tag; do + tag="${tag%$'\r'}" + [[ -z "$tag" || "$tag" == \#* ]] && continue + versions+=("$tag") + done <"$versions_file" + if [[ "${#versions[@]}" -eq 0 ]]; then + echo "no versions in $versions_file" >&2 + exit 2 + fi +fi + +read -r -a modes <<<"${MODES:-both watcher bouncer}" +for mode in "${modes[@]}"; do + case "$mode" in + both | watcher | bouncer) ;; + *) + echo "invalid mode '$mode' (expected both, watcher or bouncer)" >&2 + exit 2 + ;; + esac +done + +# The LAPI container always joins this network; TLS only adds the nginx proxy. +if ! docker network inspect "$network" >/dev/null 2>&1; then + docker network create "$network" >/dev/null + created_network=1 +fi + +if [[ "$tls_enabled" = "1" ]]; then + mkdir -p "$tls_dir" + openssl req -x509 -newkey rsa:2048 -nodes \ + -keyout "$tls_dir/key.pem" -out "$tls_dir/cert.pem" \ + -days 2 -subj "/CN=localhost" \ + -addext "subjectAltName=DNS:localhost,IP:127.0.0.1" >/dev/null 2>&1 || { + echo "failed to generate the TLS certificate" >&2 + exit 2 + } +fi + +wait_http() { + for _ in $(seq 1 90); do + code=$(curl -s -o /dev/null -w '%{http_code}' "$1" 2>/dev/null || true) + [[ "$code" != "000" ]] && [[ -n "$code" ]] && return 0 + sleep 1 + done + return 1 +} + +wait_tls() { + for _ in $(seq 1 60); do + code=$(curl -sk -o /dev/null -w '%{http_code}' "$1" 2>/dev/null || true) + [[ "$code" != "000" ]] && [[ -n "$code" ]] && return 0 + sleep 1 + done + return 1 +} + +seed_state() { + docker exec "$name" cscli allowlists create node-live-allowlist -d "node live e2e" >/dev/null 2>&1 || true + docker exec "$name" cscli allowlists add node-live-allowlist 198.51.100.10 >/dev/null 2>&1 || true + + if docker exec "$name" cscli decisions add --scope Country --value FR --duration 1h --reason node-live-e2e >/dev/null 2>&1; then + country_seeded="1" + else + country_seeded="" + fi + + docker exec "$name" cscli decisions add --ip 198.18.0.10 --duration 1h --type ban --reason node-live-e2e >/dev/null 2>&1 || true + docker exec "$name" cscli decisions add --range 198.18.0.0/24 --duration 1h --type ban --reason node-live-e2e >/dev/null 2>&1 || true + docker exec "$name" cscli decisions add --ip 198.18.0.77 --duration 1h --type ban --reason node-live-e2e >/dev/null 2>&1 || true + docker exec "$name" cscli decisions add --ip 198.18.0.77 --duration 1h --type captcha --reason node-live-e2e >/dev/null 2>&1 || true +} + +run_suite() { + local mode="$1" url="$2" label="$3" strict="$4" ca="${5:-}" + local -a envs=( + CROWDSEC_LIVE=1 + "CROWDSEC_URL=$url" + "CROWDSEC_API_KEY=$key" + CROWDSEC_MACHINE_ID=node-live + "CROWDSEC_PASSWORD=$password" + "CROWDSEC_LAPI_VERSION=$version" + "CROWDSEC_MODE=$mode" + "CROWDSEC_LIVE_ALLOWLIST=node-live-allowlist" + CROWDSEC_LIVE_ALLOWLIST_IP=198.51.100.10 + "CROWDSEC_LIVE_COUNTRY=$country_seeded" + "CROWDSEC_STRICT_SSL=$strict" + ) + [[ -n "$ca" ]] && envs+=("NODE_EXTRA_CA_CERTS=$ca") + + echo "==> $version mode=$mode tls=$label" + if ( + cd "$repo_root" && + env "${envs[@]}" pnpm -F crowdsec-client exec vitest run tests/Live/live.test.ts --reporter=dot + ); then + echo "PASS $version mode=$mode tls=$label" + else + echo "FAIL $version mode=$mode tls=$label" + failures=$((failures + 1)) + fi +} + +index=0 +failures=0 + +for version in "${versions[@]}"; do + name="cs-live-test-${version//./-}" + port=$((base_port + index)) + tls_port=$((base_tls_port + index)) + index=$((index + 1)) + + echo "================================================================" + echo "==> $version (http $port, tls $tls_port)" + + if ! docker run -d --name "$name" --network "$network" -p "127.0.0.1:${port}:8080" \ + -e DISABLE_ONLINE_API=true \ + -e NO_HUB_UPGRADE=true \ + -e USE_WAL=true \ + -e LEVEL_INFO=false \ + -e LEVEL_WARN=true \ + -e DISABLE_AGENT=true \ + -e CROWDSEC_BYPASS_DB_VOLUME_CHECK=true \ + -e NO_HUB_UPDATE=true \ + "crowdsecurity/crowdsec:${version}" >/dev/null; then + echo "FAIL $version: docker run failed" + failures=$((failures + 1)) + continue + fi + containers+=("$name") + + if ! wait_http "http://127.0.0.1:${port}/health"; then + echo "FAIL $version: timeout waiting for the LAPI" >&2 + docker logs "$name" 2>&1 | tail -20 >&2 || true + failures=$((failures + 1)) + continue + fi + + key=$(docker exec "$name" cscli bouncers add node-live -o raw 2>/dev/null | tr -d '\r\n' || true) + password="node-live-password" + docker exec "$name" cscli machines add node-live -p "$password" --force -o raw >/dev/null 2>&1 || true + + if [[ -z "$key" ]]; then + echo "FAIL $version: bouncer key missing" + failures=$((failures + 1)) + continue + fi + + nginx_name="cs-tls-${version//./-}" + tls_ready=0 + if [[ "$tls_enabled" = "1" ]]; then + cat >"$tls_dir/nginx.conf" </dev/null && wait_tls "https://127.0.0.1:${tls_port}/health"; then + tls_ready=1 + containers+=("$nginx_name") + else + echo "warning: TLS proxy failed for $version" >&2 + docker logs "$nginx_name" 2>&1 | tail -10 >&2 || true + docker rm -f "$nginx_name" >/dev/null 2>&1 || true + fi + fi + + for mode in "${modes[@]}"; do + seed_state + run_suite "$mode" "http://127.0.0.1:${port}" "http" "true" + + if [[ "$tls_ready" -eq 1 ]]; then + seed_state + run_suite "$mode" "https://127.0.0.1:${tls_port}" "tls" "false" + + if [[ "$tls_strict" = "1" ]] && [[ "$mode" = "both" ]]; then + seed_state + run_suite "$mode" "https://127.0.0.1:${tls_port}" "tls-strict" "true" "$tls_dir/cert.pem" + fi + fi + done + + docker rm -f "$nginx_name" "$name" >/dev/null 2>&1 || true +done + +echo "================================================================" +if [[ "$failures" -eq 0 ]]; then + echo "All live runs passed." +else + echo "$failures live run(s) failed." +fi +exit "$failures" diff --git a/.github/scripts/lapi-matrix/versions.txt b/.github/scripts/lapi-matrix/versions.txt new file mode 100644 index 000000000..77c19d114 --- /dev/null +++ b/.github/scripts/lapi-matrix/versions.txt @@ -0,0 +1,11 @@ +v1.0.0 +v1.2.0 +v1.3.0 +v1.3.3 +v1.4.0 +v1.4.2 +v1.6.0 +v1.6.6 +v1.6.9 +v1.7.7 +v1.8.2 diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 7e41ac75d..56f3c2792 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -202,10 +202,10 @@ jobs: # PRs), reported to Code Scanning. Snyk's metered tests are reserved for the # release gate in snyk.yml, so this job does not consume Snyk quota. # - # Report-only on purpose: the lockfile also contains dev-only dependencies, - # and the policy treats dev-only advisories as out of scope because they are - # not shipped (docs/dependencies.md). The blocking SCA gate stays - # `pnpm audit --prod` (runtime) in the build job. + # Report-only on purpose: OSV scans the committed lockfile including + # devDependencies (only the `dev/` path is excluded). Dev-ledger advisories + # are visible here; the blocking SCA gate stays `pnpm audit --prod` (runtime) + # in the build job. permissions: actions: read contents: read diff --git a/.github/workflows/client-live-matrix.yml b/.github/workflows/client-live-matrix.yml new file mode 100644 index 000000000..9ee6a0859 --- /dev/null +++ b/.github/workflows/client-live-matrix.yml @@ -0,0 +1,143 @@ +name: Client Live Matrix + +on: + workflow_dispatch: + inputs: + versions: + description: "JSON array of LAPI tags; empty uses .github/scripts/lapi-matrix/versions.txt" + required: false + default: "" + modes: + description: "Space-separated credential modes (both watcher bouncer)" + required: false + default: "both watcher bouncer" + tls: + description: "1 = HTTP + TLS, 0 = HTTP only" + required: false + default: "1" + tls_strict: + description: "1 = also run the CA-validation TLS pass" + required: false + default: "1" + # A reduced matrix (oldest + latest tag, one mode, HTTP only) keeps PR + # feedback fast. The full matrix still runs on demand. + pull_request: + paths: + - "packages/crowdsec-client/**" + - ".github/scripts/lapi-matrix/**" + - ".github/workflows/client-live-matrix.yml" + +permissions: + contents: read + +concurrency: + group: client-live-matrix-${{ github.ref }} + cancel-in-progress: false + +jobs: + prepare: + runs-on: ubuntu-latest + outputs: + matrix: ${{ steps.matrix.outputs.matrix }} + modes: ${{ steps.matrix.outputs.modes }} + tls: ${{ steps.matrix.outputs.tls }} + tls_strict: ${{ steps.matrix.outputs.tls_strict }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - name: Build the version matrix + id: matrix + env: + VERSIONS: ${{ inputs.versions }} + VERSIONS_FILE: .github/scripts/lapi-matrix/versions.txt + MODES: ${{ inputs.modes }} + TLS: ${{ inputs.tls }} + TLS_STRICT: ${{ inputs.tls_strict }} + run: | + set -euo pipefail + if [ "$GITHUB_EVENT_NAME" = "pull_request" ]; then + modes="both" + tls="0" + tls_strict="0" + else + modes="${MODES:-both watcher bouncer}" + tls="${TLS:-1}" + tls_strict="${TLS_STRICT:-1}" + fi + normalized_modes="" + for mode in $modes; do + case "$mode" in + both | watcher | bouncer) ;; + *) echo "invalid mode '$mode' (expected both, watcher or bouncer)" >&2; exit 1 ;; + esac + normalized_modes="${normalized_modes:+$normalized_modes }$mode" + done + modes="$normalized_modes" + for value in "$tls" "$tls_strict"; do + case "$value" in + 0 | 1) ;; + *) echo "tls and tls_strict must be 0 or 1" >&2; exit 1 ;; + esac + done + matrix=$(python3 - <<'PY' + import json, os, sys + + raw = os.environ.get("VERSIONS", "").strip() + if raw: + try: + value = json.loads(raw) + except Exception as exc: + sys.exit(f"invalid versions JSON: {exc}") + else: + with open(os.environ["VERSIONS_FILE"], encoding="utf-8") as handle: + tags = [line.strip() for line in handle if line.strip() and not line.lstrip().startswith("#")] + if not tags: + sys.exit("the curated versions file is empty") + value = [tags[0], tags[-1]] if os.environ.get("GITHUB_EVENT_NAME") == "pull_request" else tags + + if not isinstance(value, list) or not all(isinstance(item, str) and item for item in value): + sys.exit("versions must be a JSON array of non-empty strings") + print(json.dumps({"version": value}, separators=(",", ":"))) + PY + ) + { + echo "matrix=$matrix" + echo "modes=$modes" + echo "tls=$tls" + echo "tls_strict=$tls_strict" + } >> "$GITHUB_OUTPUT" + + live: + name: live (${{ matrix.version }}) + needs: prepare + runs-on: ubuntu-latest + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: ${{ fromJson(needs.prepare.outputs.matrix) }} + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + + - name: Install Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 + with: + node-version: 24 + + - name: Install pnpm + uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6 + with: + run_install: false + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Run live client E2E + env: + MODES: ${{ needs.prepare.outputs.modes }} + TLS: ${{ needs.prepare.outputs.tls }} + TLS_STRICT: ${{ needs.prepare.outputs.tls_strict }} + # The matrix value reaches the script through the environment and is + # passed as a quoted argument. It is never textually interpolated into + # the run block, so a workflow_dispatch value cannot inject syntax. + LAPI_VERSION: ${{ matrix.version }} + run: ./.github/scripts/lapi-matrix/run-live-tests.sh "$LAPI_VERSION" diff --git a/AGENTS.md b/AGENTS.md index 0dd2b31ef..a82b42516 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,8 +10,9 @@ truth; this file says what to run and where to look. - `packages/crowdsec-http-middleware` — HTTP middleware, scenarios, `IpDecisionDB`. - `packages/crowdsec-client-scenarios` — detection scenarios. - `packages/crowdsec-mcp` — MCP server (alerts, decisions, allowlists). -- `docs/` — `architecture.md` (design and threat model), `dependencies.md` - (dependency and finding policy), `releases.md` (release verification). +- `docs/` — `architecture.md` (design and threat model), `api-compatibility.md` + (LAPI version matrix and fallbacks), `dependencies.md` (dependency and finding + policy), `releases.md` (release verification). - `GOVERNANCE.md`, `SECURITY.md`, `SUPPORT.md`, `CONTRIBUTING.md` — governance, security, support and contribution rules. - `.github/workflows/` — CI, CodeQL, release, Docker and end-to-end tests. @@ -60,6 +61,9 @@ pnpm audit --prod --audit-level=high ## Keep in sync - `docs/architecture.md` — components, actors, attack surface, threat model. +- `docs/api-compatibility.md` — LAPI versions, feature matrix, probes and + fallbacks. Update it when a package starts using a new LAPI endpoint, query + parameter or response field. - `docs/dependencies.md` — dependency, SCA/SAST thresholds, VEX. - `docs/releases.md` — how to verify a release. - `GOVERNANCE.md` — maintainers, roles, access. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7cefdfab7..ec700ab0f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -5,7 +5,7 @@ Thanks for contributing to node-crowdsec. ## Requirements - Node.js >= 24 -- pnpm >= 12 (the version is pinned in `packageManager`) +- pnpm, pinned to `pnpm@12.11.2` through `packageManager` (Corepack uses it automatically) ## Setup diff --git a/docs/agent-setup-guide.md b/docs/agent-setup-guide.md index 6f79d1c57..ebc34bdc5 100644 --- a/docs/agent-setup-guide.md +++ b/docs/agent-setup-guide.md @@ -126,8 +126,8 @@ Ask : is it acceptable that a brand-new ban takes up to `pollingInterval` > **Recommended** : `company` (up to `/24`). Real-world malicious traffic is almost always single IPs (`/32`). Larger blocks -follow who owns them : an abusive datacenter rack is a `/24`, an entire national -block is `/8` - banning a whole country is almost never intended. +follow who owns them : an abusive datacenter rack is a `/24`, a national block +is `/16` - banning a whole country is almost never intended. - `resident` : only single IPs (`/32`). Most restrictive on false positives. - `company` (recommended) : up to `/24` (an ISP / hosting provider block). diff --git a/docs/api-compatibility.md b/docs/api-compatibility.md new file mode 100644 index 000000000..a83785f7f --- /dev/null +++ b/docs/api-compatibility.md @@ -0,0 +1,239 @@ +# CrowdSec LAPI version compatibility + +Records the LAPI version each client capability requires and the behaviour when +the connected LAPI is older. Update it when a package uses a new endpoint, +parameter or response field. + +Tested range: `v1.0.0` … `v1.8.x`; the exact live matrix is the curated list in +`.github/scripts/lapi-matrix/versions.txt`. + +## Why detection is needed + +The LAPI does not expose a queryable version: `GET /health` is unversioned, +`GET /v1/heartbeat` only returns `200` (from v1.4.0), and +`LapiMetrics.features` (v1.8.2) is a metrics payload, not a capability list. The +client must therefore be told the version, probe, or fail lazily. + +## Failure semantics + +| Situation | Status | Body | +| --- | --- | --- | +| Unknown route | `404` | `Page or Method not found` | +| Unknown method | `405` | method not allowed | +| Unknown filter parameter | `500` | database filter error | +| Alert delete from a non-trusted host | `403` | restricted to the LAPI host / `TrustedIPs` | +| Unknown JSON field | `2xx` | silently ignored | +| Filter not read by the handler | `2xx` | ignored, results wider than requested | + +Unknown filters are **not** `400`. Route-`404` and object-`404` differ only by +message; never treat `/not found/i` as "object not found" without checking it. + +## Capability matrix + +`code` is the first release where the behaviour works; `swagger` is when it was +documented. Gate on `code`. + +### Endpoints + +| Capability | Code | If older | +| --- | --- | --- | +| `POST /v1/watchers/login`, `POST /v1/watchers` | 1.0.0 | — | +| `registration_token` in registration | 1.6.3 | ignored silently | +| `GET /v1/heartbeat` | 1.4.0 | `404`, the client disables the heartbeat loop | +| `DELETE /v1/watchers/self` | 1.6.9 | `404` | +| `GET /v1/decisions/stream`, `GET /v1/decisions` | 1.0.0 | — | +| `DELETE /v1/decisions`, `DELETE /v1/decisions/{id}` | 1.0.0 | — | +| `POST /v1/alerts`, `GET /v1/alerts[/{id}]`, `HEAD /v1/alerts`, `HEAD /v1/decisions` | 1.0.0 | — | +| `DELETE /v1/alerts` | 1.0.0 | `403` from a remote host | +| `DELETE /v1/alerts/{id}` | 1.4.2 | `405` before 1.4.2, `403` remotely | +| `GET /v1/allowlists`, `GET /v1/allowlists/{name}`, `GET /v1/allowlists/check/{value}` | 1.6.6 | `404` | +| `POST /v1/allowlists/check` (bulk) | 1.6.9 | `404`/`405` | + +### Query parameters + +| Parameter | Endpoint(s) | Code | If older | +| --- | --- | --- | --- | +| `contains` | `GET/DELETE /decisions`, `GET/DELETE /alerts` | 1.0.3 | `500` | +| `scopes` (stream) | `GET /decisions/stream` | 1.1.0 | silently ignored | +| `origin` | `GET /alerts` | 1.3.0 | `500` | +| `origins`, `scenarios_containing`, `scenarios_not_containing` | `GET /decisions`, stream | 1.3.3 | `500` on `/decisions`, ignored on stream | +| `scenario` | `DELETE /decisions` | 1.4.2 | `500` | +| `kind` | `GET /alerts` | 1.7.7 | `500` | +| `scope` (singular, list) | `GET /decisions` | 1.0.0, ignored 1.3.3–1.6.0, restored 1.6.1 | silently ignored (set too wide) | +| `scope` (singular, delete) | `DELETE /decisions` | 1.0.0, removed 1.3.3 | `500`; use `scopes` | +| `scopes` (delete) | `DELETE /decisions` | 1.3.3 | `500`; use `scope` | +| `alert_source` | `DELETE /alerts` | never implemented | `500` on every version; use `origin` | +| `simulated` | `GET /decisions` | 1.0.0 | ignored; simulated decisions stay excluded unless `true` | +| `with_content` | `GET /allowlists[/{name}]` | 1.6.6 | — | + +`GET /v1/decisions` silently ignores the *known* `scope` parameter on +1.3.3–1.6.0, unlike `/v1/alerts` and the DELETE routes. A request that relies on +it therefore returns a wider result instead of an error. Unknown parameters are +rejected with the `500` listed above. Because `scope` is ignored on that range, +the MCP `list_decisions` tool routes a `scope` query to the watcher alert scan +whenever watcher credentials are available. + +`Decisions.delete` maps `scope`/`scopes` through the `decisionScopesDelete` +capability (1.3.3), then falls back on the specific `500 invalid filter` and +caches the result. `CROWDSEC_LAPI_VERSION` makes the choice deterministic. + +### Response fields + +| Field | Model | Code | If older | +| --- | --- | --- | --- | +| `until` | `Decision` | 1.3.0 | `undefined`; compute `endAt` from `duration` | +| `uuid` | `Alert`, `Decision` | 1.5.0 | `undefined` | +| `kind` | `Alert` | 1.7.7 | `undefined` | +| `simulated` | `Decision` | always stored | `/v1/decisions` excludes simulated by default and omits the field | +| `deleted` | `DecisionsStreamResponse` | 1.1.0 (optional) | absent or `null` on old releases | +| `features` | `LapiMetrics` | 1.8.2 | `undefined` | + +`/v1/decisions` may omit `until` even when the model has it (observed on 1.8.1). + +## Write/delete asymmetry + +Creating a decision works on every supported LAPI (`POST /v1/alerts`, 1.0.0). +Deleting it is gated, and alert deletion is restricted to the LAPI host: + +| Delete path | Minimum | Notes | +| --- | --- | --- | +| `DELETE /v1/decisions/{id}` | 1.0.0 | requires the decision id | +| `DELETE /v1/decisions?scope=` | 1.0.0 | singular, removed in 1.3.3 | +| `DELETE /v1/decisions?scopes=` | 1.3.3 | plural, learned by `Decisions.delete` | +| `DELETE /v1/decisions?scenario=` | 1.4.2 | | +| `DELETE /v1/alerts/{id}` | 1.4.2 | | +| `DELETE /v1/alerts` | 1.0.0 | LAPI host / `TrustedIPs` only | + +Deletes filtered by `ip`/`range` send `contains=false` to mean "decisions +contained within the value". `Alerts.delete` and `Decisions.delete` add this +default automatically; pass `contains: true` to opt into the wider LAPI +behaviour. That parameter needs 1.0.3: on 1.0.0-1.0.2 the request fails instead +of silently widening the delete to a Range decision that contains the value. + +A client can therefore **create a decision it cannot delete**: the decision +stays active until its `duration` expires. Mitigations: use a short `duration`, +delete by decision id, or gate creation on `supports('alertDeleteById')` / +`supports('decisionScenarioDelete')`. + +## Handling an unsupported capability + +Apply this order. Never silently drop a filter that changes the meaning of a +write. + +1. **Declare the version.** `lapiVersion` resolves every capability locally, + without a request. A capability known to be unsupported always throws + `FeatureNotSupportedError`; `strictCapabilities` additionally makes + capabilities that could not be verified throw `LapiVersionUnknownError`. +2. **Probe after login and cache.** `detectCapabilities: true` probes once after + login; the result is cached per client instance. Calling + `detectCapabilities()` again re-probes and merges the result, except when a + version was declared (it returns immediately); use + `detectCapability(name, { force: true })` to verify a single capability. +3. **Fall back** to an equivalent endpoint or a narrower request when one + exists (see the fallback catalogue). +4. **Raise a typed error.** `FeatureNotSupportedError` + (`EErrorsCodes.FEATURE_NOT_SUPPORTED`) carries `capability`, + `minimumVersion` and `detectedVersion`. In strict mode an unverifiable + capability throws `LapiVersionUnknownError`. +5. **Degrade explicitly.** Fail or emit a warning; do not let the server ignore + a filter silently. + +```ts +const watcher = new WatcherClient({ + url: 'https://lapi:8080', + auth: { machineID, password }, + detectCapabilities: true, // probe after login + // lapiVersion: '1.6.6', // or declare it: no probe is sent + // strictCapabilities: true // fail when a capability is unknown +}); + +await watcher.login(); + +watcher.getCapabilities(); // { source: 'probed', values: { allowlists: true, ... } } +watcher.supports('allowlists'); // true | false | undefined +watcher.getProbableVersion(); // { minVersion: '1.6.9', belowVersion: '1.7.7' } +``` + +Detection propagates through the version ordering: seeing `allowlists` work +implies every capability up to 1.6.6; seeing it fail implies everything from +1.6.6 upwards is unavailable. A value learned from a real request (`learn`) is +**not** propagated: a single rejected request must not disable unrelated +features. It sets `source` to `observed` when no probe has run and leaves +`probed` in place otherwise; it can correct a value that was only inferred, but +never a declared or explicitly probed one. Capabilities that no probe can reach +(mainly `alertDeleteById` and `decisionScenarioDelete`) stay `undefined` unless +the version is declared. The client never sends a `DELETE` as a probe. + +## Probe catalogue + +| Capability | Probe | Interpretation | +| --- | --- | --- | +| `contains` | `GET /v1/decisions?ip=192.0.2.1&contains=false` | `2xx` supported, `500` not | +| decisions `origins` | `GET /v1/decisions?origins=node-crowdsec-probe` | `2xx` supported, `500` not | +| alert `origin` | `GET /v1/alerts?origin=cscli&limit=1` | `2xx` supported, `500` not | +| heartbeat | `GET /v1/heartbeat` | `2xx` supported, `404` not | +| allowlists | `GET /v1/allowlists` | not `404` supported | +| bulk allowlist check | `POST /v1/allowlists/check` `{"targets":[]}` | `400`/`2xx` supported, `404`/`405` not | +| `kind` filter | `GET /v1/alerts?kind=cscli&limit=1` | `2xx` supported, `500` not | + +A `401` on any probe is inconclusive (the caller is not authenticated), and is +never read as proof that a route or filter exists; a `403` still proves the +route exists. This keeps an unauthenticated `detectCapability` call from marking +every endpoint as supported. + +A watcher JWT cannot reach decision routes and a bouncer key cannot reach alert +routes, so each client probes its own set. A bouncer therefore cannot detect +`allowlists`, `kind` or `heartbeat`; with both credentials, declare +`lapiVersion` (the two clients do not share state). + +The bouncer probes are selective because `/v1/decisions` has no `limit`: an +unfiltered probe would download the whole decision set twice. Do not use a short +timeout instead — it does not cancel the LAPI work and turns a slow deployment +into a false negative. + +Before v1.6.9, `POST /v1/allowlists/check` answers `405` because it shares a +prefix with the single-value route. + +## Fallback catalogue + +| Capability | Fallback | +| --- | --- | +| `contains` | Only send it with `ip`/`range`, so plain listings work on 1.0.0. Writes deliberately fail on `<1.0.3` instead of widening the delete. | +| `kind` filter | Typed error, or drop the filter with an explicit warning. Never on delete. | +| allowlist pre-check (`ban_ip`) | On `404`/`405` or `FeatureNotSupportedError`, skip the pre-check and continue. Implemented in `ensureBanAllowed`. | +| bulk allowlist check | On `404`/`405`, iterate `GET /v1/allowlists/check/{value}`. Implemented in `Allowlists.bulkCheck`; the fallback only returns allowlisted targets and labels the allowlist name as `unknown allowlist (matched item: ...)` because the single-value route does not expose it. | +| decision `origins`/`scenarios_*` | Typed error, or query alerts instead. | +| `DELETE /decisions?scenario=` | Gate on 1.4.2, or search alerts then delete by id. | +| stream `scopes` | Typed error when the capability is known. No automatic restart: declare `lapiVersion` or omit `scopes` on old LAPIs. | +| `DELETE /alerts/{id}` | `404`/`405`: typed error when the capability is known (declared/probed), otherwise the raw HTTP error; `403`: error stating host-only. | +| `decision_type` on `DELETE /alerts` | On a `400`/`500` "unknown filter", the MCP searches alerts with `decision_type` then deletes by id. | +| alert `simulated` | On a `400`/`500` "unknown filter", the MCP retries the alert search without it (simulated decisions are omitted). Never dropped when the caller asked to exclude simulated decisions (`simulated: false`). | +| heartbeat | On `404`, disable the loop and log once. | +| `Decision.until` | Compute from `duration`. | + +## Live validation + +`.github/workflows/client-live-matrix.yml` runs +`packages/crowdsec-client/tests/Live/live.test.ts` against the supported tags in +Docker (`both`, `watcher`, `bouncer`, HTTP and TLS). The suite asserts detected +capabilities against each tag's minimum and exercises the gated methods. +Pull requests touching the client run a reduced matrix (oldest and latest tag, +`both` mode, HTTP only); the full matrix runs on demand via `workflow_dispatch`. +`packages/crowdsec-client` exposes it as `pnpm test:live:matrix`. + +## JSDoc convention + +A public method or option that depends on a LAPI capability documents its +minimum with `@since CrowdSec X.Y.Z`; use the runtime version from the matrix, +not the swagger version. Add `@remarks` when the capability is probed and +`@throws` when it can fail for a non-version reason. + +## Known limitations + +1. The instance `WatcherClient.deleteWatcher()` must be called after `login()` + because `/v1/watchers/self` is JWT-only. The static + `WatcherClient.deleteWatcher(options)` helper uses Basic Auth and therefore + fails where the LAPI enforces JWT. +2. Route-`404` and object-`404` are only distinguishable by message. +3. `Alerts.delete({})` / `Decisions.delete({})` with an empty filter delete + everything; the MCP guards `all=true`, the client methods do not. diff --git a/docs/architecture.md b/docs/architecture.md index d9b6872ab..81cc27084 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -8,9 +8,9 @@ reviewed whenever a package, tool or external interface is added. | Package | Responsibility | | --- | --- | -| `crowdsec-client` | CrowdSec Local API (LAPI) client: bouncer endpoints (`/v1/decisions`) and watcher endpoints (`/v1/alerts`, `/v1/allowlists`). | -| `crowdsec-http-middleware` | HTTP middleware that queries or caches decisions and blocks or flags requests; includes scenarios and the `IpDecisionDB` store. | -| `crowdsec-client-scenarios` | Detection scenarios (for example the `X-Forwarded-For` checker) built on the middleware. | +| `crowdsec-client` | CrowdSec Local API (LAPI) client: bouncer endpoints (`/v1/decisions`) and watcher endpoints (`/v1/alerts`, `/v1/allowlists`), with version capability detection and typed `FeatureNotSupportedError` guards. | +| `crowdsec-http-middleware` | HTTP middleware that queries or caches decisions and exposes the decision on the request (the application blocks or flags it); includes the `IpDecisionDB` store and the watcher middleware that runs scenarios. | +| `crowdsec-client-scenarios` | Detection and IP-extraction scenarios (for example the `X-Forwarded-For` checker) consumed by the watcher middleware or standalone. | | `crowdsec-mcp` | Model Context Protocol server exposing alerts, decisions and allowlists to MCP clients over stdio or HTTP. | ## Actors @@ -25,9 +25,13 @@ reviewed whenever a package, tool or external interface is added. ## Actions and data flows -1. The operator configures a bouncer or watcher credential. +1. The operator configures a bouncer API key and/or watcher credentials. The + MCP server may use both at once: the bouncer key serves the fast + `/v1/decisions` path, the watcher serves alerts, allowlists and writes. 2. `crowdsec-client` authenticates to the LAPI over HTTPS and fetches decisions - (bouncer) or alerts and allowlists (watcher). + (bouncer) or alerts and allowlists (watcher). Capabilities are resolved from + a declared `lapiVersion`, optional post-login probes, or lazily; unsupported + features raise a typed error instead of being silently ignored. 3. The middleware answers each request from its in-memory decision store (`IpDecisionDB`), with an optional live mode that queries the LAPI. 4. Scenarios inspect request metadata (headers, client IP) to detect abuse. @@ -48,8 +52,10 @@ reviewed whenever a package, tool or external interface is added. | Asset | Threat | Mitigation | | --- | --- | --- | -| CrowdSec API keys | Leakage through logs, errors or the repository | Credentials are read from the environment or configuration only, redacted from MCP tool output and errors, and the repository has secret scanning and push protection enabled | -| Decisions and allowlists | Poisoned or unauthorised writes | Read-only by default; write tools are opt-in per tool; destructive tools require an additional flag and, over HTTP, a service token; bans pre-check allowlists and are capped by a maximum duration | +| CrowdSec API keys | Leakage through logs, errors or the repository | Credentials are read from the environment, a `_FILE` secret or configuration only, redacted from MCP tool output and errors, and the repository has secret scanning and push protection enabled | +| Version mismatch | A request the connected LAPI does not understand is silently widened or fails with a raw 500 | Capabilities are declared or probed; gated methods raise `FeatureNotSupportedError`, and `docs/api-compatibility.md` records the fallbacks | +| Passthrough credentials | A reverse proxy injects a privileged identity and a caller adds its own header, gaining the union | Passthrough trusts every `X-CrowdSec-*` header it receives and cannot tell a proxy-injected header from a caller-supplied one; operators must strip incoming `X-CrowdSec-*` at the proxy (see "Passthrough credentials" in the MCP README) | +| Decisions and allowlists | Poisoned or unauthorised writes | Read-only by default; write tools require `CROWDSEC_MCP_READONLY=false`; `delete_alerts` additionally requires `CROWDSEC_MCP_ENABLE_ALERT_DELETE=true` and, over HTTP, a service token unless explicitly overridden; bans pre-check allowlists and are capped by a maximum duration | | Client IP determination | Spoofing through `X-Forwarded-For` | Only configured `trustedProxies` are honoured, with normalisation of IPv4-mapped (`::ffff:`) addresses | | Transport | Man-in-the-middle or tampering | HTTPS with certificate verification enabled by default | | Release artifacts | Supply-chain tampering | CI-only publishing, npm provenance, cosign signatures and SLSA provenance on releases, least-privilege workflow tokens, pinned actions and a digest-pinned base image | @@ -76,7 +82,11 @@ added, and at least once per release. - The LAPI and its credentials are trusted; a compromised LAPI can return arbitrary decisions. -- The MCP server inherits the privileges of the credentials it is given. +- The MCP server inherits the privileges of the credentials it is given. When + both credentials are configured, it holds the union of their rights. +- Capability state is per client instance: a watcher and a bouncer configured + together do not share what they detected, so the estimated version is coarser + unless `lapiVersion` is declared. - Denial of service against an application remains possible if the middleware is exposed without rate limiting or a reverse proxy. - The security assessment is revisited when a new package, tool or external diff --git a/docs/compliance.md b/docs/compliance.md index c580a7b53..88b6200c7 100644 --- a/docs/compliance.md +++ b/docs/compliance.md @@ -22,7 +22,9 @@ All of these are expected to pass before a pull request is merged. | Area | Mechanism | Where | | --- | --- | --- | -| Build, tests, types, lint | CI matrix (4 packages x Node 24 / lts / latest) | `.github/workflows/CI.yml` | +| Build, tests | CI matrix (4 packages x Node 24 / lts / latest) | `.github/workflows/CI.yml` | +| Types, format | `quality` job (single Node lts run) | `.github/workflows/CI.yml` | +| Lint | `metrics` job (`check=true`) | `.github/workflows/CI.yml` | | Static analysis (SAST) | CodeQL `Analyze (javascript)` | `CI.yml`, `codeql.yml` | | Dependency analysis (SCA) | `pnpm audit --prod` (blocking), OSV-Scanner (report-only) on PR/push, Snyk weekly + release gate (shipped components) | `CI.yml`, `snyk.yml`, `release.yml` | | Secrets | GitHub secret scanning and push protection | GitHub repository settings | @@ -79,5 +81,5 @@ changes. | Item | Why N/A | Re-check when | | --- | --- | --- | | OSPS-QA-04.01 / QA-04.02 (multiple repositories) | Single monorepo | A second repository is added | -| OSPS-BR-01.04 (collaborator input in CI) | No workflow accepts free-form collaborator input | A `workflow_dispatch` input is added | +| OSPS-BR-01.04 (collaborator input in CI) | `workflow_dispatch` inputs are enumerated (versions/modes/TLS) and validated; no free-form command input | A free-form or shell-interpolated input is added | | OSPS-VM-04.02 (VEX) | No shipped component is affected today (`pnpm audit --prod` is clean) | A runtime advisory is assessed as non-exploitable | diff --git a/docs/dependencies.md b/docs/dependencies.md index a5f16f268..4e8f657c1 100644 --- a/docs/dependencies.md +++ b/docs/dependencies.md @@ -17,13 +17,13 @@ dependencies. ## Obtaining and building -- pnpm is the only package manager (pinned through the `packageManager` field, - pnpm >= 12). +- pnpm is the only package manager, pinned to `pnpm@12.11.2` through the + `packageManager` field (Corepack uses that exact version). - `pnpm-lock.yaml` is committed. CI installs with `pnpm install --frozen-lockfile`, and any dependency change must include the matching lockfile update. - Node.js >= 24 is required (see the `engines` field). -- Builds use esbuild and TypeScript and emit to `dist/`; build output is not +- Builds use esbuild and TypeScript and emit to `lib/`; build output is not committed. ## Tracking and updating diff --git a/docs/releases.md b/docs/releases.md index a61b03a02..0d169af5d 100644 --- a/docs/releases.md +++ b/docs/releases.md @@ -7,7 +7,7 @@ after CI and the Snyk gate pass. 1. Bump the version in the package's `package.json` and merge it to `main`. 2. Create a **draft** release whose tag is `/v` - (e.g. `crowdsec-mcp/v0.0.7`), with the release notes. + (e.g. `crowdsec-mcp/v`), with the release notes. 3. Trigger the workflow (no input: it picks up the single open draft): ```bash @@ -35,9 +35,10 @@ the only path. Every release is published from CI. A release page contains: -- the npm tarball, e.g. `crowdsec-mcp-0.0.6.tgz`; -- its keyless cosign signature, `crowdsec-mcp-0.0.6.tgz.sigstore`; -- its SLSA build provenance, `crowdsec-mcp-0.0.6.tgz.intoto.jsonl`. +- the npm tarball, e.g. `crowdsec-mcp-.tgz`; +- its keyless cosign signature, `crowdsec-mcp-.tgz.sigstore`; +- its SLSA build provenance, `crowdsec-mcp-.tgz.intoto.jsonl`; +- its CycloneDX SBOM (`*.cdx.json`). Container images are published separately with build provenance and an SBOM; see the image documentation for their digests. @@ -47,8 +48,8 @@ see the image documentation for their digests. The tarball hash can be checked against the digest recorded by npm: ```bash -sha256sum crowdsec-mcp-0.0.6.tgz -npm view crowdsec-mcp@0.0.6 dist.integrity +sha256sum crowdsec-mcp-.tgz +npm view crowdsec-mcp@ dist.integrity ``` For an installed dependency set, `npm audit signatures` verifies the registry @@ -62,17 +63,17 @@ release workflow. Verify it with cosign, checking both the certificate identity ```bash cosign verify-blob \ - --bundle crowdsec-mcp-0.0.6.tgz.sigstore \ + --bundle crowdsec-mcp-.tgz.sigstore \ --certificate-identity-regexp 'https://github.com/thib3113/node-crowdsec/.github/workflows/release.yml@refs/tags/.*' \ --certificate-oidc-issuer https://token.actions.githubusercontent.com \ - crowdsec-mcp-0.0.6.tgz + crowdsec-mcp-.tgz ``` The SLSA provenance records the same identity and the commit that produced the artifact: ```bash -gh attestation verify crowdsec-mcp-0.0.6.tgz \ +gh attestation verify crowdsec-mcp-.tgz \ --repo thib3113/node-crowdsec ``` diff --git a/examples/express-bouncer-cjs/src/index.js b/examples/express-bouncer-cjs/src/index.js index 34ad926d5..f5bf15969 100644 --- a/examples/express-bouncer-cjs/src/index.js +++ b/examples/express-bouncer-cjs/src/index.js @@ -44,14 +44,14 @@ const main = async () => { //listen for added decisions stream.on('added', (decision) => { - if (!decisions.find((d) => d.value === d.value)) { + if (!decisions.find((d) => d.value === decision.value && d.type === decision.type)) { decisions.push(decision); } }); //listen for deleted decisions stream.on('deleted', (decision) => { - decisions = decisions.filter(({ value }) => value !== decision.value); + decisions = decisions.filter(({ value, type }) => value !== decision.value || type !== decision.type); }); //start the stream diff --git a/examples/express-bouncer/src/index.ts b/examples/express-bouncer/src/index.ts index db04de3e3..1a550a96d 100644 --- a/examples/express-bouncer/src/index.ts +++ b/examples/express-bouncer/src/index.ts @@ -44,14 +44,14 @@ const main = async () => { //listen for added decisions stream.on('added', (decision) => { - if (!decisions.find((d) => d.value === decision.value)) { + if (!decisions.find((d) => d.value === decision.value && d.type === decision.type)) { decisions.push(decision); } }); //listen for deleted decisions stream.on('deleted', (decision) => { - decisions = decisions.filter(({ value }) => value !== decision.value); + decisions = decisions.filter(({ value, type }) => value !== decision.value || type !== decision.type); }); //start the stream diff --git a/llms.txt b/llms.txt index bfb6779dd..844d7a01e 100644 --- a/llms.txt +++ b/llms.txt @@ -1,43 +1,55 @@ # node-crowdsec -> Node.js client for the CrowdSec Local API (LAPI), with an HTTP bouncer/watcher middleware, detection scenarios and a Model Context Protocol (MCP) server. +> Node.js client for the CrowdSec Local API (LAPI): bouncer/watcher client, HTTP middleware, detection scenarios and a Model Context Protocol (MCP) server. Node.js 24 or newer. -## Packages +All links point to raw Markdown so an agent can read them directly. The GitHub +wiki is for humans only and is intentionally not indexed here. -- [crowdsec-client](https://github.com/thib3113/node-crowdsec/blob/main/packages/crowdsec-client/README.md): CrowdSec LAPI client for bouncers and watchers (decisions, alerts, allowlists, streams, TLS/mTLS). -- [crowdsec-http-middleware](https://github.com/thib3113/node-crowdsec/blob/main/packages/crowdsec-http-middleware/readme.md): HTTP middleware that checks each request's IP against CrowdSec decisions and exposes `req.decision`. -- [crowdsec-client-scenarios](https://github.com/thib3113/node-crowdsec/blob/main/packages/crowdsec-client-scenarios/readme.md): optional detection scenarios (X-Forwarded-For, allowlist, HTTP enrichment, MaxMind). -- [crowdsec-mcp](https://github.com/thib3113/node-crowdsec/blob/main/packages/crowdsec-mcp/README.md): Model Context Protocol server exposing decisions, alerts and allowlists to an LLM. +## Project -## Documentation +- [README](https://raw.githubusercontent.com/thib3113/node-crowdsec/main/readme.md): overview, features and package list. +- [API compatibility](https://raw.githubusercontent.com/thib3113/node-crowdsec/main/docs/api-compatibility.md): LAPI version matrix, failure modes, probes and fallbacks. +- [Architecture and threat model](https://raw.githubusercontent.com/thib3113/node-crowdsec/main/docs/architecture.md): components, data flows, security assessment. +- [Agent setup guide](https://raw.githubusercontent.com/thib3113/node-crowdsec/main/docs/agent-setup-guide.md): configure the HTTP middleware with an agent. -- [Guides and usage documentation](https://github.com/thib3113/node-crowdsec/wiki): authentication, bouncer/watcher setup, performance notes. -- [API reference](https://thib3113.github.io/node-crowdsec/): generated Typedoc API documentation. -- [AI agent setup guide](https://github.com/thib3113/node-crowdsec/blob/main/docs/agent-setup-guide.md): configure the HTTP middleware with an AI agent. -- [Architecture decisions](https://github.com/thib3113/node-crowdsec/blob/main/docs/adr/README.md): ADRs, including the bouncer decision store. -- [Security policy](https://github.com/thib3113/node-crowdsec/blob/main/SECURITY.md): private vulnerability reporting. +## crowdsec-client -## Examples +- [README](https://raw.githubusercontent.com/thib3113/node-crowdsec/main/packages/crowdsec-client/README.md): install, compatibility, capability detection, type overrides. +- [API reference](https://thib3113.github.io/node-crowdsec/): generated Typedoc HTML. -- [express-bouncer](https://github.com/thib3113/node-crowdsec/tree/main/examples/express-bouncer): Express + bouncer (TypeScript, ESM). -- [express-bouncer-cjs](https://github.com/thib3113/node-crowdsec/tree/main/examples/express-bouncer-cjs): the same example in CommonJS. -- [express-web-parser](https://github.com/thib3113/node-crowdsec/tree/main/examples/express-web-parser): watcher that reports bad user-agents. +## crowdsec-http-middleware -## Repository +- [README](https://raw.githubusercontent.com/thib3113/node-crowdsec/main/packages/crowdsec-http-middleware/readme.md): install, options, debug. +- [Scenarios README](https://raw.githubusercontent.com/thib3113/node-crowdsec/main/packages/crowdsec-client-scenarios/readme.md): scenario options used by the middleware. +- [Agent setup guide](https://raw.githubusercontent.com/thib3113/node-crowdsec/main/docs/agent-setup-guide.md): interview-style configuration. + +## crowdsec-client-scenarios + +- [README](https://raw.githubusercontent.com/thib3113/node-crowdsec/main/packages/crowdsec-client-scenarios/readme.md): `XForwardedForChecker`, `AllowListEnricher`, `HTTPEnricher`, `MaxMindEnricher`. + +## crowdsec-mcp -- [README](https://github.com/thib3113/node-crowdsec/blob/main/readme.md): project overview and features. -- [Contributing](https://github.com/thib3113/node-crowdsec/blob/main/CONTRIBUTING.md) -- [Support](https://github.com/thib3113/node-crowdsec/blob/main/SUPPORT.md) -- [License (MIT)](https://github.com/thib3113/node-crowdsec/blob/main/LICENSE) +- [README](https://raw.githubusercontent.com/thib3113/node-crowdsec/main/packages/crowdsec-mcp/README.md): install, environment variables, CLI, tools, limits. +- [API compatibility](https://raw.githubusercontent.com/thib3113/node-crowdsec/main/docs/api-compatibility.md): version-gated filters and write/delete asymmetry. +- [Docker Hub description](https://raw.githubusercontent.com/thib3113/node-crowdsec/main/packages/crowdsec-mcp/DOCKERHUB.md): image usage. -## Source layout +## Examples + +- [express-bouncer](https://raw.githubusercontent.com/thib3113/node-crowdsec/main/examples/express-bouncer/readme.md): Express + bouncer (TypeScript, ESM). +- [express-bouncer-cjs](https://raw.githubusercontent.com/thib3113/node-crowdsec/main/examples/express-bouncer-cjs/readme.md): the same example in CommonJS. +- [express-web-parser](https://raw.githubusercontent.com/thib3113/node-crowdsec/main/examples/express-web-parser/readme.md): watcher that reports bad user-agents. + +## Repository -- [packages/](https://github.com/thib3113/node-crowdsec/tree/main/packages): npm packages. -- [examples/](https://github.com/thib3113/node-crowdsec/tree/main/examples): runnable examples. -- [docs/](https://github.com/thib3113/node-crowdsec/tree/main/docs): guides and ADRs. +- [Contributing](https://raw.githubusercontent.com/thib3113/node-crowdsec/main/CONTRIBUTING.md) +- [Security policy](https://raw.githubusercontent.com/thib3113/node-crowdsec/main/SECURITY.md) +- [Support](https://raw.githubusercontent.com/thib3113/node-crowdsec/main/SUPPORT.md) +- [Agent instructions](https://raw.githubusercontent.com/thib3113/node-crowdsec/main/AGENTS.md): repository conventions for coding agents. +- [License (MIT)](https://raw.githubusercontent.com/thib3113/node-crowdsec/main/LICENSE) ## Optional - [npm: crowdsec-client](https://www.npmjs.com/package/crowdsec-client) - [npm: crowdsec-http-middleware](https://www.npmjs.com/package/crowdsec-http-middleware) - [npm: crowdsec-client-scenarios](https://www.npmjs.com/package/crowdsec-client-scenarios) +- [npm: crowdsec-mcp](https://www.npmjs.com/package/crowdsec-mcp) diff --git a/package.json b/package.json index 73451d730..65362f885 100644 --- a/package.json +++ b/package.json @@ -15,8 +15,7 @@ "name": "Thibaut Severac" }, "engines": { - "node": ">=24", - "pnpm": ">=9" + "node": ">=24" }, "license": "UNLICENSED", "scripts": { diff --git a/packages/crowdsec-client-scenarios/readme.md b/packages/crowdsec-client-scenarios/readme.md index bce1bf37c..dab40670c 100644 --- a/packages/crowdsec-client-scenarios/readme.md +++ b/packages/crowdsec-client-scenarios/readme.md @@ -30,6 +30,9 @@ This package provides optional CrowdSec detection scenarios for [crowdsec-http-middleware](https://www.npmjs.com/package/crowdsec-http-middleware) and compatible middlewares. Node.js >= 24 is required. +> **For LLMs:** give your agent +> . + ## Start install it @@ -40,14 +43,8 @@ npm i crowdsec-client-scenarios and then read the [scenarios guide](https://github.com/thib3113/node-crowdsec/wiki/Scenarios) or the [API reference](https://thib3113.github.io/node-crowdsec/). -## Usage - -This package hosts scenarios used by [crowdsec-http-middleware](https://www.npmjs.com/package/crowdsec-http-middleware) and other middlewares that extend it. - ## Scenarios -in this part, we will use the variables `scenarios` and `scenariosOptions`, to illustrate the use in the middlewares - ### Defaults scenarios the defaults scenarios are ([defined here](https://github.com/thib3113/node-crowdsec/blob/main/packages/crowdsec-client-scenarios/src/index.ts#L8)) : @@ -81,56 +78,6 @@ const scenariosOptions = { this scenario support the extractIp capability, so, if you enable it, it will extract the IP automatically from the headers, will use set it on `req.ip`, and will use it to trigger alerts and check if decisions exists -##### Example - -you are using cloudflare (you can get cloudflare [ips](https://www.cloudflare.com/fr-fr/ips/) here, then traefik in subnet 10.0.3.0/24, and finally your webserver - -on your server, you will configure : - -````typescript -const scenarios = [XForwardedForChecker]; -const scenariosOptions = { - 'x-forwarded-for': { - //list of trusted CIDR, you need to setup here that all the trusted proxies, else, it will trigger alert for your reverse proxies, and extract incorrect ip - trustedProxies: [ - //cloudflare ips - "173.245.48.0/20", - "103.21.244.0/22", - "103.22.200.0/22", - "103.31.4.0/22", - "141.101.64.0/18", - "108.162.192.0/18", - "190.93.240.0/20", - "188.114.96.0/20", - "197.234.240.0/22", - "198.41.128.0/17", - "162.158.0.0/15", - "104.16.0.0/13", - "104.24.0.0/14", - "172.64.0.0/13", - "131.0.72.0/22", - "2400:cb00::/32", - "2606:4700::/32", - "2803:f800::/32", - "2405:b500::/32", - "2405:8100::/32", - "2a06:98c0::/29", - "2c0f:f248::/32", - //traefik ip - "10.0.3.0/24" - ], - //trigger alert if an untrusted ip set the header - alertOnNotTrustedIps: true - } -} -```` - -so, if someone with ip `1.2.3.4` it will produce an `X-Forwarded-For` like `1.2.3.4, 173.245.48.2`, and your webserver will detect a remote address like `10.0.3.1` . -This scenario will parse the information, and so set `req.ip = "1.2.3.4"`, so you now know the real ip of your visitor . - -I need to warn you, if you miss configured the list of allowed ips, it can ban your reverse proxy . -you can test it before, by setting `alertOnNotTrustedIps` to false, and log `req.ip`, if the IP is correct, you can enable the alerts - #### AllowList This scenario allows you to exclude some IPs from alerts. diff --git a/packages/crowdsec-client-scenarios/src/index.ts b/packages/crowdsec-client-scenarios/src/index.ts index a3f839f4d..b565791ce 100644 --- a/packages/crowdsec-client-scenarios/src/index.ts +++ b/packages/crowdsec-client-scenarios/src/index.ts @@ -1,10 +1,10 @@ import { pkg } from './pkg.js'; -import { IScenario } from './baseScenarios/IScenario.js'; +import { IScenarioConstructor } from './baseScenarios/IScenario.js'; import { AllowListEnricher, HTTPEnricher, XForwardedForChecker } from './scenarios/index.js'; export * from './baseScenarios/index.js'; export * from './scenarios/index.js'; -export const scenarios: Array = [AllowListEnricher, XForwardedForChecker, HTTPEnricher]; +export const scenarios: Array = [AllowListEnricher, XForwardedForChecker, HTTPEnricher]; export const VERSION = pkg.version; diff --git a/packages/crowdsec-client-scenarios/src/scenarios/HTTPEnricher/HTTPEnricher.ts b/packages/crowdsec-client-scenarios/src/scenarios/HTTPEnricher/HTTPEnricher.ts index 679ce46fa..820d66917 100644 --- a/packages/crowdsec-client-scenarios/src/scenarios/HTTPEnricher/HTTPEnricher.ts +++ b/packages/crowdsec-client-scenarios/src/scenarios/HTTPEnricher/HTTPEnricher.ts @@ -14,7 +14,13 @@ export class HTTPEnricher extends EnricherScenario { } enrich(alert: APITypes.Alert, req: IncomingMessage): APITypes.Alert | undefined { - const url = new URL(req.url ?? '', 'http://localhost'); + let url: URL; + try { + url = new URL(req.url ?? '', 'http://localhost'); + } catch { + debug('invalid request url %o', req.url); + return alert; + } //allow to get 0 when only ? . and 0 when nothing const http_args_len = String((url.search.length || 1) - 1); diff --git a/packages/crowdsec-client-scenarios/src/scenarios/MaxMind/MaxMindEnricher.ts b/packages/crowdsec-client-scenarios/src/scenarios/MaxMind/MaxMindEnricher.ts index 47aa72175..aa346b5e9 100644 --- a/packages/crowdsec-client-scenarios/src/scenarios/MaxMind/MaxMindEnricher.ts +++ b/packages/crowdsec-client-scenarios/src/scenarios/MaxMind/MaxMindEnricher.ts @@ -76,6 +76,7 @@ export class MaxMindEnricher extends BaseScenario { public loaded = false; public async load() { await Promise.all(this.internalEnrichers.map((e) => e.load())); + this.loaded = true; } public enrich(alert: APITypes.Alert): APITypes.Alert | undefined { diff --git a/packages/crowdsec-client-scenarios/src/scenarios/MaxMind/internalsEnrichers/InternalBaseEnricher.ts b/packages/crowdsec-client-scenarios/src/scenarios/MaxMind/internalsEnrichers/InternalBaseEnricher.ts index fc17a7d04..01a8fa93d 100644 --- a/packages/crowdsec-client-scenarios/src/scenarios/MaxMind/internalsEnrichers/InternalBaseEnricher.ts +++ b/packages/crowdsec-client-scenarios/src/scenarios/MaxMind/internalsEnrichers/InternalBaseEnricher.ts @@ -9,10 +9,12 @@ export abstract class InternalBaseEnricher implements IInter protected abstract databaseType: string; protected database?: Reader; protected databasePath: string; + protected readonly maxmindOpts: OpenOpts; protected debug = debug; public constructor(databasePath: string, maxmindOpts: OpenOpts) { this.databasePath = databasePath; + this.maxmindOpts = maxmindOpts; if (!fs.existsSync(this.databasePath)) { throw new Error(`database "${this.databasePath}" seems to doesn't exist`); @@ -20,7 +22,7 @@ export abstract class InternalBaseEnricher implements IInter } async load(): Promise { - const database = await maxmind.open(this.databasePath); + const database = await maxmind.open(this.databasePath, this.maxmindOpts); const { metadata } = database; this.debug('load database %o with languages %o builded at %o', metadata.databaseType, metadata.languages, metadata.buildEpoch); diff --git a/packages/crowdsec-client-scenarios/src/scenarios/XForwardedFor/XForwardedForChecker.ts b/packages/crowdsec-client-scenarios/src/scenarios/XForwardedFor/XForwardedForChecker.ts index cd577d1a7..696150647 100644 --- a/packages/crowdsec-client-scenarios/src/scenarios/XForwardedFor/XForwardedForChecker.ts +++ b/packages/crowdsec-client-scenarios/src/scenarios/XForwardedFor/XForwardedForChecker.ts @@ -221,7 +221,13 @@ export class XForwardedForChecker extends CheckerScenario { localDebug(`X-Forwarded-For extracted (${xForwardedForHeaderValues.length}) : "${xForwardedForHeaderValues.join('", "')}"`); //use cache if this xForwardedFor is always known - const cacheKey = xForwardedForHeaderValues.map((h) => crypto.createHash('sha256').update(h).digest('hex')).join('|'); + // Include the socket address: without X-Forwarded-For the header list is + // empty, and a key built from it alone would reuse the first client's + // extraction (socket/trusted-proxy result) for every later client. + const cacheKey = [ + String(remoteAddress ?? ''), + ...xForwardedForHeaderValues.map((h) => crypto.createHash('sha256').update(h).digest('hex')) + ].join('|'); const cache = this.extractIpCache.get(cacheKey); if (cache) { return [...cache]; diff --git a/packages/crowdsec-client-scenarios/src/utils.ts b/packages/crowdsec-client-scenarios/src/utils.ts index c39e95a55..2e9cb712d 100644 --- a/packages/crowdsec-client-scenarios/src/utils.ts +++ b/packages/crowdsec-client-scenarios/src/utils.ts @@ -45,8 +45,11 @@ export const getIpObject = (ip: string): AddressObject => { //maybe it's a valid IPv6 const address = new Address6(ip); - //IPv4-mapped IPv6 are compared as IPv4 ( https://github.com/thib3113/node-crowdsec/issues/88 ) - if (address.is4() && address.address4) { + // IPv4-mapped IPv6 are compared as IPv4 ( https://github.com/thib3113/node-crowdsec/issues/88 ). + // `is4()` is notation-level and also matches non-mapped dotted-quad + // forms; require a real mapped address and a /96+ prefix so a + // `::ffff:10.0.0.0/64` is not silently turned into an IPv4 /32. + if (address.isMapped4() && address.subnetMask >= 96 && address.address4) { return address.address4; } diff --git a/packages/crowdsec-client-scenarios/tests/scenarios/Enrichers.tests.ts b/packages/crowdsec-client-scenarios/tests/scenarios/Enrichers.tests.ts new file mode 100644 index 000000000..316a5b962 --- /dev/null +++ b/packages/crowdsec-client-scenarios/tests/scenarios/Enrichers.tests.ts @@ -0,0 +1,54 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const { mockOpen } = vi.hoisted(() => ({ mockOpen: vi.fn() })); + +vi.mock('fs', () => ({ existsSync: () => true })); +vi.mock('maxmind', () => ({ default: { open: mockOpen } })); + +import { AllowListEnricher } from '../../src/scenarios/AllowList/AllowListEnricher.js'; +import { HTTPEnricher } from '../../src/scenarios/HTTPEnricher/HTTPEnricher.js'; +import { MaxMindEnricher } from '../../src/scenarios/MaxMind/MaxMindEnricher.js'; + +describe('AllowListEnricher', () => { + it('honours a custom list instead of the defaults', () => { + const enricher = new AllowListEnricher({ 'allow-list': { allowed: ['203.0.113.0/24'] } }); + + expect(enricher.enrich({ source: { ip: '203.0.113.5' }, events: [], meta: [] } as any)).toBeUndefined(); + // 10.0.0.0/8 is a default entry, but the custom list replaces defaults. + const other = { source: { ip: '10.1.2.3' }, events: [], meta: [] } as any; + expect(enricher.enrich(other)).toBe(other); + }); +}); + +describe('HTTPEnricher', () => { + it('keeps the alert when the request URL is malformed', () => { + const enricher = new HTTPEnricher(); + const alert = { events: [], meta: [] } as any; + const req = { url: 'http://[::1', headers: {}, method: 'GET' } as any; + + expect(() => enricher.enrich(alert, req)).not.toThrow(); + expect(enricher.enrich(alert, req)).toBe(alert); + }); +}); + +describe('MaxMindEnricher', () => { + beforeEach(() => { + mockOpen.mockReset(); + }); + + it('passes OpenOpts to maxmind and marks the enricher as loaded', async () => { + mockOpen.mockResolvedValue({ + metadata: { databaseType: 'GeoLite2-City', languages: [], buildEpoch: 0 }, + getWithPrefixLength: () => [null, 0] + }); + const enricher = new MaxMindEnricher({ + maxmind: { paths: { city: 'fake.mmdb' }, watchForUpdates: true }, + maxIpCache: 10 + }); + + await enricher.load(); + + expect(enricher.loaded).toBe(true); + expect(mockOpen).toHaveBeenCalledWith('fake.mmdb', { watchForUpdates: true, cache: { max: 10 } }); + }); +}); diff --git a/packages/crowdsec-client-scenarios/tests/scenarios/XForwarderForChecker.tests.ts b/packages/crowdsec-client-scenarios/tests/scenarios/XForwarderForChecker.tests.ts index 7cb86bf98..98c8ad807 100644 --- a/packages/crowdsec-client-scenarios/tests/scenarios/XForwarderForChecker.tests.ts +++ b/packages/crowdsec-client-scenarios/tests/scenarios/XForwarderForChecker.tests.ts @@ -12,7 +12,7 @@ const getRequest = (forwardedFor: string, remoteAddress = '1.1.1.1'): IncomingMe headers: { 'X-Forwarded-For': forwardedFor } - } as unknown as IncomingMessage); + }) as unknown as IncomingMessage; describe('getIpObject', () => { it.each<[string, boolean]>([ @@ -63,6 +63,15 @@ describe('XForwardedForChecker', () => { }); }); + it('does not reuse the extraction cache across sockets without X-Forwarded-For', () => { + const scenario = new XForwardedForChecker({ 'x-forwarded-for': { trustedProxies: [] } }); + const req1 = { socket: { remoteAddress: '1.1.1.1' }, headers: {} } as unknown as IncomingMessage; + const req2 = { socket: { remoteAddress: '9.9.9.9' }, headers: {} } as unknown as IncomingMessage; + + expect(scenario.extractIp(req1)?.ip).toBe('1.1.1.1'); + expect(scenario.extractIp(req2)?.ip).toBe('9.9.9.9'); + }); + describe('ipv4-mapped ipv6 in trusted proxies', () => { const scenario = new XForwardedForChecker({ 'x-forwarded-for': { diff --git a/packages/crowdsec-client/README.md b/packages/crowdsec-client/README.md index 5091c7da8..5947118bc 100644 --- a/packages/crowdsec-client/README.md +++ b/packages/crowdsec-client/README.md @@ -28,6 +28,9 @@ This library is a Node.js client for the CrowdSec REST API. +> **For LLMs:** give your agent +> . + ## Start install it @@ -38,126 +41,105 @@ npm i crowdsec-client and then read the [getting started guide](https://github.com/thib3113/node-crowdsec/wiki/Getting-Started) or the [API reference](https://thib3113.github.io/node-crowdsec/). -## Usage - -### as a Bouncer - -First, create a client pointing to your CrowdSec instance, with a bouncer API key ([doc](https://doc.crowdsec.net/docs/user_guides/bouncers_configuration/)). - -````typescript -import { BouncerClient } from 'crowdsec-client'; - -const client = new BouncerClient({ - url: process.env.CROWDSEC_URL, - auth: { - apiKey: process.env.CROWDSEC_API_KEY || '' - }, - //use this option if you use a self signed ssl certificate - strictSSL: false -}); -await client.login(); -```` - -Second, ask for a decision +## CrowdSec compatibility + +The client works with CrowdSec LAPI `v1.0.0` and newer; features added in later +releases are unavailable on older servers. + +| Feature | Minimum LAPI | +| --- | --- | +| Bouncer (decisions, decisions stream) | 1.0.0 | +| Watcher (alerts) | 1.0.0 | +| `contains` filter | 1.0.3 | +| Heartbeat | 1.4.0 | +| `DELETE /alerts/{id}`, `DELETE /decisions?scenario=` | 1.4.2 | +| Allowlists (list, get, check) | 1.6.6 | +| Bulk allowlist check, watcher self-delete | 1.6.9 | +| `kind` alert filter | 1.7.7 | + +See [`docs/api-compatibility.md`](../../docs/api-compatibility.md) for the full +matrix, failure modes, probes and fallbacks. + +### Capability detection + +Declare `lapiVersion` to resolve capabilities without a request, or set +`detectCapabilities: true` to probe after login. Results are memoised per +instance; methods that need a newer LAPI throw `FeatureNotSupportedError`, and +`strictCapabilities` also rejects unverifiable capabilities. + +```ts +const watcher = new WatcherClient({ url, auth, detectCapabilities: true }); +await watcher.login(); +watcher.supports('allowlists'); // true | false | undefined +watcher.getProbableVersion(); // { probable: '>=1.6.9 <1.7.7' } +``` -````typescript -const stream = client.Decisions.getStream({ - // the stream polls the API at this interval, in ms - interval: 10000 -}); +Two caveats: `DELETE /alerts/{id}` and `DELETE /decisions?scenario=` (1.4.2) +cannot be probed without sending a `DELETE`, so they stay `undefined`; and a +decision created on an old or remote LAPI may not be deletable (alert deletion +is LAPI-host-only). Prefer short durations or delete by decision id. -//or with filters -const filteredStream = client.Decisions.getStream({ - // the stream polls the API at this interval, in ms - interval: 10000, - scopes: ['ip', 'range'], - origins: ['capi'] , - scenarios_containing: ['bruteforce'], - scenarios_not_containing: ['slow'], -}); -```` +## Usage -now, use this stream (`stream` is the object returned by `client.Decisions.getStream()`) +### Quick start -````typescript -stream.on('added', (decision) => { - // emitted when a new decision is added -}); +```ts +import { BouncerClient, WatcherClient } from 'crowdsec-client'; -stream.on('deleted', (decision) => { - // emitted when a decision is deleted +const bouncer = new BouncerClient({ + url: process.env.CROWDSEC_URL!, + auth: { apiKey: process.env.CROWDSEC_API_KEY! } }); +await bouncer.login(); +const { new: newDecisions } = await bouncer.Decisions.getRawStream({ startup: true }); -// start the stream -stream.resume(); - -// pause the stream -stream.pause(); - -// check if the stream is paused -if (stream.paused) { - // ... -} -```` - -### as a Watcher - -First, create a client pointing to your CrowdSec instance, with a machine login/password ([doc](https://doc.crowdsec.net/docs/user_guides/machines_mgmt)). - -````typescript -import { WatcherClient } from 'crowdsec-client'; - -const client = new WatcherClient({ - url: process.env.CROWDSEC_URL, +const watcher = new WatcherClient({ + url: process.env.CROWDSEC_URL!, auth: { - machineID: 'nameOfTheMachine', - password: 'password', - // the CrowdSec token is valid for 1h; autoRenew (default: true) keeps it fresh - autoRenew: true, + machineID: process.env.CROWDSEC_MACHINE_ID!, + password: process.env.CROWDSEC_PASSWORD!, + autoRenew: true }, - //use this option if you use a self signed ssl certificate - strictSSL: false -}); -await client.login(); -```` - -Search for Alert - -```typescript -//get alerts with an active decision -const alerts = await client.Alerts.search({ - has_active_decision: true -}); - -//select one alert -const alert = alerts[0] -if(!alert.id) { - //do something if no id -} - -//delete it ? -await client.Alerts.deleteById(alert.id); - -//or delete all the alerts about an ip -await client.Alerts.delete({ - ip: '127.0.0.1' + heartbeat: false }); +await watcher.login(); +const alerts = await watcher.Alerts.search({ has_active_decision: true, limit: 10 }); ``` -More authentication options (such as TLS) are documented in the [wiki](https://github.com/thib3113/node-crowdsec/wiki/Authentications). +Stream filters, alert management and all authentication modes (TLS, mTLS) are +documented in the [getting started guide](https://github.com/thib3113/node-crowdsec/wiki/Getting-Started) +and [Authentications](https://github.com/thib3113/node-crowdsec/wiki/Authentications). ## Type overrides The generated API types under `src/types/generated` come from the upstream CrowdSec swagger and are never edited by hand. Known discrepancies with the actual LAPI are typed in `src/types/overrides.ts` and exported as -`SearchAlertsQuery` / `DeleteAlertsQuery` (also available as -`APITypes.SearchAlertsQuery` / `APITypes.DeleteAlertsQuery`): +`SearchAlertsQuery` / `DeleteAlertsQuery` / `DeleteDecisionsQuery` (also +available as `APITypes.SearchAlertsQuery` / `APITypes.DeleteAlertsQuery` / +`APITypes.DeleteDecisionsQuery`): - `since` and `until` are Go durations (`24h`, `7d`) on both alert search and alert delete, despite the swagger documenting them as timestamps for delete. - `contains` and `kind` are supported by the alert filters but missing from the generated search type; `decision_type` is also missing from the delete type. +- Alert delete accepts `origin` (decision origin), not `alert_source` (rejected + by LAPI 1.8.1). `kind`, `contains` and `decision_type` are accepted too. +- Decision delete uses `scope` before LAPI 1.3.3 and `scopes` from 1.3.3. + `Decisions.delete()` uses the `decisionScopesDelete` capability when known; + otherwise it tries `scopes`, falls back to `scope` on the specific + `500 invalid filter`, and caches the learned value. At the LAPI level + `contains` defaults to true; `Alerts.delete()` and `Decisions.delete()` make + it explicit (`contains: false`) whenever `ip` or `range` is present, so an + IP delete does not also expire Range decisions that contain it. Pass + `contains: true` to opt into the wider behaviour. +- Decision search accepts `simulated`. The LAPI excludes simulated decisions by + default and does not return the `simulated` field on `/v1/decisions`; pass + `simulated: true` to include them. `Decision.simulated` is therefore + `boolean | undefined` in 1.4.0: `undefined` means the connected LAPI omitted + the field, not `false`. + +These behaviours were validated against `crowdsec:v1.8.1` in Docker. Run `pnpm run generate-api` to refresh the generated files, then re-check the overrides against the new schema. diff --git a/packages/crowdsec-client/package.json b/packages/crowdsec-client/package.json index 45d4f2eb7..07ee36c01 100644 --- a/packages/crowdsec-client/package.json +++ b/packages/crowdsec-client/package.json @@ -1,6 +1,6 @@ { "name": "crowdsec-client", - "version": "1.3.0", + "version": "1.4.0", "description": "A CrowdSec client that allows you to easily create a bouncer or watcher", "main": "./lib/index.cjs", "module": "./lib/index.mjs", @@ -22,6 +22,8 @@ "debug": "npm run build && node -r source-map-support/register ./lib/esm/debug.mjs", "generate-api": "node generator.ts", "test": "vitest run", + "test:live": "vitest run tests/Live/live.test.ts", + "test:live:matrix": "bash ../../.github/scripts/lapi-matrix/run-live-tests.sh", "test:ci": "vitest run", "test:ci:coverage": "vitest run --coverage", "lint": "eslint src", diff --git a/packages/crowdsec-client/src/Alerts/Alerts.ts b/packages/crowdsec-client/src/Alerts/Alerts.ts index 02f2c8845..6eaa23695 100644 --- a/packages/crowdsec-client/src/Alerts/Alerts.ts +++ b/packages/crowdsec-client/src/Alerts/Alerts.ts @@ -1,6 +1,8 @@ import { BaseSubObject } from '../BaseSubObject.js'; +import { LapiCapability } from '../Capabilities.js'; import { Alerts as AlertsTypes } from '../types/index.js'; import type { DeleteAlertsQuery, SearchAlertsQuery } from '../types/index.js'; +import { withContainsDefault } from '../utils.js'; import { AxiosResponse } from 'axios'; export class Alerts extends BaseSubObject { @@ -18,7 +20,26 @@ export class Alerts extends BaseSubObject { ).data; } + /** + * Search alerts. + * @since CrowdSec 1.0.0 + * @remarks + * - `contains` requires CrowdSec LAPI 1.0.3. + * - `origin` requires CrowdSec LAPI 1.3.0. + * - `kind` requires CrowdSec LAPI 1.7.7. + * @throws {FeatureNotSupportedError} when a used filter is not supported by the connected LAPI. + */ public async search(options?: SearchAlertsQuery): Promise { + if (options?.contains !== undefined) { + this.requireCapability(LapiCapability.containsFilter); + } + if (options?.origin !== undefined) { + this.requireCapability(LapiCapability.alertOriginFilter); + } + if (options?.kind !== undefined) { + this.requireCapability(LapiCapability.alertKindFilter); + } + return ( await this.http.get< AlertsTypes.SearchAlerts.ResponseBody, @@ -33,24 +54,53 @@ export class Alerts extends BaseSubObject { public async getById(id: string): Promise { return ( await this.http.get>( - `/v1/alerts/${id}` + `/v1/alerts/${encodeURIComponent(id)}` ) ).data; } + /** + * Delete alerts matching a filter. + * @since CrowdSec 1.0.0 + * @remarks + * - `contains` requires CrowdSec LAPI 1.0.3. + * - `origin` requires CrowdSec LAPI 1.3.0. + * - `kind` requires CrowdSec LAPI 1.7.7. + * - Alert deletion from a remote host requires the LAPI host to trust the caller (otherwise HTTP 403). + * @throws {FeatureNotSupportedError} when a used filter is not supported by the connected LAPI. + */ public async delete(options: DeleteAlertsQuery): Promise { + const normalized = withContainsDefault(options); + + if (normalized.contains !== undefined) { + this.requireCapability(LapiCapability.containsFilter); + } + if (normalized.origin !== undefined) { + this.requireCapability(LapiCapability.alertOriginFilter); + } + if (normalized.kind !== undefined) { + this.requireCapability(LapiCapability.alertKindFilter); + } + return ( await this.http.delete< AlertsTypes.DeleteAlerts.ResponseBody, AxiosResponse, AlertsTypes.DeleteAlerts.RequestQuery >('/v1/alerts', { - params: options + params: normalized }) ).data; } + /** + * Delete a single alert by id. + * @since CrowdSec 1.4.2 + * @remarks Alert deletion from a remote host requires the LAPI host to trust the caller (otherwise HTTP 403). + * @throws {FeatureNotSupportedError} when the connected LAPI is older than 1.4.2. + */ public async deleteById(id: string): Promise { - return (await this.http.delete(`/v1/alerts/${id}`)).data; + this.requireCapability(LapiCapability.alertDeleteById); + return (await this.http.delete(`/v1/alerts/${encodeURIComponent(id)}`)).data; } } diff --git a/packages/crowdsec-client/src/Allowlists/Allowlists.ts b/packages/crowdsec-client/src/Allowlists/Allowlists.ts index e96bc158b..8f6a31280 100644 --- a/packages/crowdsec-client/src/Allowlists/Allowlists.ts +++ b/packages/crowdsec-client/src/Allowlists/Allowlists.ts @@ -1,9 +1,27 @@ import { BaseSubObject } from '../BaseSubObject.js'; +import { CAPABILITY_MIN_VERSION, LapiCapability } from '../Capabilities.js'; +import { FeatureNotSupportedError } from '../Errors/FeatureNotSupportedError.js'; import type { Allowlists as AllowlistsTypes } from '../types/index.js'; import type { AxiosResponse } from 'axios'; +/** A missing route: 404 on older LAPIs, 405 on 1.6.6-1.6.8 (shared prefix). */ +function isRouteUnavailable(error: unknown): boolean { + const candidate = error as { code?: unknown; response?: { status?: unknown } } | undefined; + // Wrapped errors carry the numeric status in `code`; a raw AxiosError uses a + // string `code` and keeps the status in `response.status`. + const status = typeof candidate?.code === 'number' ? candidate.code : candidate?.response?.status; + return status === 404 || status === 405; +} + export class Allowlists extends BaseSubObject { + /** + * List allowlists. + * @since CrowdSec 1.6.6 + * @throws {FeatureNotSupportedError} when the connected LAPI is older than 1.6.6. + */ public async list(withContent: boolean = true): Promise { + this.requireCapability(LapiCapability.allowlists); + return ( await this.http.get< AllowlistsTypes.GetAllowlists.ResponseBody, @@ -15,7 +33,14 @@ export class Allowlists extends BaseSubObject { ).data; } + /** + * Get a single allowlist. + * @since CrowdSec 1.6.6 + * @throws {FeatureNotSupportedError} when the connected LAPI is older than 1.6.6. + */ public async get(name: string, withContent: boolean = true): Promise { + this.requireCapability(LapiCapability.allowlists); + return ( await this.http.get< AllowlistsTypes.GetAllowlist.ResponseBody, @@ -27,7 +52,14 @@ export class Allowlists extends BaseSubObject { ).data; } + /** + * Check whether a single value is allowlisted. + * @since CrowdSec 1.6.6 + * @throws {FeatureNotSupportedError} when the connected LAPI is older than 1.6.6. + */ public async check(value: string): Promise { + this.requireCapability(LapiCapability.allowlists); + return ( await this.http.get< AllowlistsTypes.CheckAllowlist.ResponseBody, @@ -37,7 +69,34 @@ export class Allowlists extends BaseSubObject { ).data; } + /** + * Check several values against the allowlists in one request. + * @since CrowdSec 1.6.9 + * @remarks On 1.6.6 to 1.6.8, falls back to {@link check} per value. + * @throws {FeatureNotSupportedError} when the connected LAPI is older than 1.6.6. + */ public async bulkCheck(targets: string[]): Promise { + // On 1.6.6-1.6.8 the bulk route is missing (405). When the capability + // is already known to be absent, skip the doomed request. + if (this.capabilities?.supports(LapiCapability.allowlistsBulkCheck) === false) { + return this.bulkCheckFallback(targets); + } + + this.requireCapability(LapiCapability.allowlistsBulkCheck); + + try { + return await this.bulkCheckRequest(targets); + } catch (error) { + if (!isRouteUnavailable(error)) { + throw error; + } + + this.capabilities?.learn(LapiCapability.allowlistsBulkCheck, false); + return this.bulkCheckFallback(targets); + } + } + + private async bulkCheckRequest(targets: string[]): Promise { return ( await this.http.post< AllowlistsTypes.PostCheckAllowlist.ResponseBody, @@ -46,4 +105,30 @@ export class Allowlists extends BaseSubObject { >('/v1/allowlists/check', { targets }) ).data; } + + private async bulkCheckFallback(targets: string[]): Promise { + const results: AllowlistsTypes.PostCheckAllowlist.ResponseBody['results'] = []; + + for (const target of targets) { + let checked: AllowlistsTypes.CheckAllowlist.ResponseBody; + try { + checked = await this.check(target); // NOSONAR: sequential by design to bound LAPI load + } catch (error) { + if (isRouteUnavailable(error)) { + throw new FeatureNotSupportedError(LapiCapability.allowlists, CAPABILITY_MIN_VERSION[LapiCapability.allowlists]); + } + throw error; + } + + if (checked.allowlisted) { + // The single-value route only exposes the matched item (`reason`), + // not the allowlist name and comment returned by the bulk route. + // Label it explicitly so callers do not mistake the matched item + // for an allowlist name. + results.push({ target, allowlists: [`unknown allowlist (matched item: ${checked.reason ?? target})`] }); + } + } + + return { results }; + } } diff --git a/packages/crowdsec-client/src/BaseSubObject.ts b/packages/crowdsec-client/src/BaseSubObject.ts index af16aeeb6..9dd784769 100644 --- a/packages/crowdsec-client/src/BaseSubObject.ts +++ b/packages/crowdsec-client/src/BaseSubObject.ts @@ -1,12 +1,21 @@ import { AxiosInstance } from 'axios'; +import type { CapabilityGuard, LapiCapabilityInput } from './Capabilities.js'; export interface IBaseSubObjectOptions { httpClient: AxiosInstance; + capabilities?: CapabilityGuard; } export class BaseSubObject { protected http: AxiosInstance; + protected capabilities?: CapabilityGuard; + constructor(options: IBaseSubObjectOptions) { this.http = options.httpClient; + this.capabilities = options.capabilities; + } + + protected requireCapability(capability: LapiCapabilityInput): void { + this.capabilities?.assertSupport(capability); } } diff --git a/packages/crowdsec-client/src/Capabilities.ts b/packages/crowdsec-client/src/Capabilities.ts new file mode 100644 index 000000000..1280c7057 --- /dev/null +++ b/packages/crowdsec-client/src/Capabilities.ts @@ -0,0 +1,507 @@ +import { CrowdsecClientError } from './Errors/CrowdsecClientError.js'; +import { FeatureNotSupportedError } from './Errors/FeatureNotSupportedError.js'; +import { LapiVersionUnknownError } from './Errors/LapiVersionUnknownError.js'; + +/** + * CrowdSec LAPI capabilities the client can gate on. + * + * The minimum version is the first stable release where the behaviour works, + * which is not always the version where it was documented in the swagger. + * + * Some entries (`uuidField`, `registrationToken`, `usageMetrics`, + * `alertKindField`, `lapiMetricsFeatures`, `decisionUntilField`) are + * informational for now: they are not used by `requireCapability` yet. + */ +export enum LapiCapability { + containsFilter = 'containsFilter', + streamScopes = 'streamScopes', + alertOriginFilter = 'alertOriginFilter', + decisionUntilField = 'decisionUntilField', + decisionOriginsFilter = 'decisionOriginsFilter', + heartbeat = 'heartbeat', + alertDeleteById = 'alertDeleteById', + decisionScenarioDelete = 'decisionScenarioDelete', + decisionScopesDelete = 'decisionScopesDelete', + uuidField = 'uuidField', + registrationToken = 'registrationToken', + usageMetrics = 'usageMetrics', + allowlists = 'allowlists', + allowlistsBulkCheck = 'allowlistsBulkCheck', + watcherSelfDelete = 'watcherSelfDelete', + alertKindField = 'alertKindField', + alertKindFilter = 'alertKindFilter', + lapiMetricsFeatures = 'lapiMetricsFeatures' +} + +/** + * A capability accepted on the public API: either the enum member + * (`LapiCapability.heartbeat`) or its raw string value (`'heartbeat'`). + */ +export type LapiCapabilityInput = LapiCapability | `${LapiCapability}`; + +/** Normalize a capability input to its enum member. */ +export function toLapiCapability(capability: LapiCapabilityInput): LapiCapability { + if (!Object.hasOwn(CAPABILITY_MIN_VERSION, capability)) { + throw new CrowdsecClientError(`unknown CrowdSec LAPI capability: ${String(capability)}`); + } + + return capability as LapiCapability; +} + +export const CAPABILITY_MIN_VERSION: Record = { + [LapiCapability.containsFilter]: '1.0.3', + [LapiCapability.streamScopes]: '1.1.0', + [LapiCapability.alertOriginFilter]: '1.3.0', + [LapiCapability.decisionUntilField]: '1.3.0', + [LapiCapability.decisionOriginsFilter]: '1.3.3', + [LapiCapability.heartbeat]: '1.4.0', + [LapiCapability.alertDeleteById]: '1.4.2', + [LapiCapability.decisionScenarioDelete]: '1.4.2', + [LapiCapability.decisionScopesDelete]: '1.3.3', + [LapiCapability.uuidField]: '1.5.0', + [LapiCapability.registrationToken]: '1.6.3', + [LapiCapability.usageMetrics]: '1.6.3', + [LapiCapability.allowlists]: '1.6.6', + [LapiCapability.allowlistsBulkCheck]: '1.6.9', + [LapiCapability.watcherSelfDelete]: '1.6.9', + [LapiCapability.alertKindField]: '1.7.7', + [LapiCapability.alertKindFilter]: '1.7.7', + [LapiCapability.lapiMetricsFeatures]: '1.8.2' +}; + +export type LapiVersion = [number, number, number]; + +export function parseLapiVersion(version: string): LapiVersion | null { + const match = /^v?(\d+)\.(\d+)\.(\d+)$/.exec(version.trim()); + if (!match) { + return null; + } + + return [Number(match[1]), Number(match[2]), Number(match[3])]; +} + +export function compareLapiVersions(a: string, b: string): number { + const left = parseLapiVersion(a); + const right = parseLapiVersion(b); + + if (!left || !right) { + throw new CrowdsecClientError(`invalid CrowdSec LAPI version: ${!left ? a : b}`); + } + + for (let i = 0; i < 3; i++) { + if (left[i] !== right[i]) { + return left[i] < right[i] ? -1 : 1; + } + } + + return 0; +} + +export type CapabilitySource = 'unknown' | 'declared' | 'probed' | 'observed'; + +export interface LapiVersionEstimate { + /** Declared version, when the caller provided one. */ + exactVersion?: string; + /** Highest version proven by a capability that works. */ + minVersion?: string; + /** Lowest version proven unsupported: exclusive upper bound. */ + belowVersion?: string; + /** Human-readable range, e.g. `>=1.6.9 <1.7.7`. */ + probable: string; +} + +export interface LapiCapabilityState { + /** Where the values come from. */ + source: CapabilitySource; + /** Declared LAPI version, when the caller provided one. */ + version?: string; + /** Best guess of the LAPI version, derived from the known capabilities. */ + estimate: LapiVersionEstimate; + /** `undefined` means the capability could not be determined. */ + values: Partial>; +} + +export interface CapabilityGuard { + getCapabilities(): LapiCapabilityState; + supports(capability: LapiCapabilityInput): boolean | undefined; + assertSupport(capability: LapiCapabilityInput): void; + /** + * Record a capability observed on a real request; never overrides a + * declared/probed value. Unlike a probe, this is a side signal: it is not + * used to infer the other capabilities. + */ + learn(capability: LapiCapabilityInput, supported: boolean): void; +} + +const ALL_CAPABILITIES: Array = Object.values(LapiCapability); + +/** + * Propagate what is known through the version ordering: a capability that + * works at version V means every capability with an older minimum also works, + * and a capability that does not work at V means every newer one does not. + * + * This assumes features are introduced monotonically, which a backport can + * violate (two capabilities with the same minimum are not necessarily shipped + * together). Only deliberate version probes feed this function: values learned + * from real requests are kept out so one rejected request cannot disable + * unrelated features. + */ +function inferFromKnown(values: Partial>, known: LapiCapability, supported: boolean): boolean { + let changed = false; + + for (const candidate of ALL_CAPABILITIES) { + if (values[candidate] !== undefined) { + continue; + } + + const order = compareLapiVersions(CAPABILITY_MIN_VERSION[candidate], CAPABILITY_MIN_VERSION[known]); + + if ((supported && order <= 0) || (!supported && order >= 0)) { + values[candidate] = supported; + changed = true; + } + } + + return changed; +} + +function inferCapabilities(values: Partial>): void { + let changed = true; + + while (changed) { + changed = false; + + for (const known of ALL_CAPABILITIES) { + const supported = values[known]; + if (supported === undefined) { + continue; + } + + changed = inferFromKnown(values, known, supported) || changed; + } + } +} + +/** + * Turn the known capabilities into a version range. + * + * A capability that works proves the LAPI is at least its minimum version; a + * capability that fails proves it is older. The result is the smallest range + * consistent with both, for example `>=1.6.9 <1.7.7`. Patch-level versions + * inside the range cannot be told apart without a declared version. + */ +function maxOfVersions(versions: string[]): string | undefined { + let result: string | undefined; + + for (const version of versions) { + if (!result || compareLapiVersions(version, result) > 0) { + result = version; + } + } + + return result; +} + +function minOfVersions(versions: string[]): string | undefined { + let result: string | undefined; + + for (const version of versions) { + if (!result || compareLapiVersions(version, result) < 0) { + result = version; + } + } + + return result; +} + +export function estimateLapiVersion(values: Partial>, exactVersion?: string): LapiVersionEstimate { + if (exactVersion) { + return { exactVersion, minVersion: exactVersion, probable: exactVersion }; + } + + const known = ALL_CAPABILITIES.filter((capability) => values[capability] !== undefined); + const supported = known.filter((capability) => values[capability] === true).map((capability) => CAPABILITY_MIN_VERSION[capability]); + const unsupported = known.filter((capability) => values[capability] === false).map((capability) => CAPABILITY_MIN_VERSION[capability]); + + let minVersion = maxOfVersions(supported); + let belowVersion = minOfVersions(unsupported); + + // Inference should make this impossible; never return an empty range. + if (minVersion && belowVersion && compareLapiVersions(minVersion, belowVersion) >= 0) { + belowVersion = undefined; + } + + let probable = 'unknown'; + if (minVersion && belowVersion) { + probable = `>=${minVersion} <${belowVersion}`; + } else if (minVersion) { + probable = `>=${minVersion}`; + } else if (belowVersion) { + probable = `<${belowVersion}`; + } + + return { minVersion, belowVersion, probable }; +} + +export class CapabilityContext implements CapabilityGuard { + private state: LapiCapabilityState; + private readonly strict: boolean; + /** Capabilities explicitly probed; an explicit probe always wins. */ + private readonly probed = new Set(); + /** Capabilities observed on a real request, excluded from inference. */ + private readonly learned = new Set(); + + public constructor(options: { version?: string; strict?: boolean } = {}) { + this.strict = options.strict ?? false; + this.state = { source: 'unknown', estimate: estimateLapiVersion({}), values: {} }; + + if (options.version) { + this.applyVersion(options.version); + } + } + + public applyVersion(version: string): void { + const parsed = parseLapiVersion(version); + if (!parsed) { + throw new CrowdsecClientError(`invalid lapiVersion "${version}", expected a semver like 1.6.6`); + } + + const values: Partial> = {}; + for (const capability of ALL_CAPABILITIES) { + values[capability] = compareLapiVersions(version, CAPABILITY_MIN_VERSION[capability]) >= 0; + } + + this.probed.clear(); + this.learned.clear(); + + this.state = { source: 'declared', version, estimate: estimateLapiVersion(values, version), values }; + } + + private extractLearned(values: Partial>): Partial> { + const learnedValues: Partial> = {}; + + // Learned values are observations from real requests, not version + // probes: keep them out of the inference input. Re-added after + // inference so they still answer `supports()`. + for (const capability of this.learned) { + if (values[capability] !== undefined) { + learnedValues[capability] = values[capability]; + } + delete values[capability]; + } + + return learnedValues; + } + + private mergeObserved(values: Partial>, observed: Partial>): boolean { + let seen = false; + + for (const [capability, supported] of Object.entries(observed) as Array<[LapiCapability, boolean | undefined]>) { + if (supported === undefined) { + continue; + } + values[capability] = supported; + this.learned.delete(capability); + this.probed.add(capability); + seen = true; + } + + return seen; + } + + private rebuildOnContradiction(values: Partial>, version: string | undefined): string | undefined { + if (!version || this.isConsistentWithVersion(values, version)) { + return version; + } + + // A probe contradicts the declared version: the declared-derived values + // are not trustworthy, so rebuild from what was actually observed. + for (const capability of ALL_CAPABILITIES) { + if (!this.probed.has(capability)) { + delete values[capability]; + } + } + + return undefined; + } + + private restoreLearned( + values: Partial>, + learnedValues: Partial> + ): void { + for (const [capability, supported] of Object.entries(learnedValues) as Array<[LapiCapability, boolean]>) { + // A capability probed in this call left `learned` and was written + // into `values`: the explicit probe wins over the stale observation. + if (this.learned.has(capability)) { + values[capability] = supported; + } + } + } + + private sourceFor(version: string | undefined, seen: boolean): 'unknown' | 'declared' | 'probed' | 'observed' { + if (version) { + return 'declared'; + } + return seen ? 'probed' : this.state.source; + } + + public applyProbes(observed: Partial>): void { + const values: Partial> = { ...this.state.values }; + const learnedValues = this.extractLearned(values); + const seen = this.mergeObserved(values, observed); + const version = this.rebuildOnContradiction(values, this.state.version); + + inferCapabilities(values); + this.restoreLearned(values, learnedValues); + + this.state = { + source: this.sourceFor(version, seen), + version, + estimate: this.estimate(values, version), + values + }; + } + + /** + * Version estimate that ignores request-level observations: a single + * rejected request must not advertise a lower LAPI version. + */ + private estimate(values: Partial>, version: string | undefined): LapiVersionEstimate { + const inferable: Partial> = { ...values }; + for (const capability of this.learned) { + delete inferable[capability]; + } + + return estimateLapiVersion(inferable, version); + } + + private isConsistentWithVersion(values: Partial>, version: string): boolean { + for (const capability of this.probed) { + const supported = values[capability]; + if (supported === undefined) { + continue; + } + + const expected = compareLapiVersions(version, CAPABILITY_MIN_VERSION[capability]) >= 0; + if (supported !== expected) { + return false; + } + } + + return true; + } + + public getCapabilities(): LapiCapabilityState { + return { + ...this.state, + estimate: { ...this.state.estimate }, + values: { ...this.state.values } + }; + } + + public supports(capability: LapiCapabilityInput): boolean | undefined { + return this.state.values[toLapiCapability(capability)]; + } + + public learn(capability: LapiCapabilityInput, supported: boolean): void { + const key = toLapiCapability(capability); + + // Declared and explicitly probed values are authoritative. + if (this.state.source === 'declared' || this.probed.has(key)) { + return; + } + + // A value learned from a real request is not a deliberate version probe, + // so it must not propagate to the other capabilities: a single rejected + // filter (for example a 500 whose message matched the scope fallback) + // would otherwise disable unrelated features such as heartbeat or + // allowlists for the rest of the session. Mark it as learned even when + // it corrects a value that was only inferred. + const values: Partial> = { ...this.state.values, [key]: supported }; + this.learned.add(key); + this.state = { + // Keep the stronger provenance: one observation must not downgrade + // a state where the other values come from probes. + source: this.state.source === 'probed' ? 'probed' : 'observed', + version: this.state.version, + estimate: this.estimate(values, this.state.version), + values + }; + } + + public assertSupport(capability: LapiCapabilityInput): void { + const key = toLapiCapability(capability); + const supported = this.supports(key); + + if (supported === true) { + return; + } + + if (supported === false) { + throw new FeatureNotSupportedError(key, CAPABILITY_MIN_VERSION[key], this.state.version); + } + + if (this.strict) { + throw new LapiVersionUnknownError(key, CAPABILITY_MIN_VERSION[key]); + } + } +} + +/** + * Interpret the HTTP status of a probe request. + * + * Filter probes: 2xx means supported, 500 means the parameter is unknown, and + * anything else (400, 401, 403) is inconclusive. Route probes: 404 means the + * endpoint does not exist, and any other status below 500 means it exists + * (400 for a rejected empty body, 403 for a credential type that does not apply + * to the probe). For route probes, a 401 is inconclusive: it only says the + * caller is not authenticated, so it must not be read as proof that the route + * exists. + */ +export function interpretProbe(capability: LapiCapabilityInput, status: number | undefined): boolean | undefined { + const key = toLapiCapability(capability); + + if (status === undefined) { + return undefined; + } + + if (status === 404) { + return false; + } + + // On 1.6.6-1.6.8 the bulk route is missing, but Gin answers 405 because the + // path shares a prefix with the single-value check route. + if (key === LapiCapability.allowlistsBulkCheck && status === 405) { + return false; + } + + const filterLike = + key === LapiCapability.containsFilter || + key === LapiCapability.alertOriginFilter || + key === LapiCapability.decisionOriginsFilter || + key === LapiCapability.alertKindFilter; + + if (filterLike) { + if (status >= 200 && status < 300) { + return true; + } + if (status === 500) { + return false; + } + return undefined; + } + + // A 401 means the caller is not authenticated: it proves nothing about the + // route, so an unauthenticated probe must not report every endpoint as + // supported. A 403 (wrong credential type for an existing route) does prove + // the route exists. + if (status === 401) { + return undefined; + } + + if (status >= 200 && status < 500) { + return true; + } + + return undefined; +} diff --git a/packages/crowdsec-client/src/Clients/BouncerClient.ts b/packages/crowdsec-client/src/Clients/BouncerClient.ts index efaa526c9..c2491e8d3 100644 --- a/packages/crowdsec-client/src/Clients/BouncerClient.ts +++ b/packages/crowdsec-client/src/Clients/BouncerClient.ts @@ -1,6 +1,7 @@ import { CrowdSecClient } from './CrowdSecClient.js'; import { createDebugger } from '../utils.js'; import { IBouncerAuthentication, IBouncerClientOptions, ITLSAuthentication } from '../interfaces/index.js'; +import { LapiCapability } from '../Capabilities.js'; import { DecisionsBouncer } from '../Decisions/DecisionsBouncer.js'; import Validate from '../Validate.js'; import { CrowdsecClientError } from '../Errors/CrowdsecClientError.js'; @@ -27,11 +28,36 @@ export class BouncerClient extends CrowdSecClient { }); } - this.Decisions = new DecisionsBouncer({ httpClient: this.http }); + this.Decisions = new DecisionsBouncer({ httpClient: this.http, capabilities: this.capabilityContext }); } public async login(): Promise { - return this.testConnection(); + await this.testConnection(); + + if (this.options.detectCapabilities) { + await this.detectCapabilities(); + } + } + + protected collectProbes() { + // `/v1/decisions` is reachable with a bouncer key only. A watcher JWT + // gets 403 there, so these probes live in the bouncer client. + // + // The probes are deliberately selective: `/v1/decisions` has no `limit` + // parameter, so an unfiltered request would download the whole decision + // set twice. The filters below exercise the parameter under test while + // matching (almost) nothing: TEST-NET-1 is never in a real deployment, + // and an unknown origin returns an empty list. + return [ + { + capability: LapiCapability.containsFilter, + request: () => this.http.get('/v1/decisions', { params: { ip: '192.0.2.1', contains: false } }) + }, + { + capability: LapiCapability.decisionOriginsFilter, + request: () => this.http.get('/v1/decisions', { params: { origins: 'node-crowdsec-probe' } }) + } + ]; } public async testConnection(): Promise { diff --git a/packages/crowdsec-client/src/Clients/CrowdSecClient.ts b/packages/crowdsec-client/src/Clients/CrowdSecClient.ts index 7a71ff041..9d7871802 100644 --- a/packages/crowdsec-client/src/Clients/CrowdSecClient.ts +++ b/packages/crowdsec-client/src/Clients/CrowdSecClient.ts @@ -5,31 +5,86 @@ import * as https from 'https'; import { createDebugger, getUrlRepresentation } from '../utils.js'; import { AxiosError, CrowdsecClientError, CrowdSecServerError, EErrorsCodes } from '../Errors/index.js'; import type { ErrorResponse } from '../types/index.js'; +import { + CapabilityContext, + interpretProbe, + toLapiCapability, + type LapiCapability, + type LapiCapabilityInput, + type LapiCapabilityState, + type LapiVersionEstimate +} from '../Capabilities.js'; const debug = createDebugger('client'); const axiosDebug = createDebugger('axios'); const axiosDebugVerbose = axiosDebug.extend('verbose'); -const defaultsHTTPOptions: Required>> = { +const defaultsHTTPOptions: Required> = { timeout: 2000, userAgent: `node-${pkg.name}/v${pkg.version}`, strictSSL: true }; +const SENSITIVE_HEADERS = new Set(['authorization', 'x-api-key', 'x-crowdsec-api-key', 'x-crowdsec-token', 'cookie', 'set-cookie']); +const SENSITIVE_FIELDS = new Set(['password', 'token', 'registration_token', 'api_key', 'apikey']); + +/** + * Mask credentials before a debug log prints them. Debug output is opt-in, but + * a login response or a passthrough header must never be written in clear. + */ +export function redactHeaders(headers: unknown): unknown { + if (!headers || typeof headers !== 'object') { + return headers; + } + + const redacted: Record = {}; + for (const [key, value] of Object.entries(headers as Record)) { + redacted[key] = SENSITIVE_HEADERS.has(key.toLowerCase()) ? '[redacted]' : value; + } + return redacted; +} + +export function redactBody(body: unknown, seen = new WeakSet()): unknown { + if (!body || typeof body !== 'object') { + return body; + } + + if (seen.has(body)) { + return '[circular]'; + } + seen.add(body); + + if (Array.isArray(body)) { + return body.map((item) => redactBody(item, seen)); + } + + const redacted: Record = {}; + for (const [key, value] of Object.entries(body as Record)) { + redacted[key] = SENSITIVE_FIELDS.has(key.toLowerCase()) ? '[redacted]' : redactBody(value, seen); + } + return redacted; +} + export abstract class CrowdSecClient { protected debug = debug; get http(): AxiosInstance { return this._http; } - private options: ICrowdSecClientOptions; + protected readonly options: ICrowdSecClientOptions; protected static http: AxiosInstance; private readonly _http: AxiosInstance; + protected readonly capabilityContext: CapabilityContext; + protected constructor(options: ICrowdSecClientOptions) { this.options = options; this._http = CrowdSecClient.getHTTPClient(this.options); + this.capabilityContext = new CapabilityContext({ + version: options.lapiVersion, + strict: options.strictCapabilities + }); } protected static getHTTPClient(options: IHTTPOptions): AxiosInstance { @@ -73,8 +128,8 @@ export abstract class CrowdSecClient { config.metadata = { startTime: new Date() }; axiosDebug(`Starting Request on url ${config.method} ${getUrlRepresentation(config)}`); - axiosDebugVerbose(`headers : %O`, config.headers); - axiosDebugVerbose(`payload : %O`, config.data); + axiosDebugVerbose(`headers : %O`, redactHeaders(config.headers)); + axiosDebugVerbose(`payload : %O`, redactBody(config.data)); return config; }); @@ -88,8 +143,8 @@ export abstract class CrowdSecClient { response?.config )} with code ${response?.status} ${response?.statusText}${durationStr}` ); - axiosDebugVerbose('headers : %O', response?.headers); - axiosDebugVerbose(`payload : %O`, response?.data); + axiosDebugVerbose('headers : %O', redactHeaders(response?.headers)); + axiosDebugVerbose('payload : %O', redactBody(response?.data)); return response; }, (error) => { @@ -98,8 +153,8 @@ export abstract class CrowdSecClient { axiosDebug( `Response from ${rep.config?.method} ${getUrlRepresentation(rep.config)} with code ${rep.status} ${rep.statusText}` ); - axiosDebugVerbose(`headers : %O`, rep.headers); - axiosDebugVerbose(`payload : %O`, rep.data); + axiosDebugVerbose(`headers : %O`, redactHeaders(rep.headers)); + axiosDebugVerbose(`payload : %O`, redactBody(rep.data)); } else { if (error?.isAxiosError) { axiosDebug( @@ -139,6 +194,122 @@ export abstract class CrowdSecClient { Object.entries(headers).forEach(([key, value]) => (this._http.defaults.headers[key] = value)); } + /** + * Capabilities detected or declared for the connected LAPI. + */ + public getCapabilities(): LapiCapabilityState { + return this.capabilityContext.getCapabilities(); + } + + /** + * Best guess of the connected LAPI version, derived from the capabilities + * confirmed by probes. Exact only when `lapiVersion` was declared. + * + * @example { probable: '>=1.6.9 <1.7.7', minVersion: '1.6.9', belowVersion: '1.7.7' } + */ + public getProbableVersion(): LapiVersionEstimate { + return this.capabilityContext.getCapabilities().estimate; + } + + /** + * Whether a capability is supported. `undefined` means it is unknown. + */ + public supports(capability: LapiCapabilityInput): boolean | undefined { + return this.capabilityContext.supports(capability); + } + + /** + * Probe one capability and record the result. + * + * Returns the already-known value when the capability is resolved, unless + * `force` is set. Returns `undefined` when no probe exists for it (for + * example the 1.4.2 DELETE endpoints) or when the probe is inconclusive. + * + * The client must be authenticated first (call `login()`). + */ + public async detectCapability(capability: LapiCapabilityInput, options: { force?: boolean } = {}): Promise { + const key = toLapiCapability(capability); + + const known = this.capabilityContext.supports(key); + if (known !== undefined && !options.force) { + return known; + } + + const probes = this.collectProbes(); + const probe = probes.find((entry) => entry.capability === key); + if (!probe) { + return known; + } + + const status = await this.probeStatus(probe.request); + const supported = interpretProbe(key, status); + this.capabilityContext.applyProbes({ [key]: supported }); + return supported; + } + + /** + * Probe the connected LAPI to discover its capabilities. + * + * The client must be authenticated first (call `login()`). When + * `lapiVersion` is declared, capabilities are already known and no request + * is sent. + */ + public async detectCapabilities(): Promise { + const current = this.getCapabilities(); + if (current.source === 'declared') { + return current; + } + + const probes = this.collectProbes(); + const observed: Partial> = {}; + + await Promise.all( + probes.map(async ({ capability, request }) => { + const status = await this.probeStatus(request); + const supported = interpretProbe(capability, status); + if (supported !== undefined) { + observed[capability] = supported; + } + }) + ); + + this.capabilityContext.applyProbes(observed); + return this.getCapabilities(); + } + + protected requireCapability(capability: LapiCapabilityInput): void { + this.capabilityContext.assertSupport(capability); + } + + /** + * Probes shared by bouncers and watchers. Each authentication mode adds the + * endpoints it is allowed to reach: `/v1/decisions` is bouncer-only, while + * a watcher probes `/v1/alerts` and the allowlist routes. + */ + protected collectProbes(): Array<{ capability: LapiCapability; request: () => Promise }> { + return []; + } + + private async probeStatus(request: () => Promise): Promise { + try { + const response = (await request()) as { status?: number } | undefined; + return response?.status ?? 200; + } catch (error) { + if (axios.isAxiosError(error) && error.response) { + return error.response.status; + } + + // The response interceptor wraps HTTP failures in CrowdSecServerError, + // which keeps the status in `code`. + const code = (error as { code?: unknown } | undefined)?.code; + if (typeof code === 'number' && code >= 100 && code < 600) { + return code; + } + + return undefined; + } + } + public abstract login(): Promise; /** diff --git a/packages/crowdsec-client/src/Clients/WatcherClient.ts b/packages/crowdsec-client/src/Clients/WatcherClient.ts index 8793df618..5b8aee8d6 100644 --- a/packages/crowdsec-client/src/Clients/WatcherClient.ts +++ b/packages/crowdsec-client/src/Clients/WatcherClient.ts @@ -3,6 +3,7 @@ import { createDebugger } from '../utils.js'; import type { IHTTPOptions, ITLSAuthentication, IWatcherAuthentication, IWatcherClientOptions } from '../interfaces/index.js'; import type { AxiosResponse } from 'axios'; import type { WatcherAuthRequest, WatcherAuthResponse, WatcherRegistrationRequest } from '../types/index.js'; +import { LapiCapability } from '../Capabilities.js'; import { DecisionsWatcher } from '../Decisions/DecisionsWatcher.js'; import { Alerts } from '../Alerts/Alerts.js'; import { Allowlists } from '../Allowlists/Allowlists.js'; @@ -14,6 +15,7 @@ export class WatcherClient extends CrowdSecClient { private autoRenewTimeout?: NodeJS.Timeout; private heartbeatTimeout?: NodeJS.Timeout; + private stopped = false; private readonly auth?: Omit; readonly #password?: string; @@ -44,15 +46,20 @@ export class WatcherClient extends CrowdSecClient { this.scenarios = options.scenarios ?? []; this.heartbeat = options.heartbeat ?? true; - this.Decisions = new DecisionsWatcher({ httpClient: this.http }); - this.Alerts = new Alerts({ httpClient: this.http }); - this.Allowlists = new Allowlists({ httpClient: this.http }); + this.Decisions = new DecisionsWatcher({ httpClient: this.http, capabilities: this.capabilityContext }); + this.Alerts = new Alerts({ httpClient: this.http, capabilities: this.capabilityContext }); + this.Allowlists = new Allowlists({ httpClient: this.http, capabilities: this.capabilityContext }); } private async _login() { const localDebug = this.debug.extend('_login'); localDebug('start _login'); + if (this.stopped) { + localDebug('client is stopped, skipping login'); + return; + } + if (this.autoRenewTimeout) { clearTimeout(this.autoRenewTimeout); } @@ -81,7 +88,7 @@ export class WatcherClient extends CrowdSecClient { Authorization: `Bearer ${res.token}` }); - if (!this.auth || this.auth.autoRenew) { + if (!this.stopped && (!this.auth || this.auth.autoRenew)) { // 5m const renewTimeBeforeEnd = 5 * 60 * 1000; const renewInTime = new Date(res.expire).getTime() - renewTimeBeforeEnd - Date.now(); @@ -98,49 +105,124 @@ export class WatcherClient extends CrowdSecClient { } async login(): Promise { + if (this.stopped) { + throw new CrowdsecClientError('client is stopped', EErrorsCodes.CONNECTION_FAILED); + } + await this._login(); + if (this.stopped) { + throw new CrowdsecClientError('client is stopped', EErrorsCodes.CONNECTION_FAILED); + } const connectionResult = await this.testConnection(); - if (this.heartbeat) { + + if (this.options.detectCapabilities) { + await this.detectCapabilities(); + } + + if (!this.stopped && this.heartbeat && this.supports(LapiCapability.heartbeat) !== false) { this.heartbeatLoop().catch((e) => this.debug('uncatched error from starting heartbeatLoop : %o', e)); } return connectionResult; } + protected collectProbes() { + // A watcher JWT is rejected on `/v1/decisions` (bouncer route), so probe + // the equivalent alert filters instead of inheriting decision probes. + return [ + { + capability: LapiCapability.containsFilter, + // Match the bouncer probe: `contains` is only meaningful with + // ip/range, so send a TEST-NET address. + request: () => this.http.get('/v1/alerts', { params: { contains: false, ip: '192.0.2.1', limit: 1 } }) + }, + { + capability: LapiCapability.alertOriginFilter, + request: () => this.http.get('/v1/alerts', { params: { origin: 'cscli', limit: 1 } }) + }, + { + capability: LapiCapability.heartbeat, + request: () => this.http.get('/v1/heartbeat') + }, + { + capability: LapiCapability.allowlists, + // Do not download every allowlist item just to detect the route. + request: () => this.http.get('/v1/allowlists', { params: { with_content: false } }) + }, + { + capability: LapiCapability.allowlistsBulkCheck, + request: () => this.http.post('/v1/allowlists/check', { targets: [] }) + }, + { + capability: LapiCapability.alertKindFilter, + request: () => this.http.get('/v1/alerts', { params: { kind: 'cscli', limit: 1 } }) + } + ]; + } + public async testConnection(): Promise { return this._testConnection('/v1/alerts'); } private async heartbeatLoop() { const localDebug = this.debug.extend('heartbeatLoop'); + if (this.stopped) { + return; + } if (this.heartbeatTimeout) { clearTimeout(this.heartbeatTimeout); } + if (this.supports(LapiCapability.heartbeat) === false) { + localDebug('heartbeat is not supported by this LAPI, disabling it'); + return; + } + localDebug('start heartbeat'); + let disable = false; try { await this.http.get('/v1/heartbeat'); localDebug('Heartbeat sent'); } catch (e) { localDebug('error %o', e); + if ((e as { code?: unknown } | undefined)?.code === 404) { + // Older LAPIs have no heartbeat route: stop retrying and record + // the fact so a declared/known state stays consistent. + this.capabilityContext.learn(LapiCapability.heartbeat, false); + disable = true; + localDebug('heartbeat route not found, disabling the loop'); + } } finally { - const timer = typeof this.heartbeat === 'number' ? this.heartbeat : 30000; - localDebug('next heartbeat will be send at %o', new Date(Date.now() + timer)); - setTimeout(() => { - this.heartbeatLoop().catch((e) => this.debug('uncatched error from heartbeatLoop : %o', e)); - }, timer); + if (disable || this.stopped) { + this.heartbeatTimeout = undefined; + } else { + const timer = typeof this.heartbeat === 'number' ? this.heartbeat : 30000; + if (timer <= 0) { + this.heartbeatTimeout = undefined; + } else { + localDebug('next heartbeat will be send at %o', new Date(Date.now() + timer)); + this.heartbeatTimeout = setTimeout(() => { + this.heartbeatLoop().catch((e) => this.debug('uncatched error from heartbeatLoop : %o', e)); + }, timer); + } + } } } /** * Allow to register a watcher on CLAPI * you need to validate on the local machine + * @remarks The optional `registration_token` field requires CrowdSec LAPI 1.6.3 or newer. * @param options */ public async registerWatcher(options: WatcherRegistrationRequest) { return (await this.http.post, WatcherRegistrationRequest>('/v1/watchers', options)).data; } + /** + * Register a watcher without keeping a client instance. + * @remarks The optional `registration_token` field requires CrowdSec LAPI 1.6.3 or newer. + */ public static async registerWatcher(options: WatcherRegistrationRequest & IHTTPOptions) { const httpClient = CrowdSecClient.getHTTPClient({ url: options.url, @@ -152,7 +234,8 @@ export class WatcherClient extends CrowdSecClient { return ( await httpClient.post, WatcherRegistrationRequest>('/v1/watchers', { password: options.password, - machine_id: options.machine_id + machine_id: options.machine_id, + registration_token: options.registration_token }) ).data; } @@ -160,14 +243,17 @@ export class WatcherClient extends CrowdSecClient { /** * Delete the current watcher from the LAPI. * Useful to cleanup an auto-registered watcher. + * @since CrowdSec 1.6.9 */ public async deleteWatcher(): Promise { + this.requireCapability(LapiCapability.watcherSelfDelete); await this.http.delete>('/v1/watchers/self'); } /** * Delete a watcher from the LAPI using its credentials. * Useful to cleanup an auto-registered watcher without keeping a client instance. + * @since CrowdSec 1.6.9 * @param options - the machine credentials + connection options */ public static async deleteWatcher(options: WatcherRegistrationRequest & IHTTPOptions): Promise { @@ -187,11 +273,14 @@ export class WatcherClient extends CrowdSecClient { } public async stop() { + this.stopped = true; if (this.heartbeatTimeout) { clearTimeout(this.heartbeatTimeout); + this.heartbeatTimeout = undefined; } if (this.autoRenewTimeout) { clearTimeout(this.autoRenewTimeout); + this.autoRenewTimeout = undefined; } } } diff --git a/packages/crowdsec-client/src/Decisions/Decision.ts b/packages/crowdsec-client/src/Decisions/Decision.ts index 238c3eb3c..c1577c0ec 100644 --- a/packages/crowdsec-client/src/Decisions/Decision.ts +++ b/packages/crowdsec-client/src/Decisions/Decision.ts @@ -11,6 +11,11 @@ export class Decision> = []; - private getStreamTimeout?: NodeJS.Timeout; + /** Per-stream timer: pausing/closing one stream must not stop another. */ + private readonly streamTimeouts = new WeakMap, NodeJS.Timeout>(); + private readonly streamRunning = new WeakSet>(); + /** + * Fetch one page of the decisions stream. + * @since CrowdSec 1.0.0 + * @remarks `scopes` requires CrowdSec LAPI 1.1.0; `origins` and `scenarios_*` require 1.3.3. + * @throws {FeatureNotSupportedError} when a used filter is not supported by the connected LAPI. + */ public async getRawStream(options?: { startup?: boolean; scopes?: string | Array; @@ -33,6 +42,17 @@ export class DecisionsBouncer extends BaseSubObject { }): Promise { debug('getRawStream(%o)', options); + if (options?.scopes !== undefined) { + this.requireCapability(LapiCapability.streamScopes); + } + if ( + options?.origins !== undefined || + options?.scenarios_containing !== undefined || + options?.scenarios_not_containing !== undefined + ) { + this.requireCapability(LapiCapability.decisionOriginsFilter); + } + const params = ((): Decisions.GetDecisionsStream.RequestQuery => ({ ...options, scopes: options?.scopes ? forceArray(options.scopes).join(',') : undefined, @@ -57,6 +77,12 @@ export class DecisionsBouncer extends BaseSubObject { } } + /** + * Start a decision stream that polls the LAPI. + * @since CrowdSec 1.0.0 + * @remarks `scopes` requires CrowdSec LAPI 1.1.0; `origins` and `scenarios_*` require 1.3.3. + * @throws {FeatureNotSupportedError} when a used filter is not supported by the connected LAPI. + */ public getStream( optionsParam?: { interval?: number; @@ -70,6 +96,17 @@ export class DecisionsBouncer extends BaseSubObject { const localDebug = debug.extend('getStream'); localDebug('(%o) with cb %o', optionsParam, !!cb); + if (optionsParam?.scopes !== undefined) { + this.requireCapability(LapiCapability.streamScopes); + } + if ( + optionsParam?.origins !== undefined || + optionsParam?.scenarios_containing !== undefined || + optionsParam?.scenarios_not_containing !== undefined + ) { + this.requireCapability(LapiCapability.decisionOriginsFilter); + } + const interval = optionsParam?.interval ?? 10000; const options = ((): Omit => ({ scopes: optionsParam?.scopes ? forceArray(optionsParam.scopes).join(',') : undefined, @@ -89,7 +126,12 @@ export class DecisionsBouncer extends BaseSubObject { decisionStream.once('close', () => { localDebug('receive close event'); - clearTimeout(this.getStreamTimeout); + const timeout = this.streamTimeouts.get(decisionStream); + if (timeout) { + clearTimeout(timeout); + } + this.streamTimeouts.delete(decisionStream); + this.streamRunning.delete(decisionStream); //remove from running streams this.runningStreams = this.runningStreams.filter((stream) => stream != decisionStream); @@ -97,7 +139,11 @@ export class DecisionsBouncer extends BaseSubObject { decisionStream.on('pause', () => { localDebug('receive pause event'); - clearTimeout(this.getStreamTimeout); + const timeout = this.streamTimeouts.get(decisionStream); + if (timeout) { + clearTimeout(timeout); + } + this.streamTimeouts.delete(decisionStream); }); decisionStream.on('resume', () => { @@ -142,8 +188,17 @@ export class DecisionsBouncer extends BaseSubObject { ) { const localDebug = debug.extend('getStreamLoop'); localDebug('start loop'); - if (this.getStreamTimeout) { - clearTimeout(this.getStreamTimeout); + + if (this.streamRunning.has(decisionStream)) { + localDebug('loop already running, skipping'); + return; + } + this.streamRunning.add(decisionStream); + + const existing = this.streamTimeouts.get(decisionStream); + if (existing) { + clearTimeout(existing); + this.streamTimeouts.delete(decisionStream); } try { @@ -152,6 +207,8 @@ export class DecisionsBouncer extends BaseSubObject { } catch (e) { localDebug('loop error %o', e); decisionStream.emit('error', e); + } finally { + this.streamRunning.delete(decisionStream); } localDebug('end loop'); @@ -161,7 +218,8 @@ export class DecisionsBouncer extends BaseSubObject { } localDebug('prepare next loop'); - this.getStreamTimeout = setTimeout(() => { + const timeout = setTimeout(() => { + this.streamTimeouts.delete(decisionStream); this.getStreamLoopWrapper( { ...options, @@ -171,6 +229,7 @@ export class DecisionsBouncer extends BaseSubObject { interval ); }, interval); + this.streamTimeouts.set(decisionStream, timeout); } private streamToCallback( @@ -203,6 +262,16 @@ export class DecisionsBouncer extends BaseSubObject { this.runningStreams.forEach((stream) => stream.close()); } + /** + * Search decisions. + * @since CrowdSec 1.0.0 + * @remarks + * - `contains` requires CrowdSec LAPI 1.0.3; `origins` and `scenarios_*` require 1.3.3. + * - The decision `scope` filter is silently ignored on LAPI 1.3.3-1.6.0. Use + * `Alerts.search` (watcher) or a LAPI version outside that range when the + * scope must be enforced. + * @throws {FeatureNotSupportedError} when a used filter is not supported by the connected LAPI. + */ public async search( options?: Omit & { /** name of origins. If provided, then only the decisions originating from provided origins would be returned. */ @@ -211,9 +280,25 @@ export class DecisionsBouncer extends BaseSubObject { scenarios_containing?: string | Array; /** If provided, only the decisions created by scenarios, not containing any of the provided word would be returned. */ scenarios_not_containing?: string | Array; + /** + * Include simulated decisions. The LAPI excludes them by default and + * does not return the `simulated` field on `/v1/decisions`. + */ + simulated?: boolean; } ): Promise { debug('search(%o)', options); + + if (options?.contains !== undefined) { + this.requireCapability(LapiCapability.containsFilter); + } + if ( + options?.origins !== undefined || + options?.scenarios_containing !== undefined || + options?.scenarios_not_containing !== undefined + ) { + this.requireCapability(LapiCapability.decisionOriginsFilter); + } const params = ((): Omit => ({ ...options, origins: options?.origins ? forceArray(options.origins).join(',') : undefined, diff --git a/packages/crowdsec-client/src/Decisions/DecisionsStream.ts b/packages/crowdsec-client/src/Decisions/DecisionsStream.ts index 09eaae3e6..29b336cc2 100644 --- a/packages/crowdsec-client/src/Decisions/DecisionsStream.ts +++ b/packages/crowdsec-client/src/Decisions/DecisionsStream.ts @@ -90,13 +90,13 @@ export class DecisionsStream { - const i = array.length - index; - if (!array[i]) { - array.splice(i, 1); + // Delete empty decisions (processed above), keep the ones that were not + // emitted because the stream was paused. + for (let i = decisions.length - 1; i >= 0; i--) { + if (!decisions[i]) { + decisions.splice(i, 1); } - }); + } } private loopWrapper() { @@ -116,10 +116,11 @@ export class DecisionsStream { try { - await Promise.all([ - this.emitDecisions('deleted', this.decisions.deleted), - this.emitDecisions('added', this.decisions.added) - ]); + // Apply deletions before additions: a renewal can appear as a + // deleted+added pair in the same poll, and running them + // concurrently could re-add an entry that was just removed. + await this.emitDecisions('deleted', this.decisions.deleted); + await this.emitDecisions('added', this.decisions.added); } catch (e) { this.handleError(new CrowdsecClientError('loop error', EErrorsCodes.UNKNOWN_ERROR, e as Error)); } finally { diff --git a/packages/crowdsec-client/src/Decisions/DecisionsWatcher.ts b/packages/crowdsec-client/src/Decisions/DecisionsWatcher.ts index 612fcd245..44b0a53cf 100644 --- a/packages/crowdsec-client/src/Decisions/DecisionsWatcher.ts +++ b/packages/crowdsec-client/src/Decisions/DecisionsWatcher.ts @@ -1,12 +1,104 @@ import { BaseSubObject } from '../BaseSubObject.js'; -import type { Decisions } from '../types/index.js'; +import { LapiCapability } from '../Capabilities.js'; +import type { Decisions, DeleteDecisionsQuery } from '../types/index.js'; +import { withContainsDefault } from '../utils.js'; import type { AxiosResponse } from 'axios'; +function httpStatus(error: unknown): unknown { + const candidate = error as { code?: unknown; response?: { status?: unknown } } | undefined; + // Wrapped errors carry the numeric HTTP status in `code`; a raw AxiosError + // uses a string `code` and keeps the status in `response.status`. + return typeof candidate?.code === 'number' ? candidate.code : candidate?.response?.status; +} + +function isUnknownFilter(error: unknown, parameter: 'scope' | 'scopes'): boolean { + const candidate = error as { message?: unknown }; + + if (httpStatus(error) !== 500 || typeof candidate?.message !== 'string') { + return false; + } + + // The message format is not stable across releases: 1.8.x answers + // "'scope' doesn't exist: invalid filter", older versions use variants + // such as "unknown filter parameter 'scope'". Match the parameter name + // together with any of the documented rejection wordings instead of a + // single sentence. + const mentionsParameter = new RegExp(String.raw`\b${parameter}\b`, 'i').test(candidate.message); + if (!mentionsParameter) { + return false; + } + + return /(doesn'?t exist|unknown|invalid)[\s\S]{0,60}filter|filter[\s\S]{0,60}(doesn'?t exist|unknown|invalid)/i.test(candidate.message); +} + +function requestedScopeOf(options: DeleteDecisionsQuery): string | undefined { + const legacy = options as { scope?: string; scopes?: string }; + return legacy.scopes ?? legacy.scope; +} + +function withScopeParameter(options: DeleteDecisionsQuery, parameter: 'scope' | 'scopes', value: string): DeleteDecisionsQuery { + const query: Record = { ...options }; + delete query.scope; + delete query.scopes; + query[parameter] = value; + return query as DeleteDecisionsQuery; +} + export class DecisionsWatcher extends BaseSubObject { public async deleteById(id: string): Promise { - return (await this.http.delete(`/v1/decisions/${id}`)).data; + return (await this.http.delete(`/v1/decisions/${encodeURIComponent(id)}`)).data; + } + + /** + * Delete decisions matching a filter. + * @since CrowdSec 1.0.0 + * @remarks + * - `contains` requires CrowdSec LAPI 1.0.3. It is set to `false` + * automatically when `ip`/`range` is used, unless the caller overrides it. + * - `scenario` requires CrowdSec LAPI 1.4.2. + * - The LAPI delete filter uses `scope` before 1.3.3 and `scopes` from + * 1.3.3. The client uses the known capability, or tries `scopes` and + * falls back to `scope` on the specific "invalid filter" 500, then + * remembers the result for the next calls. + * @throws {FeatureNotSupportedError} when a used filter is not supported by the connected LAPI. + */ + public async delete(rawOptions: DeleteDecisionsQuery): Promise { + const options = withContainsDefault(rawOptions); + + if (options.contains !== undefined) { + this.requireCapability(LapiCapability.containsFilter); + } + if (options.scenario !== undefined) { + this.requireCapability(LapiCapability.decisionScenarioDelete); + } + + const requestedScope = requestedScopeOf(options); + if (requestedScope === undefined) { + return this.send(options); + } + + const supported = this.capabilities?.supports(LapiCapability.decisionScopesDelete); + const preferred = supported === false ? 'scope' : 'scopes'; + const alternate = preferred === 'scopes' ? 'scope' : 'scopes'; + + try { + const result = await this.send(withScopeParameter(options, preferred, requestedScope)); + this.capabilities?.learn(LapiCapability.decisionScopesDelete, preferred === 'scopes'); + return result; + } catch (error) { + if (!isUnknownFilter(error, preferred)) { + throw error; + } + + // The failure happened while parsing the filter, before any query + // executed, so retrying with the other parameter name is safe. + const result = await this.send(withScopeParameter(options, alternate, requestedScope)); + this.capabilities?.learn(LapiCapability.decisionScopesDelete, alternate === 'scopes'); + return result; + } } - public async delete(options: Decisions.DeleteDecisions.RequestQuery): Promise { + + private async send(options: DeleteDecisionsQuery): Promise { return ( await this.http.delete< Decisions.DeleteDecisions.ResponseBody, diff --git a/packages/crowdsec-client/src/Errors/EErrorsCodes.ts b/packages/crowdsec-client/src/Errors/EErrorsCodes.ts index b689f1c4c..9fbcb6410 100644 --- a/packages/crowdsec-client/src/Errors/EErrorsCodes.ts +++ b/packages/crowdsec-client/src/Errors/EErrorsCodes.ts @@ -4,7 +4,11 @@ export enum EErrorsCodes { CONNECTION_TEST_FAILED = 1, CONNECTION_FAILED = 2, - // CODE THAT CAN COME FROM UNIFI ( 100 to 600 ) + /** The connected LAPI does not support a required capability. */ + FEATURE_NOT_SUPPORTED = 3, + /** The capability is unknown and the client runs in strict mode. */ + LAPI_VERSION_UNKNOWN = 4, + CONTINUE = 100, SWITCHING_PROTOCOLS = 101, OK = 200, diff --git a/packages/crowdsec-client/src/Errors/FeatureNotSupportedError.ts b/packages/crowdsec-client/src/Errors/FeatureNotSupportedError.ts new file mode 100644 index 000000000..b060c0303 --- /dev/null +++ b/packages/crowdsec-client/src/Errors/FeatureNotSupportedError.ts @@ -0,0 +1,26 @@ +import type { LapiCapability } from '../Capabilities.js'; +import { CrowdsecClientError } from './CrowdsecClientError.js'; +import { EErrorsCodes } from './EErrorsCodes.js'; + +/** + * Raised when a method requires a CrowdSec LAPI capability the connected + * server does not provide. + */ +export class FeatureNotSupportedError extends CrowdsecClientError { + public readonly capability: LapiCapability; + public readonly minimumVersion: string; + public readonly detectedVersion?: string; + + public constructor(capability: LapiCapability, minimumVersion: string, detectedVersion?: string) { + const detected = detectedVersion ? ` (detected ${detectedVersion})` : ''; + super( + `This feature requires CrowdSec LAPI ${minimumVersion} or newer${detected}: capability "${capability}" is not supported.`, + EErrorsCodes.FEATURE_NOT_SUPPORTED + ); + + this.name = 'FeatureNotSupportedError'; + this.capability = capability; + this.minimumVersion = minimumVersion; + this.detectedVersion = detectedVersion; + } +} diff --git a/packages/crowdsec-client/src/Errors/LapiVersionUnknownError.ts b/packages/crowdsec-client/src/Errors/LapiVersionUnknownError.ts new file mode 100644 index 000000000..b834c42e7 --- /dev/null +++ b/packages/crowdsec-client/src/Errors/LapiVersionUnknownError.ts @@ -0,0 +1,24 @@ +import type { LapiCapability } from '../Capabilities.js'; +import { CrowdsecClientError } from './CrowdsecClientError.js'; +import { EErrorsCodes } from './EErrorsCodes.js'; + +/** + * Raised in strict mode when the client could not determine whether the + * connected LAPI supports a capability. + */ +export class LapiVersionUnknownError extends CrowdsecClientError { + public readonly capability: LapiCapability; + public readonly minimumVersion: string; + + public constructor(capability: LapiCapability, minimumVersion: string) { + super( + `Cannot verify that the CrowdSec LAPI supports "${capability}" (requires ${minimumVersion} or newer). ` + + 'Declare `lapiVersion`, enable `detectCapabilities`, or disable `strictCapabilities`.', + EErrorsCodes.LAPI_VERSION_UNKNOWN + ); + + this.name = 'LapiVersionUnknownError'; + this.capability = capability; + this.minimumVersion = minimumVersion; + } +} diff --git a/packages/crowdsec-client/src/Errors/__Error.ts b/packages/crowdsec-client/src/Errors/__Error.ts index 4fdd51429..d1b393f76 100644 --- a/packages/crowdsec-client/src/Errors/__Error.ts +++ b/packages/crowdsec-client/src/Errors/__Error.ts @@ -1,7 +1,6 @@ import { EErrorsCodes } from './EErrorsCodes.js'; -export class __Error implements Error { - public stack: string; +export class __Error extends Error { protected _message: string; /** * can also contain error like certificates error (https://nodejs.org/api/tls.html#tls_x509_certificate_error_codes) or other errors . Can be a string, or a number @@ -12,7 +11,6 @@ export class __Error implements Error { */ public code: EErrorsCodes; public exception: Error; - public message: string; public constructor(message: string | Error = '', code: EErrorsCodes = EErrorsCodes.UNKNOWN_ERROR, exception?: Error | string | null) { if (message instanceof Error) { @@ -20,6 +18,8 @@ export class __Error implements Error { message = message.message; } + super(typeof message === 'string' ? message : String(message)); + this.errorCode = code; this.code = code; @@ -33,7 +33,7 @@ export class __Error implements Error { return `${this.name} : ${this._message}\n${tmpStack}`; }; - this._message = message; + this._message = typeof message === 'string' ? message : String(message); this.message = this._message; this.exception = typeof exception === typeof '' ? new Error(exception as string) : (exception as Error); @@ -51,7 +51,7 @@ export class __Error implements Error { strComponents.push(`${name}${errorCodeStr} : ${message} \n`); - strComponents.push(this.stack); + strComponents.push(this.stack ?? ''); return strComponents.join(' '); }; diff --git a/packages/crowdsec-client/src/Errors/index.ts b/packages/crowdsec-client/src/Errors/index.ts index 248a3450c..69293bb6c 100644 --- a/packages/crowdsec-client/src/Errors/index.ts +++ b/packages/crowdsec-client/src/Errors/index.ts @@ -2,4 +2,6 @@ export * from './__Error.js'; export * from './AxiosError.js'; export * from './CrowdsecClientError.js'; export * from './CrowdSecServerError.js'; +export * from './FeatureNotSupportedError.js'; +export * from './LapiVersionUnknownError.js'; export * from './EErrorsCodes.js'; diff --git a/packages/crowdsec-client/src/index.ts b/packages/crowdsec-client/src/index.ts index 560fe0e3d..a762f13d9 100644 --- a/packages/crowdsec-client/src/index.ts +++ b/packages/crowdsec-client/src/index.ts @@ -8,9 +8,10 @@ export * from './Decisions/index.js'; export * from './Errors/index.js'; export * from './interfaces/index.js'; export * from './BaseSubObject.js'; +export * from './Capabilities.js'; export * from './EventEmitter.js'; export * from './duration.js'; export { APITypes }; -export type { DeleteAlertsQuery, SearchAlertsQuery } from './types/overrides.js'; +export type { DeleteAlertsQuery, DeleteDecisionsQuery, SearchAlertsQuery } from './types/overrides.js'; export const VERSION = pkg.version; diff --git a/packages/crowdsec-client/src/interfaces/ICrowdSecClientOptions.ts b/packages/crowdsec-client/src/interfaces/ICrowdSecClientOptions.ts index 4cc48690c..f711726c2 100644 --- a/packages/crowdsec-client/src/interfaces/ICrowdSecClientOptions.ts +++ b/packages/crowdsec-client/src/interfaces/ICrowdSecClientOptions.ts @@ -1,3 +1,23 @@ import { IHTTPOptions } from './IHTTPOptions.js'; -export interface ICrowdSecClientOptions extends IHTTPOptions {} +export interface ICrowdSecClientOptions extends IHTTPOptions { + /** + * CrowdSec LAPI version the client talks to (for example `1.6.6`). + * When set, capabilities are resolved locally without probing. + */ + lapiVersion?: string; + /** + * Probe the LAPI after login to discover the supported capabilities. + * Ignored when `lapiVersion` is set. + * + * @default false + */ + detectCapabilities?: boolean; + /** + * Throw when a capability is known to be unsupported, or when it cannot be + * verified. Without it, unverified capabilities are attempted optimistically. + * + * @default false + */ + strictCapabilities?: boolean; +} diff --git a/packages/crowdsec-client/src/pkg.ts b/packages/crowdsec-client/src/pkg.ts index c444b91f7..b0133f15a 100644 --- a/packages/crowdsec-client/src/pkg.ts +++ b/packages/crowdsec-client/src/pkg.ts @@ -1 +1 @@ -export const pkg = { name: 'crowdsec-client', version: '1.3.0' }; +export const pkg = { name: 'crowdsec-client', version: '1.4.0' }; diff --git a/packages/crowdsec-client/src/types/overrides.ts b/packages/crowdsec-client/src/types/overrides.ts index 3a6f19e6d..8f63761fb 100644 --- a/packages/crowdsec-client/src/types/overrides.ts +++ b/packages/crowdsec-client/src/types/overrides.ts @@ -1,5 +1,6 @@ import type { GoDuration } from '../duration.js'; import type { Alerts } from './generated/AlertsRoute.js'; +import type { Decisions } from './generated/DecisionsRoute.js'; export type { GoDuration } from '../duration.js'; @@ -7,6 +8,17 @@ export type { GoDuration } from '../duration.js'; * `contains` and `kind` are supported by the LAPI alert filter but missing from * the generated swagger type. * + * Validated against CrowdSec 1.8.1 (Docker, `alertfilter.go`): + * - `ip`/`range` match alerts through their decisions, so alerts without + * decisions never match those filters. + * - `contains` defaults to true at the LAPI level: true = decision range + * contains the value, false = decision range is contained within the value. + * `Alerts.delete`/`Decisions.delete` make it explicit (`false`) when + * `ip`/`range` is set, unless the caller passes `contains`. + * - `kind` is case-sensitive (`WAF` matches nothing); `origin` filters the + * origin of the decisions attached to the alert, not the alert kind. + * - An unknown `kind`/`origin` returns an empty list, not an error. + * * @see https://github.com/crowdsecurity/crowdsec/blob/909b5157986a2b2c2163300fdaef5ed01289f7d2/pkg/database/alertfilter.go */ export type SearchAlertsQuery = Omit & { @@ -20,15 +32,49 @@ export type SearchAlertsQuery = Omit 500 `filter parameter + * 'alert_source' is unknown`. + * - `DELETE /v1/alerts?origin=...`, `kind=...`, `contains=...` and + * `decision_type=...` are accepted. * * @see https://github.com/crowdsecurity/crowdsec/blob/909b5157986a2b2c2163300fdaef5ed01289f7d2/pkg/database/alertfilter.go#L44-L67 */ -export type DeleteAlertsQuery = Omit & { +export type DeleteAlertsQuery = Omit & { + /** @deprecated Rejected by LAPI 1.8.1; use `origin`. */ + alert_source?: string; since?: GoDuration; until?: GoDuration; decision_type?: string; kind?: string; contains?: boolean; + origin?: string; +}; + +/** + * Decision delete filters. + * + * Validated against CrowdSec 1.8.1 (Docker): + * - `DELETE /v1/decisions?scope=Country` -> 500 `'scope' doesn't exist: + * invalid filter`; `scopes=Country` is accepted. + * - `contains` is supported and defaults to true. Omitting it on an IP delete + * also expires every Range decision that contains the IP; `contains=false` + * restricts the delete to decisions contained within the value. + * `Decisions.delete` applies `contains:false` automatically for `ip`/`range` + * unless the caller overrides it. + * + * @see https://github.com/crowdsecurity/crowdsec/blob/v1.8.1/pkg/database/decisions.go + */ +export type DeleteDecisionsQuery = Omit & { + /** @deprecated Rejected by LAPI 1.8.1 (`'scope' doesn't exist`); use `scopes`. */ + scope?: string; + /** + * A single scope. The delete filter uses `ScopeEQ(value)`, so a + * comma-separated list does not match; only the plural name is required. + */ + scopes?: string; + contains?: boolean; }; diff --git a/packages/crowdsec-client/src/utils.ts b/packages/crowdsec-client/src/utils.ts index 4e0e67dc1..3ba25790b 100644 --- a/packages/crowdsec-client/src/utils.ts +++ b/packages/crowdsec-client/src/utils.ts @@ -51,7 +51,7 @@ export const getUrlRepresentation = (req: RawAxiosRequestConfig, hidePassword = }; export const parseExpiration = (duration: string) => { - const durationRe = /(?[-+]?)(?:(?\d{1,8})h)?(?:(?\d{1,2})m)?(?:(?\d{1,2}(?:\.\d+)?)s)?/gm.exec( + const durationRe = /^(?[-+]?)(?:(?\d{1,8})h)?(?:(?\d{1,2})m)?(?:(?\d{1,2}(?:\.\d+)?)s)?$/.exec( duration ); @@ -59,6 +59,10 @@ export const parseExpiration = (duration: string) => { throw new Error(`fail to parse duration "${duration}"`); } + if (!durationRe.groups.hours && !durationRe.groups.minutes && !durationRe.groups.seconds) { + throw new Error(`fail to parse duration "${duration}"`); + } + const multiplier = durationRe.groups.multiplier === '-' ? -1 : 1; const hours = parseInt(durationRe.groups.hours); const minutes = parseInt(durationRe.groups.minutes); @@ -76,6 +80,19 @@ export const parseExpiration = (duration: string) => { export const forceArray = (p: Readonly>): Array => (Array.isArray(p) ? (p as T[]) : [p as T]); +/** + * A delete filtered by `ip`/`range` must not silently widen to a Range decision + * that contains the value. The LAPI `contains` filter defaults to true, so make + * the safe value explicit unless the caller chose one. + */ +export function withContainsDefault(options: T): T { + if (options.contains === undefined && (options.ip !== undefined || options.range !== undefined)) { + return { ...options, contains: false }; + } + + return options; +} + /** * the job of this function, is to unblock the loop when running a long while * ( else the event loop is blocked, waiting for the loop to end ) diff --git a/packages/crowdsec-client/tests/Alerts/Alerts.test.ts b/packages/crowdsec-client/tests/Alerts/Alerts.test.ts index 5e3d39aef..90896205e 100644 --- a/packages/crowdsec-client/tests/Alerts/Alerts.test.ts +++ b/packages/crowdsec-client/tests/Alerts/Alerts.test.ts @@ -2,8 +2,13 @@ import { describe, it, afterEach, beforeEach, expect, vi } from 'vitest'; import type { DeleteAlertsQuery, SearchAlertsQuery } from '../../src/types/index.js'; import type { Alerts } from '../../src/index.js'; +import { LapiCapability } from '../../src/Capabilities.js'; -vi.mock('../../src/BaseSubObject.js', () => ({ BaseSubObject: vi.fn() })); +vi.mock('../../src/BaseSubObject.js', () => ({ + BaseSubObject: class { + requireCapability = vi.fn(); + } +})); describe('DecisionsWatcher', () => { const httpDeleteMock = vi.fn(); @@ -85,7 +90,18 @@ describe('DecisionsWatcher', () => { expect(await alerts.delete(deleteOptions)).toBe('test'); - expect(httpDeleteMock).toHaveBeenCalledWith('/v1/alerts', { params: deleteOptions }); + expect(httpDeleteMock).toHaveBeenCalledWith('/v1/alerts', { params: { ...deleteOptions, contains: false } }); + // The implicit contains=false must be gated like an explicit one. + // @ts-ignore + expect(alerts.requireCapability).toHaveBeenCalledWith(LapiCapability.containsFilter); + }); + + it('should keep an explicit contains value on an ip delete', async () => { + httpDeleteMock.mockImplementationOnce(() => ({ data: 'test' })); + + await alerts.delete({ ip: '1.2.3.4', contains: true }); + + expect(httpDeleteMock).toHaveBeenCalledWith('/v1/alerts', { params: { ip: '1.2.3.4', contains: true } }); }); it('should forward duration and extended delete filters', async () => { @@ -101,6 +117,16 @@ describe('DecisionsWatcher', () => { expect(httpDeleteMock).toHaveBeenCalledWith('/v1/alerts', { params: deleteOptions }); }); + it('should require the origin capability when deleting by origin', async () => { + httpDeleteMock.mockImplementationOnce(() => ({ data: 'test' })); + + await alerts.delete({ origin: 'cscli' }); + + expect((alerts as unknown as { requireCapability: ReturnType }).requireCapability).toHaveBeenCalledWith( + 'alertOriginFilter' + ); + }); + it('should call delete with id', async () => { httpDeleteMock.mockImplementationOnce(() => ({ data: 'test' })); @@ -108,4 +134,12 @@ describe('DecisionsWatcher', () => { expect(httpDeleteMock).toHaveBeenCalledWith('/v1/alerts/123'); }); + + it('should encode the id segment', async () => { + httpDeleteMock.mockImplementationOnce(() => ({ data: 'test' })); + + await alerts.deleteById('1/../watchers/self'); + + expect(httpDeleteMock).toHaveBeenCalledWith('/v1/alerts/1%2F..%2Fwatchers%2Fself'); + }); }); diff --git a/packages/crowdsec-client/tests/Allowlists/Allowlists.test.ts b/packages/crowdsec-client/tests/Allowlists/Allowlists.test.ts index 9bb960b48..a6742f75f 100644 --- a/packages/crowdsec-client/tests/Allowlists/Allowlists.test.ts +++ b/packages/crowdsec-client/tests/Allowlists/Allowlists.test.ts @@ -1,8 +1,13 @@ import { describe, it, afterEach, beforeEach, expect, vi } from 'vitest'; +import { FeatureNotSupportedError } from '../../src/index.js'; import type { Allowlists } from '../../src/index.js'; -vi.mock('../../src/BaseSubObject.js', () => ({ BaseSubObject: vi.fn() })); +vi.mock('../../src/BaseSubObject.js', () => ({ + BaseSubObject: class { + requireCapability = vi.fn(); + } +})); describe('Allowlists', () => { const httpGetMock = vi.fn(); @@ -95,4 +100,56 @@ describe('Allowlists', () => { targets: ['1.2.3.4', '5.6.7.8'] }); }); + + it('should fall back to per-value checks when the bulk capability is known to be absent', async () => { + (allowlists as unknown as { capabilities: unknown }).capabilities = { supports: () => false, learn: vi.fn() }; + httpGetMock.mockImplementation((url: string) => + Promise.resolve({ + data: url === '/v1/allowlists/check/1.2.3.4' ? { allowlisted: true, reason: 'my-list/1.2.3.4' } : { allowlisted: false } + }) + ); + + const result = await allowlists.bulkCheck(['1.2.3.4', '5.6.7.8']); + + expect(result).toEqual({ results: [{ target: '1.2.3.4', allowlists: ['unknown allowlist (matched item: my-list/1.2.3.4)'] }] }); + expect(httpPostMock).not.toHaveBeenCalled(); + }); + + it('should use the target when the single check has no reason', async () => { + (allowlists as unknown as { capabilities: unknown }).capabilities = { supports: () => false, learn: vi.fn() }; + httpGetMock.mockResolvedValue({ data: { allowlisted: true } }); + + const result = await allowlists.bulkCheck(['1.2.3.4']); + + expect(result).toEqual({ results: [{ target: '1.2.3.4', allowlists: ['unknown allowlist (matched item: 1.2.3.4)'] }] }); + }); + + it('should fall back when the bulk route answers 405 (LAPI 1.6.6-1.6.8)', async () => { + const learn = vi.fn(); + (allowlists as unknown as { capabilities: unknown }).capabilities = { supports: () => undefined, learn }; + httpPostMock.mockRejectedValueOnce({ code: 405 }); + httpGetMock.mockResolvedValue({ data: { allowlisted: true, reason: 'my-list/1.2.3.4' } }); + + const result = await allowlists.bulkCheck(['1.2.3.4']); + + expect(result.results).toEqual([{ target: '1.2.3.4', allowlists: ['unknown allowlist (matched item: my-list/1.2.3.4)'] }]); + expect(learn).toHaveBeenCalledWith('allowlistsBulkCheck', false); + }); + + it('should fall back on a raw Axios 404', async () => { + httpPostMock.mockRejectedValueOnce({ code: 'ERR_BAD_REQUEST', response: { status: 404 } }); + httpGetMock.mockResolvedValue({ data: { allowlisted: true, reason: 'my-list/1.2.3.4' } }); + + const result = await allowlists.bulkCheck(['1.2.3.4']); + + expect(result.results).toEqual([{ target: '1.2.3.4', allowlists: ['unknown allowlist (matched item: my-list/1.2.3.4)'] }]); + expect(httpGetMock).toHaveBeenCalledWith('/v1/allowlists/check/1.2.3.4'); + }); + + it('should raise a typed error when the per-value route is also missing', async () => { + httpPostMock.mockRejectedValueOnce({ code: 405 }); + httpGetMock.mockRejectedValueOnce({ code: 404 }); + + await expect(allowlists.bulkCheck(['1.2.3.4'])).rejects.toBeInstanceOf(FeatureNotSupportedError); + }); }); diff --git a/packages/crowdsec-client/tests/Capabilities.test.ts b/packages/crowdsec-client/tests/Capabilities.test.ts new file mode 100644 index 000000000..4376d9168 --- /dev/null +++ b/packages/crowdsec-client/tests/Capabilities.test.ts @@ -0,0 +1,241 @@ +import { describe, expect, it } from 'vitest'; +import { CAPABILITY_MIN_VERSION, CapabilityContext, compareLapiVersions, interpretProbe, parseLapiVersion } from '../src/Capabilities.js'; +import { FeatureNotSupportedError } from '../src/Errors/FeatureNotSupportedError.js'; +import { LapiVersionUnknownError } from '../src/Errors/LapiVersionUnknownError.js'; +import { Alerts } from '../src/Alerts/Alerts.js'; +import { Allowlists } from '../src/Allowlists/Allowlists.js'; +import type { AxiosInstance } from 'axios'; + +const fakeHttp = {} as AxiosInstance; + +describe('Capabilities', () => { + it('parses semver with an optional v prefix', () => { + expect(parseLapiVersion('1.6.6')).toEqual([1, 6, 6]); + expect(parseLapiVersion('v1.8.2')).toEqual([1, 8, 2]); + expect(parseLapiVersion('1.7')).toBeNull(); + expect(parseLapiVersion('1.8.2-beta')).toBeNull(); + expect(parseLapiVersion('1.8.2foo')).toBeNull(); + }); + + it('compares versions', () => { + expect(compareLapiVersions('1.6.6', '1.6.6')).toBe(0); + expect(compareLapiVersions('1.6.5', '1.6.6')).toBe(-1); + expect(compareLapiVersions('1.7.0', '1.6.9')).toBe(1); + }); + + it('resolves every capability from a declared version', () => { + const context = new CapabilityContext({ version: '1.6.6' }); + + expect(context.supports('containsFilter')).toBe(true); + expect(context.supports('streamScopes')).toBe(true); + expect(context.supports('heartbeat')).toBe(true); + expect(context.supports('decisionScopesDelete')).toBe(true); + expect(context.supports('allowlists')).toBe(true); + expect(context.supports('allowlistsBulkCheck')).toBe(false); + expect(context.supports('alertKindFilter')).toBe(false); + expect(context.getCapabilities().source).toBe('declared'); + }); + + it('estimates a probable version range from probes', () => { + const context = new CapabilityContext(); + context.applyProbes({ heartbeat: true, allowlists: false }); + + expect(context.getCapabilities().estimate).toEqual({ + minVersion: '1.4.0', + belowVersion: '1.6.6', + probable: '>=1.4.0 <1.6.6' + }); + }); + + it('narrows the range with newer capabilities', () => { + const context = new CapabilityContext(); + context.applyProbes({ allowlists: true, allowlistsBulkCheck: true, alertKindFilter: false }); + + expect(context.getCapabilities().estimate.probable).toBe('>=1.6.9 <1.7.7'); + }); + + it('reports an exact version when declared', () => { + const context = new CapabilityContext({ version: '1.8.2' }); + + expect(context.getCapabilities().estimate).toEqual({ + exactVersion: '1.8.2', + minVersion: '1.8.2', + probable: '1.8.2' + }); + }); + + it('returns unknown without any information', () => { + expect(new CapabilityContext().getCapabilities().estimate).toEqual({ probable: 'unknown' }); + }); + + it('infers older capabilities from a newer one and newer ones from a failure', () => { + const context = new CapabilityContext(); + context.applyProbes({ allowlists: true, alertKindFilter: false }); + + expect(context.supports('allowlists')).toBe(true); + expect(context.supports('alertDeleteById')).toBe(true); + expect(context.supports('alertKindFilter')).toBe(false); + expect(context.supports('lapiMetricsFeatures')).toBe(false); + expect(context.getCapabilities().source).toBe('probed'); + }); + + it('learns a capability from a real request without inferring the others', () => { + const context = new CapabilityContext(); + context.learn('decisionScopesDelete', false); + + expect(context.supports('decisionScopesDelete')).toBe(false); + // A request-level observation must not disable unrelated capabilities. + expect(context.supports('heartbeat')).toBeUndefined(); + expect(context.getCapabilities().source).toBe('observed'); + + const declared = new CapabilityContext({ version: '1.8.2' }); + declared.learn('decisionScopesDelete', false); + expect(declared.supports('decisionScopesDelete')).toBe(true); + expect(declared.getCapabilities().source).toBe('declared'); + }); + + it('does not narrow the probable version from a learned value', () => { + const context = new CapabilityContext(); + context.learn('decisionScopesDelete', false); + + // A single rejected request must not advertise an older LAPI version. + expect(context.getCapabilities().estimate.probable).toBe('unknown'); + }); + + it('keeps a probed source when an additional value is learned', () => { + const context = new CapabilityContext(); + // heartbeat (1.4.0) leaves the newer capabilities unresolved. + context.applyProbes({ heartbeat: true }); + expect(context.supports('alertDeleteById')).toBeUndefined(); + + context.learn('alertDeleteById', true); + + expect(context.supports('alertDeleteById')).toBe(true); + expect(context.getCapabilities().source).toBe('probed'); + }); + + it('does not propagate a learned value on a later probe', () => { + const context = new CapabilityContext(); + context.learn('heartbeat', false); + + // A later probe must not turn the learned heartbeat failure into a + // false negative for allowlists and the other newer capabilities. + context.applyProbes({ allowlists: true }); + + expect(context.supports('allowlists')).toBe(true); + expect(context.supports('allowlistsBulkCheck')).toBeUndefined(); + expect(context.supports('heartbeat')).toBe(false); + expect(context.supports('lapiMetricsFeatures')).toBeUndefined(); + }); + + it('lets an explicit probe override a previous observation', () => { + const context = new CapabilityContext(); + context.learn('heartbeat', false); + expect(context.supports('heartbeat')).toBe(false); + + context.applyProbes({ heartbeat: true }); + expect(context.supports('heartbeat')).toBe(true); + expect(context.getCapabilities().source).toBe('probed'); + + // The stale observation must not come back on the next probe. + context.applyProbes({}); + expect(context.supports('heartbeat')).toBe(true); + }); + + it('lets an observation correct a value that was only inferred', () => { + const context = new CapabilityContext(); + // decisionOriginsFilter (1.3.3) failing infers decisionScopesDelete + // (same minimum) as unsupported. + context.applyProbes({ decisionOriginsFilter: false }); + expect(context.supports('decisionScopesDelete')).toBe(false); + + context.learn('decisionScopesDelete', true); + expect(context.supports('decisionScopesDelete')).toBe(true); + + // The correction survives another probe and remains non-propagating. + context.applyProbes({}); + expect(context.supports('decisionScopesDelete')).toBe(true); + expect(context.supports('allowlists')).toBe(false); + }); + + it('drops a declared version when a forced probe contradicts it', () => { + const context = new CapabilityContext({ version: '1.8.2' }); + context.applyProbes({ allowlists: false }); + + expect(context.getCapabilities().version).toBeUndefined(); + expect(context.getCapabilities().source).toBe('probed'); + expect(context.getCapabilities().estimate.probable).not.toBe('1.8.2'); + }); + + it('rejects an unknown capability name at runtime', () => { + const context = new CapabilityContext(); + + expect(() => context.supports('notARealCapability' as never)).toThrow(/unknown CrowdSec LAPI capability/); + expect(() => context.learn('notARealCapability' as never, true)).toThrow(/unknown CrowdSec LAPI capability/); + }); + + it('leaves unrelated capabilities unknown', () => { + const context = new CapabilityContext(); + context.applyProbes({ streamScopes: true }); + + expect(context.supports('streamScopes')).toBe(true); + expect(context.supports('containsFilter')).toBe(true); + expect(context.supports('allowlists')).toBeUndefined(); + }); + + it('throws on a known-unsupported capability', () => { + const context = new CapabilityContext({ version: '1.5.0' }); + + expect(() => context.assertSupport('allowlists')).toThrow(FeatureNotSupportedError); + + try { + context.assertSupport('allowlists'); + } catch (error) { + expect(error).toBeInstanceOf(FeatureNotSupportedError); + expect((error as FeatureNotSupportedError).minimumVersion).toBe(CAPABILITY_MIN_VERSION.allowlists); + expect((error as FeatureNotSupportedError).detectedVersion).toBe('1.5.0'); + } + }); + + it('throws on unknown capabilities only in strict mode', () => { + expect(() => new CapabilityContext().assertSupport('allowlists')).not.toThrow(); + expect(() => new CapabilityContext({ strict: true }).assertSupport('allowlists')).toThrow(LapiVersionUnknownError); + }); + + it('rejects an invalid declared version', () => { + expect(() => new CapabilityContext({ version: 'one' })).toThrow(/invalid lapiVersion/); + }); + + it('interprets probe statuses', () => { + expect(interpretProbe('allowlists', 200)).toBe(true); + expect(interpretProbe('allowlists', 400)).toBe(true); + // 401 proves nothing about the route (unauthenticated probe); 403 does. + expect(interpretProbe('allowlists', 401)).toBeUndefined(); + expect(interpretProbe('allowlists', 403)).toBe(true); + expect(interpretProbe('allowlists', 404)).toBe(false); + expect(interpretProbe('allowlists', undefined)).toBeUndefined(); + expect(interpretProbe('allowlistsBulkCheck', 400)).toBe(true); + expect(interpretProbe('allowlistsBulkCheck', 405)).toBe(false); + + expect(interpretProbe('alertKindFilter', 200)).toBe(true); + expect(interpretProbe('alertKindFilter', 500)).toBe(false); + expect(interpretProbe('alertKindFilter', 401)).toBeUndefined(); + + // `origin` on `/v1/alerts` answers 500 before 1.3.0; it must be read as + // unsupported, like the other filters. + expect(interpretProbe('alertOriginFilter', 200)).toBe(true); + expect(interpretProbe('alertOriginFilter', 500)).toBe(false); + }); + + it('gates client methods before sending a request', async () => { + const old = new CapabilityContext({ version: '1.2.0' }); + const alerts = new Alerts({ httpClient: fakeHttp, capabilities: old }); + + await expect(alerts.search({ kind: 'cscli' })).rejects.toBeInstanceOf(FeatureNotSupportedError); + await expect(alerts.deleteById('1')).rejects.toBeInstanceOf(FeatureNotSupportedError); + + const modern = new CapabilityContext({ version: '1.8.0' }); + expect(new Allowlists({ httpClient: fakeHttp, capabilities: modern }).list).toBeDefined(); + await expect(new Allowlists({ httpClient: fakeHttp, capabilities: old }).list()).rejects.toBeInstanceOf(FeatureNotSupportedError); + }); +}); diff --git a/packages/crowdsec-client/tests/Clients/BouncerClient.test.ts b/packages/crowdsec-client/tests/Clients/BouncerClient.test.ts index 1abdac477..62d71e656 100644 --- a/packages/crowdsec-client/tests/Clients/BouncerClient.test.ts +++ b/packages/crowdsec-client/tests/Clients/BouncerClient.test.ts @@ -8,8 +8,14 @@ const { mockCrowdSecClientConstructor, FakeClient, mockDecisionsBouncer } = vi.h setAuthenticationHeaders = vi.fn(); setAuthenticationByTLS = vi.fn(); _testConnection = vi.fn(); + supports = vi.fn(); + requireCapability = vi.fn(); + detectCapabilities = vi.fn().mockResolvedValue({ source: 'unknown', values: {} }); + capabilityContext = { assertSupport: vi.fn(), supports: vi.fn(), getCapabilities: vi.fn() }; + options: any; // @ts-ignore constructor(...args) { + this.options = args[0]; mockCrowdSecClientConstructor(...args); } http = 'fake-http'; @@ -46,7 +52,7 @@ describe('BouncerClient.test.ts', () => { expect(client.setAuthenticationHeaders).toHaveBeenCalledWith({ 'X-Api-Key': 'test-apiKey' }); - expect(mockDecisionsBouncer).toHaveBeenCalledWith({ httpClient: client.http }); + expect(mockDecisionsBouncer).toHaveBeenCalledWith(expect.objectContaining({ httpClient: client.http })); }); it('should construct with certificate', async () => { const client = new BouncerClient({ diff --git a/packages/crowdsec-client/tests/Clients/CrowdSecClient.test.ts b/packages/crowdsec-client/tests/Clients/CrowdSecClient.test.ts index 63b925ebd..9a5988a4f 100644 --- a/packages/crowdsec-client/tests/Clients/CrowdSecClient.test.ts +++ b/packages/crowdsec-client/tests/Clients/CrowdSecClient.test.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, describe, expect, vi, it } from 'vitest'; import type { CrowdSecClient as TypeCrowdSecClient } from '../../src/Clients/CrowdSecClient.js'; import type { ICrowdSecClientOptions } from '../../src/index.js'; +import { LapiCapability } from '../../src/Capabilities.js'; import Validate from '../../src/Validate.js'; import * as https from 'https'; import { CrowdsecClientError } from '../../src/Errors/CrowdsecClientError.js'; @@ -700,4 +701,39 @@ describe('CrowdSecClient.ts', () => { }); }); }); + + describe('detectCapability', () => { + class ProbeClient extends FakeClient { + public probes: Array<{ capability: import('../../src/Capabilities.js').LapiCapability; request: () => Promise }> = []; + + protected collectProbes() { + return this.probes; + } + } + + it('probes once, records the result and reuses it', async () => { + const client = new ProbeClient({ url: 'https://crowdsec.lan' }); + const request = vi.fn().mockResolvedValue({ status: 200 }); + client.probes = [{ capability: LapiCapability.allowlists, request }]; + + await expect(client.detectCapability('allowlists')).resolves.toBe(true); + expect(client.supports('allowlists')).toBe(true); + expect(client.getCapabilities().source).toBe('probed'); + + await expect(client.detectCapability('allowlists')).resolves.toBe(true); + expect(request).toHaveBeenCalledTimes(1); + }); + + it('re-probes when forced and returns undefined when no probe exists', async () => { + const client = new ProbeClient({ url: 'https://crowdsec.lan' }); + const request = vi.fn().mockResolvedValue({ status: 404 }); + client.probes = [{ capability: LapiCapability.allowlists, request }]; + + await expect(client.detectCapability('allowlists')).resolves.toBe(false); + await expect(client.detectCapability('allowlists', { force: true })).resolves.toBe(false); + expect(request).toHaveBeenCalledTimes(2); + + await expect(client.detectCapability('alertDeleteById')).resolves.toBeUndefined(); + }); + }); }); diff --git a/packages/crowdsec-client/tests/Clients/Redaction.test.ts b/packages/crowdsec-client/tests/Clients/Redaction.test.ts new file mode 100644 index 000000000..0f194bb51 --- /dev/null +++ b/packages/crowdsec-client/tests/Clients/Redaction.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest'; +import { redactBody, redactHeaders } from '../../src/Clients/CrowdSecClient.js'; + +describe('redactHeaders', () => { + it('redacts sensitive headers case-insensitively', () => { + expect(redactHeaders({ Authorization: 'Bearer x', 'X-Api-Key': 'k', Other: 'v' })).toEqual({ + Authorization: '[redacted]', + 'X-Api-Key': '[redacted]', + Other: 'v' + }); + }); +}); + +describe('redactBody', () => { + it('redacts nested fields, arrays and cycles', () => { + const body: Record = { + token: 't', + nested: { password: 'p', list: [{ apiKey: 'k' }] } + }; + body.self = body; + + expect(redactBody(body)).toEqual({ + token: '[redacted]', + nested: { password: '[redacted]', list: [{ apiKey: '[redacted]' }] }, + self: '[circular]' + }); + }); +}); diff --git a/packages/crowdsec-client/tests/Clients/WatcherClient.test.ts b/packages/crowdsec-client/tests/Clients/WatcherClient.test.ts index e5596b9f4..bfaea2fdc 100644 --- a/packages/crowdsec-client/tests/Clients/WatcherClient.test.ts +++ b/packages/crowdsec-client/tests/Clients/WatcherClient.test.ts @@ -2,6 +2,7 @@ import { beforeEach, describe, expect, vi, it, afterEach } from 'vitest'; import type { WatcherClient as WatcherClientType } from '../../src/Clients/WatcherClient.js'; import { CrowdsecClientError } from '../../src/Errors/CrowdsecClientError.js'; import { EErrorsCodes } from '../../src/Errors/EErrorsCodes.js'; +import { LapiCapability } from '../../src/Capabilities.js'; const { mockDebug, mockDebugExtend, createDebuggerMock, mockDecisionsWatcher, mockAlerts, mockCrowdSecClientConstructor, FakeClient } = vi.hoisted(() => { @@ -17,15 +18,29 @@ const { mockDebug, mockDebugExtend, createDebuggerMock, mockDecisionsWatcher, mo setAuthenticationHeaders = vi.fn(); setAuthenticationByTLS = vi.fn(); _testConnection = vi.fn(); + supports = vi.fn(); + requireCapability = vi.fn(); + detectCapabilities = vi.fn().mockResolvedValue({ source: 'unknown', values: {} }); + capabilityContext = { assertSupport: vi.fn(), supports: vi.fn(), getCapabilities: vi.fn(), learn: vi.fn() }; // @ts-ignore + options: any; constructor(...args) { + this.options = args[0]; mockCrowdSecClientConstructor(...args); } http = 'fake-http'; static getHTTPClient: unknown; } - return { mockDebug, mockDebugExtend, createDebuggerMock, mockDecisionsWatcher, mockAlerts, mockCrowdSecClientConstructor, FakeClient }; + return { + mockDebug, + mockDebugExtend, + createDebuggerMock, + mockDecisionsWatcher, + mockAlerts, + mockCrowdSecClientConstructor, + FakeClient + }; }); const getFakeTimeout = () => { @@ -168,6 +183,13 @@ describe('WatcherClient.test.ts', () => { expect(mockHeartbeatLoop).toHaveBeenCalledWith(); expect(mockTestConnection).toHaveBeenCalledWith(); }); + it('should reject login after stop', async () => { + await watcher.stop(); + + await expect(watcher.login()).rejects.toThrow('client is stopped'); + expect(mockLogin).not.toHaveBeenCalled(); + }); + it('should call skip heartLoop if disabled', async () => { mockLogin.mockImplementationOnce(() => Promise.resolve()); // @ts-ignore @@ -249,6 +271,10 @@ describe('WatcherClient.test.ts', () => { }); // @ts-ignore watcher.http = { get: httpGetMock, post: httpPostMock }; + // @ts-ignore + watcher.setAuthenticationHeaders = mockSetAuthenticationHeaders; + // @ts-ignore + _login = watcher._login.bind(watcher); httpPostMock.mockImplementationOnce(() => ({ data: { @@ -258,8 +284,6 @@ describe('WatcherClient.test.ts', () => { })); await _login(); expect(httpPostMock).toHaveBeenCalledWith('/v1/watchers/login', { - machine_id: 'test_machine_id', - password: 'test_password', scenarios: [] }); expect(mockSetAuthenticationHeaders).toHaveBeenCalledWith(expect.objectContaining({ Authorization: `Bearer test_token` })); @@ -470,6 +494,13 @@ describe('WatcherClient.test.ts', () => { expect(mockDebug).toHaveBeenCalledWith('error %o', 'fake-error'); }); + it('should learn and disable the loop when the heartbeat route is missing', async () => { + httpGetMock.mockImplementationOnce(() => Promise.reject(Object.assign(new Error('not found'), { code: 404 }))); + await heartbeatLoop(); + + expect((watcher as any).capabilityContext.learn).toHaveBeenCalledWith(LapiCapability.heartbeat, false); + expect(mockSetTimeout).not.toHaveBeenCalled(); + }); it('should recall heartbeat', async () => { const [timeout, mockTimeout] = getFakeTimeout(); // @ts-ignore @@ -519,13 +550,15 @@ describe('WatcherClient.test.ts', () => { await WatcherClient.registerWatcher({ machine_id: 'test_machine_id', password: 'test_password', + registration_token: 'registration-token', url: 'https://localhost:8080' }); expect(mockGetHTTPClient).toHaveBeenCalledWith(expect.objectContaining({ url: 'https://localhost:8080' })); expect(mockPost).toHaveBeenCalledWith('/v1/watchers', { machine_id: 'test_machine_id', - password: 'test_password' + password: 'test_password', + registration_token: 'registration-token' }); }); }); @@ -552,4 +585,4 @@ describe('WatcherClient.test.ts', () => { }); }); }); -}); \ No newline at end of file +}); diff --git a/packages/crowdsec-client/tests/Decisions/Decision.test.ts b/packages/crowdsec-client/tests/Decisions/Decision.test.ts index 8840f6518..cf3c7ab81 100644 --- a/packages/crowdsec-client/tests/Decisions/Decision.test.ts +++ b/packages/crowdsec-client/tests/Decisions/Decision.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it, vi } from 'vitest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; const { mockParseExpiration } = vi.hoisted(() => ({ mockParseExpiration: vi.fn().mockReturnValue(new Date('2023-06-01T17:41:26.499Z')) @@ -9,6 +9,26 @@ vi.mock('../../src/utils.js', () => ({ })); describe('decision', () => { + beforeEach(() => { + mockParseExpiration.mockClear(); + }); + + it('prefers a valid until date over the duration', async () => { + const decision = new (await import('../../src/Decisions/Decision.js')).Decision({ + id: 1, + origin: 'Origin', + type: 'type', + scope: 'Scope', + value: 'value', + duration: '1h54m', + until: '2024-01-02T03:04:05.000Z', + scenario: 'Scenario' + }); + + expect(decision.endAt.toISOString()).toBe('2024-01-02T03:04:05.000Z'); + expect(mockParseExpiration).not.toHaveBeenCalled(); + }); + it('should create a Decision object', async () => { const rawDecision = { id: 1, @@ -58,9 +78,10 @@ describe('decision', () => { expect(decision.duration).toBe(rawDecision.duration); expect(decision.until).toBe(rawDecision.until); expect(decision.scenario).toBe(rawDecision.scenario.toLowerCase()); - expect(decision.simulated).toBe(false); + // The LAPI may omit `simulated` (notably on `/v1/decisions`). + expect(decision.simulated).toBeUndefined(); expect(decision.endAt.getTime()).toBe(1685641286499); expect(mockParseExpiration).toHaveBeenCalledWith(decision.duration); }); -}); \ No newline at end of file +}); diff --git a/packages/crowdsec-client/tests/Decisions/DecisionsBouncer.test.ts b/packages/crowdsec-client/tests/Decisions/DecisionsBouncer.test.ts index 1fe377854..3dd20ffe0 100644 --- a/packages/crowdsec-client/tests/Decisions/DecisionsBouncer.test.ts +++ b/packages/crowdsec-client/tests/Decisions/DecisionsBouncer.test.ts @@ -56,7 +56,11 @@ vi.mock('../../src/utils.js', () => ({ createDebugger: createDebuggerMock, forceArray: mockForceArray })); -vi.mock('../../src/BaseSubObject.js', () => ({ BaseSubObject: vi.fn() })); +vi.mock('../../src/BaseSubObject.js', () => ({ + BaseSubObject: class { + requireCapability = vi.fn(); + } +})); vi.mock('../../src/Decisions/DecisionsStream.js', () => ({ DecisionsStream: mockDecisionStreamConstructor @@ -127,12 +131,12 @@ describe('DecisionsBouncer', () => { mockSetTimeout.mockReturnValue('fakeTimeout'); // @ts-ignore - expect(bouncer.getStreamTimeout).not.toBeDefined(); + expect(bouncer.streamTimeouts.get(localDecisionStream)).not.toBeDefined(); await getStreamLoop(options, localDecisionStream, interval); // @ts-ignore - expect(bouncer.getStreamTimeout).toBe('fakeTimeout'); + expect(bouncer.streamTimeouts.get(localDecisionStream)).toBe('fakeTimeout'); expect(mockGetRawStream).toHaveBeenCalledWith({}); expect(global.setTimeout).toHaveBeenCalledWith(expect.any(Function), interval); @@ -155,7 +159,7 @@ describe('DecisionsBouncer', () => { const interval = 2; const options = {}; // @ts-ignore - bouncer.getStreamTimeout = fakeTimeout; + bouncer.streamTimeouts.set(localDecisionStream, fakeTimeout); await getStreamLoop(options, localDecisionStream, interval); @@ -193,6 +197,36 @@ describe('DecisionsBouncer', () => { expect(localDecisionStream.emit).toHaveBeenCalledWith('error', fakeError); }); + + it('should not start a second loop for the same stream', async () => { + // @ts-ignore + localDecisionStream.paused = true; + let release!: () => void; + mockGetRawStream.mockImplementationOnce(() => new Promise((resolve) => (release = resolve))); + + const first = getStreamLoop({}, localDecisionStream, 2); + const second = getStreamLoop({}, localDecisionStream, 2); + + release(); + await Promise.all([first, second]); + + expect(mockGetRawStream).toHaveBeenCalledTimes(1); + }); + + it('should keep one timer per stream', async () => { + // @ts-ignore + localDecisionStream.paused = false; + const otherStream = { paused: false, emit: vi.fn(), push: vi.fn() } as unknown as DecisionsStream; + mockSetTimeout.mockReturnValueOnce('timer-1').mockReturnValueOnce('timer-2'); + + await getStreamLoop({}, localDecisionStream, 2); + await getStreamLoop({}, otherStream, 2); + + // @ts-ignore + expect(bouncer.streamTimeouts.get(localDecisionStream)).toBe('timer-1'); + // @ts-ignore + expect(bouncer.streamTimeouts.get(otherStream)).toBe('timer-2'); + }); }); describe('streamToCallback', () => { let streamToCallback: DecisionsBouncer['streamToCallback']; @@ -333,6 +367,7 @@ describe('DecisionsBouncer', () => { ip: '', range: '', contains: false, + simulated: true, origins: '', scenarios_containing: '', scenarios_not_containing: '' @@ -353,6 +388,7 @@ describe('DecisionsBouncer', () => { ip: '', range: '', contains: false, + simulated: true, origins: undefined, scenarios_containing: undefined, scenarios_not_containing: undefined @@ -484,6 +520,18 @@ describe('DecisionsBouncer', () => { return listeners; }; const getStreamLoopWrapper = vi.fn().mockImplementation(() => Promise.resolve()); + const expectResumeWiring = () => { + const { resume } = getStreamListeners([mockStreamOn, mockStreamOnce]); + resume(); + resume(); + + const calls = getStreamLoopWrapper.mock.calls; + expect(calls).toHaveLength(2); + expect(calls[0][0]).toEqual(expect.objectContaining({ startup: true })); + expect(calls[1][0]).toEqual(expect.objectContaining({ startup: false })); + expect(calls[0][1]).toBe(mockDecisionStream); + expect(calls[1][1]).toBe(mockDecisionStream); + }; beforeEach(() => { // @ts-ignore bouncer.getStreamLoopWrapper = getStreamLoopWrapper; @@ -504,17 +552,7 @@ describe('DecisionsBouncer', () => { expect(await bouncer.getStream(params)).toBe(mockDecisionStream); - const { resume } = getStreamListeners([mockStreamOn, mockStreamOnce]); - resume(); - getStreamLoopWrapper({ - ...params, - startup: true - }); - resume(); - getStreamLoopWrapper({ - ...params, - startup: false - }); + expectResumeWiring(); expect(mockDecisionStreamConstructor).toHaveBeenCalledWith(expect.any(String)); expect(mockStreamOnce).toHaveBeenCalledWith('close', expect.any(Function)); @@ -528,17 +566,7 @@ describe('DecisionsBouncer', () => { }; expect(await bouncer.getStream(params)).toBe(mockDecisionStream); - const { resume } = getStreamListeners([mockStreamOn, mockStreamOnce]); - resume(); - getStreamLoopWrapper({ - ...params, - startup: true - }); - resume(); - getStreamLoopWrapper({ - ...params, - startup: false - }); + expectResumeWiring(); expect(mockDecisionStreamConstructor).toHaveBeenCalledWith(expect.any(String)); expect(mockStreamOnce).toHaveBeenCalledWith('close', expect.any(Function)); @@ -550,15 +578,7 @@ describe('DecisionsBouncer', () => { const params = undefined; expect(await bouncer.getStream(params)).toBe(mockDecisionStream); - const { resume } = getStreamListeners([mockStreamOn, mockStreamOnce]); - resume(); - getStreamLoopWrapper({ - startup: true - }); - resume(); - getStreamLoopWrapper({ - startup: false - }); + expectResumeWiring(); expect(mockDecisionStreamConstructor).toHaveBeenCalledWith(expect.any(String)); expect(mockStreamOnce).toHaveBeenCalledWith('close', expect.any(Function)); @@ -576,17 +596,7 @@ describe('DecisionsBouncer', () => { }; expect(await bouncer.getStream(params)).toBe(mockDecisionStream); - const { resume } = getStreamListeners([mockStreamOn, mockStreamOnce]); - resume(); - getStreamLoopWrapper({ - ...params, - startup: true - }); - resume(); - getStreamLoopWrapper({ - ...params, - startup: false - }); + expectResumeWiring(); expect(mockDecisionStreamConstructor).toHaveBeenCalledWith(expect.any(String)); expect(mockStreamOnce).toHaveBeenCalledWith('close', expect.any(Function)); @@ -605,17 +615,7 @@ describe('DecisionsBouncer', () => { expect(await bouncer.getStream(params)).toBe(mockDecisionStream); - const { resume } = getStreamListeners([mockStreamOn, mockStreamOnce]); - resume(); - getStreamLoopWrapper({ - ...params, - startup: true - }); - resume(); - getStreamLoopWrapper({ - ...params, - startup: false - }); + expectResumeWiring(); expect(mockDecisionStreamConstructor).toHaveBeenCalledWith(expect.any(String)); expect(mockStreamOnce).toHaveBeenCalledWith('close', expect.any(Function)); @@ -633,15 +633,7 @@ describe('DecisionsBouncer', () => { expect(await bouncer.getStream(params, mockCB)).toBe(mockDecisionStream); - const { resume } = getStreamListeners([mockStreamOn, mockStreamOnce]); - resume(); - getStreamLoopWrapper({ - startup: true - }); - resume(); - getStreamLoopWrapper({ - startup: false - }); + expectResumeWiring(); expect(mockStreamToCallback).toHaveBeenCalledWith(mockDecisionStream, mockCB); @@ -676,7 +668,7 @@ describe('DecisionsBouncer', () => { it('should handle the close listener', async () => { // @ts-ignore - bouncer.getStreamTimeout = fakeTimeout; + bouncer.streamTimeouts.set(mockDecisionStream, fakeTimeout); // @ts-ignore bouncer.runningStreams = [mockDecisionStream]; @@ -694,7 +686,7 @@ describe('DecisionsBouncer', () => { it('should handle the pause listener', async () => { // @ts-ignore - bouncer.getStreamTimeout = fakeTimeout; + bouncer.streamTimeouts.set(mockDecisionStream, fakeTimeout); // @ts-ignore bouncer.runningStreams = [mockDecisionStream]; diff --git a/packages/crowdsec-client/tests/Decisions/DecisionsWatcher.test.ts b/packages/crowdsec-client/tests/Decisions/DecisionsWatcher.test.ts index d426c835a..6559376f7 100644 --- a/packages/crowdsec-client/tests/Decisions/DecisionsWatcher.test.ts +++ b/packages/crowdsec-client/tests/Decisions/DecisionsWatcher.test.ts @@ -1,9 +1,14 @@ -import { describe, it, afterEach, beforeEach, expect } from 'vitest'; +import { describe, it, afterEach, beforeEach, expect, vi } from 'vitest'; +import { CapabilityContext, LapiCapability } from '../../src/Capabilities.js'; import type { Decisions } from '../../src/types/index.js'; import type { DecisionsWatcher } from '../../src/index.js'; -vi.mock('../../src/BaseSubObject.js', () => ({ BaseSubObject: vi.fn() })); +vi.mock('../../src/BaseSubObject.js', () => ({ + BaseSubObject: class { + requireCapability = vi.fn(); + } +})); describe('DecisionsWatcher', () => { const httpDeleteMock = vi.fn(); @@ -26,6 +31,14 @@ describe('DecisionsWatcher', () => { expect(httpDeleteMock).toHaveBeenCalledWith('/v1/decisions/123'); }); + it('should encode the id segment', async () => { + httpDeleteMock.mockImplementationOnce(() => ({ data: 'test' })); + + await watcher.deleteById('1/../watchers/self'); + + expect(httpDeleteMock).toHaveBeenCalledWith('/v1/decisions/1%2F..%2Fwatchers%2Fself'); + }); + it('should call delete with options', async () => { httpDeleteMock.mockImplementationOnce(() => ({ data: 'test' })); const deleteOptions: Decisions.DeleteDecisions.RequestQuery = { @@ -34,6 +47,148 @@ describe('DecisionsWatcher', () => { expect(await watcher.delete(deleteOptions)).toBe('test'); - expect(httpDeleteMock).toHaveBeenCalledWith('/v1/decisions', { params: deleteOptions }); + expect(httpDeleteMock).toHaveBeenCalledWith('/v1/decisions', { params: { ...deleteOptions, contains: false } }); + // @ts-ignore + expect(watcher.requireCapability).toHaveBeenCalledWith(LapiCapability.containsFilter); + }); + + it('should keep an explicit contains value on an ip delete', async () => { + httpDeleteMock.mockImplementationOnce(() => ({ data: 'test' })); + + await watcher.delete({ ip: '1.2.3.4', contains: true }); + + expect(httpDeleteMock).toHaveBeenCalledWith('/v1/decisions', { params: { ip: '1.2.3.4', contains: true } }); + }); + + it('should retry with scope on a raw Axios 500', async () => { + httpDeleteMock.mockRejectedValueOnce( + Object.assign(new Error("'scopes' doesn't exist: invalid filter"), { + code: 'ERR_BAD_RESPONSE', + response: { status: 500 } + }) + ); + httpDeleteMock.mockResolvedValueOnce({ data: 'test' }); + + expect(await watcher.delete({ scopes: 'Country', value: 'FR' })).toBe('test'); + + expect(httpDeleteMock).toHaveBeenNthCalledWith(1, '/v1/decisions', { params: { scopes: 'Country', value: 'FR' } }); + expect(httpDeleteMock).toHaveBeenNthCalledWith(2, '/v1/decisions', { params: { scope: 'Country', value: 'FR' } }); + }); + + it('should require the contains capability when deleting with contains', async () => { + httpDeleteMock.mockImplementationOnce(() => ({ data: 'test' })); + + await watcher.delete({ contains: false }); + + expect((watcher as unknown as { requireCapability: ReturnType }).requireCapability).toHaveBeenCalledWith( + 'containsFilter' + ); + }); + + it('should use scope when the capability is known unsupported', async () => { + const supports = vi.fn().mockReturnValue(false); + const learn = vi.fn(); + // @ts-ignore + watcher.capabilities = { supports, learn }; + httpDeleteMock.mockResolvedValueOnce({ data: { nbDeleted: '1' } }); + + await watcher.delete({ scopes: 'Country', value: 'FR' }); + + expect(httpDeleteMock).toHaveBeenCalledWith('/v1/decisions', { + params: { value: 'FR', scope: 'Country' } + }); + expect(learn).toHaveBeenCalledWith('decisionScopesDelete', false); + }); + + it('should use scopes when the capability is known supported', async () => { + const supports = vi.fn().mockReturnValue(true); + const learn = vi.fn(); + // @ts-ignore + watcher.capabilities = { supports, learn }; + httpDeleteMock.mockResolvedValueOnce({ data: { nbDeleted: '1' } }); + + await watcher.delete({ scopes: 'Country', value: 'FR' }); + + expect(httpDeleteMock).toHaveBeenCalledWith('/v1/decisions', { + params: { value: 'FR', scopes: 'Country' } + }); + expect(learn).toHaveBeenCalledWith('decisionScopesDelete', true); + }); + + it('should retry with scope when scopes is rejected and the capability is unknown', async () => { + const supports = vi.fn().mockReturnValue(undefined); + const learn = vi.fn(); + // @ts-ignore + watcher.capabilities = { supports, learn }; + const error = Object.assign(new Error("'scopes' doesn't exist: invalid filter"), { code: 500 }); + httpDeleteMock.mockRejectedValueOnce(error).mockResolvedValueOnce({ data: { nbDeleted: '1' } }); + + await watcher.delete({ scopes: 'Country', value: 'FR' }); + + expect(httpDeleteMock).toHaveBeenCalledTimes(2); + expect(httpDeleteMock.mock.calls[0][1].params).toMatchObject({ scopes: 'Country', value: 'FR' }); + expect(httpDeleteMock.mock.calls[1][1].params).toMatchObject({ scope: 'Country', value: 'FR' }); + expect(learn).toHaveBeenCalledWith('decisionScopesDelete', false); + }); + + it('should retry with scopes when scope is rejected', async () => { + const supports = vi.fn().mockReturnValue(false); + const learn = vi.fn(); + // @ts-ignore + watcher.capabilities = { supports, learn }; + const error = Object.assign(new Error("'scope' doesn't exist: invalid filter"), { code: 500 }); + httpDeleteMock.mockRejectedValueOnce(error).mockResolvedValueOnce({ data: { nbDeleted: '1' } }); + + await watcher.delete({ scopes: 'Country', value: 'FR' }); + + expect(httpDeleteMock).toHaveBeenCalledTimes(2); + expect(httpDeleteMock.mock.calls[0][1].params).toMatchObject({ scope: 'Country', value: 'FR' }); + expect(httpDeleteMock.mock.calls[1][1].params).toMatchObject({ scopes: 'Country', value: 'FR' }); + expect(learn).toHaveBeenCalledWith('decisionScopesDelete', true); + }); + + it('should cache the learned scope parameter and avoid a second failed request', async () => { + const capabilities = new CapabilityContext(); + // @ts-ignore + watcher.capabilities = capabilities; + const error = Object.assign(new Error("'scopes' doesn't exist: invalid filter"), { code: 500 }); + httpDeleteMock + .mockRejectedValueOnce(error) + .mockResolvedValueOnce({ data: { nbDeleted: '1' } }) + .mockResolvedValueOnce({ data: { nbDeleted: '0' } }); + + await watcher.delete({ scopes: 'Country', value: 'FR' }); + expect(capabilities.supports('decisionScopesDelete')).toBe(false); + + await watcher.delete({ scopes: 'Country', value: 'ZZ' }); + + expect(httpDeleteMock).toHaveBeenCalledTimes(3); + expect(httpDeleteMock.mock.calls[2][1].params).toMatchObject({ scope: 'Country', value: 'ZZ' }); + }); + + it('should retry on older unknown-filter wording', async () => { + const supports = vi.fn().mockReturnValue(undefined); + const learn = vi.fn(); + // @ts-ignore + watcher.capabilities = { supports, learn }; + const error = Object.assign(new Error("unknown filter parameter 'scopes'"), { code: 500 }); + httpDeleteMock.mockRejectedValueOnce(error).mockResolvedValueOnce({ data: { nbDeleted: '1' } }); + + await watcher.delete({ scopes: 'Country', value: 'FR' }); + + expect(httpDeleteMock).toHaveBeenCalledTimes(2); + expect(httpDeleteMock.mock.calls[1][1].params).toMatchObject({ scope: 'Country', value: 'FR' }); + }); + + it('should not retry an unrelated 500', async () => { + const supports = vi.fn().mockReturnValue(undefined); + const learn = vi.fn(); + // @ts-ignore + watcher.capabilities = { supports, learn }; + httpDeleteMock.mockRejectedValueOnce(Object.assign(new Error('database is down'), { code: 500 })); + + await expect(watcher.delete({ scopes: 'Country', value: 'FR' })).rejects.toThrow('database is down'); + expect(httpDeleteMock).toHaveBeenCalledTimes(1); + expect(learn).not.toHaveBeenCalled(); }); }); diff --git a/packages/crowdsec-client/tests/Errors/__Errors.test.ts b/packages/crowdsec-client/tests/Errors/__Errors.test.ts index fd0aa3056..5b12c6b3f 100644 --- a/packages/crowdsec-client/tests/Errors/__Errors.test.ts +++ b/packages/crowdsec-client/tests/Errors/__Errors.test.ts @@ -15,6 +15,7 @@ describe('Errors', () => { it('should handle error', () => { const err = new __Error(new Error('my error'), EErrorsCodes.CONNECTION_TEST_FAILED); + expect(err).toBeInstanceOf(Error); expect(err.code).toBe(EErrorsCodes.CONNECTION_TEST_FAILED); expect(err.errorCode).toBe(EErrorsCodes.CONNECTION_TEST_FAILED); expect(err.message).toBe('my error'); diff --git a/packages/crowdsec-client/tests/Live/live.test.ts b/packages/crowdsec-client/tests/Live/live.test.ts index 380985d4a..6ea62fc05 100644 --- a/packages/crowdsec-client/tests/Live/live.test.ts +++ b/packages/crowdsec-client/tests/Live/live.test.ts @@ -1,5 +1,16 @@ -import { describe, expect, it } from 'vitest'; -import { BouncerClient, WatcherClient } from '../../src/index.js'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { + BouncerClient, + CAPABILITY_MIN_VERSION, + compareLapiVersions, + FeatureNotSupportedError, + LapiCapability, + parseLapiVersion, + toLapiCapability, + WatcherClient +} from '../../src/index.js'; +import type { LapiCapabilityInput } from '../../src/index.js'; +import type { APITypes } from '../../src/index.js'; const live = process.env.CROWDSEC_LIVE === '1'; const url = process.env.CROWDSEC_URL; @@ -7,52 +18,603 @@ const apiKey = process.env.CROWDSEC_API_KEY; const machineId = process.env.CROWDSEC_MACHINE_ID; const password = process.env.CROWDSEC_PASSWORD; const strictSSL = process.env.CROWDSEC_STRICT_SSL !== 'false'; +const tag = process.env.CROWDSEC_LAPI_VERSION; +const allowlistName = process.env.CROWDSEC_LIVE_ALLOWLIST; +const allowlistIp = process.env.CROWDSEC_LIVE_ALLOWLIST_IP ?? '198.51.100.10'; +const countrySeeded = process.env.CROWDSEC_LIVE_COUNTRY === '1'; -describe.skipIf(!live)('live CrowdSec API', () => { - it.skipIf(!url || !apiKey)( - 'authenticates a bouncer and reads decisions', - async () => { - const client = new BouncerClient({ - url: url!, - auth: { apiKey: apiKey! }, - strictSSL - }); +type LiveMode = 'both' | 'watcher' | 'bouncer'; +const mode: LiveMode = (process.env.CROWDSEC_MODE as LiveMode | undefined) ?? 'both'; +const wantWatcher = mode === 'both' || mode === 'watcher'; +const wantBouncer = mode === 'both' || mode === 'bouncer'; - try { - await client.login(); - const decisions = await client.Decisions.search({}); - expect(Array.isArray(decisions)).toBe(true); - } finally { - await client.stop(); - } - }, - 30000 - ); - - it.skipIf(!url || !machineId || !password)( - 'authenticates a watcher and reads alerts and allowlists', - async () => { - const client = new WatcherClient({ - url: url!, - auth: { - machineID: machineId!, - password: password!, - autoRenew: false - }, - strictSSL, - heartbeat: false - }); +const SEED_IP = '198.18.0.10'; +const SEED_RANGE = '198.18.0.0/24'; +const SEED_MULTI_IP = '198.18.0.77'; +const SEED_SIMULATED_IP = '198.20.0.10'; +const SEED_NO_DECISION_IP = '198.21.0.10'; +const SEED_BY_ID_IP = '198.22.0.10'; + +const WATCHER_CAPABILITIES: LapiCapability[] = [ + LapiCapability.containsFilter, + LapiCapability.alertOriginFilter, + LapiCapability.heartbeat, + LapiCapability.allowlists, + LapiCapability.allowlistsBulkCheck, + LapiCapability.alertKindFilter +]; +const BOUNCER_CAPABILITIES: LapiCapability[] = [LapiCapability.containsFilter, LapiCapability.decisionOriginsFilter]; + +function expected(capability: LapiCapabilityInput): boolean | undefined { + if (!tag || !parseLapiVersion(tag)) { + return undefined; + } + return compareLapiVersions(tag, CAPABILITY_MIN_VERSION[toLapiCapability(capability)]) >= 0; +} + +function expectTagWithinEstimate(client: WatcherClient | BouncerClient, label: string): void { + if (!tag || !parseLapiVersion(tag)) { + return; + } + + const estimate = client.getProbableVersion(); + + if (estimate.minVersion) { + expect(compareLapiVersions(tag, estimate.minVersion), `${label} should be >= ${estimate.minVersion}`).toBeGreaterThanOrEqual(0); + } + if (estimate.belowVersion) { + expect(compareLapiVersions(tag, estimate.belowVersion), `${label} should be < ${estimate.belowVersion}`).toBeLessThan(0); + } +} + +function makeWatcher(withVersion: boolean): WatcherClient { + return new WatcherClient({ + url: url!, + auth: { machineID: machineId!, password: password!, autoRenew: false }, + heartbeat: false, + detectCapabilities: true, + ...(withVersion && tag ? { lapiVersion: tag } : {}), + strictSSL, + timeout: 10_000 + }); +} + +function makeBouncer(withVersion: boolean): BouncerClient { + return new BouncerClient({ + url: url!, + auth: { apiKey: apiKey! }, + detectCapabilities: true, + ...(withVersion && tag ? { lapiVersion: tag } : {}), + strictSSL, + timeout: 10_000 + }); +} + +function ipSource(ip: string): APITypes.Source { + return { scope: 'Ip', value: ip, ip }; +} + +function rangeSource(range: string): APITypes.Source { + return { scope: 'Range', value: range, range }; +} + +function makeDecision(scope: string, value: string, type = 'ban', simulated = false): APITypes.Decision { + return { + origin: 'cscli', + type, + scope, + value, + duration: '1h', + scenario: 'node-live-e2e', + simulated + }; +} + +function makeAlert(options: { + source: APITypes.Source; + decisions?: APITypes.Decision[]; + kind?: string; + simulated?: boolean; +}): APITypes.Alert { + const now = new Date().toISOString(); + return { + scenario: 'node-live-e2e', + scenario_hash: '', + scenario_version: '', + message: 'node-live e2e alert', + events_count: 1, + start_at: now, + stop_at: now, + capacity: 0, + leakspeed: '0', + simulated: options.simulated ?? false, + events: [], + remediation: (options.decisions?.length ?? 0) > 0, + decisions: options.decisions ?? [], + source: options.source, + ...(options.kind ? { kind: options.kind } : {}) + }; +} + +async function attempt(fn: () => Promise): Promise<{ ok: true; value: T } | { ok: false; error: any }> { + try { + return { ok: true, value: await fn() }; + } catch (error) { + return { ok: false, error }; + } +} + +describe.skipIf(!live)('live CrowdSec API matrix', () => { + let watcher: WatcherClient; + let bouncer: BouncerClient; + let probeWatcher: WatcherClient; + let probeBouncer: BouncerClient; + + let probeError: unknown; + let seedError: unknown; + let seeded: { + ipAlert?: number; + rangeAlert?: number; + multiAlert?: number; + simulatedAlert?: number; + noDecisionAlert?: number; + } = {}; + + function supports(capability: LapiCapabilityInput): boolean | undefined { + // Probe-driven clients first: gating must be validated against what the + // client detected, not against the version table we declared on the + // `watcher`/`bouncer` clients (which would make these assertions + // tautological). + const clients = [probeWatcher, probeBouncer, watcher, bouncer].filter((client): client is WatcherClient | BouncerClient => + Boolean(client) + ); + + for (const client of clients) { + const value = client.supports(capability); + if (value !== undefined) { + return value; + } + } + + return expected(capability); + } + + function ensureSeeded(): void { + if (seedError) { + throw seedError; + } + } + + async function pushAlert(alert: APITypes.Alert): Promise { + const ids = await watcher.Alerts.pushAlerts([alert] as APITypes.AddAlertsRequest); + return Number(ids[0]); + } + + async function expectGate(capability: LapiCapabilityInput, fn: () => Promise, check: (value: T) => void): Promise { + const state = supports(capability); + + if (state === false) { + await expect(fn()).rejects.toBeInstanceOf(FeatureNotSupportedError); + return; + } + + if (state === true) { + check(await fn()); + return; + } + + // Unknown capability (no version and no probe): accept either the call + // succeeding or the LAPI rejecting the filter. + const result = await attempt(fn); + if (result.ok) { + check(result.value); + } + } + + beforeAll(async () => { + if (!url) { + throw new Error('CROWDSEC_URL is required'); + } + if (wantWatcher && (!machineId || !password)) { + throw new Error('CROWDSEC_MACHINE_ID and CROWDSEC_PASSWORD are required in watcher/both mode'); + } + if (wantBouncer && !apiKey) { + throw new Error('CROWDSEC_API_KEY is required in bouncer/both mode'); + } + // Keep the fields typed, but leave the unused client undefined at + // runtime: tests for that credential are skipped with skipIf below. + watcher = (wantWatcher ? makeWatcher(true) : undefined) as WatcherClient; + probeWatcher = (wantWatcher ? makeWatcher(false) : undefined) as WatcherClient; + bouncer = (wantBouncer ? makeBouncer(true) : undefined) as BouncerClient; + probeBouncer = (wantBouncer ? makeBouncer(false) : undefined) as BouncerClient; + + if (wantWatcher) { + await watcher.login(); + } + if (wantBouncer) { + await bouncer.login(); + } + + try { + if (wantWatcher) { + await probeWatcher.login(); + } + if (wantBouncer) { + await probeBouncer.login(); + } + } catch (error) { + probeError = error; + } + + if (!wantWatcher) { + return; + } + + try { + const kind = supports('alertKindField') === true ? 'node-live' : undefined; + + seeded.ipAlert = await pushAlert(makeAlert({ source: ipSource(SEED_IP), decisions: [makeDecision('Ip', SEED_IP)], kind })); + seeded.rangeAlert = await pushAlert( + makeAlert({ source: rangeSource(SEED_RANGE), decisions: [makeDecision('Range', SEED_RANGE)], kind }) + ); + seeded.multiAlert = await pushAlert( + makeAlert({ + source: ipSource(SEED_MULTI_IP), + decisions: [makeDecision('Ip', SEED_MULTI_IP, 'ban'), makeDecision('Ip', SEED_MULTI_IP, 'captcha')], + kind + }) + ); + seeded.noDecisionAlert = await pushAlert(makeAlert({ source: ipSource(SEED_NO_DECISION_IP), decisions: [], kind })); + + // Simulation support is old but the alert payload validation has + // changed across releases; do not fail the whole matrix if this one + // seed is rejected. try { - await client.login(); - const alerts = await client.Alerts.search({ limit: 1 }); - const allowlists = await client.Allowlists.list(); - expect(Array.isArray(alerts)).toBe(true); - expect(Array.isArray(allowlists)).toBe(true); - } finally { - await client.stop(); - } - }, - 30000 - ); + seeded.simulatedAlert = await pushAlert( + makeAlert({ + source: ipSource(SEED_SIMULATED_IP), + decisions: [makeDecision('Ip', SEED_SIMULATED_IP, 'ban', true)], + simulated: true, + kind + }) + ); + } catch { + seeded.simulatedAlert = undefined; + } + } catch (error) { + seedError = error; + } + }, 60_000); + + afterAll(async () => { + await probeWatcher?.stop(); + await probeBouncer?.stop(); + await watcher?.stop(); + await bouncer?.stop(); + }); + + it('detects capabilities without mismatch against the declared tag', () => { + if (probeError) { + throw probeError; + } + + if (wantWatcher) { + expect(probeWatcher.getCapabilities().source).toBe('probed'); + + for (const capability of WATCHER_CAPABILITIES) { + const detected = probeWatcher.supports(capability); + const wanted = expected(capability); + if (wanted !== undefined) { + // Every watcher capability below is probed, so a probe that + // returns `undefined` is a detection bug, not a skip. + expect(detected, `watcher ${capability} should be detected`).toBe(wanted); + } + } + + expectTagWithinEstimate(probeWatcher, 'watcher estimate'); + if (tag) { + expect(watcher.getProbableVersion().exactVersion).toBe(tag); + } + } + + if (wantBouncer) { + expect(probeBouncer.getCapabilities().source).toBe('probed'); + + for (const capability of BOUNCER_CAPABILITIES) { + const detected = probeBouncer.supports(capability); + const wanted = expected(capability); + if (wanted !== undefined) { + expect(detected, `bouncer ${capability} should be detected`).toBe(wanted); + } + } + + expectTagWithinEstimate(probeBouncer, 'bouncer estimate'); + if (tag) { + expect(bouncer.getProbableVersion().exactVersion).toBe(tag); + } + } + }); + + it.skipIf(!wantBouncer)('lists decisions and reads their fields', async () => { + ensureSeeded(); + + const decisions = await bouncer.Decisions.search({}); + expect(Array.isArray(decisions)).toBe(true); + + const seededDecision = decisions.find((decision) => decision.value === SEED_IP); + expect(seededDecision).toBeDefined(); + expect(seededDecision!.scope.toLowerCase()).toBe('ip'); + expect(seededDecision!.type).toBe('ban'); + + // `/v1/decisions` does not return `until` on 1.8.1, even though the + // field exists on the model. The client must still compute `endAt` + // from `duration`. + expect(seededDecision!.endAt).toBeInstanceOf(Date); + expect(seededDecision!.endAt.getTime()).toBeGreaterThan(Date.now()); + }); + + it.skipIf(!wantBouncer)('includes simulated decisions on the bouncer endpoint', async () => { + ensureSeeded(); + if (!seeded.simulatedAlert) { + return; + } + + // `simulated` is a supported decision filter since 1.0.0; a failure here + // is a regression, not an old-version limitation. + const decisions = await bouncer.Decisions.search({ simulated: true }); + expect(decisions.some((decision) => decision.value === SEED_SIMULATED_IP)).toBe(true); + }); + + it.skipIf(!wantBouncer)('gates the contains filter on decisions', async () => { + ensureSeeded(); + + await expectGate( + 'containsFilter', + () => bouncer.Decisions.search({ ip: SEED_RANGE, contains: false }), + (decisions) => { + expect(decisions.some((decision) => decision.value === SEED_IP)).toBe(true); + } + ); + }); + + it.skipIf(!wantBouncer)('reads the decision stream and gates scopes/origins', async () => { + const stream = await bouncer.Decisions.getRawStream({ startup: true }); + expect(Array.isArray(stream.new)).toBe(true); + // `deleted` was added after 1.0.0; it is optional/null on old releases. + if (stream.deleted !== undefined && stream.deleted !== null) { + expect(Array.isArray(stream.deleted)).toBe(true); + } + + await expectGate( + 'streamScopes', + () => bouncer.Decisions.getRawStream({ scopes: ['ip'] }), + (value) => expect(value).toHaveProperty('new') + ); + await expectGate( + 'decisionOriginsFilter', + () => bouncer.Decisions.getRawStream({ origins: ['cscli'] }), + (value) => expect(value).toHaveProperty('new') + ); + }); + + it.skipIf(!wantWatcher)('lists alerts and filters by source, decision state and contains', async () => { + ensureSeeded(); + + const alerts = await watcher.Alerts.search({ limit: 10 }); + expect(Array.isArray(alerts)).toBe(true); + + const bySource = await watcher.Alerts.search({ scope: 'Ip', value: SEED_IP }); + expect(bySource.some((alert) => alert.source.value === SEED_IP)).toBe(true); + + const noDecision = await watcher.Alerts.search({ has_active_decision: false, limit: 0 }); + expect(noDecision.some((alert) => alert.source.value === SEED_NO_DECISION_IP)).toBe(true); + + await expectGate( + 'containsFilter', + () => watcher.Alerts.search({ ip: SEED_RANGE, contains: false, limit: 0 }), + (result) => { + expect(result.some((alert) => alert.source.value === SEED_IP)).toBe(true); + } + ); + }); + + it.skipIf(!wantWatcher)('gates alert kind and origin filters', async () => { + ensureSeeded(); + + await expectGate( + 'alertKindFilter', + () => watcher.Alerts.search({ kind: 'node-live' }), + (alerts) => expect(alerts.some((alert) => alert.source.value === SEED_IP)).toBe(true) + ); + await expectGate( + 'alertOriginFilter', + () => watcher.Alerts.search({ origin: 'cscli' }), + (alerts) => expect(alerts.some((alert) => alert.source.value === SEED_IP)).toBe(true) + ); + }); + + it.skipIf(!wantWatcher)('reads one alert with decisions and versioned fields', async () => { + ensureSeeded(); + + const alert = await watcher.Alerts.getById(String(seeded.ipAlert)); + expect(alert.id).toBe(seeded.ipAlert); + expect(alert.source.value).toBe(SEED_IP); + expect(alert.decisions?.some((decision) => decision.value === SEED_IP)).toBe(true); + + if (supports('alertKindField') === true) { + expect(alert.kind).toBe('node-live'); + } + if (supports('uuidField') === true) { + expect(alert.uuid).toBeTruthy(); + } + }); + + it.skipIf(!wantWatcher || !wantBouncer)('deletes an IP without deleting the Range decision that contains it', async () => { + ensureSeeded(); + const state = supports('containsFilter'); + + if (state === false) { + await expect(watcher.Decisions.delete({ ip: SEED_IP, contains: false })).rejects.toBeInstanceOf(FeatureNotSupportedError); + return; + } + + const deleted = await watcher.Decisions.delete({ ip: SEED_IP, contains: false }); + expect(Number(deleted.nbDeleted)).toBeGreaterThan(0); + + const remaining = await bouncer.Decisions.search({ ip: SEED_RANGE, contains: false }); + expect(remaining.some((decision) => decision.value === SEED_RANGE)).toBe(true); + }); + + it.skipIf(!wantWatcher || !wantBouncer)('deletes a range by type and leaves other decision types', async () => { + ensureSeeded(); + const state = supports('containsFilter'); + + if (state === false) { + await expect(watcher.Decisions.delete({ range: SEED_RANGE, contains: false, type: 'ban' })).rejects.toBeInstanceOf( + FeatureNotSupportedError + ); + return; + } + + const deleted = await watcher.Decisions.delete({ range: SEED_RANGE, contains: false, type: 'ban' }); + expect(Number(deleted.nbDeleted)).toBeGreaterThan(0); + + const remaining = await bouncer.Decisions.search({ ip: SEED_MULTI_IP, contains: false }); + expect(remaining.some((decision) => decision.type === 'captcha')).toBe(true); + expect(remaining.some((decision) => decision.type === 'ban')).toBe(false); + }); + + it.skipIf(!wantWatcher)('learns the scope delete parameter from a real call when the version is unknown', async () => { + const bare = new WatcherClient({ + url: url!, + auth: { machineID: machineId!, password: password!, autoRenew: false }, + heartbeat: false, + strictSSL, + timeout: 10_000 + }); + + try { + await bare.login(); + expect(bare.supports('decisionScopesDelete')).toBeUndefined(); + + const first = await bare.Decisions.delete({ scopes: 'Country', value: 'ZZ' }); + expect(Number(first.nbDeleted)).toBe(0); + expect(typeof bare.supports('decisionScopesDelete')).toBe('boolean'); + + // The learned value must be reused on the next call. + const second = await bare.Decisions.delete({ scopes: 'Country', value: 'ZZ' }); + expect(Number(second.nbDeleted)).toBe(0); + } finally { + await bare.stop(); + } + }); + + it.skipIf(!wantWatcher)('learns the scope delete parameter when the caller uses the singular scope', async () => { + const bare = new WatcherClient({ + url: url!, + auth: { machineID: machineId!, password: password!, autoRenew: false }, + heartbeat: false, + strictSSL, + timeout: 10_000 + }); + + try { + await bare.login(); + expect(bare.supports('decisionScopesDelete')).toBeUndefined(); + + const result = await bare.Decisions.delete({ scope: 'Country', value: 'ZZ' }); + expect(Number(result.nbDeleted)).toBe(0); + expect(typeof bare.supports('decisionScopesDelete')).toBe('boolean'); + } finally { + await bare.stop(); + } + }); + + it.skipIf(!wantWatcher || !wantBouncer)('deletes non-IP scopes through the plural scopes filter', async () => { + if (!countrySeeded) { + return; + } + + // The client normalizes this to `scope` before 1.4.0 when the version + // is declared, and falls back on the first 500 when it is unknown. + const deleted = await watcher.Decisions.delete({ scopes: 'Country', value: 'FR' }); + expect(Number(deleted.nbDeleted)).toBeGreaterThan(0); + + const remaining = await bouncer.Decisions.search({ value: 'FR' }); + expect(remaining).toHaveLength(0); + }); + + it.skipIf(!wantWatcher || !wantBouncer)('deletes a decision by id', async () => { + const id = await pushAlert(makeAlert({ source: ipSource(SEED_BY_ID_IP), decisions: [makeDecision('Ip', SEED_BY_ID_IP)] })); + expect(id).toBeGreaterThan(0); + + const decisions = await bouncer.Decisions.search({}); + const decision = decisions.find((candidate) => candidate.value === SEED_BY_ID_IP); + expect(decision?.id).toBeDefined(); + + const deleted = await watcher.Decisions.deleteById(String(decision!.id)); + expect(Number(deleted.nbDeleted)).toBe(1); + }); + + it.skipIf(!wantWatcher)('gates the scenario delete filter', async () => { + await expectGate( + 'decisionScenarioDelete', + () => watcher.Decisions.delete({ scenario: 'node-live-does-not-exist' }), + (value) => expect(Number(value.nbDeleted)).toBeGreaterThanOrEqual(0) + ); + }); + + it.skipIf(!wantWatcher)('gates allowlists and checks a seeded allowlist', async () => { + const state = supports('allowlists'); + + if (state === false) { + await expect(watcher.Allowlists.list()).rejects.toBeInstanceOf(FeatureNotSupportedError); + } else if (state === true) { + const allowlists = await watcher.Allowlists.list(); + expect(Array.isArray(allowlists)).toBe(true); + + if (allowlistName) { + const allowlist = await watcher.Allowlists.get(allowlistName); + expect(allowlist.name).toBe(allowlistName); + + const check = await watcher.Allowlists.check(allowlistIp); + expect(check.allowlisted).toBe(true); + } + } + + const bulkState = supports('allowlistsBulkCheck'); + if (bulkState === false) { + // On 1.6.6-1.6.8 the bulk route is missing, but bulkCheck falls back + // to the single-value route when allowlists are supported. + if (supports('allowlists') === false) { + await expect(watcher.Allowlists.bulkCheck([allowlistIp])).rejects.toBeInstanceOf(FeatureNotSupportedError); + } else if (allowlistName) { + const bulk = await watcher.Allowlists.bulkCheck([allowlistIp]); + expect(bulk.results.some((result) => result.target === allowlistIp)).toBe(true); + } + } else if (bulkState === true && allowlistName) { + const bulk = await watcher.Allowlists.bulkCheck([allowlistIp]); + expect(bulk.results.some((result) => result.target === allowlistIp)).toBe(true); + } + }); + + it.skipIf(!wantWatcher)('reports alert deletion restrictions instead of silently failing', async () => { + ensureSeeded(); + const state = supports('alertDeleteById'); + + if (state === false) { + await expect(watcher.Alerts.deleteById(String(seeded.ipAlert))).rejects.toBeInstanceOf(FeatureNotSupportedError); + return; + } + + const result = await attempt(() => watcher.Alerts.deleteById(String(seeded.ipAlert))); + if (result.ok) { + return; + } + + // 403: route exists but deletion is LAPI-host-only. + // 405: route did not exist yet (1.4.0/1.4.1 cannot be probed). + expect([403, 404, 405]).toContain(result.error?.code); + }); }); diff --git a/packages/crowdsec-client/tests/utils.test.ts b/packages/crowdsec-client/tests/utils.test.ts index 1f00cd21e..871bcb3ff 100644 --- a/packages/crowdsec-client/tests/utils.test.ts +++ b/packages/crowdsec-client/tests/utils.test.ts @@ -41,6 +41,15 @@ describe('utils', () => { expect(() => { parseExpiration('fake'); }).toThrow(`fail to parse duration "fake"`); + expect(() => { + parseExpiration('1hfoo'); + }).toThrow(`fail to parse duration "1hfoo"`); + expect(() => { + parseExpiration('+'); + }).toThrow(`fail to parse duration "+"`); + expect(() => { + parseExpiration('-'); + }).toThrow(`fail to parse duration "-"`); }); it('should fail to parse too big numbers', async () => { const duration = "'999999999h59m59.264032632s'"; diff --git a/packages/crowdsec-http-middleware/readme.md b/packages/crowdsec-http-middleware/readme.md index 112215f89..341ff363a 100644 --- a/packages/crowdsec-http-middleware/readme.md +++ b/packages/crowdsec-http-middleware/readme.md @@ -39,6 +39,15 @@ them to CrowdSec. Requires Node.js >= 24 and a CrowdSec LAPI. +> **For LLMs:** give your agent +> . + +The middleware works with CrowdSec LAPI `v1.0.0` and newer. The decision stream +uses the `scopes` filter (LAPI `1.1.0+`, documented from `1.2.0`); on older +servers it falls back to an unfiltered stream. See +[`docs/api-compatibility.md`](../../docs/api-compatibility.md) for the full +compatibility matrix. + ## Quick start The simplest setup: install, configure the LAPI URL + a bouncer API key, and @@ -98,67 +107,12 @@ npm i crowdsec-http-middleware crowdsec-client-scenarios you can read what are the default scenarios enabled in [crowdsec-client-scenarios](../crowdsec-client-scenarios#defaults-scenarios) -## Usage - -This package is a base package for creating HTTP middleware for HTTP servers. - -A full example, showing how you stay in control of the response (custom message -per decision type) : - -````typescript -import * as http from 'http'; -import { CrowdSecHTTPMiddleware } from 'crowdsec-http-middleware'; - -// init the middleware (we will see the options later) -const middleware = new CrowdSecHTTPMiddleware(middlewareOptions); -//wait async stuff like connection to crowdsec LAPI -await middleware.start(); - -const server = http.createServer((req: IncomingMessage & { ip?: string; decision?: Decision }, res: ServerResponse) => { - try { - middleware.getMiddleware()(req, res); - } catch (e) { - console.error('middleware error', e); - } - - if (!req.decision) { - res.statusCode = 200; - res.setHeader('Content-Type', 'text/plain'); - res.end('Hello, World!'); - return; - } - - res.statusCode = 403; - res.setHeader('Content-Type', 'text/plain'); - res.end(`You can't access this api, because you are : ${req.decision?.type}`); -}); - -const port: number = 3000; -server.listen(port, () => { - console.log(`Server running at http://localhost:${port}/`); -}); -```` - -### options - -options are described here : [technical documentation](https://thib3113.github.io/node-crowdsec/interfaces/crowdsec_http_middleware.ICrowdSecHTTPMiddlewareOptions.html) - -#### Give to your AI agent +## Configuration -Copy-paste this into your AI agent. It reads the setup guide and interviews you -before writing the config. +Options are described in the [wiki](https://github.com/thib3113/node-crowdsec/wiki/HTTP-Middleware) +and the [technical documentation](https://thib3113.github.io/node-crowdsec/interfaces/crowdsec_http_middleware.ICrowdSecHTTPMiddlewareOptions.html). -````text -Help me configure the node-crowdsec HTTP middleware (bouncer and/or watcher, -with optional scenarios). - -1. Read this guide: https://raw.githubusercontent.com/thib3113/node-crowdsec/main/docs/agent-setup-guide.md -2. First tell me if I even need this library, then ask me the questions it lists. -3. Use the recommended defaults when I have no opinion. -4. Output the `CrowdSecHTTPMiddleware` config + a short justification. -```` - -First the global options +#### Global options ````typescript const middlewareOptions: ICrowdSecHTTPMiddlewareOptions = { @@ -215,6 +169,7 @@ const bouncerOptions = { pollingInterval: 10000, // how far up the prefix hierarchy to consider as malicious. // "resident" = only /32, "company" = up to /24 ( default ), "country" = up to /16 + // IPv6 equivalents: /128, /120, /112 (a /64 is ignored) subnetLevel: SubnetLevel.company, // optional live mode : checks unknown ips against the LAPI in the background live: { @@ -257,20 +212,6 @@ const middleware = new CrowdSecHTTPMiddleware({ }); ```` -##### Live mode behavior - -On a local cache miss, the current request **always passes** and a live check -(`GET /v1/decisions?ip=`) runs in the background. If the LAPI says the IP is -banned, the decision is injected in the local index, so the **next** request -from that IP is blocked. A malicious unknown IP can pass once, never twice. - -## Benchmarks - -`npm run bench` compares the IP lookup strategies explored during the design -(linear `isInSubnet` scan, current `MapOfMaps` index, packed `MapSMI`, sorted -`Uint32Array` + binary search, custom open-addressing hash) across hit / miss -lookups, `subnetLevel` presets and index setup. - ## Debug this library include [debug](https://www.npmjs.com/package/debug), to debug, you can set the env variable : diff --git a/packages/crowdsec-http-middleware/src/CrowdSecHTTPBouncerMiddleware.ts b/packages/crowdsec-http-middleware/src/CrowdSecHTTPBouncerMiddleware.ts index 62196fe69..a0e0b1883 100644 --- a/packages/crowdsec-http-middleware/src/CrowdSecHTTPBouncerMiddleware.ts +++ b/packages/crowdsec-http-middleware/src/CrowdSecHTTPBouncerMiddleware.ts @@ -14,11 +14,13 @@ import { IBouncerAuthentication, ICrowdSecClientOptions, ITLSAuthentication, + LapiCapability, TypedEventEmitter } from 'crowdsec-client'; import { AddressObject } from './utils.js'; import { IpObjectsCacher } from './IpObjectsCacher.js'; import { IpDecisionDB } from './IpDecisionDB.js'; +import { Address6 } from 'ip-address'; import { IncomingMessage, ServerResponse } from 'http'; import { CommonsMiddleware } from './CommonsMiddleware.js'; import { LRUCache } from 'lru-cache'; @@ -121,6 +123,9 @@ export class CrowdSecHTTPBouncerMiddleware extends CommonsMiddleware { userAgent: this.clientOptions.userAgent, timeout: this.clientOptions.timeout, strictSSL: this.clientOptions.strictSSL, + lapiVersion: this.clientOptions.lapiVersion, + detectCapabilities: this.clientOptions.detectCapabilities, + strictCapabilities: this.clientOptions.strictCapabilities, auth }); @@ -150,10 +155,17 @@ export class CrowdSecHTTPBouncerMiddleware extends CommonsMiddleware { this.logger.info('start'); await this.client.login(); - this._decisionStream = this.client.Decisions.getStream({ - interval: this.options?.pollingInterval, - scopes: ['ip', 'range'] - }); + // `scopes` requires LAPI 1.1.0. With an unknown version and strict + // capabilities, sending it would make start() fail instead of falling + // back; the unfiltered stream is narrowed in addDecision(). + const streamOptions: { interval?: number; scopes?: Array } = { + interval: this.options?.pollingInterval + }; + if (this.client.supports(LapiCapability.streamScopes) === true) { + streamOptions.scopes = ['ip', 'range']; + } + + this._decisionStream = this.client.Decisions.getStream(streamOptions); this._decisionStream.on('error', (e) => { this.logger.error('client stream error', e); @@ -196,7 +208,28 @@ export class CrowdSecHTTPBouncerMiddleware extends CommonsMiddleware { return `${decision.value}:${decision.type}`; } + /** + * `SubnetLevel` is expressed for IPv4 (/32, /24, /16). An IPv6 address has + * 96 more bits, so the same policy means /128, /120, /112. Comparing the raw + * masks inter-family would accept an IPv6 /32 (2^96 addresses) as "resident". + */ + private minMaskFor(ipObject: AddressObject): number { + return ipObject instanceof Address6 ? this.minMask + 96 : this.minMask; + } + + private isAllowedMask(ipObject: AddressObject): boolean { + return ipObject.subnetMask >= this.minMaskFor(ipObject); + } + private addDecision(decision: decisionType): boolean { + // The stream may be unfiltered on LAPI < 1.1.0; only ip/range scopes can + // be stored in the IP decision database. An absent scope is kept for + // callers that build a decision without the field. + const scope: string | undefined = decision.scope; + if (scope !== undefined && scope !== 'ip' && scope !== 'range') { + return false; + } + const key = this.decisionKey(decision); if (this.decisionKeys.has(key)) { return false; @@ -204,8 +237,13 @@ export class CrowdSecHTTPBouncerMiddleware extends CommonsMiddleware { const ipObject = this.ipObjectCache.getIpObjectWithCache(decision.value); // ignore decisions with a bigger subnet than configured (e.g. /8 country blocks) - if (ipObject.subnetMask < this.minMask) { - this.logger.debug('ignore decision %s: subnet mask %o < minMask %o', decision.value, ipObject.subnetMask, this.minMask); + if (!this.isAllowedMask(ipObject)) { + this.logger.debug( + 'ignore decision %s: subnet mask %o < minMask %o', + decision.value, + ipObject.subnetMask, + this.minMaskFor(ipObject) + ); return false; } @@ -319,8 +357,22 @@ export class CrowdSecHTTPBouncerMiddleware extends CommonsMiddleware { if (d.type !== 'ban' && d.type !== 'captcha') { return false; } - const ipObject = this.ipObjectCache.getIpObjectWithCache(d.value); - return ipObject.subnetMask >= this.minMask; + const scope: string | undefined = d.scope; + if (scope !== undefined && scope !== 'ip' && scope !== 'range') { + return false; + } + if (typeof d.value !== 'string' || !d.value) { + return false; + } + + try { + return this.isAllowedMask(this.ipObjectCache.getIpObjectWithCache(d.value)); + } catch (e) { + // One malformed decision must not discard the valid bans in + // the same live-check response. + localDebug.debug('ignore malformed live decision %o : %o', d.value, e); + return false; + } }); if (blocking.length === 0) { diff --git a/packages/crowdsec-http-middleware/src/CrowdSecHTTPMiddleware.ts b/packages/crowdsec-http-middleware/src/CrowdSecHTTPMiddleware.ts index aff839f4b..dbea1a83f 100644 --- a/packages/crowdsec-http-middleware/src/CrowdSecHTTPMiddleware.ts +++ b/packages/crowdsec-http-middleware/src/CrowdSecHTTPMiddleware.ts @@ -62,7 +62,8 @@ export class CrowdSecHTTPMiddleware extends CommonsMiddleware { /** * extract current ip from the request . - * First try the option getCurrentIp, second check if a scenario allow to extractIp + * First try the option getCurrentIp, then a scenario, then the socket address + * (the bouncer-only quickstart has no scenario loaded). * @param req * @private */ @@ -71,10 +72,10 @@ export class CrowdSecHTTPMiddleware extends CommonsMiddleware { return this.options.getCurrentIp(req); } - const ip = this.watcher?.extractIp(req); + const ip = this.watcher?.extractIp(req) ?? req.socket.remoteAddress; if (!ip) { - throw new Error('no scenario can extract the ip from this request . And no option "getCurrentIp" to extract it'); + throw new Error('cannot determine the client ip: provide getCurrentIp or a scenario'); } return ip; diff --git a/packages/crowdsec-http-middleware/src/CrowdSecHTTPWatcherMiddleware.ts b/packages/crowdsec-http-middleware/src/CrowdSecHTTPWatcherMiddleware.ts index e5a3c6952..76fe461d6 100644 --- a/packages/crowdsec-http-middleware/src/CrowdSecHTTPWatcherMiddleware.ts +++ b/packages/crowdsec-http-middleware/src/CrowdSecHTTPWatcherMiddleware.ts @@ -3,10 +3,13 @@ import Validate from './Validate.js'; import { APITypes, Decision, ICrowdSecClientOptions, ITLSAuthentication, IWatcherAuthentication, WatcherClient } from 'crowdsec-client'; import { IpObjectsCacher } from './IpObjectsCacher.js'; import { IncomingMessage } from 'http'; -import { BaseScenario, IIpExtractionResult, IScenario, IScenarioConstructor, MAX_CONFIDENCE } from 'crowdsec-client-scenarios'; +import type { IIpExtractionResult, IScenario, IScenarioConstructor } from './scenarios-types.js'; import { CommonsMiddleware } from './CommonsMiddleware.js'; const SCENARIOS_PACKAGE_NAME = 'crowdsec-client-scenarios'; +// Kept local so the published middleware does not import the optional +// scenarios package at module load time (it is a devDependency). +const MAX_CONFIDENCE = 10; /** * TODO @@ -36,6 +39,9 @@ export class CrowdSecHTTPWatcherMiddleware extends CommonsMiddleware { userAgent: this.clientOptions.userAgent, timeout: this.clientOptions.timeout, strictSSL: this.clientOptions.strictSSL, + lapiVersion: this.clientOptions.lapiVersion, + detectCapabilities: this.clientOptions.detectCapabilities, + strictCapabilities: this.clientOptions.strictCapabilities, heartbeat: options?.heartbeat, auth }); @@ -89,7 +95,7 @@ export class CrowdSecHTTPWatcherMiddleware extends CommonsMiddleware { public async loadDefaultsScenarios(allowFail = false) { this.logger.info('loadDefaultsScenarios'); - let defaultScenariosPackage: { scenarios: Array BaseScenario> }; + let defaultScenariosPackage: { scenarios: Array }; try { defaultScenariosPackage = await import(SCENARIOS_PACKAGE_NAME); } catch (e) { diff --git a/packages/crowdsec-http-middleware/src/ICrowdSecHTTPMiddlewareOptions.ts b/packages/crowdsec-http-middleware/src/ICrowdSecHTTPMiddlewareOptions.ts index d47b7ff6a..798a6db24 100644 --- a/packages/crowdsec-http-middleware/src/ICrowdSecHTTPMiddlewareOptions.ts +++ b/packages/crowdsec-http-middleware/src/ICrowdSecHTTPMiddlewareOptions.ts @@ -1,7 +1,7 @@ import type { IBouncerAuthentication, ITLSAuthentication, IWatcherAuthentication } from 'crowdsec-client'; import { ICrowdSecClientOptions } from 'crowdsec-client'; import { IncomingMessage } from 'http'; -import { IScenarioConstructor, IScenarioOptions } from 'crowdsec-client-scenarios'; +import type { IScenarioConstructor, IScenarioOptions } from './scenarios-types.js'; export type logFn = (message?: any, ...optionalParams: any[]) => void; export type logger = { @@ -29,6 +29,10 @@ export interface ICommonOptions { * hosts abusive customers but the whole datacenter is rarely banned. Checking * country-sized blocks is an extreme edge case, so this lets the operator * choose how far up the prefix hierarchy to look. + * + * IPv6 uses the equivalent masks: `resident` = /128, `company` = /120, + * `country` = /112. A broader IPv6 range (for example /64) is ignored at every + * level. */ export enum SubnetLevel { /** only single IPs ( /32 ) : an individual attacker */ diff --git a/packages/crowdsec-http-middleware/src/IpDecisionDB.ts b/packages/crowdsec-http-middleware/src/IpDecisionDB.ts index 8949ccc92..cf83fc586 100644 --- a/packages/crowdsec-http-middleware/src/IpDecisionDB.ts +++ b/packages/crowdsec-http-middleware/src/IpDecisionDB.ts @@ -160,9 +160,18 @@ export class IpDecisionDB { private keyFor(ip: AddressObject, mask: number): numericAddress { const numeric = this.numericOf(ip); if (typeof numeric === 'number') { + // An IPv4 address can never match an IPv6 mask bucket. Returning an + // impossible numeric key avoids relying on the number/bigint key + // type separation of the Map. + if (mask > 32) { + return -1; + } // >>> handles values up to 2^32-1 and always returns an unsigned int return numeric >>> (32 - mask); } + if (mask > 128) { + return -1n; + } return numeric >> BigInt(128 - mask); } } diff --git a/packages/crowdsec-http-middleware/src/scenarios-types.ts b/packages/crowdsec-http-middleware/src/scenarios-types.ts new file mode 100644 index 000000000..2a75ffc93 --- /dev/null +++ b/packages/crowdsec-http-middleware/src/scenarios-types.ts @@ -0,0 +1,32 @@ +import type { APITypes } from 'crowdsec-client'; +import type { IncomingMessage } from 'node:http'; +import type { AddressObject } from './utils.js'; + +/** + * Minimal structural types for the optional `crowdsec-client-scenarios` + * package. The published middleware must not depend on that devDependency at + * type-resolution time (bouncer-only consumers do not install it). + */ +export interface IScenarioOptions { + maxIpCache?: number; + 'x-forwarded-for'?: unknown; + maxmind?: unknown; + 'allow-list'?: unknown; +} + +export interface IIpExtractionResult { + ip: string; + confidence: number; +} + +export interface IScenario { + name: string; + announceToLAPI?: boolean; + load?: () => Promise; + loaded?: boolean; + check?: (ip: AddressObject, req: IncomingMessage) => APITypes.Alert | Array | undefined; + enrich?: (alert: APITypes.Alert, req: IncomingMessage) => APITypes.Alert | undefined; + extractIp?: (req: IncomingMessage) => IIpExtractionResult | undefined; +} + +export type IScenarioConstructor = new (option?: any) => IScenario; diff --git a/packages/crowdsec-http-middleware/src/utils.ts b/packages/crowdsec-http-middleware/src/utils.ts index 0cb2527b9..4321147ae 100644 --- a/packages/crowdsec-http-middleware/src/utils.ts +++ b/packages/crowdsec-http-middleware/src/utils.ts @@ -45,8 +45,11 @@ export const getIpObject = (ip: string): AddressObject => { //maybe it's a valid IPv6 const address = new Address6(ip); - //IPv4-mapped IPv6 are compared as IPv4 ( https://github.com/thib3113/node-crowdsec/issues/88 ) - if (address.is4() && address.address4) { + // IPv4-mapped IPv6 are compared as IPv4 ( https://github.com/thib3113/node-crowdsec/issues/88 ). + // `is4()` is notation-level and also matches non-mapped dotted-quad + // forms; require a real mapped address and a /96+ prefix so a + // `::ffff:10.0.0.0/64` is not silently turned into an IPv4 /32. + if (address.isMapped4() && address.subnetMask >= 96 && address.address4) { return address.address4; } diff --git a/packages/crowdsec-http-middleware/tests/liveMode.tests.ts b/packages/crowdsec-http-middleware/tests/liveMode.tests.ts index bc1414a50..48fc70b73 100644 --- a/packages/crowdsec-http-middleware/tests/liveMode.tests.ts +++ b/packages/crowdsec-http-middleware/tests/liveMode.tests.ts @@ -63,6 +63,26 @@ describe('CrowdSecHTTPBouncerMiddleware live mode', () => { expect((await checkIp(middleware, '10.0.0.5'))?.value).toBe('10.0.0.5'); }); + it('should keep valid bans and ignore non-ip or malformed decisions in a mixed response', async () => { + mockSearch.mockResolvedValueOnce([ + { type: 'ban', value: '10.0.0.5', duration: '1h', scope: 'ip' }, + { type: 'ban', value: 'FR', duration: '1h', scope: 'country' }, + { type: 'ban', value: 'not-an-ip', duration: '1h', scope: 'ip' } + ]); + const errors: unknown[] = []; + // @ts-ignore event typing is internal + middleware.liveEvents.on('liveCheckError', (e: unknown) => errors.push(e)); + + const req = {} as IncomingMessage & { decision?: Decision }; + // @ts-ignore + middleware.middleware('10.0.0.5', req); + await waitForLiveEvent(middleware, 'liveDecisionAdded'); + + expect(middleware.decisionsCount).toBe(1); + expect((await checkIp(middleware, '10.0.0.5'))?.value).toBe('10.0.0.5'); + expect(errors).toHaveLength(0); + }); + it('should cache a clean verdict and not re-check', async () => { mockSearch.mockResolvedValueOnce([]); diff --git a/packages/crowdsec-http-middleware/tests/optionPropagation.tests.ts b/packages/crowdsec-http-middleware/tests/optionPropagation.tests.ts index e8b77d954..c5a19f409 100644 --- a/packages/crowdsec-http-middleware/tests/optionPropagation.tests.ts +++ b/packages/crowdsec-http-middleware/tests/optionPropagation.tests.ts @@ -1,6 +1,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { CrowdSecHTTPMiddleware } from '../src/CrowdSecHTTPMiddleware.js'; +import { CrowdSecHTTPBouncerMiddleware } from '../src/CrowdSecHTTPBouncerMiddleware.js'; import { LiveCheckErrorBehavior, SubnetLevel } from '../src/ICrowdSecHTTPMiddlewareOptions.js'; +import { LapiCapability } from 'crowdsec-client'; import { IncomingMessage } from 'http'; const makeMiddleware = (bouncer?: Record) => @@ -35,6 +37,100 @@ describe('CrowdSecHTTPMiddleware option propagation', () => { expect(middleware.bouncer.live.errorBehavior).toBe(LiveCheckErrorBehavior.failFast); }); + it('should propagate client options to the clients', () => { + const middleware = new CrowdSecHTTPMiddleware({ + url: 'https://crowdsec.lan', + clientOptions: { + lapiVersion: '1.8.2', + detectCapabilities: true, + strictCapabilities: true + }, + bouncer: { apiKey: 'test-apiKey' } + }); + + // @ts-ignore private field + expect(middleware.bouncer.client.options.lapiVersion).toBe('1.8.2'); + // @ts-ignore private field + expect(middleware.bouncer.client.options.detectCapabilities).toBe(true); + // @ts-ignore private field + expect(middleware.bouncer.client.options.strictCapabilities).toBe(true); + }); + + it('should use the socket address when getCurrentIp is not configured', () => { + const middleware = new CrowdSecHTTPMiddleware({ + url: 'https://crowdsec.lan', + bouncer: { apiKey: 'test-apiKey' } + }); + const req = { socket: { remoteAddress: '203.0.113.9' }, headers: {} } as unknown as IncomingMessage; + // @ts-ignore private field + const spy = vi.spyOn(middleware.bouncer, 'middleware').mockImplementation(() => {}); + + middleware.getMiddleware()(req); + + expect(spy).toHaveBeenCalledWith('203.0.113.9', req); + }); + + it('should propagate client options to the watcher client', () => { + const middleware = new CrowdSecHTTPMiddleware({ + url: 'https://crowdsec.lan', + clientOptions: { + lapiVersion: '1.8.2', + detectCapabilities: true, + strictCapabilities: true + }, + watcher: { machineID: 'machine', password: 'password' } + }); + + // @ts-ignore private field + expect(middleware.watcher.client.options.lapiVersion).toBe('1.8.2'); + // @ts-ignore private field + expect(middleware.watcher.client.options.detectCapabilities).toBe(true); + // @ts-ignore private field + expect(middleware.watcher.client.options.strictCapabilities).toBe(true); + }); + + it.each([false, undefined])('should omit stream scopes when streamScopes is %s', async (value) => { + const middleware = new CrowdSecHTTPBouncerMiddleware( + { apiKey: 'test-apiKey', live: { enabled: false, watchdog: false } }, + { url: 'https://crowdsec.lan' } + ); + // @ts-ignore private field + middleware.client.login = vi.fn().mockResolvedValue(undefined); + const supports = vi.fn().mockReturnValue(value); + // @ts-ignore private field + middleware.client.supports = supports; + const stream = { on: vi.fn(), resume: vi.fn(), close: vi.fn() }; + const getStream = vi.fn().mockReturnValue(stream); + // @ts-ignore private field + middleware.client.Decisions.getStream = getStream; + + await middleware.start(); + + expect(supports).toHaveBeenCalledWith(LapiCapability.streamScopes); + expect(getStream).toHaveBeenCalledWith(expect.not.objectContaining({ scopes: expect.anything() })); + }); + + it('should send stream scopes when streamScopes is confirmed', async () => { + const middleware = new CrowdSecHTTPBouncerMiddleware( + { apiKey: 'test-apiKey', live: { enabled: false, watchdog: false } }, + { url: 'https://crowdsec.lan' } + ); + // @ts-ignore private field + middleware.client.login = vi.fn().mockResolvedValue(undefined); + const supports = vi.fn().mockReturnValue(true); + // @ts-ignore private field + middleware.client.supports = supports; + const stream = { on: vi.fn(), resume: vi.fn(), close: vi.fn() }; + const getStream = vi.fn().mockReturnValue(stream); + // @ts-ignore private field + middleware.client.Decisions.getStream = getStream; + + await middleware.start(); + + expect(supports).toHaveBeenCalledWith(LapiCapability.streamScopes); + expect(getStream).toHaveBeenCalledWith(expect.objectContaining({ scopes: ['ip', 'range'] })); + }); + it('should apply default values when no bouncer options are provided', () => { const middleware = makeMiddleware(); diff --git a/packages/crowdsec-http-middleware/tests/subnetLevel.tests.ts b/packages/crowdsec-http-middleware/tests/subnetLevel.tests.ts index 87df9c4f7..24cfa1661 100644 --- a/packages/crowdsec-http-middleware/tests/subnetLevel.tests.ts +++ b/packages/crowdsec-http-middleware/tests/subnetLevel.tests.ts @@ -39,6 +39,15 @@ describe('CrowdSecHTTPBouncerMiddleware subnetLevel', () => { } }); + it('should not turn a short-prefix mapped dotted-quad into IPv4', () => { + for (const level of [undefined, SubnetLevel.resident, SubnetLevel.company, SubnetLevel.country]) { + const middleware = makeMiddleware(level); + + expect(addDecision(middleware, '::ffff:10.0.0.0/64')).toBe(false); + expect(addDecision(middleware, '::ffff:0.0.0.0/0')).toBe(false); + } + }); + describe('default (company /24)', () => { let middleware: CrowdSecHTTPBouncerMiddleware; beforeEach(() => { @@ -61,6 +70,14 @@ describe('CrowdSecHTTPBouncerMiddleware subnetLevel', () => { expect(middleware.decisionsCount).toBe(0); expect(checkIp(middleware, '10.1.2.3')).toBeUndefined(); }); + + it('should apply the IPv4 policy to IPv6 (/120, not /119)', () => { + expect(addDecision(middleware, '2001:db8::/120')).toBe(true); + expect(checkIp(middleware, '2001:db8::1')?.value).toBe('2001:db8::/120'); + + expect(addDecision(middleware, '2001:db8:1::/119')).toBe(false); + expect(checkIp(middleware, '2001:db8:1::1')).toBeUndefined(); + }); }); describe('resident (/32 only)', () => { @@ -72,6 +89,10 @@ describe('CrowdSecHTTPBouncerMiddleware subnetLevel', () => { it('should match /32 decisions', () => { addDecision(middleware, '10.0.0.5'); expect(checkIp(middleware, '10.0.0.5')?.value).toBe('10.0.0.5'); + + // A real mapped address without a short prefix still becomes IPv4. + expect(addDecision(middleware, '::ffff:10.0.0.6')).toBe(true); + expect(checkIp(middleware, '10.0.0.6')?.value).toBe('::ffff:10.0.0.6'); }); it('should ignore /24 decisions', () => { @@ -79,6 +100,14 @@ describe('CrowdSecHTTPBouncerMiddleware subnetLevel', () => { expect(middleware.decisionsCount).toBe(0); expect(checkIp(middleware, '10.0.0.123')).toBeUndefined(); }); + + it('should apply the IPv4 policy to IPv6 (/128, not /64)', () => { + expect(addDecision(middleware, '2001:db8::1/128')).toBe(true); + expect(checkIp(middleware, '2001:db8::1')?.value).toBe('2001:db8::1/128'); + + expect(addDecision(middleware, '2001:db8:2::/64')).toBe(false); + expect(checkIp(middleware, '2001:db8:2::5')).toBeUndefined(); + }); }); describe('country (/16)', () => { @@ -97,5 +126,13 @@ describe('CrowdSecHTTPBouncerMiddleware subnetLevel', () => { expect(middleware.decisionsCount).toBe(0); expect(checkIp(middleware, '10.1.2.3')).toBeUndefined(); }); + + it('should apply the IPv4 policy to IPv6 (/112, not /111)', () => { + expect(addDecision(middleware, '2001:db8::/112')).toBe(true); + expect(checkIp(middleware, '2001:db8::abcd')?.value).toBe('2001:db8::/112'); + + expect(addDecision(middleware, '2001:db8:1::/111')).toBe(false); + expect(checkIp(middleware, '2001:db8:1::1')).toBeUndefined(); + }); }); }); diff --git a/packages/crowdsec-mcp/README.md b/packages/crowdsec-mcp/README.md index 78b67b43b..b672fac86 100644 --- a/packages/crowdsec-mcp/README.md +++ b/packages/crowdsec-mcp/README.md @@ -20,23 +20,30 @@ **Give this to your AI agent.** Copy/paste this prompt: -> Read and give me a brief of what the MCP can do, then explain how to install and configure it for my client (Claude Desktop/Code, Cursor or opencode). Never ask me for credentials: just tell me which environment variables to set. Also explain the security impact before enabling `ban_ip`, `unban_ip` or `delete_alerts`. - -The agent can use this document as the installation and configuration reference. +> Read , then the `crowdsec-mcp` README it links, and give me a brief of what the MCP can do. Then explain how to install and configure it for my client (Claude Desktop/Code, Cursor or opencode). Never ask me for credentials: just tell me which environment variables to set. Also explain the security impact before enabling `ban_ip`, `unban_ip` or `delete_alerts`. A [Model Context Protocol](https://modelcontextprotocol.io) server for CrowdSec. It exposes decisions, alerts and allowlists to an LLM as readable Markdown, with guarded write operations for watcher credentials. - `npx`-friendly, stdio by default - Bouncer API key, watcher machine credentials, or mutual TLS - Read-only by default -- Optional Streamable HTTP transport with a mandatory bearer token +- Optional Streamable HTTP transport with a bearer token (required outside passthrough) - Server-side tool filtering - cscli-compatible behavior for decisions, alerts and allowlists +Guides (authentication, deployment, security, write operations, client +configuration, HTTP transport, troubleshooting) live in the +[MCP server wiki](https://github.com/thib3113/node-crowdsec/wiki/MCP-Server). + ## Requirements - Node.js 24 or newer. -- A reachable CrowdSec Local API (LAPI). +- A reachable CrowdSec Local API (LAPI), `v1.0.0` or newer. + +Some tools require a newer LAPI: allowlists need `1.6.6` (bulk check `1.6.9`), +alert deletion by id needs `1.4.2`, and the `kind` alert filter needs `1.7.7`. +On older servers the affected tools return an error instead of an empty result. +See [`docs/api-compatibility.md`](../../docs/api-compatibility.md) for details. ## Quick start @@ -51,7 +58,7 @@ pnpm --filter crowdsec-mcp build node packages/crowdsec-mcp/dist/index.js ``` -With a bouncer API key: +With a bouncer API key (read decisions): ```bash CROWDSEC_URL=https://crowdsec:8080 \ @@ -70,38 +77,46 @@ npx -y crowdsec-mcp ### Docker image -Published as `ghcr.io/thib3113/crowdsec-mcp` and `docker.io/thib3113/crowdsec-mcp` (multi-arch `linux/amd64`, `linux/arm64`). +Published as `ghcr.io/thib3113/crowdsec-mcp` and `docker.io/thib3113/crowdsec-mcp` +(multi-arch `linux/amd64`, `linux/arm64`). `latest` follows `main`; pin a version +tag or `sha-` for a reproducible deployment. -| Tag | Updated on | -| --- | --- | -| `latest` | every merge to `main`, including automated dependency and base-image updates | -| `X.Y.Z` | a release | -| `sha-` | the matching `main` commit | +## Authentication -`latest` therefore follows the `main` branch and can be ahead of the last release. Pin a version tag or `sha-` for a reproducible deployment. +Every supplied credential is enabled at the same time: a bouncer API key serves +the fast decision path, the watcher handles alerts, allowlists and writes. +`CROWDSEC_AUTH` only forces one mode (for example to disambiguate a mutual-TLS +certificate). All three TLS files are required together, and mutual TLS defaults +to `watcher` without `CROWDSEC_AUTH`. -## Authentication +See [Authentications](https://github.com/thib3113/node-crowdsec/wiki/Authentications) +for creating the credentials. -The authentication mode is auto-detected from the provided credentials, or can be forced with `CROWDSEC_AUTH=bouncer|watcher`. +### Passthrough credentials -| Mode | Credentials | Capabilities | -| --- | --- | --- | -| `bouncer` | `CROWDSEC_API_KEY` | read decisions | -| `watcher` | `CROWDSEC_MACHINE_ID` + `CROWDSEC_PASSWORD` | alerts, decisions, allowlists, writes | -| either | `CROWDSEC_TLS_CERT` + `CROWDSEC_TLS_KEY` + `CROWDSEC_TLS_CA` | mutual TLS | +With `CROWDSEC_MCP_PASSTHROUGH=true` (HTTP transport only), every request carries +its own LAPI credentials: -All three TLS files are required together. Use `CROWDSEC_STRICT_SSL=false` only for self-signed certificates in development. +- `X-CrowdSec-Api-Key`: bouncer API key (fast `/v1/decisions` path). +- `X-CrowdSec-Token`: watcher JWT (alerts, allowlists, writes). -With mutual TLS and no explicit `CROWDSEC_AUTH`, the server defaults to `watcher` (agent certificate). Set `CROWDSEC_AUTH=bouncer` when the certificate belongs to a bouncer. +Both headers may be sent together; the request then gets the union of the +bouncer and watcher capabilities. Mutual TLS is rejected in passthrough mode +because certificates cannot be selected per request. -If both a bouncer key and machine credentials are present, set `CROWDSEC_AUTH` explicitly. Without it, the bouncer API key takes precedence. +**Security requirement.** The reverse proxy in front of the MCP server must +strip any incoming `X-CrowdSec-*` header and inject only the credentials it +vouches for. Otherwise a caller can add the missing header and combine its own +credential with the proxy-injected identity. Keep `CROWDSEC_MCP_HTTP_TOKEN` set +in passthrough mode so callers must authenticate to the MCP server itself. ### Environment variables | Variable | Description | Default | | --- | --- | --- | | `CROWDSEC_URL` | CrowdSec LAPI URL | required | -| `CROWDSEC_AUTH` | `bouncer` or `watcher` | auto | +| `CROWDSEC_AUTH` | Force `bouncer` or `watcher`; omit to enable every supplied credential | auto | +| `CROWDSEC_LAPI_VERSION` | Declared LAPI version (e.g. `1.8.2`); resolves version-gated filters without probing | auto | | `CROWDSEC_API_KEY` | Bouncer API key | - | | `CROWDSEC_MACHINE_ID` | Watcher machine ID | - | | `CROWDSEC_PASSWORD` | Watcher password | - | @@ -123,23 +138,37 @@ If both a bouncer key and machine credentials are present, set `CROWDSEC_AUTH` e | `CROWDSEC_MCP_MAX_RESULTS` | Default result limit | `25` | | `CROWDSEC_MCP_MAX_BAN_DURATION` | Maximum ban duration without `force` | `24h` | -Secrets should stay in the environment. Command-line arguments are available for convenience, but are visible in the process list. +`CROWDSEC_API_KEY`, `CROWDSEC_MACHINE_ID`, `CROWDSEC_PASSWORD` and +`CROWDSEC_MCP_HTTP_TOKEN` also accept a `_FILE` variant. Trailing line endings +written by Docker/Kubernetes secrets are stripped; leading and trailing spaces +are preserved because they can be part of a password. Precedence: command-line +flag > plain variable > `_FILE`. A missing file is reported by naming the +variable, never the path. -### CLI arguments +Secrets should stay in the environment or in secret files. Command-line +arguments are visible in the process list. -Most environment variables above have a kebab-case argument equivalent: `--url`, `--auth`, `--api-key`, `--machine-id`, `--password`, `--tls-cert`, `--tls-key`, `--tls-ca`, `--timeout`, `--transport`, `--http-host`, `--http-port`, `--http-token`, `--passthrough`, `--enable-alert-delete`, `--allow-alert-delete-without-token`, `--tools`, `--disable-tools`, `--max-results`, `--max-ban-duration`. Exceptions: `CROWDSEC_STRICT_SSL` uses `--insecure`, and `CROWDSEC_MCP_READONLY` uses `--readonly`/`--write`. +### CLI arguments -Use `--help` for the full list. +Most environment variables have a kebab-case equivalent: `--url`, `--auth`, +`--api-key`, `--machine-id`, `--password`, `--tls-cert`, `--tls-key`, `--tls-ca`, +`--timeout`, `--transport`, `--http-host`, `--http-port`, `--http-token`, +`--passthrough`, `--enable-alert-delete`, `--allow-alert-delete-without-token`, +`--tools`, `--disable-tools`, `--max-results`, `--max-ban-duration`. Exceptions: +`CROWDSEC_STRICT_SSL` uses `--insecure`, and `CROWDSEC_MCP_READONLY` uses +`--readonly`/`--write`. Use `--help` for the full list. ## Tools -Read-only tools are always available according to the authentication mode. Write tools are hidden by default and require `CROWDSEC_MCP_READONLY=false`. +Read-only tools are available according to the configured credentials and their +capabilities. Write tools are hidden by default and require +`CROWDSEC_MCP_READONLY=false`. | Tool | Kind | Auth | Description | | --- | --- | --- | --- | | `crowdsec_status` | read | any | Connection status, auth mode, capabilities and active tools | | `list_decisions` | read | bouncer, watcher | Active decisions, like `cscli decisions list` | -| `get_decision` | read | watcher | Get an active decision by ID, with alert context | +| `get_decision` | read | bouncer, watcher | Get an active decision by ID; alert context is included on the watcher path | | `list_alerts` | read | watcher | Alerts with filters, like `cscli alerts list` | | `get_alert` | read | watcher | Alert details, decisions, meta and events | | `list_allowlists` | read | watcher | Allowlists and their size | @@ -149,20 +178,14 @@ Read-only tools are always available according to the authentication mode. Write | `unban_ip` | write | watcher | Delete decisions by ID, filters, or all with confirmation | | `delete_alerts` | write | watcher | Opt-in; delete alerts by ID, filters, or all with confirmation (local deployment only) | -### Read-only by default +When read-only is enabled, write tools are not advertised at all: the model +cannot call them. -```bash -CROWDSEC_MCP_READONLY=true # default: write tools are not registered -CROWDSEC_MCP_READONLY=false # expose write tools -``` - -When read-only is enabled, write tools are not advertised at all: the model cannot call them. - -`list_alerts` reports active decisions only in its Decisions column. `list_decisions`, `get_decision` and `get_alert` expose the decision ID and a computed expiry (from the remaining decision duration). - -When `limit` is explicit, the MCP fetches all matching rows so the `hidden` count is exact. Without an explicit `limit`, it fetches `CROWDSEC_MCP_MAX_RESULTS` rows and only hints that more may exist. This keeps default calls cheap on large alert datasets. - -### Limit the tools exposed to the model +**Safety.** Write tools are hidden unless `CROWDSEC_MCP_READONLY=false`. +`delete_alerts` also requires `CROWDSEC_MCP_ENABLE_ALERT_DELETE=true` and a +deployment next to the LAPI. Over HTTP, require `CROWDSEC_MCP_HTTP_TOKEN`, +restrict the bind address, and terminate TLS in front. Keep secrets in the +environment or in `_FILE` variables, not in command-line arguments. ```bash # Only these tools are registered @@ -172,422 +195,27 @@ CROWDSEC_MCP_TOOLS=crowdsec_status,list_decisions,list_alerts CROWDSEC_MCP_DISABLE_TOOLS=delete_alerts,ban_ip ``` -The allowlist wins over the denylist, and read-only mode always wins over both. Unknown names in `CROWDSEC_MCP_TOOLS` make the server fail at startup, so typos are visible immediately. - -## Documentation for the model - -The server ships its own CrowdSec documentation, so an agent can work without prior knowledge of the product: - -- **Server instructions** are sent at initialization. They carry the current authentication mode, write access, limits, availability of alerts/allowlists/alert deletion, and the working rules (investigate before acting, confirm before writing, never invent IDs). -- **Resources** can be read on demand: - - `crowdsec://docs/overview`: components, detection lifecycle, and what this MCP exposes. - - `crowdsec://docs/concepts`: alert vs decision, scopes, types, durations, origins, allowlists, bouncer vs watcher. - - `crowdsec://docs/triage`: alert to decision workflow with guardrails and `cscli` equivalents. -- **Prompts** provide ready-made workflows: - - `triage_alerts`: review recent alerts, correlate them with active decisions, propose or apply remediation. - - `investigate_ip`: summarise the detection history and remediation state of one IP. - - `banned_from_country`: list the IPs with an active decision that are geolocated in a given country. The LAPI alert search has no country filter, so the selection is done on the alert `Country` column, filled by MaxMind enrichment. - -The content adapts to the configuration: a bouncer only gets `investigate_ip` (the other prompts need alerts), and a read-only server gets analysis-only prompts. - -### Upstream CrowdSec documentation - -| Topic | Link | -| --- | --- | -| Introduction | | -| Concepts | | -| Local API | | -| Remediation components (bouncers) | | -| Scenarios | | -| Central API and community blocklist | | -| Centralized allowlists | | -| `cscli alerts` | | -| `cscli decisions` | | -| `cscli allowlists` | | - -## Write operations - -### `ban_ip` - -Mirrors `cscli decisions add`: - -```text -ban_ip(ip="203.0.113.10", duration="4h", type="ban", reason="manual block") -ban_ip(range="203.0.113.0/24", duration="1h", type="captcha") -``` - -- Provide exactly one of `ip`, `range`, or `scope` + `value`; mixing them is rejected. -- IP and CIDR inputs are validated before sending anything. Scopes and decision types are validated too. -- The value is checked against allowlists first. If it is allowlisted, the call is refused unless `force=true`. -- `duration` accepts a unit (`30m`, `4h`, `7d`, `1h30m`). A bare number is interpreted as seconds (`300` = `5m`). -- `Country` values must be two-letter codes; `AS` values must be numeric ASNs. `Ip`/`Range` values are validated as IP/CIDR. -- `duration` is limited by `CROWDSEC_MCP_MAX_BAN_DURATION` unless `force=true`. -- CrowdSec accepts private, unspecified (`0.0.0.0`), broadcast and TEST-NET addresses; the MCP does not filter them. -- The decision is created through `POST /v1/alerts`, exactly like cscli. It is therefore visible as an alert, and may be forwarded to CAPI depending on your CrowdSec configuration. -- `origin` is always `cscli`; the MCP does not impersonate a scenario. - -### `unban_ip` - -`unban_ip` deletes decisions and works from anywhere: - -```text -unban_ip(ip="203.0.113.10") -unban_ip(id="42") -unban_ip(all=true, confirm=true) -``` - -`all=true` without `confirm=true` is rejected. `scope` must be combined with `value` (`unban_ip(scope="Country", value="FR")`); `scope` alone is rejected so a broad filter cannot delete every decision of that scope. `range` containment is resolved through an alert search and deleted by ID; other scopes are sent directly to the LAPI. `type`/`scenario` alone are broad and also require `confirm=true`; narrow with `ip`, `range`, or `scope`+`value`. - -### `delete_alerts` (opt-in) +The allowlist wins over the denylist, and read-only mode always wins over both. +Unknown names in `CROWDSEC_MCP_TOOLS` fail when the toolset is built: at startup +in static mode, and on the request in passthrough mode. -`delete_alerts` is disabled by default because CrowdSec only allows alert deletion from the LAPI host. Enable it only when the MCP runs next to the LAPI: - -```bash -CROWDSEC_MCP_ENABLE_ALERT_DELETE=true -``` - -A remote watcher receives `403 access forbidden from this IP`. Use `unban_ip` to remove decisions remotely, and `cscli alerts delete` on the LAPI host to clean up alerts. - -Over HTTP, `delete_alerts` is hidden unless a service token (`CROWDSEC_MCP_HTTP_TOKEN`) is configured or `CROWDSEC_MCP_ALLOW_ALERT_DELETE_WITHOUT_TOKEN=true` is set. This prevents a tokenless shared MCP (for example in passthrough mode) from exposing the local-only destructive path. Over stdio, the process is already local, so only `CROWDSEC_MCP_ENABLE_ALERT_DELETE` is required. - -`all=true` cannot be combined with filters. `ip` and `range` accept a CIDR and perform containment. `type` is resolved through an alert search followed by deletion by ID, as the conservative path for LAPIs that do not accept `decision_type` on DELETE. `since` and `until` are Go durations (`24h`, `7d`) and are sent directly to the delete endpoint, like the alert search. `id`, `origin` (sent as `alert_source`) and `has_active_decision` are sent directly. `scope` must be combined with `value`; scope alone is rejected to avoid deleting every alert of that scope. Deleting without a narrow target (`id`, `ip`, `range`, or `scope`+`value`) — e.g. `scenario`, `origin`, `type`, `since`/`until` or `has_active_decision` alone — requires `confirm=true`, like `unban_ip`. Deleting an alert also deletes its active decisions; this cascade is a CrowdSec LAPI behavior. - -### CIDR semantics - -- `list_decisions(ip="198.51.100.0/24")` performs containment (`contains=false`, the default). `contains=true` returns decisions that contain the value. -- `list_alerts`, `delete_alerts` and `unban_ip` accept a CIDR in `ip`/`range` and perform containment. -- `delete_alerts` deletes matching alerts by ID when containment is used. -- `unban_ip` supports non-IP scopes (`Country`, `AS`, `Session`, `Username`) by resolving active decisions and deleting them by ID. - -## Allowlists - -Allowlists are read/check only. The CrowdSec local API exposes no create, update or delete endpoint for allowlists: those operations are done with `cscli allowlists ...` or the CrowdSec Console. The MCP therefore provides: - -- `list_allowlists` -- `get_allowlist` -- `check_allowlist` - -`ban_ip` automatically calls `check_allowlist` for IP and range scopes, like cscli. `check_allowlist` accepts IPs and CIDR ranges only; the LAPI bulk check endpoint does not support other scopes. When the target is a CIDR, a match means the CIDR overlaps or contains an allowlisted entry; the output labels it as a CIDR match rather than an exact IP match. - -`list_allowlists` reports an exact item count, which the LAPI only provides by returning every allowlist together with its items. On accounts with large allowlists this is the most expensive read tool; prefer `get_allowlist` with a `limit` when only one allowlist is needed. - -## Performance - -Rule of thumb, measured against a local CrowdSec 1.8 LAPI: - -| Operation | Path | Throughput | Payload | -| --- | --- | --- | --- | -| `list_decisions` | bouncer `GET /v1/decisions` | ~44k decisions/s | ~132 B/decision | -| `list_alerts` / `get_alert` | watcher `GET /v1/alerts` | ~870 alerts/s | 766 B–3.5 KiB/alert | - -The alert endpoints are the slow path: they stream a chunked response with no `Content-Length` and no `X-Total-Count`, so the size is unknown until it has been read. `limit=0` (or a large explicit `limit`) reads everything, which took ~11.5 s for 10k minimal alerts and scales linearly. Prefer a small `limit`, a `since` window, or `has_active_decision=true` to keep a call cheap. CrowdSec marshals the whole response before writing it, so `CROWDSEC_TIMEOUT` behaves like a total time-to-first-byte budget rather than an idle-socket timeout. - -## MCP client configuration - -### Claude Desktop / Claude Code - -```json -{ - "mcpServers": { - "crowdsec": { - "command": "npx", - "args": ["-y", "crowdsec-mcp"], - "env": { - "CROWDSEC_URL": "https://crowdsec:8080", - "CROWDSEC_MACHINE_ID": "crowdsec-mcp", - "CROWDSEC_PASSWORD": "change-me", - "CROWDSEC_MCP_READONLY": "true" - } - } - } -} -``` - -### Cursor - -```json -{ - "mcpServers": { - "crowdsec": { - "command": "npx", - "args": ["-y", "crowdsec-mcp"], - "env": { - "CROWDSEC_URL": "https://crowdsec:8080", - "CROWDSEC_API_KEY": "your-bouncer-key", - "CROWDSEC_MCP_TOOLS": "crowdsec_status,list_decisions" - } - } - } -} -``` - -### opencode - -```json -{ - "$schema": "https://opencode.ai/config.json", - "mcp": { - "crowdsec": { - "type": "local", - "command": ["npx", "-y", "crowdsec-mcp"], - "environment": { - "CROWDSEC_URL": "https://crowdsec:8080", - "CROWDSEC_API_KEY": "your-bouncer-key" - }, - "enabled": true - } - } -} -``` - -## HTTP transport - -```bash -CROWDSEC_MCP_TRANSPORT=http \ -CROWDSEC_MCP_HTTP_HOST=127.0.0.1 \ -CROWDSEC_MCP_HTTP_PORT=3939 \ -CROWDSEC_MCP_HTTP_TOKEN=change-me \ -CROWDSEC_URL=https://crowdsec:8080 \ -CROWDSEC_API_KEY=your-bouncer-key \ -npx -y crowdsec-mcp -``` - -The token is **mandatory for every request**, including on `127.0.0.1` and including unknown routes. Send it as: - -```text -Authorization: Bearer change-me -``` - -The MCP endpoint is `/mcp`. Do not expose this server publicly without TLS and a strong token: it can read security data and, when writes are enabled, ban or unban addresses. - -### Shared deployment next to CrowdSec - -A common setup is one MCP server next to the LAPI, with remote clients connecting over HTTP: - -```bash -CROWDSEC_URL=http://127.0.0.1:8080 \ -CROWDSEC_MACHINE_ID=crowdsec-mcp \ -CROWDSEC_PASSWORD=change-me \ -CROWDSEC_MCP_TRANSPORT=http \ -CROWDSEC_MCP_HTTP_HOST=0.0.0.0 \ -CROWDSEC_MCP_HTTP_TOKEN=change-me \ -CROWDSEC_MCP_READONLY=false \ -CROWDSEC_MCP_ENABLE_ALERT_DELETE=true \ -npx -y crowdsec-mcp -``` - -Clients point their MCP client at `https://mcp.example.com/mcp` and send: - -```text -Authorization: Bearer change-me -``` - -The MCP holds the LAPI credentials; users only need the MCP token. Put TLS and a reverse proxy in front, and use one token per MCP instance. This deployment allows `delete_alerts` because the LAPI sees the MCP as local. - -### Per-user passthrough (multi-user) - -For multiple users with individual LAPI credentials, enable passthrough: - -```bash -CROWDSEC_URL=http://127.0.0.1:8080 \ -CROWDSEC_MCP_TRANSPORT=http \ -CROWDSEC_MCP_HTTP_HOST=0.0.0.0 \ -CROWDSEC_MCP_PASSTHROUGH=true \ -CROWDSEC_MCP_READONLY=false \ -# Optional service gate: -# CROWDSEC_MCP_HTTP_TOKEN=change-me \ -npx -y crowdsec-mcp -``` - -Each request provides exactly one LAPI credential: - -```text -X-CrowdSec-Api-Key: # read decisions only -# OR -X-CrowdSec-Token: # full watcher tools / writes -``` - -If `CROWDSEC_MCP_HTTP_TOKEN` is configured, every request must also send: - -```text -Authorization: Bearer -``` - -Rules: -- Both `X-CrowdSec-Api-Key` and `X-CrowdSec-Token` -> `400`. -- Neither -> `401`. -- Bouncer keys expose only bouncer-compatible tools; watcher JWTs expose the watcher toolset. -- Clients are created per request and never reuse another user's credential. -- The watcher JWT must be refreshed by the user when it expires. - -**Why two tokens?** The optional service token gates the MCP endpoint itself, while the LAPI credential authorizes the actual CrowdSec action. The service token is optional because the LAPI credential already authenticates the request, but it is recommended when exposing the MCP: it prevents anonymous probing and gates the local-only `delete_alerts`. Without a service token, `delete_alerts` is hidden unless `CROWDSEC_MCP_ALLOW_ALERT_DELETE_WITHOUT_TOKEN=true` is set. - -## Security - -The MCP speaks to CrowdSec with real LAPI credentials. The security posture -depends on two choices: the transport (`stdio` vs `http`) and where the -credentials live (server environment vs per-request headers). - -### Threat model - -- **stdio**: the MCP is a local process started by the client. Nothing listens - on the network. The main risk is who can read the client config or the - process environment. -- **http**: the MCP listens on `CROWDSEC_MCP_HTTP_HOST:PORT` and only serves - `POST /mcp` (anything else is 404/405). It runs stateless: one fresh - server and transport per request, no session stored. Bodies are capped at - 4 MiB (413 beyond that) and server errors are returned as generic JSON-RPC - messages without stack traces. There is **no TLS on the MCP port itself**: - the bearer token and any passthrough credentials travel in cleartext. In - practice the server is reachable from the network (e.g. a management VLAN - for the AI agents), so put a TLS reverse proxy in front and restrict at - the firewall who can reach the port. -- Credentials (API key, password, token, TLS material) are kept in process - memory and never written to logs or tool outputs. Tool errors surfaced to - the model are truncated to their first line. - -### Recommended deployments - -| Deployment | Access control | LAPI identity | Notes | -| --- | --- | --- | --- | -| stdio, local client | OS user boundary | server env (`CROWDSEC_API_KEY` or machine credentials) | Default. Nothing exposed on the network. | -| http on `127.0.0.1` + service token | `Authorization: Bearer` per request | server env, shared by all callers | Token is mandatory at startup outside passthrough. Local-only setups. | -| http on a management VLAN + TLS reverse proxy + service token | proxy + service token, firewall-limited to the VLAN | server env, shared by all callers | The realistic production setup. Rotate the token if it leaks: every holder shares the same LAPI identity. | -| http passthrough + service token | service token + per-request LAPI credential | per request (`X-CrowdSec-Api-Key` or `X-CrowdSec-Token`) | Multi-user friendly: each caller only gets their own LAPI rights. | -| http passthrough, no service token | per-request LAPI credential only | per request | Acceptable on a trusted management VLAN; anyone with a valid LAPI credential can probe the endpoint. | - -In passthrough mode, `X-CrowdSec-Api-Key` (bouncer, read decisions only) and -`X-CrowdSec-Token` (watcher JWT, full toolset) are mutually exclusive: -sending both is a 400, sending neither is a 401. Requests headers are -validated and then discarded; one request never reuses another's credential. -The passthrough mode ignores `CROWDSEC_TLS_*`: mTLS client certificates are -not applied per request. - -### Security-relevant variables - -| Variable | Effect | Safe values | -| --- | --- | --- | -| `CROWDSEC_MCP_HTTP_HOST` | Network interface the MCP binds to. `0.0.0.0` exposes it to the LAN/container network. | `127.0.0.1` for local-only setups; otherwise bind behind a TLS reverse proxy on a management VLAN and firewall the port. | -| `CROWDSEC_MCP_HTTP_TOKEN` | Bearer token required on every request (compared in constant time). Mandatory in non-passthrough HTTP: the server refuses to start without it. | A long random value, rotated like a password. One token per MCP instance. | -| `CROWDSEC_MCP_READONLY` | `true` hides `ban_ip`, `unban_ip` and `delete_alerts` from `listTools`: the model cannot call what it cannot see. | Keep `true` (the default) unless writes are needed. | -| `CROWDSEC_MCP_ENABLE_ALERT_DELETE` | Exposes `delete_alerts`. Deletion only works from the LAPI host (403 otherwise). | `true` only in a sidecar/host deployment next to the LAPI. | -| `CROWDSEC_MCP_ALLOW_ALERT_DELETE_WITHOUT_TOKEN` | Forces `delete_alerts` to be exposed over HTTP **without** a service token. | Leave `false`. With this flag, anyone holding a watcher JWT can trigger local-only destructive deletions as soon as the port is reachable. | -| `CROWDSEC_MCP_TOOLS` / `CROWDSEC_MCP_DISABLE_TOOLS` | Allowlist/denylist of exposed tools. | Expose the smallest useful surface, e.g. `CROWDSEC_MCP_DISABLE_TOOLS=delete_alerts,ban_ip`. | -| `CROWDSEC_MCP_MAX_BAN_DURATION` | Bans above this need `force=true`. | `24h` default; tighten for shared deployments. | -| `CROWDSEC_STRICT_SSL` / `--insecure` | Disabling TLS validation between the MCP and the LAPI exposes credentials to MITM. | Keep `true`. Only disable for self-signed certificates in development. | - -Keep secrets in the environment, not in command-line arguments: arguments are -visible in the process list. - -### Confirmations are not authorization - -Destructive tools ask for explicit confirmation, but that is a guardrail, not -an access boundary: - -- `all=true` always requires `confirm=true`. -- `unban_ip` filtered only by `type`/`scenario` requires `confirm=true`. -- `delete_alerts` without a narrow target (`id`, `ip`, `range`, or - `scope`+`value`) — e.g. `scenario`, `origin`, `type`, time filters or - `has_active_decision` alone — requires `confirm=true`. -- `ban_ip` refuses allowlisted targets unless `force=true`; `check_allowlist` - first when in doubt. - -The server instructions repeat these rules to the model, but any client that -can reach the endpoint can also confirm: the real protection is the token, -the bind address, and the read-only default. - -## Troubleshooting - -| Symptom | Cause / fix | -| --- | --- | -| `401 Unauthorized` | Missing or invalid HTTP bearer token. In HTTP mode, send `Authorization: Bearer `. | -| `403 access forbidden from this IP` on `delete_alerts` | CrowdSec only allows alert deletion from the LAPI host. Use `unban_ip` for decisions, or enable `delete_alerts` only in a deployment next to the LAPI. | -| ` is allowlisted by item ...` | The target matches an allowlist. Use `force=true` only if you really want to ban an allowlisted value. | -| A tool is missing from `listTools` | It may be a write tool while `CROWDSEC_MCP_READONLY=true`, a watcher tool in bouncer mode, or hidden by `CROWDSEC_MCP_TOOLS` / `CROWDSEC_MCP_DISABLE_TOOLS`. | -| `invalid duration` | Use durations such as `30m`, `4h`, `7d`, `3650d`, or `1h30m`. | -| `Duration ... exceeds maximum allowed ...` | The duration is above `CROWDSEC_MCP_MAX_BAN_DURATION`. Lower it or use `force=true`. | -| `timeout of 10000ms exceeded` / `ECONNABORTED` | The LAPI did not start answering before `CROWDSEC_TIMEOUT` (milliseconds, max `600000`). Raise it, then narrow the call with `since`, `ip`, `scope`/`value` or a smaller `limit` (and `all=false`). On alert/decision scans this is a total time-to-first-byte budget, not an idle timeout. | +The server also exposes resources (`crowdsec://docs/overview`, `concepts`, +`triage`), prompts (`triage_alerts`, `investigate_ip`, `banned_from_country`) and +its own instructions to the model. See the +[MCP server wiki](https://github.com/thib3113/node-crowdsec/wiki/MCP-Server#documentation-for-the-model). ## Development ```bash pnpm --filter crowdsec-mcp build pnpm --filter crowdsec-mcp test -node packages/crowdsec-mcp/dist/index.js --help -``` - -The test suite includes unit tests, HTTP contract tests for the CrowdSec client, and a stdio end-to-end test that spawns the built binary against a fake LAPI. The integration test against a real CrowdSec LAPI in Docker also runs in CI (see the HTTP E2E script below). - -Live client checks are opt-in: - -```bash -CROWDSEC_LIVE=1 \ -CROWDSEC_URL=https://crowdsec:8080 \ -CROWDSEC_API_KEY=your-bouncer-key \ -pnpm --filter crowdsec-client exec vitest run tests/Live/live.test.ts -``` - -Set `CROWDSEC_MACHINE_ID` and `CROWDSEC_PASSWORD` instead of `CROWDSEC_API_KEY` to exercise watcher mode, including allowlists. - -### Integration test against a real LAPI - -Start a disposable CrowdSec container: - -```bash -docker run -d --name crowdsec-mcp-test \ - -p 18080:8080 \ - -v crowdsec-mcp-data:/var/lib/crowdsec/data \ - crowdsecurity/crowdsec:latest -``` - -Create credentials and seed data: - -```bash -export BOUNCER_KEY=$(docker exec crowdsec-mcp-test cscli bouncers add crowdsec-mcp-bouncer -o raw) -docker exec crowdsec-mcp-test cscli machines add crowdsec-mcp-watcher --auto -f - -# export CROWDSEC_MACHINE_ID= and CROWDSEC_PASSWORD= from the output -docker exec crowdsec-mcp-test cscli allowlists create test-allowlist -d "mcp integration" -docker exec crowdsec-mcp-test cscli allowlists add test-allowlist 192.0.2.10 -d "mcp test" -docker exec crowdsec-mcp-test cscli decisions add --ip 203.0.113.10 --duration 24h --reason "mcp integration" -``` - -Run the integration test: - -```bash -CROWDSEC_INTEGRATION=1 \ -CROWDSEC_INTEGRATION_WRITE=1 \ -CROWDSEC_URL=http://127.0.0.1:18080 \ -CROWDSEC_API_KEY="$BOUNCER_KEY" \ -CROWDSEC_MACHINE_ID= \ -CROWDSEC_PASSWORD= \ -pnpm --filter crowdsec-mcp exec vitest run tests/integration/live.test.ts -``` - -`delete_alerts` is not covered by the integration test because it requires the MCP to run next to the LAPI. Clean up with: - -```bash -docker rm -f crowdsec-mcp-test && docker volume rm crowdsec-mcp-data -``` - -### HTTP transport and passthrough E2E - -This E2E starts a disposable CrowdSec LAPI, an nginx log generator, and two MCP HTTP servers: - -- `mcp` on `23939` with a service token; -- `mcp-open` on `23940` without a service token; -- both share CrowdSec's network namespace, so `delete_alerts` works. - -Requirements: Docker Compose v2, `pnpm`, `jq` and `openssl`. The script builds the client and MCP first unless `E2E_SKIP_BUILD=1` is set. - -```bash pnpm --filter crowdsec-mcp test:e2e:http ``` -The test waits for alerts generated by nginx logs, then exercises bouncer/watcher tool filtering, per-request credentials, service-token gating, CIDR filtering of decisions, `ban_ip`, `unban_ip` by range, and local-only `delete_alerts`. It then seeds an allowlist and a decision and runs `tests/integration/live.test.ts` against the same LAPI. The orchestration script lives in `.github/scripts/mcp-http-e2e.sh`. - -Ports can be overridden with `E2E_LAPI_PORT`, `E2E_MCP_PORT`, and `E2E_MCP_OPEN_PORT`. Use `E2E_KEEP=1` to keep the stack for debugging. The stack is removed automatically, including volumes, unless `E2E_KEEP=1` is set. - -The GitHub Actions workflow is `.github/workflows/mcp-http-e2e.yml`; it runs on MCP/client/workflow changes, on pushes to `main`, and on manual dispatch. +The test suite includes unit tests, HTTP contract tests and a stdio end-to-end +test. The HTTP transport and passthrough E2E runs in +`.github/workflows/mcp-http-e2e.yml` (orchestration: +`.github/scripts/mcp-http-e2e.sh`). ## License diff --git a/packages/crowdsec-mcp/compose.yaml b/packages/crowdsec-mcp/compose.yaml index df35e8c7e..f5fe4cca1 100644 --- a/packages/crowdsec-mcp/compose.yaml +++ b/packages/crowdsec-mcp/compose.yaml @@ -8,7 +8,9 @@ services: # 3939 is published by CrowdSec because the MCP shares its network # namespace (Docker does not allow `ports` on the sidecar service). - "8080:8080" - - "3939:3939" + # Keep the MCP write surface local: passthrough writes without a service + # token must not be reachable from the network. + - "127.0.0.1:3939:3939" volumes: - crowdsec-data:/var/lib/crowdsec/data - crowdsec-config:/etc/crowdsec @@ -42,6 +44,12 @@ services: # empty the tool stays hidden, unless # CROWDSEC_MCP_ALLOW_ALERT_DELETE_WITHOUT_TOKEN=true (dangerous) is set. CROWDSEC_MCP_HTTP_TOKEN: ${CROWDSEC_MCP_HTTP_TOKEN:-} + # Static credentials can be mounted as files instead of env vars: + # CROWDSEC_API_KEY_FILE: /run/secrets/crowdsec_api_key + # CROWDSEC_MCP_HTTP_TOKEN_FILE: /run/secrets/crowdsec_mcp_http_token + # secrets: + # - crowdsec_api_key + # - crowdsec_mcp_http_token read_only: true tmpfs: - /tmp @@ -53,3 +61,11 @@ services: volumes: crowdsec-data: crowdsec-config: + +# To use file-backed secrets instead of environment variables, uncomment the +# service `secrets:` block above and this top-level declaration: +# secrets: +# crowdsec_api_key: +# file: ./crowdsec_api_key +# crowdsec_mcp_http_token: +# file: ./crowdsec_mcp_http_token diff --git a/packages/crowdsec-mcp/package.json b/packages/crowdsec-mcp/package.json index 808556598..ed2bf0e93 100644 --- a/packages/crowdsec-mcp/package.json +++ b/packages/crowdsec-mcp/package.json @@ -1,6 +1,6 @@ { "name": "crowdsec-mcp", - "version": "0.0.6", + "version": "0.1.0", "description": "Model Context Protocol (MCP) server for CrowdSec: decisions, alerts and allowlists", "type": "module", "main": "./dist/index.js", diff --git a/packages/crowdsec-mcp/src/allowlists-port.ts b/packages/crowdsec-mcp/src/allowlists-port.ts index f4028b747..0be408989 100644 --- a/packages/crowdsec-mcp/src/allowlists-port.ts +++ b/packages/crowdsec-mcp/src/allowlists-port.ts @@ -5,7 +5,7 @@ const unavailable = (): Promise => Promise.reject(new Error('allowlists a export function createAllowlistsPort(watcher: WatcherClient): AllowlistsPort { return { - list: () => watcher.Allowlists.list(), + list: (withContent = true) => watcher.Allowlists.list(withContent), get: (name, withContent) => watcher.Allowlists.get(name, withContent), check: (value) => watcher.Allowlists.check(value), bulkCheck: (targets) => watcher.Allowlists.bulkCheck(targets) diff --git a/packages/crowdsec-mcp/src/client.ts b/packages/crowdsec-mcp/src/client.ts index 8413e48c2..4a2e0dcc1 100644 --- a/packages/crowdsec-mcp/src/client.ts +++ b/packages/crowdsec-mcp/src/client.ts @@ -2,22 +2,28 @@ import { readFile } from 'node:fs/promises'; import type { IncomingHttpHeaders } from 'node:http'; import { BouncerClient, CrowdsecClientError, WatcherClient } from 'crowdsec-client'; import type { Config } from './config.js'; -import type { AppContext } from './types.js'; +import type { AppContext, ClientReadiness, ReadinessRequirement } from './types.js'; import { createAllowlistsPort, unavailableAllowlistsPort } from './allowlists-port.js'; import { HttpRequestError } from './http-error.js'; interface TokenWatcherClientOptions { url: string; token: string; + lapiVersion?: string; strictSSL?: boolean; timeout?: number; } function isAuthenticationFailure(error: unknown): boolean { // CrowdSec answers 403 for an invalid key/token and 401 for a missing one. - // The client wraps 403 as UNEXPECTED_KEY and any other status as - // UNEXPECTED_STATUS_CODE, so the status has to be read from the cause. + // Login/connection failures are wrapped as CrowdSecServerError, which + // carries the HTTP status in `code` but is not a CrowdsecClientError + // subclass; other paths use UNEXPECTED_KEY / UNEXPECTED_STATUS_CODE. // Anything else (DNS, timeout, TLS, 5xx) must keep its original message. + const code = (error as { code?: unknown } | undefined)?.code; + if (code === 401 || code === 403) { + return true; + } if (!(error instanceof CrowdsecClientError)) { return false; } @@ -31,6 +37,7 @@ class TokenWatcherClient extends WatcherClient { public constructor(options: TokenWatcherClientOptions) { super({ url: options.url, + lapiVersion: options.lapiVersion, auth: { machineID: 'passthrough', password: 'passthrough' @@ -57,7 +64,10 @@ class TokenWatcherClient extends WatcherClient { } } -export type PassthroughAuth = { mode: 'bouncer'; apiKey: string } | { mode: 'watcher'; token: string }; +export interface PassthroughAuth { + apiKey?: string; + token?: string; +} function headerValue(headers: IncomingHttpHeaders, name: string): string | undefined { const value = headers[name]; @@ -68,17 +78,13 @@ export function resolvePassthroughAuth(headers: IncomingHttpHeaders): Passthroug const apiKey = headerValue(headers, 'x-crowdsec-api-key')?.trim(); const token = headerValue(headers, 'x-crowdsec-token')?.trim(); - if (apiKey && token) { - throw new HttpRequestError(400, -32602, 'Provide either X-CrowdSec-Api-Key or X-CrowdSec-Token, not both'); - } - if (apiKey) { - return { mode: 'bouncer', apiKey }; - } - if (token) { - return { mode: 'watcher', token }; + if (!apiKey && !token) { + throw new HttpRequestError(401, -32001, 'Missing X-CrowdSec-Api-Key or X-CrowdSec-Token'); } - throw new HttpRequestError(401, -32001, 'Missing X-CrowdSec-Api-Key or X-CrowdSec-Token'); + // Both headers on the same request enable the fast decision path and the + // richer watcher tools at once, mirroring static dual credentials. + return { ...(apiKey ? { apiKey } : {}), ...(token ? { token } : {}) }; } async function loadTls(config: Config) { @@ -91,137 +97,195 @@ async function loadTls(config: Config) { return { cert, key, ca }; } -export async function createContext(config: Config): Promise { - const tls = await loadTls(config); +function buildCapabilities(watcher: WatcherClient | undefined, bouncer: BouncerClient | undefined): AppContext['capabilities'] { + return { + read: true, + alerts: watcher !== undefined, + decisions: watcher !== undefined || bouncer !== undefined, + decisionsFast: bouncer !== undefined, + write: watcher !== undefined, + allowlists: watcher !== undefined + }; +} - let watcher: WatcherClient | undefined; - let bouncer: BouncerClient | undefined; +function createReadiness( + watcher: WatcherClient | undefined, + bouncer: BouncerClient | undefined, + readiness: ClientReadiness, + mapError?: (error: unknown) => unknown +): (requirement?: ReadinessRequirement) => Promise { + // Login lazily and once per client. A watcher-only tool must not fail + // because the bouncer key is invalid, and vice versa. + const loginPromises = new WeakMap>(); + const loginOnce = async (client: WatcherClient | BouncerClient): Promise => { + const key = client === watcher ? 'watcher' : 'bouncer'; + let promise = loginPromises.get(client); + if (!promise) { + promise = client.login(); + loginPromises.set(client, promise); + } - if (config.auth === 'bouncer') { - bouncer = new BouncerClient({ - url: config.url, - auth: tls ?? { apiKey: config.apiKey! }, - strictSSL: config.strictSSL, - timeout: config.timeout - }); - } else { - watcher = new WatcherClient({ - url: config.url, - auth: tls ?? { - machineID: config.machineId!, - password: config.password!, - autoRenew: true - }, - strictSSL: config.strictSSL, - timeout: config.timeout, - heartbeat: false - }); - } + try { + await promise; + readiness[key] = 'ok'; + } catch (error) { + loginPromises.delete(client); + readiness[key] = 'error'; + throw mapError ? mapError(error) : error; + } + }; - let loginPromise: Promise | undefined; + return async (requirement: ReadinessRequirement = 'any'): Promise => { + if (requirement === 'none') { + return; + } - const ensureReady = async (): Promise => { - loginPromise ??= (watcher ?? bouncer)!.login(); + if (requirement === 'watcher') { + if (!watcher) { + throw new Error('Watcher credentials are not configured'); + } + await loginOnce(watcher); + return; + } - try { - await loginPromise; - } catch (error) { - loginPromise = undefined; - throw error; + if (requirement === 'bouncer') { + if (!bouncer) { + throw new Error('Bouncer credentials are not configured'); + } + await loginOnce(bouncer); + return; + } + + // `any` is used by crowdsec_status: prefer the bouncer (cheaper), fall + // back to the watcher, and succeed as soon as one credential works. + let lastError: unknown; + if (bouncer) { + try { + await loginOnce(bouncer); + return; + } catch (error) { + lastError = error; + } } + if (watcher) { + try { + await loginOnce(watcher); + return; + } catch (error) { + lastError = error; + } + } + + if (lastError) { + throw lastError; + } + throw new Error('No CrowdSec credentials are configured'); }; +} - const stop = async (): Promise => { - await (watcher ?? bouncer)?.stop(); +function createAuthErrorMapper(watcher: WatcherClient | undefined, bouncer: BouncerClient | undefined): (error: unknown) => unknown { + return (error) => { + if (!isAuthenticationFailure(error)) { + return error; + } + if (watcher && bouncer) { + return new Error('Invalid CrowdSec credentials'); + } + return new Error(watcher ? 'Invalid CrowdSec token' : 'Invalid CrowdSec API key'); }; +} + +function stopClients(watcher: WatcherClient | undefined, bouncer: BouncerClient | undefined): Promise { + return Promise.all([watcher?.stop(), bouncer?.stop()]).then(() => undefined); +} + +export async function createContext(config: Config): Promise { + // Only read the certificate files when a configured client actually needs + // them: an explicit machine pair or API key takes precedence, so unreadable + // TLS files must not break an otherwise valid configuration. + const needsTls = (config.watcher && !(config.machineId && config.password)) || (config.bouncer && !config.apiKey); + const tls = needsTls ? await loadTls(config) : undefined; + + // Credentials are selected per client: an explicit machine pair/API key + // always wins over the ambiguous TLS certificate. + const watcher = config.watcher + ? new WatcherClient({ + url: config.url, + lapiVersion: config.lapiVersion, + auth: + config.machineId && config.password + ? { + machineID: config.machineId, + password: config.password, + autoRenew: true + } + : (tls ?? { machineID: config.machineId!, password: config.password!, autoRenew: true }), + strictSSL: config.strictSSL, + timeout: config.timeout, + heartbeat: false + }) + : undefined; + + const bouncer = config.bouncer + ? new BouncerClient({ + url: config.url, + lapiVersion: config.lapiVersion, + auth: config.apiKey ? { apiKey: config.apiKey } : (tls ?? { apiKey: config.apiKey! }), + strictSSL: config.strictSSL, + timeout: config.timeout + }) + : undefined; + + const readiness: ClientReadiness = {}; return { mode: config.auth, - capabilities: { - read: true, - write: config.auth === 'watcher', - allowlists: config.auth === 'watcher' - }, + capabilities: buildCapabilities(watcher, bouncer), watcher, bouncer, allowlists: watcher ? createAllowlistsPort(watcher) : unavailableAllowlistsPort(), config, - ensureReady, - stop + readiness, + ensureReady: createReadiness(watcher, bouncer, readiness, createAuthErrorMapper(watcher, bouncer)), + stop: () => stopClients(watcher, bouncer) }; } export function createPassthroughContext(config: Config, headers: IncomingHttpHeaders): AppContext { const auth = resolvePassthroughAuth(headers); - if (auth.mode === 'bouncer') { - const bouncer = new BouncerClient({ - url: config.url, - auth: { apiKey: auth.apiKey }, - strictSSL: config.strictSSL, - timeout: config.timeout - }); - - let loginPromise: Promise | undefined; - const ensureReady = async (): Promise => { - loginPromise ??= bouncer.login(); - - try { - await loginPromise; - } catch (error) { - loginPromise = undefined; - if (isAuthenticationFailure(error)) { - throw new Error('Invalid CrowdSec API key'); - } - throw error; - } - }; - - return { - mode: 'bouncer', - capabilities: { - read: true, - write: false, - allowlists: false - }, - bouncer, - allowlists: unavailableAllowlistsPort(), - config, - ensureReady, - stop: () => bouncer.stop() - }; - } + const bouncer = auth.apiKey + ? new BouncerClient({ + url: config.url, + lapiVersion: config.lapiVersion, + auth: { apiKey: auth.apiKey }, + strictSSL: config.strictSSL, + timeout: config.timeout + }) + : undefined; - const watcher = new TokenWatcherClient({ - url: config.url, - token: auth.token, - strictSSL: config.strictSSL, - timeout: config.timeout - }); + const watcher = auth.token + ? new TokenWatcherClient({ + url: config.url, + lapiVersion: config.lapiVersion, + token: auth.token, + strictSSL: config.strictSSL, + timeout: config.timeout + }) + : undefined; - let loginPromise: Promise | undefined; - const ensureReady = async (): Promise => { - loginPromise ??= watcher.login(); - - try { - await loginPromise; - } catch (error) { - loginPromise = undefined; - throw error; - } - }; + const readiness: ClientReadiness = {}; + const ensureReady = createReadiness(watcher, bouncer, readiness, createAuthErrorMapper(watcher, bouncer)); return { - mode: 'watcher', - capabilities: { - read: true, - write: true, - allowlists: true - }, + mode: watcher ? 'watcher' : 'bouncer', + capabilities: buildCapabilities(watcher, bouncer), watcher, - allowlists: createAllowlistsPort(watcher), + bouncer, + allowlists: watcher ? createAllowlistsPort(watcher) : unavailableAllowlistsPort(), config, + readiness, ensureReady, - stop: () => watcher.stop() + stop: () => stopClients(watcher, bouncer) }; } diff --git a/packages/crowdsec-mcp/src/config.ts b/packages/crowdsec-mcp/src/config.ts index afec54fd7..c06d4b9b0 100644 --- a/packages/crowdsec-mcp/src/config.ts +++ b/packages/crowdsec-mcp/src/config.ts @@ -1,4 +1,6 @@ +import { readFileSync } from 'node:fs'; import { parseArgs } from 'node:util'; +import { parseLapiVersion } from 'crowdsec-client'; import { parseDuration, splitList } from './utils.js'; import { NAME, VERSION } from './version.js'; @@ -19,7 +21,14 @@ export interface HttpConfig { export interface Config { url: string; + /** Primary/display mode. Kept for back-compat; gating uses `watcher`/`bouncer`. */ auth: AuthMode; + /** A watcher client is configured (alerts, allowlists, writes). */ + watcher: boolean; + /** A bouncer client is configured (fast decision path). */ + bouncer: boolean; + /** Declared CrowdSec LAPI version, used to resolve capabilities without probing. */ + lapiVersion?: string; apiKey?: string; machineId?: string; password?: string; @@ -44,6 +53,7 @@ const cliOptions = { version: { type: 'boolean', short: 'v' }, url: { type: 'string' }, auth: { type: 'string' }, + 'lapi-version': { type: 'string' }, 'api-key': { type: 'string' }, 'machine-id': { type: 'string' }, password: { type: 'string' }, @@ -116,53 +126,160 @@ function firstDefined(...values: Array): string | undefined return values.find((value) => value !== undefined && value !== ''); } +/** + * Read a secret from a `${NAME}_FILE` environment variable. + * + * Docker and Kubernetes mount secrets as files; the trailing newline written + * by `docker secret` is stripped. Only line endings are removed: leading or + * trailing spaces can be part of a password. Neither the value nor the path + * is ever included in an error message. + */ +function readSecretFile(env: NodeJS.ProcessEnv, name: string): string | undefined { + const fileVariable = `${name}_FILE`; + const path = env[fileVariable]; + if (path === undefined || path === '') { + return undefined; + } + + try { + let content = readFileSync(path, 'utf8'); + while (content.endsWith('\n') || content.endsWith('\r')) { + content = content.slice(0, -1); + } + return content; + } catch { + throw new Error(`${fileVariable} is set but the secret file could not be read`); + } +} + +/** + * Resolve a secret input with a documented precedence: + * command-line flag > environment variable > `${NAME}_FILE`. + */ +function readSecret(values: CliValues, env: NodeJS.ProcessEnv, cliKey: keyof CliValues, name: string): string | undefined { + const fromCli = values[cliKey] as string | undefined; + if (fromCli !== undefined && fromCli !== '') { + return fromCli; + } + + const fromEnv = env[name]; + if (fromEnv !== undefined && fromEnv !== '') { + return fromEnv; + } + + // Only touch the file when the higher-precedence sources are absent: an + // unreadable ${NAME}_FILE must not break a configuration that already + // provides the value directly. + return readSecretFile(env, name); +} + function requireUrl(values: CliValues, env: NodeJS.ProcessEnv): string { const url = firstDefined(values.url as string | undefined, env.CROWDSEC_URL); if (!url) { throw new Error('CROWDSEC_URL (or --url) is required'); } if (!/^https?:\/\//i.test(url)) { - throw new Error(`CROWDSEC_URL must start with http:// or https://, got '${url}'`); + throw new Error(`CROWDSEC_URL must start with http:// or https://, got '${redactedUrl(url)}'`); } return url; } -function resolveAuth( - requestedAuth: string | undefined, - apiKey: string | undefined, - machineId: string | undefined, - password: string | undefined, - passthrough: boolean, - hasTls: boolean -): AuthMode { - if (requestedAuth === 'bouncer' || requestedAuth === 'watcher') { - return requestedAuth; - } - if (requestedAuth !== undefined) { +interface ResolvedCredentials { + auth: AuthMode; + watcher: boolean; + bouncer: boolean; +} + +function assertRequestedAuth(requestedAuth: string | undefined): void { + if (requestedAuth !== undefined && requestedAuth !== 'bouncer' && requestedAuth !== 'watcher') { throw new Error(`CROWDSEC_AUTH must be 'bouncer' or 'watcher', got '${requestedAuth}'`); } - if (apiKey) { - return 'bouncer'; +} + +function resolveRequestedBouncer(hasBouncerCredentials: boolean): ResolvedCredentials { + if (!hasBouncerCredentials) { + throw new Error('bouncer authentication requires CROWDSEC_API_KEY or TLS certificates'); } - if (machineId || password) { - return 'watcher'; + return { auth: 'bouncer', watcher: false, bouncer: true }; +} + +function resolveRequestedWatcher(hasWatcherCredentials: boolean, hasPartialMachine: boolean): ResolvedCredentials { + if (!hasWatcherCredentials) { + if (hasPartialMachine) { + throw new Error('CROWDSEC_MACHINE_ID and CROWDSEC_PASSWORD must be provided together'); + } + throw new Error('watcher authentication requires CROWDSEC_MACHINE_ID and CROWDSEC_PASSWORD (or TLS certificates)'); } - if (passthrough) { - // The env credentials are not used in passthrough mode; keep a valid - // mode for the shared Config shape. - return 'watcher'; + return { auth: 'watcher', watcher: true, bouncer: false }; +} + +function resolveAutoCredentials( + hasMachinePair: boolean, + apiKey: string | undefined, + hasTls: boolean, + hasPartialMachine: boolean +): ResolvedCredentials { + // Without CROWDSEC_AUTH, enable every explicit credential that is present. + // A bouncer key and a watcher machine pair can be supplied together, which + // gives the fast decision path and the richer watcher tools at once. + if (hasMachinePair && apiKey) { + return { auth: 'bouncer', watcher: true, bouncer: true }; + } + if (hasMachinePair) { + return { auth: 'watcher', watcher: true, bouncer: false }; + } + if (apiKey) { + return { auth: 'bouncer', watcher: false, bouncer: true }; } if (hasTls) { // With mutual TLS alone we cannot tell a bouncer certificate from an // agent one, so default to the richer watcher mode. Set // CROWDSEC_AUTH=bouncer when the certificate belongs to a bouncer. - return 'watcher'; + // TLS is deliberately not combined with an API key: the certificate + // could be either kind, so the explicit key wins and no watcher is + // invented. + return { auth: 'watcher', watcher: true, bouncer: false }; } + + if (hasPartialMachine) { + throw new Error('CROWDSEC_MACHINE_ID and CROWDSEC_PASSWORD must be provided together'); + } + throw new Error( 'unable to detect authentication mode: set CROWDSEC_API_KEY, CROWDSEC_MACHINE_ID/CROWDSEC_PASSWORD, TLS certificates, or CROWDSEC_AUTH' ); } +function resolveCredentials( + requestedAuth: string | undefined, + apiKey: string | undefined, + machineId: string | undefined, + password: string | undefined, + passthrough: boolean, + hasTls: boolean +): ResolvedCredentials { + assertRequestedAuth(requestedAuth); + + if (passthrough) { + // Passthrough credentials come from headers on every request. Static + // credentials and CROWDSEC_AUTH are irrelevant, not invalid: keep a + // valid mode for the shared Config shape. + return { auth: 'watcher', watcher: false, bouncer: false }; + } + + const hasMachinePair = Boolean(machineId && password); + const hasPartialMachine = Boolean(machineId) !== Boolean(password); + + if (requestedAuth === 'bouncer') { + return resolveRequestedBouncer(Boolean(apiKey || hasTls)); + } + if (requestedAuth === 'watcher') { + return resolveRequestedWatcher(hasMachinePair || hasTls, hasPartialMachine); + } + + return resolveAutoCredentials(hasMachinePair, apiKey, hasTls, hasPartialMachine); +} + function resolveTls(cert: string | undefined, key: string | undefined, ca: string | undefined): Config['tls'] { const tlsCount = [cert, key, ca].filter(Boolean).length; if (tlsCount !== 0 && tlsCount !== 3) { @@ -171,22 +288,6 @@ function resolveTls(cert: string | undefined, key: string | undefined, ca: strin return tlsCount === 3 ? { cert: cert!, key: key!, ca: ca! } : undefined; } -function validateCredentials( - passthrough: boolean, - auth: AuthMode, - apiKey: string | undefined, - tls: Config['tls'], - machineId: string | undefined, - password: string | undefined -): void { - if (!passthrough && auth === 'bouncer' && !apiKey && !tls) { - throw new Error('bouncer authentication requires CROWDSEC_API_KEY or TLS certificates'); - } - if (!passthrough && auth === 'watcher' && !tls && (!machineId || !password)) { - throw new Error('watcher authentication requires CROWDSEC_MACHINE_ID and CROWDSEC_PASSWORD (or TLS certificates)'); - } -} - function resolveTransport(values: CliValues, env: NodeJS.ProcessEnv, passthrough: boolean): 'stdio' | 'http' { const transport = (firstDefined(values.transport as string | undefined, env.CROWDSEC_MCP_TRANSPORT) ?? 'stdio').toLowerCase(); if (transport !== 'stdio' && transport !== 'http') { @@ -220,9 +321,13 @@ function resolveReadonly(values: CliValues, env: NodeJS.ProcessEnv): boolean { export function loadConfig(values: CliValues, env: NodeJS.ProcessEnv = process.env): Config { const url = requireUrl(values, env); - const apiKey = firstDefined(values['api-key'] as string | undefined, env.CROWDSEC_API_KEY); - const machineId = firstDefined(values['machine-id'] as string | undefined, env.CROWDSEC_MACHINE_ID); - const password = firstDefined(values.password as string | undefined, env.CROWDSEC_PASSWORD); + const lapiVersion = firstDefined(values['lapi-version'] as string | undefined, env.CROWDSEC_LAPI_VERSION); + if (lapiVersion !== undefined && parseLapiVersion(lapiVersion) === null) { + throw new Error(`CROWDSEC_LAPI_VERSION must look like 1.8.2, got '${lapiVersion}'`); + } + const apiKey = readSecret(values, env, 'api-key', 'CROWDSEC_API_KEY'); + const machineId = readSecret(values, env, 'machine-id', 'CROWDSEC_MACHINE_ID'); + const password = readSecret(values, env, 'password', 'CROWDSEC_PASSWORD'); const passthrough = values.passthrough === true || readBoolean(env.CROWDSEC_MCP_PASSTHROUGH, 'CROWDSEC_MCP_PASSTHROUGH', false); const requestedAuth = firstDefined(values.auth as string | undefined, env.CROWDSEC_AUTH)?.toLowerCase(); @@ -232,11 +337,17 @@ export function loadConfig(values: CliValues, env: NodeJS.ProcessEnv = process.e firstDefined(values['tls-key'] as string | undefined, env.CROWDSEC_TLS_KEY), firstDefined(values['tls-ca'] as string | undefined, env.CROWDSEC_TLS_CA) ); - const auth = resolveAuth(requestedAuth, apiKey, machineId, password, passthrough, Boolean(tls)); - validateCredentials(passthrough, auth, apiKey, tls, machineId, password); + if (passthrough && tls) { + // The passthrough context is rebuilt for every request from HTTP + // headers; loading client certificates there would either re-read the + // files on each call or silently drop them. Reject the combination + // instead of accepting it and losing mTLS. + throw new Error('passthrough mode does not support CROWDSEC_TLS_* certificates; terminate mTLS in front of the MCP server'); + } + const credentials = resolveCredentials(requestedAuth, apiKey, machineId, password, passthrough, Boolean(tls)); const transport = resolveTransport(values, env, passthrough); - const httpToken = firstDefined(values['http-token'] as string | undefined, env.CROWDSEC_MCP_HTTP_TOKEN); + const httpToken = readSecret(values, env, 'http-token', 'CROWDSEC_MCP_HTTP_TOKEN'); validateHttpToken(transport, httpToken, passthrough); if (values.readonly === true && values.write === true) { @@ -279,7 +390,10 @@ export function loadConfig(values: CliValues, env: NodeJS.ProcessEnv = process.e return { url, - auth, + auth: credentials.auth, + watcher: credentials.watcher, + bouncer: credentials.bouncer, + lapiVersion, apiKey, machineId, password, @@ -319,14 +433,22 @@ export function isAlertDeleteAvailable(config: Config): boolean { return true; } +function maskUserInfo(value: string): string { + return value.replace(/(\/\/)[^/@\s]+@/g, '$1***:***@').replace(/^[^/@\s:]+:[^/@\s]+@/, '***:***@'); +} + export function redactedUrl(url: string): string { + const masked = maskUserInfo(url); try { - const parsed = new URL(url); + const parsed = new URL(masked); if (parsed.username) parsed.username = '***'; if (parsed.password) parsed.password = '***'; - return parsed.toString(); + return maskUserInfo(parsed.toString()); } catch { - return url; + // An unparseable value can still contain `user:password@`: show only the + // scheme so the error stays useful without echoing the credential. + const scheme = /^([a-z][a-z0-9+.-]*):\/\//i.exec(masked)?.[1]; + return scheme ? `${scheme}://` : masked; } } @@ -335,10 +457,15 @@ export function printHelp(): void { Connection: --url CrowdSec LAPI URL (env: CROWDSEC_URL) - --auth Authentication mode (env: CROWDSEC_AUTH) - --api-key Bouncer API key (env: CROWDSEC_API_KEY) - --machine-id Watcher machine ID (env: CROWDSEC_MACHINE_ID) - --password Watcher password (env: CROWDSEC_PASSWORD) + --auth Restrict to one mode (env: CROWDSEC_AUTH) + Without it, every supplied credential is enabled; + a bouncer key and watcher credentials can coexist. + --lapi-version CrowdSec LAPI version, e.g. 1.8.2 (env: CROWDSEC_LAPI_VERSION) + Resolves capabilities locally instead of probing or + discovering them from failed requests. + --api-key Bouncer API key (env: CROWDSEC_API_KEY or CROWDSEC_API_KEY_FILE) + --machine-id Watcher machine ID (env: CROWDSEC_MACHINE_ID or CROWDSEC_MACHINE_ID_FILE) + --password Watcher password (env: CROWDSEC_PASSWORD or CROWDSEC_PASSWORD_FILE) --tls-cert Client certificate (env: CROWDSEC_TLS_CERT) --tls-key Client key (env: CROWDSEC_TLS_KEY) --tls-ca CA certificate (env: CROWDSEC_TLS_CA) @@ -349,7 +476,7 @@ MCP: --transport Transport, default stdio (env: CROWDSEC_MCP_TRANSPORT) --http-host HTTP host, default 127.0.0.1 --http-port HTTP port, default 3939 - --http-token HTTP bearer token (required for HTTP) + --http-token HTTP bearer token (env: CROWDSEC_MCP_HTTP_TOKEN or CROWDSEC_MCP_HTTP_TOKEN_FILE) --readonly Force read-only mode (default) --write Enable write tools --passthrough Use per-request LAPI credentials (HTTP only) diff --git a/packages/crowdsec-mcp/src/docs.ts b/packages/crowdsec-mcp/src/docs.ts index feec1a5d8..0ab3f1d49 100644 --- a/packages/crowdsec-mcp/src/docs.ts +++ b/packages/crowdsec-mcp/src/docs.ts @@ -24,17 +24,30 @@ export interface DocResource { render: (ctx: AppContext) => string; } +function watcherLabel(ctx: AppContext): string { + if (ctx.config.machineId) { + return `watcher with machine ${ctx.config.machineId} (machine credentials)`; + } + if (ctx.config.tls) { + return 'watcher (mTLS certificates)'; + } + return 'watcher (token)'; +} + function authenticationSummary(ctx: AppContext): string { - if (ctx.mode === 'watcher') { - const machine = ctx.config.machineId ? ` with machine ${ctx.config.machineId}` : ''; - return `watcher${machine} (machine credentials): alerts, decisions, allowlists and, unless read-only, write tools are available.`; + if (ctx.capabilities.alerts && ctx.capabilities.decisionsFast) { + return `${watcherLabel(ctx)} and bouncer (API key): alerts, allowlists, writes and the fast decision path are available.`; + } + + if (ctx.capabilities.alerts) { + return `${watcherLabel(ctx)}: alerts, decisions, allowlists and, unless read-only, write tools are available.`; } return 'bouncer (API key): only active decisions are visible. Alerts, allowlists and write tools are unavailable.'; } function writeSummary(ctx: AppContext): string { - if (ctx.mode === 'bouncer') { + if (!ctx.capabilities.write) { return 'bouncer mode (read-only): no write tools (ban_ip and unban_ip require watcher credentials).'; } @@ -46,13 +59,21 @@ function writeSummary(ctx: AppContext): string { function canDeleteAlerts(ctx: AppContext): boolean { // delete_alerts is a write tool: it also requires watcher credentials and // read-only mode disables every write tool. - return ctx.mode === 'watcher' && !ctx.config.readonly && isAlertDeleteAvailable(ctx.config); + return ctx.capabilities.alerts && !ctx.config.readonly && isAlertDeleteAvailable(ctx.config); +} + +function decisionPathSummary(ctx: AppContext): string { + return ctx.capabilities.decisionsFast + ? 'bouncer (/v1/decisions): fast path' + : 'watcher (alert scan): add CROWDSEC_API_KEY for the ~60x faster bouncer path'; } function availabilityLines(ctx: AppContext): string[] { return [ - `- Alerts (list_alerts, get_alert): ${ctx.mode === 'watcher' ? 'available' : 'unavailable (watcher credentials required)'}.`, - `- Decisions (list_decisions): available. get_decision: ${ctx.mode === 'watcher' ? 'available' : 'unavailable (watcher credentials required)'}.`, + `- Alerts (list_alerts, get_alert): ${ctx.capabilities.alerts ? 'available' : 'unavailable (watcher credentials required)'}.`, + `- Decisions (list_decisions): ${ctx.capabilities.decisions ? 'available' : 'unavailable'}. get_decision: ${ + ctx.capabilities.decisions ? 'available' : 'unavailable' + }. Path: ${decisionPathSummary(ctx)}.`, `- Allowlists: ${ctx.capabilities.allowlists ? 'available' : 'unavailable in this mode'}.`, `- delete_alerts: ${canDeleteAlerts(ctx) ? 'available (destructive, only works on the LAPI host)' : 'hidden'}.` ]; @@ -66,9 +87,9 @@ function workingRules(ctx: AppContext): string[] { add('Call crowdsec_status when the connection, mode or active tools are unclear.'); - if (ctx.mode === 'bouncer') { + if (!ctx.capabilities.alerts) { add( - 'Only active decisions are visible: use list_decisions. get_decision, alerts and allowlists need watcher credentials: say so instead of calling them.' + 'Only active decisions are visible: use list_decisions and get_decision. Alerts and allowlists need watcher credentials: say so instead of calling them.' ); add('A decision origin of CAPI comes from the community blocklist and is not necessarily local to this engine.'); add('Never invent decision IDs. If a lookup returns nothing, say so instead of guessing.'); @@ -77,7 +98,9 @@ function workingRules(ctx: AppContext): string[] { add('Investigate before acting: list_alerts -> get_alert -> list_decisions/get_decision for the same source.'); - if (ctx.config.readonly) { + if (!ctx.capabilities.write) { + add('Write tools are hidden: analyse and recommend, but never claim that a ban or unban was applied.'); + } else if (ctx.config.readonly) { add('Write tools are hidden: analyse and recommend, but never claim that a ban or unban was applied.'); } else { const destructive = canDeleteAlerts(ctx) ? 'ban_ip, unban_ip and delete_alerts' : 'ban_ip and unban_ip'; @@ -99,7 +122,7 @@ function workingRules(ctx: AppContext): string[] { export function buildInstructions(ctx: AppContext): string { const limits = - ctx.mode === 'watcher' && !ctx.config.readonly + ctx.capabilities.write && !ctx.config.readonly ? [`Limits: bans longer than ${ctx.config.maxBanDuration} are refused unless force=true.`] : []; @@ -112,6 +135,7 @@ export function buildInstructions(ctx: AppContext): string { '', `Authentication: ${authenticationSummary(ctx)}`, `Write access: ${writeSummary(ctx)}`, + `Timeout: ${ctx.config.timeout} ms (CROWDSEC_TIMEOUT, maximum 600000). The LAPI builds the whole response before sending it, so this is a total time-to-first-byte budget.`, ...limits, ...availabilityLines(ctx), '', @@ -151,7 +175,7 @@ const OVERVIEW = (ctx: AppContext): string => '## What this MCP server exposes', '', '- Alerts: detection history (list_alerts, get_alert).', - '- Decisions: active remediation (list_decisions; get_decision, ban_ip and unban_ip require watcher credentials).', + '- Decisions: active remediation (list_decisions and get_decision; ban_ip and unban_ip require watcher credentials).', '- Allowlists: exemptions that prevent remediation (list_allowlists, get_allowlist, check_allowlist).', '- crowdsec_status: connection mode, capabilities and limits.', '', @@ -206,9 +230,33 @@ const CONCEPTS = (): string => '', '## Authentication: bouncer vs watcher', '', - '- bouncer: API key. Can only read decisions, and only those the bouncer is allowed to see.', + '- bouncer: API key. Can only read decisions, and only those the bouncer is allowed to see. The /v1/decisions', + ' endpoint is much faster than scanning alerts.', '- watcher: machine ID and password (or TLS certificates). Full access to alerts and decisions, plus allowlists', ' and write operations depending on the server configuration.', + '- Both can be configured together: the bouncer key serves list_decisions/get_decision while the watcher handles', + ' alerts, allowlists and writes. `since`/`until` on list_decisions use the watcher path because they filter alerts.', + '- With both credentials, list_decisions uses the bouncer by default: `scenario` is a substring match there (exact on', + ' the watcher path), and the active decision set is fetched then truncated client-side. `scope`, `since` and `until`', + ' force the watcher path because `/v1/decisions` ignores `scope` on LAPI 1.3.3-1.6.0.', + '', + '## Filter semantics (validated on CrowdSec 1.8.1)', + '', + '- `contains`: true means "the decision range contains the value"; false means "the decision range is contained', + ' within the value". The LAPI default is true. list_decisions defaults to false so `ip=` means "decisions', + ' inside this CIDR"; list_alerts exposes the same flag. The parameter only exists from LAPI 1.0.3 and is only', + ' sent when ip/range is provided.', + '- On alerts, `ip` and `range` match the decisions attached to the alert, not the alert source (same for', + ' list_alerts and delete_alerts). Alerts without decisions never match these filters; use `scope`+`value` to', + ' filter the alert source. delete_alerts uses contains=false, so an exact IP does not match a containing Range decision.', + '- `kind` is the alert origin (case-sensitive: `waf`, `crowdsec`, `bot-detection`, ...). `origin` is the origin of', + ' the decisions attached to the alert. Unknown values return an empty list, not an error.', + '- `has_active_decision=false` means "alerts with no decisions at all", not "do not filter".', + '- Simulated decisions are recorded but not enforced. list_decisions includes them by default (`no_simulated=false`);', + ' the bouncer endpoint excludes them unless `simulated=true` is sent and does not return the field.', + '- `unban_ip(ip=...)` removes decisions contained at/below the IP; a Range decision containing the IP is kept.', + ' Use `range` to remove decisions inside a CIDR. Non-IP scopes use the LAPI `scopes` filter.', + '- `delete_alerts(origin=...)` filters the decision origin, not the alert kind.', '', '## Upstream documentation', '', @@ -218,18 +266,21 @@ const CONCEPTS = (): string => ].join('\n'); function triageModeLines(ctx: AppContext): string[] { - if (ctx.mode === 'bouncer') { + if (!ctx.capabilities.alerts) { return [ '## Mode caveats', '', 'This server runs in bouncer mode: alerts and allowlists are unavailable, only active decisions can be read.', - 'Work from list_decisions, and say when get_decision, alerts or allowlists would need watcher credentials.' + 'Work from list_decisions, and say when alerts or allowlists would need watcher credentials.' ]; } - const lines = ['## Mode caveats', '', 'This server runs in watcher mode: alerts, decisions and allowlists are available.']; + const line = ctx.capabilities.decisionsFast + ? 'This server runs in watcher mode with a bouncer key: alerts, decisions, allowlists and the fast decision path are available.' + : 'This server runs in watcher mode: alerts, decisions and allowlists are available.'; + const lines = ['## Mode caveats', '', line]; - if (ctx.config.readonly) { + if (!ctx.capabilities.write || ctx.config.readonly) { lines.push('Write tools are disabled (read-only): analyse and recommend, but do not claim to have banned or unbanned anything.'); } else { lines.push('Write tools are enabled: always get confirmation before ban_ip or unban_ip.'); @@ -247,11 +298,14 @@ const TRIAGE = (ctx: AppContext): string => '## 1. Look at what fired', '', 'Use list_alerts to see the detection history. Useful filters: since/until, ip or range (CIDR containment),', - 'scenario, origin, kind, has_active_decision and type. Then use get_alert for events and metadata of one alert.', + 'scenario, origin, kind, has_active_decision and type. Note that ip/range match the decisions attached to the', + 'alert, not the alert source: alerts without decisions are invisible to those filters, so use scope+value to', + 'filter the source. kind is case-sensitive; origin is the decision origin. Then use get_alert for events and', + 'metadata of one alert.', '', '## 2. Check the current remediation', '', - 'Use list_decisions with the same ip/range to see what is already blocked, and get_decision (watcher only) for context.', + 'Use list_decisions with the same ip/range to see what is already blocked, and get_decision for context.', 'An already active ban is often enough: avoid stacking duplicate decisions.', '', '## 3. Decide', @@ -267,6 +321,7 @@ const TRIAGE = (ctx: AppContext): string => '- ban_ip refuses allowlisted targets unless force=true.', '- Deleting an alert also deletes its active decisions (LAPI cascade); do not unban them afterwards.', '- delete_alerts is destructive and only works when this server runs on the LAPI host.', + '- unban_ip(ip=...) does not remove a Range decision that contains the IP; use unban_ip(range=...) for that.', '', ...triageModeLines(ctx), '', diff --git a/packages/crowdsec-mcp/src/format/alerts.ts b/packages/crowdsec-mcp/src/format/alerts.ts index 741fa8688..344645e2f 100644 --- a/packages/crowdsec-mcp/src/format/alerts.ts +++ b/packages/crowdsec-mcp/src/format/alerts.ts @@ -96,7 +96,11 @@ function formatDecisionRow(decision: APITypes.Decision): string[] { const duration = decision.duration ?? '-'; const expiryInfo = resolveDecisionExpiry(decision); const until = formatDecisionExpiry(expiryInfo); - const simulated = decision.simulated === true ? 'yes' : 'no'; + // Older LAPIs may omit the field: report it as unknown, not as "no". + let simulated = '-'; + if (decision.simulated !== undefined) { + simulated = decision.simulated ? 'yes' : 'no'; + } return [ escapeCell(decision.id ?? '-'), diff --git a/packages/crowdsec-mcp/src/format/allowlists.ts b/packages/crowdsec-mcp/src/format/allowlists.ts index 9160038bc..5381feb67 100644 --- a/packages/crowdsec-mcp/src/format/allowlists.ts +++ b/packages/crowdsec-mcp/src/format/allowlists.ts @@ -2,7 +2,7 @@ import type { APITypes } from 'crowdsec-client'; import { isValidCidr } from '../utils.js'; import { escapeCell, markdownTable, formatDate, expiry, truncateRows, moreHint, bullets, plural } from './common.js'; -export function formatAllowlistList(allowlists: APITypes.GetAllowlistsResponse, maxResults: number): string { +export function formatAllowlistList(allowlists: APITypes.GetAllowlistsResponse, maxResults: number, withContent = true): string { const { rows, hidden } = truncateRows(allowlists, maxResults); const tableRows = rows.map((al) => [ @@ -11,7 +11,7 @@ export function formatAllowlistList(allowlists: APITypes.GetAllowlistsResponse, escapeCell(formatDate(al.created_at)), escapeCell(formatDate(al.updated_at)), escapeCell(al.console_managed ? 'yes' : 'no'), - escapeCell(al.items?.length ?? 0) + escapeCell(withContent && Array.isArray(al.items) ? al.items.length : '-') ]); const header = 'Name | Description | Created at | Updated at | Managed by Console | Size'; diff --git a/packages/crowdsec-mcp/src/format/decisions.ts b/packages/crowdsec-mcp/src/format/decisions.ts index d1ede9b8e..443b71958 100644 --- a/packages/crowdsec-mcp/src/format/decisions.ts +++ b/packages/crowdsec-mcp/src/format/decisions.ts @@ -9,11 +9,19 @@ export interface DecisionRow { origin: string; scenario: string; expires?: string; - simulated: boolean; + simulated?: boolean; alertId?: number; decisionId?: number; } +/** `-` when the LAPI does not expose the field, instead of claiming `no`. */ +function simulatedLabel(simulated: boolean | undefined): string { + if (simulated === undefined) { + return '-'; + } + return simulated ? 'yes' : 'no'; +} + function decisionKey(decision: APITypes.Decision): string { return decision.id !== undefined ? `id:${decision.id}` @@ -49,7 +57,7 @@ function collectDecisionRows(alerts: APITypes.GetAlertsResponse, now: number): D origin: decision.origin, scenario: decision.scenario, expires: expiryInfo.expires, - simulated: decision.simulated ?? false, + simulated: decision.simulated, alertId: alert.id, decisionId: decision.id }); @@ -72,7 +80,7 @@ export function formatDecisionList(alerts: APITypes.GetAlertsResponse, maxResult escapeCell(r.origin), escapeCell(r.scenario), escapeCell(expiry(r.expires)), - escapeCell(r.simulated ? 'yes' : 'no'), + escapeCell(simulatedLabel(r.simulated)), escapeCell(r.alertId ?? '-'), escapeCell(r.decisionId ?? '-') ]) @@ -116,7 +124,7 @@ export function formatBouncerDecisionList(decisions: APITypes.GetDecisionsRespon escapeCell(formatOrigin(d.origin)), escapeCell(d.scenario), escapeCell(expiry(expires)), - escapeCell(d.simulated ? 'yes' : 'no') + escapeCell(simulatedLabel(d.simulated)) ]; }) ); @@ -133,13 +141,13 @@ export function formatDecisionDetail(decision: APITypes.Decision, alert?: APITyp `### Decision #${decision.id ?? '-'}`, '', `- **Type:** ${decision.type ?? '-'}`, - `- **Scope:** ${decision.scope ?? '-'}`, + `- **Scope:** ${decision.scope ? normalizeScope(decision.scope) : '-'}`, `- **Value:** ${decision.value ?? '-'}`, - `- **Origin:** ${decision.origin ?? '-'}`, + `- **Origin:** ${formatOrigin(decision.origin) ?? '-'}`, `- **Scenario:** ${decision.scenario ?? '-'}`, `- **Remaining:** ${decision.duration ?? '-'}`, `- **Expires:** ${expires}`, - `- **Simulated:** ${decision.simulated ? 'yes' : 'no'}` + `- **Simulated:** ${simulatedLabel(decision.simulated)}` ]; if (alert) { diff --git a/packages/crowdsec-mcp/src/pkg.ts b/packages/crowdsec-mcp/src/pkg.ts index 09290be98..7366dc3ab 100644 --- a/packages/crowdsec-mcp/src/pkg.ts +++ b/packages/crowdsec-mcp/src/pkg.ts @@ -1 +1 @@ -export const pkg = { name: 'crowdsec-mcp', version: '0.0.6' }; +export const pkg = { name: 'crowdsec-mcp', version: '0.1.0' }; diff --git a/packages/crowdsec-mcp/src/prompts.ts b/packages/crowdsec-mcp/src/prompts.ts index a3e065649..7ada78cf8 100644 --- a/packages/crowdsec-mcp/src/prompts.ts +++ b/packages/crowdsec-mcp/src/prompts.ts @@ -8,12 +8,12 @@ export interface CrowdSecPrompt { name: string; title: string; description: string; - requires?: Array<'watcher'>; + requires?: Array<'alerts'>; register: (server: McpServer, ctx: AppContext) => void; } export function isPromptAvailable(prompt: CrowdSecPrompt, ctx: AppContext): boolean { - return !prompt.requires?.includes('watcher') || ctx.mode === 'watcher'; + return !prompt.requires?.includes('alerts') || ctx.capabilities.alerts; } function promptResult(description: string, text: string): GetPromptResult { @@ -32,7 +32,7 @@ function promptResult(description: string, text: string): GetPromptResult { } function writeGuardrail(ctx: AppContext): string { - if (ctx.mode === 'bouncer') { + if (!ctx.capabilities.write) { return 'Write tools are unavailable in bouncer mode: report findings and recommendations only.'; } if (ctx.config.readonly) { @@ -123,7 +123,7 @@ function renderTriageAlerts(args: TriageAlertsArgs, ctx: AppContext): string { function renderInvestigateIp(args: InvestigateIpArgs, ctx: AppContext): string { const { ip } = args; - const isBouncer = ctx.mode === 'bouncer'; + const isBouncer = !ctx.capabilities.alerts; let steps: string[]; let summary: string; @@ -187,7 +187,7 @@ export const crowdsecPrompts: CrowdSecPrompt[] = [ name: TriageAlerts.name, title: TriageAlerts.title, description: TriageAlerts.description, - requires: ['watcher'], + requires: ['alerts'], register: (server, ctx) => { server.registerPrompt( TriageAlerts.name, @@ -220,7 +220,7 @@ export const crowdsecPrompts: CrowdSecPrompt[] = [ name: BannedFromCountry.name, title: BannedFromCountry.title, description: BannedFromCountry.description, - requires: ['watcher'], + requires: ['alerts'], register: (server, ctx) => { server.registerPrompt( BannedFromCountry.name, diff --git a/packages/crowdsec-mcp/src/registry.ts b/packages/crowdsec-mcp/src/registry.ts index adb364b4e..b82416c57 100644 --- a/packages/crowdsec-mcp/src/registry.ts +++ b/packages/crowdsec-mcp/src/registry.ts @@ -1,7 +1,7 @@ import debug from 'debug'; import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'; -import type { AppContext, ToolDefinition } from './types.js'; +import type { AppContext, ReadinessRequirement, ToolDefinition } from './types.js'; import { buildInstructions, docResources } from './docs.js'; import { isAlertDeleteAvailable } from './config.js'; import { crowdsecPrompts, isPromptAvailable } from './prompts.js'; @@ -13,7 +13,91 @@ export function textResult(text: string): CallToolResult { return { content: [{ type: 'text', text }] }; } -export function cleanErrorMessage(error: unknown): string { +export interface ErrorMessageOptions { + /** Configured CROWDSEC_TIMEOUT, in milliseconds. */ + timeout?: number; + /** Tool being executed, used to add a contextual hint. */ + toolName?: string; + /** True when a bouncer client is available (fast decision path). */ + hasBouncer?: boolean; +} + +const MAX_TIMEOUT_MS = 600_000; + +function errorChain(error: unknown): unknown[] { + const chain: unknown[] = []; + let current: unknown = error; + + for (let depth = 0; depth < 5 && current !== undefined && current !== null; depth++) { + chain.push(current); + const candidate = current as { exception?: unknown; cause?: unknown }; + current = candidate.exception ?? candidate.cause; + } + + return chain; +} + +function messageOf(item: unknown): string { + if (item instanceof Error) { + return item.message; + } + if (typeof item === 'string') { + return item; + } + return ''; +} + +function timeoutValueMs(error: unknown): number | undefined { + for (const item of errorChain(error)) { + const message = messageOf(item); + const match = /timeout of (\d+)\s*ms exceeded/i.exec(message); + if (match) { + return Number(match[1]); + } + const code = (item as { code?: unknown }).code; + if (code === 'ECONNABORTED' || code === 'ETIMEDOUT') { + return undefined; + } + } + return undefined; +} + +function isTimeoutError(error: unknown): boolean { + for (const item of errorChain(error)) { + const message = messageOf(item); + if (/timeout of \d+\s*ms exceeded/i.test(message)) { + return true; + } + const code = (item as { code?: unknown }).code; + if (code === 'ECONNABORTED' || code === 'ETIMEDOUT') { + return true; + } + } + return false; +} + +function timeoutMessage(error: unknown, options?: ErrorMessageOptions): string { + const timeout = timeoutValueMs(error) ?? options?.timeout; + const configured = timeout ? ` after ${timeout} ms` : ''; + const parts = [ + `CrowdSec LAPI request timed out${configured}.`, + 'The LAPI builds the whole response before sending it, so the timeout behaves like a total time-to-first-byte budget.', + 'Narrow the query (since/until, ip, range, scope+value), lower limit, or set all=false.', + `CROWDSEC_TIMEOUT is in milliseconds (maximum ${MAX_TIMEOUT_MS}).` + ]; + + if (!options?.hasBouncer && (options?.toolName === 'list_decisions' || options?.toolName === 'get_decision')) { + parts.push('Set CROWDSEC_API_KEY (bouncer): the /v1/decisions path is roughly 60x faster than scanning alerts.'); + } + + return parts.join(' '); +} + +export function cleanErrorMessage(error: unknown, options?: ErrorMessageOptions): string { + if (isTimeoutError(error)) { + return timeoutMessage(error, options); + } + const raw = error instanceof Error ? error.message : String(error); let message = raw.split(/\r?\n/, 1)[0].trim(); @@ -39,15 +123,18 @@ export function cleanErrorMessage(error: unknown): string { message = 'Access forbidden from this IP (alert deletion is only allowed from the LAPI host)'; } + // The client redacts its own URLs/logs. Tool errors can still embed a URL + // with userinfo or a token query parameter from a server/proxy message. + message = message.replace(/(\/\/)[^/@\s]+@/g, '$1***:***@').replace(/([?&](?:token|api[_-]?key|password)=)[^&\s]+/gi, '$1[redacted]'); + return message || 'unknown error'; } -export function errorResult(error: unknown): CallToolResult { - const raw = error instanceof Error ? error.message : String(error); +export function errorResult(error: unknown, options?: ErrorMessageOptions): CallToolResult { // Client errors can embed a full stack in their message. Keep only the first // cleaned line so tool output stays actionable and does not leak internals. - const message = cleanErrorMessage(error); - log('tool error: %s', raw); + const message = cleanErrorMessage(error, options); + log('tool error: %s', message); return { content: [{ type: 'text', text: `Error: ${message}` }], isError: true @@ -70,7 +157,11 @@ export function selectTools(tools: ToolDefinition[], ctx: AppContext): ToolDefin return false; } - if (tool.requires?.includes('watcher') && context.mode !== 'watcher') { + if (tool.requires?.includes('alerts') && !context.capabilities.alerts) { + return false; + } + + if (tool.requires?.includes('write') && !context.capabilities.write) { return false; } @@ -85,11 +176,15 @@ export function selectTools(tools: ToolDefinition[], ctx: AppContext): ToolDefin return false; } - if (context.config.tools && !context.config.tools.includes(tool.name)) { + const allowlisted = context.config.tools?.includes(tool.name) ?? false; + // Documented precedence: an explicit allowlist entry wins over the + // denylist, so an operator can re-enable one tool without clearing + // CROWDSEC_MCP_DISABLE_TOOLS. + if (context.config.disableTools.includes(tool.name) && !allowlisted) { return false; } - if (context.config.disableTools.includes(tool.name)) { + if (context.config.tools && !allowlisted) { return false; } @@ -113,11 +208,16 @@ export function createServer(tools: ToolDefinition[], ctx: AppContext): McpServe for (const tool of tools) { const handler = async (input: unknown): Promise => { try { - await ctx.ensureReady(); + const requirement: ReadinessRequirement = tool.client ?? (tool.requires && tool.requires.length > 0 ? 'watcher' : 'none'); + await ctx.ensureReady(requirement); const result = await tool.handler(input ?? {}, ctx); return typeof result === 'string' ? textResult(result) : result; } catch (error) { - return errorResult(error); + return errorResult(error, { + timeout: ctx.config.timeout, + toolName: tool.name, + hasBouncer: ctx.capabilities.decisionsFast + }); } }; diff --git a/packages/crowdsec-mcp/src/tools/alerts.ts b/packages/crowdsec-mcp/src/tools/alerts.ts index 45ecf3121..435d39d92 100644 --- a/packages/crowdsec-mcp/src/tools/alerts.ts +++ b/packages/crowdsec-mcp/src/tools/alerts.ts @@ -8,32 +8,112 @@ import { assertValidDecisionScope, assertValidDecisionType, assertValidScopeValue, + isTotalCidr, isValidCidr, isValidIp, isValidTimeFilter, + mapWithConcurrency, + parseDuration, parsePositiveId, + resolveDecisionExpiry, resolveListWindow, toGoDuration } from '../utils.js'; +const DELETE_CONCURRENCY = 8; + async function deleteAlertIds(ctx: AppContext, ids: number[]): Promise { - const responses = await Promise.all(ids.map((id) => ctx.watcher!.Alerts.deleteById(String(id)))); + const responses = await mapWithConcurrency(ids, DELETE_CONCURRENCY, (id) => ctx.watcher!.Alerts.deleteById(String(id))); return responses.reduce((total, response) => total + Number(response.nbDeleted ?? 0), 0); } +/** + * Re-check the decision-level filters locally before deleting whole alerts. + * The search is expected to apply them, but a LAPI that silently ignores an + * unread filter would otherwise delete alerts outside the requested set. + */ +function alertMatchesDeleteFilters(alert: APITypes.Alert, filters: NormalizedDeleteAlertInput): boolean { + const decisions = alert.decisions ?? []; + const hasDecisionFilter = Boolean(filters.decisionType || filters.origin || filters.scenario || filters.has_active_decision === true); + + // A single decision must satisfy the whole conjunction: an alert with + // `ban`/origin A and `captcha`/origin B must not match `type=ban&origin=B`. + if (hasDecisionFilter) { + const matches = decisions.some((decision) => { + if (filters.decisionType && decision.type?.toLowerCase() !== filters.decisionType.toLowerCase()) { + return false; + } + if (filters.origin && decision.origin?.toLowerCase() !== filters.origin.toLowerCase()) { + return false; + } + if (filters.scenario && decision.scenario?.toLowerCase() !== filters.scenario.toLowerCase()) { + return false; + } + // `duration` is the remaining duration at fetch time (same + // convention as Decision.endAt and the formatters), so do not + // anchor it on alert.created_at. + if (filters.has_active_decision === true && !resolveDecisionExpiry(decision).active) { + return false; + } + return true; + }); + if (!matches) { + return false; + } + } + + if (filters.has_active_decision === false && decisions.length > 0) { + return false; + } + + const createdAt = alert.created_at ? Date.parse(alert.created_at) : Number.NaN; + if (Number.isFinite(createdAt)) { + const now = Date.now(); + if (filters.since && createdAt < now - parseDuration(filters.since) * 1000) { + return false; + } + if (filters.until && createdAt > now - parseDuration(filters.until) * 1000) { + return false; + } + } + + return true; +} + const ListAlertsInput = z .object({ - ip: z.string().optional().describe('IP or CIDR range (CIDR performs containment)'), - range: z.string().optional().describe('CIDR range (containment)'), - scope: z.string().optional().describe('Filter by scope (Ip, Range, Username, etc.)'), - value: z.string().optional().describe('Filter by value (used with scope)'), - scenario: z.string().optional().describe('Filter by scenario name'), - type: z.string().optional().describe('Filter by decision type (ban, captcha, etc.)'), - origin: z.string().optional().describe('Filter by origin (cscli, crowdsec, etc.)'), - kind: z.string().optional().describe('Filter by alert kind (crowdsec, waf, bot-detection, etc.)'), + ip: z + .string() + .optional() + .describe( + 'IP or CIDR range. The LAPI matches alerts through their decisions, so alerts without decisions are never returned; use scope+value to filter the alert source.' + ), + range: z + .string() + .optional() + .describe('CIDR range matched against the decisions attached to alerts. Alerts without decisions never match.'), + scope: z.string().optional().describe('Filter the alert source by scope (Ip, Range, Username, etc.).'), + value: z.string().optional().describe('Filter the alert source by value (used with scope).'), + scenario: z.string().optional().describe('Filter by scenario name.'), + type: z.string().optional().describe('Filter by decision type (ban, captcha, etc.). This filters at the alert level.'), + origin: z.string().optional().describe('Filter by decision origin (cscli, crowdsec, capi, console, ...), not by alert kind.'), + kind: z + .string() + .optional() + .describe('Filter by alert kind (crowdsec, waf, bot-detection, cscli, ...). The match is case-sensitive.'), + contains: z + .boolean() + .optional() + .default(false) + .describe( + 'Only with ip/range: false (default) matches alerts whose decisions are contained within the value; true matches alerts whose decisions contain the value.' + ), since: z.string().optional().describe('Filter alerts newer than this duration (e.g., 4h, 30d, 3650d)'), until: z.string().optional().describe('Filter alerts older than this duration (e.g., 4h, 30d, 3650d)'), - has_active_decision: z.boolean().optional().describe('Only return alerts with active (non-expired) decisions'), + has_active_decision: z + .boolean() + .optional() + .describe('true: alerts with at least one active decision; false: alerts with no decisions at all.'), all: z.boolean().optional().describe('Return all results (ignore limit)'), limit: z.number().int().positive().optional().describe('Maximum number of results to return') }) @@ -48,16 +128,25 @@ const GetAlertInput = z const DeleteAlertsInput = z .object({ id: z.union([z.string(), z.number()]).optional().describe('Delete a specific alert by ID'), - ip: z.string().optional().describe('IP or CIDR range (CIDR performs containment)'), - range: z.string().optional().describe('CIDR range (containment)'), - scope: z.string().optional().describe('Filter by scope (Ip, Range, Username, etc.)'), - value: z.string().optional().describe('Filter by value (used with scope)'), - scenario: z.string().optional().describe('Filter by scenario name'), - type: z.string().optional().describe('Filter by decision type (ban, captcha, throttle)'), - origin: z.string().optional().describe('Filter by alert source/origin (cscli, crowdsec, etc.)'), + ip: z + .string() + .optional() + .describe('IP or CIDR range matched through the alerts decisions; alerts without decisions are never matched.'), + range: z + .string() + .optional() + .describe('CIDR range matched through the alerts decisions; alerts without decisions are never matched.'), + scope: z.string().optional().describe('Filter the alert source by scope (Ip, Range, Username, etc.).'), + value: z.string().optional().describe('Filter the alert source by value (used with scope).'), + scenario: z.string().optional().describe('Filter by scenario name.'), + type: z.string().optional().describe('Filter by decision type (ban, captcha, throttle). This filters at the alert level.'), + origin: z.string().optional().describe('Filter by decision origin (cscli, crowdsec, capi, console, ...), not by alert kind.'), since: z.string().optional().describe('Filter alerts newer than this duration (e.g., 4h, 30d)'), until: z.string().optional().describe('Filter alerts older than this duration (e.g., 4h, 30d)'), - has_active_decision: z.boolean().optional().describe('Only delete alerts with active decisions'), + has_active_decision: z + .boolean() + .optional() + .describe('true: alerts with at least one active decision; false: alerts with no decisions at all.'), all: z.boolean().optional().describe('Delete all matching alerts (requires confirm=true)'), confirm: z.boolean().optional().describe('Confirm deletion when using all=true or broad filters') }) @@ -119,15 +208,7 @@ function assertDeleteTargets(input: DeleteAlertInput): void { } } -function normalizeDeleteInput(input: DeleteAlertInput): NormalizedDeleteAlertInput { - validateDeleteTimes(input.since, input.until); - const decisionType = input.type ? assertValidDecisionType(input.type) : undefined; - - if (input.all === true) { - assertAllDelete(input, decisionType); - } - assertDeleteTargets(input); - +function normalizeScopeValue(input: DeleteAlertInput): { normalizedScope?: string; normalizedValue?: string } { if (input.scope && !input.value) { throw new Error('scope and value must be provided together for delete_alerts'); } @@ -135,6 +216,10 @@ function normalizeDeleteInput(input: DeleteAlertInput): NormalizedDeleteAlertInp const normalizedScope = input.scope ? assertValidDecisionScope(input.scope) : undefined; const normalizedValue = normalizedScope && input.value ? assertValidScopeValue(normalizedScope, input.value) : input.value; + return { normalizedScope, normalizedValue }; +} + +function assertDeleteCombination(input: DeleteAlertInput, decisionType?: string): void { if (input.id !== undefined && hasDeleteFilters(input, decisionType)) { throw new Error('Cannot combine id with filters or all=true'); } @@ -143,13 +228,41 @@ function normalizeDeleteInput(input: DeleteAlertInput): NormalizedDeleteAlertInp 'At least one filter (ip, range, scope, value, scenario, origin, type, since, until, has_active_decision) or all=true is required' ); } +} + +function hasNarrowDeleteTarget(input: DeleteAlertInput, normalizedScope: string | undefined, normalizedValue: string | undefined): boolean { + // A /0 CIDR is not a narrow target: it covers everything, so it must go + // through the same confirm=true gate as a broad filter or all=true. + const totalScopeValue = normalizedScope === 'Range' && normalizedValue !== undefined && isTotalCidr(normalizedValue); - const hasNarrowTarget = Boolean(input.ip || input.range || (normalizedScope && normalizedValue)); - if (input.id === undefined && !hasNarrowTarget && input.confirm !== true) { + return Boolean( + (input.ip && !isTotalCidr(input.ip)) || + (input.range && !isTotalCidr(input.range)) || + (normalizedScope && normalizedValue && !totalScopeValue) + ); +} + +function assertNarrowDeleteTarget(input: DeleteAlertInput, normalizedScope: string | undefined, normalizedValue: string | undefined): void { + if (input.id === undefined && !hasNarrowDeleteTarget(input, normalizedScope, normalizedValue) && input.confirm !== true) { throw new Error( 'Deleting alerts filtered only by scenario, origin, type, time or has_active_decision requires confirm=true; add ip, range, or scope+value to narrow the target' ); } +} + +function normalizeDeleteInput(input: DeleteAlertInput): NormalizedDeleteAlertInput { + validateDeleteTimes(input.since, input.until); + const decisionType = input.type ? assertValidDecisionType(input.type) : undefined; + + if (input.all === true) { + assertAllDelete(input, decisionType); + } + assertDeleteTargets(input); + + const { normalizedScope, normalizedValue } = normalizeScopeValue(input); + + assertDeleteCombination(input, decisionType); + assertNarrowDeleteTarget(input, normalizedScope, normalizedValue); return { ...input, decisionType, normalizedScope, normalizedValue }; } @@ -179,11 +292,14 @@ async function deleteAlertsById(ctx: AppContext, id: string | number): Promise { +async function deleteAlertsByCidr(ctx: AppContext, filters: NormalizedDeleteAlertInput): Promise { // The delete endpoint matches exact filter values; search first so alerts - // whose source IP is contained in the range are also removed. + // whose decisions are contained in the range are also removed. Validated on + // LAPI 1.8.1: alert ip/range filters match the decisions attached to the + // alert, not the alert source. const query: APITypes.SearchAlertsQuery = { - ip: cidr, + ip: filters.ip, + range: filters.range, scope: filters.normalizedScope, value: filters.normalizedValue, scenario: filters.scenario, @@ -199,13 +315,34 @@ async function deleteAlertsByCidr(ctx: AppContext, filters: NormalizedDeleteAler return deleteAlertsByIds( ctx, - alerts.map((alert) => alert.id).filter((id): id is number => typeof id === 'number') + alerts + .filter((alert) => alertMatchesDeleteFilters(alert, filters)) + .map((alert) => alert.id) + .filter((id): id is number => typeof id === 'number') ); } +/** + * True when the LAPI rejected a filter parameter on the DELETE endpoint. + * Older releases reuse the alert filter for search but not for delete. + */ +function isUnknownFilterError(error: unknown, parameter: string): boolean { + const code = (error as { code?: unknown } | undefined)?.code; + if (code !== 500 && code !== 400) { + return false; + } + + const message = cleanErrorMessage(error); + if (!new RegExp(String.raw`\b${parameter}\b`, 'i').test(message)) { + return false; + } + + return /(doesn'?t exist|unknown|invalid)[\s\S]{0,60}filter|filter[\s\S]{0,60}(doesn'?t exist|unknown|invalid)/i.test(message); +} + async function deleteAlertsBySearch(ctx: AppContext, filters: NormalizedDeleteAlertInput): Promise { - // Keep the search path for LAPI versions that do not accept `decision_type` - // on the DELETE endpoint. + // Fallback for LAPIs that accept `decision_type` on the search filter but + // not on the DELETE endpoint: search first, then delete by id. const query: APITypes.SearchAlertsQuery = { ip: filters.ip, range: filters.range, @@ -216,7 +353,7 @@ async function deleteAlertsBySearch(ctx: AppContext, filters: NormalizedDeleteAl decision_type: filters.decisionType, since: filters.since ? toGoDuration(filters.since) : undefined, until: filters.until ? toGoDuration(filters.until) : undefined, - contains: false, + ...(filters.ip || filters.range ? { contains: false } : {}), has_active_decision: filters.has_active_decision, limit: 0 }; @@ -224,11 +361,19 @@ async function deleteAlertsBySearch(ctx: AppContext, filters: NormalizedDeleteAl return deleteAlertsByIds( ctx, - alerts.map((alert) => alert.id).filter((id): id is number => typeof id === 'number') + alerts + .filter((alert) => alertMatchesDeleteFilters(alert, filters)) + .map((alert) => alert.id) + .filter((id): id is number => typeof id === 'number') ); } function buildDeleteQuery(filters: NormalizedDeleteAlertInput): APITypes.DeleteAlertsQuery { + // Validated on CrowdSec 1.8.1: DeleteAlertWithFilter reuses the alert + // filter. `alert_source` is rejected ("filter parameter 'alert_source' is + // unknown"), while `origin`, `kind`, `contains` and `decision_type` are + // accepted (`kind` is not exposed by this tool). `origin` filters the + // origin of the decisions attached to the alert, not the alert kind. return { ip: filters.ip, scope: filters.normalizedScope, @@ -236,8 +381,13 @@ function buildDeleteQuery(filters: NormalizedDeleteAlertInput): APITypes.DeleteA scenario: filters.scenario, since: filters.since ? toGoDuration(filters.since) : undefined, until: filters.until ? toGoDuration(filters.until) : undefined, + // `contains` only exists from LAPI 1.0.3 and only matters with + // ip/range. Without it, deleting an exact IP would also match Range + // decisions that contain the IP. + ...(filters.ip || filters.range ? { contains: false } : {}), + decision_type: filters.decisionType, has_active_decision: filters.has_active_decision, - alert_source: filters.origin + origin: filters.origin }; } @@ -260,13 +410,13 @@ export const alertTools: ToolDefinition[] = [ 'List alerts from CrowdSec with optional filters. Returns a table with ID, scope, value, reason, country, AS, decisions, creation time, and kind.', inputSchema: ListAlertsInput, kind: 'read', - requires: ['watcher'], + requires: ['alerts'], annotations: { readOnlyHint: true, idempotentHint: true }, handler: async (input, ctx) => { - const { ip, range, scope, value, scenario, type, origin, kind, since, until, has_active_decision, all, limit } = + const { ip, range, scope, value, scenario, type, origin, kind, contains, since, until, has_active_decision, all, limit } = ListAlertsInput.parse(input); if (ip && !isValidIp(ip) && !isValidCidr(ip)) { @@ -286,6 +436,10 @@ export const alertTools: ToolDefinition[] = [ } const window = resolveListWindow(limit, all === true, ctx.config.maxResults); + // Validated on CrowdSec 1.8.1: `ip`/`range` match alerts through + // their decisions (alerts without decisions never match), `kind` is + // case-sensitive, `origin` is the decision origin, and + // `has_active_decision=false` means "no decisions at all". const query: APITypes.SearchAlertsQuery = { ip, range, @@ -297,7 +451,12 @@ export const alertTools: ToolDefinition[] = [ kind, since: since ? toGoDuration(since) : undefined, until: until ? toGoDuration(until) : undefined, - contains: false, + // Validated on CrowdSec 1.8.1: `contains` defaults to true; the + // tool defaults to false so `ip=` means "decisions inside + // this CIDR". The option lets callers match decisions that + // contain the value instead. Do not send it without ip/range: + // the parameter does not exist before LAPI 1.0.3. + ...(ip || range ? { contains } : {}), has_active_decision, limit: window.fetchLimit }; @@ -313,7 +472,7 @@ export const alertTools: ToolDefinition[] = [ description: 'Get detailed information about a specific alert including decisions, meta, and events.', inputSchema: GetAlertInput, kind: 'read', - requires: ['watcher'], + requires: ['alerts'], annotations: { readOnlyHint: true, idempotentHint: true @@ -341,7 +500,7 @@ export const alertTools: ToolDefinition[] = [ 'Delete alerts by ID or filters. Requires at least one filter or all=true with confirm=true; all=true cannot be combined with filters. Broad filters (scenario, origin, type, time, has_active_decision alone) also require confirm=true; narrow with ip, range, or scope+value. ip and range accept a CIDR and perform containment. CrowdSec only allows alert deletion from the LAPI host; remote watchers receive 403.', inputSchema: DeleteAlertsInput, kind: 'write', - requires: ['watcher'], + requires: ['alerts'], feature: 'alert-delete', annotations: { readOnlyHint: false, @@ -360,10 +519,20 @@ export const alertTools: ToolDefinition[] = [ const cidr = filters.range ?? (filters.ip && isValidCidr(filters.ip) ? filters.ip : undefined); if (cidr) { - return deleteAlertsByCidr(ctx, filters, cidr); + return deleteAlertsByCidr(ctx, filters); } + if (filters.decisionType) { - return deleteAlertsBySearch(ctx, filters); + try { + return await deleteAlertsDirect(ctx, filters); + } catch (error) { + // Older LAPIs reject `decision_type` on DELETE; fall back to + // the search + delete-by-id path that has always worked. + if (!isUnknownFilterError(error, 'decision_type')) { + throw error; + } + return deleteAlertsBySearch(ctx, filters); + } } return deleteAlertsDirect(ctx, filters); diff --git a/packages/crowdsec-mcp/src/tools/allowlists.ts b/packages/crowdsec-mcp/src/tools/allowlists.ts index 31734109e..34488d66e 100644 --- a/packages/crowdsec-mcp/src/tools/allowlists.ts +++ b/packages/crowdsec-mcp/src/tools/allowlists.ts @@ -6,7 +6,11 @@ import { isValidCidr, isValidIp } from '../utils.js'; const ListAllowlistsInput = z .object({ - limit: z.number().int().positive().optional().describe('Maximum number of allowlists to display') + limit: z.number().int().positive().optional().describe('Maximum number of allowlists to display'), + with_content: z + .boolean() + .default(true) + .describe('Download allowlist items to report their size. Set false to avoid transferring every item (size shows as -).') }) .strict(); @@ -36,19 +40,19 @@ export const allowlistTools: ToolDefinition[] = [ name: 'list_allowlists', title: 'List allowlists', description: - 'List all allowlists with their name, description, creation/update dates, console management status, and item count. Mirrors `cscli allowlists list`.', + 'List all allowlists with their name, description, creation/update dates, console management status, and item count. Mirrors `cscli allowlists list`. Set with_content=false to skip item transfer; the size column then shows -.', inputSchema: ListAllowlistsInput, kind: 'read', - requires: ['watcher', 'allowlists'], + requires: ['allowlists'], annotations: { readOnlyHint: true, idempotentHint: true }, handler: async (input, ctx) => { - const { limit } = ListAllowlistsInput.parse(input); - const allowlists = await ctx.allowlists.list(); + const { limit, with_content: withContent } = ListAllowlistsInput.parse(input); + const allowlists = await ctx.allowlists.list(withContent); - return formatAllowlistList(allowlists, limit ?? ctx.config.maxResults); + return formatAllowlistList(allowlists, limit ?? ctx.config.maxResults, withContent); } }, { @@ -57,7 +61,7 @@ export const allowlistTools: ToolDefinition[] = [ description: 'Get detailed information about a specific allowlist including its items. Mirrors `cscli allowlists inspect`.', inputSchema: GetAllowlistInput, kind: 'read', - requires: ['watcher', 'allowlists'], + requires: ['allowlists'], annotations: { readOnlyHint: true, idempotentHint: true @@ -84,7 +88,7 @@ export const allowlistTools: ToolDefinition[] = [ 'Check whether one or more IPs or CIDR ranges match any allowlist entry. A CIDR can match because it contains an allowlisted IP; the output distinguishes CIDR matches from exact IP matches. Provide either a single `value` or an array of `values`.', inputSchema: CheckAllowlistInput, kind: 'read', - requires: ['watcher', 'allowlists'], + requires: ['allowlists'], annotations: { readOnlyHint: true, idempotentHint: true diff --git a/packages/crowdsec-mcp/src/tools/decisions.ts b/packages/crowdsec-mcp/src/tools/decisions.ts index 8ad497fb8..75863178c 100644 --- a/packages/crowdsec-mcp/src/tools/decisions.ts +++ b/packages/crowdsec-mcp/src/tools/decisions.ts @@ -1,4 +1,6 @@ +import debug from 'debug'; import { z } from 'zod'; +import { compareLapiVersions, FeatureNotSupportedError, parseLapiVersion } from 'crowdsec-client'; import type { APITypes } from 'crowdsec-client'; import { assertValidCidr, @@ -9,7 +11,9 @@ import { formatDuration, isValidCidr, isValidIp, + isTotalCidr, isValidTimeFilter, + mapWithConcurrency, normalizeScope, parseDuration, parsePositiveId, @@ -26,47 +30,66 @@ import { import { cleanErrorMessage } from '../registry.js'; import type { AppContext, ToolDefinition } from '../types.js'; -function collectDecisionIds(alerts: APITypes.GetAlertsResponse): number[] { - const ids = new Set(); +const log = debug('crowdsec-mcp:tools:decisions'); + +function collectDecisions(alerts: APITypes.GetAlertsResponse): APITypes.Decision[] { + const decisions = new Map(); for (const alert of alerts) { for (const decision of alert.decisions ?? []) { if (typeof decision.id === 'number') { - ids.add(decision.id); + decisions.set(decision.id, decision); } } } - return [...ids]; + return [...decisions.values()]; } -async function searchActiveDecisionIds(ctx: AppContext, query: APITypes.SearchAlertsQuery): Promise { - // `contains: false` means "decisions contained within the value" and is - // required for CIDR containment; the LAPI defaults to the opposite. - const searchQuery: APITypes.SearchAlertsQuery = { - ...query, - contains: query.contains ?? false, - has_active_decision: true, - limit: 0 - }; - const alerts = await ctx.watcher!.Alerts.search(searchQuery); - return collectDecisionIds(alerts); +const DELETE_CONCURRENCY = 8; + +function isUnknownAlertFilter(error: unknown, parameter: string): boolean { + const code = (error as { code?: unknown } | undefined)?.code; + if (code !== 400 && code !== 500) { + return false; + } + + const message = cleanErrorMessage(error); + if (!new RegExp(String.raw`\b${parameter}\b`, 'i').test(message)) { + return false; + } + + return /(doesn'?t exist|unknown|invalid)[\s\S]{0,60}filter|filter[\s\S]{0,60}(doesn'?t exist|unknown|invalid)/i.test(message); +} + +/** + * The alert `simulated` parameter is not available on every LAPI. When asking + * to include simulated decisions, a rejected filter is retried without it + * (narrower result) instead of failing the tool. A request to exclude them + * (`simulated: false`) is never widened by dropping the filter. + */ +async function searchAlerts(ctx: AppContext, query: APITypes.SearchAlertsQuery): Promise { + try { + return await ctx.watcher!.Alerts.search(query); + } catch (error) { + if (query.simulated !== true || !isUnknownAlertFilter(error, 'simulated')) { + throw error; + } + + const withoutSimulated: APITypes.SearchAlertsQuery = { ...query }; + delete withoutSimulated.simulated; + return ctx.watcher!.Alerts.search(withoutSimulated); + } } async function deleteDecisionIds(ctx: AppContext, ids: number[]): Promise { - const results = await Promise.all(ids.map((id) => ctx.watcher!.Decisions.deleteById(String(id)))); + const results = await mapWithConcurrency(ids, DELETE_CONCURRENCY, (id) => ctx.watcher!.Decisions.deleteById(String(id))); return results.reduce((total, result) => total + Number(result.nbDeleted ?? 0), 0); } async function fetchActiveDecisions(ctx: AppContext): Promise { - const alerts = await ctx.watcher!.Alerts.search({ has_active_decision: true, limit: 0 }); - const decisions = new Map(); - for (const alert of alerts) { - for (const decision of alert.decisions ?? []) { - if (typeof decision.id === 'number') { - decisions.set(decision.id, decision); - } - } - } - return [...decisions.values()]; + // Include simulated decisions: `list_decisions` shows them by default, so + // `all=true` must delete the same set the operator just listed. + const alerts = await searchAlerts(ctx, { has_active_decision: true, simulated: true, limit: 0 }); + return collectDecisions(alerts); } const ListDecisionsInput = z @@ -85,7 +108,11 @@ const ListDecisionsInput = z .optional() .default(false) .describe('false: decisions contained within the value (CIDR containment); true: decisions that contain the value'), - no_simulated: z.boolean().optional().default(false).describe('Exclude simulated decisions'), + no_simulated: z + .boolean() + .optional() + .default(false) + .describe('Exclude simulated decisions (recorded but not enforced). Default false includes them.'), all: z.boolean().optional().default(false).describe('Return all results without limit'), limit: z.number().int().positive().optional().describe('Maximum number of results to return') }) @@ -117,9 +144,17 @@ const GetDecisionInput = z const UnbanIpInput = z .object({ id: z.union([z.string(), z.number()]).optional().describe('Decision ID to delete'), - ip: z.string().optional().describe('Single IP address to filter by (exact match)'), - range: z.string().optional().describe('CIDR value for decisions whose scope is Range (exact match)'), - scope: z.string().optional().describe('Scope to filter by (must be combined with value)'), + ip: z + .string() + .optional() + .describe( + 'Single IP: deletes only decisions contained at/below this IP. A Range decision that contains the IP is kept; use range for containment.' + ), + range: z.string().optional().describe('CIDR range: deletes decisions contained within it (server-side filter).'), + scope: z + .string() + .optional() + .describe('Scope to filter by (must be combined with value). Non-IP scopes use the LAPI scopes filter.'), value: z.string().optional().describe('Value to filter by (used with scope)'), type: z.string().optional().describe('Decision type to filter by (ban, captcha, throttle)'), scenario: z.string().optional().describe('Scenario name to filter by'), @@ -167,12 +202,32 @@ function resolveBanTarget(input: BanInput): { scope: string; targetValue: string return { scope, targetValue: assertValidScopeValue(scope, input.value!) }; } +/** Allowlists need LAPI 1.6.6: a missing route must not block a ban. */ +function isAllowlistUnavailable(error: unknown): boolean { + if (error instanceof FeatureNotSupportedError) { + return true; + } + const code = (error as { code?: unknown } | undefined)?.code; + return code === 404 || code === 405; +} + async function ensureBanAllowed(ctx: AppContext, scope: string, targetValue: string, force: boolean): Promise { if (force || (scope !== 'Ip' && scope !== 'Range')) { return; } - const checkResult = await ctx.allowlists.check(targetValue); + let checkResult: APITypes.CheckAllowlistResponse; + try { + checkResult = await ctx.allowlists.check(targetValue); + } catch (error) { + if (isAllowlistUnavailable(error)) { + // Older LAPI: no allowlist endpoint. Continue without the + // pre-check rather than refusing every ban. + return; + } + throw error; + } + if (checkResult.allowlisted) { const suffix = checkResult.reason ? ` by item ${checkResult.reason}` : ''; throw new Error(`${targetValue} is allowlisted${suffix}, use force=true to add the decision anyway`); @@ -246,9 +301,16 @@ function assertUnbanIdHasNoFilters(input: UnbanInput): void { } } -function buildUnbanQuery(input: UnbanInput, type: string | undefined): { ip?: string; value?: string; type?: string; scenario?: string } { - const query: { ip?: string; value?: string; type?: string; scenario?: string } = {}; - if (input.ip) query.ip = input.ip; +function buildUnbanQuery(input: UnbanInput, type: string | undefined): UnbanQuery { + const query: UnbanQuery = {}; + if (input.ip) { + query.ip = input.ip; + // Validated on CrowdSec 1.8.1: the delete filter defaults contains to + // true, so `?ip=...` also expires Range decisions containing the IP. + // `contains=false` limits the delete to decisions contained within the + // value (the exact IP, and anything nested inside it). + query.contains = false; + } if (input.value) query.value = input.value; if (type) query.type = type; if (input.scenario) query.scenario = input.scenario; @@ -305,39 +367,171 @@ async function unbanByScopeValue( const normalizedValue = assertValidScopeValue(normalized, value); if (normalized === 'Ip') { - return unbanByQuery(ctx, { ip: normalizedValue, type, scenario }); + return unbanByQuery(ctx, { ip: normalizedValue, type, scenario, contains: false }); } if (normalized === 'Range') { - // The delete endpoint matches the exact range value; search first so - // decisions for individual IPs inside the range are also removed. - const ids = await searchActiveDecisionIds(ctx, { ip: normalizedValue, decision_type: type, scenario }); - return unbanDecisionIds(ctx, ids); + // Validated on CrowdSec 1.8.1: ExpireDecisionsWithFilter supports + // `range` + `contains=false` + `type` + `scenario` server-side. Deleting + // via an alert search then by ID would also collect decisions of the + // same alert that are outside the range. + return unbanByQuery(ctx, { range: normalizedValue, type, scenario, contains: false }); } - return unbanByQuery(ctx, { scope: normalized, value: normalizedValue, type, scenario }); + // Validated on CrowdSec 1.8.1: `scope` is rejected by the decision delete + // filter with "'scope' doesn't exist: invalid filter"; `scopes` (plural) is + // the supported parameter. + return unbanByQuery(ctx, { scopes: normalized, value: normalizedValue, type, scenario }); } async function unbanByRange(ctx: AppContext, range: string, type: string | undefined, scenario: string | undefined): Promise { - // Same as scope=Range: containment requires an alert search to collect IDs. - const ids = await searchActiveDecisionIds(ctx, { ip: range, decision_type: type, scenario }); - return unbanDecisionIds(ctx, ids); + // Same as scope=Range: the LAPI filters decisions contained in the range. + return unbanByQuery(ctx, { range, type, scenario, contains: false }); } interface UnbanQuery { ip?: string; - scope?: string; + range?: string; + scopes?: string; value?: string; type?: string; scenario?: string; + contains?: boolean; +} + +/** + * True when the delete filter was rejected by the LAPI or the client guard. + * Such a failure happens while parsing the filter, before any row is deleted, + * so replaying it as a search + delete-by-id is safe. + */ +function shouldFallbackToSearch(error: unknown): boolean { + if (error instanceof FeatureNotSupportedError) { + return true; + } + + const code = (error as { code?: unknown } | undefined)?.code; + if (code !== 400 && code !== 500) { + return false; + } + + return /(doesn'?t exist|unknown|invalid)[\s\S]{0,60}filter|filter[\s\S]{0,60}(doesn'?t exist|unknown|invalid)/i.test( + cleanErrorMessage(error) + ); +} + +/** + * Keep only the decisions the requested filter would have deleted. + * + * The alert search returns whole alerts, and an alert can carry decisions for + * other values, types or scenarios. Deleting every decision of a matching alert + * would widen the operation, so the fallback is deliberately conservative: + * decisions are matched by exact scope/value (never by CIDR containment) and + * by type/scenario equality. It may leave a nested decision behind on an old + * LAPI, but it never deletes a decision the filter did not target. + */ +function decisionMatchesUnbanQuery(decision: APITypes.Decision, query: UnbanQuery): boolean { + if (query.type && decision.type?.toLowerCase() !== query.type.toLowerCase()) { + return false; + } + + if (query.scenario && decision.scenario?.toLowerCase() !== query.scenario.toLowerCase()) { + return false; + } + + // `normalizeScope(undefined)` defaults to Ip, which would let an incomplete + // decision match an IP filter. Require an explicit scope instead. + const decisionScope = decision.scope ? normalizeScope(decision.scope) : undefined; + + if (query.scopes !== undefined) { + return query.value !== undefined && decisionScope === normalizeScope(query.scopes) && decision.value === query.value; + } + + if (query.ip) { + return decisionScope === 'Ip' && decision.value === query.ip; + } + + if (query.range) { + return decisionScope === 'Range' && decision.value === query.range; + } + + // A bare value is not a valid unban filter; never widen to every decision. + return query.value === undefined; +} + +/** Smallest-version fallback: search alerts, then delete the matching decisions by id. */ +async function unbanBySearch(ctx: AppContext, query: UnbanQuery): Promise { + // `scope`/`value` on the alert search filters the alert source, not the + // decisions attached to it. A non-IP scope decision (Country, AS, ...) + // attached to a different alert source would be silently missed, so refuse + // rather than under-delete. + if (query.scopes !== undefined) { + throw new Error( + 'Cannot safely resolve a non-IP scope unban on this LAPI: the alert fallback cannot match decision scopes. ' + + 'Delete by decision id or upgrade the LAPI.' + ); + } + + // With a known-unsupported `contains`, the alert search would either fail + // or silently ignore the narrowing and return a wider set. Refuse instead + // of risking a deletion the filter did not intend. + if ((query.ip || query.range) && ctx.watcher?.supports('containsFilter') === false) { + throw new Error( + 'Cannot safely resolve this unban on this LAPI: the contains filter requires CrowdSec 1.0.3 or newer. ' + + 'Delete by decision id, shorten the decision duration, or upgrade the LAPI.' + ); + } + + const search: APITypes.SearchAlertsQuery = { + ip: query.ip, + range: query.range, + scope: query.scopes, + value: query.value, + decision_type: query.type, + scenario: query.scenario, + ...(query.ip || query.range ? { contains: false } : {}), + // Match the bouncer/direct paths, which can also target simulated + // decisions; the alert search excludes them unless asked. + simulated: true, + has_active_decision: true, + limit: 0 + }; + const alerts = await searchAlerts(ctx, search); + const ids = collectDecisions(alerts) + .filter((decision) => decisionMatchesUnbanQuery(decision, query)) + .map((decision) => decision.id) + .filter((id): id is number => typeof id === 'number'); + + return formatUnbanResult(await deleteDecisionIds(ctx, ids)); } async function unbanByQuery(ctx: AppContext, query: UnbanQuery) { - if (!query.ip && !query.scope && !query.value && !query.type && !query.scenario) { + if (!query.ip && !query.range && !query.scopes && !query.value && !query.type && !query.scenario) { throw new Error('Must provide id, at least one filter, or all=true with confirm=true'); } - const result = await ctx.watcher!.Decisions.delete(query); - return formatUnbanResult(result.nbDeleted ?? 0); + try { + const result = await ctx.watcher!.Decisions.delete(query); + return formatUnbanResult(result.nbDeleted ?? 0); + } catch (error) { + if (!shouldFallbackToSearch(error)) { + throw error; + } + + log('decision delete rejected (%s), falling back to the alert search', cleanErrorMessage(error)); + return unbanBySearch(ctx, query); + } +} + +/** + * `GET /v1/decisions` honours `scope` before 1.3.3 and from 1.6.1, but ignores + * it on 1.3.3-1.6.0. Without a declared version we cannot tell, so a scope + * filter through the bouncer path is refused instead of silently widened. + */ +function bouncerScopeFilterIsReliable(lapiVersion: string | undefined): boolean { + if (!lapiVersion || parseLapiVersion(lapiVersion) === null) { + return false; + } + + return compareLapiVersions(lapiVersion, '1.3.3') < 0 || compareLapiVersions(lapiVersion, '1.6.1') >= 0; } type ListDecisionsFilters = z.infer; @@ -365,11 +559,124 @@ function normalizeListDecisionsFilters(input: ListDecisionsFilters): NormalizedL return { scope, value }; } +interface ListDecisionFilters { + ip?: string; + range?: string; + scope?: string; + value?: string; + type?: string; + origin?: string; + scenario?: string; + since?: string; + until?: string; + contains?: boolean; + simulated: boolean; +} + +type ListWindow = ReturnType; + +async function searchBouncerDecisions(ctx: AppContext, filters: ListDecisionFilters, window: ListWindow): Promise { + if (!ctx.bouncer) { + return undefined; + } + + try { + await ctx.ensureReady('bouncer'); + const decisions = await ctx.bouncer.Decisions.search({ + ip: filters.ip, + range: filters.range, + scope: filters.scope, + value: filters.value, + type: filters.type, + origins: filters.origin, + scenarios_containing: filters.scenario, + simulated: filters.simulated, + ...(filters.ip || filters.range ? { contains: filters.contains } : {}) + }); + + return formatBouncerDecisionList(decisions, window.displayLimit); + } catch (error) { + // A broken bouncer key must not hide a healthy watcher, but keep the + // original failure visible in the debug log. + if (!ctx.watcher) { + throw error; + } + log('bouncer decision search failed, falling back to the watcher: %s', cleanErrorMessage(error)); + return undefined; + } +} + +async function searchWatcherDecisions(ctx: AppContext, filters: ListDecisionFilters, window: ListWindow): Promise { + await ctx.ensureReady('watcher'); + const query: APITypes.SearchAlertsQuery = { + ip: filters.ip, + range: filters.range, + scope: filters.scope, + value: filters.value, + scenario: filters.scenario, + decision_type: filters.type, + origin: filters.origin, + since: filters.since, + until: filters.until, + simulated: filters.simulated, + // `contains` only exists from LAPI 1.0.3 and is only meaningful with + // ip/range (docs/api-compatibility.md). + ...(filters.ip || filters.range ? { contains: filters.contains } : {}), + has_active_decision: true, + limit: window.fetchLimit + }; + + const alerts = await searchAlerts(ctx, query); + const rendered = formatDecisionList(alerts, window.displayLimit, window.maybeMore); + + if (!ctx.capabilities.decisionsFast) { + return `${rendered}\n\n_Bouncer credentials (CROWDSEC_API_KEY) would make this scan about 60x faster._`; + } + return rendered; +} + +function isTotalValue(value: string | undefined): boolean { + return value !== undefined && isTotalCidr(value); +} + +function unbanTargetState(input: UnbanInput): { totalCidr: boolean; hasNarrowTarget: boolean } { + const trimmedValue = input.value?.trim(); + const totalScopeValue = + input.scope !== undefined && + trimmedValue !== undefined && + normalizeScope(input.scope) === 'Range' && + isValidCidr(trimmedValue) && + isTotalCidr(trimmedValue); + const totalCidr = isTotalValue(input.ip) || isTotalValue(input.range) || totalScopeValue; + // Keep the truthy semantics: an empty string is not a narrowing target. + const hasNarrowTarget = Boolean( + (input.ip && !isTotalValue(input.ip)) || + (input.range && !isTotalValue(input.range)) || + (input.scope && input.value && !totalScopeValue) + ); + + return { totalCidr, hasNarrowTarget }; +} + +function assertUnbanConfirmation(input: UnbanInput, normalizedType: string | undefined): void { + const { totalCidr, hasNarrowTarget } = unbanTargetState(input); + + if (totalCidr && input.confirm !== true) { + throw new Error('Deleting decisions for a /0 range requires confirm=true; narrow the range or use all=true with confirm=true'); + } + if (!hasNarrowTarget && (normalizedType || input.scenario) && input.confirm !== true) { + throw new Error( + 'Deleting decisions filtered only by type/scenario requires confirm=true; add ip, range, or scope+value to narrow the target' + ); + } +} + export const decisionTools: ToolDefinition[] = [ { name: 'list_decisions', title: 'List Decisions', - description: 'List active decisions from CrowdSec. Works in both bouncer and watcher modes. Mirrors `cscli decisions list`.', + description: + 'List active decisions from CrowdSec. Works in both bouncer and watcher modes. With both credentials the bouncer path is used by default, where `scenario` is a substring match; `since`/`until` and `scope` force the watcher alert scan. Mirrors `cscli decisions list`.', inputSchema: ListDecisionsInput, kind: 'read', annotations: { readOnlyHint: true, idempotentHint: true }, @@ -381,71 +688,103 @@ export const decisionTools: ToolDefinition[] = [ const window = resolveListWindow(limit, all, ctx.config.maxResults); const normalizedSince = since ? toGoDuration(since) : undefined; const normalizedUntil = until ? toGoDuration(until) : undefined; + const needsAlertWindow = Boolean(normalizedSince || normalizedUntil); + const scopeNeedsWatcher = normalizedScope !== undefined && ctx.watcher !== undefined; - if (ctx.mode === 'watcher' && ctx.watcher) { - const query: APITypes.SearchAlertsQuery = { - ip, - range, - scope: normalizedScope, - value: normalizedValue, - scenario, - decision_type: decisionType, - origin, - since: normalizedSince, - until: normalizedUntil, - simulated: no_simulated ? false : undefined, - contains, - has_active_decision: true, - limit: window.fetchLimit - }; - - const alerts = await ctx.watcher.Alerts.search(query); - - return formatDecisionList(alerts, window.displayLimit, window.maybeMore); + if (normalizedScope !== undefined && !ctx.watcher && !bouncerScopeFilterIsReliable(ctx.config.lapiVersion)) { + throw new Error( + 'scope filtering requires watcher credentials because /v1/decisions ignores it on some LAPI versions; add CROWDSEC_MACHINE_ID/CROWDSEC_PASSWORD or declare a compatible CROWDSEC_LAPI_VERSION' + ); + } + + const filters: ListDecisionFilters = { + ip, + range, + scope: normalizedScope, + value: normalizedValue, + type: decisionType, + origin, + scenario, + since: normalizedSince, + until: normalizedUntil, + contains, + simulated: !no_simulated + }; + + if (ctx.bouncer && !needsAlertWindow && !scopeNeedsWatcher) { + const rendered = await searchBouncerDecisions(ctx, filters, window); + if (rendered !== undefined) { + return rendered; + } } - if (ctx.mode === 'bouncer' && ctx.bouncer) { - const decisions = await ctx.bouncer.Decisions.search({ - ip, - range, - scope: normalizedScope, - value: normalizedValue, - type: decisionType, - origins: origin, - scenarios_containing: scenario, - contains - }); - - return formatBouncerDecisionList(decisions, window.displayLimit); + if (ctx.watcher) { + return searchWatcherDecisions(ctx, filters, window); } - throw new Error('No client available for the current mode'); + if (needsAlertWindow) { + throw new Error( + 'since/until filter alerts and require watcher credentials; add CROWDSEC_MACHINE_ID/CROWDSEC_PASSWORD or drop those filters' + ); + } + + throw new Error('No decision client available'); } }, { name: 'get_decision', title: 'Get decision details', - description: 'Get an active decision by ID, including its alert context. Requires watcher mode.', + description: + 'Get an active decision by ID. The watcher path also includes the alert context; with a bouncer key the decision is found in the fast decision list.', inputSchema: GetDecisionInput, kind: 'read', - requires: ['watcher'], annotations: { readOnlyHint: true, idempotentHint: true }, handler: async (input, ctx) => { - if (!ctx.watcher) { - throw new Error('Watcher client not available'); - } - const { id } = GetDecisionInput.parse(input); const decisionId = parsePositiveId(id, 'decision id'); - const alerts = await ctx.watcher.Alerts.search({ has_active_decision: true, limit: 0 }); - for (const alert of alerts) { - const decision = (alert.decisions ?? []).find((candidate) => candidate.id === Number(decisionId)); + let watcherError: unknown; + + if (ctx.watcher) { + try { + await ctx.ensureReady('watcher'); + // The LAPI exposes no decision lookup by id: this full scan + // is the price of returning the alert context. The bouncer + // path below is cheaper but only has the decision itself. + const alerts = await searchAlerts(ctx, { has_active_decision: true, simulated: true, limit: 0 }); + + for (const alert of alerts) { + const decision = (alert.decisions ?? []).find((candidate) => candidate.id === Number(decisionId)); + if (decision) { + return formatDecisionDetail(decision, alert); + } + } + } catch (error) { + if (!ctx.bouncer) { + throw error; + } + // The bouncer can still satisfy the lookup when the watcher + // is unavailable or the decision has no local alert. + watcherError = error; + } + } + + if (ctx.bouncer) { + await ctx.ensureReady('bouncer'); + // Include simulated decisions so the lookup matches the + // watcher path; the bouncer endpoint excludes them by default. + // `/v1/decisions` has no id filter, so this downloads the + // active decision set and filters locally. + const decisions = await ctx.bouncer.Decisions.search({ simulated: true }); + const decision = decisions.find((candidate) => candidate.id === Number(decisionId)); if (decision) { - return formatDecisionDetail(decision, alert); + return formatDecisionDetail(decision); } } + if (watcherError) { + throw watcherError; + } throw new Error(`Decision ${decisionId} not found`); } }, @@ -456,7 +795,7 @@ export const decisionTools: ToolDefinition[] = [ 'Add a new decision (ban, captcha, etc.) for an IP, range, or other scope. Requires watcher mode. Mirrors `cscli decisions add`.', inputSchema: BanIpInput, kind: 'write', - requires: ['watcher'], + requires: ['write'], annotations: { readOnlyHint: false, destructiveHint: true }, handler: async (input, ctx) => { if (!ctx.watcher) { @@ -494,7 +833,7 @@ export const decisionTools: ToolDefinition[] = [ 'Delete decisions by ID or filters. Requires watcher mode. Broad type/scenario-only filters require confirm=true. Mirrors `cscli decisions delete`.', inputSchema: UnbanIpInput, kind: 'write', - requires: ['watcher'], + requires: ['write'], annotations: { readOnlyHint: false, destructiveHint: true }, handler: async (input, ctx) => { if (!ctx.watcher) { @@ -522,13 +861,7 @@ export const decisionTools: ToolDefinition[] = [ } const normalizedType = unbanInput.type ? assertValidDecisionType(unbanInput.type) : undefined; - - const hasNarrowTarget = Boolean(unbanInput.ip || unbanInput.range || (unbanInput.scope && unbanInput.value)); - if (!hasNarrowTarget && (normalizedType || unbanInput.scenario) && unbanInput.confirm !== true) { - throw new Error( - 'Deleting decisions filtered only by type/scenario requires confirm=true; add ip, range, or scope+value to narrow the target' - ); - } + assertUnbanConfirmation(unbanInput, normalizedType); if (unbanInput.scope && unbanInput.value) { return unbanByScopeValue(ctx, unbanInput.scope, unbanInput.value, normalizedType, unbanInput.scenario); diff --git a/packages/crowdsec-mcp/src/tools/system.ts b/packages/crowdsec-mcp/src/tools/system.ts index 7fb1e88c5..72fe46248 100644 --- a/packages/crowdsec-mcp/src/tools/system.ts +++ b/packages/crowdsec-mcp/src/tools/system.ts @@ -9,24 +9,52 @@ export const statusTool: ToolDefinition = { description: 'Check the connection to the CrowdSec local API and show the authentication mode, capabilities and active MCP tools.', inputSchema: z.object({}), kind: 'read', + // The status tool must never fail before its handler runs: reporting a + // failed login is exactly what it is for. It triggers the login itself and + // keeps the result in `ctx.readiness`. + client: 'none', annotations: { readOnlyHint: true, idempotentHint: true }, - handler: (_input, ctx) => { - const machineSuffix = ctx.mode === 'watcher' && ctx.config.machineId ? ` (${ctx.config.machineId})` : ''; - const auth = ctx.mode === 'watcher' ? `watcher${machineSuffix}` : 'bouncer'; + handler: async (_input, ctx) => { + let connection = 'connected'; + try { + await ctx.ensureReady('any'); + } catch { + connection = 'connection failed'; + } + + const machineSuffix = ctx.config.machineId ? ` (${ctx.config.machineId})` : ''; + const authParts: string[] = []; + if (ctx.capabilities.alerts) { + authParts.push(`watcher${machineSuffix}`); + } + if (ctx.capabilities.decisionsFast) { + authParts.push('bouncer'); + } + const auth = authParts.length > 0 ? authParts.join(' + ') : ctx.mode; let writeLabel = 'no'; if (ctx.capabilities.write) { writeLabel = ctx.config.readonly ? 'yes (disabled by read-only)' : 'yes'; } + const decisionPath = ctx.capabilities.decisionsFast + ? 'bouncer (/v1/decisions, fast)' + : 'watcher (alert scan; set CROWDSEC_API_KEY for the bouncer fast path)'; const lines = [ - 'CrowdSec MCP is connected.', + `CrowdSec MCP is ${connection}.`, '', bullets([ `URL: ${redactedUrl(ctx.config.url)}`, + `LAPI version: ${ctx.config.lapiVersion ?? 'not declared'}`, `Authentication: ${auth}`, `Capabilities: read=yes, write=${writeLabel}, allowlists=${ctx.capabilities.allowlists ? 'yes' : 'no'}`, + `Credentials: alerts=${ctx.capabilities.alerts ? 'yes' : 'no'}, decisions=${ + ctx.capabilities.decisions ? 'yes' : 'no' + }, bouncer=${ctx.capabilities.decisionsFast ? 'configured' : 'no'}`, + `Readiness: watcher=${ctx.readiness.watcher ?? 'unknown'}, bouncer=${ctx.readiness.bouncer ?? 'unknown'}`, + `Decision path: ${decisionPath}`, + `Timeout: ${ctx.config.timeout} ms (CROWDSEC_TIMEOUT, maximum 600000)`, `Read-only: ${ctx.config.readonly ? 'yes' : 'no'}`, `Default result limit: ${ctx.config.maxResults}`, `Maximum ban duration: ${ctx.config.maxBanDuration} (force=true can override)`, diff --git a/packages/crowdsec-mcp/src/types.ts b/packages/crowdsec-mcp/src/types.ts index 617d8c276..22224e443 100644 --- a/packages/crowdsec-mcp/src/types.ts +++ b/packages/crowdsec-mcp/src/types.ts @@ -7,17 +7,34 @@ export type AuthMode = 'bouncer' | 'watcher'; export interface Capabilities { read: boolean; + /** Watcher credentials: alerts, alert deletion and writes. */ + alerts: boolean; + /** Any credentials: decisions can be listed/looked up. */ + decisions: boolean; + /** Bouncer credentials: `/v1/decisions` fast path. */ + decisionsFast: boolean; + /** Watcher credentials: write tools (ban/unban). */ write: boolean; + /** Watcher credentials: allowlists. */ allowlists: boolean; } export interface AllowlistsPort { - list(): Promise; + list(withContent?: boolean): Promise; get(name: string, withContent?: boolean): Promise; check(value: string): Promise; bulkCheck(targets: string[]): Promise; } +export type ReadinessRequirement = 'watcher' | 'bouncer' | 'any' | 'none'; + +export type ClientReadinessState = 'ok' | 'error'; + +export interface ClientReadiness { + watcher?: ClientReadinessState; + bouncer?: ClientReadinessState; +} + export interface AppContext { mode: AuthMode; capabilities: Capabilities; @@ -26,11 +43,14 @@ export interface AppContext { allowlists: AllowlistsPort; config: Config; activeTools?: string[]; - ensureReady: () => Promise; + /** Last login result per configured client, for crowdsec_status. */ + readiness: ClientReadiness; + /** Log in lazily, only for the client(s) the current tool needs. */ + ensureReady: (requirement?: ReadinessRequirement) => Promise; stop: () => Promise; } -export type ToolRequirement = 'watcher' | 'allowlists'; +export type ToolRequirement = 'alerts' | 'write' | 'allowlists'; export type ToolFeature = 'alert-delete'; export interface ToolDefinition { @@ -40,6 +60,8 @@ export interface ToolDefinition { inputSchema: ZodType; kind: 'read' | 'write'; requires?: ToolRequirement[]; + /** Client that must be logged in before the handler runs. Defaults to watcher when `requires` is set, none otherwise. */ + client?: ReadinessRequirement; feature?: ToolFeature; annotations?: ToolAnnotations; handler: (input: unknown, ctx: AppContext) => CallToolResult | string | Promise; diff --git a/packages/crowdsec-mcp/src/utils.ts b/packages/crowdsec-mcp/src/utils.ts index 87cad9167..0ed1bd886 100644 --- a/packages/crowdsec-mcp/src/utils.ts +++ b/packages/crowdsec-mcp/src/utils.ts @@ -18,7 +18,9 @@ export function isValidCidr(value: string): boolean { return false; } - if (!/^\d+$/.test(prefix)) { + // Reject non-canonical prefixes such as /00: Go normalises them to /0, which + // would turn a supposedly narrow target into a delete-everything range. + if (!/^(0|[1-9]\d*)$/.test(prefix)) { return false; } @@ -26,6 +28,15 @@ export function isValidCidr(value: string): boolean { return family === 4 ? prefixNumber >= 0 && prefixNumber <= 32 : prefixNumber >= 0 && prefixNumber <= 128; } +/** + * A /0 range (0.0.0.0/0, ::/0) covers everything. It must never be treated as + * a narrow delete target: `confirm=true` is required just like `all=true`. + */ +export function isTotalCidr(value: string): boolean { + const [address, prefix, ...rest] = value.split('/'); + return rest.length === 0 && prefix !== undefined && Number(prefix) === 0 && isValidIp(address); +} + /** * Mirror cscli's scope normalization and IP/range validation. */ @@ -249,3 +260,41 @@ export function splitList(value?: string): string[] | undefined { .filter(Boolean); return items.length > 0 ? items : undefined; } + +/** + * Run an async mapper with a bounded number of in-flight calls. Deleting a + * large CIDR or `all=true` can collect thousands of ids; an unbounded + * `Promise.all` would exhaust sockets and hammer the LAPI. + */ +export async function mapWithConcurrency(items: T[], limit: number, mapper: (item: T) => Promise): Promise { + if (limit <= 0) { + throw new Error('concurrency limit must be positive'); + } + + const results = new Array(items.length); + let next = 0; + let failed = false; + + const worker = async (): Promise => { + while (!failed) { + const index = next++; + if (index >= items.length) { + return; + } + + try { + results[index] = await mapper(items[index]); // NOSONAR: bounded concurrency worker + } catch (error) { + // Stop scheduling new work as soon as one item fails: a delete + // loop must not keep mutating the LAPI after the tool reported + // an error. + failed = true; + throw error; + } + } + }; + + const workers = Array.from({ length: Math.min(limit, items.length) }, () => worker()); + await Promise.all(workers); + return results; +} diff --git a/packages/crowdsec-mcp/tests/client-context.test.ts b/packages/crowdsec-mcp/tests/client-context.test.ts new file mode 100644 index 000000000..7d8109a3a --- /dev/null +++ b/packages/crowdsec-mcp/tests/client-context.test.ts @@ -0,0 +1,173 @@ +import http from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { createContext } from '../src/client.js'; +import { decisionTools } from '../src/tools/decisions.js'; +import { makeConfig } from './helpers.js'; + +let server: http.Server; +let baseUrl: string; +let watcherValid = true; +let bouncerValid = true; + +const decision = { + id: 123, + type: 'ban', + scope: 'ip', + value: '1.2.3.4', + origin: 'capi', + scenario: 'test', + duration: '4h', + simulated: false +}; + +beforeAll(async () => { + server = http.createServer((request, response) => { + if (request.method === 'POST' && request.url === '/v1/watchers/login') { + if (!watcherValid) { + response.writeHead(403); + response.end(); + return; + } + response.setHeader('content-type', 'application/json'); + response.end(JSON.stringify({ token: 'test-token', expire: new Date(Date.now() + 60 * 60 * 1000).toISOString() })); + return; + } + + if (request.method === 'HEAD' && request.url === '/v1/alerts') { + response.writeHead(watcherValid ? 200 : 403); + response.end(); + return; + } + + if (request.method === 'HEAD' && request.url === '/v1/decisions') { + response.writeHead(bouncerValid ? 200 : 403); + response.end(); + return; + } + + if (request.method === 'GET' && request.url?.startsWith('/v1/decisions')) { + if (!bouncerValid) { + response.writeHead(403); + response.end(); + return; + } + response.setHeader('content-type', 'application/json'); + response.end(JSON.stringify([decision])); + return; + } + + response.writeHead(404); + response.end(); + }); + + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; +}); + +afterAll(async () => { + await new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve()))); +}); + +beforeEach(() => { + watcherValid = true; + bouncerValid = true; +}); + +function makeDualConfig() { + return makeConfig({ + url: baseUrl, + auth: 'bouncer', + watcher: true, + bouncer: true, + machineId: 'machine', + password: 'password', + apiKey: 'key' + }); +} + +describe('dual-credential readiness', () => { + it('does not let an invalid watcher block the bouncer path', async () => { + watcherValid = false; + const ctx = await createContext(makeDualConfig()); + + try { + await expect(ctx.ensureReady('bouncer')).resolves.toBeUndefined(); + await expect(ctx.ensureReady('watcher')).rejects.toBeTruthy(); + expect(ctx.readiness.bouncer).toBe('ok'); + expect(ctx.readiness.watcher).toBe('error'); + + const tool = decisionTools.find((candidate) => candidate.name === 'list_decisions')!; + const result = (await tool.handler({}, ctx)) as string; + expect(result).toContain('1.2.3.4'); + } finally { + await ctx.stop(); + } + }); + + it('does not let an invalid bouncer block the watcher path', async () => { + bouncerValid = false; + const ctx = await createContext(makeDualConfig()); + + try { + await expect(ctx.ensureReady('watcher')).resolves.toBeUndefined(); + await expect(ctx.ensureReady('bouncer')).rejects.toBeTruthy(); + expect(ctx.readiness.watcher).toBe('ok'); + expect(ctx.readiness.bouncer).toBe('error'); + } finally { + await ctx.stop(); + } + }); + + it('succeeds with any readiness when at least one credential works', async () => { + bouncerValid = false; + const ctx = await createContext(makeDualConfig()); + + try { + await expect(ctx.ensureReady('any')).resolves.toBeUndefined(); + expect(ctx.readiness.bouncer).toBe('error'); + expect(ctx.readiness.watcher).toBe('ok'); + } finally { + await ctx.stop(); + } + }); + + it('maps a static authentication failure to a friendly message', async () => { + watcherValid = false; + const ctx = await createContext(makeConfig({ url: baseUrl })); + + try { + await expect(ctx.ensureReady('watcher')).rejects.toThrow('Invalid CrowdSec token'); + } finally { + await ctx.stop(); + } + }); + + it('maps a static dual authentication failure to a friendly message', async () => { + watcherValid = false; + bouncerValid = false; + const ctx = await createContext(makeDualConfig()); + + try { + await expect(ctx.ensureReady('any')).rejects.toThrow('Invalid CrowdSec credentials'); + } finally { + await ctx.stop(); + } + }); + + it('falls back to the bouncer for get_decision and normalises scope/origin', async () => { + watcherValid = false; + const ctx = await createContext(makeDualConfig()); + + try { + const tool = decisionTools.find((candidate) => candidate.name === 'get_decision')!; + const result = (await tool.handler({ id: 123 }, ctx)) as string; + + expect(result).toContain('### Decision #123'); + expect(result).toContain('Scope:** Ip'); + expect(result).toContain('Origin:** CAPI'); + } finally { + await ctx.stop(); + } + }); +}); diff --git a/packages/crowdsec-mcp/tests/client.test.ts b/packages/crowdsec-mcp/tests/client.test.ts index 8dd674f3e..736d06fae 100644 --- a/packages/crowdsec-mcp/tests/client.test.ts +++ b/packages/crowdsec-mcp/tests/client.test.ts @@ -14,30 +14,21 @@ describe('passthrough auth', () => { } }); - it('rejects both credential headers', () => { - expect(() => + it('accepts both credential headers on the same request', () => { + expect( resolvePassthroughAuth({ 'x-crowdsec-api-key': 'key', 'x-crowdsec-token': 'jwt' }) - ).toThrow(HttpRequestError); - - try { - resolvePassthroughAuth({ - 'x-crowdsec-api-key': 'key', - 'x-crowdsec-token': 'jwt' - }); - } catch (error) { - expect(error).toMatchObject({ status: 400, code: -32602 }); - } + ).toEqual({ apiKey: 'key', token: 'jwt' }); }); it('resolves a bouncer API key', () => { - expect(resolvePassthroughAuth({ 'x-crowdsec-api-key': 'key' })).toEqual({ mode: 'bouncer', apiKey: 'key' }); + expect(resolvePassthroughAuth({ 'x-crowdsec-api-key': 'key' })).toEqual({ apiKey: 'key' }); }); it('resolves a watcher token', () => { - expect(resolvePassthroughAuth({ 'x-crowdsec-token': 'jwt' })).toEqual({ mode: 'watcher', token: 'jwt' }); + expect(resolvePassthroughAuth({ 'x-crowdsec-token': 'jwt' })).toEqual({ token: 'jwt' }); }); }); @@ -49,7 +40,14 @@ describe('createPassthroughContext', () => { try { expect(context.mode).toBe('bouncer'); - expect(context.capabilities).toEqual({ read: true, write: false, allowlists: false }); + expect(context.capabilities).toEqual({ + read: true, + alerts: false, + decisions: true, + decisionsFast: true, + write: false, + allowlists: false + }); } finally { await context.stop(); } @@ -62,7 +60,36 @@ describe('createPassthroughContext', () => { try { expect(context.mode).toBe('watcher'); - expect(context.capabilities).toEqual({ read: true, write: true, allowlists: true }); + expect(context.capabilities).toEqual({ + read: true, + alerts: true, + decisions: true, + decisionsFast: false, + write: true, + allowlists: true + }); + } finally { + await context.stop(); + } + }); + + it('builds both clients when both headers are present', async () => { + const context = await createPassthroughContext(makeConfig({ passthrough: true }), { + 'x-crowdsec-api-key': 'key', + 'x-crowdsec-token': 'jwt' + }); + + try { + expect(context.watcher).toBeDefined(); + expect(context.bouncer).toBeDefined(); + expect(context.capabilities).toEqual({ + read: true, + alerts: true, + decisions: true, + decisionsFast: true, + write: true, + allowlists: true + }); } finally { await context.stop(); } diff --git a/packages/crowdsec-mcp/tests/config.test.ts b/packages/crowdsec-mcp/tests/config.test.ts index c4cca325d..c71e536fb 100644 --- a/packages/crowdsec-mcp/tests/config.test.ts +++ b/packages/crowdsec-mcp/tests/config.test.ts @@ -1,6 +1,21 @@ -import { describe, expect, it } from 'vitest'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterAll, describe, expect, it } from 'vitest'; import { loadConfig, parseCliArgs } from '../src/config.js'; +const secretDir = mkdtempSync(join(tmpdir(), 'crowdsec-mcp-config-')); + +afterAll(() => { + rmSync(secretDir, { recursive: true, force: true }); +}); + +function secretFile(name: string, content: string): string { + const path = join(secretDir, name); + writeFileSync(path, content); + return path; +} + describe('config', () => { it('auto-detects bouncer authentication from the API key', () => { const config = loadConfig({}, { CROWDSEC_URL: 'https://crowdsec:8080', CROWDSEC_API_KEY: 'key' }); @@ -11,6 +26,20 @@ describe('config', () => { expect(config.transport).toBe('stdio'); }); + it('should not leak credentials from a rejected URL', () => { + for (const url of ['ftp://user:secret@host', 'user:secret@host']) { + let message = ''; + try { + loadConfig({}, { CROWDSEC_URL: url, CROWDSEC_API_KEY: 'key' }); + } catch (error) { + message = (error as Error).message; + } + + expect(message).toContain('must start with'); + expect(message).not.toContain('secret'); + } + }); + it('auto-detects watcher authentication from machine credentials', () => { const config = loadConfig( {}, @@ -33,6 +62,103 @@ describe('config', () => { ); expect(config.auth).toBe('bouncer'); + expect(config.watcher).toBe(true); + expect(config.bouncer).toBe(true); + }); + + it('enables both clients when bouncer and watcher credentials coexist without CROWDSEC_AUTH', () => { + const config = loadConfig( + {}, + { + CROWDSEC_URL: 'https://crowdsec:8080', + CROWDSEC_API_KEY: 'key', + CROWDSEC_MACHINE_ID: 'machine', + CROWDSEC_PASSWORD: 'password' + } + ); + + expect(config.watcher).toBe(true); + expect(config.bouncer).toBe(true); + }); + + it('does not invent a watcher from TLS when only an API key and TLS are supplied', () => { + const config = loadConfig( + {}, + { + CROWDSEC_URL: 'https://crowdsec:8080', + CROWDSEC_API_KEY: 'key', + CROWDSEC_TLS_CERT: '/tmp/cert.pem', + CROWDSEC_TLS_KEY: '/tmp/key.pem', + CROWDSEC_TLS_CA: '/tmp/ca.pem' + } + ); + + expect(config.bouncer).toBe(true); + expect(config.watcher).toBe(false); + }); + + it.each([ + ['CROWDSEC_MACHINE_ID only', { CROWDSEC_MACHINE_ID: 'machine' }], + ['CROWDSEC_PASSWORD only', { CROWDSEC_PASSWORD: 'password' }] + ])('ignores incomplete machine credentials when a bouncer key is configured (%s)', (_label, extra) => { + const config = loadConfig( + {}, + { + CROWDSEC_URL: 'https://crowdsec:8080', + CROWDSEC_API_KEY: 'key', + ...extra + } + ); + + expect(config.watcher).toBe(false); + expect(config.bouncer).toBe(true); + }); + + it.each([ + ['CROWDSEC_MACHINE_ID only', { CROWDSEC_MACHINE_ID: 'machine' }], + ['CROWDSEC_PASSWORD only', { CROWDSEC_PASSWORD: 'password' }] + ])('rejects incomplete machine credentials when they are the only auth source (%s)', (_label, extra) => { + expect(() => + loadConfig( + {}, + { + CROWDSEC_URL: 'https://crowdsec:8080', + ...extra + } + ) + ).toThrow(/must be provided together/); + }); + + it('uses TLS for the watcher when machine credentials are incomplete', () => { + const config = loadConfig( + {}, + { + CROWDSEC_URL: 'https://crowdsec:8080', + CROWDSEC_MACHINE_ID: 'machine', + CROWDSEC_TLS_CERT: '/tmp/cert.pem', + CROWDSEC_TLS_KEY: '/tmp/key.pem', + CROWDSEC_TLS_CA: '/tmp/ca.pem' + } + ); + + expect(config.watcher).toBe(true); + expect(config.bouncer).toBe(false); + }); + + it('does not require static credentials when passthrough is enabled', () => { + const config = loadConfig( + {}, + { + CROWDSEC_URL: 'https://crowdsec:8080', + CROWDSEC_MCP_TRANSPORT: 'http', + CROWDSEC_MCP_PASSTHROUGH: 'true', + CROWDSEC_MCP_HTTP_TOKEN: 'service-token', + CROWDSEC_AUTH: 'bouncer' + } + ); + + expect(config.watcher).toBe(false); + expect(config.bouncer).toBe(false); }); it('honours explicit auth', () => { @@ -41,12 +167,15 @@ describe('config', () => { { CROWDSEC_URL: 'https://crowdsec:8080', CROWDSEC_AUTH: 'watcher', + CROWDSEC_API_KEY: 'key', CROWDSEC_MACHINE_ID: 'machine', CROWDSEC_PASSWORD: 'password' } ); expect(config.auth).toBe('watcher'); + expect(config.watcher).toBe(true); + expect(config.bouncer).toBe(false); }); it('rejects an invalid auth', () => { @@ -210,4 +339,116 @@ describe('config', () => { it('rejects an invalid URL', () => { expect(() => loadConfig({}, { CROWDSEC_URL: 'crowdsec:8080', CROWDSEC_API_KEY: 'key' })).toThrow(/http/); }); + + it('reads and validates CROWDSEC_LAPI_VERSION', () => { + const config = loadConfig( + {}, + { + CROWDSEC_URL: 'https://crowdsec:8080', + CROWDSEC_API_KEY: 'key', + CROWDSEC_LAPI_VERSION: 'v1.8.2' + } + ); + + expect(config.lapiVersion).toBe('v1.8.2'); + + expect(() => + loadConfig( + {}, + { + CROWDSEC_URL: 'https://crowdsec:8080', + CROWDSEC_API_KEY: 'key', + CROWDSEC_LAPI_VERSION: 'latest' + } + ) + ).toThrow(/CROWDSEC_LAPI_VERSION/); + }); + + it('accepts --lapi-version on the command line', () => { + const config = loadConfig(parseCliArgs(['--lapi-version', '1.6.6']).values, { + CROWDSEC_URL: 'https://crowdsec:8080', + CROWDSEC_API_KEY: 'key' + }); + + expect(config.lapiVersion).toBe('1.6.6'); + }); + + it('reads secrets from _FILE variables and strips trailing newlines', () => { + const keyFile = secretFile('api_key', 'file-key\r\n\r\n'); + const machineFile = secretFile('machine_id', 'file-machine\n'); + const passwordFile = secretFile('password', 'file-password\n'); + + const config = loadConfig( + {}, + { + CROWDSEC_URL: 'https://crowdsec:8080', + CROWDSEC_API_KEY_FILE: keyFile, + CROWDSEC_MACHINE_ID_FILE: machineFile, + CROWDSEC_PASSWORD_FILE: passwordFile + } + ); + + expect(config.apiKey).toBe('file-key'); + expect(config.machineId).toBe('file-machine'); + expect(config.password).toBe('file-password'); + expect(config.watcher).toBe(true); + expect(config.bouncer).toBe(true); + }); + + it('preserves spaces in a secret read from _FILE', () => { + const keyFile = secretFile('spaced_key', ' spaced key \n'); + + const config = loadConfig( + {}, + { + CROWDSEC_URL: 'https://crowdsec:8080', + CROWDSEC_API_KEY_FILE: keyFile + } + ); + + expect(config.apiKey).toBe(' spaced key '); + }); + + it('lets the plain environment variable win over _FILE', () => { + const keyFile = secretFile('ignored_key', 'file-key\n'); + + const config = loadConfig( + {}, + { + CROWDSEC_URL: 'https://crowdsec:8080', + CROWDSEC_API_KEY: 'env-key', + CROWDSEC_API_KEY_FILE: keyFile + } + ); + + expect(config.apiKey).toBe('env-key'); + }); + + it('reports a missing secret file without leaking its path', () => { + expect(() => + loadConfig( + {}, + { + CROWDSEC_URL: 'https://crowdsec:8080', + CROWDSEC_API_KEY_FILE: join(secretDir, 'missing') + } + ) + ).toThrow(/CROWDSEC_API_KEY_FILE/); + }); + + it('rejects passthrough with TLS certificates instead of silently dropping them', () => { + expect(() => + loadConfig( + {}, + { + CROWDSEC_URL: 'https://crowdsec:8080', + CROWDSEC_MCP_TRANSPORT: 'http', + CROWDSEC_MCP_PASSTHROUGH: 'true', + CROWDSEC_TLS_CERT: '/tmp/cert.pem', + CROWDSEC_TLS_KEY: '/tmp/key.pem', + CROWDSEC_TLS_CA: '/tmp/ca.pem' + } + ) + ).toThrow(/passthrough mode does not support/); + }); }); diff --git a/packages/crowdsec-mcp/tests/docs.test.ts b/packages/crowdsec-mcp/tests/docs.test.ts index 40d8b647b..da4dda0df 100644 --- a/packages/crowdsec-mcp/tests/docs.test.ts +++ b/packages/crowdsec-mcp/tests/docs.test.ts @@ -46,8 +46,8 @@ const watcherContext = (): AppContext => makeContext(); const bouncerContext = (): AppContext => makeContext({ mode: 'bouncer', - capabilities: { read: true, write: false, allowlists: false }, - config: makeConfig({ readonly: true }) + capabilities: { read: true, alerts: false, decisions: true, decisionsFast: true, write: false, allowlists: false }, + config: makeConfig({ auth: 'bouncer', watcher: false, bouncer: true, readonly: true }) }); describe('server instructions', () => { diff --git a/packages/crowdsec-mcp/tests/e2e/http/live.test.ts b/packages/crowdsec-mcp/tests/e2e/http/live.test.ts index f04c0b136..c9d685c1e 100644 --- a/packages/crowdsec-mcp/tests/e2e/http/live.test.ts +++ b/packages/crowdsec-mcp/tests/e2e/http/live.test.ts @@ -100,14 +100,27 @@ describe.skipIf(!enabled || !mcpUrl || !openMcpUrl || !bouncerKey || !watcherTok await response.text(); }); - it('rejects both bouncer and watcher credentials', async () => { - const response = await post(mcpUrl!, { + it('accepts both bouncer and watcher credentials and exposes the union', async () => { + const headers = { authorization: `Bearer ${serviceToken}`, 'x-crowdsec-api-key': bouncerKey!, 'x-crowdsec-token': watcherToken - }); - expect(response.status).toBe(400); + }; + const response = await post(mcpUrl!, headers); + expect(response.status).toBe(200); await response.text(); + + await withClient(mcpUrl!, headers, async (client) => { + const names = (await client.listTools()).tools.map((tool) => tool.name); + expect(names).toContain('list_alerts'); + expect(names).toContain('get_alert'); + expect(names).toContain('list_decisions'); + expect(names).toContain('get_decision'); + + const status = textOf(await client.callTool({ name: 'crowdsec_status', arguments: {} })); + expect(status).toContain('watcher'); + expect(status).toContain('bouncer'); + }); }); it('exposes bouncer tools and reads decisions', async () => { diff --git a/packages/crowdsec-mcp/tests/helpers.ts b/packages/crowdsec-mcp/tests/helpers.ts index 8f0940b46..5a8f07f13 100644 --- a/packages/crowdsec-mcp/tests/helpers.ts +++ b/packages/crowdsec-mcp/tests/helpers.ts @@ -5,6 +5,8 @@ export function makeConfig(overrides: Partial = {}): Config { return { url: 'http://127.0.0.1:8080', auth: 'watcher', + watcher: true, + bouncer: false, machineId: 'machine', password: 'password', strictSSL: true, @@ -33,6 +35,9 @@ export function makeContext(overrides: Partial = {}): AppContext { mode: 'watcher', capabilities: { read: true, + alerts: true, + decisions: true, + decisionsFast: false, write: true, allowlists: true }, @@ -43,6 +48,7 @@ export function makeContext(overrides: Partial = {}): AppContext { bulkCheck: () => Promise.resolve({ results: [] }) }, config: makeConfig(), + readiness: {}, ensureReady: () => { readyCalls++; return Promise.resolve(); diff --git a/packages/crowdsec-mcp/tests/registry.test.ts b/packages/crowdsec-mcp/tests/registry.test.ts index 0811d642c..17ce38b9f 100644 --- a/packages/crowdsec-mcp/tests/registry.test.ts +++ b/packages/crowdsec-mcp/tests/registry.test.ts @@ -26,7 +26,7 @@ const tools = [ readTool('list_decisions'), readTool('list_alerts'), writeTool('ban_ip'), - { ...readTool('check_allowlist'), requires: ['watcher', 'allowlists'] as const } + { ...readTool('check_allowlist'), requires: ['allowlists'] as const } ]; describe('registry', () => { @@ -43,7 +43,13 @@ describe('registry', () => { }); it('hides watcher-only tools in bouncer mode', () => { - const selected = selectTools(tools, makeContext({ mode: 'bouncer' })); + const selected = selectTools( + tools, + makeContext({ + mode: 'bouncer', + capabilities: { read: true, alerts: false, decisions: true, decisionsFast: true, write: false, allowlists: false } + }) + ); expect(selected.map((tool) => tool.name)).not.toContain('check_allowlist'); }); @@ -52,7 +58,7 @@ describe('registry', () => { const selected = selectTools( tools, makeContext({ - capabilities: { read: true, write: true, allowlists: false } + capabilities: { read: true, alerts: true, decisions: true, decisionsFast: false, write: true, allowlists: false } }) ); @@ -71,6 +77,17 @@ describe('registry', () => { expect(selected.map((tool) => tool.name)).toEqual(['list_decisions', 'check_allowlist']); }); + it('lets the allowlist override the denylist', () => { + const selected = selectTools( + tools, + makeContext({ + config: makeConfig({ readonly: false, tools: ['ban_ip'], disableTools: ['ban_ip'] }) + }) + ); + + expect(selected.map((tool) => tool.name)).toEqual(['ban_ip']); + }); + it('rejects unknown tool names', () => { expect(() => selectTools(tools, makeContext({ config: makeConfig({ tools: ['does_not_exist'] }) }))).toThrow(/unknown tool/); }); @@ -85,7 +102,49 @@ describe('errorResult', () => { }); }); +describe('timeout errors', () => { + it('turns an axios timeout into an actionable message', () => { + const error = Object.assign(new Error('timeout of 10000ms exceeded'), { code: 'ECONNABORTED' }); + const result = errorResult(error, { timeout: 10000, toolName: 'list_decisions', hasBouncer: false }); + + expect(result.isError).toBe(true); + const text = (result.content[0] as { text: string }).text; + expect(text).toContain('timed out after 10000 ms'); + expect(text).toContain('CROWDSEC_TIMEOUT'); + expect(text).toContain('600000'); + expect(text).toContain('bouncer'); + }); + + it('does not suggest a bouncer key when one is already configured', () => { + const result = errorResult(new Error('timeout of 5000ms exceeded'), { + timeout: 5000, + toolName: 'list_decisions', + hasBouncer: true + }); + + expect((result.content[0] as { text: string }).text).not.toContain('Set CROWDSEC_API_KEY'); + }); + + it('detects a timeout nested in a client exception', () => { + const error = new Error('HOST_NOT_REACHABLE'); + (error as Error & { exception?: unknown }).exception = Object.assign(new Error('timeout of 10000ms exceeded'), { + code: 'ECONNABORTED' + }); + + expect(cleanErrorMessage(error, { timeout: 10000 })).toContain('timed out'); + }); +}); + describe('cleanErrorMessage', () => { + it('redacts credentials in URLs and token query parameters', () => { + const message = cleanErrorMessage(new Error('request to https://user:pass@host/path?token=abc failed')); + + expect(message).not.toContain('pass'); + expect(message).not.toContain('abc'); + expect(message).toContain('***'); + expect(message).toContain('[redacted]'); + }); + it('maps CrowdSec internals to business messages', () => { expect(cleanErrorMessage(new Error('CrowdSecError (404) : object not found'))).toBe('Resource not found'); expect(cleanErrorMessage(new Error("CrowdSecError (500) : allowlist 'nope' not found"))).toBe("Allowlist 'nope' not found"); diff --git a/packages/crowdsec-mcp/tests/system.test.ts b/packages/crowdsec-mcp/tests/system.test.ts index 7ebbbb6a6..23a480b07 100644 --- a/packages/crowdsec-mcp/tests/system.test.ts +++ b/packages/crowdsec-mcp/tests/system.test.ts @@ -29,4 +29,21 @@ describe('crowdsec_status', () => { expect(result).toContain('write=yes,'); }); + + it('shows the declared LAPI version, or that it is not declared', async () => { + const declared = makeContext({ config: makeConfig({ lapiVersion: '1.8.2' }) }); + expect(await statusTool.handler({}, declared)).toContain('LAPI version: 1.8.2'); + + const unknown = makeContext({ config: makeConfig({ lapiVersion: undefined }) }); + expect(await statusTool.handler({}, unknown)).toContain('LAPI version: not declared'); + }); + + it('reports a failed connection instead of throwing', async () => { + const context = makeContext({ ensureReady: () => Promise.reject(new Error('boom')) }); + + const result = await statusTool.handler({}, context); + + expect(result).toContain('CrowdSec MCP is connection failed.'); + expect(result).toContain('Readiness: watcher=unknown, bouncer=unknown'); + }); }); diff --git a/packages/crowdsec-mcp/tests/tools/alerts.test.ts b/packages/crowdsec-mcp/tests/tools/alerts.test.ts index 2b4903a62..a7773be28 100644 --- a/packages/crowdsec-mcp/tests/tools/alerts.test.ts +++ b/packages/crowdsec-mcp/tests/tools/alerts.test.ts @@ -267,6 +267,29 @@ describe('alertTools', () => { ); }); + it('should not send contains when no ip/range is provided', async () => { + mockWatcher.Alerts.search.mockResolvedValue([]); + const tool = alertTools.find((t) => t.name === 'list_alerts')!; + + await tool.handler({ scenario: 'ssh-bf' }, mockCtx); + + expect(mockWatcher.Alerts.search.mock.calls[0][0]).not.toHaveProperty('contains'); + }); + + it('should allow matching decisions that contain the value with contains=true', async () => { + mockWatcher.Alerts.search.mockResolvedValue([]); + const tool = alertTools.find((t) => t.name === 'list_alerts')!; + + await tool.handler({ ip: '1.2.3.4', contains: true }, mockCtx); + + expect(mockWatcher.Alerts.search).toHaveBeenCalledWith( + expect.objectContaining({ + ip: '1.2.3.4', + contains: true + }) + ); + }); + it('should normalize scope and value before querying the LAPI', async () => { mockWatcher.Alerts.search.mockResolvedValue([]); const tool = alertTools.find((t) => t.name === 'list_alerts')!; @@ -503,7 +526,8 @@ describe('alertTools', () => { expect(mockWatcher.Alerts.delete).toHaveBeenCalledWith( expect.objectContaining({ ip: '192.168.1.100', - scenario: 'ssh-bf' + scenario: 'ssh-bf', + contains: false }) ); expect(result).toContain('Deleted 5 alert(s).'); @@ -517,6 +541,20 @@ describe('alertTools', () => { expect(mockWatcher.Alerts.deleteById).not.toHaveBeenCalled(); }); + it('should require confirm for a /0 range', async () => { + const tool = alertTools.find((t) => t.name === 'delete_alerts')!; + + await expect(tool.handler({ range: '0.0.0.0/0' }, mockCtx)).rejects.toThrow(/requires confirm=true/); + expect(mockWatcher.Alerts.search).not.toHaveBeenCalled(); + }); + + it('should require confirm for a /0 scope=Range value', async () => { + const tool = alertTools.find((t) => t.name === 'delete_alerts')!; + + await expect(tool.handler({ scope: 'Range', value: '0.0.0.0/0' }, mockCtx)).rejects.toThrow(/requires confirm=true/); + expect(mockWatcher.Alerts.search).not.toHaveBeenCalled(); + }); + it('should require confirm for origin-only deletes', async () => { const tool = alertTools.find((t) => t.name === 'delete_alerts')!; @@ -532,9 +570,11 @@ describe('alertTools', () => { expect(mockWatcher.Alerts.delete).toHaveBeenCalledWith( expect.objectContaining({ - alert_source: 'cscli' + origin: 'cscli' }) ); + expect(mockWatcher.Alerts.delete.mock.calls[0][0]).not.toHaveProperty('alert_source'); + expect(mockWatcher.Alerts.delete.mock.calls[0][0]).not.toHaveProperty('contains'); expect(mockWatcher.Alerts.search).not.toHaveBeenCalled(); expect(result).toContain('Deleted 5 alert(s).'); }); @@ -548,24 +588,82 @@ describe('alertTools', () => { expect(mockWatcher.Alerts.deleteById).not.toHaveBeenCalled(); }); - it('should delete alerts by decision type and time filters through a search when confirmed', async () => { + it('should delete alerts by decision type and time filters directly when confirmed', async () => { const tool = alertTools.find((t) => t.name === 'delete_alerts')!; - mockWatcher.Alerts.search.mockResolvedValue([{ id: 31 }]); - mockWatcher.Alerts.deleteById.mockResolvedValue({ nbDeleted: '1' }); const result = await tool.handler({ type: 'Ban', since: '4h', until: '1h', confirm: true }, mockCtx); - expect(mockWatcher.Alerts.search).toHaveBeenCalledWith( + expect(mockWatcher.Alerts.delete).toHaveBeenCalledWith( expect.objectContaining({ decision_type: 'ban', since: '4h', - until: '1h', - limit: 0 + until: '1h' }) ); + expect(mockWatcher.Alerts.search).not.toHaveBeenCalled(); + expect(mockWatcher.Alerts.deleteById).not.toHaveBeenCalled(); + expect(result).toContain('Deleted 5 alert(s).'); + }); + + it('should fall back to search and delete-by-id when DELETE rejects decision_type', async () => { + const tool = alertTools.find((t) => t.name === 'delete_alerts')!; + mockWatcher.Alerts.delete.mockRejectedValueOnce( + Object.assign(new Error("filter parameter 'decision_type' is unknown"), { code: 500 }) + ); + mockWatcher.Alerts.search.mockResolvedValue([{ id: 7, decisions: [{ type: 'ban', origin: 'cscli' }] }]); + + const result = await tool.handler({ type: 'Ban', since: '4h', confirm: true }, mockCtx); + + expect(mockWatcher.Alerts.search).toHaveBeenCalledWith(expect.objectContaining({ decision_type: 'ban', since: '4h' })); + expect(mockWatcher.Alerts.deleteById).toHaveBeenCalledWith('7'); expect(result).toContain('Deleted 1 alert(s).'); }); + it('should skip fallback alerts that do not match the decision type', async () => { + const tool = alertTools.find((t) => t.name === 'delete_alerts')!; + mockWatcher.Alerts.delete.mockRejectedValueOnce( + Object.assign(new Error("filter parameter 'decision_type' is unknown"), { code: 500 }) + ); + mockWatcher.Alerts.search.mockResolvedValue([ + { id: 7, decisions: [{ type: 'ban', origin: 'cscli' }] }, + { id: 8, decisions: [{ type: 'captcha', origin: 'cscli' }] } + ]); + + const result = await tool.handler({ type: 'Ban', since: '4h', confirm: true }, mockCtx); + + expect(mockWatcher.Alerts.deleteById).toHaveBeenCalledTimes(1); + expect(mockWatcher.Alerts.deleteById).toHaveBeenCalledWith('7'); + expect(result).toContain('Deleted 1 alert(s).'); + }); + + it('should not match type and origin on different decisions', async () => { + const tool = alertTools.find((t) => t.name === 'delete_alerts')!; + mockWatcher.Alerts.delete.mockRejectedValueOnce( + Object.assign(new Error("filter parameter 'decision_type' is unknown"), { code: 500 }) + ); + mockWatcher.Alerts.search.mockResolvedValue([ + { + id: 7, + decisions: [ + { type: 'ban', origin: 'cscli' }, + { type: 'captcha', origin: 'crowdsec' } + ] + } + ]); + + await tool.handler({ type: 'Ban', origin: 'crowdsec', confirm: true }, mockCtx); + + expect(mockWatcher.Alerts.deleteById).not.toHaveBeenCalled(); + }); + + it('should not fall back for an unrelated delete failure', async () => { + const tool = alertTools.find((t) => t.name === 'delete_alerts')!; + mockWatcher.Alerts.delete.mockRejectedValueOnce(Object.assign(new Error('database is down'), { code: 500 })); + + await expect(tool.handler({ type: 'Ban', since: '4h', confirm: true }, mockCtx)).rejects.toThrow('database is down'); + expect(mockWatcher.Alerts.search).not.toHaveBeenCalled(); + }); + it('should require confirm for time-only deletes', async () => { const tool = alertTools.find((t) => t.name === 'delete_alerts')!; @@ -628,7 +726,7 @@ describe('alertTools', () => { expect(mockWatcher.Alerts.search).toHaveBeenCalledWith( expect.objectContaining({ - ip: '198.51.100.0/24', + range: '198.51.100.0/24', contains: false, limit: 0 }) diff --git a/packages/crowdsec-mcp/tests/tools/allowlists.test.ts b/packages/crowdsec-mcp/tests/tools/allowlists.test.ts index 75c85634d..d92805455 100644 --- a/packages/crowdsec-mcp/tests/tools/allowlists.test.ts +++ b/packages/crowdsec-mcp/tests/tools/allowlists.test.ts @@ -75,7 +75,7 @@ describe('allowlistTools', () => { const result = (await findTool('list_allowlists').handler({ limit: 10 }, mockCtx)) as string; - expect(mockAllowlists.list).toHaveBeenCalledWith(); + expect(mockAllowlists.list).toHaveBeenCalledWith(true); expect(result).toContain('| Name'); expect(result).toContain('Description'); expect(result).toContain('Created at'); @@ -96,7 +96,19 @@ describe('allowlistTools', () => { await findTool('list_allowlists').handler({}, mockCtx); - expect(mockAllowlists.list).toHaveBeenCalledWith(); + expect(mockAllowlists.list).toHaveBeenCalledWith(true); + }); + + it('should skip item transfer with with_content=false and show an unknown size', async () => { + // The LAPI returns an empty items array (not undefined) when + // with_content=false, so the formatter must rely on the flag. + mockAllowlists.list.mockResolvedValue([makeAllowlist(0, { name: 'al1', description: 'd', items: [] })]); + + const result = (await findTool('list_allowlists').handler({ with_content: false }, mockCtx)) as string; + + expect(mockAllowlists.list).toHaveBeenCalledWith(false); + expect(result).toContain('al1'); + expect(result).toMatch(/\| -\s+\|/); }); it('should truncate rows to the requested limit and hint at hidden rows', async () => { diff --git a/packages/crowdsec-mcp/tests/tools/decisions.test.ts b/packages/crowdsec-mcp/tests/tools/decisions.test.ts index 62d583538..78987369b 100644 --- a/packages/crowdsec-mcp/tests/tools/decisions.test.ts +++ b/packages/crowdsec-mcp/tests/tools/decisions.test.ts @@ -1,8 +1,10 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { FeatureNotSupportedError, LapiCapability } from 'crowdsec-client'; import { decisionTools } from '../../src/tools/decisions.js'; describe('decisionTools', () => { const createMockWatcher = () => ({ + supports: vi.fn(), Alerts: { search: vi.fn(), pushAlerts: vi.fn() @@ -131,15 +133,120 @@ describe('decisionTools', () => { const result = await tool!.handler({ limit: 10 }, ctx as any); expect(ctx.bouncer!.Decisions.search).toHaveBeenCalledWith( - expect.not.objectContaining({ - limit: expect.anything() + expect.objectContaining({ + simulated: true }) ); + expect(ctx.bouncer!.Decisions.search.mock.calls[0][0]).not.toHaveProperty('limit'); + expect(ctx.bouncer!.Decisions.search.mock.calls[0][0]).not.toHaveProperty('contains'); expect(result).toContain('ban'); expect(result).toContain('1.2.3.4'); expect(result).not.toContain('never'); }); + it('should reject since/until without watcher credentials instead of ignoring them', async () => { + const ctx = createMockContext({ mode: 'bouncer', watcher: undefined, bouncer: createMockBouncer() }); + const tool = findTool('list_decisions')!; + + await expect(tool.handler({ since: '24h' }, ctx as any)).rejects.toThrow(/since\/until filter alerts/); + await expect(tool.handler({ until: '1h' }, ctx as any)).rejects.toThrow(/since\/until filter alerts/); + expect(ctx.bouncer!.Decisions.search).not.toHaveBeenCalled(); + }); + + it('should ask the bouncer to include simulated decisions by default', async () => { + const ctx = createMockContext({ mode: 'bouncer', watcher: undefined, bouncer: createMockBouncer() }); + ctx.bouncer!.Decisions.search.mockResolvedValue([ + { id: 1, type: 'ban', scope: 'Ip', value: '1.1.1.1', origin: 'cscli', duration: '4h', simulated: true }, + { id: 2, type: 'ban', scope: 'Ip', value: '2.2.2.2', origin: 'cscli', duration: '4h', simulated: false } + ]); + + const result = await findTool('list_decisions')!.handler({}, ctx as any); + + expect(ctx.bouncer!.Decisions.search).toHaveBeenCalledWith(expect.objectContaining({ simulated: true })); + expect(result).toContain('1.1.1.1'); + expect(result).toContain('2.2.2.2'); + }); + + it('should ask the bouncer to exclude simulated decisions with no_simulated=true', async () => { + const ctx = createMockContext({ mode: 'bouncer', watcher: undefined, bouncer: createMockBouncer() }); + ctx.bouncer!.Decisions.search.mockResolvedValue([ + { id: 2, type: 'ban', scope: 'Ip', value: '2.2.2.2', origin: 'cscli', duration: '4h', simulated: false } + ]); + + const result = await findTool('list_decisions')!.handler({ no_simulated: true }, ctx as any); + + expect(ctx.bouncer!.Decisions.search).toHaveBeenCalledWith(expect.objectContaining({ simulated: false })); + expect(result).toContain('2.2.2.2'); + }); + + it('should include simulated decisions on the watcher path by default', async () => { + const ctx = createMockContext(); + ctx.watcher!.Alerts.search.mockResolvedValue([]); + + await findTool('list_decisions')!.handler({}, ctx as any); + + expect(ctx.watcher!.Alerts.search).toHaveBeenCalledWith(expect.objectContaining({ simulated: true })); + }); + + it('should retry without simulated when the LAPI rejects the alert filter', async () => { + const ctx = createMockContext(); + ctx.watcher!.Alerts.search.mockRejectedValueOnce( + Object.assign(new Error("'simulated' doesn't exist: invalid filter"), { code: 500 }) + ).mockResolvedValueOnce([]); + + await findTool('list_decisions')!.handler({}, ctx as any); + + expect(ctx.watcher!.Alerts.search).toHaveBeenCalledTimes(2); + expect(ctx.watcher!.Alerts.search.mock.calls[1][0]).not.toHaveProperty('simulated'); + }); + + it('should not widen no_simulated when the LAPI rejects the alert filter', async () => { + const ctx = createMockContext(); + ctx.watcher!.Alerts.search.mockRejectedValueOnce( + Object.assign(new Error("'simulated' doesn't exist: invalid filter"), { code: 500 }) + ); + + await expect(findTool('list_decisions')!.handler({ no_simulated: true }, ctx as any)).rejects.toThrow(/invalid filter/); + expect(ctx.watcher!.Alerts.search).toHaveBeenCalledTimes(1); + }); + + it('should report the simulation state as unknown when the bouncer omits the field', async () => { + const ctx = createMockContext({ mode: 'bouncer', watcher: undefined, bouncer: createMockBouncer() }); + ctx.bouncer!.Decisions.search.mockResolvedValue([ + // `/v1/decisions` does not return `simulated`: it must not be + // reported as `no`. + { id: 3, type: 'ban', scope: 'Ip', value: '3.3.3.3', origin: 'cscli', duration: '4h' } + ]); + + const result = await findTool('list_decisions')!.handler({}, ctx as any); + const row = result.split('\n').find((line) => line.includes('3.3.3.3')); + + expect(row).toBeDefined(); + expect(row!.trimEnd()).toMatch(/\|\s*-\s*\|$/); + }); + + it('should fall back to the watcher when the bouncer search fails', async () => { + const ctx = createMockContext({ bouncer: createMockBouncer() }); + ctx.bouncer!.Decisions.search.mockRejectedValue(new Error('bouncer down')); + ctx.watcher!.Alerts.search.mockResolvedValue(makeDecisionAlerts(1)); + + const result = await findTool('list_decisions')!.handler({}, ctx as any); + + expect(ctx.bouncer!.Decisions.search).toHaveBeenCalled(); + expect(ctx.watcher!.Alerts.search).toHaveBeenCalled(); + expect(result).toContain('198.51.100.1'); + }); + + it('should use the watcher for scope queries even when a bouncer is configured', async () => { + const ctx = createMockContext({ bouncer: createMockBouncer() }); + ctx.watcher!.Alerts.search.mockResolvedValue([]); + + await findTool('list_decisions')!.handler({ scope: 'Country', value: 'FR' }, ctx as any); + + expect(ctx.bouncer!.Decisions.search).not.toHaveBeenCalled(); + expect(ctx.watcher!.Alerts.search).toHaveBeenCalledWith(expect.objectContaining({ scope: 'Country', value: 'FR' })); + }); + it('should normalize scope and value before querying the LAPI', async () => { const ctx = createMockContext(); ctx.watcher!.Alerts.search.mockResolvedValue([]); @@ -152,6 +259,7 @@ describe('decisionTools', () => { value: '1.2.3.4' }) ); + expect(ctx.watcher!.Alerts.search.mock.calls[0][0]).not.toHaveProperty('contains'); }); it('should hide expired decisions', async () => { @@ -423,6 +531,7 @@ describe('decisionTools', () => { expect(result).toContain('### Decision #123'); expect(result).toContain('1.2.3.4'); expect(result).toContain('Alert #10'); + expect(ctx.watcher!.Alerts.search).toHaveBeenCalledWith(expect.objectContaining({ simulated: true })); }); it('should reject unknown decision ids', async () => { @@ -439,6 +548,35 @@ describe('decisionTools', () => { 'decision id must be a positive integer' ); }); + + it('should fall back to the bouncer decision list without watcher credentials', async () => { + const ctx = createMockContext({ watcher: undefined, bouncer: createMockBouncer() }); + ctx.bouncer!.Decisions.search.mockResolvedValue([ + { + id: 123, + type: 'ban', + scope: 'Ip', + value: '1.2.3.4', + origin: 'cscli', + scenario: 'test', + duration: '1h', + simulated: false + } + ]); + + const result = await findTool('get_decision')!.handler({ id: 123 }, ctx as any); + + expect(ctx.bouncer!.Decisions.search).toHaveBeenCalledWith({ simulated: true }); + expect(result).toContain('### Decision #123'); + expect(result).toContain('1.2.3.4'); + }); + + it('should report a missing decision when the bouncer list has no match', async () => { + const ctx = createMockContext({ watcher: undefined, bouncer: createMockBouncer() }); + ctx.bouncer!.Decisions.search.mockResolvedValue([]); + + await expect(findTool('get_decision')!.handler({ id: 999 }, ctx as any)).rejects.toThrow('Decision 999 not found'); + }); }); describe('ban_ip', () => { @@ -475,6 +613,28 @@ describe('decisionTools', () => { ); }); + it('should not block a ban when the allowlist route is missing (LAPI < 1.6.6)', async () => { + const ctx = createMockContext(); + ctx.watcher!.Alerts.pushAlerts.mockResolvedValue(['alert-123']); + ctx.allowlists.check.mockRejectedValue(Object.assign(new Error('not found'), { code: 404 })); + + const result = await findTool('ban_ip')!.handler({ ip: '1.2.3.4' }, ctx as any); + + expect(result).toContain('1.2.3.4'); + expect(ctx.watcher!.Alerts.pushAlerts).toHaveBeenCalled(); + }); + + it('should not block a ban when the allowlist capability is known unsupported', async () => { + const ctx = createMockContext(); + ctx.watcher!.Alerts.pushAlerts.mockResolvedValue(['alert-123']); + ctx.allowlists.check.mockRejectedValue(new FeatureNotSupportedError(LapiCapability.allowlists, '1.6.6')); + + const result = await findTool('ban_ip')!.handler({ ip: '1.2.3.4' }, ctx as any); + + expect(result).toContain('1.2.3.4'); + expect(ctx.watcher!.Alerts.pushAlerts).toHaveBeenCalled(); + }); + it('should use range as scope Range when provided', async () => { const ctx = createMockContext(); ctx.watcher!.Alerts.pushAlerts.mockResolvedValue(['alert-123']); @@ -776,6 +936,46 @@ describe('decisionTools', () => { await expect(tool!.handler({ all: true }, ctx as any)).rejects.toThrow('Deleting all decisions requires confirm=true'); }); + it('should require confirm=true for a /0 range', async () => { + const ctx = createMockContext(); + const tool = findTool('unban_ip'); + + await expect(tool!.handler({ range: '0.0.0.0/0' }, ctx as any)).rejects.toThrow(/requires confirm=true/); + expect(ctx.watcher!.Decisions.delete).not.toHaveBeenCalled(); + }); + + it('should require confirm=true for a /0 value with scope=Range', async () => { + const ctx = createMockContext(); + const tool = findTool('unban_ip'); + + await expect(tool!.handler({ scope: 'Range', value: '0.0.0.0/0' }, ctx as any)).rejects.toThrow(/requires confirm=true/); + expect(ctx.watcher!.Decisions.delete).not.toHaveBeenCalled(); + }); + + it('should require confirm=true for a padded /0 value with scope=Range', async () => { + const ctx = createMockContext(); + const tool = findTool('unban_ip'); + + await expect(tool!.handler({ scope: 'Range', value: ' 0.0.0.0/0 ' }, ctx as any)).rejects.toThrow(/requires confirm=true/); + expect(ctx.watcher!.Decisions.delete).not.toHaveBeenCalled(); + }); + + it('should require confirm=true when ip is empty and only a type is set', async () => { + const ctx = createMockContext(); + const tool = findTool('unban_ip'); + + await expect(tool!.handler({ ip: '', type: 'ban' }, ctx as any)).rejects.toThrow(/requires confirm=true/); + expect(ctx.watcher!.Decisions.delete).not.toHaveBeenCalled(); + }); + + it('should reject a non-canonical /00 range', async () => { + const ctx = createMockContext(); + const tool = findTool('unban_ip'); + + await expect(tool!.handler({ range: '0.0.0.0/00' }, ctx as any)).rejects.toThrow(/not a valid range/); + expect(ctx.watcher!.Decisions.delete).not.toHaveBeenCalled(); + }); + it('should delete all active decisions when all=true and confirm=true', async () => { const ctx = createMockContext(); ctx.watcher!.Alerts.search.mockResolvedValue([ @@ -790,6 +990,7 @@ describe('decisionTools', () => { expect(result).toContain('2 decision(s) deleted'); expect(ctx.watcher!.Decisions.deleteById).toHaveBeenCalledTimes(2); expect(ctx.watcher!.Decisions.delete).not.toHaveBeenCalled(); + expect(ctx.watcher!.Alerts.search).toHaveBeenCalledWith(expect.objectContaining({ simulated: true })); }); it('should reject scope without value', async () => { @@ -850,26 +1051,21 @@ describe('decisionTools', () => { await expect(tool!.handler({ id: '123' }, ctx as any)).rejects.toThrow('Decision 123 not found'); }); - it('should delete decisions contained in a range through a search', async () => { + it('should delete decisions contained in a range with the server-side filter', async () => { const ctx = createMockContext(); - ctx.watcher!.Alerts.search.mockResolvedValue([ - { id: 1, decisions: [{ id: 11 }] }, - { id: 2, decisions: [{ id: 12 }] } - ]); - ctx.watcher!.Decisions.deleteById.mockResolvedValue({ nbDeleted: '1' }); + ctx.watcher!.Decisions.delete.mockResolvedValue({ nbDeleted: '2' }); const tool = findTool('unban_ip'); const result = await tool!.handler({ range: '198.51.100.0/24' }, ctx as any); - expect(ctx.watcher!.Alerts.search).toHaveBeenCalledWith( + expect(ctx.watcher!.Decisions.delete).toHaveBeenCalledWith( expect.objectContaining({ - ip: '198.51.100.0/24', - contains: false, - has_active_decision: true, - limit: 0 + range: '198.51.100.0/24', + contains: false }) ); - expect(ctx.watcher!.Decisions.deleteById).toHaveBeenCalledTimes(2); + expect(ctx.watcher!.Alerts.search).not.toHaveBeenCalled(); + expect(ctx.watcher!.Decisions.deleteById).not.toHaveBeenCalled(); expect(result).toContain('2 decision(s) deleted'); }); @@ -884,11 +1080,73 @@ describe('decisionTools', () => { expect(ctx.watcher!.Decisions.delete).toHaveBeenCalledWith( expect.objectContaining({ ip: '1.2.3.4', - type: 'ban' + type: 'ban', + contains: false }) ); }); + it('should forward type and scenario to the server-side range filter', async () => { + const ctx = createMockContext(); + ctx.watcher!.Decisions.delete.mockResolvedValue({ nbDeleted: '1' }); + const tool = findTool('unban_ip'); + + const result = await tool!.handler({ range: '198.51.100.0/24', type: 'ban', scenario: 'ssh-bf' }, ctx as any); + + expect(ctx.watcher!.Decisions.delete).toHaveBeenCalledWith( + expect.objectContaining({ + range: '198.51.100.0/24', + contains: false, + type: 'ban', + scenario: 'ssh-bf' + }) + ); + expect(ctx.watcher!.Alerts.search).not.toHaveBeenCalled(); + expect(ctx.watcher!.Decisions.deleteById).not.toHaveBeenCalled(); + expect(result).toContain('1 decision(s) deleted'); + }); + + it('should not delete decisions the fallback filter did not target', async () => { + const ctx = createMockContext(); + ctx.watcher!.Decisions.delete.mockRejectedValue( + Object.assign(new Error("'scenario' doesn't exist: invalid filter"), { code: 500 }) + ); + ctx.watcher!.Alerts.search.mockResolvedValue([ + { + id: 1, + decisions: [ + { id: 11, type: 'ban', scope: 'Ip', value: '1.2.3.4', scenario: 'ssh-bf' }, + { id: 12, type: 'captcha', scope: 'Ip', value: '1.2.3.4', scenario: 'ssh-bf' }, + { id: 13, type: 'ban', scope: 'Ip', value: '5.6.7.8', scenario: 'ssh-bf' }, + { id: 14, type: 'ban', scope: 'Ip', value: '1.2.3.4', scenario: 'other' }, + // Missing scope must not be defaulted to Ip. + { id: 15, type: 'ban', value: '1.2.3.4', scenario: 'ssh-bf' } + ] + } + ]); + ctx.watcher!.Decisions.deleteById.mockResolvedValue({ nbDeleted: '1' }); + const tool = findTool('unban_ip'); + + const result = await tool!.handler({ ip: '1.2.3.4', type: 'ban', scenario: 'ssh-bf' }, ctx as any); + + expect(ctx.watcher!.Decisions.deleteById).toHaveBeenCalledTimes(1); + expect(ctx.watcher!.Decisions.deleteById).toHaveBeenCalledWith('11'); + expect(result).toContain('1 decision(s) deleted'); + }); + + it('should refuse the search fallback when contains is known unsupported', async () => { + const ctx = createMockContext(); + ctx.watcher!.supports.mockReturnValue(false); + ctx.watcher!.Decisions.delete.mockRejectedValue( + Object.assign(new Error("'contains' doesn't exist: invalid filter"), { code: 500 }) + ); + const tool = findTool('unban_ip'); + + await expect(tool!.handler({ ip: '1.2.3.4' }, ctx as any)).rejects.toThrow(/contains filter requires CrowdSec 1\.0\.3/); + expect(ctx.watcher!.Alerts.search).not.toHaveBeenCalled(); + expect(ctx.watcher!.Decisions.deleteById).not.toHaveBeenCalled(); + }); + it('should reject unknown unban parameters', async () => { const ctx = createMockContext(); const tool = findTool('unban_ip'); @@ -940,7 +1198,7 @@ describe('decisionTools', () => { await tool!.handler({ scope: 'Ip', value: '1.2.3.4', type: 'Ban', scenario: 'test' }, ctx as any); const query = ctx.watcher!.Decisions.delete.mock.calls[0][0]; - expect(query).toMatchObject({ ip: '1.2.3.4', type: 'ban', scenario: 'test' }); + expect(query).toMatchObject({ ip: '1.2.3.4', type: 'ban', scenario: 'test', contains: false }); expect(query).not.toHaveProperty('scope'); expect(query).not.toHaveProperty('value'); }); @@ -954,10 +1212,11 @@ describe('decisionTools', () => { expect(ctx.watcher!.Decisions.delete).toHaveBeenCalledWith( expect.objectContaining({ - scope: 'Country', + scopes: 'Country', value: 'DE' }) ); + expect(ctx.watcher!.Decisions.delete.mock.calls[0][0]).not.toHaveProperty('scope'); expect(ctx.watcher!.Alerts.search).not.toHaveBeenCalled(); expect(result).toContain('1 decision(s) deleted'); }); diff --git a/packages/crowdsec-mcp/tests/utils.test.ts b/packages/crowdsec-mcp/tests/utils.test.ts index eb4843845..fb1770077 100644 --- a/packages/crowdsec-mcp/tests/utils.test.ts +++ b/packages/crowdsec-mcp/tests/utils.test.ts @@ -2,9 +2,11 @@ import { describe, expect, it } from 'vitest'; import { assertValidScopeValue, formatDuration, + isTotalCidr, isValidCidr, isValidIp, isValidTimeFilter, + mapWithConcurrency, normalizeScope, parseDuration, splitList, @@ -101,4 +103,29 @@ describe('utils', () => { expect(splitList('')).toBeUndefined(); expect(splitList(undefined)).toBeUndefined(); }); + + it('detects total ranges and rejects non-canonical prefixes', () => { + expect(isTotalCidr('0.0.0.0/0')).toBe(true); + expect(isTotalCidr('::/0')).toBe(true); + expect(isTotalCidr('10.0.0.0/8')).toBe(false); + // Go normalises /00 to /0, which would bypass the confirm gate. + expect(isValidCidr('0.0.0.0/00')).toBe(false); + expect(isValidCidr('0.0.0.0/0')).toBe(true); + }); + + it('stops scheduling work after the first failure', async () => { + const seen: number[] = []; + + await expect( + mapWithConcurrency([1, 2, 3, 4], 2, async (item) => { + seen.push(item); + if (item === 1) { + throw new Error('boom'); + } + return item; + }) + ).rejects.toThrow('boom'); + + expect(seen.length).toBeLessThan(4); + }); }); diff --git a/readme.md b/readme.md index f36ab79e4..7e4124b22 100644 --- a/readme.md +++ b/readme.md @@ -17,9 +17,19 @@ This repository hosts several packages, listed below with examples. - [Guides and usage documentation](https://github.com/thib3113/node-crowdsec/wiki): authentication, bouncer/watcher setup, performance notes and the glossary. - [API reference](https://thib3113.github.io/node-crowdsec/): generated technical documentation (Typedoc). +- [CrowdSec API compatibility](./docs/api-compatibility.md): LAPI version matrix, failure modes and fallbacks. - [AI agent setup guide](./docs/agent-setup-guide.md): configure the HTTP middleware with an AI agent. - [llms.txt](./llms.txt): index for agents and LLM tooling. +## For LLMs + +Give this to your agent: + +> Read and follow the links for the package you need. Do not ask for credentials: list the environment variables to set. Explain the security impact before enabling write tools. + +`llms.txt` indexes the raw README, compatibility matrix and setup guide for each +package. Wiki pages are for humans only. + ## Features - **Full CrowdSec client** : watcher & bouncer clients for the CrowdSec LAPI @@ -31,10 +41,12 @@ This repository hosts several packages, listed below with examples. background, closing the freshness gap of the stream poll. A malicious unknown IP passes at most once. - **Configurable trust scope** : `subnetLevel` lets you choose how far up the - prefix hierarchy to consider as malicious (`resident` / `company` / `country`), - so a whole country block is never banned by accident. -- **Watcher scenarios** : bundled scenarios (user-agent, ip-extraction...) to - detect and alert on malicious requests, with a pluggable scenario system. + prefix hierarchy to consider as malicious (`resident` / `company` / `country`, + or `/128` / `/120` / `/112` for IPv6), so a whole country block is never + banned by accident. +- **Watcher scenarios** : bundled IP-extraction (`X-Forwarded-For`) and MaxMind + enrichment scenarios to detect and alert on malicious requests, with a + pluggable scenario system. - **MCP server** : expose decisions, alerts and allowlists to an LLM through the Model Context Protocol, read-only by default.