Skip to content

Latest commit

 

History

History
455 lines (345 loc) · 42 KB

API.md

File metadata and controls

455 lines (345 loc) · 42 KB

CrowdSec Web UI API

All HTTP API routes return JSON unless a route explicitly redirects for OIDC login/callback. Routes are served below /api, or below the configured server.basePath when set. GET /api/health is always registered at the root path and below the configured base path.

API request bodies are limited to 1 MiB. Browser requests using state-changing methods must be same-origin; non-browser clients that do not send Origin or Sec-Fetch-Site remain supported. API responses are marked private, no-store.

The browser UI authenticates with the HTTP-only crowdsec_web_ui_session cookie. There is no bearer-token API in this codebase. Authentication is enabled for new installs by default; migrated databases from older unauthenticated versions retain their prior state until auth.enabled is explicitly configured. When auth is enabled, protected API routes return 401 without a valid session.

Protected application routes also ensure the backend can authenticate to CrowdSec LAPI. If LAPI login fails, they return 502.

ui.readOnly: true or a read-only user role blocks enforcement and management writes. Blocked requests return:

{ "error": "Read-only mode is enabled", "code": "READ_ONLY" }

Read-only mode still allows user preferences and notification read-state writes.

Common Behavior

Pagination

Alert and decision list pagination uses page and page_size and is enabled only when page is present. Notification lists are always paginated and default to the first page.

  • page defaults to 1 and is clamped to at least 1.
  • page_size defaults to 50 and is clamped from 10 to 200.
  • For high-volume alert and decision lists, selectable_ids contains IDs for the returned page only. Use additional pages to expand the loaded selection set.
  • With multiple instances, responses also include selectable_refs entries containing both instance_id and the upstream record id.
  • Paginated responses use:
{
  "data": [],
  "pagination": {
    "page": 1,
    "page_size": 50,
    "total": 0,
    "total_pages": 0,
    "unfiltered_total": 0
  },
  "selectable_ids": [],
  "selectable_refs": []
}

selectable_refs is omitted for single-instance deployments.

Search and Filters

GET /api/alerts and GET /api/decisions support a structured q search when paginated. Search supports free text, quoted phrases, AND, OR, NOT, -, grouping, field matching with :, exact matching with =, inequality with <>, and date comparisons with <, <=, >, >=.

: performs a case-insensitive contains match and = matches the complete normalized field value. The browser's Quick Filters use exact = predicates for selected facet values, so a selection such as target=tausend.me does not also match bw.tausend.me. Multiple selected values are joined with OR; exclusions use <>.

Alert search fields: id, instance, scenario, kind, message, ip/source, country, region, city, as, target, date/created/created_at/time, sim/simulation, machine, origin, decision/decisions.

Use a quoted empty value to match an empty field, such as origin:"". Use origin<>"" or -origin:"" to require a non-empty value.

Decision search fields: id, instance, alert/alert_id, scenario/reason, kind, message, ip/value, country, region, city, as, target, date/created/created_at/time, action, type, status, duplicate, sim/simulation, machine, origin. Decision kind and message are inherited from the linked alert. Decision free text also matches the linked alert's message.

Date range filters use dateStart and dateEnd. Use YYYY-MM-DD for day buckets or values containing T for hour-level comparisons. tz_offset is an offset in minutes; browser_tz accepts an IANA timezone. They control local bucket comparisons when the server has no fixed timezone configured.

Multiple Instances

  • instance=<instance-id> selects one instance for paginated Alerts, Decisions, and Dashboard requests. instance=all, the default, selects the Combined scope.
  • Single-record routes without an instance are available only when one instance is configured. Multi-instance deployments use the instance-qualified routes below.
  • Bulk deletion uses refs: [{ "instance_id": "primary", "id": 42 }]. Plain ids requests are rejected when multiple instances are configured.
  • Decision creation and cleanup accept scope: "all" or scope: "instance". The latter also requires instance_id; omitting scope targets the primary instance.
  • Multi-instance writes return per-instance results, succeeded, and failed. Partial success returns HTTP 207.

Saved and Recent Search Filters

Saved and recent filter queries are stored in SQLite for the current session user. When authentication is disabled, all clients share one installation-wide list. Read-only users may manage their own filters. Queries are validated against the alert or decision search syntax before storage; each page only applies queries compatible with its search.

