diff --git a/.env.example b/.env.example index c841f14..2c999b3 100644 --- a/.env.example +++ b/.env.example @@ -118,6 +118,10 @@ MONITOR_EXTRA_NAMESPACES=vault,vault-transit,longhorn-system # LOGGING_QUERY_URL=http://127.0.0.1:3100 # LOGGING_QUERY_TIMEOUT=5m +# Bearer token accepted only by the internal Alertmanager webhook. In-cluster +# deployments load it from the vtafarm-alertmanager-webhook Secret. +ALERTMANAGER_WEBHOOK_TOKEN= + # Workload placement ships complete but activates in three operational gates: # disabled (labels/reports only), canary (listed numeric setup-session IDs), # then enabled. Changing modes does not require a different build. diff --git a/docs/tenant-alerting.md b/docs/tenant-alerting.md new file mode 100644 index 0000000..5dd8019 --- /dev/null +++ b/docs/tenant-alerting.md @@ -0,0 +1,135 @@ +# Tenant resource alerting + +This document is the contract between the observability stack, `vtafarm-api`, and the Portal. It covers the first alerting phase only; paid plan selection and automated capacity upgrades are intentionally separate. + +## Data flow + +1. Prometheus evaluates the VTA Farm rules every 15 seconds. +2. Alertmanager groups alerts by cluster, session, component, alert name, and resource. +3. Alertmanager sends firing and resolved notifications to the API webhook. +4. The API validates the shared bearer token, allowlists the alert name, maps the internal session label to its database session, and persists an incident. +5. The Portal reads tenant-isolated incidents from the API. Related log downloads query only the affected component and the incident window. + +Alertmanager is responsible for evaluation delivery, grouping, inhibition, and retries. The API remains the source of truth for user-visible incident history, read state, access control, and log downloads. + +## Alert catalogue + +| Alert name | Severity | Condition | Pending period | User impact | +| --- | --- | --- | --- | --- | +| `VTAFarmCPUUsageHigh` | warning | CPU usage is at least 75% but below 90% of its limit | 10 minutes | Sustained load; approaching throttling | +| `VTAFarmCPUUsageCritical` | critical | CPU usage is at least 90% of its limit | 5 minutes | CPU throttling is likely | +| `VTAFarmMemoryUsageHigh` | warning | working-set memory is at least 75% but below 90% of its limit | 10 minutes | Reduced memory headroom | +| `VTAFarmMemoryUsageCritical` | critical | working-set memory is at least 90% of its limit | 5 minutes | OOMKill risk | +| `VTAFarmStorageUsageHigh` | warning | persistent-volume usage is at least 75% but below 90% of capacity | 15 minutes | Storage increase should be planned | +| `VTAFarmStorageUsageCritical` | critical | persistent-volume usage is at least 90% of capacity | 5 minutes | Writes may fail soon | +| `VTAFarmMemoryOOMKilled` | critical | a container restarted in the last 5 minutes and its last termination reason is `OOMKilled` | immediate | Component restarted after reaching its memory limit | +| `VTAFarmComponentCrashLooping` | critical | a container remains in `CrashLoopBackOff` | 3 minutes | Component cannot start reliably | + +CPU and memory percentages use the Kubernetes container limits applied to the workload. Storage uses the PVC requested capacity. A missing limit or capacity produces no percentage alert instead of inventing a denominator. + +The table lists the normal-operation defaults. Stack 06 may override the CPU recording window, CPU and memory pending periods, and Alertmanager tenant grouping per cluster. Development uses a 1-minute CPU window, 1-minute warning and critical pending periods, a 10-second initial group wait, and a 30-second group interval for end-to-end testing. Staging and production retain the alert defaults above, use a 30-second initial group wait, and deliver subsequent firing or resolved state changes on a 1-minute group interval. + +During a rolling upgrade, two pods may coexist. The rules aggregate with `max` by session and component, so limits and usage do not double merely because an old and a new pod overlap. + +## Labels and annotations + +Every tenant rule sets: + +- `audience="tenant"`: required by both the Alertmanager route and API allowlist. +- `severity="warning"` or `severity="critical"`. +- `category="resource"` or `category="availability"`. +- `resource`: `cpu`, `memory`, `storage`, or `runtime`. +- `cluster`: supplied by Prometheus external labels. +- `label_session_id`: internal numeric setup-session ID propagated from the workload label. +- `label_app`: workload component label, mapped by the API to `vta`, `mediator`, `dids`, `vtc`, or `trust-registry`. + +Rules provide user-facing `summary` and `description` annotations. Percentage rules also provide `usage_percent`. The API never accepts arbitrary alert names from this endpoint; extending the rule catalogue requires extending its allowlist as part of the same release. + +## Routing, grouping, and inhibition + +The Alertmanager default receiver remains `null`. Only alerts with `audience="tenant"` are routed to the VTA Farm API webhook. + +Tenant alerts are grouped by `cluster`, `label_session_id`, `label_app`, `alertname`, and `resource`. A critical alert inhibits its warning counterpart for the same cluster, session, component, and resource. Alertmanager sends resolved notifications so the API can record the end of the incident and calculate the observed incident duration. + +The API suppresses user visibility when the session is not running or has an active upgrade task. Suppressed incidents remain available to administrators for diagnosis and never become tenant-visible later just because the upgrade completed. + +## Incident lifecycle and deduplication + +The incident identity is the tuple `(cluster, fingerprint, starts_at)`. Repeated Alertmanager deliveries update `last_seen_at` rather than creating duplicate rows. A resolved event closes the matching incident; a late firing delivery cannot reopen an already resolved incident. + +`downtime_seconds` is the elapsed time between `started_at` and `resolved_at`. It is an observed alert window, not an SLA calculation. For resource-pressure alerts it describes how long the alert condition remained active. + +## HTTP API + +The full schemas are in `/openapi.yaml` and the interactive reference at `/docs`. + +### Internal delivery + +- `POST /api/v1/internal/alertmanager/webhook` + - Requires `Authorization: Bearer `. + - Accepts the standard Alertmanager webhook payload. + - Returns `202` with accepted and ignored counts. + - Has a 1 MiB request limit. + +### User endpoints + +- `GET /api/v1/user/incidents`: incidents across all sessions owned by the current user. +- `GET /api/v1/setup/{id}/incidents`: incidents for one owned session. +- `GET /api/v1/setup/{id}/incidents/{incident_id}`: incident detail. +- `PATCH /api/v1/setup/{id}/incidents/read` with `{ "incident_ids": ["..."] }` or `{ "all": true }`: atomically mark selected or all visible session incidents read. +- `PATCH /api/v1/setup/{id}/incidents/{incident_id}` with `{ "read": true | false }`: update read state. +- `GET /api/v1/setup/{id}/incidents/{incident_id}/logs`: download related retained logs. + +List endpoints support `status=firing|resolved`, `resource=cpu|memory|storage|runtime|availability`, `range=24h|7d|30d|all`, `unread=true`, `page`, and `limit=1..100`. Responses include `page`, `page_size`, `total`, and `total_pages` alongside the incidents. + +### Admin endpoints + +- `GET /api/v1/admin/incidents` +- `GET /api/v1/admin/setup-sessions/{id}/incidents` +- `GET /api/v1/admin/setup-sessions/{id}/incidents/{incident_id}` +- `GET /api/v1/admin/setup-sessions/{id}/incidents/{incident_id}/logs` + +Admin lists include suppressed incidents. + +## Related log window + +The incident log archive contains Loki logs for only the affected component. Its query window begins five minutes before `started_at`; for a resolved incident it ends five minutes after `resolved_at`, capped at the current time. For an active incident it ends at the current time. Session creation time and the user's log-retention entitlement still bound the query. + +## Secret and deployment activation + +Use one randomly generated token value per cluster. Put the same value and revision in that cluster's stack 05 and stack 06 local `terraform.tfvars` files: + +```hcl +alertmanager_webhook_enabled = true +alertmanager_webhook_token = "" +alertmanager_webhook_token_revision = 1 +``` + +Stack 05 creates `vtafarm-alertmanager-webhook` in the API namespace. Stack 06 creates the same-named Secret in the monitoring namespace. Both contain the `ALERTMANAGER_WEBHOOK_TOKEN` key. The token variables are ephemeral and the Kubernetes provider receives them through its write-only `data_wo` field, so the values are not persisted in OpenTofu plan or state. Cluster tfvars are local, ignored files and must never be committed. + +To rotate a token, replace it in both stack files and increment both revisions to the same new integer. The revision changes the API and Alertmanager Pod templates so both workloads roll and load the new value. + +Activation order: + +1. Publish the API and Portal releases containing the incident feature. +2. Put those release versions in stack 05 and apply the database migration according to the release procedure. +3. Put the same generated token, enabled flag, and revision in the cluster's stack 05 and stack 06 tfvars. +4. Apply stack 05. It creates the API Secret and deploys the API and Portal releases. +5. Apply stack 06. It creates the monitoring Secret and enables Alertmanager delivery. +6. Confirm the Alertmanager configuration and fire a controlled test alert. + +Keep stack 06 `alertmanager_webhook_enabled` false until the API migration and release are ready. Alert rules can exist before webhook routing is enabled; their default receiver is `null`. + +## Verification + +After deployment: + +1. Confirm the Prometheus rules page shows all nine `VTAFarm*` rules without an evaluation error. +2. Confirm Alertmanager status shows the `vtafarm-api` receiver and the tenant route. +3. Send a valid controlled alert or temporarily load a test workload past a threshold. +4. Confirm one incident is created, repeated deliveries do not duplicate it, and a resolved notification closes it. +5. Confirm another user cannot read the incident or download its logs. +6. Confirm an alert produced during an upgrade is visible to an admin as suppressed and invisible to the tenant. +7. Confirm the Portal can open Metrics and download the related log archive from the incident. + +Do not lower production thresholds solely to test delivery. A dedicated synthetic rule with the tenant labels is safer, and should be removed immediately after validation. diff --git a/helm/vtafarm-api/templates/vtafarm-api/deployment.yaml b/helm/vtafarm-api/templates/vtafarm-api/deployment.yaml index 904203c..34a89b0 100644 --- a/helm/vtafarm-api/templates/vtafarm-api/deployment.yaml +++ b/helm/vtafarm-api/templates/vtafarm-api/deployment.yaml @@ -9,6 +9,10 @@ spec: {{- include "app.labels" . | nindent 6 }} template: metadata: + {{- with .Values.alerting.existingSecret }} + annotations: + vtafarm.ic3.dev/alertmanager-webhook-token-revision: {{ $.Values.alerting.tokenRevision | quote }} + {{- end }} labels: {{- include "app.labels" . | nindent 8 }} spec: @@ -35,6 +39,11 @@ spec: name: {{ .Values.name }}-config - secretRef: name: {{ .Values.name }}-secrets + {{- with .Values.alerting.existingSecret }} + - secretRef: + name: {{ . }} + optional: true + {{- end }} env: - name: DB_PASSWORD valueFrom: diff --git a/helm/vtafarm-api/values.yaml b/helm/vtafarm-api/values.yaml index a6e0524..01b2871 100644 --- a/helm/vtafarm-api/values.yaml +++ b/helm/vtafarm-api/values.yaml @@ -96,6 +96,12 @@ logging: queryURL: "" queryTimeout: "5m" +alerting: + # Pre-create this Secret with ALERTMANAGER_WEBHOOK_TOKEN. It is optional so + # the API remains deployable before Alertmanager routing is enabled. + existingSecret: "vtafarm-alertmanager-webhook" + tokenRevision: "0" + placement: mode: disabled canarySessionIDs: "" diff --git a/internal/apidocs/openapi.yaml b/internal/apidocs/openapi.yaml index 0757d8e..b4c686a 100644 --- a/internal/apidocs/openapi.yaml +++ b/internal/apidocs/openapi.yaml @@ -69,6 +69,10 @@ tags: description: User endpoints (requires `vtafarm_user` cookie) - name: User — Metrics description: Tenant-isolated historical and live session metrics. + - name: User — Incidents + description: Tenant-visible resource pressure and availability incidents. + - name: Internal — Alerting + description: Cluster-internal Alertmanager delivery endpoints. - name: User — Passkeys description: | Manage passkeys bound to the authenticated user account (requires `vtafarm_user` cookie). @@ -92,8 +96,70 @@ components: scheme: bearer bearerFormat: opaque description: Environment-scoped MONITOR_TOKEN for external uptime polling. + AlertmanagerBearerAuth: + type: http + scheme: bearer + bearerFormat: opaque + description: Shared token mounted into Alertmanager and the API from separate Kubernetes Secrets. schemas: + Incident: + type: object + additionalProperties: false + required: [id, session_id, cluster, alert_name, type, component, severity, status, title, message, started_at, last_seen_at, created_at, updated_at] + properties: + id: {type: string, format: uuid} + session_id: {type: string, description: Public setup-session identifier (the VTA name).} + cluster: {type: string} + alert_name: {type: string} + type: {type: string} + component: {type: string, enum: [vta, mediator, dids, vtc, trust-registry]} + resource: {type: string, enum: [cpu, memory, storage, runtime, availability]} + severity: {type: string, enum: [warning, critical]} + status: {type: string, enum: [firing, resolved]} + title: {type: string} + message: {type: string} + usage_percent: {type: number, minimum: 0} + started_at: {type: string, format: date-time} + resolved_at: {type: string, format: date-time} + last_seen_at: {type: string, format: date-time} + read_at: {type: string, format: date-time} + downtime_seconds: {type: integer, minimum: 0} + suppressed: {type: boolean, description: Admin-only visibility for incidents hidden during provisioning or upgrades.} + created_at: {type: string, format: date-time} + updated_at: {type: string, format: date-time} + + IncidentList: + type: object + additionalProperties: false + required: [incidents, page, page_size, total, total_pages] + properties: + incidents: + type: array + items: {$ref: '#/components/schemas/Incident'} + page: {type: integer, minimum: 1} + page_size: {type: integer, minimum: 1, maximum: 100} + total: {type: integer, minimum: 0} + total_pages: {type: integer, minimum: 0} + + AlertmanagerWebhook: + type: object + required: [status, alerts] + properties: + status: {type: string, enum: [firing, resolved]} + alerts: + type: array + items: + type: object + required: [status, labels, annotations, startsAt, fingerprint] + properties: + status: {type: string, enum: [firing, resolved]} + labels: {type: object, additionalProperties: {type: string}} + annotations: {type: object, additionalProperties: {type: string}} + startsAt: {type: string, format: date-time} + endsAt: {type: string, format: date-time} + fingerprint: {type: string} + MaintenanceState: type: object additionalProperties: false @@ -6111,6 +6177,203 @@ paths: "409": { description: Farm DID host is not ready, content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } } } "422": { description: Public DID does not resolve, content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } } } + /api/v1/internal/alertmanager/webhook: + post: + summary: Receive tenant alerts from Alertmanager + description: Accepts only the documented tenant alert allowlist. Deliveries are idempotent by cluster, fingerprint, and start time; resolved notifications close the existing incident. + tags: [Internal — Alerting] + security: [{AlertmanagerBearerAuth: []}] + requestBody: + required: true + content: + application/json: + schema: {$ref: '#/components/schemas/AlertmanagerWebhook'} + responses: + '202': {description: Delivery processed; reports accepted and ignored alert counts.} + '400': {description: Invalid Alertmanager payload.} + '401': {description: Missing or invalid webhook token.} + '503': {description: Webhook token is not configured on the API.} + + /api/v1/user/incidents: + get: + summary: List incidents across the current user's sessions + tags: [User — Incidents] + security: [{CookieAuthUser: []}] + parameters: + - {name: status, in: query, schema: {type: string, enum: [firing, resolved]}} + - {name: resource, in: query, schema: {type: string, enum: [cpu, memory, storage, runtime, availability]}} + - {name: range, in: query, schema: {type: string, enum: [24h, 7d, 30d, all]}} + - {name: unread, in: query, schema: {type: boolean}} + - {name: page, in: query, schema: {type: integer, minimum: 1, default: 1}} + - {name: limit, in: query, schema: {type: integer, minimum: 1, maximum: 100, default: 50}} + responses: + '200': {description: "Visible, newest-first incidents.", content: {application/json: {schema: {$ref: '#/components/schemas/IncidentList'}}}} + '400': {description: Invalid filter.} + '401': {description: Missing or invalid user cookie.} + + /api/v1/setup/{id}/incidents: + get: + summary: List incidents for a session + tags: [User — Incidents] + security: [{CookieAuthUser: []}] + parameters: + - {name: id, in: path, required: true, schema: {type: string}} + - {name: status, in: query, schema: {type: string, enum: [firing, resolved]}} + - {name: resource, in: query, schema: {type: string, enum: [cpu, memory, storage, runtime, availability]}} + - {name: range, in: query, schema: {type: string, enum: [24h, 7d, 30d, all]}} + - {name: unread, in: query, schema: {type: boolean}} + - {name: page, in: query, schema: {type: integer, minimum: 1, default: 1}} + - {name: limit, in: query, schema: {type: integer, minimum: 1, maximum: 100, default: 50}} + responses: + '200': {description: "Visible, newest-first incidents.", content: {application/json: {schema: {$ref: '#/components/schemas/IncidentList'}}}} + '401': {description: Missing or invalid user cookie.} + '404': {description: Session not found or belongs to another user.} + + /api/v1/setup/{id}/incidents/read: + patch: + summary: Mark selected or all session incidents read + tags: [User — Incidents] + security: [{CookieAuthUser: []}] + parameters: + - {name: id, in: path, required: true, schema: {type: string}} + requestBody: + required: true + content: + application/json: + schema: + oneOf: + - type: object + additionalProperties: false + required: [incident_ids] + properties: + incident_ids: + type: array + minItems: 1 + maxItems: 100 + items: {type: string, format: uuid} + - type: object + additionalProperties: false + required: [all] + properties: + all: {const: true} + responses: + '200': + description: Number of previously unread incidents marked read. + content: + application/json: + schema: + type: object + additionalProperties: false + required: [updated] + properties: {updated: {type: integer, minimum: 0}} + '400': {description: Invalid or ambiguous selection.} + '401': {description: Missing or invalid user cookie.} + '404': {description: Session not found or belongs to another user.} + + /api/v1/setup/{id}/incidents/{incident_id}: + get: + summary: Get a session incident + tags: [User — Incidents] + security: [{CookieAuthUser: []}] + parameters: + - {name: id, in: path, required: true, schema: {type: string}} + - {name: incident_id, in: path, required: true, schema: {type: string, format: uuid}} + responses: + '200': {description: Incident detail., content: {application/json: {schema: {$ref: '#/components/schemas/Incident'}}}} + '404': {description: Session or incident not found.} + patch: + summary: Mark a session incident read or unread + tags: [User — Incidents] + security: [{CookieAuthUser: []}] + parameters: + - {name: id, in: path, required: true, schema: {type: string}} + - {name: incident_id, in: path, required: true, schema: {type: string, format: uuid}} + requestBody: + required: true + content: + application/json: + schema: + type: object + additionalProperties: false + required: [read] + properties: {read: {type: boolean}} + responses: + '200': {description: Updated incident., content: {application/json: {schema: {$ref: '#/components/schemas/Incident'}}}} + '400': {description: The read field is missing.} + '404': {description: Session or incident not found.} + + /api/v1/setup/{id}/incidents/{incident_id}/logs: + get: + summary: Download logs related to an incident + description: Returns a ZIP containing retained Loki logs for the affected component, bounded to five minutes before and after the incident. The user's retention entitlement still applies. + tags: [User — Incidents] + security: [{CookieAuthUser: []}] + parameters: + - {name: id, in: path, required: true, schema: {type: string}} + - {name: incident_id, in: path, required: true, schema: {type: string, format: uuid}} + responses: + '200': {description: ZIP archive., content: {application/zip: {schema: {type: string, format: binary}}}} + '404': {description: Session or incident not found.} + '410': {description: Incident is outside the user's log-retention window.} + '503': {description: Retained logging is not configured.} + + /api/v1/admin/incidents: + get: + summary: List incidents across all sessions + tags: [Admin] + security: [{CookieAuthAdmin: []}] + parameters: + - {name: status, in: query, schema: {type: string, enum: [firing, resolved]}} + - {name: resource, in: query, schema: {type: string, enum: [cpu, memory, storage, runtime, availability]}} + - {name: range, in: query, schema: {type: string, enum: [24h, 7d, 30d, all]}} + - {name: unread, in: query, schema: {type: boolean}} + - {name: page, in: query, schema: {type: integer, minimum: 1, default: 1}} + - {name: limit, in: query, schema: {type: integer, minimum: 1, maximum: 100, default: 50}} + responses: + '200': {description: "Newest-first incidents, including suppressed records.", content: {application/json: {schema: {$ref: '#/components/schemas/IncidentList'}}}} + + /api/v1/admin/setup-sessions/{id}/incidents: + get: + summary: List incidents for an admin-visible session + tags: [Admin] + security: [{CookieAuthAdmin: []}] + parameters: + - {name: id, in: path, required: true, schema: {type: string}} + - {name: status, in: query, schema: {type: string, enum: [firing, resolved]}} + - {name: resource, in: query, schema: {type: string, enum: [cpu, memory, storage, runtime, availability]}} + - {name: range, in: query, schema: {type: string, enum: [24h, 7d, 30d, all]}} + - {name: unread, in: query, schema: {type: boolean}} + - {name: page, in: query, schema: {type: integer, minimum: 1, default: 1}} + - {name: limit, in: query, schema: {type: integer, minimum: 1, maximum: 100, default: 50}} + responses: + '200': {description: "Newest-first incidents, including suppressed records.", content: {application/json: {schema: {$ref: '#/components/schemas/IncidentList'}}}} + '404': {description: Session not found.} + + /api/v1/admin/setup-sessions/{id}/incidents/{incident_id}: + get: + summary: Get an admin-visible incident + tags: [Admin] + security: [{CookieAuthAdmin: []}] + parameters: + - {name: id, in: path, required: true, schema: {type: string}} + - {name: incident_id, in: path, required: true, schema: {type: string, format: uuid}} + responses: + '200': {description: Incident detail., content: {application/json: {schema: {$ref: '#/components/schemas/Incident'}}}} + '404': {description: Session or incident not found.} + + /api/v1/admin/setup-sessions/{id}/incidents/{incident_id}/logs: + get: + summary: Download logs related to an admin-visible incident + tags: [Admin] + security: [{CookieAuthAdmin: []}] + parameters: + - {name: id, in: path, required: true, schema: {type: string}} + - {name: incident_id, in: path, required: true, schema: {type: string, format: uuid}} + responses: + '200': {description: ZIP archive., content: {application/zip: {schema: {type: string, format: binary}}}} + '404': {description: Session or incident not found.} + '503': {description: Retained logging is not configured.} + /api/v1/admin/setup-sessions/{id}/metrics/meta: get: summary: Get metrics selectors for an admin-visible session diff --git a/internal/config/config.go b/internal/config/config.go index 11cb072..0eca4aa 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -47,6 +47,7 @@ type Config struct { Placement PlacementConfig Metrics MetricsConfig Logging LoggingConfig + Alerting AlertingConfig } type MetricsConfig struct { @@ -66,6 +67,10 @@ type LoggingConfig struct { QueryTimeout time.Duration } +type AlertingConfig struct { + WebhookToken string +} + const ( PlacementDisabled = "disabled" PlacementCanary = "canary" @@ -300,6 +305,9 @@ func Load() *Config { QueryURL: getEnv("LOGGING_QUERY_URL", ""), QueryTimeout: getEnvDuration("LOGGING_QUERY_TIMEOUT", 5*time.Minute), }, + Alerting: AlertingConfig{ + WebhookToken: getEnv("ALERTMANAGER_WEBHOOK_TOKEN", ""), + }, Vault: VaultConfig{ Addr: getEnv("VAULT_ADDR", ""), VTAAddr: getEnv("VAULT_VTA_ADDR", "https://vault.vault.svc:8200"), diff --git a/internal/handler/incidents.go b/internal/handler/incidents.go new file mode 100644 index 0000000..21d37e3 --- /dev/null +++ b/internal/handler/incidents.go @@ -0,0 +1,537 @@ +package handler + +import ( + "crypto/subtle" + "encoding/json" + "errors" + "fmt" + "net/http" + "os" + "strconv" + "strings" + "time" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "gorm.io/gorm" + + "github.com/ic3software/vtafarm-api/internal/middleware" + "github.com/ic3software/vtafarm-api/internal/model" +) + +const incidentLogPadding = 5 * time.Minute + +var tenantAlertTypes = map[string]string{ + "VTAFarmCPUUsageHigh": "cpu_usage_high", + "VTAFarmCPUUsageCritical": "cpu_usage_critical", + "VTAFarmMemoryUsageHigh": "memory_usage_high", + "VTAFarmMemoryUsageCritical": "memory_usage_critical", + "VTAFarmStorageUsageHigh": "storage_usage_high", + "VTAFarmStorageUsageCritical": "storage_usage_critical", + "VTAFarmMemoryOOMKilled": "memory_oom", + "VTAFarmComponentCrashLooping": "component_crash_looping", +} + +type alertmanagerWebhook struct { + Status string `json:"status"` + Alerts []alertmanagerAlert `json:"alerts"` +} + +type alertmanagerAlert struct { + Status string `json:"status"` + Labels map[string]string `json:"labels"` + Annotations map[string]string `json:"annotations"` + StartsAt time.Time `json:"startsAt"` + EndsAt time.Time `json:"endsAt"` + Fingerprint string `json:"fingerprint"` +} + +type incidentResponse struct { + model.Incident + SessionID string `json:"session_id"` + DowntimeSeconds *int64 `json:"downtime_seconds,omitempty"` + Suppressed bool `json:"suppressed,omitempty"` +} + +type incidentListResponse struct { + Incidents []incidentResponse `json:"incidents"` + Page int `json:"page"` + PageSize int `json:"page_size"` + Total int64 `json:"total"` + TotalPages int `json:"total_pages"` +} + +type markIncidentsReadResponse struct { + Updated int64 `json:"updated"` +} + +func (h *SetupHandler) ConfigureAlertmanagerWebhook(token string) { + h.alertmanagerWebhookToken = strings.TrimSpace(token) +} + +func (h *SetupHandler) AlertmanagerWebhook(c *gin.Context) { + if h.alertmanagerWebhookToken == "" { + c.JSON(http.StatusServiceUnavailable, gin.H{"error": "alertmanager webhook is not configured"}) + return + } + authorization := c.GetHeader("Authorization") + if !strings.HasPrefix(authorization, "Bearer ") { + c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid alertmanager webhook token"}) + return + } + provided := strings.TrimSpace(strings.TrimPrefix(authorization, "Bearer ")) + if len(provided) != len(h.alertmanagerWebhookToken) || subtle.ConstantTimeCompare([]byte(provided), []byte(h.alertmanagerWebhookToken)) != 1 { + c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid alertmanager webhook token"}) + return + } + c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 1<<20) + var payload alertmanagerWebhook + if err := c.ShouldBindJSON(&payload); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid alertmanager webhook payload"}) + return + } + accepted, ignored := 0, 0 + for _, alert := range payload.Alerts { + ok, err := h.recordTenantAlert(c, alert) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "could not record alert"}) + return + } + if ok { + accepted++ + } else { + ignored++ + } + } + c.JSON(http.StatusAccepted, gin.H{"accepted": accepted, "ignored": ignored}) +} + +func (h *SetupHandler) recordTenantAlert(c *gin.Context, alert alertmanagerAlert) (bool, error) { + alertName := alert.Labels["alertname"] + incidentType, allowed := tenantAlertTypes[alertName] + if !allowed || alert.Labels["audience"] != "tenant" { + return false, nil + } + sessionID64, err := strconv.ParseUint(alert.Labels["label_session_id"], 10, 64) + if err != nil || sessionID64 == 0 || alert.Fingerprint == "" || alert.StartsAt.IsZero() { + return false, nil + } + var session model.SetupSession + if err := h.db.WithContext(c.Request.Context()).First(&session, uint(sessionID64)).Error; err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return false, nil + } + return false, err + } + status := alert.Status + if status != model.IncidentFiring && status != model.IncidentResolved { + return false, nil + } + component := publicIncidentComponent(alert.Labels["label_app"]) + if component == "" { + return false, nil + } + now := time.Now().UTC() + labelsJSON, _ := json.Marshal(alert.Labels) + annotationsJSON, _ := json.Marshal(alert.Annotations) + usagePercent := parseUsagePercent(alert.Annotations["usage_percent"]) + severity := alert.Labels["severity"] + if severity != "warning" && severity != "critical" { + severity = "warning" + } + title := strings.TrimSpace(alert.Annotations["summary"]) + if title == "" { + title = alertName + } + message := strings.TrimSpace(alert.Annotations["description"]) + if message == "" { + message = title + } + resolvedAt := (*time.Time)(nil) + if status == model.IncidentResolved { + end := alert.EndsAt.UTC() + if end.IsZero() || end.Before(alert.StartsAt) { + end = now + } + resolvedAt = &end + } + suppressed, err := h.suppressIncident(c, &session) + if err != nil { + return false, err + } + lookup := model.Incident{Cluster: alert.Labels["cluster"], Fingerprint: alert.Fingerprint, StartedAt: alert.StartsAt.UTC()} + if lookup.Cluster == "" { + lookup.Cluster = "unknown" + } + return true, h.db.WithContext(c.Request.Context()).Transaction(func(tx *gorm.DB) error { + var existing model.Incident + err := tx.Where("cluster = ? AND fingerprint = ? AND started_at = ?", lookup.Cluster, lookup.Fingerprint, lookup.StartedAt).First(&existing).Error + if err == nil { + if existing.Status == model.IncidentResolved && status == model.IncidentFiring { + return nil + } + updates := map[string]any{ + "status": status, "severity": severity, "title": title, "message": message, + "usage_percent": usagePercent, "resolved_at": resolvedAt, "last_seen_at": now, + "suppressed": suppressed || existing.Suppressed, "labels": string(labelsJSON), "annotations": string(annotationsJSON), "updated_at": now, + } + return tx.Model(&existing).Updates(updates).Error + } + if !errors.Is(err, gorm.ErrRecordNotFound) { + return err + } + incident := model.Incident{ + PublicID: uuid.NewString(), SetupSessionID: session.ID, + Cluster: lookup.Cluster, Fingerprint: lookup.Fingerprint, AlertName: alertName, + IncidentType: incidentType, Component: component, Resource: alert.Labels["resource"], + Severity: severity, Status: status, Title: title, Message: message, UsagePercent: usagePercent, + StartedAt: lookup.StartedAt, ResolvedAt: resolvedAt, LastSeenAt: now, Suppressed: suppressed, + LabelsJSON: string(labelsJSON), AnnotationsJSON: string(annotationsJSON), + } + return tx.Create(&incident).Error + }) +} + +func (h *SetupHandler) suppressIncident(c *gin.Context, session *model.SetupSession) (bool, error) { + if session.Status != "running" { + return true, nil + } + var count int64 + err := h.db.WithContext(c.Request.Context()).Table("upgrade_tasks"). + Where("session_id = ? AND status IN ?", session.ID, []string{ + model.UpgradeTaskPending, model.UpgradeTaskRunning, model.UpgradeTaskRollingBack, + }).Count(&count).Error + return count > 0, err +} + +func publicIncidentComponent(label string) string { + switch label { + case "vta", "fs-vta": + return "vta" + case "fs-mediator": + return "mediator" + case "fs-dids": + return "dids" + case "fs-vtc": + return "vtc" + case "fs-trust-registry": + return "trust-registry" + default: + return "" + } +} + +func parseUsagePercent(value string) *float64 { + value = strings.TrimSpace(strings.TrimSuffix(value, "%")) + if value == "" { + return nil + } + parsed, err := strconv.ParseFloat(value, 64) + if err != nil { + return nil + } + return &parsed +} + +func (h *SetupHandler) UserIncidents(c *gin.Context) { + userID := c.MustGet(middleware.ContextUserID).(uint) + h.listIncidents(c, h.db.Joins("JOIN setup_sessions ON setup_sessions.id = incidents.setup_session_id"). + Where("setup_sessions.user_id = ? AND incidents.suppressed = FALSE", userID), true) +} + +func (h *SetupHandler) SessionIncidents(c *gin.Context) { + if session := h.userSession(c); session != nil { + h.listIncidents(c, h.db.Where("setup_session_id = ? AND suppressed = FALSE", session.ID), true) + } +} + +func (h *SetupHandler) AdminIncidents(c *gin.Context) { + h.listIncidents(c, h.db.Model(&model.Incident{}), false) +} + +func (h *SetupHandler) AdminSessionIncidents(c *gin.Context) { + if session := h.adminSession(c); session != nil { + h.listIncidents(c, h.db.Where("setup_session_id = ?", session.ID), false) + } +} + +func (h *SetupHandler) listIncidents(c *gin.Context, query *gorm.DB, hideSuppressed bool) { + if status := c.Query("status"); status != "" { + if status != model.IncidentFiring && status != model.IncidentResolved { + c.JSON(http.StatusBadRequest, gin.H{"error": "status must be firing or resolved"}) + return + } + query = query.Where("incidents.status = ?", status) + } + if c.Query("unread") == "true" { + query = query.Where("incidents.read_at IS NULL") + } + if resource := c.Query("resource"); resource != "" { + switch resource { + case "cpu", "memory", "storage", "runtime", "availability": + query = query.Where("incidents.resource = ?", resource) + default: + c.JSON(http.StatusBadRequest, gin.H{"error": "resource must be cpu, memory, storage, runtime, or availability"}) + return + } + } + if incidentRange := c.Query("range"); incidentRange != "" && incidentRange != "all" { + var duration time.Duration + switch incidentRange { + case "24h": + duration = 24 * time.Hour + case "7d": + duration = 7 * 24 * time.Hour + case "30d": + duration = 30 * 24 * time.Hour + default: + c.JSON(http.StatusBadRequest, gin.H{"error": "range must be 24h, 7d, 30d, or all"}) + return + } + query = query.Where("incidents.started_at >= ?", time.Now().UTC().Add(-duration)) + } + page, _ := strconv.Atoi(c.DefaultQuery("page", "1")) + if page < 1 { + c.JSON(http.StatusBadRequest, gin.H{"error": "page must be at least 1"}) + return + } + limit, _ := strconv.Atoi(c.DefaultQuery("limit", "50")) + if limit < 1 || limit > 100 { + c.JSON(http.StatusBadRequest, gin.H{"error": "limit must be between 1 and 100"}) + return + } + var total int64 + if err := query.Session(&gorm.Session{}).Model(&model.Incident{}).Count(&total).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "could not count incidents"}) + return + } + var incidents []model.Incident + if err := query.Order("incidents.started_at DESC").Offset((page - 1) * limit).Limit(limit).Find(&incidents).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "could not load incidents"}) + return + } + responses := make([]incidentResponse, 0, len(incidents)) + for _, incident := range incidents { + if hideSuppressed && incident.Suppressed { + continue + } + var session model.SetupSession + if err := h.db.Select("vta_name").First(&session, incident.SetupSessionID).Error; err != nil { + continue + } + responses = append(responses, toIncidentResponse(incident, session.VtaName)) + } + totalPages := int((total + int64(limit) - 1) / int64(limit)) + c.JSON(http.StatusOK, incidentListResponse{ + Incidents: responses, Page: page, PageSize: limit, Total: total, TotalPages: totalPages, + }) +} + +func toIncidentResponse(incident model.Incident, sessionID string) incidentResponse { + return incidentResponse{ + Incident: incident, SessionID: sessionID, DowntimeSeconds: incident.DowntimeSeconds(), Suppressed: incident.Suppressed, + } +} + +func (h *SetupHandler) GetSessionIncident(c *gin.Context) { + if session := h.userSession(c); session != nil { + h.getIncident(c, session, false) + } +} + +func (h *SetupHandler) AdminGetSessionIncident(c *gin.Context) { + if session := h.adminSession(c); session != nil { + h.getIncident(c, session, true) + } +} + +func (h *SetupHandler) getIncident(c *gin.Context, session *model.SetupSession, admin bool) { + incident := h.findIncident(c, session.ID, admin) + if incident == nil { + return + } + c.JSON(http.StatusOK, toIncidentResponse(*incident, session.VtaName)) +} + +func (h *SetupHandler) MarkSessionIncidentRead(c *gin.Context) { + session := h.userSession(c) + if session == nil { + return + } + incident := h.findIncident(c, session.ID, false) + if incident == nil { + return + } + var input struct { + Read *bool `json:"read"` + } + if err := c.ShouldBindJSON(&input); err != nil || input.Read == nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "read is required"}) + return + } + var readAt *time.Time + if *input.Read { + now := time.Now().UTC() + readAt = &now + } + if err := h.db.Model(incident).Update("read_at", readAt).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "could not update incident"}) + return + } + incident.ReadAt = readAt + c.JSON(http.StatusOK, toIncidentResponse(*incident, session.VtaName)) +} + +func (h *SetupHandler) MarkSessionIncidentsRead(c *gin.Context) { + session := h.userSession(c) + if session == nil { + return + } + var input struct { + IncidentIDs []string `json:"incident_ids"` + All bool `json:"all"` + } + if err := c.ShouldBindJSON(&input); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"}) + return + } + if input.All == (len(input.IncidentIDs) > 0) { + c.JSON(http.StatusBadRequest, gin.H{"error": "provide incident_ids or all, but not both"}) + return + } + if len(input.IncidentIDs) > 100 { + c.JSON(http.StatusBadRequest, gin.H{"error": "incident_ids cannot contain more than 100 items"}) + return + } + if !input.All { + seen := make(map[string]struct{}, len(input.IncidentIDs)) + for _, incidentID := range input.IncidentIDs { + if _, err := uuid.Parse(incidentID); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "incident_ids must contain UUIDs"}) + return + } + seen[incidentID] = struct{}{} + } + input.IncidentIDs = input.IncidentIDs[:0] + for incidentID := range seen { + input.IncidentIDs = append(input.IncidentIDs, incidentID) + } + } + now := time.Now().UTC() + query := h.db.WithContext(c.Request.Context()).Model(&model.Incident{}). + Where("setup_session_id = ? AND suppressed = FALSE AND read_at IS NULL", session.ID) + if !input.All { + query = query.Where("public_id IN ?", input.IncidentIDs) + } + result := query.Update("read_at", &now) + if result.Error != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "could not update incidents"}) + return + } + c.JSON(http.StatusOK, markIncidentsReadResponse{Updated: result.RowsAffected}) +} + +func (h *SetupHandler) findIncident(c *gin.Context, sessionID uint, admin bool) *model.Incident { + query := h.db.Where("public_id = ? AND setup_session_id = ?", c.Param("incident_id"), sessionID) + if !admin { + query = query.Where("suppressed = FALSE") + } + var incident model.Incident + if err := query.First(&incident).Error; err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "incident not found"}) + return nil + } + return &incident +} + +func (h *SetupHandler) SessionIncidentLogs(c *gin.Context) { + if session := h.userSession(c); session != nil { + h.exportIncidentLogs(c, session, false) + } +} + +func (h *SetupHandler) AdminSessionIncidentLogs(c *gin.Context) { + if session := h.adminSession(c); session != nil { + h.exportIncidentLogs(c, session, true) + } +} + +func (h *SetupHandler) exportIncidentLogs(c *gin.Context, session *model.SetupSession, admin bool) { + incident := h.findIncident(c, session.ID, admin) + if incident == nil { + return + } + if h.logquery == nil || h.k8s == nil { + c.JSON(http.StatusServiceUnavailable, gin.H{"error": "retained logging is not configured"}) + return + } + var owner model.User + if err := h.db.First(&owner, session.UserID).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "could not load log retention entitlement"}) + return + } + entitlement := logExportEntitlement(owner, admin) + now := time.Now().UTC() + start := incident.StartedAt.Add(-incidentLogPadding) + if session.CreatedAt.After(start) { + start = session.CreatedAt.UTC() + } + if start.Before(now.Add(-time.Duration(entitlement.RetentionDays) * 24 * time.Hour)) { + c.JSON(http.StatusGone, gin.H{"error": "incident logs are outside the retention window"}) + return + } + end := now + if incident.ResolvedAt != nil { + end = incident.ResolvedAt.Add(incidentLogPadding) + if end.After(now) { + end = now + } + } + var component *exportComponent + for _, candidate := range exportComponents(session) { + if candidate.name == incident.Component { + copy := candidate + component = © + break + } + } + if component == nil { + c.JSON(http.StatusConflict, gin.H{"error": "incident component is not part of this session"}) + return + } + logsFile, err := os.CreateTemp("", "vtafarm-incident-*.log") + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to prepare incident log export"}) + return + } + logsPath := logsFile.Name() + defer os.Remove(logsPath) + namespace := h.k8s.UserNamespace(strconv.FormatUint(uint64(session.UserID), 10)) + entries, queryErr := h.logquery.WriteRange(c.Request.Context(), componentLogQuery(namespace, session, *component), start, end, logsFile) + closeErr := logsFile.Close() + if queryErr != nil || closeErr != nil { + c.JSON(http.StatusBadGateway, gin.H{"error": "could not query incident logs"}) + return + } + archive, err := os.CreateTemp("", "vtafarm-incident-logs-*.zip") + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to prepare incident log archive"}) + return + } + archivePath := archive.Name() + defer os.Remove(archivePath) + rangeDays := int(end.Sub(start)/(24*time.Hour)) + 1 + manifest := logExportManifest{RetentionDays: entitlement.RetentionDays, RangeDays: rangeDays, Start: start, End: end, Entries: entries} + if err := writeRetainedLogArchive(archive, []retainedLogFile{{name: component.name + ".log", path: logsPath}}, manifest); err != nil { + archive.Close() + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to build incident log archive"}) + return + } + if err := archive.Close(); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to finalize incident log archive"}) + return + } + c.Header("X-Log-Source", logSourceRetained) + c.Header("X-Log-Retention-Days", strconv.Itoa(entitlement.RetentionDays)) + c.FileAttachment(archivePath, fmt.Sprintf("%s-%s-%s-logs.zip", session.VtaName, incident.Component, incident.PublicID)) +} diff --git a/internal/handler/incidents_test.go b/internal/handler/incidents_test.go new file mode 100644 index 0000000..49abf73 --- /dev/null +++ b/internal/handler/incidents_test.go @@ -0,0 +1,158 @@ +package handler + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + + "github.com/ic3software/vtafarm-api/internal/middleware" + "github.com/ic3software/vtafarm-api/internal/model" + "github.com/ic3software/vtafarm-api/internal/testutil" +) + +func TestAlertmanagerWebhookLifecycleAndUserIncidentAPI(t *testing.T) { + gin.SetMode(gin.TestMode) + db := testutil.Postgres(t) + user := newAdminTestUser(t) + if err := db.Create(&user).Error; err != nil { + t.Fatal(err) + } + session := model.SetupSession{ + UserID: user.ID, VtaName: "alert-session", Mode: model.ModeVtaOnly, + Status: "running", Domain: "example.com", Subdomain: "alert-session", + } + if err := db.Create(&session).Error; err != nil { + t.Fatal(err) + } + h := &SetupHandler{db: db} + h.ConfigureAlertmanagerWebhook("test-token") + router := gin.New() + router.POST("/webhook", h.AlertmanagerWebhook) + router.GET("/setup/:id/incidents", func(c *gin.Context) { + c.Set(middleware.ContextUserID, user.ID) + h.SessionIncidents(c) + }) + router.GET("/user/incidents", func(c *gin.Context) { + c.Set(middleware.ContextUserID, user.ID) + h.UserIncidents(c) + }) + router.PATCH("/setup/:id/incidents/read", func(c *gin.Context) { + c.Set(middleware.ContextUserID, user.ID) + h.MarkSessionIncidentsRead(c) + }) + router.PATCH("/setup/:id/incidents/:incident_id", func(c *gin.Context) { + c.Set(middleware.ContextUserID, user.ID) + h.MarkSessionIncidentRead(c) + }) + + started := time.Date(2026, 11, 24, 14, 32, 0, 0, time.UTC) + payload := func(status string, endsAt time.Time) string { + body, err := json.Marshal(alertmanagerWebhook{Status: status, Alerts: []alertmanagerAlert{{ + Status: status, StartsAt: started, EndsAt: endsAt, Fingerprint: "fingerprint-1", + Labels: map[string]string{ + "alertname": "VTAFarmMemoryUsageCritical", "audience": "tenant", "cluster": "dev", + "label_session_id": fmt.Sprint(session.ID), "label_app": "vta", "resource": "memory", "severity": "critical", + }, + Annotations: map[string]string{"summary": "Memory usage is above 90%", "description": "Memory pressure", "usage_percent": "93.5"}, + }}}) + if err != nil { + t.Fatal(err) + } + return string(body) + } + request := func(method, path, body, token string) *httptest.ResponseRecorder { + t.Helper() + w := httptest.NewRecorder() + req := httptest.NewRequest(method, path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + router.ServeHTTP(w, req) + return w + } + if w := request(http.MethodPost, "/webhook", payload("firing", time.Time{}), ""); w.Code != http.StatusUnauthorized { + t.Fatalf("unauthorized webhook = %d: %s", w.Code, w.Body.String()) + } + for range 2 { + if w := request(http.MethodPost, "/webhook", payload("firing", time.Time{}), "test-token"); w.Code != http.StatusAccepted { + t.Fatalf("firing webhook = %d: %s", w.Code, w.Body.String()) + } + } + var incidents []model.Incident + if err := db.Find(&incidents).Error; err != nil { + t.Fatal(err) + } + if len(incidents) != 1 || incidents[0].Status != model.IncidentFiring || incidents[0].UsagePercent == nil || *incidents[0].UsagePercent != 93.5 { + t.Fatalf("firing incidents = %+v", incidents) + } + resolvedAt := started.Add(3 * time.Minute) + if w := request(http.MethodPost, "/webhook", payload("resolved", resolvedAt), "test-token"); w.Code != http.StatusAccepted { + t.Fatalf("resolved webhook = %d: %s", w.Code, w.Body.String()) + } + w := request(http.MethodGet, "/setup/alert-session/incidents", "", "") + if w.Code != http.StatusOK { + t.Fatalf("list incidents = %d: %s", w.Code, w.Body.String()) + } + var response struct { + Incidents []incidentResponse `json:"incidents"` + } + if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil { + t.Fatal(err) + } + if len(response.Incidents) != 1 || response.Incidents[0].Status != model.IncidentResolved || + response.Incidents[0].DowntimeSeconds == nil || *response.Incidents[0].DowntimeSeconds != 180 { + t.Fatalf("resolved incidents = %+v", response.Incidents) + } + w = request(http.MethodGet, "/setup/alert-session/incidents?status=resolved&resource=memory&range=all&page=1&limit=1", "", "") + if w.Code != http.StatusOK { + t.Fatalf("filtered incidents = %d: %s", w.Code, w.Body.String()) + } + var filtered incidentListResponse + if err := json.Unmarshal(w.Body.Bytes(), &filtered); err != nil { + t.Fatal(err) + } + if len(filtered.Incidents) != 1 || filtered.Total != 1 || filtered.Page != 1 || filtered.PageSize != 1 || filtered.TotalPages != 1 { + t.Fatalf("filtered incident page = %+v", filtered) + } + for _, path := range []string{ + "/setup/alert-session/incidents?resource=network", + "/setup/alert-session/incidents?range=2d", + "/setup/alert-session/incidents?page=0", + } { + if w := request(http.MethodGet, path, "", ""); w.Code != http.StatusBadRequest { + t.Fatalf("invalid filter %q = %d: %s", path, w.Code, w.Body.String()) + } + } + if w := request(http.MethodGet, "/user/incidents", "", ""); w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"session_id":"alert-session"`) { + t.Fatalf("user incidents = %d: %s", w.Code, w.Body.String()) + } + incidentID := response.Incidents[0].PublicID + if w := request(http.MethodPatch, "/setup/alert-session/incidents/read", `{}`, ""); w.Code != http.StatusBadRequest { + t.Fatalf("missing bulk selection = %d: %s", w.Code, w.Body.String()) + } + w = request(http.MethodPatch, "/setup/alert-session/incidents/read", `{"incident_ids":["`+incidentID+`"]}`, "") + if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"updated":1`) { + t.Fatalf("bulk mark selected read = %d: %s", w.Code, w.Body.String()) + } + if err := db.Model(&model.Incident{}).Where("public_id = ?", incidentID).Update("read_at", nil).Error; err != nil { + t.Fatal(err) + } + w = request(http.MethodPatch, "/setup/alert-session/incidents/read", `{"all":true}`, "") + if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"updated":1`) { + t.Fatalf("bulk mark all read = %d: %s", w.Code, w.Body.String()) + } + if w := request(http.MethodPatch, "/setup/alert-session/incidents/"+incidentID, `{}`, ""); w.Code != http.StatusBadRequest { + t.Fatalf("missing read field = %d: %s", w.Code, w.Body.String()) + } + w = request(http.MethodPatch, "/setup/alert-session/incidents/"+incidentID, `{"read":true}`, "") + if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"read_at"`) { + t.Fatalf("mark read = %d: %s", w.Code, w.Body.String()) + } +} diff --git a/internal/handler/setup.go b/internal/handler/setup.go index 5be3776..2ee6ef5 100644 --- a/internal/handler/setup.go +++ b/internal/handler/setup.go @@ -47,6 +47,8 @@ type SetupHandler struct { didsGhcr *ghcr.Client // nil when not configured vtcGhcr *ghcr.Client // nil when not configured trustRegistryGhcr *ghcr.Client + + alertmanagerWebhookToken string } func NewSetupHandler( diff --git a/internal/model/incident.go b/internal/model/incident.go new file mode 100644 index 0000000..4a871b7 --- /dev/null +++ b/internal/model/incident.go @@ -0,0 +1,45 @@ +package model + +import "time" + +const ( + IncidentFiring = "firing" + IncidentResolved = "resolved" +) + +type Incident struct { + ID uint `gorm:"primaryKey;autoIncrement" json:"-"` + PublicID string `gorm:"not null;uniqueIndex" json:"id"` + SetupSessionID uint `gorm:"not null;index" json:"-"` + Cluster string `gorm:"not null" json:"cluster"` + Fingerprint string `gorm:"not null" json:"-"` + AlertName string `gorm:"not null" json:"alert_name"` + IncidentType string `gorm:"not null" json:"type"` + Component string `gorm:"not null" json:"component"` + Resource string `gorm:"not null;default:''" json:"resource,omitempty"` + Severity string `gorm:"not null" json:"severity"` + Status string `gorm:"not null" json:"status"` + Title string `gorm:"not null" json:"title"` + Message string `gorm:"not null" json:"message"` + UsagePercent *float64 `json:"usage_percent,omitempty"` + StartedAt time.Time `gorm:"not null;index" json:"started_at"` + ResolvedAt *time.Time `json:"resolved_at,omitempty"` + LastSeenAt time.Time `gorm:"not null" json:"last_seen_at"` + ReadAt *time.Time `json:"read_at,omitempty"` + Suppressed bool `gorm:"not null;default:false" json:"-"` + LabelsJSON string `gorm:"column:labels;type:jsonb;not null" json:"-"` + AnnotationsJSON string `gorm:"column:annotations;type:jsonb;not null" json:"-"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +func (i Incident) DowntimeSeconds() *int64 { + if i.ResolvedAt == nil { + return nil + } + seconds := int64(i.ResolvedAt.Sub(i.StartedAt).Seconds()) + if seconds < 0 { + seconds = 0 + } + return &seconds +} diff --git a/internal/router/router.go b/internal/router/router.go index a61e2d9..d9fbe7b 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -57,7 +57,7 @@ func Setup( r.Use(cors.New(cors.Config{ AllowOrigins: allowOrigins, - AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, + AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"}, AllowHeaders: []string{"Authorization", "Content-Type", "Idempotency-Key", "X-VTA-Claim-Token"}, ExposeHeaders: []string{"Content-Length", "Content-Disposition"}, AllowCredentials: true, @@ -113,6 +113,7 @@ func Setup( registryGhcr = ghcr.New(cfg.GHCR.Token, cfg.GHCR.Owner, cfg.GHCR.TrustRegistryPackageName) } sh.ConfigureTrustRegistry(registryGhcr) + sh.ConfigureAlertmanagerWebhook(cfg.Alerting.WebhookToken) var placementService *placement.Service if k8sClient != nil { var placementErr error @@ -130,6 +131,7 @@ func Setup( } v1 := r.Group("/api/v1") + v1.POST("/internal/alertmanager/webhook", middleware.NoStore(), sh.AlertmanagerWebhook) v1.GET("/status/maintenance", middleware.NoStore(), maintenanceH.Status) v1.GET("/auth/keyring/config", middleware.NoStore(), middleware.RateLimit(60, time.Minute), trustTask.WalletSignInConfig) statusHandler := handler.NewStatusHandler(db, k8sClient, handler.StatusConfig{ @@ -240,6 +242,10 @@ func Setup( adminAuth.GET("/admin/image-defaults", sh.AdminImageDefaults) adminAuth.PUT("/admin/image-defaults", sh.AdminSaveImageDefaults) adminAuth.GET("/admin/setup-sessions", sh.AdminListSessions) + adminAuth.GET("/admin/incidents", sh.AdminIncidents) + adminAuth.GET("/admin/setup-sessions/:id/incidents", sh.AdminSessionIncidents) + adminAuth.GET("/admin/setup-sessions/:id/incidents/:incident_id", sh.AdminGetSessionIncident) + adminAuth.GET("/admin/setup-sessions/:id/incidents/:incident_id/logs", sh.AdminSessionIncidentLogs) adminAuth.POST("/admin/setup-sessions/:id/recover", workflow("vta_recovery", true), sh.AdminRecoverSession) adminAuth.GET("/admin/setup-sessions/:id/resources", sh.AdminSessionResources) adminAuth.PUT("/admin/setup-sessions/resources", workflow("resource_update", true), sh.AdminApplySessionResources) @@ -366,6 +372,7 @@ func Setup( walletBindings := handler.NewWalletLoginBindingHandler(db) { userAuth.GET("/user/me", uh.Me) + userAuth.GET("/user/incidents", sh.UserIncidents) userAuth.GET("/user/wallet-login-bindings", walletBindings.List) userAuth.DELETE("/user/wallet-login-bindings/:id", walletBindings.Revoke) userAuth.POST("/user/passkeys/register/begin", pkh.RegisterBegin) @@ -387,6 +394,11 @@ func Setup( userAuth.GET("/setup/:id/metrics/meta", middleware.NoStore(), middleware.RateLimit(120, time.Minute), metricsH.Meta) userAuth.GET("/setup/:id/metrics/range", middleware.NoStore(), middleware.RateLimit(120, time.Minute), metricsH.Range) userAuth.GET("/setup/:id/metrics/live", middleware.NoStore(), metricsH.Live) + userAuth.GET("/setup/:id/incidents", sh.SessionIncidents) + userAuth.PATCH("/setup/:id/incidents/read", sh.MarkSessionIncidentsRead) + userAuth.GET("/setup/:id/incidents/:incident_id", sh.GetSessionIncident) + userAuth.PATCH("/setup/:id/incidents/:incident_id", sh.MarkSessionIncidentRead) + userAuth.GET("/setup/:id/incidents/:incident_id/logs", sh.SessionIncidentLogs) userAuth.GET("/setup/:id/trust-registry", sh.GetTrustRegistry) userAuth.POST("/setup/:id/trust-registry", workflow("trust_registry", false), sh.EnableTrustRegistry) userAuth.POST("/setup/:id/recover", workflow("vta_recovery", false), sh.RecoverSession) diff --git a/migrations/000056_incidents.down.sql b/migrations/000056_incidents.down.sql new file mode 100644 index 0000000..8a80144 --- /dev/null +++ b/migrations/000056_incidents.down.sql @@ -0,0 +1 @@ +DROP TABLE incidents; diff --git a/migrations/000056_incidents.up.sql b/migrations/000056_incidents.up.sql new file mode 100644 index 0000000..5175e6b --- /dev/null +++ b/migrations/000056_incidents.up.sql @@ -0,0 +1,33 @@ +CREATE TABLE incidents ( + id BIGSERIAL PRIMARY KEY, + public_id TEXT NOT NULL UNIQUE, + setup_session_id BIGINT NOT NULL REFERENCES setup_sessions(id) ON DELETE CASCADE, + cluster TEXT NOT NULL, + fingerprint TEXT NOT NULL, + alert_name TEXT NOT NULL, + incident_type TEXT NOT NULL, + component TEXT NOT NULL, + resource TEXT NOT NULL DEFAULT '', + severity TEXT NOT NULL CHECK (severity IN ('warning', 'critical')), + status TEXT NOT NULL CHECK (status IN ('firing', 'resolved')), + title TEXT NOT NULL, + message TEXT NOT NULL, + usage_percent DOUBLE PRECISION, + started_at TIMESTAMPTZ NOT NULL, + resolved_at TIMESTAMPTZ, + last_seen_at TIMESTAMPTZ NOT NULL, + read_at TIMESTAMPTZ, + suppressed BOOLEAN NOT NULL DEFAULT FALSE, + labels JSONB NOT NULL DEFAULT '{}'::jsonb, + annotations JSONB NOT NULL DEFAULT '{}'::jsonb, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + CONSTRAINT incidents_alert_delivery_unique UNIQUE (cluster, fingerprint, started_at) +); + +CREATE INDEX incidents_session_started_idx + ON incidents (setup_session_id, started_at DESC); + +CREATE INDEX incidents_active_idx + ON incidents (status, severity, started_at DESC) + WHERE suppressed = FALSE;