Files
errors.bitreport.pt/docs/HTTP_CONTRACTS.md
T
Peter Spark 6971b7669c fix(api): non-empty stack_trace on recent-errors for legacy rows
When occurrence.stack_trace is null/blank, synthesize the same text as
ingest-api (BIT-796) at read time so CRM / Paperclip always get a stable
contract (BIT-1008, ERRPAYLOAD:5d26a50c83c0). Add unit tests and document
in HTTP_CONTRACTS + ERROR_MONITORING_PUBLIC_API.

Paperclip-Agent: 0b1fcf92-5fe3-4ac0-9f29-df4ab72f5376
Paperclip-Issue: BIT-1008
Paperclip-Run: 4c4da0dd-38ab-4f32-86d7-f2502c7cceca
Made-with: Cursor
2026-04-05 10:49:24 +00:00

438 lines
11 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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](../api/docs/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 — health & metrics
### `GET /health`
**Response 200**
```json
{ "ok": true, "ts": "2026-04-02T19:00:00.000Z" }
```
```bash
curl -sS "${ER_API_BASE:-http://127.0.0.1:3200}/health"
```
### `GET /metrics`
Prometheus exposition format (`text/plain`). See [OBSERVABILITY_PROMETHEUS.md](OBSERVABILITY_PROMETHEUS.md).
```bash
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`.
**Response 200**
```json
{
"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"
}
]
}
```
**`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).
```bash
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)
```json
{
"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).
```bash
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**
```json
{
"success": true,
"message": "Erro marcado como resolvido",
"data": { "unique_id": "12345", "resolution_notes": "Marked as resolved via API" }
}
```
```bash
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)
```json
{
"success": true,
"message": "Bulk resolve by unique_ids completed",
"data": { "resolved": 3, "by": "unique_ids" }
}
```
**Response 200** (by pattern)
```json
{
"success": true,
"message": "Bulk resolve by message pattern completed",
"data": {
"resolved": 2,
"by": "message_pattern",
"patterns": ["%timeout%"]
}
}
```
```bash
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)
```json
{
"success": true,
"message": "Dry run",
"data": { "dry_run": true, "would_delete": 12 }
}
```
**Response 200** (execute)
```json
{
"success": true,
"message": "Apagados 12 incidentes resolvidos",
"data": { "deleted": 12 }
}
```
```bash
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**
```json
{ "email": "[email protected]", "password": "…" }
```
**Response 200** — sets `__Host-access` and `__Host-refresh`; body:
```json
{ "user": { "id": "…", "email": "[email protected]", "role": "admin" } }
```
```bash
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.
```bash
curl -sS -b "$COOKIE_JAR" -c "$COOKIE_JAR" -X POST "${BASE}/admin/auth/refresh"
```
### `POST /admin/auth/logout`
Requires valid access cookie.
```bash
curl -sS -b "$COOKIE_JAR" -X POST "${BASE}/admin/auth/logout"
```
### `GET /admin/auth/me`
**Response 200**
```json
{ "user": { "id": "…", "email": "[email protected]", "role": "admin" } }
```
```bash
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>`.
```bash
curl -sS -b "$COOKIE_JAR" "${BASE}/v1/stats/summary?project=crm"
```
### `GET /v1/stats/trend`
Query: `granularity=day|hour`, `days`, `hours`, optional `project`.
```bash
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).
```bash
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](ADMIN_STATS_API.md).
---
## Hub API — admin incidents (`errors:read`)
### `GET /v1/incidents`
Query: optional `state`, `severity`, `project`, `q` (max 500 rows).
```bash
curl -sS -b "$COOKIE_JAR" "${BASE}/v1/incidents?project=crm&state=open"
```
**Response 200**
```json
{
"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).
```bash
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`
```json
{ "status": "ok" }
```
### `GET /metrics`
Ingest Prometheus metrics (`er_ingest_*`). See [OBSERVABILITY_PROMETHEUS.md](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**
```json
{
"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**.
```bash
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"}]}'
```
---
## Related
- [RUNBOOK_OPERATIONS.md](RUNBOOK_OPERATIONS.md) — five common operational flows.
- [RUNBOOK_INGEST_DEBUG.md](RUNBOOK_INGEST_DEBUG.md) — ingestion failures and rate limits.
- [scripts/er-cli.sh](../scripts/er-cli.sh) — bash wrapper over public hub endpoints.