Method Endpoint Description
GET /api/search-filters Return { saved, recent, shared } for the current owner.
POST /api/search-filters/saved Create a named filter with { "name": string, "query": string }; returns the entry. Names are unique per owner (case-insensitive).
PATCH /api/search-filters/saved/:id Rename an owned filter with { "name": string }.
DELETE /api/search-filters/saved/:id Delete an owned filter.
POST /api/search-filters/recent Record a used query with { "query": string }; returns the latest five distinct queries.
DELETE /api/search-filters/recent Clear the current owner's recent queries.

Names are limited to 80 characters, queries to 4096 characters, and named filters to 100 per owner. Invalid input returns 400, duplicate names or a full named list return 409, and missing or unowned IDs return 404.

Health

Method Endpoint Description
GET /api/health Public health check returning { "status": "ok" }.

Auth

These routes are mounted below /api/auth. Auth setup/login routes are available without a session so onboarding and login can work.

Method Endpoint Description
GET /api/auth/status Auth state, setup status, current user/session state, OIDC availability, passkey availability, and password-login state. oidcAutoLogin is true when the login page should redirect straight to the identity provider. preferences holds the language and font the signed-in user saved.
POST /api/auth/setup Create the first admin user and start a session. Requires username and password; only works before any auth user exists.
POST /api/auth/login Password login with username and password. Accounts with TOTP enabled also require totpCode; missing or invalid codes return requiresTotp: true.
POST /api/auth/logout Clear the session cookie. SSO sessions may return a provider redirectUrl for RP-initiated logout.
GET /api/auth/me Current authenticated session user.
GET /api/auth/settings Auth settings visible to the current user. Non-admin sessions only receive their own hasPassword, passkeysAvailable, totpEnabled, and authMethod; administrators also receive the OIDC settings metadata and password-login state. passwordLoginManaged is true when auth.passwordLogin.enabled is set; passwordLoginFallback is true when the configuration disables password login but it stays enabled because neither OIDC nor an administrator passkey is configured. oidcAutoLogin is the saved auto-login setting; oidcAutoLoginActive is false while it lacks a configured OIDC provider or disabled password login. managedSettings maps each field that the application config locks, such as oidcClientId or disablePasswordLogin, to { path, env? }: its config path and, when a CONFIG_* variable sets it, that variable's name.
PUT /api/auth/settings Admin-only auth settings update. Can disable password login and configure OIDC issuer, client ID, client secret, scopes, groups claim, admin groups, read-only groups, unmatched-user policy, whether logout also ends the identity provider session, back-channel logout, OIDC auto-login, and linking by username (oidcAutoLinkUsername). Returns 409 with code: "MANAGED_BY_CONFIG" when the body changes password login or an OIDC field that the application config sets.
POST /api/auth/change-password Change the current user's password. The user must be logged in with password auth. The new password must differ from the current one. Clears a pending password change.
GET /api/auth/users Admin-only list of users with id, username, role, source (local or oidc), disabled, passwordChangeRequired, totpEnabled, passkeyCount, oidcLink (the linked SSO identity and its role, which is null after the provider denied it, or null), createdAt, and current (the signed-in user).
POST /api/auth/users Admin-only. Create a local user with username, password, role (admin or read-only), and optional requirePasswordChange (default true). Returns 201, or 409 when the username exists.
PATCH /api/auth/users/:id Admin-only. Change a local user's role and/or disabled state. Disabling ends the user's sessions.
POST /api/auth/users/:id/password Admin-only. Set a local user's password with password and optional requirePasswordChange (default true). Ends the user's sessions.
POST /api/auth/users/:id/reset-mfa Admin-only. Remove a local user's TOTP enrollment and passkeys and end their sessions.
POST /api/auth/users/:id/unlink-oidc Admin-only. Remove the user's linked SSO identity and end their sessions. Returns 400 for your own account and when this would remove the last administrator access.
DELETE /api/auth/users/:id Admin-only. Delete a local or OIDC user with their passkeys and saved search filters.
POST /api/auth/totp/setup Start TOTP enrollment for the current password-authenticated user. Returns a base32 secret and otpauth:// URI for QR setup.
POST /api/auth/totp/enable Complete TOTP enrollment with { "code": "123456" }.
DELETE /api/auth/totp Disable Settings-enrolled TOTP for the current password-authenticated user with { "currentPassword": "..." }. TOTP supplied through auth.totpSeed remains deployment-managed and cannot be disabled through the API.
GET /api/auth/passkeys List passkeys for the current user.
PATCH /api/auth/passkeys/:id Rename a passkey with { "name": "..." }.
DELETE /api/auth/passkeys/:id Delete one of the current user's passkeys.
POST /api/auth/webauthn/register/options Start passkey registration for the current password-backed user. OIDC-only accounts receive 403.
POST /api/auth/webauthn/register/verify Complete passkey registration. Optional name is stored as the passkey label. OIDC-only accounts receive 403.
POST /api/auth/webauthn/login/options Start passkey login. Optional username narrows allowed credentials.
POST /api/auth/webauthn/login/verify Complete passkey login and start a session.
GET /api/auth/oidc/login Redirect to the configured OIDC provider.
GET /api/auth/oidc/callback OIDC callback handler; creates or updates the OIDC user session and redirects to the UI. For a link started with /api/auth/oidc/link/start it holds the identity without changing anything and redirects to /settings?oidcLink=<outcome>.
GET /api/auth/oidc/link SSO link state of the current account: available, canManage, username, totpEnabled, passwordLoginDisabled, link (with role, null after the provider denied the identity, and provider: current, changed, or unavailable, from a discovery check with a 5-second timeout whose result is reused for 30 seconds), and pending (an identity waiting for confirmation, with the id to confirm it by).
POST /api/auth/oidc/link/start Start linking an SSO identity from a password or passkey session. Returns the provider redirectUrl, or 502 when the provider cannot be reached.
POST /api/auth/oidc/link/confirm Link the waiting identity after verifying password and, if enabled, totpCode. confirmationId must be the pending.id that was shown; otherwise, such as after a newer attempt in another tab, it returns 409 with code: "OIDC_LINK_CHANGED" and links nothing. Merges a separate SSO account of the identity. Password or passkey session only.
DELETE /api/auth/oidc/link Unlink the SSO identity after verifying password and, if enabled, totpCode. Password or passkey session only.
POST /api/auth/oidc/backchannel-logout OpenID Connect Back-Channel Logout endpoint for the identity provider. Accepts a form-encoded logout_token, ends the matching dashboard sessions (sid takes precedence over sub; with both, the user's sessions without a stored sid end too), and returns 200. Duplicate issuer/jti notifications return 200 without repeating revocation; invalid tokens, or requests while auth.oidc.backchannelLogout is off (the default), return 400 with error: "invalid_request".

User management rejects changes to the signed-in user's own account and to OIDC users other than deletion with 400, changes that would leave no active administrator with 400, non-admin sessions with 403, and writes in ui.readOnly mode with 403 and code: "READ_ONLY". While a password session has a pending password change, /api/auth/status returns passwordChangeRequired: true and other protected APIs return 403 with code: "PASSWORD_CHANGE_REQUIRED" until /api/auth/change-password succeeds. An SSO session on an account with a linked identity uses the SSO role, reports linkedSso: true in user, and receives 403 from the password, TOTP, passkey, and SSO link management routes.

Configuration

Method Endpoint Description
GET /api/config Runtime UI config, LAPI status, sync status, simulation setting, time settings, manual refresh availability, metrics availability, metrics sidebar preference, permissions, each instance's effective manual decision scenarios (manual_decision_scenarios), the configured and Settings-managed scenario lists (manual_decision_scenario_settings), and the settings that the application config locks (managed_settings, mapping refresh_interval and manual_refresh_enabled to { path, env? } like /api/auth/settings).
GET /api/instances Configured instance identities, LAPI and synchronization status, metrics endpoint identities, per-instance overrides, effective manual decision scenarios (manual_decision_scenarios), and aggregate availability.
PUT /api/config/metrics-sidebar Save the metrics sidebar preference. Body: { "visible": true }. With dashboard authentication it is saved for the signed-in user; otherwise for the instance.
PUT /api/config/allowlists-sidebar Save the allowlists sidebar preference. Body: { "visible": true }. With dashboard authentication it is saved for the signed-in user; otherwise for the instance. Editable in read-only mode.
PUT /api/config/statistics-sidebar Save the statistics sidebar preference. Body: { "visible": true }. With dashboard authentication it is saved for the signed-in user; otherwise for the instance. Editable in read-only mode.
PUT /api/config/refresh-interval Update the refresh interval. Body: { "interval": "manual" | "0" | "5s" | "30s" | "1m" | "5m" }. Blocked in read-only mode. Returns 409 with code: "MANAGED_BY_CONFIG" when crowdsec.sync.refreshInterval is set.
PUT /api/config/manual-refresh Enable or disable manual cache refreshes. Body: { "enabled": true }. Blocked in read-only mode. Returns 409 with code: "MANAGED_BY_CONFIG" when crowdsec.sync.manualRefreshEnabled is set.
PUT /api/config/manual-decision-scenarios Replace the scenarios added in Settings. Body: { "scenarios": ["custom/scanner"] }. Entries must look like author/name; manual/web-ui and configured scenarios are ignored; at most 100. They are offered for every instance on top of the configured list. Blocked in read-only mode.
PUT /api/config/language Save language preference. Body: { "language": "browser" } or a supported locale code. With dashboard authentication it is saved for the signed-in user; administrators (and deployments without authentication) also set the instance language used for notification texts.
PUT /api/config/font Save the signed-in user's font preference. Body: { "font": "system" }, "auto", or a font preset ID. Without dashboard authentication the browser keeps the font and nothing is stored.

Branding

Method Endpoint Description
GET /api/branding Unauthenticated branding: { "appName", "defaultAppName", "logoUrl", "logoDarkUrl", "theme" }. logoUrl is null when the default logo is used; logoDarkUrl is null when no dark mode logo is set.
GET /api/branding/logo Unauthenticated custom logo image; 404 when none is configured. Versioned URLs (?v=) are cached as immutable.
GET /api/branding/logo/dark Unauthenticated dark mode logo image; 404 when none is configured. Versioned URLs (?v=) are cached as immutable.
PUT /api/branding Set the application name. Body: { "appName": "Acme SOC" }. An empty name restores the default. Blocked in read-only mode.
PUT /api/branding/logo Upload a custom logo. Body: { "dataUrl": "data:image/png;base64,..." }. Blocked in read-only mode.
DELETE /api/branding/logo Restore the default logo. Blocked in read-only mode.
PUT /api/branding/logo/dark Upload a logo used while the dark theme is active. Body: { "dataUrl": "data:image/png;base64,..." }. Blocked in read-only mode.
DELETE /api/branding/logo/dark Remove the dark mode logo so the main logo is used in both themes. Blocked in read-only mode.
PUT /api/branding/theme Set the colors. Body: { "theme": { "light": { "accent": "#e11d48", "neutral": "slate" }, "dark": { "accent": null, "neutral": null } } }. Blocked in read-only mode.

Names are limited to 60 characters. Logos may be PNG, JPEG, GIF, WebP, or SVG images up to 512 KB; the image type is detected from the file content, and SVG logos are served with a sandboxed Content Security Policy.

Theme colors: accent is a #rrggbb (or #rgb) color from which the full accent palette is generated, and neutral is one of gray, slate, zinc, neutral, or stone. null uses the default; in dark, null uses the light setting instead. Sending all values as null restores the default colors.

Alerts

Method Endpoint Description
GET /api/alerts List synced alerts. Without page, returns an array. With page, returns a paginated response.
GET /api/alerts/facets Return one bounded quick-filter facet across the complete effective alert result set.
GET /api/alerts/sessions List alerts grouped into attack sessions, newest activity first.
GET /api/alerts/:id Fetch alert details, including CrowdSec meta context entries, from CrowdSec LAPI; hydrate with decisions; and apply simulation visibility. :id must be numeric.
GET /api/instances/:instanceId/alerts/:id Fetch an alert from a specific instance.
POST /api/alerts/bulk-delete Immediately hide multiple alerts and durably queue deletion of them and their linked decisions. Body: { "ids": [1, "2"] }. Blocked in read-only mode.
DELETE /api/alerts/:id Immediately hide one alert and durably queue deletion of it and its linked decisions. :id must be numeric. Blocked in read-only mode.
DELETE /api/instances/:instanceId/alerts/:id Delete one alert from a specific instance and its local cache. Blocked in read-only mode.

Supported paginated alert parameters: instance, q, ip, country, scenario, as, date, dateStart, dateEnd, target, simulation, include_decisions, tz_offset, browser_tz.

Free-text q searches include CrowdSec alert context values from meta in addition to the standard alert and event metadata fields.

Alert records expose the most frequent event target as target and the total number of distinct event targets as target_count. Decision list items carry the same values in detail.target and detail.target_count.

simulation accepts all, live, or simulated; unknown values behave like all.

Set include_decisions=false to omit decision hydration from paginated lists or single-instance alert details. Bulk deletion accepts ids in single-instance deployments or instance-qualified refs as described above.

GET /api/alerts/sessions accepts page, page_size, and the filters of the paginated alert endpoint. Filters apply first, then matching alerts from one instance, IP or range, and simulation state join a session until more than 30 minutes separate two consecutive alerts. Alerts with any other source stay in sessions of their own. Each row has key, alert_count, first_seen, last_seen, scenario_groups (per kind, with up to 25 of the most frequent scenarios), scenario_count, targets (the three most frequent), target_count, decision_alert_ids (the newest 500 of its alerts that have decisions, for the alert_id decision filter), and latest, the session's newest alert with decision_summary totals for the session. When a session has more than 2,000 alerts those totals cover its newest 2,000 and decision_summary_partial is true. pagination carries page, page_size, has_more, total_alerts, and unfiltered_total_alerts; there is deliberately no session total, because counting sessions requires reading every matching alert.

Alert facets require field=id|instance|scenario|kind|country|region|city|as|ip|target|machine|origin|decision. The decision facet returns active, expired, and an empty value for alerts without decisions. Facets accept the same filters as the paginated alert endpoint, plus optional case-insensitive search, offset (clamped to 0–500), and limit (default 10, maximum 50). A facet value can include a label; the browser displays that label while applying value as the exact = predicate. Instance and machine facets therefore retain stable IDs while showing configured names or aliases, and search matches both values and labels. Multi-origin and multi-target alerts contribute once to each distinct origin or target bucket. The requested field's own predicates are removed so counts remain disjunctive. Facet requests return 400 for unsupported fields and 504 when their isolated five-second query budget is exhausted.

Decisions

Method Endpoint Description
GET /api/decisions List decisions. Without page, returns an array. With page, returns a paginated response. Active decisions are returned by default.
GET /api/decisions/facets Return one bounded quick-filter facet across the complete effective decision result set.
POST /api/decisions Add a manual CrowdSec decision through LAPI. Body: { "ip": "1.2.3.4", "duration": "4h", "reason": "manual", "type": "ban", "scenario": "manual/web-ui" }. type defaults to ban and accepts ban or captcha; scenario defaults to manual/web-ui and must look like author/name (letters, digits, _, ., -; at most 256 characters); crowdsec.manualDecisions only limits the Web UI form, not this endpoint; optional scope and instance_id select targets. Returns 409 when a target instance allowlists the value, unless bypass_allowlist: true is sent. Blocked in read-only mode.
POST /api/decisions/bulk-add Add the same manual decision for up to 500 IPs or ranges in one LAPI request per target instance. Body: { "values": ["1.2.3.4", "198.51.100.0/24"], "duration": "4h" } plus the optional fields of POST /api/decisions except ip. Duplicates are ignored. Allowlisted values are skipped instead of refusing the request: the response lists them in allowlisted (each with its matching instances) next to added, results, succeeded, and failed; resend them with bypass_allowlist: true to add them anyway. Blocked in read-only mode.
POST /api/decisions/manual-lookup Find the active manual decisions (origins cscli, cscli-import, and console; this Web UI adds decisions as cscli) for up to 500 IPs or ranges. Body: { "values": ["1.2.3.4"] }. Returns { "decisions": [{ "value": "1.2.3.4", "instance_id": "default", "stop_at": "..." }] } with one entry per value and instance and the latest expiry. Values match exactly; a range decision does not cover the IPs inside it. Simulated decisions are ignored. The Statistics page uses it to mark values that already received a decision.
POST /api/decisions/bulk-delete Delete multiple decisions by numeric ID. Body: { "ids": [10, "11"] }. Blocked in read-only mode.
DELETE /api/decisions/:id Delete one decision from CrowdSec LAPI and local cache. :id must be numeric. Blocked in read-only mode.
DELETE /api/instances/:instanceId/decisions/:id Delete one decision from a specific instance and its local cache. Blocked in read-only mode.

Supported decision query parameters: instance, include_expired, page, page_size, q, alert_id, country, scenario, as, ip, target, dateStart, dateEnd, simulation, hide_duplicates, tz_offset, browser_tz.

  • include_expired=true includes expired decisions within the configured lookback window.

  • Paginated rows include message, the linked alert's message, when it has one. The non-paginated list omits it.

  • Duplicate decisions are hidden by default in paginated results. Deduplication is applied after active filters, so the preferred matching row remains visible even when the globally preferred row does not match. Set hide_duplicates=false or filter by alert_id to show every row.

  • alert_id accepts one alert ID or a comma-separated list. Combine it with instance when instances can share alert IDs.

  • simulation accepts all, live, or simulated; unknown values behave like all.

  • Bulk deletion accepts ids in single-instance deployments or instance-qualified refs as described above.

  • LAPI does not check allowlists for decisions sent with an alert, so decision creation checks every target instance first. When any of them allowlists the value, nothing is added and the response is 409:

    {
      "error": "10.1.2.3 is allowlisted",
      "code": "ALLOWLISTED",
      "allowlisted": [{ "instance_id": "primary", "instance_name": "CrowdSec", "reason": "10.0.0.0/8 from office (VPN)" }]
    }

    Repeat the request with "bypass_allowlist": true to add the decision anyway; the audit log records the bypass. Instances that do not support allowlists or cannot be checked do not block the request.

Decision facets require field=id|instance|alert|scenario|kind|country|region|city|as|ip|target|action|status|machine|origin and support the same value/label, pagination, and search behavior as alert facets. Status faceting considers both active and expired values within the configured lookback window even when the list is currently active-only.

Both facet endpoints return at most the requested limit and use an empty string for missing raw values:

{
  "field": "country",
  "values": [
    { "value": "DE", "count": 1234 },
    { "value": "", "count": 17 }
  ],
  "offset": 0,
  "has_more": true
}

Allowlists

CrowdSec centralized allowlists cannot be changed through LAPI, so these routes are read-only and available to read-only users. They accept instance=<instance-id> or instance=all (the default); an unknown instance returns 404. Allowlists with the same name on several instances are combined. Like alerts and decisions, allowlists are cached in SQLite: every refresh of an instance (scheduled, manual, or on demand) re-reads its allowlists from LAPI and writes only changed entries, and the list and entry routes read the cache. An instance that has never been synchronized is read once before the response. When LAPI cannot be read, the cached allowlists remain and the instance reports the failure. Checks always query LAPI so that range matching and the manual-decision guard use the current state.

Method Endpoint Description
GET /api/allowlists Instance statuses and allowlist summaries without entries. Optional q keeps only allowlists whose name, description, or entries contain the text. Always returns 200; per-instance problems are reported in status.
GET /api/allowlists/:name/entries One page of an allowlist's active entries. Accepts page, page_size (10–200, default 50), and q. Returns 404 for an allowlist that does not exist in the scope.
GET /api/allowlists/check?value=<ip|range> Check whether an IP address or CIDR range is covered by an allowlist on each instance. Returns 400 for an invalid value.

Each instance has a status of available, unsupported (the LAPI predates allowlists, which require CrowdSec 1.6.5) or unavailable (with error). partial is true when any instance is unavailable.

{
  "instances": [{ "instance_id": "primary", "instance_name": "CrowdSec", "status": "available" }],
  "allowlists": [{
    "name": "office",
    "description": "Office network",
    "created_at": "2026-01-01T00:00:00Z",
    "updated_at": "2026-01-02T00:00:00Z",
    "console_managed": false,
    "instance_ids": ["primary"],
    "entry_count": 2,
    "matching_entries": 2
  }],
  "partial": false
}

instance_ids lists the instances that have the allowlist, and matching_entries counts the entries matching q (all entries without it). A q that matches the allowlist's name or description keeps every entry.

Entry pages contain the allowlist summary, data, and the same pagination object as Alerts and Decisions, with unfiltered_total counting all entries:

{
  "allowlist": { "name": "office", "entry_count": 2, "matching_entries": 2, "instance_ids": ["primary"], "console_managed": false },
  "data": [{ "value": "10.0.0.0/8", "description": "VPN", "created_at": "2026-01-01T00:00:00Z", "expiration": null, "instance_ids": ["primary"] }],
  "pagination": { "page": 1, "page_size": 50, "total": 2, "total_pages": 1, "unfiltered_total": 2 }
}

expiration is null for entries that never expire; expired entries are omitted by LAPI. An entry's instance_ids can be shorter than the allowlist's when an instance's copy lacks the entry. Check responses contain value, an overall allowlisted flag, and per-instance results with status, allowlisted, and CrowdSec's reason, for example 10.0.0.0/8 from office (VPN).

Cleanup and Cache

Method Endpoint Description
POST /api/cleanup/by-ip Delete cached/LAPI alerts and decisions for one IP address or range. Body: { "ip": "1.2.3.4" }; optional scope and instance_id select targets. Blocked in read-only mode.
POST /api/cache/refresh Run a manual refresh with { "mode": "delta" | "latest" | "full" }. Requires manual refresh to be enabled; returns 409 when another refresh is running.
POST /api/cache/clear Clear synced alert/decision data and run a bootstrap sync. Blocked in read-only mode.

Alert deletion, bulk deletion, and cleanup responses use:

{
  "requested_alerts": 0,
  "requested_decisions": 0,
  "deleted_alerts": 0,
  "deleted_decisions": 0,
  "failed": [],
  "ip": "1.2.3.4"
}

Alert deletion requests return after a durable deletion tombstone is stored and the alert is removed from the visible cache. A backend worker expires linked decisions, waits for the configured bouncer propagation delay, and then deletes the owning alert. Pending work survives restarts, is processed before historical sync, and prevents sync from restoring the hidden alert. Failed work is retried until crowdsec.sync.deletionQueueMaxAge (24 hours by default); its tombstone remains active after retries stop so historical sync cannot immediately restore the alert. ip is only included for cleanup-by-IP responses.

Stats and Dashboard

Method Endpoint Description
GET /api/stats/alerts Alert records shaped for chart/stat consumers within the configured lookback window.
GET /api/stats/decisions Decision records shaped for chart/stat consumers within the configured lookback window.
GET /api/dashboard/stats Aggregated dashboard totals, filtered totals, top targets/countries/scenarios/AS, world-map country data, bounded source-location clusters, and history series.

Supported dashboard filters: instance, q, decision_q, country, scenario, as, ip, target, dateStart, dateEnd, simulation, granularity, tz_offset, browser_tz.

  • simulation accepts all, live, or simulated.
  • granularity=hour returns hourly buckets; any other value uses daily buckets.
  • q uses alert structured-search semantics and controls the filtered alert count, top lists, map data, and alert history.
  • decision_q uses decision structured-search semantics and controls the filtered active-decision count and decision history. When omitted, it falls back to q for compatibility.
  • The browser sends separate alert and decision queries from the same persisted Quick Filter state. Filtered Dashboard counts therefore match the corresponding paginated list totals, including default active-only and duplicate-hiding behavior on Decisions.
  • The legacy scalar filters remain supported. If both a scalar filter and q are supplied, both must match.

Long-term Statistics

Method Endpoint Description
GET /api/statistics Return archived totals, period comparisons, activity series, rankings, and coverage for the selected scope.
GET /api/statistics/details Return the IPs, ranges, or machines behind a finding. Accepts the same filters as /api/statistics.
DELETE /api/statistics Permanently delete all archived statistics. Enabled collection starts over with the alerts and decisions still in the cache. Returns { "success": true, "statistics": { ... } }. Blocked in read-only mode.
PUT /api/config/statistics Update any of enabled, retentionDays, jobInterval, and jobTimeBudget. Returns { "success": true, "statistics": { ... } }. Blocked in read-only mode. Returns 409 with code: "MANAGED_BY_CONFIG" when a changed field is set by the application configuration.
  • from and to are inclusive dates in YYYY-MM-DD format, as calendar days of the statistics time zone (statistics.timeZone in GET /api/config). They default to 29 days ago and today, respectively. The range can span up to 3,650 days. The API accepts an end date up to one day ahead of the current date for clock skew.
  • instance defaults to all and accepts a configured instance ID. simulation accepts live (default), simulated, or all. When simulations are disabled, the API uses live. limit accepts 10 (default), 20, or 50.
  • Optional filters include ip (an IP address or range), machine (a JSON array containing the instance ID and machine ID), scenario, country (two-letter code), network (AS name), and target.
  • Finding details require kind=ips, kind=returned, or kind=machines. Use network to scope IP results to an AS, history=1 to include remediations (alert decisions of any type) before the selected range for returned IPs, or machines with a JSON array of 1–25 machine keys. IP and range lists accept a size of 1–500 and default to 25.
  • Both read endpoints return 400 for invalid filters and 503 with retryAfterMs when the archive is unavailable. GET /api/config includes the statistics settings, managed fields, collection status, and time zone in its statistics object.

CrowdSec Metrics

Method Endpoint Description
GET /api/metrics/crowdsec Fetch and normalize the primary instance's first metrics endpoint. Returns 404 when it is not configured and 502 when the metrics fetch fails.
GET /api/metrics/crowdsec/combined?instance=<id|all> Fetch and normalize every metrics endpoint in one instance or all instances. Successful sources are aggregated concurrently; partial success returns 200 with source statuses, while total failure returns 502.
GET /api/instances/:instanceId/metrics/:endpointId Fetch and normalize a specific instance metrics endpoint. Returns 404 for an unknown instance or endpoint and 502 when the fetch fails.

The response includes fetched_at, totals, bouncers, machines, parserSources, parserNodes, whitelists, and parserTimings. It can also include runtime-only observability sections: lapiRoutes and appsecEngines. Combined responses add aggregation.partial and an aggregation.sources entry for each configured endpoint, including its optional endpoint_icon; detailed rows include source_id so matching labels remain attributable.

Parser node entries include isChild, which is true for CrowdSec child parser nodes emitted with the child- prefix.

Parser, LAPI latency, AppSec, bouncer, and machine values are derived from the current CrowdSec Prometheus scrape. The endpoint does not query Prometheus history or calculate Grafana-style rate()/increase() windows, so metrics that require time-window tracking are intentionally omitted.

Cache Update WebSocket

Connect to /api/cache-updates, below server.basePath when configured, using ws:// or wss://. The upgrade uses the normal session cookie, enforces same-origin browser requests, and returns 401 when authentication fails.

Server messages are JSON:

Type Fields Purpose
ready updated_at Initial cache timestamp after connection.
cache-updated updated_at, instance_ids Signals that one or more instance caches changed.
heartbeat sent_at Sent every 30 seconds alongside the WebSocket ping.

Notifications

Notification inbox routes operate on generated notification items.

Method Endpoint Description
GET /api/notifications List notification items. Supports page and page_size; defaults to page 1, size 50 when omitted.
POST /api/notifications/:id/read Mark one notification as read. Allowed in read-only mode.
POST /api/notifications/bulk-read Mark multiple notifications as read. Body: { "ids": ["id-1", "id-2"] }. Allowed in read-only mode.
POST /api/notifications/bulk-delete Delete multiple notifications. Body: { "ids": ["id-1", "id-2"] }. Blocked in read-only mode.
POST /api/notifications/delete-read Delete all read notifications. Blocked in read-only mode.
DELETE /api/notifications/:id Delete one notification. Blocked in read-only mode.
GET /api/notifications/settings List notification channels and rules.

Notification configuration routes manage destinations and rule definitions.

Method Endpoint Description
POST /api/notification-channels Create a notification channel. Blocked in read-only mode.
PUT /api/notification-channels/:id Update a notification channel. Blocked in read-only mode.
DELETE /api/notification-channels/:id Delete a notification channel. Blocked in read-only mode.
POST /api/notification-channels/:id/test Send a test notification through a saved channel and return its title, message, and delivery result. Blocked in read-only mode.
POST /api/notification-rules Create a notification rule. Blocked in read-only mode.
POST /api/notification-rules/:id/test Send one test notification through the saved rule's enabled destinations. Blocked in read-only mode.
PUT /api/notification-rules/:id Update a notification rule. Blocked in read-only mode.
DELETE /api/notification-rules/:id Delete a notification rule. Blocked in read-only mode.

Destination tests return success: true, the sent title and message, and a delivery result. This lets the UI show the same result details as rule tests.

Rule tests return source: "current" when a rule matches current data, or source: "sample" when a synthetic example is used. The response includes the exact sent title and message and a deliveries result for each enabled destination. A sample checks rendering and delivery but does not verify filters or thresholds. Test sends are marked [TEST] and do not create notifications or incident state. A rule with no enabled outbound destinations cannot be tested.

Channel create/update body:

{
  "name": "Security alerts",
  "type": "ntfy",
  "enabled": true,
  "config": {}
}

Supported channel types: apprise, ntfy, gotify, email, mqtt, webhook.

Rule create/update body:

{
  "name": "IP bans",
  "type": "ip-ban",
  "enabled": true,
  "severity": "warning",
  "channel_ids": ["channel-id"],
  "config": {}
}

Supported rule types: alert-spike, alert-threshold, new-alert-decision, new-cve, ip-ban, application-update, crowdsec-update, lapi-availability. The crowdsec-update rule has an empty config and checks each configured Prometheus endpoint against the latest stable CrowdSec release.

Supported severities: info, warning, critical.

Update Check

Method Endpoint Description
GET /api/update-check Check whether a newer application release is available. Response is not cached.

Optional query parameters override the runtime version metadata used for the check: version, branch, commit_hash.

Example Requests

List the first page of active decisions:

curl -b cookie.txt 'http://localhost:3000/api/decisions?page=1&page_size=50'

Search alerts with structured syntax:

curl -b cookie.txt 'http://localhost:3000/api/alerts?page=1&page_size=50&q=kind=waf%20AND%20-country:us'

Add a manual ban:

curl -b cookie.txt \
  -H 'Content-Type: application/json' \
  -d '{"ip":"1.2.3.4","duration":"4h","type":"ban","reason":"manual"}' \
  http://localhost:3000/api/decisions