Files
David Santos d4059d801a
CI / Test ingest-api (pull_request) Successful in 41s
CI / Test api (pull_request) Successful in 44s
CI / Lint and typecheck admin-ui (pull_request) Successful in 1m24s
CI / Validate Docker build (pull_request) Successful in 6m2s
fix(hub): BIT-31442 route /v1/paperclip alias to admin API + accept X-Api-Key header
The recent-errors handler (api/src/routes/public/recentErrors.ts) registers
both GET /api/error-monitoring/recent-errors and the alias
GET /v1/paperclip/recent-errors on the admin API (port 3200). However the
admin-ui Next.js rewrite sent all /v1/* to ingest-api (port 3041), which has
no such route, so the alias returned 404 in production while the
/api/error-monitoring path worked (401 without a key).

Changes:
- admin-ui/next.config.ts: add a specific /v1/paperclip/:path* -> admin API
  rewrite before the generic /v1/:path* -> ingest-api rule (rewrite order
  matters; first match wins).
- api/src/lib/errorMonitoringAuth.ts: authorizeReadQuery now also accepts an
  X-Api-Key header carrying either ERROR_RESOLVE_API_KEY/ERROR_REPORTING_API_KEY
  or DEBUG_VIEW_ERRORS_KEY, so programmatic callers avoid leaking keys in
  URLs/access logs. Backward compatible with the existing query params.
- api/src/routes/public/recentErrors.test.ts: cover the alias path and the
  X-Api-Key header (resolve key, view key, invalid key).
- docs/HTTP_CONTRACTS.md, docs/permission-matrix.md: document the header and
  the proxy ordering requirement.
2026-10-21 18:16:05 +01:00

13 KiB
Raw Permalink Blame History

HTTP contracts — errors.bitreport.pt

Audience: Operators, automation, integrators.
Scope: Fastify hub API (api/, default port 3200) and ingest API (ingest-api/).
Companion: Curl examples below mirror production paths; substitute ER_API_BASE, INGEST_API_BASE, and secrets from your vault.


Conventions

  • JSON bodies use Content-Type: application/json unless noted.
  • Hub public read endpoints require api_key or view_errors query params when server secrets are configured (see ERROR_MONITORING_PUBLIC_API.md).
  • Hub mutations accept X-Error-Resolve-Key or body field api_key matching ERROR_RESOLVE_API_KEY / ERROR_REPORTING_API_KEY, or an admin session cookie with RBAC.
  • Admin JSON routes expect JWT in HTTP-only cookie __Host-access after POST /admin/auth/login (use a cookie jar with curl).

Hub API — rate limiting (api/)

The hub registers @fastify/rate-limit globally and attaches stricter presets to selected routes (api/src/plugins/rate-limit.ts, api/src/index.ts). Defaults and env tunables are documented in the plugin header (RATE_*, body size caps).

Request augmentation: ingest_token_id

Hub ingest handlers (e.g. future POST /api/ingest/*) may set request.ingest_token_id to the authenticated ingest key’s stable id before the rate-limit hook runs. The ingest preset’s keyGenerator then uses ingest:token:<id> instead of ingest:ip:<ip>, so many clients behind one NAT do not share one counter. The separate ingest-api process already applies DB-backed per-key limits; this field keeps the hub aligned if ingest is ever co-hosted in the same Fastify app.

Rate-limit denials are counted in Prometheus as er_api_rate_limit_rejections_total (bucket label: global, ingest, login, mutation). See OBSERVABILITY_PROMETHEUS.md.


Hub API — health & metrics

GET /health

Response 200

{ "ok": true, "ts": "2026-04-02T19:00:00.000Z" }
curl -sS "${ER_API_BASE:-http://127.0.0.1:3200}/health"

GET /metrics

Prometheus exposition format (text/plain). See OBSERVABILITY_PROMETHEUS.md.

curl -sS "${ER_API_BASE:-http://127.0.0.1:3200}/metrics" | head

Hub API — public error monitoring (token or view key)

GET /api/error-monitoring/recent-errors

Alias: GET /v1/paperclip/recent-errors (same handler).

Query: api_key or view_errors, plus optional limit, offset, status, severity, project_slug, q, order.

Header (BIT-31442): X-Api-Key: <key> is accepted as an alternative to the api_key/view_errors query params, so programmatic callers can avoid leaking the key in URLs and access logs. The header may carry either ERROR_RESOLVE_API_KEY/ERROR_REPORTING_API_KEY or the read-only DEBUG_VIEW_ERRORS_KEY.

Proxy note (BIT-31442): the /v1/paperclip/* alias is served by the admin API (port 3200), not ingest-api (port 3041). The admin-ui Next.js rewrite routes /v1/paperclip/:path* to the admin API before the generic /v1/:path* → ingest-api rule. If the alias returns 404 in production, verify that rewrite order in admin-ui/next.config.ts.

Response 200

{
  "success": true,
  "message": "ok",
  "data": [
    {
      "status": "open",
      "message": "Exception: …",
      "error_message": "Exception: …",
      "stack_trace": "#0 /app/src/foo.ts:42: Exception: …",
      "file_path": "/app/src/foo.ts",
      "line_number": "42",
      "severity": "high",
      "unique_id": "12345",
      "project_slug": "crm",
      "environment": "production",
      "occurred_at": "2026-04-05T12:34:56.789Z"
    }
  ]
}

occurred_at: ISO-8601 time of the latest occurrence represented in the row (same as unique_id when that id is an occurrence id). Exposed for ops automation (e.g. post-deploy “no new events in N hours” checks).

stack_trace: The hub returns a non-empty string for every row. Ingest stores a synthesized stack when the reporter omits one; for legacy occurrences whose column is still null/blank, recent-errors applies the same synthesis at read time using message and context_json (BIT-1008).

API_KEY="$ERROR_RESOLVE_API_KEY"
BASE="${ER_API_BASE:-http://127.0.0.1:3200}"
curl -sS -G "${BASE}/api/error-monitoring/recent-errors" \
  --data-urlencode "api_key=${API_KEY}" \
  --data-urlencode "status=open,investigating" \
  --data-urlencode "project_slug=crm" \
  --data-urlencode "limit=50"

GET /api/error-monitoring/stats

Query: api_key or view_errors only (no extra filters).

Response 200 (shape)

{
  "ingestion": {
    "last24h": 0,
    "resolvedLast24h": 0,
    "hourlyTrend": [
      {
        "hour": "2026-04-01 12:00:00",
        "critical": 0,
        "high": 0,
        "medium": 0,
        "low": 0,
        "info": 0
      }
    ]
  },
  "bySeverity": {
    "critical": 0,
    "high": 0,
    "medium": 0,
    "low": 0,
    "info": 0
  },
  "byState": { "open": 0 },
  "projects": [
    {
      "slug": "crm",
      "total": 0,
      "open": 0,
      "investigating": 0,
      "resolved": 0,
      "ignored": 0,
      "critical": 0,
      "resolutionRate": 0
    }
  ]
}

Calling this endpoint also refreshes Prometheus gauges on the hub (best-effort, non-blocking).

curl -sS -G "${BASE}/api/error-monitoring/stats" --data-urlencode "api_key=${API_KEY}" | jq .

POST /api/error-monitoring/resolve

Auth: resolve key or session with errors:triage.

Body

Field Type Required
unique_id string (digits) yes
resolution_notes string no
assigned_to string no
api_key string no (if header used)

Response 200

{
  "success": true,
  "message": "Erro marcado como resolvido",
  "data": { "unique_id": "12345", "resolution_notes": "Marked as resolved via API" }
}
curl -sS -X POST "${BASE}/api/error-monitoring/resolve" \
  -H "Content-Type: application/json" \
  -H "X-Error-Resolve-Key: ${API_KEY}" \
  -d '{"unique_id":"12345","resolution_notes":"ops: verified fix"}'

POST /api/error-monitoring/bulk-resolve

Auth: same as resolve.

Provide either unique_ids (non-empty array of numeric strings, max 1000) or message_pattern (string or array, max 20 patterns). If both are sent, unique_ids wins.

Response 200 (by ids)

{
  "success": true,
  "message": "Bulk resolve by unique_ids completed",
  "data": { "resolved": 3, "by": "unique_ids" }
}

Response 200 (by pattern)

{
  "success": true,
  "message": "Bulk resolve by message pattern completed",
  "data": {
    "resolved": 2,
    "by": "message_pattern",
    "patterns": ["%timeout%"]
  }
}
curl -sS -X POST "${BASE}/api/error-monitoring/bulk-resolve" \
  -H "Content-Type: application/json" \
  -H "X-Error-Resolve-Key: ${API_KEY}" \
  -d '{"message_pattern":"Connection refused","resolution_notes":"bulk close"}'

Note: A separate POST …/resolve-by-pattern route is not implemented on this service; use bulk-resolve with message_pattern (CRM-style bulk behaviour).

POST /api/error-monitoring/purge-resolved

Auth: resolve key or session with errors:delete.

Body

Field Type Description
dry_run boolean If true, returns would_delete only
api_key string optional

Effect: Deletes all rows in er_incidents with current_state = 'resolved' (cascade per schema). There is no older_than_days filter in the current implementation.

Response 200 (dry run)

{
  "success": true,
  "message": "Dry run",
  "data": { "dry_run": true, "would_delete": 12 }
}

Response 200 (execute)

{
  "success": true,
  "message": "Apagados 12 incidentes resolvidos",
  "data": { "deleted": 12 }
}
curl -sS -X POST "${BASE}/api/error-monitoring/purge-resolved" \
  -H "Content-Type: application/json" \
  -H "X-Error-Resolve-Key: ${API_KEY}" \
  -d '{"dry_run":true}'

Hub API — admin authentication

Base path: /admin/auth. Responses use JSON; cookies are __Host-* (secure, path / in production).

POST /admin/auth/login

Body

{ "email": "[email protected]", "password": "…" }

Response 200 — sets __Host-access and __Host-refresh; body:

{ "user": { "id": "…", "email": "[email protected]", "role": "admin" } }
COOKIE_JAR="$(mktemp)"
curl -sS -c "$COOKIE_JAR" -X POST "${BASE}/admin/auth/login" \
  -H "Content-Type: application/json" \
  -d '{"email":"[email protected]","password":"YOUR_PASSWORD"}'

POST /admin/auth/refresh

Uses __Host-refresh cookie; returns { "ok": true } and rotates cookies.

curl -sS -b "$COOKIE_JAR" -c "$COOKIE_JAR" -X POST "${BASE}/admin/auth/refresh"

POST /admin/auth/logout

Requires valid access cookie.

curl -sS -b "$COOKIE_JAR" -X POST "${BASE}/admin/auth/logout"

GET /admin/auth/me

Response 200

{ "user": { "id": "…", "email": "[email protected]", "role": "admin" } }
curl -sS -b "$COOKIE_JAR" "${BASE}/admin/auth/me"

Hub API — admin statistics (errors:read)

All require __Host-access + permission errors:read.

GET /v1/stats/summary

Optional query: project=<slug>.

curl -sS -b "$COOKIE_JAR" "${BASE}/v1/stats/summary?project=crm"

GET /v1/stats/trend

Query: granularity=day|hour, days, hours, optional project.

curl -sS -b "$COOKIE_JAR" "${BASE}/v1/stats/trend?granularity=day&days=14"

GET /v1/stats/recurrence

Query: optional project, days (1–90), limit (max 100).

curl -sS -b "$COOKIE_JAR" "${BASE}/v1/stats/recurrence?days=7&limit=20"

Response includes windowDays, rangeStart, rangeEndExclusive, top[] with fingerprint, hitsInWindow, etc. See ADMIN_STATS_API.md.


Hub API — admin incidents (errors:read)

GET /v1/incidents

Query: optional state, severity, project, q (max 500 rows).

curl -sS -b "$COOKIE_JAR" "${BASE}/v1/incidents?project=crm&state=open"

Response 200

{
  "incidents": [
    {
      "id": "1",
      "projectSlug": "crm",
      "fingerprint": "abc…",
      "title": "…",
      "severity": "high",
      "currentState": "open",
      "firstSeenAt": "2026-04-01T12:00:00.000Z",
      "lastSeenAt": "2026-04-02T10:00:00.000Z",
      "occurrencesCount": 5
    }
  ]
}

GET /v1/incidents/:id

Response 200 — { "incident": { …, "occurrences": [ … ] } } (up to 200 recent occurrences).

curl -sS -b "$COOKIE_JAR" "${BASE}/v1/incidents/12345"

Ingest API

Default prefix: /v1/ingest. Authenticate with Authorization: Bearer <token> or X-Api-Key: <token> (project-bound ingest key).

GET /health

{ "status": "ok" }

GET /metrics

Ingest Prometheus metrics (er_ingest_*). See OBSERVABILITY_PROMETHEUS.md.

GET /v1/openapi.json

OpenAPI 3.1 document generated from Fastify.

GET /v1/docs/ui

Swagger UI (browser).

POST /v1/ingest/events

Body

{
  "events": [
    {
      "schema_version": 1,
      "occurred_at": "2026-04-02T18:00:00.000Z",
      "level": "error",
      "message": "Something failed",
      "fingerprint": "optional-custom-fp",
      "stacktrace": "optional",
      "context": { "file_path": "app.ts", "line_number": 10 }
    }
  ]
}

Response 200 — includes fingerprint_policy_version, noise_ruleset_version, noise_filtered_count, results[] (each item either stored { incident_id, occurrence_id, fingerprint } or skipped noise { skipped, rule_id, reason, … }).

Headers: optional Idempotency-Key (max 128 chars). Reuse with same body → cached 200; reuse with different body → 409 idempotency_conflict.

Status codes: 400 (schema / occurred_at), 401 (missing/invalid key), 429 (rate limit; Retry-After), 409 (idempotency), 500.

INGEST_BASE="${INGEST_API_BASE:-http://127.0.0.1:3210}"
INGEST_TOKEN="<er_ingest_key_plaintext>"
curl -sS -X POST "${INGEST_BASE}/v1/ingest/events" \
  -H "Authorization: Bearer ${INGEST_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{"events":[{"schema_version":1,"occurred_at":"2026-04-02T18:00:00.000Z","level":"error","message":"smoke test"}]}'