Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d4059d801a | ||
|
|
954b0ced2e | ||
|
|
9dd88db4ae | ||
|
|
52e75a8760 | ||
|
|
b190d6fa1b | ||
|
|
3da9e47873 | ||
|
|
7f76c5287d |
No files matched your search
@@ -23,6 +23,15 @@ const nextConfig: NextConfig = {
|
||||
async rewrites() {
|
||||
return [
|
||||
{ source: "/health", destination: `${INGEST_API_URL}/health` },
|
||||
// BIT-31442: the recent-errors handler (api/src/routes/public/recentErrors.ts)
|
||||
// registers the /v1/paperclip/recent-errors alias on the admin API (port 3200),
|
||||
// not on ingest-api. The generic /v1/* rule below would otherwise send it to
|
||||
// ingest-api (port 3041), which has no such route and returns 404. This more
|
||||
// specific rule must come first; Next.js evaluates rewrites in order.
|
||||
{
|
||||
source: "/v1/paperclip/:path*",
|
||||
destination: `${ADMIN_API_URL}/v1/paperclip/:path*`,
|
||||
},
|
||||
{ source: "/v1/:path*", destination: `${INGEST_API_URL}/v1/:path*` },
|
||||
{
|
||||
source: "/api/error-monitoring/:path*",
|
||||
|
||||
@@ -45,6 +45,22 @@ export function authorizeReadQuery(request: FastifyRequest, reply: FastifyReply)
|
||||
return true;
|
||||
}
|
||||
|
||||
// BIT-31442: accept X-Api-Key header as an alternative to the query param so
|
||||
// programmatic callers (Paperclip, QA) can avoid leaking the key in URLs/logs.
|
||||
// The header may carry either the resolve/reporting key or the read-only
|
||||
// DEBUG_VIEW_ERRORS_KEY, mirroring the query-param semantics.
|
||||
const headerRaw = request.headers['x-api-key'];
|
||||
const headerVal = Array.isArray(headerRaw) ? headerRaw[0] : headerRaw;
|
||||
const providedHeader = typeof headerVal === 'string' ? headerVal.trim() : '';
|
||||
if (providedHeader !== '') {
|
||||
if (apiKey && safeEqual(providedHeader, apiKey)) {
|
||||
return true;
|
||||
}
|
||||
if (viewKey && safeEqual(providedHeader, viewKey)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
reply.code(401).send({
|
||||
success: false,
|
||||
message: 'Unauthorized',
|
||||
|
||||
@@ -171,4 +171,60 @@ describe('GET /api/error-monitoring/recent-errors', () => {
|
||||
// ['resolved', '%boom%', '%boom%', '%boom%', limit, offset]
|
||||
expect(params).toEqual(['resolved', '%boom%', '%boom%', '%boom%', 10, 0]);
|
||||
});
|
||||
|
||||
it('serves the /v1/paperclip/recent-errors alias from the same handler (BIT-31442)', async () => {
|
||||
const execute = vi.fn().mockResolvedValue([[]]);
|
||||
const app = await buildApp(execute);
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/v1/paperclip/recent-errors?api_key=test-recent-errors-key',
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(execute).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('accepts the resolve key via X-Api-Key header (BIT-31442)', async () => {
|
||||
const execute = vi.fn().mockResolvedValue([[]]);
|
||||
const app = await buildApp(execute);
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/error-monitoring/recent-errors',
|
||||
headers: { 'x-api-key': 'test-recent-errors-key' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(execute).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('accepts the read-only view key via X-Api-Key header (BIT-31442)', async () => {
|
||||
const prevView = process.env.DEBUG_VIEW_ERRORS_KEY;
|
||||
process.env.DEBUG_VIEW_ERRORS_KEY = 'test-view-key';
|
||||
try {
|
||||
const execute = vi.fn().mockResolvedValue([[]]);
|
||||
const app = await buildApp(execute);
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/error-monitoring/recent-errors',
|
||||
headers: { 'x-api-key': 'test-view-key' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
} finally {
|
||||
if (prevView === undefined) {
|
||||
delete process.env.DEBUG_VIEW_ERRORS_KEY;
|
||||
} else {
|
||||
process.env.DEBUG_VIEW_ERRORS_KEY = prevView;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects an invalid X-Api-Key header with 401 (BIT-31442)', async () => {
|
||||
const execute = vi.fn().mockResolvedValue([[]]);
|
||||
const app = await buildApp(execute);
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/error-monitoring/recent-errors',
|
||||
headers: { 'x-api-key': 'wrong-key' },
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
expect(execute).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -59,6 +59,10 @@ 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**
|
||||
|
||||
```json
|
||||
|
||||
@@ -50,11 +50,14 @@ These routes mirror the CRM error-monitoring module for Paperclip and automation
|
||||
|
||||
### Read: `GET /api/error-monitoring/recent-errors`
|
||||
|
||||
Alias: `GET /v1/paperclip/recent-errors` (same handler; served by the admin API via the `admin-ui` rewrite — BIT-31442).
|
||||
|
||||
| Credential | Notes |
|
||||
|------------|--------|
|
||||
| `api_key` query | Must match `ERROR_RESOLVE_API_KEY` or `ERROR_REPORTING_API_KEY` |
|
||||
| `view_errors` query | Must match `DEBUG_VIEW_ERRORS_KEY` (read-oriented) |
|
||||
| Admin session | Not used on this path; query credentials only |
|
||||
| `X-Api-Key` header (BIT-31442) | Carries either the resolve/reporting key or `DEBUG_VIEW_ERRORS_KEY`; alternative to the query params to avoid key leakage in URLs/logs |
|
||||
| Admin session | Not used on this path; query/header credentials only |
|
||||
|
||||
At least one of the server secrets above must be configured or the endpoint returns **503**.
|
||||
|
||||
|
||||
@@ -11,6 +11,8 @@ Env vars lidos (ver /etc/paperclip/paperclip-fleet-error-audit.env):
|
||||
PAPERCLIP_FLEET_AUDIT_HUB_BASE — base URL do hub (default: https://errors.bitreport.pt)
|
||||
PAPERCLIP_FLEET_AUDIT_EXPECTED_SLUGS — CSV de slugs esperados
|
||||
PAPERCLIP_FLEET_AUDIT_MAX_AGE_HOURS — limiar de frescura (default: 168)
|
||||
PAPERCLIP_FLEET_AUDIT_MAX_AGE_HOURS_OVERRIDES — CSV "slug=horas" por slug (opcional,
|
||||
sobrepõe o limiar global para esse slug)
|
||||
PAPERCLIP_FLEET_AUDIT_FETCH_LIMIT — rows a buscar (default: 2000)
|
||||
PAPERCLIP_FLEET_AUDIT_MIN_ROWS — mínimo de rows antes de enforcement (default: 20)
|
||||
PAPERCLIP_FLEET_AUDIT_PROJECT_ID — Paperclip project ID para issues de correção
|
||||
@@ -27,6 +29,7 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
@@ -36,6 +39,12 @@ from typing import Any
|
||||
from urllib import request as urllib_request
|
||||
from urllib.error import HTTPError, URLError
|
||||
|
||||
# Marker convention used for one-off pipe-liveness verification events (e.g. sent by
|
||||
# hand while investigating a "stale" finding, per BIT-30273/BIT-30527). These are real
|
||||
# hub rows but not production traffic — counting them as "fresh" masks genuine staleness
|
||||
# for as long as they remain the newest row for a slug. Excluded from freshness scoring.
|
||||
_SYNTHETIC_EVENT_RE = re.compile(r"^\[BIT-\d+\]\s+\S+.*smoke test", re.IGNORECASE)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Env helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -126,7 +135,7 @@ def _patch_json(url: str, payload: dict[str, Any], headers: dict[str, str] | Non
|
||||
def fetch_hub_rows(hub_base: str, api_key: str, limit: int) -> list[dict[str, Any]]:
|
||||
url = (
|
||||
f"{hub_base}/api/error-monitoring/recent-errors"
|
||||
f"?limit={limit}&order=occurred_at_desc&api_key={api_key}"
|
||||
f"?limit={limit}&order=occurred_at_desc&status=open,investigating,resolved,ignored&api_key={api_key}"
|
||||
)
|
||||
# Use curl to avoid Cloudflare bot challenges on urllib
|
||||
result = subprocess.run(
|
||||
@@ -144,21 +153,45 @@ def fetch_hub_rows(hub_base: str, api_key: str, limit: int) -> list[dict[str, An
|
||||
return data.get("data", [])
|
||||
|
||||
|
||||
def _parse_max_age_overrides(raw: str) -> dict[str, int]:
|
||||
overrides: dict[str, int] = {}
|
||||
for part in raw.split(","):
|
||||
part = part.strip()
|
||||
if not part or "=" not in part:
|
||||
continue
|
||||
slug, _, hours_raw = part.partition("=")
|
||||
slug = slug.strip().lower()
|
||||
try:
|
||||
hours = int(hours_raw.strip())
|
||||
except ValueError:
|
||||
continue
|
||||
if slug:
|
||||
overrides[slug] = hours
|
||||
return overrides
|
||||
|
||||
|
||||
def analyse_rows(
|
||||
rows: list[dict[str, Any]],
|
||||
expected_slugs: list[str],
|
||||
max_age_hours: int,
|
||||
min_rows: int,
|
||||
max_age_overrides: dict[str, int] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
max_age_overrides = max_age_overrides or {}
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
# Aggregate per slug
|
||||
by_slug: dict[str, list[datetime]] = defaultdict(list)
|
||||
synthetic_skipped: dict[str, int] = defaultdict(int)
|
||||
for row in rows:
|
||||
slug = str(row.get("project_slug", "")).lower()
|
||||
occurred_at_raw = row.get("occurred_at", "")
|
||||
if not slug or not occurred_at_raw:
|
||||
continue
|
||||
message = str(row.get("message") or row.get("error_message") or "")
|
||||
if _SYNTHETIC_EVENT_RE.match(message.strip()):
|
||||
synthetic_skipped[slug] += 1
|
||||
continue
|
||||
try:
|
||||
dt = datetime.fromisoformat(str(occurred_at_raw).replace("Z", "+00:00"))
|
||||
by_slug[slug].append(dt)
|
||||
@@ -171,6 +204,7 @@ def analyse_rows(
|
||||
results: list[dict[str, Any]] = []
|
||||
for slug in expected_slugs:
|
||||
times = by_slug.get(slug, [])
|
||||
slug_max_age = max_age_overrides.get(slug, max_age_hours)
|
||||
if not times:
|
||||
status = "silent"
|
||||
hours_since = None
|
||||
@@ -178,7 +212,7 @@ def analyse_rows(
|
||||
else:
|
||||
latest = max(times)
|
||||
hours_since = (now - latest).total_seconds() / 3600
|
||||
status = "stale" if hours_since > max_age_hours else "ok"
|
||||
status = "stale" if hours_since > slug_max_age else "ok"
|
||||
|
||||
results.append(
|
||||
{
|
||||
@@ -187,6 +221,8 @@ def analyse_rows(
|
||||
"event_count": len(times),
|
||||
"latest_occurred_at": latest.isoformat() if latest else None,
|
||||
"hours_since_last_event": round(hours_since, 1) if hours_since is not None else None,
|
||||
"max_age_hours": slug_max_age,
|
||||
"synthetic_events_excluded": synthetic_skipped.get(slug, 0),
|
||||
}
|
||||
)
|
||||
|
||||
@@ -283,6 +319,7 @@ def main() -> int:
|
||||
hub_api_key = _env("PAPERCLIP_ERROR_API_KEY")
|
||||
expected_slugs_raw = _env("PAPERCLIP_FLEET_AUDIT_EXPECTED_SLUGS", "")
|
||||
max_age_hours = _env_int("PAPERCLIP_FLEET_AUDIT_MAX_AGE_HOURS", 168)
|
||||
max_age_overrides = _parse_max_age_overrides(_env("PAPERCLIP_FLEET_AUDIT_MAX_AGE_HOURS_OVERRIDES", ""))
|
||||
fetch_limit = _env_int("PAPERCLIP_FLEET_AUDIT_FETCH_LIMIT", 2000)
|
||||
min_rows = _env_int("PAPERCLIP_FLEET_AUDIT_MIN_ROWS", 20)
|
||||
project_id = _env("PAPERCLIP_FLEET_AUDIT_PROJECT_ID")
|
||||
@@ -308,6 +345,8 @@ def main() -> int:
|
||||
print(f"Fleet audit starting — hub: {hub_base}")
|
||||
print(f"Expected slugs: {expected_slugs}")
|
||||
print(f"Max age: {max_age_hours}h, min rows: {min_rows}, fetch limit: {fetch_limit}")
|
||||
if max_age_overrides:
|
||||
print(f"Max age overrides: {max_age_overrides}")
|
||||
|
||||
# Fetch hub data
|
||||
try:
|
||||
@@ -319,7 +358,7 @@ def main() -> int:
|
||||
print(f"Fetched {len(rows)} rows from hub")
|
||||
|
||||
# Analyse
|
||||
report = analyse_rows(rows, expected_slugs, max_age_hours, min_rows)
|
||||
report = analyse_rows(rows, expected_slugs, max_age_hours, min_rows, max_age_overrides)
|
||||
print(json.dumps(report, indent=2, default=str))
|
||||
|
||||
# Determine problems
|
||||
@@ -352,10 +391,11 @@ def main() -> int:
|
||||
else:
|
||||
hours = p["hours_since_last_event"]
|
||||
latest = p["latest_occurred_at"]
|
||||
slug_max_age = p["max_age_hours"]
|
||||
title = f"[fleet-audit] {slug} — stale ({hours:.0f}h sem eventos)"
|
||||
desc = (
|
||||
f"O slug `{slug}` está stale: último evento há **{hours:.1f}h** "
|
||||
f"(limiar: {max_age_hours}h).\n\n"
|
||||
f"(limiar: {slug_max_age}h).\n\n"
|
||||
f"Último evento: `{latest}`\n"
|
||||
f"Hub: `{hub_base}`\n"
|
||||
f"Auditoria: {report['audited_at']}"
|
||||
@@ -396,7 +436,7 @@ def main() -> int:
|
||||
elif st == "stale":
|
||||
hours = r["hours_since_last_event"]
|
||||
icon = "⚠️"
|
||||
detail = f"stale — último evento há {hours:.1f}h (limiar: {max_age_hours}h)"
|
||||
detail = f"stale — último evento há {hours:.1f}h (limiar: {r['max_age_hours']}h)"
|
||||
else:
|
||||
icon = "🔴"
|
||||
detail = "silencioso — sem eventos"
|
||||
|
||||
Reference in new issue
Block a user