diff --git a/docs/api/openapi.json b/docs/api/openapi.json index 9810e75ae..1bfae60ea 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -17,6 +17,58 @@ ], "type": "object" }, + "CreateEndpointBody": { + "description": "A new endpoint.", + "properties": { + "description": { + "description": "A note for people: what the endpoint is for.", + "examples": [ + "Deploy bot" + ], + "type": [ + "string", + "null" + ] + }, + "enabled": { + "description": "Defaults to `true`.", + "examples": [ + true + ], + "type": [ + "boolean", + "null" + ] + }, + "events": { + "description": "Event types to receive, or `[\"*\"]` for every event. Defaults to every\nevent.", + "examples": [ + [ + "run.completed", + "run.failed" + ] + ], + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "url": { + "description": "An `https://` address on the public internet.", + "examples": [ + "https://hooks.example.com/coderhelm" + ], + "type": "string" + } + }, + "required": [ + "url" + ], + "type": "object" + }, "CreatePlan": { "description": "A new plan.", "examples": [ @@ -97,6 +149,26 @@ ], "type": "object" }, + "CreatedEndpoint": { + "description": "A new endpoint and its signing secret. The secret is shown here once;\nreveal it later with `GET …/secret`.", + "properties": { + "endpoint": { + "$ref": "#/components/schemas/WebhookEndpoint" + }, + "secret": { + "description": "`whsec_` and 32 random bytes in base64. Verify signatures with it.", + "examples": [ + "whsec_C2FVsBQIhrscChlQIMV+b5sSYspob7oD7vS8nSUIQ2c=" + ], + "type": "string" + } + }, + "required": [ + "endpoint", + "secret" + ], + "type": "object" + }, "CreatedPlan": { "description": "The plan that was made.", "properties": { @@ -137,6 +209,52 @@ ], "type": "object" }, + "DeliveryAttempt": { + "description": "One attempt.", + "properties": { + "at": { + "description": "When it was sent.", + "examples": [ + "2026-10-26T14:31:47.901Z" + ], + "type": "string" + }, + "code": { + "description": "The endpoint's HTTP status, when it answered.", + "examples": [ + 401 + ], + "format": "int32", + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "duration_ms": { + "description": "How long it took.", + "examples": [ + 112 + ], + "format": "int64", + "minimum": 0, + "type": "integer" + }, + "error": { + "description": "What went wrong, when it did.", + "examples": [ + "Answered 401: bad signature" + ], + "type": "string" + } + }, + "required": [ + "at", + "duration_ms", + "error" + ], + "type": "object" + }, "ErrorBody": { "description": "The body of every error an API key request gets.", "examples": [ @@ -1327,6 +1445,73 @@ ], "type": "object" }, + "ReplayBody": { + "description": "Which kept events to send again.", + "properties": { + "only_failed": { + "description": "Only events whose deliveries to this endpoint all failed, or that it\nnever got. Defaults to `false` (every event it subscribes to).", + "examples": [ + true + ], + "type": "boolean" + }, + "since": { + "description": "RFC 3339. At most 14 days ago (events are kept that long).", + "examples": [ + "2026-10-25T00:00:00Z" + ], + "type": "string" + }, + "until": { + "description": "RFC 3339. Defaults to now.", + "examples": [ + "2026-10-26T00:00:00Z" + ], + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "since" + ], + "type": "object" + }, + "ReplayResult": { + "description": "What a replay queued.", + "properties": { + "capped": { + "description": "More matched than one replay sends (500); replay again from the last one.", + "examples": [ + false + ], + "type": "boolean" + }, + "found": { + "description": "Kept events in the range (of every type).", + "examples": [ + 40 + ], + "minimum": 0, + "type": "integer" + }, + "queued": { + "description": "Events queued to send again.", + "examples": [ + 12 + ], + "minimum": 0, + "type": "integer" + } + }, + "required": [ + "queued", + "found", + "capped" + ], + "type": "object" + }, "Repo": { "description": "A repository connected to the team.", "properties": { @@ -1720,6 +1905,49 @@ ], "type": "object" }, + "RotateBody": { + "description": "How long the old secret keeps signing.", + "properties": { + "overlap_hours": { + "description": "Hours the old secret keeps signing beside the new one: 0 to 168.\nDefaults to 24. With 0 the old secret stops at once.", + "examples": [ + 24 + ], + "format": "int64", + "type": [ + "integer", + "null" + ] + } + }, + "type": "object" + }, + "RotatedSecret": { + "description": "A rotated secret.", + "properties": { + "previous_secret_expires_at": { + "description": "Until then, requests carry a second signature made with the old one.", + "examples": [ + "2026-10-27T09:00:00Z" + ], + "type": [ + "string", + "null" + ] + }, + "secret": { + "description": "The new secret. Requests are signed with it from now on.", + "examples": [ + "whsec_k0q8vX2mZp5Rr3t1YbN6cH9dLwE4fJ7aS1uG0iT2oQs=" + ], + "type": "string" + } + }, + "required": [ + "secret" + ], + "type": "object" + }, "Run": { "description": "One run, in full.", "properties": { @@ -2411,6 +2639,32 @@ ], "type": "object" }, + "SecretView": { + "description": "An endpoint's signing secret.", + "properties": { + "previous_secret_expires_at": { + "description": "While the previous secret still signs too, when it stops.", + "examples": [ + null + ], + "type": [ + "string", + "null" + ] + }, + "secret": { + "description": "The current secret.", + "examples": [ + "whsec_C2FVsBQIhrscChlQIMV+b5sSYspob7oD7vS8nSUIQ2c=" + ], + "type": "string" + } + }, + "required": [ + "secret" + ], + "type": "object" + }, "SnsEnvelope": { "description": "An Amazon SNS message, as SNS posts it to an HTTPS subscription.", "examples": [ @@ -2516,6 +2770,57 @@ ], "type": "object" }, + "UpdateEndpointBody": { + "description": "Changes to an endpoint. Only the fields sent change.", + "properties": { + "description": { + "description": "A new note.", + "examples": [ + "Deploy bot (staging)" + ], + "type": [ + "string", + "null" + ] + }, + "enabled": { + "description": "Turning an endpoint back on starts its failure count again.", + "examples": [ + true + ], + "type": [ + "boolean", + "null" + ] + }, + "events": { + "description": "The new subscription list, or `[\"*\"]`.", + "examples": [ + [ + "*" + ] + ], + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "url": { + "description": "A new `https://` address.", + "examples": [ + "https://hooks.example.com/coderhelm/v2" + ], + "type": [ + "string", + "null" + ] + } + }, + "type": "object" + }, "Usage": { "description": "The team's token usage this month.", "properties": { @@ -2764,51 +3069,309 @@ "used" ], "type": "object" - } - }, - "securitySchemes": { - "api_key": { - "bearerFormat": "chk__", - "description": "A team API key, made by an admin under Settings, API keys. Send it as `Authorization: Bearer chk_...`.", - "scheme": "bearer", - "type": "http" - }, - "github_oidc": { - "bearerFormat": "JWT", - "description": "A GitHub Actions OIDC token requested with the audience `coderhelm`, from a workflow run of a repository connected to your team.", - "scheme": "bearer", - "type": "http" - }, - "github_signature": { - "description": "`sha256=` and the hex HMAC-SHA256 of the raw body, keyed with the GitHub App's webhook secret.", - "in": "header", - "name": "X-Hub-Signature-256", - "type": "apiKey" - }, - "jira_signature": { - "description": "Only when the team generated a webhook secret: `sha256=` and the hex HMAC-SHA256 of the raw body, keyed with that secret.", - "in": "header", - "name": "X-Hub-Signature", - "type": "apiKey" - }, - "notion_signature": { - "description": "`sha256=` and the hex HMAC-SHA256 of the raw body, keyed with the subscription's verification token.", - "in": "header", - "name": "X-Notion-Signature", - "type": "apiKey" - }, - "relay_signature": { - "description": "`t=,d=,v1=`: the HMAC-SHA256 of `..`, keyed with the install's relay key.", - "in": "header", - "name": "X-CoderHelm-Relay-Signature", - "type": "apiKey" }, - "sanity_signature": { - "description": "`t=,v1=` and the base64url HMAC-SHA256 of `.`, keyed with the token in the address.", - "in": "header", - "name": "sanity-webhook-signature", - "type": "apiKey" - } + "WebhookDelivery": { + "description": "One delivery of an event to an endpoint.", + "properties": { + "attempts": { + "description": "Every attempt, oldest first (the last 20).", + "items": { + "$ref": "#/components/schemas/DeliveryAttempt" + }, + "type": "array" + }, + "created_at": { + "description": "When the event was first sent to this endpoint.", + "examples": [ + "2026-10-26T14:31:47.780Z" + ], + "type": "string" + }, + "event": { + "description": "The event type.", + "examples": [ + "run.completed" + ], + "type": "string" + }, + "event_id": { + "description": "The event's id: the same `webhook-id` on every attempt.", + "examples": [ + "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W" + ], + "type": "string" + }, + "headers": { + "additionalProperties": { + "type": "string" + }, + "description": "The request's headers, the signature removed.", + "examples": [ + { + "webhook-id": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "webhook-signature": "[redacted]", + "webhook-timestamp": "1792420307" + } + ], + "propertyNames": { + "type": "string" + }, + "type": "object" + }, + "id": { + "description": "The Deliveries record's id.", + "examples": [ + "01JBDLVR5T8V1W4X7Y0Z3A6B9C" + ], + "type": "string" + }, + "next_retry_at": { + "description": "When the next retry is due, while one is.", + "examples": [ + null + ], + "type": [ + "string", + "null" + ] + }, + "outcome": { + "description": "What happened, in a few words.", + "examples": [ + "Refused (401)" + ], + "type": "string" + }, + "payload_preview": { + "description": "The body that was sent, with secret-looking values masked, cut at 4 KB.", + "examples": [ + "{\n \"id\": \"evt_01JBEVNT8M1N4P7Q0R3S6T9V2W\" …" + ], + "type": "string" + }, + "reason": { + "description": "A reason code when it failed.", + "examples": [ + "webhook_refused" + ], + "type": "string" + }, + "reason_fix": { + "description": "What to do about it.", + "examples": [ + "Check that the endpoint verifies signatures with the right secret and accepts JSON, then press Resend." + ], + "type": "string" + }, + "reason_message": { + "description": "The reason in plain words.", + "examples": [ + "Your webhook endpoint refused the event (a 4xx answer), so it isn't retried." + ], + "type": "string" + }, + "status": { + "description": "`pending` (being retried), `handled` (delivered) or `failed`.", + "examples": [ + "failed" + ], + "type": "string" + } + }, + "required": [ + "id", + "event_id", + "event", + "status", + "outcome", + "reason", + "reason_message", + "reason_fix", + "attempts", + "created_at", + "payload_preview", + "headers" + ], + "type": "object" + }, + "WebhookEndpoint": { + "description": "A webhook endpoint. Never carries its secret.", + "properties": { + "created_at": { + "description": "When it was added.", + "examples": [ + "2026-10-20T09:00:00Z" + ], + "type": "string" + }, + "created_by": { + "description": "Who added it.", + "examples": [ + "lead@example.com" + ], + "type": "string" + }, + "description": { + "description": "A note for people: what the endpoint is for.", + "examples": [ + "Deploy bot" + ], + "type": "string" + }, + "disabled_reason": { + "description": "Why it's off: `manual` (turned off by a person) or `failing` (turned\noff by CoderHelm after 5 days of failed deliveries). Empty while on.", + "examples": [ + "" + ], + "type": "string" + }, + "enabled": { + "description": "Off: nothing is sent (tests still are).", + "examples": [ + true + ], + "type": "boolean" + }, + "events": { + "description": "Event types it receives; `[\"*\"]` is every event, including types\nadded later.", + "examples": [ + [ + "run.completed", + "run.failed" + ] + ], + "items": { + "type": "string" + }, + "type": "array" + }, + "failing_since": { + "description": "The first failed delivery since the last success.", + "examples": [ + null + ], + "type": [ + "string", + "null" + ] + }, + "id": { + "description": "`ep_` and a ULID.", + "examples": [ + "ep_01jbendpt4a7b0c3d6e9f2g5h8" + ], + "type": "string" + }, + "last_failure_at": { + "description": "The last failed attempt.", + "examples": [ + "2026-10-25T08:02:11.004Z" + ], + "type": [ + "string", + "null" + ] + }, + "last_success_at": { + "description": "The last delivered attempt.", + "examples": [ + "2026-10-26T14:31:48.120Z" + ], + "type": [ + "string", + "null" + ] + }, + "previous_secret_expires_at": { + "description": "While a rotated-out secret still signs too, when it stops.", + "examples": [ + "2026-10-27T09:00:00Z" + ], + "type": [ + "string", + "null" + ] + }, + "secret_hint": { + "description": "The last characters of the signing secret.", + "examples": [ + "whsec_…Q2c=" + ], + "type": "string" + }, + "updated_at": { + "description": "When it last changed.", + "examples": [ + "2026-10-20T09:00:00Z" + ], + "type": "string" + }, + "url": { + "description": "Where events are POSTed. Always `https://`.", + "examples": [ + "https://hooks.example.com/coderhelm" + ], + "type": "string" + } + }, + "required": [ + "id", + "url", + "description", + "events", + "enabled", + "disabled_reason", + "secret_hint", + "created_at", + "created_by", + "updated_at" + ], + "type": "object" + } + }, + "securitySchemes": { + "api_key": { + "bearerFormat": "chk__", + "description": "A team API key, made by an admin under Settings, API keys. Send it as `Authorization: Bearer chk_...`.", + "scheme": "bearer", + "type": "http" + }, + "github_oidc": { + "bearerFormat": "JWT", + "description": "A GitHub Actions OIDC token requested with the audience `coderhelm`, from a workflow run of a repository connected to your team.", + "scheme": "bearer", + "type": "http" + }, + "github_signature": { + "description": "`sha256=` and the hex HMAC-SHA256 of the raw body, keyed with the GitHub App's webhook secret.", + "in": "header", + "name": "X-Hub-Signature-256", + "type": "apiKey" + }, + "jira_signature": { + "description": "Only when the team generated a webhook secret: `sha256=` and the hex HMAC-SHA256 of the raw body, keyed with that secret.", + "in": "header", + "name": "X-Hub-Signature", + "type": "apiKey" + }, + "notion_signature": { + "description": "`sha256=` and the hex HMAC-SHA256 of the raw body, keyed with the subscription's verification token.", + "in": "header", + "name": "X-Notion-Signature", + "type": "apiKey" + }, + "relay_signature": { + "description": "`t=,d=,v1=`: the HMAC-SHA256 of `..`, keyed with the install's relay key.", + "in": "header", + "name": "X-CoderHelm-Relay-Signature", + "type": "apiKey" + }, + "sanity_signature": { + "description": "`t=,v1=` and the base64url HMAC-SHA256 of `.`, keyed with the token in the address.", + "in": "header", + "name": "sanity-webhook-signature", + "type": "apiKey" + } } }, "info": { @@ -2816,7 +3379,7 @@ "name": "CoderHelm support", "url": "https://docs.coderhelm.com/api" }, - "description": "The CoderHelm API lets your own programs start and follow CoderHelm's work: list and inspect runs, retry or cancel them, create and run plans, read the reviewer's reviews, and check token usage.\n\nEvery request is authenticated with a team API key sent as a bearer token. Admins create keys in the dashboard under Settings, API keys. A key holds scopes, never more than the admin who made it, and has its own rate limit.\n\nCI jobs upload test reports with a GitHub Actions OIDC token instead of a key, and the webhooks are verified by their signatures.", + "description": "The CoderHelm API lets your own programs start and follow CoderHelm's work: list and inspect runs, retry or cancel them, create and run plans, read the reviewer's reviews, check token usage, and manage the webhook endpoints CoderHelm sends your team's events to.\n\nEvery request is authenticated with a team API key sent as a bearer token. Admins create keys in the dashboard under Settings, API keys. A key holds scopes, never more than the admin who made it, and has its own rate limit.\n\nCI jobs upload test reports with a GitHub Actions OIDC token instead of a key, and the webhooks are verified by their signatures.", "license": { "identifier": "MIT", "name": "MIT" @@ -4638,65 +5201,69 @@ ] } }, - "/webhooks/alerts/sns": { - "post": { - "description": "Subscribe CoderHelm to an SNS topic with an HTTPS subscription to this address and add the topic under Alert routes in the dashboard. Every message's SNS signature is checked (signature versions 1 and 2) and the signing certificate must come from SNS. The subscription is confirmed automatically once the topic has an enabled route; messages from topics without one are accepted and ignored. A message that matches one of the route's rules becomes a run that opens a pull request.", - "operationId": "receiveSnsAlert", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/SnsEnvelope" - } - } - }, - "description": "The SNS message.", - "required": true - }, - "responses": { - "200": { - "description": "Accepted." - }, - "400": { - "description": "Not an SNS message." - }, - "403": { - "description": "The SNS signature did not verify." - } - }, - "security": [ - {} - ], - "summary": "AWS SNS alerts", - "tags": [ - "Webhooks" - ] - } - }, - "/webhooks/ci/tests/quarantine": { + "/api/webhooks/endpoints": { "get": { - "description": "Returns the tests quarantined for the repository the OIDC token was issued to, so a CI step can keep their failures from failing the build. For Playwright, pass `playwright_grep_invert` to `--grep-invert`.", - "operationId": "listQuarantinedTests", + "description": "The team's webhook endpoints, oldest first. Secrets are never listed.", + "operationId": "listWebhookEndpoints", "responses": { "200": { "content": { "application/json": { + "example": { + "endpoints": [ + { + "created_at": "2026-10-20T09:00:00Z", + "created_by": "lead@example.com", + "description": "Deploy bot", + "disabled_reason": "", + "enabled": true, + "events": [ + "*" + ], + "id": "ep_01jbendpt4a7b0c3d6e9f2g5h8", + "secret_hint": "whsec_…Q2c=", + "updated_at": "2026-10-20T09:00:00Z", + "url": "https://hooks.example.com/coderhelm" + } + ], + "max": 20 + }, "schema": { - "$ref": "#/components/schemas/Quarantine" + "type": "object" } } }, - "description": "The quarantined tests." - }, - "401": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ErrorBody" + "description": "The endpoints.", + "headers": { + "RateLimit-Limit": { + "description": "Requests this key may make in a minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Remaining": { + "description": "Requests left in the current minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Reset": { + "description": "Seconds until the current minute ends and the count starts over.", + "schema": { + "type": "integer" + } + } + } + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" } } }, - "description": "The token is not a valid GitHub Actions OIDC token for CoderHelm." + "description": "The key is missing, malformed, revoked or expired, or the person who made it left the team." }, "403": { "content": { @@ -4706,57 +5273,110 @@ } } }, - "description": "The repository is not connected, or E2E results are off." + "description": "The key lacks the scope this endpoint needs (`missing_scope`)." + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Over the key's rate limit (`rate_limited`), or, for endpoints that start work, over the team's monthly token limit (`token_limit_reached`).", + "headers": { + "RateLimit-Limit": { + "description": "Requests this key may make in a minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Remaining": { + "description": "Requests left in the current minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Reset": { + "description": "Seconds until the current minute ends and the count starts over.", + "schema": { + "type": "integer" + } + }, + "Retry-After": { + "description": "With `rate_limited`: seconds to wait before trying again.", + "schema": { + "type": "integer" + } + } + } + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Something failed on CoderHelm's side. Safe to retry reads." } }, "security": [ { - "github_oidc": [] + "api_key": [ + "webhooks" + ] } ], - "summary": "List quarantined tests", + "summary": "List webhook endpoints", "tags": [ - "CI" + "Webhook endpoints" ] - } - }, - "/webhooks/ci/tests/results": { + }, "post": { - "description": "Takes one test report from a CI job whose results never reach GitHub (a device farm, say), signed with the job's GitHub Actions OIDC token instead of a CoderHelm secret. Request the token with the audience `coderhelm`. CoderHelm checks it was issued for a workflow run of a repository connected to your team with E2E results turned on, then reads the report like one from GitHub: flaky tests, failure groups and quarantine.", - "operationId": "uploadTestResults", - "parameters": [ - { - "description": "The report's file name. Must end in `.json` (Playwright or Cucumber JSON) or `.xml` (JUnit XML). Default `report.json`.", - "example": "results.json", - "in": "query", - "name": "name", - "required": false, - "schema": { - "type": "string" - } - } - ], + "description": "Adds an endpoint and makes its signing secret, which this answer shows once. The address must be `https://` and on the public internet: private, local and cloud metadata addresses are refused here and again before every delivery. A team has at most 20 endpoints.", + "operationId": "createWebhookEndpoint", "requestBody": { "content": { - "application/octet-stream": { + "application/json": { "schema": { - "type": "string" + "$ref": "#/components/schemas/CreateEndpointBody" } } }, - "description": "The report file, at most 6 MB.", "required": true }, "responses": { - "200": { + "201": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CiUploadResult" + "$ref": "#/components/schemas/CreatedEndpoint" } } }, - "description": "The report is stored and queued." + "description": "Created. Keep the secret.", + "headers": { + "RateLimit-Limit": { + "description": "Requests this key may make in a minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Remaining": { + "description": "Requests left in the current minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Reset": { + "description": "Seconds until the current minute ends and the count starts over.", + "schema": { + "type": "integer" + } + } + } }, "400": { "content": { @@ -4766,7 +5386,7 @@ } } }, - "description": "Not a report CoderHelm can read, or it has no tests." + "description": "The address, events or description were refused; `field` names which." }, "401": { "content": { @@ -4776,7 +5396,7 @@ } } }, - "description": "The token is not a valid GitHub Actions OIDC token for CoderHelm." + "description": "The key is missing, malformed, revoked or expired, or the person who made it left the team." }, "403": { "content": { @@ -4786,9 +5406,9 @@ } } }, - "description": "The repository is not connected, or E2E results are off." + "description": "The key lacks the scope this endpoint needs (`missing_scope`)." }, - "413": { + "409": { "content": { "application/json": { "schema": { @@ -4796,90 +5416,3896 @@ } } }, - "description": "Empty, or larger than 6 MB." + "description": "The team already has 20 endpoints." + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Over the key's rate limit (`rate_limited`), or, for endpoints that start work, over the team's monthly token limit (`token_limit_reached`).", + "headers": { + "RateLimit-Limit": { + "description": "Requests this key may make in a minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Remaining": { + "description": "Requests left in the current minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Reset": { + "description": "Seconds until the current minute ends and the count starts over.", + "schema": { + "type": "integer" + } + }, + "Retry-After": { + "description": "With `rate_limited`: seconds to wait before trying again.", + "schema": { + "type": "integer" + } + } + } + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Something failed on CoderHelm's side. Safe to retry reads." } }, "security": [ { - "github_oidc": [] + "api_key": [ + "webhooks" + ] + } + ], + "summary": "Create a webhook endpoint", + "tags": [ + "Webhook endpoints" + ] + } + }, + "/api/webhooks/endpoints/{endpoint_id}": { + "delete": { + "description": "Stops all deliveries to it, including retries already queued.", + "operationId": "deleteWebhookEndpoint", + "parameters": [ + { + "description": "The endpoint's id.", + "example": "ep_01jbendpt4a7b0c3d6e9f2g5h8", + "in": "path", + "name": "endpoint_id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "example": { + "deleted": true + }, + "schema": { + "type": "object" + } + } + }, + "description": "Deleted.", + "headers": { + "RateLimit-Limit": { + "description": "Requests this key may make in a minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Remaining": { + "description": "Requests left in the current minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Reset": { + "description": "Seconds until the current minute ends and the count starts over.", + "schema": { + "type": "integer" + } + } + } + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The key is missing, malformed, revoked or expired, or the person who made it left the team." + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The key lacks the scope this endpoint needs (`missing_scope`)." + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "No such endpoint on this team." + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Over the key's rate limit (`rate_limited`), or, for endpoints that start work, over the team's monthly token limit (`token_limit_reached`).", + "headers": { + "RateLimit-Limit": { + "description": "Requests this key may make in a minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Remaining": { + "description": "Requests left in the current minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Reset": { + "description": "Seconds until the current minute ends and the count starts over.", + "schema": { + "type": "integer" + } + }, + "Retry-After": { + "description": "With `rate_limited`: seconds to wait before trying again.", + "schema": { + "type": "integer" + } + } + } + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Something failed on CoderHelm's side. Safe to retry reads." + } + }, + "security": [ + { + "api_key": [ + "webhooks" + ] + } + ], + "summary": "Delete a webhook endpoint", + "tags": [ + "Webhook endpoints" + ] + }, + "get": { + "description": "One endpoint, with its health: when it last delivered, and since when it has been failing, if it is.", + "operationId": "getWebhookEndpoint", + "parameters": [ + { + "description": "The endpoint's id.", + "example": "ep_01jbendpt4a7b0c3d6e9f2g5h8", + "in": "path", + "name": "endpoint_id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WebhookEndpoint" + } + } + }, + "description": "The endpoint.", + "headers": { + "RateLimit-Limit": { + "description": "Requests this key may make in a minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Remaining": { + "description": "Requests left in the current minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Reset": { + "description": "Seconds until the current minute ends and the count starts over.", + "schema": { + "type": "integer" + } + } + } + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The key is missing, malformed, revoked or expired, or the person who made it left the team." + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The key lacks the scope this endpoint needs (`missing_scope`)." + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "No such endpoint on this team." + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Over the key's rate limit (`rate_limited`), or, for endpoints that start work, over the team's monthly token limit (`token_limit_reached`).", + "headers": { + "RateLimit-Limit": { + "description": "Requests this key may make in a minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Remaining": { + "description": "Requests left in the current minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Reset": { + "description": "Seconds until the current minute ends and the count starts over.", + "schema": { + "type": "integer" + } + }, + "Retry-After": { + "description": "With `rate_limited`: seconds to wait before trying again.", + "schema": { + "type": "integer" + } + } + } + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Something failed on CoderHelm's side. Safe to retry reads." + } + }, + "security": [ + { + "api_key": [ + "webhooks" + ] + } + ], + "summary": "Get a webhook endpoint", + "tags": [ + "Webhook endpoints" + ] + }, + "put": { + "description": "Changes the address, description, events, or turns the endpoint on or off. Fields left out keep their value. Turning an endpoint back on starts its failure count again; events missed while it was off are not sent by themselves (replay them).", + "operationId": "updateWebhookEndpoint", + "parameters": [ + { + "description": "The endpoint's id.", + "example": "ep_01jbendpt4a7b0c3d6e9f2g5h8", + "in": "path", + "name": "endpoint_id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateEndpointBody" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WebhookEndpoint" + } + } + }, + "description": "The endpoint as saved.", + "headers": { + "RateLimit-Limit": { + "description": "Requests this key may make in a minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Remaining": { + "description": "Requests left in the current minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Reset": { + "description": "Seconds until the current minute ends and the count starts over.", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "A field was refused; `field` names which." + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The key is missing, malformed, revoked or expired, or the person who made it left the team." + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The key lacks the scope this endpoint needs (`missing_scope`)." + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "No such endpoint on this team." + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Over the key's rate limit (`rate_limited`), or, for endpoints that start work, over the team's monthly token limit (`token_limit_reached`).", + "headers": { + "RateLimit-Limit": { + "description": "Requests this key may make in a minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Remaining": { + "description": "Requests left in the current minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Reset": { + "description": "Seconds until the current minute ends and the count starts over.", + "schema": { + "type": "integer" + } + }, + "Retry-After": { + "description": "With `rate_limited`: seconds to wait before trying again.", + "schema": { + "type": "integer" + } + } + } + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Something failed on CoderHelm's side. Safe to retry reads." + } + }, + "security": [ + { + "api_key": [ + "webhooks" + ] + } + ], + "summary": "Update a webhook endpoint", + "tags": [ + "Webhook endpoints" + ] + } + }, + "/api/webhooks/endpoints/{endpoint_id}/deliveries": { + "get": { + "description": "The endpoint's deliveries, newest first, each with every attempt. Kept 14 days.", + "operationId": "listWebhookDeliveries", + "parameters": [ + { + "description": "The endpoint's id.", + "example": "ep_01jbendpt4a7b0c3d6e9f2g5h8", + "in": "path", + "name": "endpoint_id", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "`pending`, `failed`, `ok` or `all` (default).", + "in": "query", + "name": "status", + "required": false, + "schema": { + "type": "string" + } + }, + { + "description": "1 to 100, default 25.", + "in": "query", + "name": "limit", + "required": false, + "schema": { + "minimum": 0, + "type": "integer" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "example": { + "deliveries": [ + { + "attempts": [ + { + "at": "2026-10-26T14:31:47.901Z", + "code": 200, + "duration_ms": 87, + "error": "" + } + ], + "created_at": "2026-10-26T14:31:47.780Z", + "event": "run.completed", + "event_id": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "id": "01JBDLVR5T8V1W4X7Y0Z3A6B9C", + "next_retry_at": null, + "outcome": "Delivered (200)", + "reason": "", + "reason_fix": "", + "reason_message": "", + "status": "handled" + } + ] + }, + "schema": { + "type": "object" + } + } + }, + "description": "The deliveries.", + "headers": { + "RateLimit-Limit": { + "description": "Requests this key may make in a minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Remaining": { + "description": "Requests left in the current minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Reset": { + "description": "Seconds until the current minute ends and the count starts over.", + "schema": { + "type": "integer" + } + } + } + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The key is missing, malformed, revoked or expired, or the person who made it left the team." + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The key lacks the scope this endpoint needs (`missing_scope`)." + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "No such endpoint on this team." + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Over the key's rate limit (`rate_limited`), or, for endpoints that start work, over the team's monthly token limit (`token_limit_reached`).", + "headers": { + "RateLimit-Limit": { + "description": "Requests this key may make in a minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Remaining": { + "description": "Requests left in the current minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Reset": { + "description": "Seconds until the current minute ends and the count starts over.", + "schema": { + "type": "integer" + } + }, + "Retry-After": { + "description": "With `rate_limited`: seconds to wait before trying again.", + "schema": { + "type": "integer" + } + } + } + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Something failed on CoderHelm's side. Safe to retry reads." + } + }, + "security": [ + { + "api_key": [ + "webhooks" + ] + } + ], + "summary": "List an endpoint's deliveries", + "tags": [ + "Webhook endpoints" + ] + } + }, + "/api/webhooks/endpoints/{endpoint_id}/deliveries/{delivery_id}/resend": { + "post": { + "description": "Sends the same event (the same body and `webhook-id`, signed now) to the endpoint once more and adds the attempt to the delivery. Works on any delivery whose event is still kept (14 days), delivered or not.", + "operationId": "resendWebhookDelivery", + "parameters": [ + { + "description": "The endpoint's id.", + "example": "ep_01jbendpt4a7b0c3d6e9f2g5h8", + "in": "path", + "name": "endpoint_id", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "The delivery's id.", + "example": "01JBDLVR5T8V1W4X7Y0Z3A6B9C", + "in": "path", + "name": "delivery_id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WebhookDelivery" + } + } + }, + "description": "The delivery with the new attempt.", + "headers": { + "RateLimit-Limit": { + "description": "Requests this key may make in a minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Remaining": { + "description": "Requests left in the current minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Reset": { + "description": "Seconds until the current minute ends and the count starts over.", + "schema": { + "type": "integer" + } + } + } + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The key is missing, malformed, revoked or expired, or the person who made it left the team." + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The key lacks the scope this endpoint needs (`missing_scope`)." + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "No such endpoint or delivery." + }, + "410": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The event is no longer kept." + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Over the key's rate limit (`rate_limited`), or, for endpoints that start work, over the team's monthly token limit (`token_limit_reached`).", + "headers": { + "RateLimit-Limit": { + "description": "Requests this key may make in a minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Remaining": { + "description": "Requests left in the current minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Reset": { + "description": "Seconds until the current minute ends and the count starts over.", + "schema": { + "type": "integer" + } + }, + "Retry-After": { + "description": "With `rate_limited`: seconds to wait before trying again.", + "schema": { + "type": "integer" + } + } + } + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Something failed on CoderHelm's side. Safe to retry reads." + } + }, + "security": [ + { + "api_key": [ + "webhooks" + ] + } + ], + "summary": "Resend a delivery", + "tags": [ + "Webhook endpoints" + ] + } + }, + "/api/webhooks/endpoints/{endpoint_id}/replay": { + "post": { + "description": "Sends the kept events made in a time range to this endpoint again, each as a new delivery with retries, oldest first. Only event types the endpoint subscribes to now are sent. Events carry their original `id`, so a receiver that already handled one can skip it. At most 500 per call; events are kept 14 days.", + "operationId": "replayWebhookEvents", + "parameters": [ + { + "description": "The endpoint's id.", + "example": "ep_01jbendpt4a7b0c3d6e9f2g5h8", + "in": "path", + "name": "endpoint_id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReplayBody" + } + } + }, + "required": true + }, + "responses": { + "202": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReplayResult" + } + } + }, + "description": "Queued.", + "headers": { + "RateLimit-Limit": { + "description": "Requests this key may make in a minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Remaining": { + "description": "Requests left in the current minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Reset": { + "description": "Seconds until the current minute ends and the count starts over.", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The range is not valid, or the endpoint is off." + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The key is missing, malformed, revoked or expired, or the person who made it left the team." + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The key lacks the scope this endpoint needs (`missing_scope`)." + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "No such endpoint on this team." + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Over the key's rate limit (`rate_limited`), or, for endpoints that start work, over the team's monthly token limit (`token_limit_reached`).", + "headers": { + "RateLimit-Limit": { + "description": "Requests this key may make in a minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Remaining": { + "description": "Requests left in the current minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Reset": { + "description": "Seconds until the current minute ends and the count starts over.", + "schema": { + "type": "integer" + } + }, + "Retry-After": { + "description": "With `rate_limited`: seconds to wait before trying again.", + "schema": { + "type": "integer" + } + } + } + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Something failed on CoderHelm's side. Safe to retry reads." + } + }, + "security": [ + { + "api_key": [ + "webhooks" + ] + } + ], + "summary": "Replay events", + "tags": [ + "Webhook endpoints" + ] + } + }, + "/api/webhooks/endpoints/{endpoint_id}/secret": { + "get": { + "description": "The endpoint's current signing secret. Each reveal is written to the team's audit log.", + "operationId": "getWebhookSecret", + "parameters": [ + { + "description": "The endpoint's id.", + "example": "ep_01jbendpt4a7b0c3d6e9f2g5h8", + "in": "path", + "name": "endpoint_id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SecretView" + } + } + }, + "description": "The secret.", + "headers": { + "RateLimit-Limit": { + "description": "Requests this key may make in a minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Remaining": { + "description": "Requests left in the current minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Reset": { + "description": "Seconds until the current minute ends and the count starts over.", + "schema": { + "type": "integer" + } + } + } + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The key is missing, malformed, revoked or expired, or the person who made it left the team." + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The key lacks the scope this endpoint needs (`missing_scope`)." + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "No such endpoint on this team." + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Over the key's rate limit (`rate_limited`), or, for endpoints that start work, over the team's monthly token limit (`token_limit_reached`).", + "headers": { + "RateLimit-Limit": { + "description": "Requests this key may make in a minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Remaining": { + "description": "Requests left in the current minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Reset": { + "description": "Seconds until the current minute ends and the count starts over.", + "schema": { + "type": "integer" + } + }, + "Retry-After": { + "description": "With `rate_limited`: seconds to wait before trying again.", + "schema": { + "type": "integer" + } + } + } + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Something failed on CoderHelm's side. Safe to retry reads." + } + }, + "security": [ + { + "api_key": [ + "webhooks" + ] + } + ], + "summary": "Reveal the signing secret", + "tags": [ + "Webhook endpoints" + ] + } + }, + "/api/webhooks/endpoints/{endpoint_id}/secret/rotate": { + "post": { + "description": "Makes a new secret. For `overlap_hours` (24 unless set) every request carries two signatures, one per secret, so a receiver verifying with either keeps working while you update it. Then only the new secret signs.", + "operationId": "rotateWebhookSecret", + "parameters": [ + { + "description": "The endpoint's id.", + "example": "ep_01jbendpt4a7b0c3d6e9f2g5h8", + "in": "path", + "name": "endpoint_id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RotateBody" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RotatedSecret" + } + } + }, + "description": "The new secret, shown once here.", + "headers": { + "RateLimit-Limit": { + "description": "Requests this key may make in a minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Remaining": { + "description": "Requests left in the current minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Reset": { + "description": "Seconds until the current minute ends and the count starts over.", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "`overlap_hours` is outside 0 to 168." + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The key is missing, malformed, revoked or expired, or the person who made it left the team." + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The key lacks the scope this endpoint needs (`missing_scope`)." + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "No such endpoint on this team." + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Over the key's rate limit (`rate_limited`), or, for endpoints that start work, over the team's monthly token limit (`token_limit_reached`).", + "headers": { + "RateLimit-Limit": { + "description": "Requests this key may make in a minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Remaining": { + "description": "Requests left in the current minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Reset": { + "description": "Seconds until the current minute ends and the count starts over.", + "schema": { + "type": "integer" + } + }, + "Retry-After": { + "description": "With `rate_limited`: seconds to wait before trying again.", + "schema": { + "type": "integer" + } + } + } + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Something failed on CoderHelm's side. Safe to retry reads." + } + }, + "security": [ + { + "api_key": [ + "webhooks" + ] + } + ], + "summary": "Rotate the signing secret", + "tags": [ + "Webhook endpoints" + ] + } + }, + "/api/webhooks/endpoints/{endpoint_id}/test": { + "post": { + "description": "Sends one `webhook.test` event to the endpoint now, signed like every other event, and answers with the attempt. A test is tried once (no retries) and is sent even when the endpoint is off or doesn't subscribe to it.", + "operationId": "sendWebhookTest", + "parameters": [ + { + "description": "The endpoint's id.", + "example": "ep_01jbendpt4a7b0c3d6e9f2g5h8", + "in": "path", + "name": "endpoint_id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WebhookDelivery" + } + } + }, + "description": "The delivery, delivered or not.", + "headers": { + "RateLimit-Limit": { + "description": "Requests this key may make in a minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Remaining": { + "description": "Requests left in the current minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Reset": { + "description": "Seconds until the current minute ends and the count starts over.", + "schema": { + "type": "integer" + } + } + } + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The key is missing, malformed, revoked or expired, or the person who made it left the team." + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The key lacks the scope this endpoint needs (`missing_scope`)." + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "No such endpoint on this team." + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Over the key's rate limit (`rate_limited`), or, for endpoints that start work, over the team's monthly token limit (`token_limit_reached`).", + "headers": { + "RateLimit-Limit": { + "description": "Requests this key may make in a minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Remaining": { + "description": "Requests left in the current minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Reset": { + "description": "Seconds until the current minute ends and the count starts over.", + "schema": { + "type": "integer" + } + }, + "Retry-After": { + "description": "With `rate_limited`: seconds to wait before trying again.", + "schema": { + "type": "integer" + } + } + } + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Something failed on CoderHelm's side. Safe to retry reads." + } + }, + "security": [ + { + "api_key": [ + "webhooks" + ] + } + ], + "summary": "Send a test event", + "tags": [ + "Webhook endpoints" + ] + } + }, + "/api/webhooks/event-types": { + "get": { + "description": "Every event type CoderHelm sends, with an example event. The `webhooks` section of this document has each one's schema.", + "operationId": "listWebhookEventTypes", + "responses": { + "200": { + "content": { + "application/json": { + "example": { + "api_version": "2026-10-26", + "event_types": [ + { + "description": "…", + "example": {}, + "group": "Runs", + "summary": "A run finished", + "type": "run.completed" + } + ] + }, + "schema": { + "type": "object" + } + } + }, + "description": "The catalog.", + "headers": { + "RateLimit-Limit": { + "description": "Requests this key may make in a minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Remaining": { + "description": "Requests left in the current minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Reset": { + "description": "Seconds until the current minute ends and the count starts over.", + "schema": { + "type": "integer" + } + } + } + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The key is missing, malformed, revoked or expired, or the person who made it left the team." + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The key lacks the scope this endpoint needs (`missing_scope`)." + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Over the key's rate limit (`rate_limited`), or, for endpoints that start work, over the team's monthly token limit (`token_limit_reached`).", + "headers": { + "RateLimit-Limit": { + "description": "Requests this key may make in a minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Remaining": { + "description": "Requests left in the current minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Reset": { + "description": "Seconds until the current minute ends and the count starts over.", + "schema": { + "type": "integer" + } + }, + "Retry-After": { + "description": "With `rate_limited`: seconds to wait before trying again.", + "schema": { + "type": "integer" + } + } + } + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Something failed on CoderHelm's side. Safe to retry reads." + } + }, + "security": [ + { + "api_key": [ + "webhooks" + ] + } + ], + "summary": "List event types", + "tags": [ + "Webhook endpoints" + ] + } + }, + "/webhooks/alerts/sns": { + "post": { + "description": "Subscribe CoderHelm to an SNS topic with an HTTPS subscription to this address and add the topic under Alert routes in the dashboard. Every message's SNS signature is checked (signature versions 1 and 2) and the signing certificate must come from SNS. The subscription is confirmed automatically once the topic has an enabled route; messages from topics without one are accepted and ignored. A message that matches one of the route's rules becomes a run that opens a pull request.", + "operationId": "receiveSnsAlert", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SnsEnvelope" + } + } + }, + "description": "The SNS message.", + "required": true + }, + "responses": { + "200": { + "description": "Accepted." + }, + "400": { + "description": "Not an SNS message." + }, + "403": { + "description": "The SNS signature did not verify." + } + }, + "security": [ + {} + ], + "summary": "AWS SNS alerts", + "tags": [ + "Webhooks" + ] + } + }, + "/webhooks/ci/tests/quarantine": { + "get": { + "description": "Returns the tests quarantined for the repository the OIDC token was issued to, so a CI step can keep their failures from failing the build. For Playwright, pass `playwright_grep_invert` to `--grep-invert`.", + "operationId": "listQuarantinedTests", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Quarantine" + } + } + }, + "description": "The quarantined tests." + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The token is not a valid GitHub Actions OIDC token for CoderHelm." + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The repository is not connected, or E2E results are off." + } + }, + "security": [ + { + "github_oidc": [] + } + ], + "summary": "List quarantined tests", + "tags": [ + "CI" + ] + } + }, + "/webhooks/ci/tests/results": { + "post": { + "description": "Takes one test report from a CI job whose results never reach GitHub (a device farm, say), signed with the job's GitHub Actions OIDC token instead of a CoderHelm secret. Request the token with the audience `coderhelm`. CoderHelm checks it was issued for a workflow run of a repository connected to your team with E2E results turned on, then reads the report like one from GitHub: flaky tests, failure groups and quarantine.", + "operationId": "uploadTestResults", + "parameters": [ + { + "description": "The report's file name. Must end in `.json` (Playwright or Cucumber JSON) or `.xml` (JUnit XML). Default `report.json`.", + "example": "results.json", + "in": "query", + "name": "name", + "required": false, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/octet-stream": { + "schema": { + "type": "string" + } + } + }, + "description": "The report file, at most 6 MB.", + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CiUploadResult" + } + } + }, + "description": "The report is stored and queued." + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Not a report CoderHelm can read, or it has no tests." + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The token is not a valid GitHub Actions OIDC token for CoderHelm." + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The repository is not connected, or E2E results are off." + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Empty, or larger than 6 MB." + } + }, + "security": [ + { + "github_oidc": [] + } + ], + "summary": "Upload a test report", + "tags": [ + "CI" + ] + } + }, + "/webhooks/github": { + "post": { + "description": "Where GitHub sends every event of the CoderHelm GitHub App. Installing the app sets this up; you only call it yourself when you self-host. Each request is signed with the app's webhook secret in `X-Hub-Signature-256` (`sha256=` and the hex HMAC-SHA256 of the raw body), compared in constant time. The event type comes from `X-GitHub-Event` and the body must name an installation. Events CoderHelm doesn't act on, and events from an installation not linked to a team, are accepted with `200` and ignored.", + "operationId": "receiveGithubEvent", + "parameters": [ + { + "description": "The event type, such as `issues`, `pull_request` or `push`.", + "example": "issues", + "in": "header", + "name": "X-GitHub-Event", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "GitHub's id for this delivery.", + "in": "header", + "name": "X-GitHub-Delivery", + "required": false, + "schema": { + "type": [ + "string", + "null" + ] + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + }, + "description": "The event payload, as GitHub defines it for each event type. It must include `installation.id`.", + "required": true + }, + "responses": { + "200": { + "description": "Accepted." + }, + "400": { + "description": "The body is not JSON or names no installation." + }, + "401": { + "description": "The signature is missing or wrong." + } + }, + "security": [ + { + "github_signature": [] + } + ], + "summary": "GitHub App events", + "tags": [ + "Webhooks" + ] + } + }, + "/webhooks/jira/{token}": { + "post": { + "description": "For a plain Jira webhook, when the CoderHelm Jira app can't be installed. The URL holds a token generated for your team on the Jira page of the dashboard. If you also generated a secret there, every request must carry `X-Hub-Signature`: `sha256=` and the hex HMAC-SHA256 of the raw body, keyed with that secret. Jira Cloud signs webhooks this way when you set the secret on the webhook; a Jira automation can send the header itself.", + "operationId": "receiveJiraWebhook", + "parameters": [ + { + "description": "The webhook token from the Jira page of the dashboard.", + "in": "path", + "name": "token", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/JiraWebhookBody" + } + } + }, + "description": "The Jira event.", + "required": true + }, + "responses": { + "200": { + "description": "Accepted (whether or not it started anything)." + }, + "400": { + "description": "The body is not JSON." + }, + "401": { + "description": "Unknown token, or the signature is missing or wrong." + } + }, + "security": [ + { + "jira_signature": [] + }, + {} + ], + "summary": "Jira webhook", + "tags": [ + "Webhooks" + ] + } + }, + "/webhooks/knowledge/{token}": { + "post": { + "description": "Tells CoderHelm that pages of a connected knowledge source changed, so it syncs that source now instead of at its next scheduled sync. Sanity posts to the address shown for each Sanity source (CoderHelm registers it itself when the token may manage webhooks), signed with `sanity-webhook-signature`: `t=,v1=` and the base64url HMAC-SHA256 of `.`, keyed with the token in the address; a signature older than five minutes is refused. Notion posts to `/webhooks/knowledge/notion` for the whole install, signed with `X-Notion-Signature`: `sha256=` and the hex HMAC-SHA256 of the body, keyed with the subscription's verification token. An event only starts a sync: what changed is always read back from the provider with the source's own connection.", + "operationId": "receiveKnowledgeWebhook", + "parameters": [ + { + "description": "The source's webhook token, or `notion` for the install's Notion subscription.", + "in": "path", + "name": "token", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/KnowledgeWebhookBody" + } + } + }, + "description": "The provider's event.", + "required": true + }, + "responses": { + "200": { + "description": "Accepted; a sync starts unless the source is paused." + }, + "401": { + "description": "The signature is missing, wrong or too old." + }, + "404": { + "description": "No source has this address." + } + }, + "security": [ + { + "sanity_signature": [] + }, + { + "notion_signature": [] + } + ], + "summary": "Knowledge source change", + "tags": [ + "Webhooks" + ] + } + }, + "/webhooks/relay": { + "post": { + "description": "On a hybrid self-hosted install, where CoderHelm's hosted relay forwards the events of CoderHelm's GitHub App (and Jira app) after checking the provider's own signature. Each request is signed with the install's relay key: `X-CoderHelm-Relay-Signature: t=,d=,v1=,v2=`, where `v1` is the HMAC-SHA256 of `..` and `v2` of `v2.....` (so the two headers below are signed too). Both must match: a request without `v2` is refused. Requests older than 5 minutes are refused, and so is a delivery id the install has already taken (`409`). `X-CoderHelm-Relay-Source` is `github` or `jira`; for GitHub, `X-CoderHelm-Relay-Event` is GitHub's event type and the body is GitHub's payload, unchanged.", + "operationId": "receiveRelayedEvent", + "parameters": [ + { + "description": "`t=,d=,v1=`.", + "example": "t=1761436800,d=72d3162e-cc78-11e3-81ab-4c9367dc0958,v1=5d1a…", + "in": "header", + "name": "X-CoderHelm-Relay-Signature", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Where the event came from: `github` or `jira`.", + "example": "github", + "in": "header", + "name": "X-CoderHelm-Relay-Source", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "The provider's event type.", + "example": "pull_request", + "in": "header", + "name": "X-CoderHelm-Relay-Event", + "required": false, + "schema": { + "type": [ + "string", + "null" + ] + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + }, + "description": "The provider's payload, unchanged.", + "required": true + }, + "responses": { + "200": { + "description": "Handled (or acknowledged and ignored)." + }, + "401": { + "description": "The signature is missing, wrong, or more than 5 minutes old." + }, + "404": { + "description": "This install isn't registered for the relay." + }, + "409": { + "description": "This delivery id was already received; the copy was refused." + } + }, + "security": [ + { + "relay_signature": [] + } + ], + "summary": "Events from CoderHelm's relay", + "tags": [ + "Webhooks" + ] + } + } + }, + "servers": [ + { + "description": "Production", + "url": "https://api.coderhelm.com" + } + ], + "tags": [ + { + "description": "Who a key belongs to and what it may do.", + "name": "Account", + "x-displayName": "Account" + }, + { + "description": "A run is one piece of work by CoderHelm's coder: a ticket or task turned into a pull request. Runs are listed newest first.", + "name": "Runs", + "x-displayName": "Runs" + }, + { + "description": "A plan is a set of tasks, each of which becomes a run once the plan is executed.", + "name": "Plans", + "x-displayName": "Plans" + }, + { + "description": "The repositories connected to the team through the CoderHelm GitHub App.", + "name": "Repositories", + "x-displayName": "Repositories" + }, + { + "description": "Pull request reviews written by CoderHelm's reviewer.", + "name": "Reviews", + "x-displayName": "Reviews" + }, + { + "description": "Tokens used this month and the team's limits.", + "name": "Usage", + "x-displayName": "Usage" + }, + { + "description": "Endpoints a CI job calls with its GitHub Actions OIDC token, so no CoderHelm secret is stored in CI.", + "name": "CI", + "x-displayName": "CI" + }, + { + "description": "Where CoderHelm sends your team's events (runs, pull requests, reviews, CI fixes, alerts, log findings, releases, plans). Each request is signed the Standard Webhooks way. The `webhooks` section of this document has every event's schema.", + "name": "Webhook endpoints", + "x-displayName": "Webhook endpoints" + }, + { + "description": "Webhooks CoderHelm receives from GitHub, Jira, AWS SNS, Sanity and Notion. CoderHelm verifies each one before anything happens.", + "name": "Webhooks", + "x-displayName": "Webhooks" + } + ], + "webhooks": { + "alert.received": { + "post": { + "description": "An alert came in on one of the team's alert addresses, and CoderHelm decided what to do with it. Sent as `POST` to each endpoint subscribed to `alert.received` (or to every event).", + "operationId": "event.alert.received", + "parameters": [ + { + "description": "The event id (`evt_…`). The same on every retry: use it to skip an event you already handled.", + "example": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "in": "header", + "name": "webhook-id", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Unix seconds when this attempt was sent. Refuse a request more than 5 minutes off.", + "example": "1792420307", + "in": "header", + "name": "webhook-timestamp", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Space-separated `v1,` signatures: HMAC-SHA256 of `..` keyed with the endpoint's secret (the bytes after `whsec_`, base64-decoded). Two while a rotated secret still signs; accept the request when any matches.", + "example": "v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4=", + "in": "header", + "name": "webhook-signature", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "examples": { + "event": { + "value": { + "api_version": "2026-10-26", + "created_at": "2026-10-26T14:31:47.512Z", + "data": { + "alert_id": "01JBALERT3K8P2N6Q9R1S4T7V0", + "kind": "cloudwatch_alarm", + "outcome": "run_started", + "received_at": "2026-10-26T09:14:03.000Z", + "repo": "example-org/api", + "severity": "alarm", + "ticket_id": "ALERT-3f9c2a71", + "title": "ALARM: api-5xx-rate" + }, + "id": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "team_id": "TEAM#7c1f0e2a", + "type": "alert.received" + } + } + }, + "schema": { + "properties": { + "api_version": { + "const": "2026-10-26", + "description": "The version of this event's shape.", + "type": "string" + }, + "created_at": { + "description": "When it happened.", + "format": "date-time", + "type": "string" + }, + "data": { + "properties": { + "alert_id": { + "description": "The alert's id in CoderHelm.", + "type": "string" + }, + "kind": { + "description": "What sent it, e.g. `cloudwatch_alarm`, `datadog`, `sentry`, `generic`.", + "type": "string" + }, + "outcome": { + "description": "What CoderHelm did with it: `run_started` (a fix run was queued), `notified`, `duplicate`, `in_flight` (a run for it is already working), `recovered`, `no_open_alert`, `not_alarm`, `no_match`, `route_paused`, `budget`, `alert_budget`, `daily_cap`, `misconfigured` or `error`. More may be added.", + "type": "string" + }, + "received_at": { + "description": "When CoderHelm received it.", + "format": "date-time", + "type": "string" + }, + "repo": { + "description": "The repository the alert is routed to, if any.", + "type": [ + "string", + "null" + ] + }, + "severity": { + "description": "How it reads at a glance.", + "enum": [ + "alarm", + "warning", + "resolved", + "info" + ], + "type": "string" + }, + "ticket_id": { + "description": "The alert's ticket: the same alert repeating has the same one, and a run started for it carries it as its `ticket_id`.", + "type": "string" + }, + "title": { + "description": "The alert's title.", + "type": "string" + } + }, + "required": [ + "alert_id", + "kind", + "title", + "severity", + "outcome", + "repo", + "ticket_id", + "received_at" + ], + "type": "object" + }, + "id": { + "description": "The event's id (`evt_` and a ULID). The same on every retry and every endpoint: use it to ignore an event you already handled. Also sent as the `webhook-id` header.", + "type": "string" + }, + "team_id": { + "description": "The CoderHelm team it belongs to (as `GET /api/me` returns it).", + "type": "string" + }, + "type": { + "const": "alert.received", + "description": "The event type.", + "type": "string" + } + }, + "required": [ + "id", + "type", + "created_at", + "team_id", + "api_version", + "data" + ], + "type": "object" + } + } + }, + "required": true + }, + "responses": { + "2XX": { + "description": "Received. Answer within 10 seconds; do the work afterwards." + }, + "410": { + "description": "Gone: the delivery is final (not retried). Any 4xx other than 408 and 429 is final." + }, + "5XX": { + "description": "Retried with backoff for about a day, as are timeouts, 408 and 429." + } + }, + "security": [], + "summary": "An alert arrived", + "tags": [ + "Events: Alerts" + ] + } + }, + "ci_fix.completed": { + "post": { + "description": "The CI fix finished. `outcome` says whether a fix was pushed. Sent as `POST` to each endpoint subscribed to `ci_fix.completed` (or to every event).", + "operationId": "event.ci_fix.completed", + "parameters": [ + { + "description": "The event id (`evt_…`). The same on every retry: use it to skip an event you already handled.", + "example": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "in": "header", + "name": "webhook-id", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Unix seconds when this attempt was sent. Refuse a request more than 5 minutes off.", + "example": "1792420307", + "in": "header", + "name": "webhook-timestamp", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Space-separated `v1,` signatures: HMAC-SHA256 of `..` keyed with the endpoint's secret (the bytes after `whsec_`, base64-decoded). Two while a rotated secret still signs; accept the request when any matches.", + "example": "v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4=", + "in": "header", + "name": "webhook-signature", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "examples": { + "event": { + "value": { + "api_version": "2026-10-26", + "created_at": "2026-10-26T14:31:47.512Z", + "data": { + "attempt": 1, + "branch": "coderhelm/eng-142-rate-limit-export", + "files_changed": 2, + "outcome": "pushed", + "pr_number": 318, + "repo": "example-org/api", + "run_id": "01JBRUN7Q2X9M3V6T8W1K4HZ5C" + }, + "id": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "team_id": "TEAM#7c1f0e2a", + "type": "ci_fix.completed" + } + } + }, + "schema": { + "properties": { + "api_version": { + "const": "2026-10-26", + "description": "The version of this event's shape.", + "type": "string" + }, + "created_at": { + "description": "When it happened.", + "format": "date-time", + "type": "string" + }, + "data": { + "properties": { + "attempt": { + "description": "Which fix this was, from 1.", + "type": "integer" + }, + "branch": { + "description": "The branch.", + "type": "string" + }, + "files_changed": { + "description": "Files the fix changed.", + "type": "integer" + }, + "outcome": { + "description": "`pushed`: a fix was pushed and the checks run again. `no_changes`: nothing to change, so the pull request goes to people. `failed`: the fix could not be made.", + "enum": [ + "pushed", + "no_changes", + "failed" + ], + "type": "string" + }, + "pr_number": { + "description": "The pull request.", + "type": "integer" + }, + "repo": { + "description": "`owner/name`.", + "type": "string" + }, + "run_id": { + "description": "The run.", + "type": "string" + } + }, + "required": [ + "run_id", + "repo", + "pr_number", + "branch", + "attempt", + "outcome", + "files_changed" + ], + "type": "object" + }, + "id": { + "description": "The event's id (`evt_` and a ULID). The same on every retry and every endpoint: use it to ignore an event you already handled. Also sent as the `webhook-id` header.", + "type": "string" + }, + "team_id": { + "description": "The CoderHelm team it belongs to (as `GET /api/me` returns it).", + "type": "string" + }, + "type": { + "const": "ci_fix.completed", + "description": "The event type.", + "type": "string" + } + }, + "required": [ + "id", + "type", + "created_at", + "team_id", + "api_version", + "data" + ], + "type": "object" + } + } + }, + "required": true + }, + "responses": { + "2XX": { + "description": "Received. Answer within 10 seconds; do the work afterwards." + }, + "410": { + "description": "Gone: the delivery is final (not retried). Any 4xx other than 408 and 429 is final." + }, + "5XX": { + "description": "Retried with backoff for about a day, as are timeouts, 408 and 429." + } + }, + "security": [], + "summary": "A CI fix finished", + "tags": [ + "Events: CI fixes" + ] + } + }, + "ci_fix.started": { + "post": { + "description": "A pull request CoderHelm opened failed its checks, and CoderHelm started fixing it. Sent as `POST` to each endpoint subscribed to `ci_fix.started` (or to every event).", + "operationId": "event.ci_fix.started", + "parameters": [ + { + "description": "The event id (`evt_…`). The same on every retry: use it to skip an event you already handled.", + "example": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "in": "header", + "name": "webhook-id", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Unix seconds when this attempt was sent. Refuse a request more than 5 minutes off.", + "example": "1792420307", + "in": "header", + "name": "webhook-timestamp", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Space-separated `v1,` signatures: HMAC-SHA256 of `..` keyed with the endpoint's secret (the bytes after `whsec_`, base64-decoded). Two while a rotated secret still signs; accept the request when any matches.", + "example": "v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4=", + "in": "header", + "name": "webhook-signature", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "examples": { + "event": { + "value": { + "api_version": "2026-10-26", + "created_at": "2026-10-26T14:31:47.512Z", + "data": { + "attempt": 1, + "branch": "coderhelm/eng-142-rate-limit-export", + "failing_checks": [ + "test (20.x)", + "lint" + ], + "pr_number": 318, + "repo": "example-org/api", + "run_id": "01JBRUN7Q2X9M3V6T8W1K4HZ5C" + }, + "id": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "team_id": "TEAM#7c1f0e2a", + "type": "ci_fix.started" + } + } + }, + "schema": { + "properties": { + "api_version": { + "const": "2026-10-26", + "description": "The version of this event's shape.", + "type": "string" + }, + "created_at": { + "description": "When it happened.", + "format": "date-time", + "type": "string" + }, + "data": { + "properties": { + "attempt": { + "description": "Which fix this is for the run, from 1.", + "type": "integer" + }, + "branch": { + "description": "The branch the fix is pushed to.", + "type": "string" + }, + "failing_checks": { + "description": "The checks that failed.", + "items": { + "type": "string" + }, + "type": "array" + }, + "pr_number": { + "description": "The pull request.", + "type": "integer" + }, + "repo": { + "description": "`owner/name`.", + "type": "string" + }, + "run_id": { + "description": "The run whose pull request failed its checks.", + "type": "string" + } + }, + "required": [ + "run_id", + "repo", + "pr_number", + "branch", + "attempt", + "failing_checks" + ], + "type": "object" + }, + "id": { + "description": "The event's id (`evt_` and a ULID). The same on every retry and every endpoint: use it to ignore an event you already handled. Also sent as the `webhook-id` header.", + "type": "string" + }, + "team_id": { + "description": "The CoderHelm team it belongs to (as `GET /api/me` returns it).", + "type": "string" + }, + "type": { + "const": "ci_fix.started", + "description": "The event type.", + "type": "string" + } + }, + "required": [ + "id", + "type", + "created_at", + "team_id", + "api_version", + "data" + ], + "type": "object" + } + } + }, + "required": true + }, + "responses": { + "2XX": { + "description": "Received. Answer within 10 seconds; do the work afterwards." + }, + "410": { + "description": "Gone: the delivery is final (not retried). Any 4xx other than 408 and 429 is final." + }, + "5XX": { + "description": "Retried with backoff for about a day, as are timeouts, 408 and 429." + } + }, + "security": [], + "summary": "A CI fix started", + "tags": [ + "Events: CI fixes" + ] + } + }, + "log_finding.created": { + "post": { + "description": "The log analysis found a new problem in a connected AWS account's logs. Sent as `POST` to each endpoint subscribed to `log_finding.created` (or to every event).", + "operationId": "event.log_finding.created", + "parameters": [ + { + "description": "The event id (`evt_…`). The same on every retry: use it to skip an event you already handled.", + "example": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "in": "header", + "name": "webhook-id", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Unix seconds when this attempt was sent. Refuse a request more than 5 minutes off.", + "example": "1792420307", + "in": "header", + "name": "webhook-timestamp", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Space-separated `v1,` signatures: HMAC-SHA256 of `..` keyed with the endpoint's secret (the bytes after `whsec_`, base64-decoded). Two while a rotated secret still signs; accept the request when any matches.", + "example": "v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4=", + "in": "header", + "name": "webhook-signature", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "examples": { + "event": { + "value": { + "api_version": "2026-10-26", + "created_at": "2026-10-26T14:31:47.512Z", + "data": { + "account_id": "123456789012", + "finding_id": "01JBFIND6W3X8Y1Z4A7B0C2D5E", + "log_group": "/aws/lambda/invoice-worker", + "severity": "critical", + "title": "Unhandled TimeoutError in the invoice worker", + "url": "https://coderhelm.example.com/logs/?finding=01JBFIND6W3X8Y1Z4A7B0C2D5E" + }, + "id": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "team_id": "TEAM#7c1f0e2a", + "type": "log_finding.created" + } + } + }, + "schema": { + "properties": { + "api_version": { + "const": "2026-10-26", + "description": "The version of this event's shape.", + "type": "string" + }, + "created_at": { + "description": "When it happened.", + "format": "date-time", + "type": "string" + }, + "data": { + "properties": { + "account_id": { + "description": "The AWS account whose logs it was found in.", + "type": "string" + }, + "finding_id": { + "description": "The finding's id.", + "type": "string" + }, + "log_group": { + "description": "The log group the matching lines are in.", + "type": [ + "string", + "null" + ] + }, + "severity": { + "description": "How bad it is.", + "enum": [ + "critical", + "warning", + "info" + ], + "type": "string" + }, + "title": { + "description": "What is wrong, in a line.", + "type": "string" + }, + "url": { + "description": "The finding on the Logs page.", + "format": "uri", + "type": "string" + } + }, + "required": [ + "finding_id", + "account_id", + "title", + "severity", + "log_group", + "url" + ], + "type": "object" + }, + "id": { + "description": "The event's id (`evt_` and a ULID). The same on every retry and every endpoint: use it to ignore an event you already handled. Also sent as the `webhook-id` header.", + "type": "string" + }, + "team_id": { + "description": "The CoderHelm team it belongs to (as `GET /api/me` returns it).", + "type": "string" + }, + "type": { + "const": "log_finding.created", + "description": "The event type.", + "type": "string" + } + }, + "required": [ + "id", + "type", + "created_at", + "team_id", + "api_version", + "data" + ], + "type": "object" + } + } + }, + "required": true + }, + "responses": { + "2XX": { + "description": "Received. Answer within 10 seconds; do the work afterwards." + }, + "410": { + "description": "Gone: the delivery is final (not retried). Any 4xx other than 408 and 429 is final." + }, + "5XX": { + "description": "Retried with backoff for about a day, as are timeouts, 408 and 429." + } + }, + "security": [], + "summary": "A new log finding", + "tags": [ + "Events: Logs" + ] + } + }, + "log_finding.resolved": { + "post": { + "description": "A complete log analysis no longer saw a finding that was open. Sent as `POST` to each endpoint subscribed to `log_finding.resolved` (or to every event).", + "operationId": "event.log_finding.resolved", + "parameters": [ + { + "description": "The event id (`evt_…`). The same on every retry: use it to skip an event you already handled.", + "example": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "in": "header", + "name": "webhook-id", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Unix seconds when this attempt was sent. Refuse a request more than 5 minutes off.", + "example": "1792420307", + "in": "header", + "name": "webhook-timestamp", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Space-separated `v1,` signatures: HMAC-SHA256 of `..` keyed with the endpoint's secret (the bytes after `whsec_`, base64-decoded). Two while a rotated secret still signs; accept the request when any matches.", + "example": "v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4=", + "in": "header", + "name": "webhook-signature", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "examples": { + "event": { + "value": { + "api_version": "2026-10-26", + "created_at": "2026-10-26T14:31:47.512Z", + "data": { + "account_id": "123456789012", + "finding_id": "01JBFIND6W3X8Y1Z4A7B0C2D5E", + "resolved_at": "2026-10-27T06:00:12.000Z", + "severity": "critical", + "title": "Unhandled TimeoutError in the invoice worker", + "url": "https://coderhelm.example.com/logs/?finding=01JBFIND6W3X8Y1Z4A7B0C2D5E" + }, + "id": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "team_id": "TEAM#7c1f0e2a", + "type": "log_finding.resolved" + } + } + }, + "schema": { + "properties": { + "api_version": { + "const": "2026-10-26", + "description": "The version of this event's shape.", + "type": "string" + }, + "created_at": { + "description": "When it happened.", + "format": "date-time", + "type": "string" + }, + "data": { + "properties": { + "account_id": { + "description": "The AWS account.", + "type": "string" + }, + "finding_id": { + "description": "The finding's id.", + "type": "string" + }, + "resolved_at": { + "description": "When a complete analysis no longer saw it.", + "format": "date-time", + "type": "string" + }, + "severity": { + "description": "How bad it was.", + "enum": [ + "critical", + "warning", + "info" + ], + "type": "string" + }, + "title": { + "description": "What was wrong.", + "type": "string" + }, + "url": { + "description": "The finding on the Logs page.", + "format": "uri", + "type": "string" + } + }, + "required": [ + "finding_id", + "account_id", + "title", + "severity", + "resolved_at", + "url" + ], + "type": "object" + }, + "id": { + "description": "The event's id (`evt_` and a ULID). The same on every retry and every endpoint: use it to ignore an event you already handled. Also sent as the `webhook-id` header.", + "type": "string" + }, + "team_id": { + "description": "The CoderHelm team it belongs to (as `GET /api/me` returns it).", + "type": "string" + }, + "type": { + "const": "log_finding.resolved", + "description": "The event type.", + "type": "string" + } + }, + "required": [ + "id", + "type", + "created_at", + "team_id", + "api_version", + "data" + ], + "type": "object" + } + } + }, + "required": true + }, + "responses": { + "2XX": { + "description": "Received. Answer within 10 seconds; do the work afterwards." + }, + "410": { + "description": "Gone: the delivery is final (not retried). Any 4xx other than 408 and 429 is final." + }, + "5XX": { + "description": "Retried with backoff for about a day, as are timeouts, 408 and 429." + } + }, + "security": [], + "summary": "A log finding went away", + "tags": [ + "Events: Logs" + ] + } + }, + "plan.approved": { + "post": { + "description": "Someone approved a plan and started its tasks (Approve and run in the dashboard, or the API). Sent as `POST` to each endpoint subscribed to `plan.approved` (or to every event).", + "operationId": "event.plan.approved", + "parameters": [ + { + "description": "The event id (`evt_…`). The same on every retry: use it to skip an event you already handled.", + "example": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "in": "header", + "name": "webhook-id", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Unix seconds when this attempt was sent. Refuse a request more than 5 minutes off.", + "example": "1792420307", + "in": "header", + "name": "webhook-timestamp", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Space-separated `v1,` signatures: HMAC-SHA256 of `..` keyed with the endpoint's secret (the bytes after `whsec_`, base64-decoded). Two while a rotated secret still signs; accept the request when any matches.", + "example": "v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4=", + "in": "header", + "name": "webhook-signature", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "examples": { + "event": { + "value": { + "api_version": "2026-10-26", + "created_at": "2026-10-26T14:31:47.512Z", + "data": { + "approved_by": "lead@example.com", + "plan_id": "01JBPLAN2F5G8H1J4K7L0M3N6P", + "task_count": 4, + "title": "Move exports to the background queue", + "url": "https://coderhelm.example.com/plans/detail/?id=01JBPLAN2F5G8H1J4K7L0M3N6P" + }, + "id": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "team_id": "TEAM#7c1f0e2a", + "type": "plan.approved" + } + } + }, + "schema": { + "properties": { + "api_version": { + "const": "2026-10-26", + "description": "The version of this event's shape.", + "type": "string" + }, + "created_at": { + "description": "When it happened.", + "format": "date-time", + "type": "string" + }, + "data": { + "properties": { + "approved_by": { + "description": "Who approved it: their GitHub login or email, or `api_key:` for a request made with an API key.", + "type": "string" + }, + "plan_id": { + "description": "The plan's id. `GET /api/plans/{plan_id}` returns it.", + "type": "string" + }, + "task_count": { + "description": "Tasks approved to run.", + "type": "integer" + }, + "title": { + "description": "The plan's title.", + "type": "string" + }, + "url": { + "description": "The plan in the dashboard.", + "format": "uri", + "type": "string" + } + }, + "required": [ + "plan_id", + "title", + "task_count", + "approved_by", + "url" + ], + "type": "object" + }, + "id": { + "description": "The event's id (`evt_` and a ULID). The same on every retry and every endpoint: use it to ignore an event you already handled. Also sent as the `webhook-id` header.", + "type": "string" + }, + "team_id": { + "description": "The CoderHelm team it belongs to (as `GET /api/me` returns it).", + "type": "string" + }, + "type": { + "const": "plan.approved", + "description": "The event type.", + "type": "string" + } + }, + "required": [ + "id", + "type", + "created_at", + "team_id", + "api_version", + "data" + ], + "type": "object" + } + } + }, + "required": true + }, + "responses": { + "2XX": { + "description": "Received. Answer within 10 seconds; do the work afterwards." + }, + "410": { + "description": "Gone: the delivery is final (not retried). Any 4xx other than 408 and 429 is final." + }, + "5XX": { + "description": "Retried with backoff for about a day, as are timeouts, 408 and 429." + } + }, + "security": [], + "summary": "A plan was approved", + "tags": [ + "Events: Plans" + ] + } + }, + "plugin.run.completed": { + "post": { + "description": "A plugin run finished or failed. Sent only to teams with plugins turned on. Sent as `POST` to each endpoint subscribed to `plugin.run.completed` (or to every event).", + "operationId": "event.plugin.run.completed", + "parameters": [ + { + "description": "The event id (`evt_…`). The same on every retry: use it to skip an event you already handled.", + "example": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "in": "header", + "name": "webhook-id", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Unix seconds when this attempt was sent. Refuse a request more than 5 minutes off.", + "example": "1792420307", + "in": "header", + "name": "webhook-timestamp", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Space-separated `v1,` signatures: HMAC-SHA256 of `..` keyed with the endpoint's secret (the bytes after `whsec_`, base64-decoded). Two while a rotated secret still signs; accept the request when any matches.", + "example": "v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4=", + "in": "header", + "name": "webhook-signature", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "examples": { + "event": { + "value": { + "api_version": "2026-10-26", + "created_at": "2026-10-26T14:31:47.512Z", + "data": { + "error": null, + "plugin_id": "release-announcer", + "run_id": "01JBPRUN9Q2R5S8T1U4V7W0X3Y", + "status": "completed", + "trigger": "schedule" + }, + "id": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "team_id": "TEAM#7c1f0e2a", + "type": "plugin.run.completed" + } + } + }, + "schema": { + "properties": { + "api_version": { + "const": "2026-10-26", + "description": "The version of this event's shape.", + "type": "string" + }, + "created_at": { + "description": "When it happened.", + "format": "date-time", + "type": "string" + }, + "data": { + "properties": { + "error": { + "description": "Why it failed.", + "type": [ + "string", + "null" + ] + }, + "plugin_id": { + "description": "The plugin.", + "type": "string" + }, + "run_id": { + "description": "The plugin run's id.", + "type": "string" + }, + "status": { + "description": "How it ended.", + "enum": [ + "completed", + "failed" + ], + "type": "string" + }, + "trigger": { + "description": "What started it: `manual`, `schedule`, `event` or `api`.", + "type": "string" + } + }, + "required": [ + "run_id", + "plugin_id", + "status", + "trigger", + "error" + ], + "type": "object" + }, + "id": { + "description": "The event's id (`evt_` and a ULID). The same on every retry and every endpoint: use it to ignore an event you already handled. Also sent as the `webhook-id` header.", + "type": "string" + }, + "team_id": { + "description": "The CoderHelm team it belongs to (as `GET /api/me` returns it).", + "type": "string" + }, + "type": { + "const": "plugin.run.completed", + "description": "The event type.", + "type": "string" + } + }, + "required": [ + "id", + "type", + "created_at", + "team_id", + "api_version", + "data" + ], + "type": "object" + } + } + }, + "required": true + }, + "responses": { + "2XX": { + "description": "Received. Answer within 10 seconds; do the work afterwards." + }, + "410": { + "description": "Gone: the delivery is final (not retried). Any 4xx other than 408 and 429 is final." + }, + "5XX": { + "description": "Retried with backoff for about a day, as are timeouts, 408 and 429." + } + }, + "security": [], + "summary": "A plugin run finished", + "tags": [ + "Events: Plugins" + ] + } + }, + "pull_request.opened": { + "post": { + "description": "A run opened a pull request. Pull requests people open are not sent. Sent as `POST` to each endpoint subscribed to `pull_request.opened` (or to every event).", + "operationId": "event.pull_request.opened", + "parameters": [ + { + "description": "The event id (`evt_…`). The same on every retry: use it to skip an event you already handled.", + "example": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "in": "header", + "name": "webhook-id", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Unix seconds when this attempt was sent. Refuse a request more than 5 minutes off.", + "example": "1792420307", + "in": "header", + "name": "webhook-timestamp", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Space-separated `v1,` signatures: HMAC-SHA256 of `..` keyed with the endpoint's secret (the bytes after `whsec_`, base64-decoded). Two while a rotated secret still signs; accept the request when any matches.", + "example": "v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4=", + "in": "header", + "name": "webhook-signature", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "examples": { + "event": { + "value": { + "api_version": "2026-10-26", + "created_at": "2026-10-26T14:31:47.512Z", + "data": { + "base_branch": "main", + "branch": "coderhelm/eng-142-rate-limit-export", + "draft": true, + "number": 318, + "repo": "example-org/api", + "run_id": "01JBRUN7Q2X9M3V6T8W1K4HZ5C", + "title": "Add rate limiting to the export endpoint", + "url": "https://github.com/example-org/api/pull/318" + }, + "id": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "team_id": "TEAM#7c1f0e2a", + "type": "pull_request.opened" + } + } + }, + "schema": { + "properties": { + "api_version": { + "const": "2026-10-26", + "description": "The version of this event's shape.", + "type": "string" + }, + "created_at": { + "description": "When it happened.", + "format": "date-time", + "type": "string" + }, + "data": { + "properties": { + "base_branch": { + "description": "The branch it merges into, when the work named one (otherwise the repository's default branch).", + "type": [ + "string", + "null" + ] + }, + "branch": { + "description": "The head branch.", + "type": "string" + }, + "draft": { + "description": "Opened as a draft (CoderHelm marks it ready when its checks pass).", + "type": "boolean" + }, + "number": { + "description": "The pull request number.", + "type": "integer" + }, + "repo": { + "description": "`owner/name`.", + "type": "string" + }, + "run_id": { + "description": "The run that opened it.", + "type": "string" + }, + "title": { + "description": "The run's title (the ticket or task the pull request is for).", + "type": "string" + }, + "url": { + "description": "The pull request on GitHub.", + "format": "uri", + "type": "string" + } + }, + "required": [ + "run_id", + "repo", + "number", + "url", + "title", + "branch", + "base_branch", + "draft" + ], + "type": "object" + }, + "id": { + "description": "The event's id (`evt_` and a ULID). The same on every retry and every endpoint: use it to ignore an event you already handled. Also sent as the `webhook-id` header.", + "type": "string" + }, + "team_id": { + "description": "The CoderHelm team it belongs to (as `GET /api/me` returns it).", + "type": "string" + }, + "type": { + "const": "pull_request.opened", + "description": "The event type.", + "type": "string" + } + }, + "required": [ + "id", + "type", + "created_at", + "team_id", + "api_version", + "data" + ], + "type": "object" + } + } + }, + "required": true + }, + "responses": { + "2XX": { + "description": "Received. Answer within 10 seconds; do the work afterwards." + }, + "410": { + "description": "Gone: the delivery is final (not retried). Any 4xx other than 408 and 429 is final." + }, + "5XX": { + "description": "Retried with backoff for about a day, as are timeouts, 408 and 429." + } + }, + "security": [], + "summary": "CoderHelm opened a pull request", + "tags": [ + "Events: Pull requests" + ] + } + }, + "release_notes.published": { + "post": { + "description": "CoderHelm wrote and published the notes for a release tag. Sent as `POST` to each endpoint subscribed to `release_notes.published` (or to every event).", + "operationId": "event.release_notes.published", + "parameters": [ + { + "description": "The event id (`evt_…`). The same on every retry: use it to skip an event you already handled.", + "example": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "in": "header", + "name": "webhook-id", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Unix seconds when this attempt was sent. Refuse a request more than 5 minutes off.", + "example": "1792420307", + "in": "header", + "name": "webhook-timestamp", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Space-separated `v1,` signatures: HMAC-SHA256 of `..` keyed with the endpoint's secret (the bytes after `whsec_`, base64-decoded). Two while a rotated secret still signs; accept the request when any matches.", + "example": "v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4=", + "in": "header", + "name": "webhook-signature", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "examples": { + "event": { + "value": { + "api_version": "2026-10-26", + "created_at": "2026-10-26T14:31:47.512Z", + "data": { + "channels": [ + "github", + "email" + ], + "release_url": "https://github.com/example-org/api/releases/tag/v2.14.0", + "repo": "example-org/api", + "sha": "4b7e9d1c0a2f3e5d6c8b9a0f1e2d3c4b5a6f7e8d", + "tag": "v2.14.0" + }, + "id": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "team_id": "TEAM#7c1f0e2a", + "type": "release_notes.published" + } + } + }, + "schema": { + "properties": { + "api_version": { + "const": "2026-10-26", + "description": "The version of this event's shape.", + "type": "string" + }, + "created_at": { + "description": "When it happened.", + "format": "date-time", + "type": "string" + }, + "data": { + "properties": { + "channels": { + "description": "Where the notes went: `github`, `confluence`, `email`.", + "items": { + "type": "string" + }, + "type": "array" + }, + "release_url": { + "description": "The GitHub Release, when one was written.", + "format": "uri", + "type": [ + "string", + "null" + ] + }, + "repo": { + "description": "`owner/name`.", + "type": "string" + }, + "sha": { + "description": "The commit the tag points at.", + "type": "string" + }, + "tag": { + "description": "The release tag.", + "type": "string" + } + }, + "required": [ + "repo", + "tag", + "sha", + "release_url", + "channels" + ], + "type": "object" + }, + "id": { + "description": "The event's id (`evt_` and a ULID). The same on every retry and every endpoint: use it to ignore an event you already handled. Also sent as the `webhook-id` header.", + "type": "string" + }, + "team_id": { + "description": "The CoderHelm team it belongs to (as `GET /api/me` returns it).", + "type": "string" + }, + "type": { + "const": "release_notes.published", + "description": "The event type.", + "type": "string" + } + }, + "required": [ + "id", + "type", + "created_at", + "team_id", + "api_version", + "data" + ], + "type": "object" + } + } + }, + "required": true + }, + "responses": { + "2XX": { + "description": "Received. Answer within 10 seconds; do the work afterwards." + }, + "410": { + "description": "Gone: the delivery is final (not retried). Any 4xx other than 408 and 429 is final." + }, + "5XX": { + "description": "Retried with backoff for about a day, as are timeouts, 408 and 429." + } + }, + "security": [], + "summary": "Release notes went out", + "tags": [ + "Events: Releases" + ] + } + }, + "review.completed": { + "post": { + "description": "CoderHelm's reviewer posted a review on a pull request, with its verdict. Sent as `POST` to each endpoint subscribed to `review.completed` (or to every event).", + "operationId": "event.review.completed", + "parameters": [ + { + "description": "The event id (`evt_…`). The same on every retry: use it to skip an event you already handled.", + "example": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "in": "header", + "name": "webhook-id", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Unix seconds when this attempt was sent. Refuse a request more than 5 minutes off.", + "example": "1792420307", + "in": "header", + "name": "webhook-timestamp", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Space-separated `v1,` signatures: HMAC-SHA256 of `..` keyed with the endpoint's secret (the bytes after `whsec_`, base64-decoded). Two while a rotated secret still signs; accept the request when any matches.", + "example": "v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4=", + "in": "header", + "name": "webhook-signature", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "examples": { + "event": { + "value": { + "api_version": "2026-10-26", + "created_at": "2026-10-26T14:31:47.512Z", + "data": { + "head_sha": "9f1c2ab7e04d3c5a8b6f0e1d2c3b4a5f6e7d8c9b", + "posted_as": "request_changes", + "pr_number": 902, + "pr_url": "https://github.com/example-org/web/pull/902", + "repo": "example-org/web", + "risk": "medium", + "trigger": "opened", + "url": "https://coderhelm.example.com/reviewer/?repo=example-org%2Fweb&pr=902", + "verdict": "request_changes" + }, + "id": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "team_id": "TEAM#7c1f0e2a", + "type": "review.completed" + } + } + }, + "schema": { + "properties": { + "api_version": { + "const": "2026-10-26", + "description": "The version of this event's shape.", + "type": "string" + }, + "created_at": { + "description": "When it happened.", + "format": "date-time", + "type": "string" + }, + "data": { + "properties": { + "head_sha": { + "description": "The commit the review is for.", + "type": "string" + }, + "posted_as": { + "description": "How the review was posted on GitHub. On CoderHelm's own pull requests GitHub allows only `comment`, whatever the verdict.", + "enum": [ + "approve", + "request_changes", + "comment" + ], + "type": "string" + }, + "pr_number": { + "description": "The pull request reviewed.", + "type": "integer" + }, + "pr_url": { + "description": "The pull request on GitHub.", + "format": "uri", + "type": "string" + }, + "repo": { + "description": "`owner/name`.", + "type": "string" + }, + "risk": { + "description": "The reviewer's risk rating (`low`, `medium`, `high`), or `n/a`.", + "type": "string" + }, + "trigger": { + "description": "What asked for the review: `opened`, `synchronize`, `labeled`, `requested`, `run` and others.", + "type": "string" + }, + "url": { + "description": "The review in the CoderHelm dashboard.", + "format": "uri", + "type": "string" + }, + "verdict": { + "description": "What the reviewer decided.", + "enum": [ + "approve", + "request_changes", + "comment" + ], + "type": "string" + } + }, + "required": [ + "repo", + "pr_number", + "pr_url", + "head_sha", + "verdict", + "posted_as", + "risk", + "trigger", + "url" + ], + "type": "object" + }, + "id": { + "description": "The event's id (`evt_` and a ULID). The same on every retry and every endpoint: use it to ignore an event you already handled. Also sent as the `webhook-id` header.", + "type": "string" + }, + "team_id": { + "description": "The CoderHelm team it belongs to (as `GET /api/me` returns it).", + "type": "string" + }, + "type": { + "const": "review.completed", + "description": "The event type.", + "type": "string" + } + }, + "required": [ + "id", + "type", + "created_at", + "team_id", + "api_version", + "data" + ], + "type": "object" + } + } + }, + "required": true + }, + "responses": { + "2XX": { + "description": "Received. Answer within 10 seconds; do the work afterwards." + }, + "410": { + "description": "Gone: the delivery is final (not retried). Any 4xx other than 408 and 429 is final." + }, + "5XX": { + "description": "Retried with backoff for about a day, as are timeouts, 408 and 429." } - ], - "summary": "Upload a test report", + }, + "security": [], + "summary": "A review was posted", "tags": [ - "CI" + "Events: Reviews" ] } }, - "/webhooks/github": { + "run.completed": { "post": { - "description": "Where GitHub sends every event of the CoderHelm GitHub App. Installing the app sets this up; you only call it yourself when you self-host. Each request is signed with the app's webhook secret in `X-Hub-Signature-256` (`sha256=` and the hex HMAC-SHA256 of the raw body), compared in constant time. The event type comes from `X-GitHub-Event` and the body must name an installation. Events CoderHelm doesn't act on, and events from an installation not linked to a team, are accepted with `200` and ignored.", - "operationId": "receiveGithubEvent", + "description": "The run finished: its pull request passed its checks and is ready for people, or no code change was needed. Sent as `POST` to each endpoint subscribed to `run.completed` (or to every event).", + "operationId": "event.run.completed", "parameters": [ { - "description": "The event type, such as `issues`, `pull_request` or `push`.", - "example": "issues", + "description": "The event id (`evt_…`). The same on every retry: use it to skip an event you already handled.", + "example": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", "in": "header", - "name": "X-GitHub-Event", + "name": "webhook-id", "required": true, "schema": { "type": "string" } }, { - "description": "GitHub's id for this delivery.", + "description": "Unix seconds when this attempt was sent. Refuse a request more than 5 minutes off.", + "example": "1792420307", "in": "header", - "name": "X-GitHub-Delivery", - "required": false, + "name": "webhook-timestamp", + "required": true, "schema": { - "type": [ - "string", - "null" - ] + "type": "string" + } + }, + { + "description": "Space-separated `v1,` signatures: HMAC-SHA256 of `..` keyed with the endpoint's secret (the bytes after `whsec_`, base64-decoded). Two while a rotated secret still signs; accept the request when any matches.", + "example": "v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4=", + "in": "header", + "name": "webhook-signature", + "required": true, + "schema": { + "type": "string" } } ], "requestBody": { "content": { "application/json": { + "examples": { + "event": { + "value": { + "api_version": "2026-10-26", + "created_at": "2026-10-26T14:31:47.512Z", + "data": { + "branch": "coderhelm/eng-142-rate-limit-export", + "created_at": "2026-10-26T14:02:11.000Z", + "error": null, + "pr_number": 318, + "pr_url": "https://github.com/example-org/api/pull/318", + "repo": "example-org/api", + "run_id": "01JBRUN7Q2X9M3V6T8W1K4HZ5C", + "source": "jira", + "status": "completed", + "ticket_id": "ENG-142", + "title": "Add rate limiting to the export endpoint", + "updated_at": "2026-10-26T14:31:47.000Z", + "url": "https://coderhelm.example.com/runs/detail/?id=01JBRUN7Q2X9M3V6T8W1K4HZ5C" + }, + "id": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "team_id": "TEAM#7c1f0e2a", + "type": "run.completed" + } + } + }, "schema": { + "properties": { + "api_version": { + "const": "2026-10-26", + "description": "The version of this event's shape.", + "type": "string" + }, + "created_at": { + "description": "When it happened.", + "format": "date-time", + "type": "string" + }, + "data": { + "properties": { + "branch": { + "description": "The branch CoderHelm works on.", + "type": [ + "string", + "null" + ] + }, + "created_at": { + "description": "When the run started.", + "format": "date-time", + "type": "string" + }, + "error": { + "description": "Why the run failed or what it needs, in plain words.", + "type": [ + "string", + "null" + ] + }, + "pr_number": { + "description": "The pull request CoderHelm opened, once there is one.", + "type": [ + "integer", + "null" + ] + }, + "pr_url": { + "description": "The pull request's address on GitHub.", + "format": "uri", + "type": [ + "string", + "null" + ] + }, + "repo": { + "description": "`owner/name` of the repository the run works in.", + "type": "string" + }, + "run_id": { + "description": "The run's id. `GET /api/runs/{run_id}` returns the whole run.", + "type": "string" + }, + "source": { + "description": "Where the work came from: `github`, `jira` or `alert` today; more may be added.", + "type": "string" + }, + "status": { + "description": "The run's status when the event happened.", + "enum": [ + "running", + "awaiting_ci", + "needs_input", + "needs_outside_change", + "completed", + "merged", + "failed", + "cancelled", + "closed" + ], + "type": "string" + }, + "ticket_id": { + "description": "The ticket's key or number at its source (empty for a task without one).", + "type": "string" + }, + "title": { + "description": "The ticket or task title.", + "type": "string" + }, + "updated_at": { + "description": "When the run last changed.", + "format": "date-time", + "type": "string" + }, + "url": { + "description": "The run in the CoderHelm dashboard.", + "format": "uri", + "type": "string" + } + }, + "required": [ + "run_id", + "status", + "title", + "repo", + "source", + "ticket_id", + "pr_number", + "pr_url", + "branch", + "error", + "url", + "created_at", + "updated_at" + ], + "type": "object" + }, + "id": { + "description": "The event's id (`evt_` and a ULID). The same on every retry and every endpoint: use it to ignore an event you already handled. Also sent as the `webhook-id` header.", + "type": "string" + }, + "team_id": { + "description": "The CoderHelm team it belongs to (as `GET /api/me` returns it).", + "type": "string" + }, + "type": { + "const": "run.completed", + "description": "The event type.", + "type": "string" + } + }, + "required": [ + "id", + "type", + "created_at", + "team_id", + "api_version", + "data" + ], "type": "object" } } }, - "description": "The event payload, as GitHub defines it for each event type. It must include `installation.id`.", "required": true }, "responses": { - "200": { - "description": "Accepted." + "2XX": { + "description": "Received. Answer within 10 seconds; do the work afterwards." }, - "400": { - "description": "The body is not JSON or names no installation." + "410": { + "description": "Gone: the delivery is final (not retried). Any 4xx other than 408 and 429 is final." }, - "401": { - "description": "The signature is missing or wrong." + "5XX": { + "description": "Retried with backoff for about a day, as are timeouts, 408 and 429." } }, - "security": [ - { - "github_signature": [] - } - ], - "summary": "GitHub App events", + "security": [], + "summary": "A run finished", "tags": [ - "Webhooks" + "Events: Runs" ] } }, - "/webhooks/jira/{token}": { + "run.created": { "post": { - "description": "For a plain Jira webhook, when the CoderHelm Jira app can't be installed. The URL holds a token generated for your team on the Jira page of the dashboard. If you also generated a secret there, every request must carry `X-Hub-Signature`: `sha256=` and the hex HMAC-SHA256 of the raw body, keyed with that secret. Jira Cloud signs webhooks this way when you set the secret on the webhook; a Jira automation can send the header itself.", - "operationId": "receiveJiraWebhook", + "description": "CoderHelm started work on a ticket, task or alert. Sent as `POST` to each endpoint subscribed to `run.created` (or to every event).", + "operationId": "event.run.created", "parameters": [ { - "description": "The webhook token from the Jira page of the dashboard.", - "in": "path", - "name": "token", + "description": "The event id (`evt_…`). The same on every retry: use it to skip an event you already handled.", + "example": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "in": "header", + "name": "webhook-id", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Unix seconds when this attempt was sent. Refuse a request more than 5 minutes off.", + "example": "1792420307", + "in": "header", + "name": "webhook-timestamp", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Space-separated `v1,` signatures: HMAC-SHA256 of `..` keyed with the endpoint's secret (the bytes after `whsec_`, base64-decoded). Two while a rotated secret still signs; accept the request when any matches.", + "example": "v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4=", + "in": "header", + "name": "webhook-signature", "required": true, "schema": { "type": "string" @@ -4889,46 +9315,219 @@ "requestBody": { "content": { "application/json": { + "examples": { + "event": { + "value": { + "api_version": "2026-10-26", + "created_at": "2026-10-26T14:31:47.512Z", + "data": { + "branch": null, + "created_at": "2026-10-26T14:02:11.000Z", + "error": null, + "pr_number": null, + "pr_url": null, + "repo": "example-org/api", + "run_id": "01JBRUN7Q2X9M3V6T8W1K4HZ5C", + "source": "jira", + "status": "running", + "ticket_id": "ENG-142", + "title": "Add rate limiting to the export endpoint", + "updated_at": "2026-10-26T14:31:47.000Z", + "url": "https://coderhelm.example.com/runs/detail/?id=01JBRUN7Q2X9M3V6T8W1K4HZ5C" + }, + "id": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "team_id": "TEAM#7c1f0e2a", + "type": "run.created" + } + } + }, "schema": { - "$ref": "#/components/schemas/JiraWebhookBody" + "properties": { + "api_version": { + "const": "2026-10-26", + "description": "The version of this event's shape.", + "type": "string" + }, + "created_at": { + "description": "When it happened.", + "format": "date-time", + "type": "string" + }, + "data": { + "properties": { + "branch": { + "description": "The branch CoderHelm works on.", + "type": [ + "string", + "null" + ] + }, + "created_at": { + "description": "When the run started.", + "format": "date-time", + "type": "string" + }, + "error": { + "description": "Why the run failed or what it needs, in plain words.", + "type": [ + "string", + "null" + ] + }, + "pr_number": { + "description": "The pull request CoderHelm opened, once there is one.", + "type": [ + "integer", + "null" + ] + }, + "pr_url": { + "description": "The pull request's address on GitHub.", + "format": "uri", + "type": [ + "string", + "null" + ] + }, + "repo": { + "description": "`owner/name` of the repository the run works in.", + "type": "string" + }, + "run_id": { + "description": "The run's id. `GET /api/runs/{run_id}` returns the whole run.", + "type": "string" + }, + "source": { + "description": "Where the work came from: `github`, `jira` or `alert` today; more may be added.", + "type": "string" + }, + "status": { + "description": "The run's status when the event happened.", + "enum": [ + "running", + "awaiting_ci", + "needs_input", + "needs_outside_change", + "completed", + "merged", + "failed", + "cancelled", + "closed" + ], + "type": "string" + }, + "ticket_id": { + "description": "The ticket's key or number at its source (empty for a task without one).", + "type": "string" + }, + "title": { + "description": "The ticket or task title.", + "type": "string" + }, + "updated_at": { + "description": "When the run last changed.", + "format": "date-time", + "type": "string" + }, + "url": { + "description": "The run in the CoderHelm dashboard.", + "format": "uri", + "type": "string" + } + }, + "required": [ + "run_id", + "status", + "title", + "repo", + "source", + "ticket_id", + "pr_number", + "pr_url", + "branch", + "error", + "url", + "created_at", + "updated_at" + ], + "type": "object" + }, + "id": { + "description": "The event's id (`evt_` and a ULID). The same on every retry and every endpoint: use it to ignore an event you already handled. Also sent as the `webhook-id` header.", + "type": "string" + }, + "team_id": { + "description": "The CoderHelm team it belongs to (as `GET /api/me` returns it).", + "type": "string" + }, + "type": { + "const": "run.created", + "description": "The event type.", + "type": "string" + } + }, + "required": [ + "id", + "type", + "created_at", + "team_id", + "api_version", + "data" + ], + "type": "object" } } }, - "description": "The Jira event.", "required": true }, "responses": { - "200": { - "description": "Accepted (whether or not it started anything)." + "2XX": { + "description": "Received. Answer within 10 seconds; do the work afterwards." }, - "400": { - "description": "The body is not JSON." + "410": { + "description": "Gone: the delivery is final (not retried). Any 4xx other than 408 and 429 is final." }, - "401": { - "description": "Unknown token, or the signature is missing or wrong." + "5XX": { + "description": "Retried with backoff for about a day, as are timeouts, 408 and 429." } }, - "security": [ - { - "jira_signature": [] - }, - {} - ], - "summary": "Jira webhook", + "security": [], + "summary": "A run started", "tags": [ - "Webhooks" + "Events: Runs" ] } }, - "/webhooks/knowledge/{token}": { + "run.failed": { "post": { - "description": "Tells CoderHelm that pages of a connected knowledge source changed, so it syncs that source now instead of at its next scheduled sync. Sanity posts to the address shown for each Sanity source (CoderHelm registers it itself when the token may manage webhooks), signed with `sanity-webhook-signature`: `t=,v1=` and the base64url HMAC-SHA256 of `.`, keyed with the token in the address; a signature older than five minutes is refused. Notion posts to `/webhooks/knowledge/notion` for the whole install, signed with `X-Notion-Signature`: `sha256=` and the hex HMAC-SHA256 of the body, keyed with the subscription's verification token. An event only starts a sync: what changed is always read back from the provider with the source's own connection.", - "operationId": "receiveKnowledgeWebhook", + "description": "The run stopped on an error. `error` says why. Sent as `POST` to each endpoint subscribed to `run.failed` (or to every event).", + "operationId": "event.run.failed", "parameters": [ { - "description": "The source's webhook token, or `notion` for the install's Notion subscription.", - "in": "path", - "name": "token", + "description": "The event id (`evt_…`). The same on every retry: use it to skip an event you already handled.", + "example": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "in": "header", + "name": "webhook-id", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Unix seconds when this attempt was sent. Refuse a request more than 5 minutes off.", + "example": "1792420307", + "in": "header", + "name": "webhook-timestamp", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Space-separated `v1,` signatures: HMAC-SHA256 of `..` keyed with the endpoint's secret (the bytes after `whsec_`, base64-decoded). Two while a rotated secret still signs; accept the request when any matches.", + "example": "v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4=", + "in": "header", + "name": "webhook-signature", "required": true, "schema": { "type": "string" @@ -4938,161 +9537,539 @@ "requestBody": { "content": { "application/json": { + "examples": { + "event": { + "value": { + "api_version": "2026-10-26", + "created_at": "2026-10-26T14:31:47.512Z", + "data": { + "branch": null, + "created_at": "2026-10-26T14:02:11.000Z", + "error": "The repository's install step failed: npm ERR! 404 Not Found - @example/internal-ui", + "pr_number": null, + "pr_url": null, + "repo": "example-org/api", + "run_id": "01JBRUN7Q2X9M3V6T8W1K4HZ5C", + "source": "jira", + "status": "failed", + "ticket_id": "ENG-142", + "title": "Add rate limiting to the export endpoint", + "updated_at": "2026-10-26T14:31:47.000Z", + "url": "https://coderhelm.example.com/runs/detail/?id=01JBRUN7Q2X9M3V6T8W1K4HZ5C" + }, + "id": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "team_id": "TEAM#7c1f0e2a", + "type": "run.failed" + } + } + }, "schema": { - "$ref": "#/components/schemas/KnowledgeWebhookBody" + "properties": { + "api_version": { + "const": "2026-10-26", + "description": "The version of this event's shape.", + "type": "string" + }, + "created_at": { + "description": "When it happened.", + "format": "date-time", + "type": "string" + }, + "data": { + "properties": { + "branch": { + "description": "The branch CoderHelm works on.", + "type": [ + "string", + "null" + ] + }, + "created_at": { + "description": "When the run started.", + "format": "date-time", + "type": "string" + }, + "error": { + "description": "Why the run failed or what it needs, in plain words.", + "type": [ + "string", + "null" + ] + }, + "pr_number": { + "description": "The pull request CoderHelm opened, once there is one.", + "type": [ + "integer", + "null" + ] + }, + "pr_url": { + "description": "The pull request's address on GitHub.", + "format": "uri", + "type": [ + "string", + "null" + ] + }, + "repo": { + "description": "`owner/name` of the repository the run works in.", + "type": "string" + }, + "run_id": { + "description": "The run's id. `GET /api/runs/{run_id}` returns the whole run.", + "type": "string" + }, + "source": { + "description": "Where the work came from: `github`, `jira` or `alert` today; more may be added.", + "type": "string" + }, + "status": { + "description": "The run's status when the event happened.", + "enum": [ + "running", + "awaiting_ci", + "needs_input", + "needs_outside_change", + "completed", + "merged", + "failed", + "cancelled", + "closed" + ], + "type": "string" + }, + "ticket_id": { + "description": "The ticket's key or number at its source (empty for a task without one).", + "type": "string" + }, + "title": { + "description": "The ticket or task title.", + "type": "string" + }, + "updated_at": { + "description": "When the run last changed.", + "format": "date-time", + "type": "string" + }, + "url": { + "description": "The run in the CoderHelm dashboard.", + "format": "uri", + "type": "string" + } + }, + "required": [ + "run_id", + "status", + "title", + "repo", + "source", + "ticket_id", + "pr_number", + "pr_url", + "branch", + "error", + "url", + "created_at", + "updated_at" + ], + "type": "object" + }, + "id": { + "description": "The event's id (`evt_` and a ULID). The same on every retry and every endpoint: use it to ignore an event you already handled. Also sent as the `webhook-id` header.", + "type": "string" + }, + "team_id": { + "description": "The CoderHelm team it belongs to (as `GET /api/me` returns it).", + "type": "string" + }, + "type": { + "const": "run.failed", + "description": "The event type.", + "type": "string" + } + }, + "required": [ + "id", + "type", + "created_at", + "team_id", + "api_version", + "data" + ], + "type": "object" } } }, - "description": "The provider's event.", "required": true }, "responses": { - "200": { - "description": "Accepted; a sync starts unless the source is paused." + "2XX": { + "description": "Received. Answer within 10 seconds; do the work afterwards." }, - "401": { - "description": "The signature is missing, wrong or too old." + "410": { + "description": "Gone: the delivery is final (not retried). Any 4xx other than 408 and 429 is final." }, - "404": { - "description": "No source has this address." + "5XX": { + "description": "Retried with backoff for about a day, as are timeouts, 408 and 429." } }, - "security": [ + "security": [], + "summary": "A run failed", + "tags": [ + "Events: Runs" + ] + } + }, + "run.needs_input": { + "post": { + "description": "The run asked a question on its ticket or pull request and waits for an answer. `error` holds the question. Sent as `POST` to each endpoint subscribed to `run.needs_input` (or to every event).", + "operationId": "event.run.needs_input", + "parameters": [ { - "sanity_signature": [] + "description": "The event id (`evt_…`). The same on every retry: use it to skip an event you already handled.", + "example": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "in": "header", + "name": "webhook-id", + "required": true, + "schema": { + "type": "string" + } }, { - "notion_signature": [] + "description": "Unix seconds when this attempt was sent. Refuse a request more than 5 minutes off.", + "example": "1792420307", + "in": "header", + "name": "webhook-timestamp", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Space-separated `v1,` signatures: HMAC-SHA256 of `..` keyed with the endpoint's secret (the bytes after `whsec_`, base64-decoded). Two while a rotated secret still signs; accept the request when any matches.", + "example": "v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4=", + "in": "header", + "name": "webhook-signature", + "required": true, + "schema": { + "type": "string" + } } ], - "summary": "Knowledge source change", + "requestBody": { + "content": { + "application/json": { + "examples": { + "event": { + "value": { + "api_version": "2026-10-26", + "created_at": "2026-10-26T14:31:47.512Z", + "data": { + "branch": null, + "created_at": "2026-10-26T14:02:11.000Z", + "error": "Should the limit apply per API key or per team?", + "pr_number": null, + "pr_url": null, + "repo": "example-org/api", + "run_id": "01JBRUN7Q2X9M3V6T8W1K4HZ5C", + "source": "jira", + "status": "needs_input", + "ticket_id": "ENG-142", + "title": "Add rate limiting to the export endpoint", + "updated_at": "2026-10-26T14:31:47.000Z", + "url": "https://coderhelm.example.com/runs/detail/?id=01JBRUN7Q2X9M3V6T8W1K4HZ5C" + }, + "id": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "team_id": "TEAM#7c1f0e2a", + "type": "run.needs_input" + } + } + }, + "schema": { + "properties": { + "api_version": { + "const": "2026-10-26", + "description": "The version of this event's shape.", + "type": "string" + }, + "created_at": { + "description": "When it happened.", + "format": "date-time", + "type": "string" + }, + "data": { + "properties": { + "branch": { + "description": "The branch CoderHelm works on.", + "type": [ + "string", + "null" + ] + }, + "created_at": { + "description": "When the run started.", + "format": "date-time", + "type": "string" + }, + "error": { + "description": "Why the run failed or what it needs, in plain words.", + "type": [ + "string", + "null" + ] + }, + "pr_number": { + "description": "The pull request CoderHelm opened, once there is one.", + "type": [ + "integer", + "null" + ] + }, + "pr_url": { + "description": "The pull request's address on GitHub.", + "format": "uri", + "type": [ + "string", + "null" + ] + }, + "repo": { + "description": "`owner/name` of the repository the run works in.", + "type": "string" + }, + "run_id": { + "description": "The run's id. `GET /api/runs/{run_id}` returns the whole run.", + "type": "string" + }, + "source": { + "description": "Where the work came from: `github`, `jira` or `alert` today; more may be added.", + "type": "string" + }, + "status": { + "description": "The run's status when the event happened.", + "enum": [ + "running", + "awaiting_ci", + "needs_input", + "needs_outside_change", + "completed", + "merged", + "failed", + "cancelled", + "closed" + ], + "type": "string" + }, + "ticket_id": { + "description": "The ticket's key or number at its source (empty for a task without one).", + "type": "string" + }, + "title": { + "description": "The ticket or task title.", + "type": "string" + }, + "updated_at": { + "description": "When the run last changed.", + "format": "date-time", + "type": "string" + }, + "url": { + "description": "The run in the CoderHelm dashboard.", + "format": "uri", + "type": "string" + } + }, + "required": [ + "run_id", + "status", + "title", + "repo", + "source", + "ticket_id", + "pr_number", + "pr_url", + "branch", + "error", + "url", + "created_at", + "updated_at" + ], + "type": "object" + }, + "id": { + "description": "The event's id (`evt_` and a ULID). The same on every retry and every endpoint: use it to ignore an event you already handled. Also sent as the `webhook-id` header.", + "type": "string" + }, + "team_id": { + "description": "The CoderHelm team it belongs to (as `GET /api/me` returns it).", + "type": "string" + }, + "type": { + "const": "run.needs_input", + "description": "The event type.", + "type": "string" + } + }, + "required": [ + "id", + "type", + "created_at", + "team_id", + "api_version", + "data" + ], + "type": "object" + } + } + }, + "required": true + }, + "responses": { + "2XX": { + "description": "Received. Answer within 10 seconds; do the work afterwards." + }, + "410": { + "description": "Gone: the delivery is final (not retried). Any 4xx other than 408 and 429 is final." + }, + "5XX": { + "description": "Retried with backoff for about a day, as are timeouts, 408 and 429." + } + }, + "security": [], + "summary": "A run is waiting for a person", "tags": [ - "Webhooks" + "Events: Runs" ] } }, - "/webhooks/relay": { + "webhook.test": { "post": { - "description": "On a hybrid self-hosted install, where CoderHelm's hosted relay forwards the events of CoderHelm's GitHub App (and Jira app) after checking the provider's own signature. Each request is signed with the install's relay key: `X-CoderHelm-Relay-Signature: t=,d=,v1=,v2=`, where `v1` is the HMAC-SHA256 of `..` and `v2` of `v2.....` (so the two headers below are signed too). Both must match: a request without `v2` is refused. Requests older than 5 minutes are refused, and so is a delivery id the install has already taken (`409`). `X-CoderHelm-Relay-Source` is `github` or `jira`; for GitHub, `X-CoderHelm-Relay-Event` is GitHub's event type and the body is GitHub's payload, unchanged.", - "operationId": "receiveRelayedEvent", + "description": "Sent by Send test event in Settings, Webhooks (or the API), to that endpoint only. Never sent by real work. Sent as `POST` to each endpoint subscribed to `webhook.test` (or to every event).", + "operationId": "event.webhook.test", "parameters": [ { - "description": "`t=,d=,v1=`.", - "example": "t=1761436800,d=72d3162e-cc78-11e3-81ab-4c9367dc0958,v1=5d1a…", + "description": "The event id (`evt_…`). The same on every retry: use it to skip an event you already handled.", + "example": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", "in": "header", - "name": "X-CoderHelm-Relay-Signature", + "name": "webhook-id", "required": true, "schema": { "type": "string" } }, { - "description": "Where the event came from: `github` or `jira`.", - "example": "github", + "description": "Unix seconds when this attempt was sent. Refuse a request more than 5 minutes off.", + "example": "1792420307", "in": "header", - "name": "X-CoderHelm-Relay-Source", + "name": "webhook-timestamp", "required": true, "schema": { "type": "string" } }, { - "description": "The provider's event type.", - "example": "pull_request", + "description": "Space-separated `v1,` signatures: HMAC-SHA256 of `..` keyed with the endpoint's secret (the bytes after `whsec_`, base64-decoded). Two while a rotated secret still signs; accept the request when any matches.", + "example": "v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4=", "in": "header", - "name": "X-CoderHelm-Relay-Event", - "required": false, + "name": "webhook-signature", + "required": true, "schema": { - "type": [ - "string", - "null" - ] + "type": "string" } } ], "requestBody": { "content": { "application/json": { + "examples": { + "event": { + "value": { + "api_version": "2026-10-26", + "created_at": "2026-10-26T14:31:47.512Z", + "data": { + "endpoint_id": "ep_01JBENDPT4A7B0C3D6E9F2G5H8", + "message": "A test event from CoderHelm. Nothing happened." + }, + "id": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "team_id": "TEAM#7c1f0e2a", + "type": "webhook.test" + } + } + }, "schema": { + "properties": { + "api_version": { + "const": "2026-10-26", + "description": "The version of this event's shape.", + "type": "string" + }, + "created_at": { + "description": "When it happened.", + "format": "date-time", + "type": "string" + }, + "data": { + "properties": { + "endpoint_id": { + "description": "The endpoint it was sent to.", + "type": "string" + }, + "message": { + "description": "A note that this is a test.", + "type": "string" + } + }, + "required": [ + "message", + "endpoint_id" + ], + "type": "object" + }, + "id": { + "description": "The event's id (`evt_` and a ULID). The same on every retry and every endpoint: use it to ignore an event you already handled. Also sent as the `webhook-id` header.", + "type": "string" + }, + "team_id": { + "description": "The CoderHelm team it belongs to (as `GET /api/me` returns it).", + "type": "string" + }, + "type": { + "const": "webhook.test", + "description": "The event type.", + "type": "string" + } + }, + "required": [ + "id", + "type", + "created_at", + "team_id", + "api_version", + "data" + ], "type": "object" } } }, - "description": "The provider's payload, unchanged.", "required": true }, "responses": { - "200": { - "description": "Handled (or acknowledged and ignored)." - }, - "401": { - "description": "The signature is missing, wrong, or more than 5 minutes old." + "2XX": { + "description": "Received. Answer within 10 seconds; do the work afterwards." }, - "404": { - "description": "This install isn't registered for the relay." + "410": { + "description": "Gone: the delivery is final (not retried). Any 4xx other than 408 and 429 is final." }, - "409": { - "description": "This delivery id was already received; the copy was refused." + "5XX": { + "description": "Retried with backoff for about a day, as are timeouts, 408 and 429." } }, - "security": [ - { - "relay_signature": [] - } - ], - "summary": "Events from CoderHelm's relay", + "security": [], + "summary": "A test event", "tags": [ - "Webhooks" + "Events: Testing" ] } } - }, - "servers": [ - { - "description": "Production", - "url": "https://api.coderhelm.com" - } - ], - "tags": [ - { - "description": "Who a key belongs to and what it may do.", - "name": "Account", - "x-displayName": "Account" - }, - { - "description": "A run is one piece of work by CoderHelm's coder: a ticket or task turned into a pull request. Runs are listed newest first.", - "name": "Runs", - "x-displayName": "Runs" - }, - { - "description": "A plan is a set of tasks, each of which becomes a run once the plan is executed.", - "name": "Plans", - "x-displayName": "Plans" - }, - { - "description": "The repositories connected to the team through the CoderHelm GitHub App.", - "name": "Repositories", - "x-displayName": "Repositories" - }, - { - "description": "Pull request reviews written by CoderHelm's reviewer.", - "name": "Reviews", - "x-displayName": "Reviews" - }, - { - "description": "Tokens used this month and the team's limits.", - "name": "Usage", - "x-displayName": "Usage" - }, - { - "description": "Endpoints a CI job calls with its GitHub Actions OIDC token, so no CoderHelm secret is stored in CI.", - "name": "CI", - "x-displayName": "CI" - }, - { - "description": "Events CoderHelm receives from GitHub, Jira, AWS SNS, Sanity and Notion. Each is verified before anything happens.", - "name": "Webhooks", - "x-displayName": "Webhooks" - } - ] + } } diff --git a/infra/lib/api-stack.ts b/infra/lib/api-stack.ts index 51e928765..4d52c64ec 100644 --- a/infra/lib/api-stack.ts +++ b/infra/lib/api-stack.ts @@ -51,6 +51,8 @@ export class ApiStack extends cdk.Stack { public readonly ticketQueue: sqs.Queue; public readonly ciFixQueue: sqs.Queue; public readonly feedbackQueue: sqs.Queue; + /** Outbound webhook events and their retries (common::webhooks). */ + public readonly webhookQueue: sqs.Queue; /** The shared dead-letter queue (the worker's DLQ cleanup reads it). */ public readonly dlq: sqs.Queue; /** The HTTP API (the single-origin web stack forwards to it). */ @@ -293,6 +295,16 @@ export class ApiStack extends cdk.Stack { deadLetterQueue: { queue: dlq, maxReceiveCount: 3 }, }); + // Outbound webhooks: events the work emits (`webhook_emit`) and the + // delayed retries of their deliveries (`webhook_send`). Its own queue so + // a delivery never waits behind long runs on the tickets queue. + this.webhookQueue = new sqs.Queue(this, "WebhookQueue", { + queueName: `${prefix}-webhooks`, + visibilityTimeout: cdk.Duration.minutes(16), + encryption: sqs.QueueEncryption.SQS_MANAGED, + deadLetterQueue: { queue: dlq, maxReceiveCount: 3 }, + }); + // Review-reminder sweep: every 20 min, drop a constant message on the ticket // queue; the worker's ReviewReminder handler scans repos with reminders // configured and nudges their Teams webhook about PRs still awaiting review. @@ -513,6 +525,7 @@ export class ApiStack extends cdk.Stack { PLUGIN_SCHEDULER_ROLE_ARN: pluginSchedulerRole.roleArn, CI_FIX_QUEUE_URL: this.ciFixQueue.queueUrl, FEEDBACK_QUEUE_URL: this.feedbackQueue.queueUrl, + WEBHOOK_QUEUE_URL: this.webhookQueue.queueUrl, DLQ_URL: dlq.queueUrl, SECRETS_NAME: `${props.cfg.secretName}`, SES_FROM_ADDRESS: cfg.email.from, @@ -603,6 +616,7 @@ export class ApiStack extends cdk.Stack { ); this.ciFixQueue.grantSendMessages(this.gatewayFunction); this.feedbackQueue.grantSendMessages(this.gatewayFunction); + this.webhookQueue.grantSendMessages(this.gatewayFunction); dlq.grantConsumeMessages(this.gatewayFunction); this.gatewayFunction.addToRolePolicy( new iam.PolicyStatement({ diff --git a/infra/lib/app.ts b/infra/lib/app.ts index 9bef8d35b..193ad99f0 100644 --- a/infra/lib/app.ts +++ b/infra/lib/app.ts @@ -69,6 +69,7 @@ export function buildApp(app: cdk.App, cfg: ResolvedConfig) { ticketQueue: api.ticketQueue, ciFixQueue: api.ciFixQueue, feedbackQueue: api.feedbackQueue, + webhookQueue: api.webhookQueue, dlq: api.dlq, mcpProxyFunction: api.mcpProxyFunction, encryptionKey: database.encryptionKey, @@ -92,6 +93,7 @@ export function buildApp(app: cdk.App, cfg: ResolvedConfig) { mcpProxyFunction: api.mcpProxyFunction, secretsKey: database.secretsKey, ticketQueue: api.ticketQueue, + webhookQueue: api.webhookQueue, }); // --- Web (single-origin only): dashboard + one URL for everything --- @@ -156,6 +158,7 @@ export function buildApp(app: cdk.App, cfg: ResolvedConfig) { awsInsightsTable: database.awsInsightsTable, settingsTable: database.settingsTable, secretsKey: database.secretsKey, + webhookQueue: api.webhookQueue, }); } diff --git a/infra/lib/email-stack.ts b/infra/lib/email-stack.ts index 5219bcc77..f95b840a5 100644 --- a/infra/lib/email-stack.ts +++ b/infra/lib/email-stack.ts @@ -95,6 +95,16 @@ export class EmailStack extends cdk.Stack { }, }); + // A webhook endpoint failed for days and was turned off (team admins). + new ses.CfnTemplate(this, "WebhookDisabledTemplate", { + template: { + templateName: `${prefix}-webhook-disabled`, + subjectPart: "CoderHelm turned off a webhook endpoint: {{host}}", + htmlPart: fill(WEBHOOK_DISABLED_HTML), + textPart: fill(WEBHOOK_DISABLED_TEXT), + }, + }); + new ses.CfnTemplate(this, "WeeklySummaryTemplate", { template: { templateName: `${prefix}-weekly-summary`, @@ -285,6 +295,27 @@ Error: {{error}} View run: __APP_URL__`; +const WEBHOOK_DISABLED_HTML = EMAIL_WRAPPER(` +

A webhook endpoint was turned off

+

+ Every delivery to {{url}} has failed since {{failing_since}} ({{days}} days), so CoderHelm stopped sending to it. +

+

{{description}}

+

+ Fix the endpoint, turn it back on in Settings, Webhooks, and replay the events it missed (they are kept 14 days). +

+ Open Webhooks +`); + +const WEBHOOK_DISABLED_TEXT = `A webhook endpoint was turned off + +Every delivery to {{url}} has failed since {{failing_since}} ({{days}} days), so CoderHelm stopped sending to it. +{{description}} + +Fix the endpoint, turn it back on in Settings, Webhooks, and replay the events it missed (they are kept 14 days). + +Open Webhooks: __APP_URL__/settings/webhooks`; + const WEEKLY_SUMMARY_HTML = EMAIL_WRAPPER(`

Weekly Summary — {{org}}

{{period}}

diff --git a/infra/lib/log-analyzer-stack.ts b/infra/lib/log-analyzer-stack.ts index 49caf5cfd..91cc65a3a 100644 --- a/infra/lib/log-analyzer-stack.ts +++ b/infra/lib/log-analyzer-stack.ts @@ -8,6 +8,7 @@ import * as kms from "aws-cdk-lib/aws-kms"; import * as logs from "aws-cdk-lib/aws-logs"; import * as s3 from "aws-cdk-lib/aws-s3"; import * as s3deploy from "aws-cdk-lib/aws-s3-deployment"; +import * as sqs from "aws-cdk-lib/aws-sqs"; import { Construct } from "constructs"; import { ResolvedConfig } from "./config"; import { repoPath } from "./paths"; @@ -23,6 +24,8 @@ interface LogAnalyzerStackProps extends cdk.StackProps { settingsTable: dynamodb.TableV2; /** Opens the sealed Teams/Slack webhooks new findings post to. */ secretsKey: kms.Key; + /** New and resolved findings go here as webhook events (log_finding.*). */ + webhookQueue: sqs.IQueue; } export class LogAnalyzerStack extends cdk.Stack { @@ -86,6 +89,7 @@ export class LogAnalyzerStack extends cdk.Stack { CODERHELM_ACCOUNT_ID: this.account, LOOKBACK_HOURS: "6", DASHBOARD_URL: props.appUrl, + WEBHOOK_QUEUE_URL: props.webhookQueue.queueUrl, ...modelProviderEnvironment(props.cfg), }, }); @@ -98,6 +102,7 @@ export class LogAnalyzerStack extends cdk.Stack { // Webhook URLs are sealed with the secrets key (bound to the team), like // the worker's: the analyzer only opens them. props.secretsKey.grantDecrypt(analyzerFunction); + props.webhookQueue.grantSendMessages(analyzerFunction); // Decoupled by name (like the worker) to avoid a cross-stack export. dynamodb.TableV2.fromTableName(this, "AnalyticsTableRef", `${prefix}-analytics`) .grantWriteData(analyzerFunction); diff --git a/infra/lib/streaming-stack.ts b/infra/lib/streaming-stack.ts index 61a41a3b2..7baad5615 100644 --- a/infra/lib/streaming-stack.ts +++ b/infra/lib/streaming-stack.ts @@ -30,6 +30,8 @@ interface StreamingStackProps extends cdk.StackProps { secretsKey: kms.Key; /** Where a plan chat call whose usage couldn't be written is queued. */ ticketQueue: sqs.IQueue; + /** Outbound webhook events (a route this function serves may emit one). */ + webhookQueue: sqs.IQueue; } export class StreamingStack extends cdk.Stack { @@ -112,6 +114,7 @@ export class StreamingStack extends cdk.Stack { // A model call whose usage couldn't be written waits here // (`usage_record`), for the worker to add once. TICKET_QUEUE_URL: props.ticketQueue.queueUrl, + WEBHOOK_QUEUE_URL: props.webhookQueue.queueUrl, // Unused by streaming but required by shared binary CI_FIX_QUEUE_URL: "unused", FEEDBACK_QUEUE_URL: "unused", @@ -157,6 +160,7 @@ export class StreamingStack extends cdk.Stack { ); props.ticketQueue.grantSendMessages(this.streamingFunction); + props.webhookQueue.grantSendMessages(this.streamingFunction); // Bedrock: Titan embeddings only (the shared gateway binary's memory // routes, metered in common::embed). Plan chat calls Anthropic directly diff --git a/infra/lib/worker-stack.ts b/infra/lib/worker-stack.ts index 64143f2d3..1d69af39a 100644 --- a/infra/lib/worker-stack.ts +++ b/infra/lib/worker-stack.ts @@ -37,6 +37,8 @@ interface WorkerStackProps extends cdk.StackProps { ticketQueue: sqs.Queue; ciFixQueue: sqs.Queue; feedbackQueue: sqs.Queue; + /** Outbound webhook events and retries: the worker sends them and queues retries. */ + webhookQueue: sqs.Queue; /** The shared DLQ: the daily cleanup archives and deletes unreadable messages. */ dlq: sqs.Queue; mcpProxyFunction: lambda.Function; @@ -126,6 +128,7 @@ export class WorkerStack extends cdk.Stack { PLUGIN_SCHEDULE_GROUP: `${prefix}-plugins`, PLUGIN_SCHEDULER_ROLE_ARN: `arn:aws:iam::${this.account}:role/${prefix}-plugin-scheduler`, FEEDBACK_QUEUE_URL: props.feedbackQueue.queueUrl, + WEBHOOK_QUEUE_URL: props.webhookQueue.queueUrl, DLQ_URL: props.dlq.queueUrl, RUST_LOG: "info", ...serviceEnvironment(cfg, this.account), @@ -276,6 +279,16 @@ export class WorkerStack extends cdk.Stack { }) ); + // Outbound webhooks: one event (or one retry) per message. The worker + // queues each delivery's next try back on this queue. + this.workerFunction.addEventSource( + new eventsources.SqsEventSource(props.webhookQueue, { + batchSize: 1, + maxConcurrency: 5, + }) + ); + props.webhookQueue.grantSendMessages(this.workerFunction); + // Grant worker permission to invoke the MCP proxy (owned by api-stack) props.mcpProxyFunction.grantInvoke(this.workerFunction); this.workerFunction.addEnvironment( diff --git a/infra/test/synth.test.ts b/infra/test/synth.test.ts index 139afa5f4..2f5b70c8c 100644 --- a/infra/test/synth.test.ts +++ b/infra/test/synth.test.ts @@ -621,3 +621,49 @@ test("sign-in: hosted keeps its open pool (no pre-sign-up trigger) and optional assert.equal(pool.Properties.LambdaConfig.PreSignUp, undefined); assert.ok(pool.Properties.LambdaConfig.CustomMessage); }); + +test("outbound webhooks: one queue, wired to the worker, sendable by every emitter", () => { + const t = synth(selfHost()); + const api = t["coderhelm-prod-api"]; + const queues = api.findResources("AWS::SQS::Queue", { + Properties: { QueueName: "coderhelm-prod-webhooks" }, + }); + const ids = Object.keys(queues); + assert.equal(ids.length, 1, "one webhooks queue"); + const q = (queues[ids[0]] as any).Properties; + // Visible longer than the worker can run, retried into the shared DLQ. + assert.equal(q.VisibilityTimeout, 960); + assert.equal(q.RedrivePolicy.maxReceiveCount, 3); + // Every function that emits or sends knows the queue. + const gw = envOf(api, "coderhelm-prod-gateway"); + assert.ok(gw.WEBHOOK_QUEUE_URL, "gateway"); + const worker = t["coderhelm-prod-worker"]; + assert.ok(envOf(worker, "coderhelm-prod-worker").WEBHOOK_QUEUE_URL, "worker"); + // The worker reads it one message at a time, with a concurrency cap. + const sources = Object.values(worker.findResources("AWS::Lambda::EventSourceMapping")) as any[]; + const fromWebhooks = sources.filter((s) => + JSON.stringify(s.Properties.EventSourceArn).includes("WebhookQueue") + ); + assert.equal(fromWebhooks.length, 1, "the worker consumes the webhooks queue"); + assert.equal(fromWebhooks[0].Properties.BatchSize, 1); + assert.equal(fromWebhooks[0].Properties.ScalingConfig.MaximumConcurrency, 5); + // Gateway, worker, streaming and the log analyzer may send to it. + for (const [stack, fn] of [ + ["coderhelm-prod-api", "Gateway"], + ["coderhelm-prod-worker", "Worker"], + ["coderhelm-prod-streaming", "Streaming"], + ["coderhelm-prod-log-analyzer", "Analyzer"], + ]) { + // A large role's statements spill into a managed "overflow" policy. + const policies = JSON.stringify([ + t[stack].findResources("AWS::IAM::Policy"), + t[stack].findResources("AWS::IAM::ManagedPolicy"), + ]); + assert.ok( + policies.includes("WebhookQueue") && policies.includes("sqs:SendMessage"), + `${fn} can send webhook events` + ); + } + // The template for the admins' email when an endpoint is turned off. + assert.ok(json(t["coderhelm-prod-email"]).includes("coderhelm-prod-webhook-disabled")); +}); diff --git a/lambda/log-analyzer/handler.py b/lambda/log-analyzer/handler.py index df4a0957b..acdb7d9f9 100644 --- a/lambda/log-analyzer/handler.py +++ b/lambda/log-analyzer/handler.py @@ -44,6 +44,11 @@ DASHBOARD_URL = os.environ["DASHBOARD_URL"].rstrip("/") # Team usage counters (empty: usage isn't counted). ANALYTICS_TABLE = os.environ.get("ANALYTICS_TABLE_NAME", "") +# Outbound webhook events go on this queue (empty: none are sent). The +# worker sends them to the team's endpoints (common::webhooks). +WEBHOOK_QUEUE_URL = os.environ.get("WEBHOOK_QUEUE_URL", "") +# Must equal common::webhooks::catalog::API_VERSION (a Rust test checks). +WEBHOOK_API_VERSION = "2026-10-26" dynamodb = boto3.resource("dynamodb") dynamodb_client = boto3.client("dynamodb") @@ -60,6 +65,7 @@ def _stored_model_provider(): usage.RUNTIME_LOADER = _stored_model_provider sts_client = boto3.client("sts") kms_client = boto3.client("kms") +sqs_client = boto3.client("sqs") # ── Pre-built Insights Queries ────────────────────────────────── @@ -709,6 +715,16 @@ def resolve_stale_recommendations(team_id, existing, seen_ids): ExpressionAttributeValues={":s": "resolved", ":t": now, ":pending": "pending"}, ) resolved_count += 1 + emit_event( + team_id, + "log_finding.resolved", + finding_event_data( + item["rec_id"], + item.get("source_account_id", ""), + item, + resolved_at=now.replace("+00:00", "Z"), + ), + ) except ClientError as e: if e.response.get("Error", {}).get("Code") != "ConditionalCheckFailedException": logger.warning(f"Failed to resolve {item['sk']}: {e}") @@ -716,6 +732,54 @@ def resolve_stale_recommendations(team_id, existing, seen_ids): logger.info(f"{team_id}: {resolved_count} recommendations resolved") +def finding_url(rec_id): + return f"{DASHBOARD_URL.rstrip('/')}/logs/?finding={rec_id}" + + +def webhook_event(team_id, event_type, data): + """The envelope common::webhooks::Event has, as the worker reads it.""" + now = datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z") + return { + "id": "evt_" + ulid_now().upper(), + "type": event_type, + "created_at": now, + "team_id": team_id, + "api_version": WEBHOOK_API_VERSION, + "data": data, + } + + +def emit_event(team_id, event_type, data, send=None): + """Queue one event for the team's webhook endpoints. Never raises: the + analysis matters more than the event.""" + if not WEBHOOK_QUEUE_URL or not team_id: + return None + event = webhook_event(team_id, event_type, data) + body = json.dumps({"type": "webhook_emit", "team_id": team_id, "event": event}) + try: + (send or sqs_client.send_message)(QueueUrl=WEBHOOK_QUEUE_URL, MessageBody=body) + return event["id"] + except Exception as e: # noqa: BLE001 + logger.warning(f"Could not queue webhook event {event_type}: {type(e).__name__}") + return None + + +def finding_event_data(rec_id, account_id, item, resolved_at=None): + """`log_finding.created` / `log_finding.resolved` data (the catalog's fields).""" + data = { + "finding_id": rec_id, + "account_id": account_id, + "title": scrub_secrets(str(item.get("title", ""))), + "severity": item.get("severity") if item.get("severity") in ("critical", "warning", "info") else "info", + } + if resolved_at is None: + data["log_group"] = item.get("source_log_group") or None + else: + data["resolved_at"] = resolved_at + data["url"] = finding_url(rec_id) + return data + + def error_hash_for(account_id, rec): raw = f"{account_id}:{rec.get('source_log_group', '')}:{rec.get('error_pattern', rec.get('title', ''))}" return hashlib.sha256(raw.encode()).hexdigest()[:16] @@ -854,6 +918,7 @@ def store_finding(team_id, account_id, cand, existing, cw_logs=None, window=None item["suspected_location"] = location try: aws_insights_table.put_item(Item=item) + emit_event(team_id, "log_finding.created", finding_event_data(rec_id, account_id, item)) existing.append({ "rec_id": rec_id, "sk": f"REC#{rec_id}", "error_hash": error_hash, "source_log_group": group, "count_basis": "events", "seen_count": stats["count"], diff --git a/lambda/tests/test_log_analyzer.py b/lambda/tests/test_log_analyzer.py index e694d2959..952a2e4cd 100644 --- a/lambda/tests/test_log_analyzer.py +++ b/lambda/tests/test_log_analyzer.py @@ -512,3 +512,56 @@ def invoke_model_with_response_stream(self, **kw): self.assertEqual(len(recorded), 1) u, call_id, estimated = recorded[0][5], recorded[0][6], recorded[0][7] self.assertEqual((u["uncached_input"], u["output"], call_id, estimated), (10, 3, "r1", False)) + + +class WebhookEvents(unittest.TestCase): + """Findings become log_finding.* events on the webhooks queue, in the + envelope the worker reads (common::webhooks::Event).""" + + def setUp(self): + self.sent = [] + h.WEBHOOK_QUEUE_URL = "https://sqs.example/queue" + + def tearDown(self): + h.WEBHOOK_QUEUE_URL = "" + + def send(self, **kw): + self.sent.append(kw) + + def test_an_event_has_the_envelope_and_an_uppercase_ulid(self): + import json + + item = {"title": "Timeouts", "severity": "critical", "source_log_group": "/aws/lambda/x"} + data = h.finding_event_data("01abc", "123456789012", item) + eid = h.emit_event("TEAM#a", "log_finding.created", data, send=self.send) + self.assertTrue(eid.startswith("evt_") and eid[4:] == eid[4:].upper() and len(eid) == 30) + msg = json.loads(self.sent[0]["MessageBody"]) + self.assertEqual(msg["type"], "webhook_emit") + ev = msg["event"] + self.assertEqual(list(ev), ["id", "type", "created_at", "team_id", "api_version", "data"]) + self.assertEqual(ev["api_version"], h.WEBHOOK_API_VERSION) + self.assertTrue(ev["created_at"].endswith("Z")) + self.assertEqual( + sorted(ev["data"]), + sorted(["finding_id", "account_id", "title", "severity", "log_group", "url"]), + ) + self.assertEqual(ev["data"]["url"], h.finding_url("01abc")) + + def test_resolved_findings_name_when_and_unknown_severities_read_as_info(self): + data = h.finding_event_data("01abc", "1", {"title": "t", "severity": "weird"}, resolved_at="2026-10-27T06:00:12Z") + self.assertEqual( + sorted(data), + sorted(["finding_id", "account_id", "title", "severity", "resolved_at", "url"]), + ) + self.assertEqual(data["severity"], "info") + + def test_without_a_queue_or_when_sending_fails_nothing_breaks(self): + h.WEBHOOK_QUEUE_URL = "" + self.assertIsNone(h.emit_event("TEAM#a", "log_finding.created", {}, send=self.send)) + self.assertEqual(self.sent, []) + h.WEBHOOK_QUEUE_URL = "https://sqs.example/queue" + + def boom(**kw): + raise RuntimeError("down") + + self.assertIsNone(h.emit_event("TEAM#a", "log_finding.created", {}, send=boom)) diff --git a/services/common/contract/worker_messages.json b/services/common/contract/worker_messages.json index 3fc3824b2..7e54731fc 100644 --- a/services/common/contract/worker_messages.json +++ b/services/common/contract/worker_messages.json @@ -11,6 +11,8 @@ "infra_analyze": {"type":"infra_analyze","team_id":"TEAM#team-a","triggered_by":"someone","repo":"acme/widgets"}, "resume": {"type":"resume","team_id":"TEAM#team-a","run_id":"r1","installation_id":1}, "review": {"type":"review","team_id":"TEAM#team-a","installation_id":1,"repo_owner":"acme","repo_name":"widgets","pr_number":2,"head_sha":"abc","label":"coderhelm-review","question":"why?","trigger":"labeled","dedup_key":"d","reply_to_comment_id":6,"requested_by":"someone"}, + "webhook_emit": {"type":"webhook_emit","team_id":"TEAM#team-a","event":{"id":"evt_01JBEVNT8M1N4P7Q0R3S6T9V2W","type":"run.failed","created_at":"2026-10-26T14:31:47.512Z","team_id":"TEAM#team-a","api_version":"2026-10-26","data":{"run_id":"r1"}}}, + "webhook_send": {"type":"webhook_send","team_id":"TEAM#team-a","endpoint_id":"ep_01jbendpt4a7b0c3d6e9f2g5h8","event_id":"evt_01JBEVNT8M1N4P7Q0R3S6T9V2W","delivery_id":"01hzzdelivery","due_at":1792416387}, "relay_retry": {"type":"relay_retry","install_id":"ins_abcdefghijklmnopqrstuvwx","delivery_id":"01hzzdelivery","relay_delivery_id":"72d3162e-cc78-11e3-81ab-4c9367dc0958","event":"pull_request","source":"github"}, "await_merge": {"type":"await_merge","team_id":"TEAM#team-a","installation_id":1,"repo_owner":"acme","repo_name":"widgets","pr_number":2,"head_sha":"abc","base_branch":"main","self_authored":true,"attempts":1,"chain_id":"c","error_retries":0}, "graph_index": {"type":"graph_index","team_id":"TEAM#team-a","installation_id":1,"repo_owner":"acme","repo_name":"widgets","branch":"main","changed_files":["a.rs"]}, diff --git a/services/common/src/deliveries.rs b/services/common/src/deliveries.rs index 45993f759..6cfc8d61e 100644 --- a/services/common/src/deliveries.rs +++ b/services/common/src/deliveries.rs @@ -95,6 +95,8 @@ pub enum Redeliver { Relay, /// Send a test message to the same channel (the original isn't kept). NotifyTest, + /// Send the kept event to the team's webhook endpoint again, signed now. + Webhook, } /// One delivery. @@ -102,7 +104,7 @@ pub enum Redeliver { pub struct Delivery { pub id: String, pub direction: Direction, - /// `github`, `relay`, `jira`, `alerts`, `slack`, `teams`, `email`, `broker`, `knowledge`. + /// `github`, `relay`, `jira`, `alerts`, `slack`, `teams`, `email`, `broker`, `knowledge`, `webhook`. pub source: String, /// The event or message type, e.g. `pull_request.opened`. pub event: String, @@ -122,6 +124,9 @@ pub struct Delivery { pub repo: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub pr: Option, + /// The team's webhook endpoint an outbound webhook went to. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub endpoint_id: String, pub created_at: String, pub duration_ms: u64, #[serde(default)] @@ -152,6 +157,7 @@ impl Delivery { external_id: String::new(), repo: String::new(), pr: None, + endpoint_id: String::new(), created_at: chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true), duration_ms: 0, attempts: vec![], @@ -340,6 +346,16 @@ const REASONS: &[Reason] = &[ Reason { code: "broker_refused", message: "CoderHelm's token broker refused the request.", fix: "Open Settings, System, Hybrid: it shows the link's state and how to fix it." }, Reason { code: "broker_unreachable", message: "CoderHelm's token broker didn't answer.", fix: "Usually temporary; the next request retries. status.coderhelm.com shows any outage." }, Reason { code: "jira_signature", message: "The Jira webhook's signature didn't match.", fix: "Copy the webhook secret from Settings, Jira into Jira's webhook again." }, + Reason { code: "webhook_unreachable", message: "Your webhook endpoint couldn't be reached (the connection failed or its name didn't resolve).", fix: "Check the endpoint's address and that it is up. CoderHelm keeps retrying for about a day." }, + Reason { code: "webhook_timeout", message: "Your webhook endpoint didn't answer within 10 seconds.", fix: "Answer with a 2xx at once and do the work afterwards (queue it). CoderHelm retries meanwhile." }, + Reason { code: "webhook_server_error", message: "Your webhook endpoint answered with a server error (5xx).", fix: "Check your endpoint's logs for this event id. CoderHelm retries for about a day." }, + Reason { code: "webhook_rate_limited", message: "Your webhook endpoint answered 429 Too Many Requests.", fix: "Raise the endpoint's limit for CoderHelm. CoderHelm retries later." }, + Reason { code: "webhook_refused", message: "Your webhook endpoint refused the event (a 4xx answer), so it isn't retried.", fix: "Check that the endpoint verifies signatures with the right secret and accepts JSON, then press Resend." }, + Reason { code: "webhook_endpoint_gone", message: "Your webhook endpoint answered 410 Gone.", fix: "Update the address in Settings, Webhooks, or delete the endpoint." }, + Reason { code: "webhook_redirect", message: "Your webhook endpoint answered with a redirect. Redirects aren't followed.", fix: "Use the final address (where the redirect points) in Settings, Webhooks." }, + Reason { code: "webhook_blocked", message: "The endpoint's address points inside a private network, or to a local or cloud metadata address, so nothing was sent.", fix: "Use an address on the public internet. Its name must resolve only to public addresses." }, + Reason { code: "webhook_gave_up", message: "Delivery stopped after about a day of failed attempts.", fix: "Fix what the attempts show, then press Resend, or replay a time range from the endpoint's page." }, + Reason { code: "webhook_disabled", message: "The endpoint is turned off, so the event wasn't sent.", fix: "Turn the endpoint on in Settings, Webhooks, then replay the events you missed." }, Reason { code: "jira_limit", message: "The team's monthly token limit was reached, so the ticket wasn't started.", fix: "Raise the limit in Settings, Usage, or wait for next month." }, ]; @@ -367,6 +383,7 @@ pub fn reason_for_http(source: &str, code: Option) -> &'static str { ("slack" | "teams", Some(404 | 410)) => "chat_webhook_gone", ("slack" | "teams", None) => "chat_unreachable", ("slack" | "teams", Some(_)) => "chat_rejected", + ("webhook", c) => crate::webhooks::deliver::reason_code(c, false, false), _ => "unknown", } } @@ -536,6 +553,9 @@ pub struct Filter { /// A delivery id, GitHub delivery id, repository or PR number. #[serde(default)] pub q: Option, + /// Only deliveries to this webhook endpoint. + #[serde(default)] + pub endpoint: Option, } impl Filter { @@ -563,6 +583,11 @@ impl Filter { return false; } } + if let Some(ep) = self.endpoint.as_deref().filter(|e| !e.is_empty()) { + if d.endpoint_id != ep { + return false; + } + } if let Some(since) = self.since.as_deref().filter(|s| !s.is_empty()) { if d.created_at.as_str() < since { return false; @@ -911,6 +936,7 @@ mod tests { status: status.map(Into::into), since: None, q: q.map(Into::into), + endpoint: None, }; assert!(f(Some("github"), Some("failed"), None).matches(&d)); assert!(!f(Some("relay"), None, None).matches(&d)); @@ -928,5 +954,19 @@ mod tests { ..Default::default() }; assert!(!since.matches(&d)); + let mut w = at("2026-10-25T10:00:00Z", Status::Failed, "webhook"); + w.endpoint_id = "ep_1".into(); + let ep = |e: &str| Filter { + endpoint: Some(e.into()), + ..Default::default() + }; + assert!(ep("ep_1").matches(&w)); + assert!(!ep("ep_2").matches(&w)); + assert!(!ep("ep_1").matches(&d)); + assert_eq!( + reason_for_http("webhook", Some(503)), + "webhook_server_error" + ); + assert_eq!(reason_for_http("webhook", None), "webhook_unreachable"); } } diff --git a/services/common/src/dlq.rs b/services/common/src/dlq.rs index 63aa58e44..0abe535c7 100644 --- a/services/common/src/dlq.rs +++ b/services/common/src/dlq.rs @@ -24,6 +24,8 @@ use serde::Serialize; pub const WORKER_MESSAGE_TYPES: &[&str] = &[ "ticket", "relay_retry", + "webhook_emit", + "webhook_send", "tool_proposals", "hidden_suggest", "feedback", diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 0f45b7b00..e6ec02eae 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -23,6 +23,8 @@ pub mod dlq; /// Hybrid self-hosting: CoderHelm addresses, the event relay, the token /// broker and the signatures between an install and the hosted side. pub mod hybrid; +/// Outbound webhooks: the event catalog, endpoints, signing and delivery. +pub mod webhooks; /// Agent permissions: one policy engine (allow, ask, deny) every agent loop /// asks before every call, approval cards, sign-in prompts and the pause. diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index c42dc5e5b..0526e3395 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -64,6 +64,14 @@ pub enum WorkerMessage { /// again (self-scheduled with SQS delay, about 24 hours of backoff). #[serde(rename = "relay_retry")] RelayRetry(RelayRetryMessage), + /// An event for the team's webhook endpoints (`crate::webhooks`), put on + /// the webhooks queue by `emit_event` wherever the work happened. + #[serde(rename = "webhook_emit")] + WebhookEmit(WebhookEmitMessage), + /// One more try at a webhook delivery (self-scheduled with SQS delay; + /// a wait longer than SQS allows is carried by `due_at`). + #[serde(rename = "webhook_send")] + WebhookSend(WebhookSendMessage), /// Coalesced release-tag sweep (self-scheduled with SQS delay). One is armed /// per repo by the first merge in a batch window; later merges in the window /// fold into it. When it fires it cuts ONE release tag at the default @@ -333,6 +341,8 @@ impl WorkerMessage { WorkerMessage::HealthCheck(_) | WorkerMessage::AwaitMerge(_) | WorkerMessage::RelayRetry(_) + | WorkerMessage::WebhookEmit(_) + | WorkerMessage::WebhookSend(_) | WorkerMessage::GraphIndex(_) | WorkerMessage::WeeklySummary | WorkerMessage::WeeklySummaryTest(_) @@ -503,6 +513,28 @@ pub struct AwaitMergeMessage { pub error_retries: u32, } +/// An event for the team's webhook endpoints. +#[derive(Serialize, Deserialize, Debug, Clone)] +pub struct WebhookEmitMessage { + /// The event's team, at the top so a dead-lettered message is the team's. + #[serde(default)] + pub team_id: String, + pub event: crate::webhooks::Event, +} + +/// One webhook delivery to try (again). +#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)] +pub struct WebhookSendMessage { + pub team_id: String, + pub endpoint_id: String, + pub event_id: String, + /// The delivery record the attempt goes on. + pub delivery_id: String, + /// Unix seconds: not before this. + #[serde(default)] + pub due_at: i64, +} + /// A relay forward to try again (hosted side of hybrid). #[derive(Serialize, Deserialize, Debug, Clone, Default)] pub struct RelayRetryMessage { diff --git a/services/common/src/webhooks/catalog.rs b/services/common/src/webhooks/catalog.rs new file mode 100644 index 000000000..9f5f2fc01 --- /dev/null +++ b/services/common/src/webhooks/catalog.rs @@ -0,0 +1,821 @@ +//! The event catalog: every event type CoderHelm sends to a team's webhook +//! endpoints, the shape of its `data`, and an example. +//! +//! The catalog is the contract. The OpenAPI document's `webhooks` section, +//! the endpoint settings page's event picker and the docs are all made from +//! it, and the tests below check that each example matches its own schema. +//! A field is only ever added to an event within one [`API_VERSION`]; a +//! rename or removal means a new version. + +use serde_json::{json, Map, Value}; + +/// The version every event carries as `api_version`. +pub const API_VERSION: &str = "2026-10-26"; + +/// The event sent by "Send test event". Never emitted by real work, and +/// delivered only to the endpoint it was sent to. +pub const TEST_EVENT: &str = "webhook.test"; + +/// A field's type. +#[derive(Debug, Clone, Copy)] +pub enum Kind { + String, + /// An RFC 3339 time. + Time, + /// An absolute URL. + Url, + Integer, + Boolean, + /// One of these strings. + Enum(&'static [&'static str]), + StringArray, +} + +/// One field of an event's `data`. +#[derive(Debug, Clone, Copy)] +pub struct Field { + pub name: &'static str, + pub kind: Kind, + /// May be `null` (it is always present). + pub nullable: bool, + pub description: &'static str, +} + +const fn f(name: &'static str, kind: Kind, description: &'static str) -> Field { + Field { + name, + kind, + nullable: false, + description, + } +} + +const fn opt(name: &'static str, kind: Kind, description: &'static str) -> Field { + Field { + name, + kind, + nullable: true, + description, + } +} + +/// One event type. +#[derive(Debug, Clone, Copy)] +pub struct EventType { + pub name: &'static str, + /// Groups the picker and the docs by what the event is about. + pub group: &'static str, + pub summary: &'static str, + /// When it is sent, in plain words. + pub description: &'static str, + pub fields: &'static [Field], + /// Sent only to teams with this feature turned on. + pub feature: Option<&'static str>, +} + +pub const RUN_STATUSES: &[&str] = &[ + "running", + "awaiting_ci", + "needs_input", + "needs_outside_change", + "completed", + "merged", + "failed", + "cancelled", + "closed", +]; + +/// A run, as every `run.*` event carries it. +pub const RUN_FIELDS: &[Field] = &[ + f( + "run_id", + Kind::String, + "The run's id. `GET /api/runs/{run_id}` returns the whole run.", + ), + f( + "status", + Kind::Enum(RUN_STATUSES), + "The run's status when the event happened.", + ), + f("title", Kind::String, "The ticket or task title."), + f( + "repo", + Kind::String, + "`owner/name` of the repository the run works in.", + ), + f( + "source", + Kind::String, + "Where the work came from: `github`, `jira` or `alert` today; more may be added.", + ), + f( + "ticket_id", + Kind::String, + "The ticket's key or number at its source (empty for a task without one).", + ), + opt( + "pr_number", + Kind::Integer, + "The pull request CoderHelm opened, once there is one.", + ), + opt("pr_url", Kind::Url, "The pull request's address on GitHub."), + opt("branch", Kind::String, "The branch CoderHelm works on."), + opt( + "error", + Kind::String, + "Why the run failed or what it needs, in plain words.", + ), + f("url", Kind::Url, "The run in the CoderHelm dashboard."), + f("created_at", Kind::Time, "When the run started."), + f("updated_at", Kind::Time, "When the run last changed."), +]; + +const PR_FIELDS: &[Field] = &[ + f("run_id", Kind::String, "The run that opened it."), + f("repo", Kind::String, "`owner/name`."), + f("number", Kind::Integer, "The pull request number."), + f("url", Kind::Url, "The pull request on GitHub."), + f("title", Kind::String, "The run's title (the ticket or task the pull request is for)."), + f("branch", Kind::String, "The head branch."), + opt("base_branch", Kind::String, "The branch it merges into, when the work named one (otherwise the repository's default branch)."), + f("draft", Kind::Boolean, "Opened as a draft (CoderHelm marks it ready when its checks pass)."), +]; + +const REVIEW_FIELDS: &[Field] = &[ + f("repo", Kind::String, "`owner/name`."), + f("pr_number", Kind::Integer, "The pull request reviewed."), + f("pr_url", Kind::Url, "The pull request on GitHub."), + f("head_sha", Kind::String, "The commit the review is for."), + f("verdict", Kind::Enum(&["approve", "request_changes", "comment"]), "What the reviewer decided."), + f("posted_as", Kind::Enum(&["approve", "request_changes", "comment"]), "How the review was posted on GitHub. On CoderHelm's own pull requests GitHub allows only `comment`, whatever the verdict."), + f("risk", Kind::String, "The reviewer's risk rating (`low`, `medium`, `high`), or `n/a`."), + f("trigger", Kind::String, "What asked for the review: `opened`, `synchronize`, `labeled`, `requested`, `run` and others."), + f("url", Kind::Url, "The review in the CoderHelm dashboard."), +]; + +const CI_FIX_STARTED: &[Field] = &[ + f( + "run_id", + Kind::String, + "The run whose pull request failed its checks.", + ), + f("repo", Kind::String, "`owner/name`."), + f("pr_number", Kind::Integer, "The pull request."), + f("branch", Kind::String, "The branch the fix is pushed to."), + f( + "attempt", + Kind::Integer, + "Which fix this is for the run, from 1.", + ), + f( + "failing_checks", + Kind::StringArray, + "The checks that failed.", + ), +]; + +const CI_FIX_COMPLETED: &[Field] = &[ + f("run_id", Kind::String, "The run."), + f("repo", Kind::String, "`owner/name`."), + f("pr_number", Kind::Integer, "The pull request."), + f("branch", Kind::String, "The branch."), + f("attempt", Kind::Integer, "Which fix this was, from 1."), + f("outcome", Kind::Enum(&["pushed", "no_changes", "failed"]), "`pushed`: a fix was pushed and the checks run again. `no_changes`: nothing to change, so the pull request goes to people. `failed`: the fix could not be made."), + f("files_changed", Kind::Integer, "Files the fix changed."), +]; + +const ALERT_FIELDS: &[Field] = &[ + f("alert_id", Kind::String, "The alert's id in CoderHelm."), + f("kind", Kind::String, "What sent it, e.g. `cloudwatch_alarm`, `datadog`, `sentry`, `generic`."), + f("title", Kind::String, "The alert's title."), + f("severity", Kind::Enum(&["alarm", "warning", "resolved", "info"]), "How it reads at a glance."), + f("outcome", Kind::String, "What CoderHelm did with it: `run_started` (a fix run was queued), `notified`, `duplicate`, `in_flight` (a run for it is already working), `recovered`, `no_open_alert`, `not_alarm`, `no_match`, `route_paused`, `budget`, `alert_budget`, `daily_cap`, `misconfigured` or `error`. More may be added."), + opt("repo", Kind::String, "The repository the alert is routed to, if any."), + f("ticket_id", Kind::String, "The alert's ticket: the same alert repeating has the same one, and a run started for it carries it as its `ticket_id`."), + f("received_at", Kind::Time, "When CoderHelm received it."), +]; + +const FINDING_FIELDS: &[Field] = &[ + f("finding_id", Kind::String, "The finding's id."), + f( + "account_id", + Kind::String, + "The AWS account whose logs it was found in.", + ), + f("title", Kind::String, "What is wrong, in a line."), + f( + "severity", + Kind::Enum(&["critical", "warning", "info"]), + "How bad it is.", + ), + opt( + "log_group", + Kind::String, + "The log group the matching lines are in.", + ), + f("url", Kind::Url, "The finding on the Logs page."), +]; + +const FINDING_RESOLVED: &[Field] = &[ + f("finding_id", Kind::String, "The finding's id."), + f("account_id", Kind::String, "The AWS account."), + f("title", Kind::String, "What was wrong."), + f( + "severity", + Kind::Enum(&["critical", "warning", "info"]), + "How bad it was.", + ), + f( + "resolved_at", + Kind::Time, + "When a complete analysis no longer saw it.", + ), + f("url", Kind::Url, "The finding on the Logs page."), +]; + +const RELEASE_FIELDS: &[Field] = &[ + f("repo", Kind::String, "`owner/name`."), + f("tag", Kind::String, "The release tag."), + f("sha", Kind::String, "The commit the tag points at."), + opt( + "release_url", + Kind::Url, + "The GitHub Release, when one was written.", + ), + f( + "channels", + Kind::StringArray, + "Where the notes went: `github`, `confluence`, `email`.", + ), +]; + +const PLAN_FIELDS: &[Field] = &[ + f("plan_id", Kind::String, "The plan's id. `GET /api/plans/{plan_id}` returns it."), + f("title", Kind::String, "The plan's title."), + f("task_count", Kind::Integer, "Tasks approved to run."), + f("approved_by", Kind::String, "Who approved it: their GitHub login or email, or `api_key:` for a request made with an API key."), + f("url", Kind::Url, "The plan in the dashboard."), +]; + +const PLUGIN_RUN_FIELDS: &[Field] = &[ + f("run_id", Kind::String, "The plugin run's id."), + f("plugin_id", Kind::String, "The plugin."), + f( + "status", + Kind::Enum(&["completed", "failed"]), + "How it ended.", + ), + f( + "trigger", + Kind::String, + "What started it: `manual`, `schedule`, `event` or `api`.", + ), + opt("error", Kind::String, "Why it failed."), +]; + +const TEST_FIELDS: &[Field] = &[ + f("message", Kind::String, "A note that this is a test."), + f("endpoint_id", Kind::String, "The endpoint it was sent to."), +]; + +/// Every event type, in the order the docs and the picker list them. +pub const EVENTS: &[EventType] = &[ + EventType { + name: "run.created", + group: "Runs", + summary: "A run started", + description: "CoderHelm started work on a ticket, task or alert.", + fields: RUN_FIELDS, + feature: None, + }, + EventType { + name: "run.completed", + group: "Runs", + summary: "A run finished", + description: "The run finished: its pull request passed its checks and is ready for people, or no code change was needed.", + fields: RUN_FIELDS, + feature: None, + }, + EventType { + name: "run.failed", + group: "Runs", + summary: "A run failed", + description: "The run stopped on an error. `error` says why.", + fields: RUN_FIELDS, + feature: None, + }, + EventType { + name: "run.needs_input", + group: "Runs", + summary: "A run is waiting for a person", + description: "The run asked a question on its ticket or pull request and waits for an answer. `error` holds the question.", + fields: RUN_FIELDS, + feature: None, + }, + EventType { + name: "pull_request.opened", + group: "Pull requests", + summary: "CoderHelm opened a pull request", + description: "A run opened a pull request. Pull requests people open are not sent.", + fields: PR_FIELDS, + feature: None, + }, + EventType { + name: "review.completed", + group: "Reviews", + summary: "A review was posted", + description: "CoderHelm's reviewer posted a review on a pull request, with its verdict.", + fields: REVIEW_FIELDS, + feature: None, + }, + EventType { + name: "ci_fix.started", + group: "CI fixes", + summary: "A CI fix started", + description: "A pull request CoderHelm opened failed its checks, and CoderHelm started fixing it.", + fields: CI_FIX_STARTED, + feature: None, + }, + EventType { + name: "ci_fix.completed", + group: "CI fixes", + summary: "A CI fix finished", + description: "The CI fix finished. `outcome` says whether a fix was pushed.", + fields: CI_FIX_COMPLETED, + feature: None, + }, + EventType { + name: "alert.received", + group: "Alerts", + summary: "An alert arrived", + description: "An alert came in on one of the team's alert addresses, and CoderHelm decided what to do with it.", + fields: ALERT_FIELDS, + feature: None, + }, + EventType { + name: "log_finding.created", + group: "Logs", + summary: "A new log finding", + description: "The log analysis found a new problem in a connected AWS account's logs.", + fields: FINDING_FIELDS, + feature: None, + }, + EventType { + name: "log_finding.resolved", + group: "Logs", + summary: "A log finding went away", + description: "A complete log analysis no longer saw a finding that was open.", + fields: FINDING_RESOLVED, + feature: None, + }, + EventType { + name: "release_notes.published", + group: "Releases", + summary: "Release notes went out", + description: "CoderHelm wrote and published the notes for a release tag.", + fields: RELEASE_FIELDS, + feature: None, + }, + EventType { + name: "plan.approved", + group: "Plans", + summary: "A plan was approved", + description: "Someone approved a plan and started its tasks (Approve and run in the dashboard, or the API).", + fields: PLAN_FIELDS, + feature: None, + }, + EventType { + name: "plugin.run.completed", + group: "Plugins", + summary: "A plugin run finished", + description: "A plugin run finished or failed. Sent only to teams with plugins turned on.", + fields: PLUGIN_RUN_FIELDS, + feature: Some("plugins"), + }, + EventType { + name: TEST_EVENT, + group: "Testing", + summary: "A test event", + description: "Sent by Send test event in Settings, Webhooks (or the API), to that endpoint only. Never sent by real work.", + fields: TEST_FIELDS, + feature: None, + }, +]; + +/// One event type by name. +pub fn find(name: &str) -> Option<&'static EventType> { + EVENTS.iter().find(|e| e.name == name) +} + +/// The event types an endpoint can subscribe to (all but the test event, +/// which every endpoint gets when someone sends it). +pub fn subscribable() -> impl Iterator { + EVENTS.iter().filter(|e| e.name != TEST_EVENT) +} + +fn kind_schema(k: Kind) -> Value { + match k { + Kind::String => json!({ "type": "string" }), + Kind::Time => json!({ "type": "string", "format": "date-time" }), + Kind::Url => json!({ "type": "string", "format": "uri" }), + Kind::Integer => json!({ "type": "integer" }), + Kind::Boolean => json!({ "type": "boolean" }), + Kind::Enum(values) => json!({ "type": "string", "enum": values }), + Kind::StringArray => json!({ "type": "array", "items": { "type": "string" } }), + } +} + +/// The JSON Schema (2020-12, as OpenAPI 3.1 uses) of an event's `data`. +pub fn data_schema(e: &EventType) -> Value { + let mut props = Map::new(); + for field in e.fields { + let mut s = kind_schema(field.kind); + if field.nullable { + let t = s["type"].clone(); + s["type"] = json!([t, "null"]); + if let Some(values) = s.get_mut("enum").and_then(|v| v.as_array_mut()) { + values.push(Value::Null); + } + } + s["description"] = json!(field.description); + props.insert(field.name.into(), s); + } + json!({ + "type": "object", + "properties": props, + "required": e.fields.iter().map(|f| f.name).collect::>(), + }) +} + +/// The JSON Schema of a whole event (the envelope around `data`). +pub fn event_schema(e: &EventType) -> Value { + json!({ + "type": "object", + "required": ["id", "type", "created_at", "team_id", "api_version", "data"], + "properties": { + "id": { "type": "string", "description": "The event's id (`evt_` and a ULID). The same on every retry and every endpoint: use it to ignore an event you already handled. Also sent as the `webhook-id` header." }, + "type": { "type": "string", "const": e.name, "description": "The event type." }, + "created_at": { "type": "string", "format": "date-time", "description": "When it happened." }, + "team_id": { "type": "string", "description": "The CoderHelm team it belongs to (as `GET /api/me` returns it)." }, + "api_version": { "type": "string", "const": API_VERSION, "description": "The version of this event's shape." }, + "data": data_schema(e), + }, + }) +} + +const EXAMPLE_RUN_ID: &str = "01JBRUN7Q2X9M3V6T8W1K4HZ5C"; +const EXAMPLE_TEAM: &str = "TEAM#7c1f0e2a"; + +fn run_example(status: &str, pr: bool, error: Option<&str>) -> Value { + json!({ + "run_id": EXAMPLE_RUN_ID, + "status": status, + "title": "Add rate limiting to the export endpoint", + "repo": "example-org/api", + "source": "jira", + "ticket_id": "ENG-142", + "pr_number": if pr { json!(318) } else { Value::Null }, + "pr_url": if pr { json!("https://github.com/example-org/api/pull/318") } else { Value::Null }, + "branch": if pr { json!("coderhelm/eng-142-rate-limit-export") } else { Value::Null }, + "error": error, + "url": format!("https://coderhelm.example.com/runs/detail/?id={EXAMPLE_RUN_ID}"), + "created_at": "2026-10-26T14:02:11.000Z", + "updated_at": "2026-10-26T14:31:47.000Z", + }) +} + +/// An example `data` for an event type. +pub fn example_data(name: &str) -> Value { + match name { + "run.created" => run_example("running", false, None), + "run.completed" => run_example("completed", true, None), + "run.failed" => run_example( + "failed", + false, + Some("The repository's install step failed: npm ERR! 404 Not Found - @example/internal-ui"), + ), + "run.needs_input" => run_example( + "needs_input", + false, + Some("Should the limit apply per API key or per team?"), + ), + "pull_request.opened" => json!({ + "run_id": EXAMPLE_RUN_ID, + "repo": "example-org/api", + "number": 318, + "url": "https://github.com/example-org/api/pull/318", + "title": "Add rate limiting to the export endpoint", + "branch": "coderhelm/eng-142-rate-limit-export", + "base_branch": "main", + "draft": true, + }), + "review.completed" => json!({ + "repo": "example-org/web", + "pr_number": 902, + "pr_url": "https://github.com/example-org/web/pull/902", + "head_sha": "9f1c2ab7e04d3c5a8b6f0e1d2c3b4a5f6e7d8c9b", + "verdict": "request_changes", + "posted_as": "request_changes", + "risk": "medium", + "trigger": "opened", + "url": "https://coderhelm.example.com/reviewer/?repo=example-org%2Fweb&pr=902", + }), + "ci_fix.started" => json!({ + "run_id": EXAMPLE_RUN_ID, + "repo": "example-org/api", + "pr_number": 318, + "branch": "coderhelm/eng-142-rate-limit-export", + "attempt": 1, + "failing_checks": ["test (20.x)", "lint"], + }), + "ci_fix.completed" => json!({ + "run_id": EXAMPLE_RUN_ID, + "repo": "example-org/api", + "pr_number": 318, + "branch": "coderhelm/eng-142-rate-limit-export", + "attempt": 1, + "outcome": "pushed", + "files_changed": 2, + }), + "alert.received" => json!({ + "alert_id": "01JBALERT3K8P2N6Q9R1S4T7V0", + "kind": "cloudwatch_alarm", + "title": "ALARM: api-5xx-rate", + "severity": "alarm", + "outcome": "run_started", + "repo": "example-org/api", + "ticket_id": "ALERT-3f9c2a71", + "received_at": "2026-10-26T09:14:03.000Z", + }), + "log_finding.created" => json!({ + "finding_id": "01JBFIND6W3X8Y1Z4A7B0C2D5E", + "account_id": "123456789012", + "title": "Unhandled TimeoutError in the invoice worker", + "severity": "critical", + "log_group": "/aws/lambda/invoice-worker", + "url": "https://coderhelm.example.com/logs/?finding=01JBFIND6W3X8Y1Z4A7B0C2D5E", + }), + "log_finding.resolved" => json!({ + "finding_id": "01JBFIND6W3X8Y1Z4A7B0C2D5E", + "account_id": "123456789012", + "title": "Unhandled TimeoutError in the invoice worker", + "severity": "critical", + "resolved_at": "2026-10-27T06:00:12.000Z", + "url": "https://coderhelm.example.com/logs/?finding=01JBFIND6W3X8Y1Z4A7B0C2D5E", + }), + "release_notes.published" => json!({ + "repo": "example-org/api", + "tag": "v2.14.0", + "sha": "4b7e9d1c0a2f3e5d6c8b9a0f1e2d3c4b5a6f7e8d", + "release_url": "https://github.com/example-org/api/releases/tag/v2.14.0", + "channels": ["github", "email"], + }), + "plan.approved" => json!({ + "plan_id": "01JBPLAN2F5G8H1J4K7L0M3N6P", + "title": "Move exports to the background queue", + "task_count": 4, + "approved_by": "lead@example.com", + "url": "https://coderhelm.example.com/plans/detail/?id=01JBPLAN2F5G8H1J4K7L0M3N6P", + }), + "plugin.run.completed" => json!({ + "run_id": "01JBPRUN9Q2R5S8T1U4V7W0X3Y", + "plugin_id": "release-announcer", + "status": "completed", + "trigger": "schedule", + "error": null, + }), + TEST_EVENT => json!({ + "message": "A test event from CoderHelm. Nothing happened.", + "endpoint_id": "ep_01JBENDPT4A7B0C3D6E9F2G5H8", + }), + _ => json!({}), + } +} + +/// A whole example event of a type. +pub fn example_event(name: &str) -> Value { + json!({ + "id": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "type": name, + "created_at": "2026-10-26T14:31:47.512Z", + "team_id": EXAMPLE_TEAM, + "api_version": API_VERSION, + "data": example_data(name), + }) +} + +/// Whether a stored subscription list names only real event types (`*` is +/// every event). +pub fn unknown_types(types: &[String]) -> Vec { + types + .iter() + .filter(|t| t.as_str() != "*" && !subscribable().any(|e| e.name == t.as_str())) + .cloned() + .collect() +} + +#[cfg(test)] +pub(crate) fn conforms(schema: &Value, v: &Value) -> Result<(), String> { + if let Some(c) = schema.get("const") { + if c != v { + return Err(format!("expected {c}, got {v}")); + } + } + let types: Vec<&str> = match &schema["type"] { + Value::String(s) => vec![s.as_str()], + Value::Array(a) => a.iter().filter_map(|t| t.as_str()).collect(), + _ => vec![], + }; + let ok_type = types.iter().any(|t| match *t { + "string" => v.is_string(), + "integer" => v.is_i64() || v.is_u64(), + "boolean" => v.is_boolean(), + "array" => v.is_array(), + "object" => v.is_object(), + "null" => v.is_null(), + _ => false, + }); + if !types.is_empty() && !ok_type { + return Err(format!("{v} is not {types:?}")); + } + if let Some(values) = schema.get("enum").and_then(|e| e.as_array()) { + if !values.contains(v) { + return Err(format!("{v} is not one of {values:?}")); + } + } + if let (Some(props), Some(obj)) = ( + schema.get("properties").and_then(|p| p.as_object()), + v.as_object(), + ) { + for req in schema["required"].as_array().into_iter().flatten() { + let k = req.as_str().unwrap_or(""); + if !obj.contains_key(k) { + return Err(format!("missing {k}")); + } + } + for k in obj.keys() { + if !props.contains_key(k) { + return Err(format!("{k} is not in the schema")); + } + } + for (k, s) in props { + if let Some(x) = obj.get(k) { + conforms(s, x).map_err(|e| format!("{k}: {e}"))?; + } + } + } + if let (Some(items), Some(arr)) = (schema.get("items"), v.as_array()) { + for x in arr { + conforms(items, x)?; + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_example_matches_its_schema() { + for e in EVENTS { + let ex = example_event(e.name); + conforms(&event_schema(e), &ex).unwrap_or_else(|err| panic!("{}: {err}", e.name)); + } + } + + #[test] + fn names_are_unique_dotted_and_described() { + let mut seen = std::collections::BTreeSet::new(); + for e in EVENTS { + assert!(seen.insert(e.name), "{} twice", e.name); + assert!(e.name.contains('.') && e.name == e.name.to_ascii_lowercase()); + assert!(!e.description.is_empty() && !e.summary.is_empty()); + for field in e.fields { + assert!( + field.description.ends_with('.'), + "{}.{}", + e.name, + field.name + ); + } + } + assert!(find("run.completed").is_some()); + assert!(find("run.nope").is_none()); + assert!(!subscribable().any(|e| e.name == TEST_EVENT)); + } + + /// Every source file of the services and the log analyzer, without + /// their test modules, as (path, text). + fn sources() -> Vec<(String, String)> { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(".."); + let mut out = Vec::new(); + let mut stack = vec![ + root.join("common/src"), + root.join("gateway/src"), + root.join("worker/src"), + ]; + while let Some(dir) = stack.pop() { + for entry in std::fs::read_dir(&dir).unwrap().flatten() { + let p = entry.path(); + if p.is_dir() { + stack.push(p); + } else if p.extension().is_some_and(|e| e == "rs") { + let text = std::fs::read_to_string(&p).unwrap(); + // Code only: a test module's literals don't count. + let code = text + .split("#[cfg(test)]\nmod tests") + .next() + .unwrap() + .to_string(); + out.push((p.display().to_string(), code)); + } + } + } + let py = root.join("../lambda/log-analyzer/handler.py"); + out.push(( + py.display().to_string(), + std::fs::read_to_string(py).unwrap(), + )); + out + } + + /// The catalog lists only events something really sends: each type is + /// named at an emit in the code (the run events through + /// `worker::passes::webhooks::emit_run`, by the status written). + #[test] + fn every_event_type_has_an_emit_in_the_code() { + let src = sources(); + let named = |needle: &str| { + src.iter() + .filter(|(p, _)| !p.ends_with("webhooks/catalog.rs")) + .any(|(_, t)| t.contains(needle)) + }; + for e in subscribable() { + assert!( + named(&format!("\"{}\"", e.name)), + "{} is in the catalog but nothing emits it", + e.name + ); + } + for status in ["running", "completed", "failed", "needs_input"] { + assert!( + named(&format!( + "emit_run(state, &msg.team_id, run_id, \"{status}\")" + )), + "no run is emitted with status {status}" + ); + } + } + + /// The log analyzer builds events itself, in Python: same version, same + /// envelope. + #[test] + fn the_log_analyzer_sends_the_same_version_and_envelope() { + let py = sources().pop().unwrap().1; + assert!( + py.contains(&format!("WEBHOOK_API_VERSION = \"{API_VERSION}\"")), + "lambda/log-analyzer/handler.py WEBHOOK_API_VERSION must be {API_VERSION}" + ); + for key in [ + "\"id\":", + "\"type\":", + "\"created_at\":", + "\"team_id\":", + "\"api_version\":", + "\"data\":", + ] { + assert!(py.contains(key), "the analyzer's envelope has no {key}"); + } + let msg: crate::messages::WorkerMessage = serde_json::from_value(json!({ + "type": "webhook_emit", + "event": example_event("log_finding.created"), + })) + .unwrap(); + assert!(matches!( + msg, + crate::messages::WorkerMessage::WebhookEmit(_) + )); + } + + #[test] + fn subscriptions_name_real_types() { + assert!(unknown_types(&["*".into(), "run.failed".into()]).is_empty()); + assert_eq!( + unknown_types(&["run.exploded".into(), TEST_EVENT.into()]), + vec!["run.exploded".to_string(), TEST_EVENT.to_string()] + ); + } + + #[test] + fn a_nullable_field_allows_null_and_its_type() { + let s = data_schema(find("run.completed").unwrap()); + assert_eq!( + s["properties"]["pr_number"]["type"], + json!(["integer", "null"]) + ); + assert!(conforms(&s["properties"]["pr_number"], &Value::Null).is_ok()); + assert!(conforms(&s["properties"]["pr_number"], &json!("x")).is_err()); + assert!(conforms(&s["properties"]["status"], &json!("exploded")).is_err()); + } +} diff --git a/services/common/src/webhooks/deliver.rs b/services/common/src/webhooks/deliver.rs new file mode 100644 index 000000000..b30324958 --- /dev/null +++ b/services/common/src/webhooks/deliver.rs @@ -0,0 +1,857 @@ +//! Sending one event to one endpoint, and what happens after. +//! +//! - **Where:** the endpoint's host is resolved again before every send and +//! every address it answers with must be public (no private, local, +//! link-local or metadata address). The connection is pinned to the +//! address that was checked, so a name that changes its answer between +//! the check and the connection (DNS rebinding) can't reach inside a +//! network. Redirects are never followed. +//! - **How long:** [`TIMEOUT_SECS`] for the whole request. +//! - **Retries:** a timeout, a connection failure, `408`, `429` or any `5xx` +//! is tried again on [`BACKOFF`] (about a day in all). Any other answer +//! that isn't `2xx` is final: a `4xx` won't change by itself. +//! - **Failing endpoints:** an endpoint whose deliveries have failed for +//! [`DISABLE_AFTER_DAYS`] days with no success in between is turned off, +//! and the team's admins are told. +//! - **Record:** every attempt is kept on the delivery's record in +//! Deliveries ([`crate::deliveries`]), with the headers (signature +//! removed) and a preview of the body. + +use std::net::SocketAddr; +use std::time::{Duration, Instant}; + +use crate::deliveries::{self, Attempt, Delivery, Direction, Redeliver, Status}; + +use super::{endpoint, sign}; + +pub const SOURCE: &str = "webhook"; +pub const TIMEOUT_SECS: u64 = 10; +/// The most of an endpoint's answer CoderHelm reads (for the record only: +/// an answer is never acted on). The rest is never downloaded. +pub const MAX_RESPONSE_BYTES: usize = 4096; +pub const DISABLE_AFTER_DAYS: i64 = 5; +pub const USER_AGENT: &str = "CoderHelm-Webhooks/1.0 (+https://docs.coderhelm.com/api/webhooks/)"; +/// Seconds to wait after the Nth failed attempt (N from 1). Ten attempts in +/// all, over about 24.6 hours. +pub const BACKOFF: &[i64] = &[5, 60, 300, 1800, 3600, 10800, 21600, 21600, 28800]; + +/// When to try again after `attempts` failed tries, or None to stop. +pub fn next_retry_secs(attempts: usize) -> Option { + BACKOFF.get(attempts.saturating_sub(1)).copied() +} + +/// How an answer counts. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Class { + Delivered, + /// Try again later. + Retry, + /// Final: trying again won't help. + Refused, +} + +/// Classifies an attempt's HTTP status (None: no answer). +pub fn classify(code: Option) -> Class { + match code { + Some(c) if (200..300).contains(&c) => Class::Delivered, + None | Some(408) | Some(429) => Class::Retry, + Some(c) if c >= 500 => Class::Retry, + Some(_) => Class::Refused, + } +} + +/// The reason code for a failed attempt. +pub fn reason_code(code: Option, timed_out: bool, blocked: bool) -> &'static str { + match code { + _ if blocked => "webhook_blocked", + None if timed_out => "webhook_timeout", + None => "webhook_unreachable", + Some(429) => "webhook_rate_limited", + Some(c) if c >= 500 => "webhook_server_error", + Some(c) if (300..400).contains(&c) => "webhook_redirect", + Some(410) => "webhook_endpoint_gone", + Some(_) => "webhook_refused", + } +} + +/// What comes after an attempt. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Next { + Delivered, + RetryIn(i64), + Stop, +} + +/// What one attempt found, beyond its [`Attempt`]. +#[derive(Debug, Clone, Default)] +pub struct Sent { + pub attempt: Attempt, + pub timed_out: bool, + /// Refused before sending: the address isn't public. + pub blocked: bool, + /// The request's headers (the signature is removed when recorded). + pub headers: Vec<(String, String)>, +} + +/// Applies an attempt to its delivery record and decides what's next. +/// `retry` is false for a person's Resend and for test events: those are +/// tried once. +pub fn apply( + d: &mut Delivery, + sent: &Sent, + retry: bool, + now: chrono::DateTime, +) -> Next { + let code = sent.attempt.code; + d.push_attempt(sent.attempt.clone()); + let n = d.attempts.len(); + let class = if sent.blocked { + Class::Refused + } else { + classify(code) + }; + match class { + Class::Delivered => { + d.finish( + Status::Handled, + &format!("Delivered ({})", code.unwrap_or(200)), + "", + ); + d.next_retry_at = None; + Next::Delivered + } + Class::Retry if retry => match next_retry_secs(n) { + Some(secs) => { + d.finish( + Status::Pending, + "Retrying", + reason_code(code, sent.timed_out, false), + ); + d.next_retry_at = Some( + (now + chrono::Duration::seconds(secs)) + .to_rfc3339_opts(chrono::SecondsFormat::Secs, true), + ); + Next::RetryIn(secs) + } + None => { + d.finish( + Status::Failed, + "Gave up after about a day", + "webhook_gave_up", + ); + d.next_retry_at = None; + Next::Stop + } + }, + _ => { + let outcome = match code { + Some(c) => format!("Refused ({c})"), + None if sent.blocked => "Not sent".to_string(), + None => "No answer".to_string(), + }; + d.finish( + Status::Failed, + &outcome, + reason_code(code, sent.timed_out, sent.blocked), + ); + d.next_retry_at = None; + Next::Stop + } + } +} + +/// An endpoint failing since `failing_since` should be turned off now. +pub fn should_disable(failing_since: &str, now: chrono::DateTime) -> bool { + chrono::DateTime::parse_from_rfc3339(failing_since) + .map(|t| now.signed_duration_since(t) >= chrono::Duration::days(DISABLE_AFTER_DAYS)) + .unwrap_or(false) +} + +/// A new delivery record for an event to an endpoint. +pub fn new_record( + ep: &endpoint::Endpoint, + event_id: &str, + event_type: &str, + body: &[u8], +) -> Delivery { + let mut d = + Delivery::new(Direction::Outbound, SOURCE, event_type, &ep.host()).with_payload(body); + d.external_id = event_id.into(); + d.endpoint_id = ep.id.clone(); + d.status = Status::Pending; + d.redeliver = Some(Redeliver::Webhook); + d +} + +// ─── Sending ──────────────────────────────────────────────────────────────── + +/// Looks up a host's addresses. The system resolver in production; a fake in +/// tests (a name that answers differently each time). +#[async_trait::async_trait] +pub trait Resolve: Send + Sync { + async fn lookup(&self, host: &str, port: u16) -> Result, String>; +} + +pub struct SystemDns; + +#[async_trait::async_trait] +impl Resolve for SystemDns { + async fn lookup(&self, host: &str, port: u16) -> Result, String> { + tokio::net::lookup_host((host, port)) + .await + .map(|a| a.collect()) + .map_err(|e| e.to_string()) + } +} + +/// How requests are made. +pub struct Sender<'a> { + pub dns: &'a dyn Resolve, + pub timeout: Duration, + /// Tests only: allow `http://` and loopback, so a local server can answer. + #[cfg(test)] + pub local_for_tests: bool, +} + +impl<'a> Sender<'a> { + pub fn new(dns: &'a dyn Resolve) -> Self { + Self { + dns, + timeout: Duration::from_secs(TIMEOUT_SECS), + #[cfg(test)] + local_for_tests: false, + } + } +} + +/// One request to send. +pub struct Request<'a> { + pub url: &'a str, + pub event_id: &'a str, + pub body: &'a [u8], + /// The current secret first, then a rotated-out one while it still signs. + pub secrets: &'a [String], + pub timestamp: i64, +} + +fn now_text() -> String { + chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true) +} + +fn blocked(message: &str) -> Sent { + Sent { + attempt: Attempt { + at: now_text(), + code: None, + duration_ms: 0, + error: message.chars().take(300).collect(), + }, + blocked: true, + ..Default::default() + } +} + +/// The address to connect to: every answer must be public, and the first is +/// used. Pure, for the tests. +pub fn pick_address(addrs: &[SocketAddr]) -> Result { + if addrs.is_empty() { + return Err("The address's name doesn't point anywhere.".into()); + } + if addrs + .iter() + .any(|a| !crate::live::net::is_public_ip(a.ip())) + { + return Err( + "The address's name points inside a private network (or to a local or metadata address), so nothing was sent." + .into(), + ); + } + Ok(addrs[0]) +} + +/// Checks, when an endpoint is saved, that its name resolves only to public +/// addresses (it is checked again before every send). +pub async fn check_address(dns: &dyn Resolve, url: &str) -> Result<(), String> { + let ep = crate::live::net::parse_endpoint(url).map_err(|e| e.message)?; + if ep.host.parse::().is_ok() { + return Ok(()); + } + let addrs = dns.lookup(&ep.host, ep.port).await.map_err(|_| { + format!( + "We couldn't find {} on the internet. Check the address.", + ep.host + ) + })?; + pick_address(&addrs).map(|_| ()) +} + +/// Signs and sends one request. Never errors: every outcome is an attempt. +pub async fn send(sender: &Sender<'_>, req: &Request<'_>) -> Sent { + #[cfg(test)] + let local = sender.local_for_tests; + #[cfg(not(test))] + let local = false; + + let (url, host, port) = if local { + let Ok(u) = reqwest::Url::parse(req.url) else { + return blocked("Not a web address."); + }; + let host = u.host_str().unwrap_or("").to_string(); + let port = u.port_or_known_default().unwrap_or(80); + (u, host, port) + } else { + match crate::live::net::parse_endpoint(req.url) { + Ok(ep) => (ep.url, ep.host, ep.port), + Err(e) => return blocked(&e.message), + } + }; + let addr = if local { + match sender.dns.lookup(&host, port).await { + Ok(a) if !a.is_empty() => a[0], + _ => return blocked("The address's name doesn't point anywhere."), + } + } else { + let looked = match host.parse::() { + Ok(ip) => Ok(vec![SocketAddr::new(ip, port)]), + Err(_) => sender.dns.lookup(&host, port).await, + }; + match looked { + Ok(addrs) => match pick_address(&addrs) { + Ok(a) => a, + Err(e) => return blocked(&e), + }, + Err(_) => { + return Sent { + attempt: Attempt { + at: now_text(), + code: None, + duration_ms: 0, + error: format!("Couldn't find {host} (DNS)."), + }, + ..Default::default() + } + } + } + }; + + let refs: Vec<&str> = req.secrets.iter().map(String::as_str).collect(); + let signature = match sign::header(&refs, req.event_id, req.timestamp, req.body) { + Ok(s) => s, + Err(e) => return blocked(&format!("Couldn't sign: {e}")), + }; + let headers = vec![ + ("content-type".to_string(), "application/json".to_string()), + ("user-agent".to_string(), USER_AGENT.to_string()), + (sign::ID_HEADER.to_string(), req.event_id.to_string()), + ( + sign::TIMESTAMP_HEADER.to_string(), + req.timestamp.to_string(), + ), + (sign::SIGNATURE_HEADER.to_string(), signature), + ]; + + let client = match reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .timeout(sender.timeout) + .connect_timeout(sender.timeout.min(Duration::from_secs(5))) + .resolve(&host, addr) + .no_proxy() + .build() + { + Ok(c) => c, + Err(e) => return blocked(&format!("Couldn't prepare the request: {e}")), + }; + let mut rb = client.post(url).body(req.body.to_vec()); + for (k, v) in &headers { + rb = rb.header(k, v); + } + let started = Instant::now(); + let r = rb.send().await; + let duration_ms = started.elapsed().as_millis() as u64; + let at = now_text(); + match r { + Ok(resp) => { + let code = resp.status().as_u16(); + let error = if resp.status().is_success() { + String::new() + } else { + let text = read_capped(resp, MAX_RESPONSE_BYTES).await; + format!( + "Answered {code}: {}", + text.chars().take(200).collect::() + ) + .trim_end_matches(": ") + .to_string() + }; + Sent { + attempt: Attempt { + at, + code: Some(code), + duration_ms, + error, + }, + headers, + ..Default::default() + } + } + Err(e) => { + let timed_out = e.is_timeout(); + Sent { + attempt: Attempt { + at, + code: None, + duration_ms, + error: if timed_out { + format!("No answer within {} seconds.", sender.timeout.as_secs()) + } else { + "Couldn't connect.".into() + }, + }, + timed_out, + headers, + ..Default::default() + } + } + } +} + +/// Reads at most `max` bytes of an answer, then stops (the connection is +/// dropped with the rest unread). +async fn read_capped(mut resp: reqwest::Response, max: usize) -> String { + let mut buf: Vec = Vec::new(); + while buf.len() < max { + match resp.chunk().await { + Ok(Some(c)) => buf.extend_from_slice(&c[..c.len().min(max - buf.len())]), + _ => break, + } + } + String::from_utf8_lossy(&buf).into_owned() +} + +/// Keeps the request's headers on the record (the signature is removed). +pub fn record_headers(d: &mut Delivery, sent: &Sent) { + if !sent.headers.is_empty() { + d.headers = + deliveries::redact_headers(sent.headers.iter().map(|(k, v)| (k.as_str(), v.as_str()))); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Mutex; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + fn att(code: Option) -> Sent { + Sent { + attempt: Attempt { + at: "t".into(), + code, + duration_ms: 3, + error: String::new(), + }, + ..Default::default() + } + } + + fn record() -> Delivery { + let ep = endpoint::Endpoint { + id: "ep_1".into(), + url: "https://hooks.example.com/x".into(), + ..Default::default() + }; + new_record(&ep, "evt_1", "run.failed", b"{}") + } + + #[test] + fn answers_are_classified_like_the_spec_says() { + assert_eq!(classify(Some(200)), Class::Delivered); + assert_eq!(classify(Some(204)), Class::Delivered); + for c in [ + None, + Some(408), + Some(429), + Some(500), + Some(502), + Some(503), + Some(599), + ] { + assert_eq!(classify(c), Class::Retry, "{c:?}"); + } + for c in [ + Some(301), + Some(400), + Some(401), + Some(403), + Some(404), + Some(410), + Some(422), + ] { + assert_eq!(classify(c), Class::Refused, "{c:?}"); + } + } + + #[test] + fn retries_back_off_for_about_a_day_then_stop() { + let total: i64 = BACKOFF.iter().sum(); + assert!((22 * 3600..=26 * 3600).contains(&total), "{total}"); + assert!(BACKOFF.windows(2).all(|w| w[0] <= w[1]), "never shorter"); + let now = chrono::Utc::now(); + let mut d = record(); + assert_eq!(d.target, "hooks.example.com"); + assert_eq!(apply(&mut d, &att(Some(503)), true, now), Next::RetryIn(5)); + assert_eq!( + (d.status, d.reason.as_str()), + (Status::Pending, "webhook_server_error") + ); + assert!(d.next_retry_at.is_some()); + assert_eq!(apply(&mut d, &att(None), true, now), Next::RetryIn(60)); + assert_eq!(d.reason, "webhook_unreachable"); + assert_eq!( + apply(&mut d, &att(Some(429)), true, now), + Next::RetryIn(300) + ); + assert_eq!(d.reason, "webhook_rate_limited"); + let mut last = Next::Delivered; + for _ in 0..20 { + last = apply(&mut d, &att(Some(500)), true, now); + if last == Next::Stop { + break; + } + } + assert_eq!(last, Next::Stop); + assert_eq!(d.attempts.len(), BACKOFF.len() + 1); + assert_eq!( + (d.status, d.reason.as_str()), + (Status::Failed, "webhook_gave_up") + ); + } + + #[test] + fn a_4xx_stops_at_once_but_408_and_429_retry() { + let now = chrono::Utc::now(); + for (code, reason) in [ + (400, "webhook_refused"), + (404, "webhook_refused"), + (410, "webhook_endpoint_gone"), + (302, "webhook_redirect"), + ] { + let mut d = record(); + assert_eq!(apply(&mut d, &att(Some(code)), true, now), Next::Stop); + assert_eq!((d.status, d.reason.as_str()), (Status::Failed, reason)); + } + let mut d = record(); + assert!(matches!( + apply(&mut d, &att(Some(408)), true, now), + Next::RetryIn(_) + )); + let mut d = record(); + assert_eq!(apply(&mut d, &att(Some(200)), true, now), Next::Delivered); + assert_eq!(d.status, Status::Handled); + // A Resend or a test is tried once. + let mut d = record(); + assert_eq!(apply(&mut d, &att(Some(503)), false, now), Next::Stop); + assert_eq!(d.status, Status::Failed); + // A blocked address is final. + let mut d = record(); + let mut b = att(None); + b.blocked = true; + assert_eq!(apply(&mut d, &b, true, now), Next::Stop); + assert_eq!(d.reason, "webhook_blocked"); + let mut t = att(None); + t.timed_out = true; + let mut d = record(); + apply(&mut d, &t, true, now); + assert_eq!(d.reason, "webhook_timeout"); + } + + #[test] + fn an_endpoint_is_turned_off_after_days_of_failures() { + let now = chrono::DateTime::parse_from_rfc3339("2026-10-26T12:00:00Z") + .unwrap() + .with_timezone(&chrono::Utc); + assert!(!should_disable("2026-10-22T12:00:01Z", now)); + assert!(should_disable("2026-10-21T12:00:00Z", now)); + assert!(should_disable("2026-10-01T00:00:00Z", now)); + assert!(!should_disable("garbage", now)); + } + + #[test] + fn every_reason_reads_plainly() { + for c in [ + "webhook_blocked", + "webhook_timeout", + "webhook_unreachable", + "webhook_rate_limited", + "webhook_server_error", + "webhook_redirect", + "webhook_endpoint_gone", + "webhook_refused", + "webhook_gave_up", + "webhook_disabled", + ] { + assert_eq!(deliveries::reason(c).code, c); + } + } + + /// Answers each name with the next list of addresses (a name that + /// changes its answer, as in DNS rebinding). + struct Rebinding { + answers: Mutex>>, + calls: AtomicUsize, + } + + #[async_trait::async_trait] + impl Resolve for Rebinding { + async fn lookup(&self, _host: &str, _port: u16) -> Result, String> { + self.calls.fetch_add(1, Ordering::SeqCst); + let mut a = self.answers.lock().unwrap(); + if a.is_empty() { + return Err("NXDOMAIN".into()); + } + Ok(a.remove(0)) + } + } + + fn req<'a>(url: &'a str, secrets: &'a [String]) -> Request<'a> { + Request { + url, + event_id: "evt_1", + body: b"{}", + secrets, + timestamp: 1_800_000_000, + } + } + + #[tokio::test] + async fn private_addresses_are_refused_at_send_time_after_dns() { + let secrets = vec![sign::new_secret()]; + // The name was public when the endpoint was saved; now it answers + // with the metadata address. Nothing is sent. + let dns = Rebinding { + answers: Mutex::new(vec![ + vec!["169.254.169.254:443".parse().unwrap()], + vec![ + "93.184.216.34:443".parse().unwrap(), + "10.0.0.7:443".parse().unwrap(), + ], + vec!["[::1]:443".parse().unwrap()], + vec![], + ]), + calls: AtomicUsize::new(0), + }; + let s = Sender::new(&dns); + for _ in 0..3 { + let sent = send(&s, &req("https://hooks.example.com/in", &secrets)).await; + assert!(sent.blocked, "{:?}", sent.attempt); + assert!(sent.attempt.error.contains("private network")); + assert!(sent.headers.is_empty(), "nothing was sent"); + } + assert_eq!(dns.calls.load(Ordering::SeqCst), 3); + // Literal private addresses never reach DNS. + for url in [ + "https://127.0.0.1/x", + "https://[fe80::1]/x", + "https://169.254.169.254/latest", + "http://hooks.example.com/", + ] { + let sent = send(&s, &req(url, &secrets)).await; + assert!(sent.blocked, "{url}"); + } + assert_eq!(dns.calls.load(Ordering::SeqCst), 3); + // The same rule when an endpoint is saved. + let at_save = Rebinding { + answers: Mutex::new(vec![ + vec!["10.1.2.3:443".parse().unwrap()], + vec!["93.184.216.34:443".parse().unwrap()], + ]), + calls: AtomicUsize::new(0), + }; + assert!(check_address(&at_save, "https://hooks.example.com/") + .await + .unwrap_err() + .contains("private network")); + assert!(check_address(&at_save, "https://hooks.example.com/") + .await + .is_ok()); + assert!(check_address(&at_save, "https://hooks.example.com/") + .await + .unwrap_err() + .contains("couldn't find")); + assert_eq!( + pick_address(&["8.8.8.8:443".parse().unwrap()]).unwrap(), + "8.8.8.8:443".parse().unwrap() + ); + assert!(pick_address(&[]).is_err()); + // The IPv6 forms are refused the same way. + for v6 in [ + "[::1]:443", + "[fe80::1]:443", + "[fd12::1]:443", + "[::ffff:169.254.169.254]:443", + "[::ffff:10.0.0.1]:443", + "[64:ff9b::a9fe:a9fe]:443", + ] { + assert!(pick_address(&[v6.parse().unwrap()]).is_err(), "{v6}"); + } + assert!(pick_address(&["[2606:4700:4700::1111]:443".parse().unwrap()]).is_ok()); + } + + /// A one-request HTTP server on loopback that answers `status` after + /// `delay`, and hands back the raw request it got. + async fn serve_once(status: u16, delay: Duration) -> (u16, tokio::task::JoinHandle) { + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = l.local_addr().unwrap().port(); + let h = tokio::spawn(async move { + let (mut sock, _) = l.accept().await.unwrap(); + let mut buf = vec![0u8; 16384]; + let mut got = Vec::new(); + loop { + let n = sock.read(&mut buf).await.unwrap_or(0); + got.extend_from_slice(&buf[..n]); + let text = String::from_utf8_lossy(&got).to_string(); + if n == 0 || (text.contains("\r\n\r\n") && text.ends_with("{}")) { + break; + } + } + tokio::time::sleep(delay).await; + let resp = + format!("HTTP/1.1 {status} X\r\ncontent-length: 2\r\nconnection: close\r\n\r\nno"); + let _ = sock.write_all(resp.as_bytes()).await; + String::from_utf8_lossy(&got).to_string() + }); + (port, h) + } + + struct Loopback; + #[async_trait::async_trait] + impl Resolve for Loopback { + async fn lookup(&self, _h: &str, port: u16) -> Result, String> { + Ok(vec![SocketAddr::from(([127, 0, 0, 1], port))]) + } + } + + #[tokio::test] + async fn a_request_carries_standard_webhooks_headers_that_verify() { + let (port, server) = serve_once(204, Duration::ZERO).await; + let secrets = vec![sign::new_secret(), sign::new_secret()]; + let mut s = Sender::new(&Loopback); + s.local_for_tests = true; + let url = format!("http://receiver.test:{port}/hook"); + let sent = send(&s, &req(&url, &secrets)).await; + assert_eq!(sent.attempt.code, Some(204), "{:?}", sent.attempt); + let raw = server.await.unwrap().to_ascii_lowercase(); + let header = |name: &str| { + raw.lines() + .find_map(|l| l.strip_prefix(&format!("{name}: "))) + .unwrap_or("") + .trim() + .to_string() + }; + assert_eq!(header("webhook-id"), "evt_1"); + assert_eq!(header("webhook-timestamp"), "1800000000"); + assert!(header("user-agent").starts_with("coderhelm-webhooks/")); + // Read the signature from what was sent, with its case intact. + let sig = sent + .headers + .iter() + .find(|(k, _)| k == sign::SIGNATURE_HEADER) + .unwrap() + .1 + .clone(); + assert_eq!( + sig.split(' ').count(), + 2, + "both secrets sign during a rotation" + ); + for secret in &secrets { + assert!( + sign::verify(secret, "evt_1", "1800000000", &sig, b"{}", 1_800_000_000).is_ok() + ); + } + let mut d = record(); + record_headers(&mut d, &sent); + assert_eq!(d.headers["webhook-signature"], "[redacted]"); + assert_eq!(d.headers["webhook-id"], "evt_1"); + } + + #[tokio::test] + async fn a_slow_endpoint_times_out_and_is_retried() { + let (port, _server) = serve_once(200, Duration::from_secs(3)).await; + let secrets = vec![sign::new_secret()]; + let mut s = Sender::new(&Loopback); + s.local_for_tests = true; + s.timeout = Duration::from_millis(300); + let sent = send(&s, &req(&format!("http://receiver.test:{port}/"), &secrets)).await; + assert!(sent.timed_out && sent.attempt.code.is_none()); + let mut d = record(); + assert!(matches!( + apply(&mut d, &sent, true, chrono::Utc::now()), + Next::RetryIn(5) + )); + assert_eq!(d.reason, "webhook_timeout"); + } + + #[tokio::test] + async fn a_huge_answer_is_read_only_up_to_the_limit() { + // An endpoint that answers 500 with a body far over the limit and + // never ends it: the read stops at the limit instead of hanging or + // filling memory. + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = l.local_addr().unwrap().port(); + tokio::spawn(async move { + let (mut sock, _) = l.accept().await.unwrap(); + let mut buf = vec![0u8; 16384]; + let _ = sock.read(&mut buf).await; + let _ = sock + .write_all(b"HTTP/1.1 500 X\r\ncontent-length: 100000000\r\n\r\n") + .await; + let chunk = vec![b'x'; 65536]; + for _ in 0..1000 { + if sock.write_all(&chunk).await.is_err() { + break; + } + } + }); + let secrets = vec![sign::new_secret()]; + let mut s = Sender::new(&Loopback); + s.local_for_tests = true; + s.timeout = Duration::from_secs(5); + let sent = send(&s, &req(&format!("http://receiver.test:{port}/"), &secrets)).await; + assert_eq!(sent.attempt.code, Some(500)); + assert!(sent.attempt.error.len() < 300, "only a short note is kept"); + let body = read_capped_len_check().await; + assert!(body <= MAX_RESPONSE_BYTES); + } + + /// `read_capped` itself never returns more than its limit. + async fn read_capped_len_check() -> usize { + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = l.local_addr().unwrap().port(); + tokio::spawn(async move { + let (mut sock, _) = l.accept().await.unwrap(); + let mut buf = vec![0u8; 4096]; + let _ = sock.read(&mut buf).await; + let _ = sock + .write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 200000\r\n\r\n") + .await; + let _ = sock.write_all(&vec![b'y'; 200000]).await; + }); + let r = reqwest::get(format!("http://127.0.0.1:{port}/")) + .await + .unwrap(); + read_capped(r, MAX_RESPONSE_BYTES).await.len() + } + + #[tokio::test] + async fn a_server_error_is_recorded_with_its_code() { + let (port, _server) = serve_once(503, Duration::ZERO).await; + let secrets = vec![sign::new_secret()]; + let mut s = Sender::new(&Loopback); + s.local_for_tests = true; + let sent = send(&s, &req(&format!("http://receiver.test:{port}/"), &secrets)).await; + assert_eq!(sent.attempt.code, Some(503)); + assert!(sent.attempt.error.starts_with("Answered 503")); + } +} diff --git a/services/common/src/webhooks/endpoint.rs b/services/common/src/webhooks/endpoint.rs new file mode 100644 index 000000000..1ed0b7508 --- /dev/null +++ b/services/common/src/webhooks/endpoint.rs @@ -0,0 +1,793 @@ +//! Webhook endpoints: where a team's events go, which events, and the +//! signing secrets. +//! +//! One item per endpoint on the settings table: `pk` is the team, `sk` is +//! `WEBHOOK_ENDPOINT#`. The signing secret is sealed with KMS, bound to +//! the team, the endpoint and its purpose (an item copied anywhere else will +//! not open), and only its last four characters are kept in the clear. A +//! rotated-out secret is kept, sealed the same way, until its overlap ends; +//! both sign until then. +//! +//! Health is kept on the item with conditional updates, so two deliveries +//! finishing at once never undo each other: `failing_since` is set by the +//! first failure after a success and removed by the next success. + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::{AttributeValue, ReturnValue}; +use base64::{engine::general_purpose::STANDARD, Engine}; +use serde::{Deserialize, Serialize}; + +use super::{catalog, sign}; +use crate::mcp_credentials::Cipher; + +pub const SK_PREFIX: &str = "WEBHOOK_ENDPOINT#"; +pub const ID_PREFIX: &str = "ep_"; +/// Endpoints one team may have. +pub const MAX_PER_TEAM: usize = 20; +pub const MAX_DESCRIPTION: usize = 200; +/// The default and longest overlap when a secret is rotated. +pub const DEFAULT_OVERLAP_HOURS: i64 = 24; +pub const MAX_OVERLAP_HOURS: i64 = 7 * 24; + +type Item = HashMap; + +/// Why an endpoint is off. +pub const DISABLED_MANUAL: &str = "manual"; +pub const DISABLED_FAILING: &str = "failing"; + +/// An endpoint as the API shows it (no secrets). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct Endpoint { + pub id: String, + pub url: String, + pub description: String, + /// Event types it receives; `["*"]` is every event. + pub events: Vec, + pub enabled: bool, + /// Why it's off: `manual` (a person) or `failing` (turned off after + /// failing for days). Empty while on. + #[serde(default)] + pub disabled_reason: String, + pub secret_hint: String, + /// While a rotated-out secret still signs too. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub previous_secret_expires_at: Option, + /// The first failure since the last success. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub failing_since: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_success_at: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_failure_at: Option, + pub created_at: String, + #[serde(default)] + pub created_by: String, + pub updated_at: String, +} + +impl Endpoint { + /// Receives this event type (on, and subscribed to it or to everything). + pub fn wants(&self, event_type: &str) -> bool { + self.enabled + && event_type != catalog::TEST_EVENT + && self.events.iter().any(|e| e == "*" || e == event_type) + } + + pub fn host(&self) -> String { + crate::public_urls::host_of(&self.url).to_string() + } +} + +/// An endpoint with its sealed secrets, as stored. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Stored { + pub endpoint: Endpoint, + pub secret_sealed: String, + pub previous_secret_sealed: String, +} + +/// The encryption context of an endpoint's secrets. +pub fn context(team_id: &str, endpoint_id: &str) -> HashMap { + HashMap::from([ + ("team".to_string(), team_id.to_string()), + ("purpose".to_string(), "webhook-signing-secret".to_string()), + ("endpoint".to_string(), endpoint_id.to_string()), + ]) +} + +pub async fn seal( + cipher: &dyn Cipher, + team_id: &str, + endpoint_id: &str, + secret: &str, +) -> Result { + let blob = cipher + .encrypt(context(team_id, endpoint_id), secret.as_bytes()) + .await?; + Ok(STANDARD.encode(blob)) +} + +pub async fn open( + cipher: &dyn Cipher, + team_id: &str, + endpoint_id: &str, + sealed: &str, +) -> Result { + let bytes = STANDARD + .decode(sealed) + .map_err(|_| "the stored signing secret is not valid".to_string())?; + let plain = cipher + .decrypt(context(team_id, endpoint_id), &bytes) + .await?; + String::from_utf8(plain).map_err(|_| "the stored signing secret is not text".to_string()) +} + +/// The secrets that sign a request now: the current one, and the previous +/// one while its overlap lasts. +pub async fn signing_secrets( + cipher: &dyn Cipher, + team_id: &str, + s: &Stored, + now: chrono::DateTime, +) -> Result, String> { + let id = &s.endpoint.id; + let mut out = vec![open(cipher, team_id, id, &s.secret_sealed).await?]; + if previous_live(s, now) { + match open(cipher, team_id, id, &s.previous_secret_sealed).await { + Ok(prev) => out.push(prev), + Err(e) => { + tracing::warn!(endpoint = %id, error = %e, "Could not open the previous signing secret") + } + } + } + Ok(out) +} + +/// The rotated-out secret still signs. +pub fn previous_live(s: &Stored, now: chrono::DateTime) -> bool { + !s.previous_secret_sealed.is_empty() + && s.endpoint + .previous_secret_expires_at + .as_deref() + .and_then(|t| chrono::DateTime::parse_from_rfc3339(t).ok()) + .is_some_and(|t| t > now) +} + +/// What a person may set on an endpoint. +#[derive(Debug, Clone, Default, Deserialize)] +pub struct Input { + #[serde(default)] + pub url: Option, + #[serde(default)] + pub description: Option, + #[serde(default)] + pub events: Option>, + #[serde(default)] + pub enabled: Option, +} + +/// A refused input, with the field and the words. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Invalid { + pub field: &'static str, + pub message: String, +} + +fn invalid(field: &'static str, message: impl Into) -> Invalid { + Invalid { + field, + message: message.into(), + } +} + +/// Checks a URL: https, no username or password, and not a private, local +/// or metadata address when written as one. The name is resolved and checked +/// again before every send ([`super::deliver`]). +pub fn check_url(raw: &str) -> Result { + let ep = crate::live::net::parse_endpoint(raw).map_err(|e| invalid("url", e.message))?; + Ok(ep.url.to_string()) +} + +/// Checks and normalizes a subscription list: known types, `*` alone. +pub fn check_events(events: &[String]) -> Result, Invalid> { + let mut list: Vec = events + .iter() + .map(|e| e.trim().to_string()) + .filter(|e| !e.is_empty()) + .collect(); + list.sort(); + list.dedup(); + if list.is_empty() { + return Err(invalid("events", "Pick at least one event, or all events.")); + } + let unknown = catalog::unknown_types(&list); + if !unknown.is_empty() { + return Err(invalid( + "events", + format!("Not an event type: {}.", unknown.join(", ")), + )); + } + if list.iter().any(|e| e == "*") { + return Ok(vec!["*".into()]); + } + Ok(list) +} + +fn check_description(d: &str) -> Result { + let d = d.trim(); + if d.chars().count() > MAX_DESCRIPTION { + return Err(invalid( + "description", + format!("Keep the description under {MAX_DESCRIPTION} characters."), + )); + } + Ok(d.to_string()) +} + +/// A new endpoint from a create request (without its secret yet). +pub fn new_endpoint(input: &Input, by: &str, now: &str) -> Result { + let url = check_url(input.url.as_deref().unwrap_or(""))?; + let events = check_events(input.events.as_deref().unwrap_or(&["*".to_string()]))?; + let description = check_description(input.description.as_deref().unwrap_or(""))?; + let enabled = input.enabled.unwrap_or(true); + Ok(Endpoint { + id: format!( + "{ID_PREFIX}{}", + ulid::Ulid::new().to_string().to_ascii_lowercase() + ), + url, + description, + events, + enabled, + disabled_reason: if enabled { + String::new() + } else { + DISABLED_MANUAL.into() + }, + created_at: now.into(), + created_by: by.into(), + updated_at: now.into(), + ..Default::default() + }) +} + +/// Applies an update request to an endpoint. Turning one back on clears its +/// failure record, so it gets a fresh N days. +pub fn apply_input(e: &mut Endpoint, input: &Input, now: &str) -> Result<(), Invalid> { + if let Some(u) = &input.url { + e.url = check_url(u)?; + } + if let Some(d) = &input.description { + e.description = check_description(d)?; + } + if let Some(ev) = &input.events { + e.events = check_events(ev)?; + } + if let Some(on) = input.enabled { + if on && !e.enabled { + e.failing_since = None; + } + e.enabled = on; + e.disabled_reason = if on { + String::new() + } else { + DISABLED_MANUAL.into() + }; + } + e.updated_at = now.into(); + Ok(()) +} + +// ─── Items ────────────────────────────────────────────────────────────────── + +fn s(v: &str) -> AttributeValue { + AttributeValue::S(v.to_string()) +} + +fn get_s(item: &Item, k: &str) -> String { + item.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() +} + +fn get_opt(item: &Item, k: &str) -> Option { + Some(get_s(item, k)).filter(|v| !v.is_empty()) +} + +pub fn sk(id: &str) -> String { + format!("{SK_PREFIX}{id}") +} + +/// The item for a stored endpoint. +pub fn to_item(team_id: &str, st: &Stored) -> Item { + let e = &st.endpoint; + let mut item = HashMap::from([ + ("pk".to_string(), s(team_id)), + ("sk".to_string(), s(&sk(&e.id))), + ("id".to_string(), s(&e.id)), + ("url".to_string(), s(&e.url)), + ("description".to_string(), s(&e.description)), + ( + "events".to_string(), + AttributeValue::L(e.events.iter().map(|x| s(x)).collect()), + ), + ("enabled".to_string(), AttributeValue::Bool(e.enabled)), + ("disabled_reason".to_string(), s(&e.disabled_reason)), + ("secret_sealed".to_string(), s(&st.secret_sealed)), + ("secret_hint".to_string(), s(&e.secret_hint)), + ("created_at".to_string(), s(&e.created_at)), + ("created_by".to_string(), s(&e.created_by)), + ("updated_at".to_string(), s(&e.updated_at)), + ]); + let mut opt = |k: &str, v: &Option| { + if let Some(v) = v.as_deref().filter(|v| !v.is_empty()) { + item.insert(k.to_string(), s(v)); + } + }; + opt("prev_secret_expires_at", &e.previous_secret_expires_at); + opt("failing_since", &e.failing_since); + opt("last_success_at", &e.last_success_at); + opt("last_failure_at", &e.last_failure_at); + if !st.previous_secret_sealed.is_empty() { + item.insert("prev_secret_sealed".into(), s(&st.previous_secret_sealed)); + } + item +} + +/// A stored endpoint from its item. +pub fn from_item(item: &Item) -> Option { + let id = get_s(item, "id"); + if id.is_empty() || !get_s(item, "sk").starts_with(SK_PREFIX) { + return None; + } + let events = item + .get("events") + .and_then(|v| v.as_l().ok()) + .map(|l| l.iter().filter_map(|x| x.as_s().ok().cloned()).collect()) + .unwrap_or_default(); + Some(Stored { + endpoint: Endpoint { + id, + url: get_s(item, "url"), + description: get_s(item, "description"), + events, + enabled: item + .get("enabled") + .and_then(|v| v.as_bool().ok()) + .copied() + .unwrap_or(false), + disabled_reason: get_s(item, "disabled_reason"), + secret_hint: get_s(item, "secret_hint"), + previous_secret_expires_at: get_opt(item, "prev_secret_expires_at"), + failing_since: get_opt(item, "failing_since"), + last_success_at: get_opt(item, "last_success_at"), + last_failure_at: get_opt(item, "last_failure_at"), + created_at: get_s(item, "created_at"), + created_by: get_s(item, "created_by"), + updated_at: get_s(item, "updated_at"), + }, + secret_sealed: get_s(item, "secret_sealed"), + previous_secret_sealed: get_s(item, "prev_secret_sealed"), + }) +} + +// ─── Storage ──────────────────────────────────────────────────────────────── + +fn err(e: E) -> String { + format!("{e:?}").chars().take(300).collect() +} + +/// Every endpoint of a team. +pub async fn list( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, +) -> Result, String> { + let r = dynamo + .query() + .table_name(table) + .key_condition_expression("pk = :pk AND begins_with(sk, :p)") + .expression_attribute_values(":pk", s(team_id)) + .expression_attribute_values(":p", s(SK_PREFIX)) + .send() + .await + .map_err(err)?; + let mut out: Vec = r.items().iter().filter_map(from_item).collect(); + out.sort_by(|a, b| a.endpoint.created_at.cmp(&b.endpoint.created_at)); + Ok(out) +} + +pub async fn get( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, + id: &str, +) -> Result, String> { + let r = dynamo + .get_item() + .table_name(table) + .key("pk", s(team_id)) + .key("sk", s(&sk(id))) + .consistent_read(true) + .send() + .await + .map_err(err)?; + Ok(r.item().and_then(from_item)) +} + +/// Writes a whole endpoint (create and person-made changes). +pub async fn put( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, + st: &Stored, +) -> Result<(), String> { + dynamo + .put_item() + .table_name(table) + .set_item(Some(to_item(team_id, st))) + .send() + .await + .map(|_| ()) + .map_err(err) +} + +pub async fn delete( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, + id: &str, +) -> Result<(), String> { + dynamo + .delete_item() + .table_name(table) + .key("pk", s(team_id)) + .key("sk", s(&sk(id))) + .send() + .await + .map(|_| ()) + .map_err(err) +} + +/// Notes a delivered attempt: the failure record ends. +pub async fn note_success( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, + id: &str, + at: &str, +) { + let r = dynamo + .update_item() + .table_name(table) + .key("pk", s(team_id)) + .key("sk", s(&sk(id))) + .update_expression("SET last_success_at = :t REMOVE failing_since") + .condition_expression("attribute_exists(sk)") + .expression_attribute_values(":t", s(at)) + .send() + .await; + if let Err(e) = r { + tracing::debug!(endpoint = id, error = %err(e), "Could not note a webhook success"); + } +} + +/// Notes a failed attempt; returns when the failures began (this attempt, +/// when it is the first since a success). `None` when the endpoint is gone. +pub async fn note_failure( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, + id: &str, + at: &str, +) -> Option { + let r = dynamo + .update_item() + .table_name(table) + .key("pk", s(team_id)) + .key("sk", s(&sk(id))) + .update_expression( + "SET last_failure_at = :t, failing_since = if_not_exists(failing_since, :t)", + ) + .condition_expression("attribute_exists(sk)") + .expression_attribute_values(":t", s(at)) + .return_values(ReturnValue::AllNew) + .send() + .await + .ok()?; + r.attributes() + .and_then(|a| a.get("failing_since")) + .and_then(|v| v.as_s().ok()) + .cloned() +} + +/// Turns an endpoint off because it kept failing. True only for the call +/// that turned it off (so admins are told once). +pub async fn disable_failing( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, + id: &str, + at: &str, +) -> bool { + dynamo + .update_item() + .table_name(table) + .key("pk", s(team_id)) + .key("sk", s(&sk(id))) + .update_expression("SET enabled = :off, disabled_reason = :r, updated_at = :t") + .condition_expression("attribute_exists(sk) AND enabled = :on") + .expression_attribute_values(":off", AttributeValue::Bool(false)) + .expression_attribute_values(":on", AttributeValue::Bool(true)) + .expression_attribute_values(":r", s(DISABLED_FAILING)) + .expression_attribute_values(":t", s(at)) + .send() + .await + .is_ok() +} + +/// A new secret for an endpoint: sealed, with its hint. Returned in the clear +/// once, for the person who made it. +pub async fn fresh_secret( + cipher: &dyn Cipher, + team_id: &str, + endpoint_id: &str, +) -> Result<(String, String), String> { + let secret = sign::new_secret(); + let sealed = seal(cipher, team_id, endpoint_id, &secret).await?; + Ok((secret, sealed)) +} + +/// Rotates the secret in `st`: the current one becomes the previous one, +/// signing beside the new one for `overlap_hours`. +pub fn rotate( + st: &mut Stored, + new_secret: &str, + new_sealed: String, + overlap_hours: i64, + now: chrono::DateTime, +) { + let hours = overlap_hours.clamp(0, MAX_OVERLAP_HOURS); + if hours > 0 { + st.previous_secret_sealed = std::mem::take(&mut st.secret_sealed); + st.endpoint.previous_secret_expires_at = Some( + (now + chrono::Duration::hours(hours)) + .to_rfc3339_opts(chrono::SecondsFormat::Secs, true), + ); + } else { + st.previous_secret_sealed.clear(); + st.endpoint.previous_secret_expires_at = None; + } + st.secret_sealed = new_sealed; + st.endpoint.secret_hint = sign::hint(new_secret); + st.endpoint.updated_at = now.to_rfc3339_opts(chrono::SecondsFormat::Secs, true); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Reversible "encryption" that refuses a different context. + pub(crate) struct Fake; + #[async_trait::async_trait] + impl Cipher for Fake { + async fn encrypt(&self, c: HashMap, p: &[u8]) -> Result, String> { + let mut out = format!("{}|{}|", c["team"], c["endpoint"]).into_bytes(); + out.extend(p.iter().map(|b| b ^ 0x5a)); + Ok(out) + } + async fn decrypt(&self, c: HashMap, b: &[u8]) -> Result, String> { + let head = format!("{}|{}|", c["team"], c["endpoint"]).into_bytes(); + if !b.starts_with(&head) { + return Err("InvalidCiphertextException".into()); + } + Ok(b[head.len()..].iter().map(|x| x ^ 0x5a).collect()) + } + } + + fn input(url: &str, events: &[&str]) -> Input { + Input { + url: Some(url.into()), + description: Some(" Deploy bot ".into()), + events: Some(events.iter().map(|e| e.to_string()).collect()), + enabled: None, + } + } + + #[test] + fn endpoints_need_https_public_addresses_and_real_events() { + let e = new_endpoint( + &input( + "https://hooks.example.com/coderhelm", + &["run.failed", "run.completed", "run.failed"], + ), + "a@example.com", + "t", + ) + .unwrap(); + assert!(e.id.starts_with("ep_")); + assert_eq!(e.events, vec!["run.completed", "run.failed"]); + assert_eq!(e.description, "Deploy bot"); + assert!(e.enabled && e.disabled_reason.is_empty()); + for bad in [ + "http://hooks.example.com/x", + "https://localhost/x", + "https://127.0.0.1/x", + "https://10.0.0.8/x", + "https://169.254.169.254/latest/meta-data/", + "https://[fd00::1]/x", + "https://[::ffff:169.254.169.254]/", + "https://user:pw@hooks.example.com/", + "not a url", + ] { + let r = new_endpoint(&input(bad, &["*"]), "a", "t"); + assert_eq!(r.unwrap_err().field, "url", "{bad}"); + } + let all = new_endpoint( + &input("https://h.example.com", &["run.failed", "*"]), + "a", + "t", + ) + .unwrap(); + assert_eq!(all.events, vec!["*"]); + assert_eq!( + new_endpoint(&input("https://h.example.com", &["run.exploded"]), "a", "t") + .unwrap_err() + .field, + "events" + ); + assert_eq!( + new_endpoint(&input("https://h.example.com", &[]), "a", "t") + .unwrap_err() + .field, + "events" + ); + let mut long = input("https://h.example.com", &["*"]); + long.description = Some("x".repeat(MAX_DESCRIPTION + 1)); + assert_eq!( + new_endpoint(&long, "a", "t").unwrap_err().field, + "description" + ); + } + + #[test] + fn an_endpoint_wants_what_it_subscribed_to_while_on() { + let mut e = + new_endpoint(&input("https://h.example.com", &["run.failed"]), "a", "t").unwrap(); + assert!(e.wants("run.failed")); + assert!(!e.wants("run.completed")); + assert!( + !e.wants(catalog::TEST_EVENT), + "test events go only where sent" + ); + e.events = vec!["*".into()]; + assert!(e.wants("review.completed")); + e.enabled = false; + assert!(!e.wants("review.completed")); + } + + #[test] + fn turning_an_endpoint_back_on_starts_its_failure_count_again() { + let mut e = new_endpoint(&input("https://h.example.com", &["*"]), "a", "t").unwrap(); + e.enabled = false; + e.disabled_reason = DISABLED_FAILING.into(); + e.failing_since = Some("2026-10-01T00:00:00Z".into()); + apply_input( + &mut e, + &Input { + enabled: Some(true), + ..Default::default() + }, + "t2", + ) + .unwrap(); + assert!(e.enabled && e.disabled_reason.is_empty() && e.failing_since.is_none()); + apply_input( + &mut e, + &Input { + enabled: Some(false), + ..Default::default() + }, + "t3", + ) + .unwrap(); + assert_eq!(e.disabled_reason, DISABLED_MANUAL); + assert!(apply_input( + &mut e, + &Input { + url: Some("https://192.168.0.1/".into()), + ..Default::default() + }, + "t4" + ) + .is_err()); + } + + #[tokio::test] + async fn secrets_round_trip_sealed_to_their_team_and_endpoint() { + let (secret, sealed) = fresh_secret(&Fake, "TEAM#a", "ep_1").await.unwrap(); + assert!(!sealed.contains(&secret)); + assert_eq!( + open(&Fake, "TEAM#a", "ep_1", &sealed).await.unwrap(), + secret + ); + assert!(open(&Fake, "TEAM#b", "ep_1", &sealed).await.is_err()); + assert!(open(&Fake, "TEAM#a", "ep_2", &sealed).await.is_err()); + } + + #[tokio::test] + async fn a_rotated_secret_signs_beside_the_new_one_until_the_overlap_ends() { + let now = chrono::Utc::now(); + let (old, old_sealed) = fresh_secret(&Fake, "T", "ep_1").await.unwrap(); + let mut st = Stored { + endpoint: Endpoint { + id: "ep_1".into(), + ..Default::default() + }, + secret_sealed: old_sealed, + previous_secret_sealed: String::new(), + }; + assert_eq!( + signing_secrets(&Fake, "T", &st, now).await.unwrap(), + vec![old.clone()] + ); + let (new, new_sealed) = fresh_secret(&Fake, "T", "ep_1").await.unwrap(); + rotate(&mut st, &new, new_sealed, 24, now); + assert_eq!(st.endpoint.secret_hint, sign::hint(&new)); + assert_eq!( + signing_secrets(&Fake, "T", &st, now).await.unwrap(), + vec![new.clone(), old.clone()] + ); + let later = now + chrono::Duration::hours(25); + assert_eq!( + signing_secrets(&Fake, "T", &st, later).await.unwrap(), + vec![new.clone()] + ); + // No overlap: the old secret stops at once. + let (newer, newer_sealed) = fresh_secret(&Fake, "T", "ep_1").await.unwrap(); + rotate(&mut st, &newer, newer_sealed, 0, now); + assert_eq!( + signing_secrets(&Fake, "T", &st, now).await.unwrap(), + vec![newer] + ); + // The overlap is capped. + let (x, xs) = fresh_secret(&Fake, "T", "ep_1").await.unwrap(); + rotate(&mut st, &x, xs, 10_000, now); + let until = chrono::DateTime::parse_from_rfc3339( + st.endpoint.previous_secret_expires_at.as_deref().unwrap(), + ) + .unwrap(); + assert!( + until + <= now + chrono::Duration::hours(MAX_OVERLAP_HOURS) + chrono::Duration::seconds(1) + ); + } + + #[test] + fn an_endpoint_round_trips_through_its_item() { + let mut e = new_endpoint( + &input("https://h.example.com/x", &["run.failed"]), + "a@example.com", + "2026-10-26T00:00:00Z", + ) + .unwrap(); + e.secret_hint = "whsec_…abcd".into(); + e.failing_since = Some("2026-10-26T01:00:00Z".into()); + let st = Stored { + endpoint: e, + secret_sealed: "c2VhbGVk".into(), + previous_secret_sealed: "b2xk".into(), + }; + let item = to_item("TEAM#a", &st); + assert_eq!( + item["sk"].as_s().unwrap(), + &format!("WEBHOOK_ENDPOINT#{}", st.endpoint.id) + ); + assert_eq!(from_item(&item).unwrap(), st); + // The API view never carries a secret. + let view = serde_json::to_string(&st.endpoint).unwrap(); + assert!(!view.contains("c2VhbGVk") && !view.contains("b2xk")); + } +} diff --git a/services/common/src/webhooks/event.rs b/services/common/src/webhooks/event.rs new file mode 100644 index 000000000..f5b58fb3b --- /dev/null +++ b/services/common/src/webhooks/event.rs @@ -0,0 +1,441 @@ +//! Events: the envelope, [`emit_event`], and the kept copies that retries, +//! Resend and replay send again. +//! +//! [`emit_event`] only puts the event on the webhooks queue, so the work +//! that emits never waits on a team's endpoints. The worker then keeps the +//! event (only for teams with an endpoint), finds the endpoints that want it +//! and sends. +//! +//! A kept event is the exact body that was signed, so every retry and every +//! endpoint gets the same bytes. Kept copies expire with the delivery +//! records ([`crate::deliveries::RETENTION_DAYS`]). + +use std::collections::HashMap; +use std::time::Duration; + +use aws_sdk_dynamodb::types::AttributeValue; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use super::catalog; + +pub const SK_PREFIX: &str = "WEBHOOK_EVENT#"; +pub const ID_PREFIX: &str = "evt_"; + +/// One event, as it is sent. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Event { + pub id: String, + #[serde(rename = "type")] + pub event_type: String, + pub created_at: String, + pub team_id: String, + pub api_version: String, + pub data: Value, +} + +impl Event { + pub fn new(team_id: &str, event_type: &str, data: Value) -> Self { + Self { + id: format!("{ID_PREFIX}{}", ulid::Ulid::new()), + event_type: event_type.into(), + created_at: chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true), + team_id: team_id.into(), + api_version: catalog::API_VERSION.into(), + data: scrub(&data), + } + } + + /// The body every endpoint gets for this event. + pub fn body(&self) -> String { + serde_json::to_string(self).unwrap_or_default() + } +} + +/// The most of one text field an event carries. +pub const MAX_TEXT: usize = 2000; + +/// Prefixes of credentials that may turn up inside text (an error message +/// quoting a command line, a log line). +const SECRET_PREFIXES: &[&str] = &[ + "ghp_", + "ghs_", + "gho_", + "ghu_", + "ghr_", + "github_pat_", + "xoxb-", + "xoxp-", + "xoxa-", + "sk-ant-", + "sk-", + "AKIA", + "ASIA", + "chk_", + "whsec_", + "eyJ", +]; + +/// One text value with anything that looks like a credential replaced by +/// `[redacted]`: tokens by their prefix, the word after `Bearer`/`token`, +/// `user:password@` in addresses, `key=value` pairs whose key names a +/// secret, and whole private-key blocks. Long text is cut. +pub fn scrub_text(s: &str) -> String { + if s.contains("-----BEGIN") { + return "[redacted]".into(); + } + let mut out: Vec = Vec::new(); + let mut redact_next = false; + for word in s.split(' ') { + let bare = word.trim_matches(|c: char| !c.is_alphanumeric() && c != '_' && c != '-'); + let lower = bare.to_ascii_lowercase(); + let secretish_kv = word.split_once('=').is_some_and(|(k, _)| { + let k = k.to_ascii_lowercase(); + [ + "token", + "secret", + "password", + "passwd", + "api_key", + "apikey", + "authorization", + ] + .iter() + .any(|w| k.contains(w)) + }); + let creds_in_url = word.contains("://") + && word + .split("://") + .nth(1) + .is_some_and(|r| r.split('/').next().unwrap_or("").contains('@')); + let token = SECRET_PREFIXES + .iter() + .any(|p| bare.starts_with(p) && bare.len() >= p.len() + 8); + if redact_next || token || secretish_kv || creds_in_url { + out.push("[redacted]".into()); + } else { + out.push(word.to_string()); + } + redact_next = matches!(lower.as_str(), "bearer" | "token" | "authorization:"); + } + let joined = out.join(" "); + if joined.chars().count() > MAX_TEXT { + format!("{}…", joined.chars().take(MAX_TEXT).collect::()) + } else { + joined + } +} + +/// An event's `data` with every text scrubbed ([`scrub_text`]) and every +/// field whose name says it holds a secret masked +/// ([`crate::deliveries::redact_json`]). Events never carry credentials. +pub fn scrub(v: &Value) -> Value { + match crate::deliveries::redact_json(v) { + Value::String(s) => Value::String(scrub_text(&s)), + Value::Array(a) => Value::Array(a.iter().map(scrub).collect()), + Value::Object(m) => Value::Object(m.iter().map(|(k, v)| (k.clone(), scrub(v))).collect()), + other => other, + } +} + +/// The ULID inside an event id (sortable by time). +pub fn ulid_of(event_id: &str) -> &str { + event_id.strip_prefix(ID_PREFIX).unwrap_or(event_id) +} + +pub fn sk(event_id: &str) -> String { + format!("{SK_PREFIX}{}", ulid_of(event_id)) +} + +/// Puts an event on the webhooks queue. Never fails the caller: a failure +/// is logged. Returns the event id when it was queued. Does nothing when the +/// queue isn't configured (local runs, older installs). +pub async fn emit_event( + sqs: &aws_sdk_sqs::Client, + queue_url: &str, + team_id: &str, + event_type: &str, + data: Value, +) -> Option { + emit_event_keyed(sqs, queue_url, team_id, event_type, data, None).await +} + +/// [`emit_event`] with the event's ULID given, for an event whose source +/// can arrive twice (an SNS redelivery): the second copy has the same id, so +/// it is sent once. +pub async fn emit_event_keyed( + sqs: &aws_sdk_sqs::Client, + queue_url: &str, + team_id: &str, + event_type: &str, + data: Value, + ulid: Option<&str>, +) -> Option { + if queue_url.is_empty() || team_id.is_empty() { + return None; + } + debug_assert!( + catalog::find(event_type).is_some(), + "{event_type} is not in the event catalog" + ); + let mut event = Event::new(team_id, event_type, data); + if let Some(u) = ulid.and_then(|u| ulid::Ulid::from_string(u).ok()) { + event.id = format!("{ID_PREFIX}{u}"); + } + let body = serde_json::to_string(&crate::messages::WorkerMessage::WebhookEmit( + crate::messages::WebhookEmitMessage { + team_id: event.team_id.clone(), + event: event.clone(), + }, + )) + .ok()?; + let send = sqs + .send_message() + .queue_url(queue_url) + .message_body(body) + .send(); + match tokio::time::timeout(Duration::from_secs(3), send).await { + Ok(Ok(_)) => Some(event.id), + Ok(Err(e)) => { + tracing::warn!(event_type, team_id, error = %aws_sdk_sqs::error::DisplayErrorContext(&e), "Could not queue a webhook event"); + None + } + Err(_) => { + tracing::warn!(event_type, team_id, "Queueing a webhook event timed out"); + None + } + } +} + +/// The item for a kept event. +pub fn to_item(e: &Event, body: &str, now_epoch: i64) -> HashMap { + let s = |v: &str| AttributeValue::S(v.to_string()); + HashMap::from([ + ("pk".to_string(), s(&e.team_id)), + ("sk".to_string(), s(&sk(&e.id))), + ("event_type".to_string(), s(&e.event_type)), + ("created_at".to_string(), s(&e.created_at)), + ("body".to_string(), s(body)), + ( + "ttl".to_string(), + AttributeValue::N(crate::deliveries::ttl_from(now_epoch).to_string()), + ), + ]) +} + +/// A kept event: the parsed event and the exact body. +#[derive(Debug, Clone, PartialEq)] +pub struct Kept { + pub event: Event, + pub body: String, +} + +pub fn from_item(item: &HashMap) -> Option { + let body = item.get("body")?.as_s().ok()?.clone(); + let event = serde_json::from_str(&body).ok()?; + Some(Kept { event, body }) +} + +/// Keeps an event. False when it was already kept (a second copy of the +/// same queue message), so it is never sent twice by that. +pub async fn keep( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + e: &Event, + body: &str, +) -> Result { + let r = dynamo + .put_item() + .table_name(table) + .set_item(Some(to_item(e, body, chrono::Utc::now().timestamp()))) + .condition_expression("attribute_not_exists(sk)") + .send() + .await; + match r { + Ok(_) => Ok(true), + Err(e) + if e.as_service_error() + .is_some_and(|s| s.is_conditional_check_failed_exception()) => + { + Ok(false) + } + Err(e) => Err(aws_sdk_dynamodb::error::DisplayErrorContext(&e).to_string()), + } +} + +pub async fn get( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, + event_id: &str, +) -> Result, String> { + let r = dynamo + .get_item() + .table_name(table) + .key("pk", AttributeValue::S(team_id.into())) + .key("sk", AttributeValue::S(sk(event_id))) + .send() + .await + .map_err(|e| aws_sdk_dynamodb::error::DisplayErrorContext(&e).to_string())?; + Ok(r.item().and_then(from_item)) +} + +/// The `sk` bounds of the events made between two times (inclusive). +pub fn range_keys( + since: chrono::DateTime, + until: chrono::DateTime, +) -> (String, String) { + let ms = |t: chrono::DateTime| t.timestamp_millis().max(0) as u64; + let lo = ulid::Ulid::from_parts(ms(since), 0); + let hi = ulid::Ulid::from_parts(ms(until), u128::MAX); + (format!("{SK_PREFIX}{lo}"), format!("{SK_PREFIX}{hi}")) +} + +/// Kept events made between two times, oldest first, at most `limit`. +pub async fn list_range( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, + since: chrono::DateTime, + until: chrono::DateTime, + limit: usize, +) -> Result, String> { + let (lo, hi) = range_keys(since, until); + let mut out = Vec::new(); + let mut start = None; + loop { + let r = dynamo + .query() + .table_name(table) + .key_condition_expression("pk = :pk AND sk BETWEEN :lo AND :hi") + .expression_attribute_values(":pk", AttributeValue::S(team_id.into())) + .expression_attribute_values(":lo", AttributeValue::S(lo.clone())) + .expression_attribute_values(":hi", AttributeValue::S(hi.clone())) + .set_exclusive_start_key(start) + .send() + .await + .map_err(|e| aws_sdk_dynamodb::error::DisplayErrorContext(&e).to_string())?; + out.extend(r.items().iter().filter_map(from_item)); + start = r.last_evaluated_key().cloned(); + if start.is_none() || out.len() >= limit { + break; + } + } + out.truncate(limit); + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn an_event_has_the_documented_envelope() { + let e = Event::new("TEAM#a", "run.failed", json!({"run_id": "r1"})); + assert!(e.id.starts_with("evt_") && e.id.len() == 4 + 26); + assert_eq!(e.api_version, catalog::API_VERSION); + let v: Value = serde_json::from_str(&e.body()).unwrap(); + assert_eq!(v["type"], "run.failed"); + assert_eq!(v["team_id"], "TEAM#a"); + assert_eq!(v["data"]["run_id"], "r1"); + // The body lists the fields in the documented order. + let body = e.body(); + let at = |k: &str| body.find(&format!("\"{k}\":")).unwrap(); + let order = ["id", "type", "created_at", "team_id", "api_version", "data"].map(at); + assert!(order.windows(2).all(|w| w[0] < w[1]), "{body}"); + } + + #[test] + fn events_never_carry_credentials() { + let e = Event::new( + "TEAM#a", + "run.failed", + json!({ + "error": "git push failed: remote: Invalid token ghp_abcdefghijklmnopqrstuvwxyz0123 for https://bot:hunter2secret@github.com/o/r.git, Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.payload.sig and AWS key AKIAABCDEFGHIJKLMNOP; set API_KEY=sk-live-123 then retry", + "title": "Normal words stay", + "pem": "-----BEGIN RSA PRIVATE KEY-----\nMIIE...", + "token": "abc", + "nested": [{"secret": "x"}, "whsec_C2FVsBQIhrscChlQIMV"], + "long": "x".repeat(5000), + }), + ); + let body = e.body(); + for leak in [ + "ghp_abc", + "hunter2", + "eyJhbG", + "AKIAABCD", + "sk-live", + "MIIE", + "whsec_C2F", + "\"abc\"", + ] { + assert!(!body.contains(leak), "{leak} leaked: {body}"); + } + assert_eq!(e.data["title"], "Normal words stay"); + assert!(e.data["error"] + .as_str() + .unwrap() + .starts_with("git push failed: remote: Invalid token [redacted]")); + assert!(e.data["long"].as_str().unwrap().chars().count() <= MAX_TEXT + 1); + // Catalog examples pass through unchanged: real data isn't damaged. + for t in catalog::EVENTS { + let ex = catalog::example_data(t.name); + assert_eq!(scrub(&ex), ex, "{}", t.name); + } + } + + #[test] + fn a_kept_event_keeps_the_exact_body() { + let e = Event::new("TEAM#a", "run.created", json!({"b": 1, "a": 2})); + let body = e.body(); + let item = to_item(&e, &body, 1_800_000_000); + assert_eq!( + item["sk"].as_s().unwrap(), + &format!("WEBHOOK_EVENT#{}", ulid_of(&e.id)) + ); + let k = from_item(&item).unwrap(); + assert_eq!(k.body, body); + assert_eq!(k.event, e); + } + + #[test] + fn a_time_range_covers_exactly_the_events_made_in_it() { + let t = |s: &str| { + chrono::DateTime::parse_from_rfc3339(s) + .unwrap() + .with_timezone(&chrono::Utc) + }; + let (lo, hi) = range_keys(t("2026-10-26T10:00:00Z"), t("2026-10-26T11:00:00Z")); + let at = |s: &str| { + sk(&format!( + "evt_{}", + ulid::Ulid::from_parts(t(s).timestamp_millis() as u64, 12345) + )) + }; + let inside = at("2026-10-26T10:30:00Z"); + assert!(lo <= inside && inside <= hi); + let edge = at("2026-10-26T11:00:00Z"); + assert!(edge <= hi); + assert!(at("2026-10-26T09:59:59Z") < lo); + assert!(at("2026-10-26T11:00:01Z") > hi); + } + + #[tokio::test] + async fn without_a_queue_nothing_is_emitted() { + let conf = aws_sdk_sqs::Config::builder() + .behavior_version(aws_sdk_sqs::config::BehaviorVersion::latest()) + .region(aws_sdk_sqs::config::Region::new("us-east-1")) + .build(); + let sqs = aws_sdk_sqs::Client::from_conf(conf); + assert_eq!( + emit_event(&sqs, "", "TEAM#a", "run.failed", json!({})).await, + None + ); + assert_eq!( + emit_event(&sqs, "https://q", "", "run.failed", json!({})).await, + None + ); + } +} diff --git a/services/common/src/webhooks/mod.rs b/services/common/src/webhooks/mod.rs new file mode 100644 index 000000000..526897d72 --- /dev/null +++ b/services/common/src/webhooks/mod.rs @@ -0,0 +1,408 @@ +//! Outbound webhooks: CoderHelm tells a team's own systems what it did. +//! +//! - [`catalog`]: the event types and the shape of each one's `data`. +//! - [`event`]: the envelope and [`emit_event`], which every code path that +//! does something calls. It only queues the event. +//! - [`endpoint`]: where events go (an admin adds them in Settings, Webhooks +//! or through the API), with sealed signing secrets. +//! - [`sign`]: Standard Webhooks signatures. +//! - [`deliver`]: one signed request, the address checks, retries and the +//! failing-endpoint rule. +//! +//! Every attempt is recorded in Deliveries (`crate::deliveries`, source +//! `webhook`), so the Deliveries page and an endpoint's own list read the +//! same records. +//! +//! The worker takes events off the webhooks queue ([`dispatch`]), keeps +//! them for replay, and sends each to the endpoints that want it. A failed +//! attempt queues the next one ([`crate::messages::WebhookSendMessage`]). + +pub mod catalog; +pub mod deliver; +pub mod endpoint; +pub mod event; +pub mod sign; + +pub use event::{emit_event, emit_event_keyed, Event}; + +use crate::deliveries::{self, Delivery, Status}; +use crate::mcp_credentials::Cipher; +use deliver::Next; + +/// What sending needs: the settings table, KMS for the secrets, the queue +/// retries go on, and DNS. +pub struct Ctx<'a> { + pub dynamo: &'a aws_sdk_dynamodb::Client, + pub table: &'a str, + pub cipher: &'a dyn Cipher, + pub sqs: &'a aws_sdk_sqs::Client, + pub queue_url: &'a str, + pub dns: &'a dyn deliver::Resolve, +} + +/// Who asked for an attempt. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Mode { + /// An event as it happened, and its retries: failures retry, count + /// toward turning the endpoint off. + Automatic, + /// A person's Resend or test: tried once; a success still clears the + /// endpoint's failure record. + Manual, +} + +/// The end of one attempt. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Outcome { + pub next: Next, + /// This attempt turned the endpoint off (tell the admins once). + pub disabled_now: bool, +} + +fn now_text(now: chrono::DateTime) -> String { + now.to_rfc3339_opts(chrono::SecondsFormat::Millis, true) +} + +/// Sends `body` (the event `event_id`) to one endpoint once, records the +/// attempt on `d`, keeps the endpoint's health, and queues the next try. +pub async fn attempt( + ctx: &Ctx<'_>, + team_id: &str, + st: &endpoint::Stored, + event_id: &str, + body: &str, + d: &mut Delivery, + mode: Mode, +) -> Outcome { + let now = chrono::Utc::now(); + let ep = &st.endpoint; + let stop = Outcome { + next: Next::Stop, + disabled_now: false, + }; + if mode == Mode::Automatic && !ep.enabled { + d.finish(Status::Failed, "Endpoint is off", "webhook_disabled"); + d.next_retry_at = None; + deliveries::record(ctx.dynamo, ctx.table, team_id, d).await; + return stop; + } + let secrets = match endpoint::signing_secrets(ctx.cipher, team_id, st, now).await { + Ok(s) => s, + Err(e) => { + tracing::warn!(endpoint = %ep.id, error = %e, "Could not open a webhook signing secret"); + d.push_attempt(deliveries::Attempt { + at: now_text(now), + code: None, + duration_ms: 0, + error: "The signing secret couldn't be read, so nothing was sent.".into(), + }); + d.finish(Status::Failed, "Not sent", "handler_error"); + deliveries::record(ctx.dynamo, ctx.table, team_id, d).await; + return stop; + } + }; + let sender = deliver::Sender::new(ctx.dns); + let sent = deliver::send( + &sender, + &deliver::Request { + url: &ep.url, + event_id, + body: body.as_bytes(), + secrets: &secrets, + timestamp: now.timestamp(), + }, + ) + .await; + deliver::record_headers(d, &sent); + let next = deliver::apply(d, &sent, mode == Mode::Automatic, now); + let at = now_text(now); + let mut disabled_now = false; + match next { + Next::Delivered => { + endpoint::note_success(ctx.dynamo, ctx.table, team_id, &ep.id, &at).await; + } + _ if mode == Mode::Automatic => { + if let Some(since) = + endpoint::note_failure(ctx.dynamo, ctx.table, team_id, &ep.id, &at).await + { + if deliver::should_disable(&since, now) { + disabled_now = + endpoint::disable_failing(ctx.dynamo, ctx.table, team_id, &ep.id, &at) + .await; + } + } + } + _ => {} + } + let next = match next { + Next::RetryIn(_) if disabled_now => { + d.finish(Status::Failed, "Endpoint turned off", "webhook_disabled"); + d.next_retry_at = None; + Next::Stop + } + n => n, + }; + deliveries::record(ctx.dynamo, ctx.table, team_id, d).await; + if let Next::RetryIn(secs) = next { + let msg = crate::messages::WebhookSendMessage { + team_id: team_id.into(), + endpoint_id: ep.id.clone(), + event_id: event_id.into(), + delivery_id: d.id.clone(), + due_at: now.timestamp() + secs, + }; + if let Err(e) = schedule(ctx, &msg, secs).await { + tracing::warn!(delivery = %d.id, error = %e, "Could not queue a webhook retry"); + } + } + Outcome { next, disabled_now } +} + +/// Queues a send, delayed by `secs` (SQS delays at most 15 minutes; a later +/// one is carried by `due_at` and queued again until it's due). +pub async fn schedule( + ctx: &Ctx<'_>, + msg: &crate::messages::WebhookSendMessage, + secs: i64, +) -> Result<(), String> { + let body = serde_json::to_string(&crate::messages::WorkerMessage::WebhookSend(msg.clone())) + .map_err(|e| e.to_string())?; + ctx.sqs + .send_message() + .queue_url(ctx.queue_url) + .message_body(body) + .delay_seconds(sqs_delay(secs)) + .send() + .await + .map(|_| ()) + .map_err(|e| aws_sdk_sqs::error::DisplayErrorContext(&e).to_string()) +} + +/// The SQS delay for a wait: 0 to 900 seconds. +pub fn sqs_delay(secs: i64) -> i32 { + secs.clamp(0, 900) as i32 +} + +/// Takes one emitted event: keeps it (when the team has any endpoint) and +/// sends it to every endpoint that wants it. Returns the endpoints that +/// this turned off. A second copy of the same message does nothing. +pub async fn dispatch(ctx: &Ctx<'_>, e: &Event) -> Result, String> { + // Events built outside `Event::new` (the log analyzer's) are scrubbed + // here too: nothing that looks like a credential is ever sent. + let mut e = e.clone(); + e.data = event::scrub(&e.data); + let e = &e; + let all = endpoint::list(ctx.dynamo, ctx.table, &e.team_id).await?; + if all.is_empty() { + return Ok(vec![]); + } + let body = e.body(); + if !event::keep(ctx.dynamo, ctx.table, e, &body).await? { + tracing::info!(event = %e.id, "Webhook event already taken; not sending it twice"); + return Ok(vec![]); + } + let wanting: Vec<&endpoint::Stored> = all + .iter() + .filter(|s| s.endpoint.wants(&e.event_type)) + .collect(); + let sends = wanting.iter().map(|st| { + let body = body.clone(); + async move { + let mut d = deliver::new_record(&st.endpoint, &e.id, &e.event_type, body.as_bytes()); + let out = attempt(ctx, &e.team_id, st, &e.id, &body, &mut d, Mode::Automatic).await; + (st.endpoint.clone(), out) + } + }); + Ok(futures::future::join_all(sends) + .await + .into_iter() + .filter(|(_, o)| o.disabled_now) + .map(|(ep, _)| ep) + .collect()) +} + +/// Queues kept events to one endpoint again (replay), each as a new +/// delivery. Returns how many were queued. +pub async fn replay( + ctx: &Ctx<'_>, + team_id: &str, + ep: &endpoint::Endpoint, + events: &[event::Kept], +) -> Result { + let now = chrono::Utc::now().timestamp(); + let mut queued = 0; + for chunk in events.chunks(10) { + let mut entries = Vec::new(); + for (i, k) in chunk.iter().enumerate() { + let mut d = + deliver::new_record(ep, &k.event.id, &k.event.event_type, k.body.as_bytes()); + d.outcome = "Queued (replay)".into(); + deliveries::record(ctx.dynamo, ctx.table, team_id, &d).await; + let msg = + crate::messages::WorkerMessage::WebhookSend(crate::messages::WebhookSendMessage { + team_id: team_id.into(), + endpoint_id: ep.id.clone(), + event_id: k.event.id.clone(), + delivery_id: d.id.clone(), + due_at: now, + }); + let body = serde_json::to_string(&msg).map_err(|e| e.to_string())?; + entries.push( + aws_sdk_sqs::types::SendMessageBatchRequestEntry::builder() + .id(i.to_string()) + .message_body(body) + .build() + .map_err(|e| e.to_string())?, + ); + } + let r = ctx + .sqs + .send_message_batch() + .queue_url(ctx.queue_url) + .set_entries(Some(entries)) + .send() + .await + .map_err(|e| aws_sdk_sqs::error::DisplayErrorContext(&e).to_string())?; + queued += r.successful().len(); + } + Ok(queued) +} + +/// The event types a replay should send to `ep`: what it subscribes to now. +pub fn replayable<'a>(ep: &endpoint::Endpoint, events: &'a [event::Kept]) -> Vec<&'a event::Kept> { + events + .iter() + .filter(|k| { + k.event.event_type != catalog::TEST_EVENT + && ep + .events + .iter() + .any(|t| t == "*" || *t == k.event.event_type) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn source(rel: &str) -> String { + std::fs::read_to_string( + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("..") + .join(rel), + ) + .unwrap() + } + + /// No log line in the webhook code names a secret's value: secrets are + /// only ever sealed, sent once to the person who made them, or used to + /// sign. + #[test] + fn signing_secrets_are_never_logged() { + for f in [ + "common/src/webhooks/mod.rs", + "common/src/webhooks/endpoint.rs", + "common/src/webhooks/deliver.rs", + "common/src/webhooks/sign.rs", + "common/src/webhooks/event.rs", + "gateway/src/routes/webhooks.rs", + "worker/src/passes/webhooks.rs", + ] { + let src = source(f); + let code = src.split("#[cfg(test)]").next().unwrap(); + let calls = ["tracing::", "warn!(", "info!(", "error!(", "debug!("] + .iter() + .flat_map(|m| code.split(m).skip(1)); + for (i, chunk) in calls.enumerate() { + // The call ends at its statement or its closing parenthesis. + let end = [";", ")\n", "),"] + .iter() + .filter_map(|t| chunk.find(t)) + .min() + .unwrap_or(chunk.len()); + let call = &chunk[..end]; + for bad in [ + "secret =", "%secret", "?secret", "secrets", "{secret}", "sealed", + ] { + assert!( + !call.contains(bad), + "{f}: log call {i} may print a secret: {call}" + ); + } + } + } + } + + /// Every endpoint route reads and writes only the caller's team, and + /// only admins (and keys with the scope) reach it. + #[test] + fn every_endpoint_route_is_scoped_to_the_callers_team_and_role() { + let src = source("gateway/src/routes/webhooks.rs"); + let code = src.split("#[cfg(test)]").next().unwrap(); + let mut n = 0; + for chunk in code.split("\npub async fn ").skip(1) { + let name = chunk.split('(').next().unwrap(); + if !chunk.contains("Extension(claims): Extension") { + continue; + } + n += 1; + let body = chunk.split("\n}\n").next().unwrap(); + assert!( + body.contains("claims.require_role(3)"), + "{name} has no admin check" + ); + if name != "event_types" { + assert!( + body.contains("claims.team_id"), + "{name} doesn't scope to the caller's team" + ); + } + assert!( + !body.contains("team_id: String") && !body.contains("q.team"), + "{name} takes a team from the request" + ); + } + assert_eq!(n, 12, "every endpoint route checked"); + // A delivery is resent only through the endpoint it belongs to. + assert!(code.contains(".filter(|d| d.endpoint_id == endpoint_id)")); + } + + #[test] + fn replays_send_only_what_the_endpoint_subscribes_to() { + let ep = endpoint::Endpoint { + id: "ep_1".into(), + events: vec!["run.failed".into()], + enabled: false, + ..Default::default() + }; + let kept = |t: &str| { + let e = Event::new("T", t, json!({})); + event::Kept { + body: e.body(), + event: e, + } + }; + let all = vec![ + kept("run.failed"), + kept("run.completed"), + kept(catalog::TEST_EVENT), + ]; + let picked = replayable(&ep, &all); + assert_eq!(picked.len(), 1); + assert_eq!(picked[0].event.event_type, "run.failed"); + let every = endpoint::Endpoint { + events: vec!["*".into()], + ..ep + }; + assert_eq!(replayable(&every, &all).len(), 2, "never the test event"); + } + + #[test] + fn long_waits_are_carried_past_the_sqs_limit() { + assert_eq!(sqs_delay(5), 5); + assert_eq!(sqs_delay(28_800), 900); + assert_eq!(sqs_delay(-3), 0); + } +} diff --git a/services/common/src/webhooks/sign.rs b/services/common/src/webhooks/sign.rs new file mode 100644 index 000000000..281bbedff --- /dev/null +++ b/services/common/src/webhooks/sign.rs @@ -0,0 +1,208 @@ +//! Signing, as the Standard Webhooks spec (standardwebhooks.com) has it. +//! +//! Every request carries three headers: +//! +//! - `webhook-id`: the event id, the same on every retry; +//! - `webhook-timestamp`: Unix seconds when this attempt was sent; +//! - `webhook-signature`: space-separated `v1,` entries, +//! one per live secret (two while a rotated secret is still accepted). +//! +//! A signature is the base64 HMAC-SHA256 of `..`, +//! keyed with the secret's bytes: the part after `whsec_`, base64-decoded. +//! Any Standard Webhooks library verifies these requests. + +use base64::{engine::general_purpose::STANDARD, Engine}; +use hmac::{Hmac, Mac}; +use sha2::Sha256; + +pub const SECRET_PREFIX: &str = "whsec_"; +pub const ID_HEADER: &str = "webhook-id"; +pub const TIMESTAMP_HEADER: &str = "webhook-timestamp"; +pub const SIGNATURE_HEADER: &str = "webhook-signature"; +/// How far a timestamp may be from now before a receiver should refuse it +/// (what the libraries default to). +pub const TOLERANCE_SECS: i64 = 300; + +/// A new signing secret: `whsec_` and 32 random bytes in base64. +pub fn new_secret() -> String { + use rand::RngCore; + let mut key = [0u8; 32]; + rand::rng().fill_bytes(&mut key); + format!("{SECRET_PREFIX}{}", STANDARD.encode(key)) +} + +/// The key bytes of a `whsec_` secret. +pub fn key_of(secret: &str) -> Result, String> { + let b64 = secret.strip_prefix(SECRET_PREFIX).unwrap_or(secret); + STANDARD + .decode(b64.trim()) + .map_err(|_| "the signing secret isn't valid base64".to_string()) +} + +/// The base64 signature of one message with one secret. +pub fn signature(secret: &str, id: &str, timestamp: i64, body: &[u8]) -> Result { + let key = key_of(secret)?; + let mut mac = + Hmac::::new_from_slice(&key).map_err(|_| "bad signing key".to_string())?; + mac.update(id.as_bytes()); + mac.update(b"."); + mac.update(timestamp.to_string().as_bytes()); + mac.update(b"."); + mac.update(body); + Ok(STANDARD.encode(mac.finalize().into_bytes())) +} + +/// The `webhook-signature` header: a `v1,` entry per secret, space separated. +pub fn header(secrets: &[&str], id: &str, timestamp: i64, body: &[u8]) -> Result { + let mut parts = Vec::with_capacity(secrets.len()); + for s in secrets { + parts.push(format!("v1,{}", signature(s, id, timestamp, body)?)); + } + Ok(parts.join(" ")) +} + +/// Why a request didn't verify. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum VerifyError { + Stale, + NoMatch, + Malformed, +} + +/// Checks a request the way a receiver does: the timestamp within +/// [`TOLERANCE_SECS`] of `now`, and any `v1` entry matching (compared in +/// constant time). +pub fn verify( + secret: &str, + id: &str, + timestamp: &str, + signature_header: &str, + body: &[u8], + now: i64, +) -> Result<(), VerifyError> { + let ts: i64 = timestamp + .trim() + .parse() + .map_err(|_| VerifyError::Malformed)?; + if (now - ts).abs() > TOLERANCE_SECS { + return Err(VerifyError::Stale); + } + let expected = signature(secret, id, ts, body).map_err(|_| VerifyError::Malformed)?; + let matched = signature_header.split_whitespace().any(|entry| { + entry + .strip_prefix("v1,") + .is_some_and(|sig| subtle_eq(sig.as_bytes(), expected.as_bytes())) + }); + if matched { + Ok(()) + } else { + Err(VerifyError::NoMatch) + } +} + +/// Constant time for equal lengths: every byte is compared, whatever matches. +fn subtle_eq(a: &[u8], b: &[u8]) -> bool { + a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 +} + +/// The last four characters of a secret, to tell secrets apart on the page. +pub fn hint(secret: &str) -> String { + let chars: Vec = secret.chars().collect(); + if chars.len() < 12 { + return String::new(); + } + format!( + "{SECRET_PREFIX}…{}", + chars[chars.len() - 4..].iter().collect::() + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + // The Standard Webhooks reference test vector (the spec's libraries all + // test against it). + const SECRET: &str = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw"; + const ID: &str = "msg_p5jXN8AQM9LWM0D4loKWxJek"; + const TS: i64 = 1614265330; + const BODY: &[u8] = br#"{"test": 2432232314}"#; + const EXPECTED: &str = "v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE="; + + #[test] + fn matches_the_standard_webhooks_test_vector() { + assert_eq!(header(&[SECRET], ID, TS, BODY).unwrap(), EXPECTED); + assert!(verify(SECRET, ID, &TS.to_string(), EXPECTED, BODY, TS + 10).is_ok()); + } + + #[test] + fn verification_refuses_tampering_and_old_timestamps() { + let ts = TS.to_string(); + assert_eq!( + verify(SECRET, ID, &ts, EXPECTED, br#"{"test": 1}"#, TS), + Err(VerifyError::NoMatch) + ); + assert_eq!( + verify(SECRET, "msg_other", &ts, EXPECTED, BODY, TS), + Err(VerifyError::NoMatch) + ); + assert_eq!( + verify(SECRET, ID, &ts, EXPECTED, BODY, TS + TOLERANCE_SECS + 1), + Err(VerifyError::Stale) + ); + assert_eq!( + verify(SECRET, ID, &ts, EXPECTED, BODY, TS - TOLERANCE_SECS - 1), + Err(VerifyError::Stale) + ); + assert_eq!( + verify(SECRET, ID, "soon", EXPECTED, BODY, TS), + Err(VerifyError::Malformed) + ); + assert_eq!( + verify(SECRET, ID, &ts, "v2,abc", BODY, TS), + Err(VerifyError::NoMatch) + ); + } + + #[test] + fn two_secrets_sign_during_a_rotation_and_either_verifies() { + let new = new_secret(); + let h = header(&[&new, SECRET], ID, TS, BODY).unwrap(); + let parts: Vec<&str> = h.split(' ').collect(); + assert_eq!(parts.len(), 2); + assert_eq!(parts[1], EXPECTED); + assert!(verify(&new, ID, &TS.to_string(), &h, BODY, TS).is_ok()); + assert!(verify(SECRET, ID, &TS.to_string(), &h, BODY, TS).is_ok()); + assert_eq!( + verify(&new_secret(), ID, &TS.to_string(), &h, BODY, TS), + Err(VerifyError::NoMatch) + ); + } + + #[test] + fn new_secrets_are_32_random_bytes() { + let a = new_secret(); + assert!(a.starts_with(SECRET_PREFIX)); + assert_eq!(key_of(&a).unwrap().len(), 32); + assert_ne!(a, new_secret()); + assert!(key_of("whsec_not base64!").is_err()); + // From the OS-seeded CSPRNG: no repeats, no fixed bytes. + let many: std::collections::HashSet = (0..2000).map(|_| new_secret()).collect(); + assert_eq!(many.len(), 2000); + let mut ones = 0u32; + for s in many.iter().take(200) { + ones += key_of(s) + .unwrap() + .iter() + .map(|b| b.count_ones()) + .sum::(); + } + let bits = 200 * 32 * 8; + assert!( + (bits * 45 / 100..bits * 55 / 100).contains(&ones), + "bits look random: {ones}/{bits}" + ); + assert!(hint(&a).starts_with("whsec_…") && hint(&a).ends_with(&a[a.len() - 4..])); + assert_eq!(hint("short"), ""); + } +} diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index f80c60fb4..b8c3d1491 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -197,6 +197,43 @@ async fn main() -> Result<(), Error> { "/system/hybrid/settings", put(routes::hybrid_install::put_settings), ) + // Outbound webhooks: the team's endpoints and their deliveries (admins + // and API keys with the webhooks scope). + .route("/webhooks/event-types", get(routes::webhooks::event_types)) + .route( + "/webhooks/endpoints", + get(routes::webhooks::list_endpoints).post(routes::webhooks::create_endpoint), + ) + .route( + "/webhooks/endpoints/:endpoint_id", + get(routes::webhooks::get_endpoint) + .put(routes::webhooks::update_endpoint) + .delete(routes::webhooks::delete_endpoint), + ) + .route( + "/webhooks/endpoints/:endpoint_id/secret", + get(routes::webhooks::reveal_secret), + ) + .route( + "/webhooks/endpoints/:endpoint_id/secret/rotate", + post(routes::webhooks::rotate_secret), + ) + .route( + "/webhooks/endpoints/:endpoint_id/test", + post(routes::webhooks::send_test), + ) + .route( + "/webhooks/endpoints/:endpoint_id/deliveries", + get(routes::webhooks::list_endpoint_deliveries), + ) + .route( + "/webhooks/endpoints/:endpoint_id/deliveries/:delivery_id/resend", + post(routes::webhooks::resend_delivery), + ) + .route( + "/webhooks/endpoints/:endpoint_id/replay", + post(routes::webhooks::replay), + ) // Deliveries: every event in and out, with what happened (admins). .route("/deliveries", get(routes::deliveries::list)) .route("/deliveries/:id", get(routes::deliveries::get)) diff --git a/services/gateway/src/models.rs b/services/gateway/src/models.rs index bf9bfd3cc..c562ff85b 100644 --- a/services/gateway/src/models.rs +++ b/services/gateway/src/models.rs @@ -32,6 +32,8 @@ pub struct Config { pub ticket_queue_arn: String, pub ci_fix_queue_url: String, pub feedback_queue_url: String, + /// Outbound webhook events and retries. Empty: nothing is emitted. + pub webhook_queue_url: String, pub dlq_url: String, pub ses_from_address: String, pub ses_template_prefix: String, @@ -89,6 +91,7 @@ impl Config { ci_fix_queue_url: std::env::var("CI_FIX_QUEUE_URL").expect("CI_FIX_QUEUE_URL required"), feedback_queue_url: std::env::var("FEEDBACK_QUEUE_URL") .expect("FEEDBACK_QUEUE_URL required"), + webhook_queue_url: std::env::var("WEBHOOK_QUEUE_URL").unwrap_or_default(), dlq_url: std::env::var("DLQ_URL").unwrap_or_default(), ses_from_address: std::env::var("SES_FROM_ADDRESS") .unwrap_or_else(|_| "notifications@coderhelm.com".to_string()), diff --git a/services/gateway/src/openapi.rs b/services/gateway/src/openapi.rs index 6e3c831ac..e7fb252fb 100644 --- a/services/gateway/src/openapi.rs +++ b/services/gateway/src/openapi.rs @@ -93,6 +93,58 @@ pub const PUBLIC_ROUTES: &[PublicRoute] = &[ key("GET", "/api/reviewer/reviews", "reviewer::list_reviews"), key("GET", "/api/reviewer/review", "reviewer::get_review"), key("GET", "/api/usage", "api::get_usage"), + key("GET", "/api/webhooks/event-types", "webhooks::event_types"), + key("GET", "/api/webhooks/endpoints", "webhooks::list_endpoints"), + key( + "POST", + "/api/webhooks/endpoints", + "webhooks::create_endpoint", + ), + key( + "GET", + "/api/webhooks/endpoints/:endpoint_id", + "webhooks::get_endpoint", + ), + key( + "PUT", + "/api/webhooks/endpoints/:endpoint_id", + "webhooks::update_endpoint", + ), + key( + "DELETE", + "/api/webhooks/endpoints/:endpoint_id", + "webhooks::delete_endpoint", + ), + key( + "GET", + "/api/webhooks/endpoints/:endpoint_id/secret", + "webhooks::reveal_secret", + ), + key( + "POST", + "/api/webhooks/endpoints/:endpoint_id/secret/rotate", + "webhooks::rotate_secret", + ), + key( + "POST", + "/api/webhooks/endpoints/:endpoint_id/test", + "webhooks::send_test", + ), + key( + "GET", + "/api/webhooks/endpoints/:endpoint_id/deliveries", + "webhooks::list_endpoint_deliveries", + ), + key( + "POST", + "/api/webhooks/endpoints/:endpoint_id/deliveries/:delivery_id/resend", + "webhooks::resend_delivery", + ), + key( + "POST", + "/api/webhooks/endpoints/:endpoint_id/replay", + "webhooks::replay", + ), PublicRoute { method: "POST", path: "/webhooks/ci/tests/results", @@ -198,7 +250,7 @@ pub fn default_code(status: axum::http::StatusCode) -> &'static str { const DESCRIPTION: &str = "The CoderHelm API lets your own programs start and follow CoderHelm's work: \ list and inspect runs, retry or cancel them, create and run plans, read the reviewer's reviews, \ -and check token usage.\n\n\ +check token usage, and manage the webhook endpoints CoderHelm sends your team's events to.\n\n\ Every request is authenticated with a team API key sent as a bearer token. Admins create keys in \ the dashboard under Settings, API keys. A key holds scopes, never more than the admin who made it, \ and has its own rate limit.\n\n\ @@ -229,6 +281,18 @@ are verified by their signatures."; crate::routes::reviewer::list_reviews, crate::routes::reviewer::get_review, crate::routes::api::get_usage, + crate::routes::webhooks::event_types, + crate::routes::webhooks::list_endpoints, + crate::routes::webhooks::create_endpoint, + crate::routes::webhooks::get_endpoint, + crate::routes::webhooks::update_endpoint, + crate::routes::webhooks::delete_endpoint, + crate::routes::webhooks::reveal_secret, + crate::routes::webhooks::rotate_secret, + crate::routes::webhooks::send_test, + crate::routes::webhooks::list_endpoint_deliveries, + crate::routes::webhooks::resend_delivery, + crate::routes::webhooks::replay, crate::routes::tests::ci_upload, crate::routes::tests::ci_quarantine, crate::routes::github_webhook::handle, @@ -247,7 +311,8 @@ are verified by their signatures."; (name = "Reviews", description = "Pull request reviews written by CoderHelm's reviewer."), (name = "Usage", description = "Tokens used this month and the team's limits."), (name = "CI", description = "Endpoints a CI job calls with its GitHub Actions OIDC token, so no CoderHelm secret is stored in CI."), - (name = "Webhooks", description = "Events CoderHelm receives from GitHub, Jira, AWS SNS, Sanity and Notion. Each is verified before anything happens."), + (name = "Webhook endpoints", description = "Where CoderHelm sends your team's events (runs, pull requests, reviews, CI fixes, alerts, log findings, releases, plans). Each request is signed the Standard Webhooks way. The `webhooks` section of this document has every event's schema."), + (name = "Webhooks", description = "Webhooks CoderHelm receives from GitHub, Jira, AWS SNS, Sanity and Notion. CoderHelm verifies each one before anything happens."), ), )] pub struct ApiDoc; @@ -461,6 +526,9 @@ pub fn document_json() -> String { if let Some(paths) = doc.get_mut("paths") { inline_schemas(paths); } + if let Some(obj) = doc.as_object_mut() { + obj.insert("webhooks".into(), outbound_webhooks()); + } // Readers show a tag's `x-displayName` as written ("CI"), where they // would otherwise make a title out of its name ("C I"). if let Some(tags) = doc.get_mut("tags").and_then(|v| v.as_array_mut()) { @@ -475,6 +543,61 @@ pub fn document_json() -> String { s } +/// The events CoderHelm sends to a team's endpoints, as OpenAPI 3.1 +/// `webhooks`: one operation per event type, made from the event catalog +/// (`common::webhooks::catalog`). +fn outbound_webhooks() -> serde_json::Value { + use common::webhooks::catalog; + use serde_json::json; + let header = |name: &str, description: &str, example: &str| { + json!({ + "name": name, + "in": "header", + "required": true, + "description": description, + "schema": { "type": "string" }, + "example": example, + }) + }; + let params = json!([ + header("webhook-id", "The event id (`evt_…`). The same on every retry: use it to skip an event you already handled.", "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W"), + header("webhook-timestamp", "Unix seconds when this attempt was sent. Refuse a request more than 5 minutes off.", "1792420307"), + header("webhook-signature", "Space-separated `v1,` signatures: HMAC-SHA256 of `..` keyed with the endpoint's secret (the bytes after `whsec_`, base64-decoded). Two while a rotated secret still signs; accept the request when any matches.", "v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4="), + ]); + let mut out = serde_json::Map::new(); + for e in catalog::EVENTS { + let example = catalog::example_event(e.name); + out.insert( + e.name.to_string(), + json!({ + "post": { + "operationId": format!("event.{}", e.name), + "summary": e.summary, + "description": format!("{} Sent as `POST` to each endpoint subscribed to `{}` (or to every event).", e.description, e.name), + "tags": [format!("Events: {}", e.group)], + "parameters": params, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": catalog::event_schema(e), + "examples": { "event": { "value": example } }, + } + } + }, + "responses": { + "2XX": { "description": "Received. Answer within 10 seconds; do the work afterwards." }, + "410": { "description": "Gone: the delivery is final (not retried). Any 4xx other than 408 and 429 is final." }, + "5XX": { "description": "Retried with backoff for about a day, as are timeouts, 408 and 429." }, + }, + "security": [], + } + }), + ); + } + serde_json::Value::Object(out) +} + /// OpenAPI 3.1 schemas are JSON Schema 2020-12, where an example is /// `examples: [..]`; utoipa writes the older `example`. Tools that build /// samples from the schema (the docs site among them) read `examples`. @@ -561,6 +684,34 @@ mod tests { out } + /// Outbound webhooks only go out: no unauthenticated or signature-only + /// route takes anything on that path, so whoever controls an endpoint + /// can't send events, answers or "deliveries" into CoderHelm. + #[test] + fn outbound_webhooks_have_no_inbound_path() { + for r in PUBLIC_ROUTES + .iter() + .filter(|r| r.handler.starts_with("webhooks::")) + { + assert_eq!(r.auth, RouteAuth::ApiKey, "{} must need an API key", r.path); + assert!(r.path.starts_with("/api/webhooks/"), "{}", r.path); + } + let main = include_str!("main.rs"); + let inbound = main + .split(".nest(\"/webhooks\", webhook_routes)") + .next() + .unwrap(); + let webhook_router = inbound.rsplit("let webhook_routes").next().unwrap_or(""); + assert!( + !webhook_router.contains("routes::webhooks::"), + "an outbound webhook handler is on the unauthenticated /webhooks router" + ); + // What an endpoint answers is only kept as a short note; nothing parses it. + let deliver = include_str!("../../common/src/webhooks/deliver.rs"); + let code = deliver.split("#[cfg(test)]").next().unwrap(); + assert!(!code.contains(".json::<") && !code.contains("resp.json(")); + } + #[test] fn openapi_documents_exactly_the_public_routes() { let public: BTreeSet<(String, String)> = PUBLIC_ROUTES diff --git a/services/gateway/src/permissions.rs b/services/gateway/src/permissions.rs index 67bb1bbb6..7257da94b 100644 --- a/services/gateway/src/permissions.rs +++ b/services/gateway/src/permissions.rs @@ -585,6 +585,25 @@ pub const CAPABILITIES: &[Capability] = &[ "dlq::purge_dlq", ], }, + Capability { + key: "webhooks", + label: "Add, change and delete webhook endpoints, reveal and rotate their signing secrets, and send, resend and replay their events", + min_role: "admin", + handlers: &[ + "webhooks::event_types", + "webhooks::list_endpoints", + "webhooks::create_endpoint", + "webhooks::get_endpoint", + "webhooks::update_endpoint", + "webhooks::delete_endpoint", + "webhooks::reveal_secret", + "webhooks::rotate_secret", + "webhooks::send_test", + "webhooks::list_endpoint_deliveries", + "webhooks::resend_delivery", + "webhooks::replay", + ], + }, Capability { key: "deliveries", label: "See every event in and out (webhooks, relay forwards, notifications, email) and send failed ones again", diff --git a/services/gateway/src/routes/alerts.rs b/services/gateway/src/routes/alerts.rs index 73aafeb7a..5b8953d83 100644 --- a/services/gateway/src/routes/alerts.rs +++ b/services/gateway/src/routes/alerts.rs @@ -1315,6 +1315,44 @@ async fn record_event( if let Err(e) = written { warn!(topic = %msg.topic_arn, ticket = %tid, error = %e, "Could not record alert event"); } + // The alert's id seeds the event's, so an SNS redelivery is sent once. + common::webhooks::emit_event_keyed( + &state.sqs, + &state.config.webhook_queue_url, + &route.team_id, + "alert.received", + alert_event_data(&id, alert, outcome, repo, tid, &received_at), + Some(&id), + ) + .await; +} + +/// `alert.received`'s `data` (pure). +pub fn alert_event_data( + id: &str, + alert: &Alert, + outcome: Outcome, + repo: &str, + tid: &str, + received_at: &str, +) -> Value { + use common::alert_notify::Severity; + let severity = match common::alert_notify::severity(alert.kind, &alert.title) { + Severity::Alarm => "alarm", + Severity::Warning => "warning", + Severity::Resolved => "resolved", + Severity::Info => "info", + }; + serde_json::json!({ + "alert_id": id, + "kind": alert.kind, + "title": common::truncate_str(&alert.title, 300), + "severity": severity, + "outcome": outcome.as_str(), + "repo": Some(repo).filter(|r| !r.is_empty()), + "ticket_id": tid, + "received_at": received_at, + }) } /// Pure: may another alert run start? Tokens used plus a reserve for each run @@ -2339,6 +2377,34 @@ pub async fn get_event( mod tests { use super::*; + #[test] + fn an_alert_event_carries_the_documented_fields() { + let alert = normalize( + Some("ALARM: api-5xx"), + r#"{"AlarmName":"api-5xx","NewStateValue":"ALARM","NewStateReason":"x"}"#, + ); + let d = alert_event_data( + "01JBALERT3K8P2N6Q9R1S4T7V0", + &alert, + Outcome::RunStarted, + "example-org/api", + "ALERT-1", + "2026-10-26T09:14:03+00:00", + ); + let schema = common::webhooks::catalog::data_schema( + common::webhooks::catalog::find("alert.received").unwrap(), + ); + let props = schema["properties"].as_object().unwrap(); + let keys: std::collections::BTreeSet<&String> = d.as_object().unwrap().keys().collect(); + assert_eq!(keys, props.keys().collect()); + assert_eq!(d["severity"], "alarm"); + assert_eq!(d["outcome"], "run_started"); + let none = alert_event_data("x", &alert, Outcome::NoMatch, "", "T", "t"); + assert_eq!(none["repo"], Value::Null); + let sev = props["severity"]["enum"].as_array().unwrap(); + assert!(sev.contains(&d["severity"])); + } + #[test] fn a_route_keeps_only_its_webhooks_and_shows_them_as_hints() { let item: HashMap = HashMap::from([ diff --git a/services/gateway/src/routes/deliveries.rs b/services/gateway/src/routes/deliveries.rs index 50092c579..a8d5fa883 100644 --- a/services/gateway/src/routes/deliveries.rs +++ b/services/gateway/src/routes/deliveries.rs @@ -241,6 +241,7 @@ pub async fn list( status: q.status, since: q.since, q: q.q, + endpoint: None, }; let limit = q.limit.unwrap_or(100).clamp(1, 500); let all = everything(&state, &claims, &f).await; @@ -306,7 +307,9 @@ pub async fn get( /// Which redelivery this record allows, if any. fn redeliver_kind(d: &Delivery) -> Option { - if d.status.is_ok() && d.source != "github" { + // GitHub's and a webhook's deliveries can be sent again even when they + // went fine (the receiver asks for it); the others only when they failed. + if d.status.is_ok() && d.source != "github" && d.source != "webhook" { return None; } match (d.source.as_str(), d.redeliver) { @@ -316,6 +319,11 @@ fn redeliver_kind(d: &Delivery) -> Option { ("relay", Some(deliveries::Redeliver::Relay)) if d.id.starts_with("relay:") => { Some(deliveries::Redeliver::Relay) } + ("webhook", Some(deliveries::Redeliver::Webhook)) + if !d.endpoint_id.is_empty() && !d.external_id.is_empty() => + { + Some(deliveries::Redeliver::Webhook) + } _ => None, } } @@ -344,6 +352,14 @@ pub async fn redeliver( let d: Delivery = serde_json::from_value(v["delivery"].clone()) .map_err(|_| fail(StatusCode::INTERNAL_SERVER_ERROR, "Unreadable record."))?; match redeliver_kind(&d) { + Some(deliveries::Redeliver::Webhook) => { + let d = super::webhooks::resend_record(&state, &claims.team_id, d).await?; + let ok = d.status.is_ok(); + Ok(Json(json!({ + "ok": ok, + "message": if ok { "Sent again and delivered." } else { "Sent again; the endpoint didn't take it. The attempt is on the record." }, + }))) + } Some(deliveries::Redeliver::Relay) => { let creds = common::hybrid::client::credentials().ok_or_else(|| { fail( @@ -492,6 +508,22 @@ mod tests { ); let e = Delivery::new(Direction::Outbound, "email", "invite", "example.com"); assert_eq!(redeliver_kind(&e), None); + let mut w = Delivery::new( + Direction::Outbound, + "webhook", + "run.failed", + "hooks.example.com", + ); + w.redeliver = Some(deliveries::Redeliver::Webhook); + w.status = Status::Handled; + assert_eq!(redeliver_kind(&w), None, "needs the endpoint and the event"); + w.endpoint_id = "ep_1".into(); + w.external_id = "evt_1".into(); + assert_eq!( + redeliver_kind(&w), + Some(deliveries::Redeliver::Webhook), + "a delivered webhook can be sent again" + ); } #[test] diff --git a/services/gateway/src/routes/mod.rs b/services/gateway/src/routes/mod.rs index 0c7b4241c..09d688c88 100644 --- a/services/gateway/src/routes/mod.rs +++ b/services/gateway/src/routes/mod.rs @@ -62,3 +62,4 @@ pub mod tests_setup; pub mod tools; pub mod trigger_gate; pub mod users; +pub mod webhooks; diff --git a/services/gateway/src/routes/plans.rs b/services/gateway/src/routes/plans.rs index f1ba6d541..672c2690b 100644 --- a/services/gateway/src/routes/plans.rs +++ b/services/gateway/src/routes/plans.rs @@ -1145,6 +1145,15 @@ pub async fn approve_all_and_execute( StatusCode::INTERNAL_SERVER_ERROR })?; + super::webhooks::emit_plan_approved( + &state, + &claims, + &plan_id, + &super::webhooks::plan_title(result.items(), &plan_id), + task_ids.len(), + ) + .await; + // Mark tasks as queued for (task_id, _) in &task_ids { let task_sk = format!("PLAN#{plan_id}#TASK#{task_id}"); diff --git a/services/gateway/src/routes/webhooks.rs b/services/gateway/src/routes/webhooks.rs new file mode 100644 index 000000000..51ddc5877 --- /dev/null +++ b/services/gateway/src/routes/webhooks.rs @@ -0,0 +1,1202 @@ +//! Webhook endpoints: where CoderHelm sends a team's events (admins, and API +//! keys with the `webhooks` scope). +//! +//! - `GET /api/webhooks/event-types`: the event catalog. +//! - `GET|POST /api/webhooks/endpoints`, `GET|PUT|DELETE …/:endpoint_id`. +//! - `GET …/:endpoint_id/secret` reveals the signing secret; +//! `POST …/secret/rotate` makes a new one (the old one keeps signing +//! through an overlap). +//! - `POST …/:endpoint_id/test` sends a `webhook.test` event now. +//! - `GET …/:endpoint_id/deliveries`, `POST …/deliveries/:delivery_id/resend`. +//! - `POST …/:endpoint_id/replay` sends the kept events of a time range again. +//! +//! The rules (signing, retries, address checks, turning failing endpoints +//! off) are in `common::webhooks`; every attempt is a Deliveries record. + +use std::sync::Arc; + +use axum::{ + extract::{Path, Query, State}, + http::StatusCode, + Extension, Json, +}; +use common::deliveries::{self, Delivery, Filter, Status}; +use common::webhooks::{self, catalog, endpoint, event, Mode}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use utoipa::{IntoParams, ToSchema}; + +use crate::models::Claims; +use crate::routes::roles::{self, AuditEntry}; +use crate::AppState; + +type ApiError = (StatusCode, Json); +type Reply = Result, ApiError>; + +fn fail(code: StatusCode, message: &str) -> ApiError { + (code, Json(json!({ "error": message }))) +} + +fn internal(context: &str, e: impl std::fmt::Display) -> ApiError { + tracing::error!("{context}: {e}"); + fail( + StatusCode::INTERNAL_SERVER_ERROR, + "Something went wrong on our side. Try again.", + ) +} + +fn admins_only(c: StatusCode) -> ApiError { + fail(c, "Only admins can manage webhooks.") +} + +fn kms(state: &AppState) -> common::mcp_credentials::Kms<'_> { + common::mcp_credentials::Kms { + client: &state.kms, + key_id: &state.config.secrets_key_id, + } +} + +fn now_secs(now: chrono::DateTime) -> String { + now.to_rfc3339_opts(chrono::SecondsFormat::Secs, true) +} + +async fn load(state: &AppState, team: &str, id: &str) -> Result { + endpoint::get(&state.dynamo, &state.config.settings_table_name, team, id) + .await + .map_err(|e| internal("Failed to read a webhook endpoint", e))? + .ok_or_else(|| fail(StatusCode::NOT_FOUND, "No such webhook endpoint.")) +} + +/// The address's name must resolve, and only to public addresses. +async fn check_public(url: &str) -> Result<(), ApiError> { + let check = webhooks::deliver::check_address(&webhooks::deliver::SystemDns, url); + match tokio::time::timeout(std::time::Duration::from_secs(5), check).await { + Ok(Ok(())) => Ok(()), + Ok(Err(message)) => Err(invalid(endpoint::Invalid { + field: "url", + message, + })), + Err(_) => Err(invalid(endpoint::Invalid { + field: "url", + message: "Looking up the address took too long. Try again.".into(), + })), + } +} + +fn invalid(i: endpoint::Invalid) -> ApiError { + ( + StatusCode::BAD_REQUEST, + Json(json!({ "error": i.message, "code": "bad_request", "field": i.field })), + ) +} + +// ── Emitting ──────────────────────────────────────────────────────── + +/// Queues one event for the team's endpoints (`common::webhooks::emit_event`). +pub async fn emit(state: &AppState, team_id: &str, event_type: &str, data: Value) { + webhooks::emit_event( + &state.sqs, + &state.config.webhook_queue_url, + team_id, + event_type, + data, + ) + .await; +} + +/// Who did something, as events name them: a person's login or email, or +/// `api_key:` for a request made with an API key. +pub fn actor(claims: &Claims) -> String { + match &claims.api_key { + Some(k) => format!("api_key:{}", k.id), + None => claims.display_name(), + } +} + +/// `plan.approved`'s `data` (pure). +pub fn plan_approved_data(plan_id: &str, title: &str, tasks: usize, by: &str, app: &str) -> Value { + json!({ + "plan_id": plan_id, + "title": title, + "task_count": tasks, + "approved_by": by, + "url": format!("{}/plans/detail/?id={}", app.trim_end_matches('/'), urlencoding::encode(plan_id)), + }) +} + +/// The plan's title from a plan query's items (the `PLAN#` item). +pub fn plan_title( + items: &[std::collections::HashMap], + plan_id: &str, +) -> String { + let sk = format!("PLAN#{plan_id}"); + items + .iter() + .find(|i| i.get("sk").and_then(|v| v.as_s().ok()) == Some(&sk)) + .and_then(|i| i.get("title")) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() +} + +/// Emits `plan.approved`. +pub async fn emit_plan_approved( + state: &AppState, + claims: &Claims, + plan_id: &str, + title: &str, + tasks: usize, +) { + let app = common::public_urls::app_url(&state.config.stage); + emit( + state, + &claims.team_id, + "plan.approved", + plan_approved_data(plan_id, title, tasks, &actor(claims), app), + ) + .await; +} + +// ── Shapes (for the OpenAPI document) ─────────────────────────────── + +/// A webhook endpoint. Never carries its secret. +#[derive(Serialize, ToSchema)] +pub struct WebhookEndpoint { + /// `ep_` and a ULID. + #[schema(example = "ep_01jbendpt4a7b0c3d6e9f2g5h8")] + pub id: String, + /// Where events are POSTed. Always `https://`. + #[schema(example = "https://hooks.example.com/coderhelm")] + pub url: String, + /// A note for people: what the endpoint is for. + #[schema(example = "Deploy bot")] + pub description: String, + /// Event types it receives; `["*"]` is every event, including types + /// added later. + #[schema(example = json!(["run.completed", "run.failed"]))] + pub events: Vec, + /// Off: nothing is sent (tests still are). + #[schema(example = true)] + pub enabled: bool, + /// Why it's off: `manual` (turned off by a person) or `failing` (turned + /// off by CoderHelm after 5 days of failed deliveries). Empty while on. + #[schema(example = "")] + pub disabled_reason: String, + /// The last characters of the signing secret. + #[schema(example = "whsec_…Q2c=")] + pub secret_hint: String, + /// While a rotated-out secret still signs too, when it stops. + #[schema(nullable, example = "2026-10-27T09:00:00Z")] + pub previous_secret_expires_at: Option, + /// The first failed delivery since the last success. + #[schema(nullable, example = json!(null))] + pub failing_since: Option, + /// The last delivered attempt. + #[schema(nullable, example = "2026-10-26T14:31:48.120Z")] + pub last_success_at: Option, + /// The last failed attempt. + #[schema(nullable, example = "2026-10-25T08:02:11.004Z")] + pub last_failure_at: Option, + /// When it was added. + #[schema(example = "2026-10-20T09:00:00Z")] + pub created_at: String, + /// Who added it. + #[schema(example = "lead@example.com")] + pub created_by: String, + /// When it last changed. + #[schema(example = "2026-10-20T09:00:00Z")] + pub updated_at: String, +} + +fn view(e: &endpoint::Endpoint) -> Value { + serde_json::to_value(e).unwrap_or_default() +} + +/// A new endpoint. +#[derive(Deserialize, ToSchema)] +pub struct CreateEndpointBody { + /// An `https://` address on the public internet. + #[schema(example = "https://hooks.example.com/coderhelm")] + pub url: String, + /// A note for people: what the endpoint is for. + #[serde(default)] + #[schema(example = "Deploy bot")] + pub description: Option, + /// Event types to receive, or `["*"]` for every event. Defaults to every + /// event. + #[serde(default)] + #[schema(example = json!(["run.completed", "run.failed"]))] + pub events: Option>, + /// Defaults to `true`. + #[serde(default)] + #[schema(example = true)] + pub enabled: Option, +} + +/// Changes to an endpoint. Only the fields sent change. +#[derive(Deserialize, ToSchema)] +pub struct UpdateEndpointBody { + /// A new `https://` address. + #[serde(default)] + #[schema(example = "https://hooks.example.com/coderhelm/v2")] + pub url: Option, + /// A new note. + #[serde(default)] + #[schema(example = "Deploy bot (staging)")] + pub description: Option, + /// The new subscription list, or `["*"]`. + #[serde(default)] + #[schema(example = json!(["*"]))] + pub events: Option>, + /// Turning an endpoint back on starts its failure count again. + #[serde(default)] + #[schema(example = true)] + pub enabled: Option, +} + +/// A new endpoint and its signing secret. The secret is shown here once; +/// reveal it later with `GET …/secret`. +#[derive(Serialize, ToSchema)] +pub struct CreatedEndpoint { + pub endpoint: WebhookEndpoint, + /// `whsec_` and 32 random bytes in base64. Verify signatures with it. + #[schema(example = "whsec_C2FVsBQIhrscChlQIMV+b5sSYspob7oD7vS8nSUIQ2c=")] + pub secret: String, +} + +/// An endpoint's signing secret. +#[derive(Serialize, ToSchema)] +pub struct SecretView { + /// The current secret. + #[schema(example = "whsec_C2FVsBQIhrscChlQIMV+b5sSYspob7oD7vS8nSUIQ2c=")] + pub secret: String, + /// While the previous secret still signs too, when it stops. + #[schema(nullable, example = json!(null))] + pub previous_secret_expires_at: Option, +} + +/// How long the old secret keeps signing. +#[derive(Deserialize, ToSchema, Default)] +pub struct RotateBody { + /// Hours the old secret keeps signing beside the new one: 0 to 168. + /// Defaults to 24. With 0 the old secret stops at once. + #[serde(default)] + #[schema(example = 24)] + pub overlap_hours: Option, +} + +/// A rotated secret. +#[derive(Serialize, ToSchema)] +pub struct RotatedSecret { + /// The new secret. Requests are signed with it from now on. + #[schema(example = "whsec_k0q8vX2mZp5Rr3t1YbN6cH9dLwE4fJ7aS1uG0iT2oQs=")] + pub secret: String, + /// Until then, requests carry a second signature made with the old one. + #[schema(nullable, example = "2026-10-27T09:00:00Z")] + pub previous_secret_expires_at: Option, +} + +/// One delivery of an event to an endpoint. +#[derive(Serialize, ToSchema)] +pub struct WebhookDelivery { + /// The Deliveries record's id. + #[schema(example = "01JBDLVR5T8V1W4X7Y0Z3A6B9C")] + pub id: String, + /// The event's id: the same `webhook-id` on every attempt. + #[schema(example = "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W")] + pub event_id: String, + /// The event type. + #[schema(example = "run.completed")] + pub event: String, + /// `pending` (being retried), `handled` (delivered) or `failed`. + #[schema(example = "failed")] + pub status: String, + /// What happened, in a few words. + #[schema(example = "Refused (401)")] + pub outcome: String, + /// A reason code when it failed. + #[schema(example = "webhook_refused")] + pub reason: String, + /// The reason in plain words. + #[schema( + example = "Your webhook endpoint refused the event (a 4xx answer), so it isn't retried." + )] + pub reason_message: String, + /// What to do about it. + #[schema( + example = "Check that the endpoint verifies signatures with the right secret and accepts JSON, then press Resend." + )] + pub reason_fix: String, + /// Every attempt, oldest first (the last 20). + pub attempts: Vec, + /// When the next retry is due, while one is. + #[schema(nullable, example = json!(null))] + pub next_retry_at: Option, + /// When the event was first sent to this endpoint. + #[schema(example = "2026-10-26T14:31:47.780Z")] + pub created_at: String, + /// The body that was sent, with secret-looking values masked, cut at 4 KB. + #[schema(example = "{\n \"id\": \"evt_01JBEVNT8M1N4P7Q0R3S6T9V2W\" …")] + pub payload_preview: String, + /// The request's headers, the signature removed. + #[schema(example = json!({ "webhook-id": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", "webhook-timestamp": "1792420307", "webhook-signature": "[redacted]" }))] + pub headers: std::collections::BTreeMap, +} + +/// One attempt. +#[derive(Serialize, ToSchema)] +pub struct DeliveryAttempt { + /// When it was sent. + #[schema(example = "2026-10-26T14:31:47.901Z")] + pub at: String, + /// The endpoint's HTTP status, when it answered. + #[schema(nullable, example = 401)] + pub code: Option, + /// How long it took. + #[schema(example = 112)] + pub duration_ms: u64, + /// What went wrong, when it did. + #[schema(example = "Answered 401: bad signature")] + pub error: String, +} + +fn delivery_view(d: &Delivery) -> Value { + let r = (!d.reason.is_empty()).then(|| deliveries::reason(&d.reason)); + json!({ + "id": d.id, + "event_id": d.external_id, + "event": d.event, + "status": d.status, + "outcome": d.outcome, + "reason": d.reason, + "reason_message": r.map(|r| r.message).unwrap_or(""), + "reason_fix": r.map(|r| r.fix).unwrap_or(""), + "attempts": d.attempts, + "next_retry_at": d.next_retry_at, + "created_at": d.created_at, + "payload_preview": d.payload_preview, + "headers": d.headers, + }) +} + +/// Which kept events to send again. +#[derive(Deserialize, ToSchema)] +pub struct ReplayBody { + /// RFC 3339. At most 14 days ago (events are kept that long). + #[schema(example = "2026-10-25T00:00:00Z")] + pub since: String, + /// RFC 3339. Defaults to now. + #[serde(default)] + #[schema(example = "2026-10-26T00:00:00Z")] + pub until: Option, + /// Only events whose deliveries to this endpoint all failed, or that it + /// never got. Defaults to `false` (every event it subscribes to). + #[serde(default)] + #[schema(example = true)] + pub only_failed: bool, +} + +/// What a replay queued. +#[derive(Serialize, ToSchema)] +pub struct ReplayResult { + /// Events queued to send again. + #[schema(example = 12)] + pub queued: usize, + /// Kept events in the range (of every type). + #[schema(example = 40)] + pub found: usize, + /// More matched than one replay sends (500); replay again from the last one. + #[schema(example = false)] + pub capped: bool, +} + +/// The `limit` and `status` of a delivery list. +#[derive(Deserialize, IntoParams, Default)] +#[into_params(parameter_in = Query)] +pub struct DeliveryQuery { + /// `pending`, `failed`, `ok` or `all` (default). + #[serde(default)] + pub status: Option, + /// 1 to 100, default 25. + #[serde(default)] + pub limit: Option, +} + +// ── Handlers ──────────────────────────────────────────────────────── + +/// GET /api/webhooks/event-types +#[utoipa::path( + get, + path = "/api/webhooks/event-types", + tag = "Webhook endpoints", + operation_id = "listWebhookEventTypes", + summary = "List event types", + description = "Every event type CoderHelm sends, with an example event. The `webhooks` section of this document has each one's schema.", + responses( + (status = 200, description = "The catalog.", body = inline(Object), + example = json!({ "api_version": "2026-10-26", "event_types": [{ "type": "run.completed", "group": "Runs", "summary": "A run finished", "description": "…", "example": {} }] })), + ), + security(("api_key" = ["webhooks"])), +)] +pub async fn event_types(Extension(claims): Extension) -> Reply { + claims.require_role(3).map_err(admins_only)?; + let list: Vec = catalog::EVENTS + .iter() + .map(|e| { + json!({ + "type": e.name, + "group": e.group, + "summary": e.summary, + "description": e.description, + "subscribable": e.name != catalog::TEST_EVENT, + "example": catalog::example_event(e.name), + }) + }) + .collect(); + Ok(Json( + json!({ "api_version": catalog::API_VERSION, "event_types": list }), + )) +} + +/// GET /api/webhooks/endpoints +#[utoipa::path( + get, + path = "/api/webhooks/endpoints", + tag = "Webhook endpoints", + operation_id = "listWebhookEndpoints", + summary = "List webhook endpoints", + description = "The team's webhook endpoints, oldest first. Secrets are never listed.", + responses( + (status = 200, description = "The endpoints.", body = inline(Object), + example = json!({ "endpoints": [{ "id": "ep_01jbendpt4a7b0c3d6e9f2g5h8", "url": "https://hooks.example.com/coderhelm", "description": "Deploy bot", "events": ["*"], "enabled": true, "disabled_reason": "", "secret_hint": "whsec_…Q2c=", "created_at": "2026-10-20T09:00:00Z", "created_by": "lead@example.com", "updated_at": "2026-10-20T09:00:00Z" }], "max": 20 })), + ), + security(("api_key" = ["webhooks"])), +)] +pub async fn list_endpoints( + State(state): State>, + Extension(claims): Extension, +) -> Reply { + claims.require_role(3).map_err(admins_only)?; + let all = endpoint::list( + &state.dynamo, + &state.config.settings_table_name, + &claims.team_id, + ) + .await + .map_err(|e| internal("Failed to list webhook endpoints", e))?; + Ok(Json(json!({ + "endpoints": all.iter().map(|s| view(&s.endpoint)).collect::>(), + "max": endpoint::MAX_PER_TEAM, + "disable_after_days": webhooks::deliver::DISABLE_AFTER_DAYS, + "retention_days": deliveries::RETENTION_DAYS, + }))) +} + +/// POST /api/webhooks/endpoints +#[utoipa::path( + post, + path = "/api/webhooks/endpoints", + tag = "Webhook endpoints", + operation_id = "createWebhookEndpoint", + summary = "Create a webhook endpoint", + description = "Adds an endpoint and makes its signing secret, which this answer shows once. \ + The address must be `https://` and on the public internet: private, local and cloud \ + metadata addresses are refused here and again before every delivery. A team has at most \ + 20 endpoints.", + request_body = CreateEndpointBody, + responses( + (status = 201, description = "Created. Keep the secret.", body = CreatedEndpoint), + (status = 400, description = "The address, events or description were refused; `field` names which.", body = crate::openapi::ErrorBody), + (status = 409, description = "The team already has 20 endpoints.", body = crate::openapi::ErrorBody), + ), + security(("api_key" = ["webhooks"])), +)] +pub async fn create_endpoint( + State(state): State>, + Extension(claims): Extension, + Json(body): Json, +) -> Result<(StatusCode, Json), ApiError> { + claims.require_role(3).map_err(admins_only)?; + let table = &state.config.settings_table_name; + let now = chrono::Utc::now(); + let input = endpoint::Input { + url: Some(body.url), + description: body.description, + events: body.events, + enabled: body.enabled, + }; + let mut e = + endpoint::new_endpoint(&input, &claims.display_name(), &now_secs(now)).map_err(invalid)?; + check_public(&e.url).await?; + let existing = endpoint::list(&state.dynamo, table, &claims.team_id) + .await + .map_err(|e| internal("Failed to list webhook endpoints", e))?; + if existing.len() >= endpoint::MAX_PER_TEAM { + return Err(fail( + StatusCode::CONFLICT, + &format!( + "A team can have {} webhook endpoints. Delete one first.", + endpoint::MAX_PER_TEAM + ), + )); + } + let (secret, sealed) = endpoint::fresh_secret(&kms(&state), &claims.team_id, &e.id) + .await + .map_err(|err| internal("Failed to seal a webhook secret", err))?; + e.secret_hint = webhooks::sign::hint(&secret); + let st = endpoint::Stored { + endpoint: e, + secret_sealed: sealed, + previous_secret_sealed: String::new(), + }; + roles::record( + &state, + &claims, + AuditEntry { + action: "webhook_endpoint_created", + role_id: &st.endpoint.id, + role_name: &st.endpoint.url, + detail: format!("Events: {}", st.endpoint.events.join(", ")), + }, + ) + .await?; + endpoint::put(&state.dynamo, table, &claims.team_id, &st) + .await + .map_err(|e| internal("Failed to save a webhook endpoint", e))?; + Ok(( + StatusCode::CREATED, + Json(json!({ "endpoint": view(&st.endpoint), "secret": secret })), + )) +} + +/// GET /api/webhooks/endpoints/:endpoint_id +#[utoipa::path( + get, + path = "/api/webhooks/endpoints/{endpoint_id}", + tag = "Webhook endpoints", + operation_id = "getWebhookEndpoint", + summary = "Get a webhook endpoint", + description = "One endpoint, with its health: when it last delivered, and since when it has been failing, if it is.", + params(("endpoint_id" = String, Path, description = "The endpoint's id.", example = "ep_01jbendpt4a7b0c3d6e9f2g5h8")), + responses( + (status = 200, description = "The endpoint.", body = WebhookEndpoint), + (status = 404, description = "No such endpoint on this team.", body = crate::openapi::ErrorBody), + ), + security(("api_key" = ["webhooks"])), +)] +pub async fn get_endpoint( + State(state): State>, + Extension(claims): Extension, + Path(endpoint_id): Path, +) -> Reply { + claims.require_role(3).map_err(admins_only)?; + let st = load(&state, &claims.team_id, &endpoint_id).await?; + Ok(Json(view(&st.endpoint))) +} + +/// PUT /api/webhooks/endpoints/:endpoint_id +#[utoipa::path( + put, + path = "/api/webhooks/endpoints/{endpoint_id}", + tag = "Webhook endpoints", + operation_id = "updateWebhookEndpoint", + summary = "Update a webhook endpoint", + description = "Changes the address, description, events, or turns the endpoint on or off. Fields left out keep their value. Turning an endpoint back on starts its failure count again; events missed while it was off are not sent by themselves (replay them).", + params(("endpoint_id" = String, Path, description = "The endpoint's id.", example = "ep_01jbendpt4a7b0c3d6e9f2g5h8")), + request_body = UpdateEndpointBody, + responses( + (status = 200, description = "The endpoint as saved.", body = WebhookEndpoint), + (status = 400, description = "A field was refused; `field` names which.", body = crate::openapi::ErrorBody), + (status = 404, description = "No such endpoint on this team.", body = crate::openapi::ErrorBody), + ), + security(("api_key" = ["webhooks"])), +)] +pub async fn update_endpoint( + State(state): State>, + Extension(claims): Extension, + Path(endpoint_id): Path, + Json(body): Json, +) -> Reply { + claims.require_role(3).map_err(admins_only)?; + let mut st = load(&state, &claims.team_id, &endpoint_id).await?; + let input = endpoint::Input { + url: body.url, + description: body.description, + events: body.events, + enabled: body.enabled, + }; + let old_url = st.endpoint.url.clone(); + endpoint::apply_input(&mut st.endpoint, &input, &now_secs(chrono::Utc::now())) + .map_err(invalid)?; + if st.endpoint.url != old_url { + check_public(&st.endpoint.url).await?; + } + endpoint::put( + &state.dynamo, + &state.config.settings_table_name, + &claims.team_id, + &st, + ) + .await + .map_err(|e| internal("Failed to save a webhook endpoint", e))?; + Ok(Json(view(&st.endpoint))) +} + +/// DELETE /api/webhooks/endpoints/:endpoint_id +#[utoipa::path( + delete, + path = "/api/webhooks/endpoints/{endpoint_id}", + tag = "Webhook endpoints", + operation_id = "deleteWebhookEndpoint", + summary = "Delete a webhook endpoint", + description = "Stops all deliveries to it, including retries already queued.", + params(("endpoint_id" = String, Path, description = "The endpoint's id.", example = "ep_01jbendpt4a7b0c3d6e9f2g5h8")), + responses( + (status = 200, description = "Deleted.", body = inline(Object), example = json!({ "deleted": true })), + (status = 404, description = "No such endpoint on this team.", body = crate::openapi::ErrorBody), + ), + security(("api_key" = ["webhooks"])), +)] +pub async fn delete_endpoint( + State(state): State>, + Extension(claims): Extension, + Path(endpoint_id): Path, +) -> Reply { + claims.require_role(3).map_err(admins_only)?; + let st = load(&state, &claims.team_id, &endpoint_id).await?; + roles::record( + &state, + &claims, + AuditEntry { + action: "webhook_endpoint_deleted", + role_id: &st.endpoint.id, + role_name: &st.endpoint.url, + detail: String::new(), + }, + ) + .await?; + endpoint::delete( + &state.dynamo, + &state.config.settings_table_name, + &claims.team_id, + &endpoint_id, + ) + .await + .map_err(|e| internal("Failed to delete a webhook endpoint", e))?; + Ok(Json(json!({ "deleted": true }))) +} + +/// GET /api/webhooks/endpoints/:endpoint_id/secret +#[utoipa::path( + get, + path = "/api/webhooks/endpoints/{endpoint_id}/secret", + tag = "Webhook endpoints", + operation_id = "getWebhookSecret", + summary = "Reveal the signing secret", + description = "The endpoint's current signing secret. Each reveal is written to the team's audit log.", + params(("endpoint_id" = String, Path, description = "The endpoint's id.", example = "ep_01jbendpt4a7b0c3d6e9f2g5h8")), + responses( + (status = 200, description = "The secret.", body = SecretView), + (status = 404, description = "No such endpoint on this team.", body = crate::openapi::ErrorBody), + ), + security(("api_key" = ["webhooks"])), +)] +pub async fn reveal_secret( + State(state): State>, + Extension(claims): Extension, + Path(endpoint_id): Path, +) -> Reply { + claims.require_role(3).map_err(admins_only)?; + let st = load(&state, &claims.team_id, &endpoint_id).await?; + let secret = endpoint::open( + &kms(&state), + &claims.team_id, + &st.endpoint.id, + &st.secret_sealed, + ) + .await + .map_err(|e| internal("Failed to open a webhook secret", e))?; + roles::record( + &state, + &claims, + AuditEntry { + action: "webhook_secret_revealed", + role_id: &st.endpoint.id, + role_name: &st.endpoint.url, + detail: String::new(), + }, + ) + .await?; + let live = endpoint::previous_live(&st, chrono::Utc::now()); + Ok(Json(json!({ + "secret": secret, + "previous_secret_expires_at": if live { st.endpoint.previous_secret_expires_at.clone() } else { None }, + }))) +} + +/// POST /api/webhooks/endpoints/:endpoint_id/secret/rotate +#[utoipa::path( + post, + path = "/api/webhooks/endpoints/{endpoint_id}/secret/rotate", + tag = "Webhook endpoints", + operation_id = "rotateWebhookSecret", + summary = "Rotate the signing secret", + description = "Makes a new secret. For `overlap_hours` (24 unless set) every request carries two \ + signatures, one per secret, so a receiver verifying with either keeps working while you \ + update it. Then only the new secret signs.", + params(("endpoint_id" = String, Path, description = "The endpoint's id.", example = "ep_01jbendpt4a7b0c3d6e9f2g5h8")), + request_body = RotateBody, + responses( + (status = 200, description = "The new secret, shown once here.", body = RotatedSecret), + (status = 400, description = "`overlap_hours` is outside 0 to 168.", body = crate::openapi::ErrorBody), + (status = 404, description = "No such endpoint on this team.", body = crate::openapi::ErrorBody), + ), + security(("api_key" = ["webhooks"])), +)] +pub async fn rotate_secret( + State(state): State>, + Extension(claims): Extension, + Path(endpoint_id): Path, + body: Option>, +) -> Reply { + claims.require_role(3).map_err(admins_only)?; + let hours = body + .and_then(|Json(b)| b.overlap_hours) + .unwrap_or(endpoint::DEFAULT_OVERLAP_HOURS); + if !(0..=endpoint::MAX_OVERLAP_HOURS).contains(&hours) { + return Err(fail( + StatusCode::BAD_REQUEST, + "The overlap is 0 to 168 hours.", + )); + } + let mut st = load(&state, &claims.team_id, &endpoint_id).await?; + let (secret, sealed) = endpoint::fresh_secret(&kms(&state), &claims.team_id, &st.endpoint.id) + .await + .map_err(|e| internal("Failed to seal a webhook secret", e))?; + endpoint::rotate(&mut st, &secret, sealed, hours, chrono::Utc::now()); + roles::record( + &state, + &claims, + AuditEntry { + action: "webhook_secret_rotated", + role_id: &st.endpoint.id, + role_name: &st.endpoint.url, + detail: format!("Old secret signs for {hours} more hours"), + }, + ) + .await?; + endpoint::put( + &state.dynamo, + &state.config.settings_table_name, + &claims.team_id, + &st, + ) + .await + .map_err(|e| internal("Failed to save a webhook endpoint", e))?; + Ok(Json(json!({ + "secret": secret, + "previous_secret_expires_at": st.endpoint.previous_secret_expires_at, + }))) +} + +fn ctx<'a>(state: &'a AppState, cipher: &'a common::mcp_credentials::Kms<'a>) -> webhooks::Ctx<'a> { + webhooks::Ctx { + dynamo: &state.dynamo, + table: &state.config.settings_table_name, + cipher, + sqs: &state.sqs, + queue_url: &state.config.webhook_queue_url, + dns: &webhooks::deliver::SystemDns, + } +} + +/// POST /api/webhooks/endpoints/:endpoint_id/test +#[utoipa::path( + post, + path = "/api/webhooks/endpoints/{endpoint_id}/test", + tag = "Webhook endpoints", + operation_id = "sendWebhookTest", + summary = "Send a test event", + description = "Sends one `webhook.test` event to the endpoint now, signed like every other event, \ + and answers with the attempt. A test is tried once (no retries) and is sent even when the \ + endpoint is off or doesn't subscribe to it.", + params(("endpoint_id" = String, Path, description = "The endpoint's id.", example = "ep_01jbendpt4a7b0c3d6e9f2g5h8")), + responses( + (status = 200, description = "The delivery, delivered or not.", body = WebhookDelivery), + (status = 404, description = "No such endpoint on this team.", body = crate::openapi::ErrorBody), + ), + security(("api_key" = ["webhooks"])), +)] +pub async fn send_test( + State(state): State>, + Extension(claims): Extension, + Path(endpoint_id): Path, +) -> Reply { + claims.require_role(3).map_err(admins_only)?; + let st = load(&state, &claims.team_id, &endpoint_id).await?; + let e = event::Event::new( + &claims.team_id, + catalog::TEST_EVENT, + json!({ + "message": "A test event from CoderHelm. Nothing happened.", + "endpoint_id": st.endpoint.id, + }), + ); + let body = e.body(); + let cipher = kms(&state); + let c = ctx(&state, &cipher); + // Kept like any event, so its delivery can be sent again. + if let Err(err) = event::keep(c.dynamo, c.table, &e, &body).await { + tracing::warn!(error = %err, "Could not keep a test event"); + } + let mut d = webhooks::deliver::new_record(&st.endpoint, &e.id, &e.event_type, body.as_bytes()); + webhooks::attempt(&c, &claims.team_id, &st, &e.id, &body, &mut d, Mode::Manual).await; + Ok(Json(delivery_view(&d))) +} + +/// GET /api/webhooks/endpoints/:endpoint_id/deliveries +#[utoipa::path( + get, + path = "/api/webhooks/endpoints/{endpoint_id}/deliveries", + tag = "Webhook endpoints", + operation_id = "listWebhookDeliveries", + summary = "List an endpoint's deliveries", + description = "The endpoint's deliveries, newest first, each with every attempt. Kept 14 days.", + params( + ("endpoint_id" = String, Path, description = "The endpoint's id.", example = "ep_01jbendpt4a7b0c3d6e9f2g5h8"), + DeliveryQuery, + ), + responses( + (status = 200, description = "The deliveries.", body = inline(Object), + example = json!({ "deliveries": [{ "id": "01JBDLVR5T8V1W4X7Y0Z3A6B9C", "event_id": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", "event": "run.completed", "status": "handled", "outcome": "Delivered (200)", "reason": "", "reason_message": "", "reason_fix": "", "attempts": [{ "at": "2026-10-26T14:31:47.901Z", "code": 200, "duration_ms": 87, "error": "" }], "next_retry_at": null, "created_at": "2026-10-26T14:31:47.780Z" }] })), + (status = 404, description = "No such endpoint on this team.", body = crate::openapi::ErrorBody), + ), + security(("api_key" = ["webhooks"])), +)] +pub async fn list_endpoint_deliveries( + State(state): State>, + Extension(claims): Extension, + Path(endpoint_id): Path, + Query(q): Query, +) -> Reply { + claims.require_role(3).map_err(admins_only)?; + load(&state, &claims.team_id, &endpoint_id).await?; + let f = Filter { + source: Some(webhooks::deliver::SOURCE.into()), + status: q.status, + endpoint: Some(endpoint_id), + ..Default::default() + }; + let limit = q.limit.unwrap_or(25).clamp(1, 100); + let items = deliveries::list( + &state.dynamo, + &state.config.settings_table_name, + &claims.team_id, + &f, + limit, + ) + .await + .map_err(|e| internal("Failed to list webhook deliveries", e))?; + Ok(Json(json!({ + "deliveries": items.iter().map(delivery_view).collect::>(), + }))) +} + +/// Sends a kept delivery's event once more, now. Shared with the Deliveries +/// page's Redeliver. +pub async fn resend_record( + state: &AppState, + team_id: &str, + mut d: Delivery, +) -> Result { + if d.source != webhooks::deliver::SOURCE || d.endpoint_id.is_empty() { + return Err(fail( + StatusCode::BAD_REQUEST, + "This delivery isn't a webhook.", + )); + } + let st = load(state, team_id, &d.endpoint_id).await?; + let kept = event::get( + &state.dynamo, + &state.config.settings_table_name, + team_id, + &d.external_id, + ) + .await + .map_err(|e| internal("Failed to read a kept event", e))? + .ok_or_else(|| { + fail( + StatusCode::GONE, + "The event is no longer kept (events are kept 14 days).", + ) + })?; + let cipher = kms(state); + let c = ctx(state, &cipher); + webhooks::attempt( + &c, + team_id, + &st, + &kept.event.id, + &kept.body, + &mut d, + Mode::Manual, + ) + .await; + Ok(d) +} + +/// POST /api/webhooks/endpoints/:endpoint_id/deliveries/:delivery_id/resend +#[utoipa::path( + post, + path = "/api/webhooks/endpoints/{endpoint_id}/deliveries/{delivery_id}/resend", + tag = "Webhook endpoints", + operation_id = "resendWebhookDelivery", + summary = "Resend a delivery", + description = "Sends the same event (the same body and `webhook-id`, signed now) to the endpoint \ + once more and adds the attempt to the delivery. Works on any delivery whose event is still \ + kept (14 days), delivered or not.", + params( + ("endpoint_id" = String, Path, description = "The endpoint's id.", example = "ep_01jbendpt4a7b0c3d6e9f2g5h8"), + ("delivery_id" = String, Path, description = "The delivery's id.", example = "01JBDLVR5T8V1W4X7Y0Z3A6B9C"), + ), + responses( + (status = 200, description = "The delivery with the new attempt.", body = WebhookDelivery), + (status = 404, description = "No such endpoint or delivery.", body = crate::openapi::ErrorBody), + (status = 410, description = "The event is no longer kept.", body = crate::openapi::ErrorBody), + ), + security(("api_key" = ["webhooks"])), +)] +pub async fn resend_delivery( + State(state): State>, + Extension(claims): Extension, + Path((endpoint_id, delivery_id)): Path<(String, String)>, +) -> Reply { + claims.require_role(3).map_err(admins_only)?; + let d = deliveries::get( + &state.dynamo, + &state.config.settings_table_name, + &claims.team_id, + &delivery_id, + ) + .await + .map_err(|e| internal("Failed to read a delivery", e))? + .filter(|d| d.endpoint_id == endpoint_id) + .ok_or_else(|| fail(StatusCode::NOT_FOUND, "No such delivery for this endpoint."))?; + let d = resend_record(&state, &claims.team_id, d).await?; + Ok(Json(delivery_view(&d))) +} + +/// The most events one replay sends. +pub const MAX_REPLAY: usize = 500; + +/// Events whose last delivery to the endpoint went fine, from its records. +fn delivered_ids(records: &[Delivery]) -> std::collections::HashSet { + records + .iter() + .filter(|d| d.status == Status::Handled || d.status == Status::Pending) + .map(|d| d.external_id.clone()) + .collect() +} + +/// POST /api/webhooks/endpoints/:endpoint_id/replay +#[utoipa::path( + post, + path = "/api/webhooks/endpoints/{endpoint_id}/replay", + tag = "Webhook endpoints", + operation_id = "replayWebhookEvents", + summary = "Replay events", + description = "Sends the kept events made in a time range to this endpoint again, each as a new \ + delivery with retries, oldest first. Only event types the endpoint subscribes to now are \ + sent. Events carry their original `id`, so a receiver that already handled one can skip it. \ + At most 500 per call; events are kept 14 days.", + params(("endpoint_id" = String, Path, description = "The endpoint's id.", example = "ep_01jbendpt4a7b0c3d6e9f2g5h8")), + request_body = ReplayBody, + responses( + (status = 202, description = "Queued.", body = ReplayResult), + (status = 400, description = "The range is not valid, or the endpoint is off.", body = crate::openapi::ErrorBody), + (status = 404, description = "No such endpoint on this team.", body = crate::openapi::ErrorBody), + ), + security(("api_key" = ["webhooks"])), +)] +pub async fn replay( + State(state): State>, + Extension(claims): Extension, + Path(endpoint_id): Path, + Json(body): Json, +) -> Result<(StatusCode, Json), ApiError> { + claims.require_role(3).map_err(admins_only)?; + let st = load(&state, &claims.team_id, &endpoint_id).await?; + if !st.endpoint.enabled { + return Err(fail( + StatusCode::BAD_REQUEST, + "Turn the endpoint on before replaying events to it.", + )); + } + let now = chrono::Utc::now(); + let (since, until) = replay_range(&body, now).map_err(|m| fail(StatusCode::BAD_REQUEST, &m))?; + let table = &state.config.settings_table_name; + let kept = event::list_range( + &state.dynamo, + table, + &claims.team_id, + since, + until, + MAX_REPLAY * 4, + ) + .await + .map_err(|e| internal("Failed to list kept events", e))?; + let found = kept.len(); + let mut picked = webhooks::replayable(&st.endpoint, &kept); + if body.only_failed { + let records = deliveries::list( + &state.dynamo, + table, + &claims.team_id, + &Filter { + source: Some(webhooks::deliver::SOURCE.into()), + endpoint: Some(endpoint_id.clone()), + since: Some(now_secs(since)), + ..Default::default() + }, + 1000, + ) + .await + .map_err(|e| internal("Failed to list webhook deliveries", e))?; + let ok = delivered_ids(&records); + picked.retain(|k| !ok.contains(&k.event.id)); + } + let capped = picked.len() > MAX_REPLAY; + let to_send: Vec = picked.into_iter().take(MAX_REPLAY).cloned().collect(); + let cipher = kms(&state); + let c = ctx(&state, &cipher); + let queued = webhooks::replay(&c, &claims.team_id, &st.endpoint, &to_send) + .await + .map_err(|e| internal("Failed to queue a replay", e))?; + Ok(( + StatusCode::ACCEPTED, + Json(json!({ "queued": queued, "found": found, "capped": capped })), + )) +} + +/// The range a replay covers, checked: `since` within the kept days and +/// before `until`. +pub fn replay_range( + body: &ReplayBody, + now: chrono::DateTime, +) -> Result<(chrono::DateTime, chrono::DateTime), String> { + let parse = |s: &str| { + chrono::DateTime::parse_from_rfc3339(s.trim()) + .map(|t| t.with_timezone(&chrono::Utc)) + .map_err(|_| format!("\"{s}\" isn't an RFC 3339 time.")) + }; + let since = parse(&body.since)?; + let until = match body.until.as_deref() { + Some(u) if !u.trim().is_empty() => parse(u)?, + _ => now, + }; + if since >= until { + return Err("`since` must be before `until`.".into()); + } + if since < now - chrono::Duration::days(deliveries::RETENTION_DAYS) { + return Err(format!( + "Events are kept {} days; start the range after that.", + deliveries::RETENTION_DAYS + )); + } + Ok((since, until.min(now))) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn body(since: &str, until: Option<&str>) -> ReplayBody { + ReplayBody { + since: since.into(), + until: until.map(Into::into), + only_failed: false, + } + } + + #[test] + fn plan_events_carry_the_documented_fields() { + let d = plan_approved_data( + "01JBPLAN", + "Move exports", + 4, + "lead@example.com", + "https://app.example.com/", + ); + let schema = catalog::data_schema(catalog::find("plan.approved").unwrap()); + let props = schema["properties"].as_object().unwrap(); + assert_eq!( + props.keys().collect::>(), + d.as_object() + .unwrap() + .keys() + .collect::>() + ); + assert_eq!( + d["url"], + "https://app.example.com/plans/detail/?id=01JBPLAN" + ); + let items = vec![std::collections::HashMap::from([ + ( + "sk".to_string(), + aws_sdk_dynamodb::types::AttributeValue::S("PLAN#p1".into()), + ), + ( + "title".to_string(), + aws_sdk_dynamodb::types::AttributeValue::S("Move exports".into()), + ), + ])]; + assert_eq!(plan_title(&items, "p1"), "Move exports"); + assert_eq!(plan_title(&items, "p2"), ""); + } + + #[test] + fn a_replay_range_stays_inside_the_kept_days() { + let now = chrono::DateTime::parse_from_rfc3339("2026-10-26T12:00:00Z") + .unwrap() + .with_timezone(&chrono::Utc); + let (s, u) = replay_range(&body("2026-10-25T00:00:00Z", None), now).unwrap(); + assert_eq!( + (s.to_rfc3339(), u), + ("2026-10-25T00:00:00+00:00".into(), now) + ); + assert!(replay_range(&body("2026-10-01T00:00:00Z", None), now).is_err()); + assert!(replay_range( + &body("2026-10-26T11:00:00Z", Some("2026-10-26T10:00:00Z")), + now + ) + .is_err()); + assert!(replay_range(&body("yesterday", None), now).is_err()); + let (_, u) = replay_range( + &body("2026-10-25T00:00:00Z", Some("2027-01-01T00:00:00Z")), + now, + ) + .unwrap(); + assert_eq!(u, now, "never past now"); + } + + #[test] + fn only_failed_skips_events_already_delivered_or_on_their_way() { + let rec = |ev: &str, st: Status| { + let mut d = Delivery::new( + deliveries::Direction::Outbound, + "webhook", + "run.failed", + "h", + ); + d.external_id = ev.into(); + d.status = st; + d + }; + let ok = delivered_ids(&[ + rec("evt_a", Status::Handled), + rec("evt_b", Status::Failed), + rec("evt_c", Status::Pending), + ]); + assert!(ok.contains("evt_a") && ok.contains("evt_c") && !ok.contains("evt_b")); + } +} diff --git a/services/worker/src/agent/policy.rs b/services/worker/src/agent/policy.rs index 7c0b3b21e..43de0e4fa 100644 --- a/services/worker/src/agent/policy.rs +++ b/services/worker/src/agent/policy.rs @@ -430,8 +430,11 @@ pub async fn end_run_for_stop(state: &WorkerState, team_id: &str, run_id: &str, .ended_values() .send() .await; - if let Err(e) = r { - tracing::warn!(run_id, error = %e, "Couldn't record why the run stopped"); + match r { + Ok(_) => { + crate::passes::webhooks::emit_run(state, team_id, run_id, status).await; + } + Err(e) => tracing::warn!(run_id, error = %e, "Couldn't record why the run stopped"), } } diff --git a/services/worker/src/clients/email.rs b/services/worker/src/clients/email.rs index d4c625250..dfeb4e54e 100644 --- a/services/worker/src/clients/email.rs +++ b/services/worker/src/clients/email.rs @@ -21,6 +21,22 @@ pub enum EmailEvent { used_tokens: String, limit_tokens: String, }, + /// A webhook endpoint failed for days and was turned off. Goes to the + /// team's admins and owners only. + WebhookDisabled { + url: String, + host: String, + description: String, + failing_since: String, + days: i64, + }, +} + +impl EmailEvent { + /// Only admins and owners get it. + fn admins_only(&self) -> bool { + matches!(self, EmailEvent::WebhookDisabled { .. }) + } } /// Send a templated email to all users of a team who have the notification enabled. @@ -68,6 +84,24 @@ pub async fn send_notification( }) .to_string(), ), + EmailEvent::WebhookDisabled { + url, + host, + description, + failing_since, + days, + } => ( + "webhook-disabled", + "", + json!({ + "url": url, + "host": host, + "description": description, + "failing_since": failing_since, + "days": days, + }) + .to_string(), + ), }; let template_name = format!("{}-{}", state.config.ses_template_prefix, template_suffix); @@ -99,6 +133,16 @@ pub async fn send_notification( Some(id) => id.clone(), None => continue, }; + if event.admins_only() { + let role = user_item + .get("role") + .and_then(|v| v.as_s().ok()) + .map(String::as_str) + .unwrap_or(""); + if !matches!(role, "admin" | "owner") { + continue; + } + } // Check notification preferences (skip for welcome emails — always send) if !pref_field.is_empty() { diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index f67e1bd41..c8d6697a7 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -506,6 +506,18 @@ async fn handle_message(state: Arc, message: models::WorkerMessage) error!("Health check failed: {e:?}"); } } + models::WorkerMessage::WebhookEmit(msg) => { + info!(team_id = %msg.event.team_id, event = %msg.event.event_type, id = %msg.event.id, "Webhook event"); + if let Err(e) = passes::webhooks::dispatch(&state, msg).await { + error!("Webhook dispatch failed: {e:?}"); + } + } + models::WorkerMessage::WebhookSend(msg) => { + info!(team_id = %msg.team_id, endpoint = %msg.endpoint_id, delivery = %msg.delivery_id, "Webhook retry"); + if let Err(e) = passes::webhooks::send(&state, msg).await { + error!("Webhook send failed: {e:?}"); + } + } models::WorkerMessage::RelayRetry(msg) => { info!(install = %msg.install_id, delivery = %msg.delivery_id, "Relay retry"); if let Err(e) = passes::relay_retry::run(&state, msg).await { diff --git a/services/worker/src/models.rs b/services/worker/src/models.rs index 28b30ebb0..919554e70 100644 --- a/services/worker/src/models.rs +++ b/services/worker/src/models.rs @@ -38,6 +38,8 @@ pub struct Config { pub ci_fix_queue_url: String, pub ticket_queue_url: String, pub feedback_queue_url: String, + /// Outbound webhook events and their retries. Empty: nothing is emitted. + pub webhook_queue_url: String, /// The shared dead-letter queue (the DLQ cleanup reads it). Empty: the /// cleanup does nothing. pub dlq_url: String, @@ -95,6 +97,7 @@ impl Config { ci_fix_queue_url: std::env::var("CI_FIX_QUEUE_URL").unwrap_or_default(), ticket_queue_url: std::env::var("TICKET_QUEUE_URL").unwrap_or_default(), feedback_queue_url: std::env::var("FEEDBACK_QUEUE_URL").unwrap_or_default(), + webhook_queue_url: std::env::var("WEBHOOK_QUEUE_URL").unwrap_or_default(), dlq_url: std::env::var("DLQ_URL").unwrap_or_default(), sandbox_bucket_name: std::env::var("SANDBOX_BUCKET_NAME").unwrap_or_default(), sandbox_project_name: std::env::var("SANDBOX_PROJECT_NAME").unwrap_or_default(), diff --git a/services/worker/src/passes/feedback.rs b/services/worker/src/passes/feedback.rs index 156b7fc34..36ed8d026 100644 --- a/services/worker/src/passes/feedback.rs +++ b/services/worker/src/passes/feedback.rs @@ -2497,7 +2497,7 @@ pub(crate) async fn close_own_pr_outside( async fn finish_without_change(state: &WorkerState, msg: &FeedbackMessage) { let now = chrono::Utc::now().to_rfc3339(); - let _ = state + let wrote = state .dynamo .update_item() .table_name(&state.config.runs_table_name) @@ -2526,7 +2526,11 @@ async fn finish_without_change(state: &WorkerState, msg: &FeedbackMessage) { ) .expression_attribute_values(":t", aws_sdk_dynamodb::types::AttributeValue::S(now)) .send() - .await; + .await + .is_ok(); + if wrote { + super::webhooks::emit_run(state, &msg.team_id, &msg.run_id, "completed").await; + } } /// While a run is awaiting CI or running, the resume flow owns CI fixing @@ -2642,7 +2646,7 @@ async fn hand_off_to_human(state: &WorkerState, github: &GitHubClient, msg: &Fee // (2) Finalize the run — completed, stale error cleared, never clobbering a // cancel. Safe to repeat on redelivery. let now = chrono::Utc::now().to_rfc3339(); - let _ = state + let wrote = state .dynamo .update_item() .table_name(&state.config.runs_table_name) @@ -2662,7 +2666,11 @@ async fn hand_off_to_human(state: &WorkerState, github: &GitHubClient, msg: &Fee .expression_attribute_values(":t", AttributeValue::S(now)) .ended_values() .send() - .await; + .await + .is_ok(); + if wrote { + super::webhooks::emit_run(state, &msg.team_id, &msg.run_id, "completed").await; + } // When it was handed off (the first time only), for the weekly summary. super::record_ci_outcome( state, diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 54f14926e..a5a7ef72f 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -763,6 +763,7 @@ pub mod tool_proposals; mod triage; pub mod usage_reconcile; pub mod web_check; +pub mod webhooks; pub mod weekly_summary; pub mod write_guard; @@ -2163,6 +2164,7 @@ async fn run_passes( ) .send() .await; + self::webhooks::emit_run(state, &msg.team_id, run_id, "completed").await; // Update analytics counters let analytics_month = chrono::Utc::now().format("%Y-%m").to_string(); @@ -3486,7 +3488,7 @@ async fn run_passes( let duration = start.elapsed().as_secs(); let cost = usage.estimated_cost(); let now = chrono::Utc::now().to_rfc3339(); - let _ = state + let wrote = state .dynamo .update_item() .table_name(&state.config.runs_table_name) @@ -3515,7 +3517,11 @@ async fn run_passes( .expression_attribute_values(":t", attr_s(&now)) .expression_attribute_values(":cp", attr_s("done")) .send() - .await; + .await + .is_ok(); + if wrote { + self::webhooks::emit_run(state, &msg.team_id, run_id, "completed").await; + } close_memory(state, agent_memory.take()).await; return Ok(()); } @@ -3602,6 +3608,7 @@ async fn run_passes( .expression_attribute_values(":cp", attr_s("done")) .send() .await; + self::webhooks::emit_run(state, &msg.team_id, run_id, "needs_input").await; close_memory(state, agent_memory.take()).await; return Ok(()); } @@ -3941,6 +3948,14 @@ async fn run_passes( ) .await; info!(run_id, pr_url = %pr_result.pr_url, "Draft PR created"); + self::webhooks::emit_pr_opened( + state, + msg, + run_id, + &format!("{}/{}", msg.repo_owner, msg.repo_name), + &pr_result, + ) + .await; add_progress_note( state, &msg.team_id, @@ -4464,6 +4479,14 @@ async fn run_repo_pipeline( .await; info!(run_id, repo = %format!("{repo_owner}/{repo_name}"), pr_url = %pr_result.pr_url, "Draft PR created"); + self::webhooks::emit_pr_opened( + state, + msg, + run_id, + &format!("{repo_owner}/{repo_name}"), + &pr_result, + ) + .await; add_progress_note( state, &msg.team_id, @@ -4582,6 +4605,7 @@ async fn create_run_record( } } put.send().await?; + self::webhooks::emit_run(state, &msg.team_id, run_id, "running").await; // Increment analytics counters (current month + all-time). A counter is // best effort: it must never stop a run whose record is already written. @@ -5039,6 +5063,7 @@ async fn mark_run_needs_input( ) .send() .await; + self::webhooks::emit_run(state, &msg.team_id, run_id, "needs_input").await; // Update analytics counters let analytics_month = chrono::Utc::now().format("%Y-%m").to_string(); @@ -5371,7 +5396,7 @@ async fn fail_run( ) .await { - Ok(true) => {} + Ok(true) => self::webhooks::emit_run(state, &msg.team_id, run_id, "failed").await, // Cancelled or merged meanwhile: nothing failed, so nothing to tell. Ok(false) => return, Err(e) => warn!(run_id, error = %e, "Could not mark the run failed"), @@ -7602,6 +7627,7 @@ async fn salvage_timeout_pr( .expression_attribute_values(":err", attr_s("Partial implementation — agent timed out")) .send() .await; + self::webhooks::emit_run(state, &msg.team_id, run_id, "completed").await; Ok(pr_url) } diff --git a/services/worker/src/passes/plugins.rs b/services/worker/src/passes/plugins.rs index 63bb68949..8e7c91c40 100644 --- a/services/worker/src/passes/plugins.rs +++ b/services/worker/src/passes/plugins.rs @@ -581,6 +581,13 @@ pub async fn run_plugin(state: &WorkerState, msg: PluginRunMessage) -> Res { for id in &rec.artifacts { notify_review(state, &msg.team_id, id).await; } + // Only teams with plugins on run plugins; the check keeps the event + // behind the same flag even for a run queued before it was turned off. + if let Some(data) = super::webhooks::plugin_run_data(&rec) { + if flag::enabled(&kv, &msg.team_id).await { + super::webhooks::emit(state, &msg.team_id, "plugin.run.completed", data).await; + } + } Ok(()) } diff --git a/services/worker/src/passes/release_notes.rs b/services/worker/src/passes/release_notes.rs index 476947845..a0ebc96ff 100644 --- a/services/worker/src/passes/release_notes.rs +++ b/services/worker/src/passes/release_notes.rs @@ -917,6 +917,36 @@ async fn run_locked( save_record(state, &msg.team_id, &record_sk, tag, &rec).await; } info!(%tag, repo = %format!("{owner}/{repo}"), "Release notes published"); + if msg.resend.is_empty() { + let channels: Vec<&str> = [ + ("github", !release_url.is_empty()), + ( + "confluence", + rec.get("confluence_url").is_some_and(|u| !u.is_empty()), + ), + ( + "email", + rec.get("email_sent_at").is_some_and(|u| !u.is_empty()), + ), + ] + .iter() + .filter(|(_, on)| *on) + .map(|(c, _)| *c) + .collect(); + super::webhooks::emit( + state, + &msg.team_id, + "release_notes.published", + json!({ + "repo": format!("{owner}/{repo}"), + "tag": tag, + "sha": msg.sha, + "release_url": Some(release_url.as_str()).filter(|u| !u.is_empty()), + "channels": channels, + }), + ) + .await; + } // Plugins with a release trigger (a marketing plugin's launch posts) // start from these notes. Only the first publish, never a re-send. if msg.resend.is_empty() { diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 4ed02644f..62157a6d5 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -1824,6 +1824,23 @@ pub async fn run( } // Implement fix + let repo_full = format!("{repo_owner}/{repo_name}"); + let ci_fix = super::webhooks::CiFix { + team_id: &msg.team_id, + run_id: &msg.run_id, + repo: &repo_full, + pr_number, + branch: &branch, + attempt: cycle + 1, + }; + let failing_checks: Vec = events + .iter() + .filter(|e| e.event_type == "ci_failed") + .filter_map(|e| e.payload["workflow_name"].as_str().map(str::to_string)) + .collect::>() + .into_iter() + .collect(); + super::webhooks::emit_ci_fix_started(state, &ci_fix, &failing_checks).await; let pass_start = std::time::Instant::now(); let usage_before = usage.clone(); super::update_pass(state, &msg.team_id, &msg.run_id, "implement").await?; @@ -1923,6 +1940,7 @@ pub async fn run( run_id = msg.run_id, "CI fix produced no changes — completing with PR for human review" ); + super::webhooks::emit_ci_fix_completed(state, &ci_fix, "no_changes", 0).await; super::record_ci_outcome( state, &msg.team_id, @@ -1955,12 +1973,20 @@ pub async fn run( .await; return Ok(()); } + super::webhooks::emit_ci_fix_completed( + state, + &ci_fix, + "pushed", + result.files_modified.len(), + ) + .await; } Err(e) => { if requeue_after_model_error(state, &msg, &*e).await { return Ok(()); } error!(run_id = msg.run_id, error = %e, "CI fix implementation failed — completing with PR for human review"); + super::webhooks::emit_ci_fix_completed(state, &ci_fix, "failed", 0).await; super::record_ci_outcome( state, &msg.team_id, @@ -3392,7 +3418,7 @@ async fn complete_run_with_status( .send() .await; match res { - Ok(_) => {} + Ok(_) => super::webhooks::emit_run(state, &msg.team_id, run_id, status).await, Err(e) if format!("{e:?}").contains("ConditionalCheckFailed") => { info!(run_id, "Run is cancelled — not overwriting with completion"); return Ok(()); @@ -3676,5 +3702,6 @@ async fn set_run_complete( .expression_attribute_values(":d", attr_n(duration)) .send() .await; + super::webhooks::emit_run(state, team_id, run_id, "completed").await; info!(run_id, duration, "Run marked complete (no CI / CI passed)"); } diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index b3f1db8f1..49abf2e2a 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -2915,6 +2915,11 @@ async fn store_review_record( if let Err(e) = put.send().await { warn!(pr = msg.pr_number, error = %e, "Failed to persist review record (non-fatal)"); } + // A posted review is an event for the team's webhooks (an answer to a + // question isn't a review). + if counts.posted && verdict != "QUESTION" { + super::webhooks::emit_review(state, msg, head_sha, verdict, posted_as, risk).await; + } // A small, time-ordered copy for analytics (no body). let stat = common::review_stats::stat_item( &msg.team_id, diff --git a/services/worker/src/passes/webhooks.rs b/services/worker/src/passes/webhooks.rs new file mode 100644 index 000000000..768859e65 --- /dev/null +++ b/services/worker/src/passes/webhooks.rs @@ -0,0 +1,711 @@ +//! Outbound webhooks on the worker: emitting events from the work, sending +//! them (`webhook_emit`), the retries (`webhook_send`), and telling admins +//! when an endpoint is turned off. +//! +//! The rules live in `common::webhooks`; this file only connects them to +//! the worker's clients. + +use std::collections::HashMap; +use std::time::Duration; + +use aws_sdk_dynamodb::types::AttributeValue; +use common::messages::{WebhookEmitMessage, WebhookSendMessage}; +use common::webhooks::{self, endpoint, event, Mode}; +use serde_json::{json, Value}; +use tracing::{info, warn}; + +use crate::WorkerState; + +type Error = Box; + +/// Queues one event for the team's endpoints. Never fails or slows the work +/// for long: a failure is logged. +pub async fn emit(state: &WorkerState, team_id: &str, event_type: &str, data: Value) { + webhooks::emit_event( + &state.sqs, + &state.config.webhook_queue_url, + team_id, + event_type, + data, + ) + .await; +} + +/// The dashboard's address. +fn app_url(state: &WorkerState) -> &'static str { + common::public_urls::app_url(&state.config.stage) +} + +/// A run's `data`, from its record (pure: the tests check it against the +/// catalog's schema). +pub fn run_data(item: &HashMap, status: &str, app: &str) -> Value { + let s = |k: &str| { + item.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + let opt = |k: &str| Some(s(k)).filter(|v| !v.is_empty()); + let pr = item + .get("pr_number") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse::().ok()) + .filter(|n| *n > 0); + let run_id = s("run_id"); + let error = opt("error_message").or_else(|| opt("error")); + let created = opt("created_at").unwrap_or_default(); + json!({ + "run_id": run_id, + "status": status, + "title": s("title"), + "repo": s("repo"), + "source": opt("ticket_source").unwrap_or_else(|| "github".into()), + "ticket_id": s("ticket_id"), + "pr_number": pr, + "pr_url": if pr.is_some() { opt("pr_url") } else { None }, + "branch": opt("branch"), + "error": if matches!(status, "failed" | "needs_input") { error } else { None }, + "url": format!("{}/runs/detail/?id={}", app.trim_end_matches('/'), urlencoding::encode(&run_id)), + "created_at": created.clone(), + "updated_at": opt("updated_at").unwrap_or(created), + }) +} + +/// The `run.*` event a status write means, if any. +pub fn run_event_for(status: &str) -> Option<&'static str> { + match status { + "completed" | "success" => Some("run.completed"), + "failed" => Some("run.failed"), + "needs_input" => Some("run.needs_input"), + "running" => Some("run.created"), + _ => None, + } +} + +/// Emits a `run.*` event for a run, read back from its record so every run +/// event carries the same fields. `status` is what the work just wrote. +pub async fn emit_run(state: &WorkerState, team_id: &str, run_id: &str, status: &str) { + let Some(event_type) = run_event_for(status) else { + return; + }; + if state.config.webhook_queue_url.is_empty() { + return; + } + let read = state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", AttributeValue::S(team_id.into())) + .key("run_id", AttributeValue::S(run_id.into())) + .send(); + let item = match tokio::time::timeout(Duration::from_secs(3), read).await { + Ok(Ok(r)) => r.item().cloned().unwrap_or_default(), + _ => { + warn!(run_id, "Could not read the run for its webhook event"); + HashMap::new() + } + }; + let mut item = item; + item.entry("run_id".into()) + .or_insert_with(|| AttributeValue::S(run_id.into())); + let shown = if status == "success" { + "completed" + } else { + status + }; + emit( + state, + team_id, + event_type, + run_data(&item, shown, app_url(state)), + ) + .await; +} + +/// `pull_request.opened`'s `data` (pure). +pub fn pr_opened_data( + run_id: &str, + repo: &str, + title: &str, + base_branch: &str, + pr: &super::pr::PrResult, +) -> Value { + json!({ + "run_id": run_id, + "repo": repo, + "number": pr.pr_number, + "url": pr.pr_url, + "title": title, + "branch": pr.branch, + "base_branch": Some(base_branch).filter(|b| !b.is_empty()), + "draft": pr.draft, + }) +} + +/// Emits `pull_request.opened` for a PR a run just opened. +pub async fn emit_pr_opened( + state: &WorkerState, + msg: &common::messages::TicketMessage, + run_id: &str, + repo: &str, + pr: &super::pr::PrResult, +) { + emit( + state, + &msg.team_id, + "pull_request.opened", + pr_opened_data(run_id, repo, &msg.title, &msg.base_branch, pr), + ) + .await; +} + +/// A GitHub review event or verdict in the catalog's words. +pub fn verdict_word(v: &str) -> &'static str { + match v.to_ascii_uppercase().as_str() { + "APPROVE" | "APPROVED" => "approve", + "REQUEST_CHANGES" | "CHANGES_REQUESTED" => "request_changes", + _ => "comment", + } +} + +/// `review.completed`'s `data` (pure). +#[allow(clippy::too_many_arguments)] +pub fn review_data( + repo: &str, + pr_number: u64, + head_sha: &str, + verdict: &str, + posted_as: &str, + risk: &str, + trigger: &str, + app: &str, +) -> Value { + json!({ + "repo": repo, + "pr_number": pr_number, + "pr_url": format!("https://github.com/{repo}/pull/{pr_number}"), + "head_sha": head_sha, + "verdict": verdict_word(verdict), + "posted_as": verdict_word(posted_as), + "risk": if risk.trim().is_empty() { "n/a".to_string() } else { risk.trim().to_ascii_lowercase() }, + "trigger": trigger, + "url": format!( + "{}/reviewer/?repo={}&pr={pr_number}", + app.trim_end_matches('/'), + urlencoding::encode(repo) + ), + }) +} + +/// Emits `review.completed` for a review the reviewer posted. +pub async fn emit_review( + state: &WorkerState, + msg: &common::messages::ReviewMessage, + head_sha: &str, + verdict: &str, + posted_as: &str, + risk: &str, +) { + let repo = format!("{}/{}", msg.repo_owner, msg.repo_name); + emit( + state, + &msg.team_id, + "review.completed", + review_data( + &repo, + msg.pr_number, + head_sha, + verdict, + posted_as, + risk, + &msg.trigger, + app_url(state), + ), + ) + .await; +} + +/// Where a CI fix is. +pub struct CiFix<'a> { + pub team_id: &'a str, + pub run_id: &'a str, + pub repo: &'a str, + pub pr_number: u64, + pub branch: &'a str, + /// From 1. + pub attempt: usize, +} + +/// `ci_fix.started`'s `data` (pure). +pub fn ci_fix_started_data(f: &CiFix<'_>, failing_checks: &[String]) -> Value { + json!({ + "run_id": f.run_id, + "repo": f.repo, + "pr_number": f.pr_number, + "branch": f.branch, + "attempt": f.attempt, + "failing_checks": failing_checks, + }) +} + +/// `ci_fix.completed`'s `data` (pure). `outcome` is `pushed`, `no_changes` +/// or `failed`. +pub fn ci_fix_completed_data(f: &CiFix<'_>, outcome: &str, files_changed: usize) -> Value { + json!({ + "run_id": f.run_id, + "repo": f.repo, + "pr_number": f.pr_number, + "branch": f.branch, + "attempt": f.attempt, + "outcome": outcome, + "files_changed": files_changed, + }) +} + +pub async fn emit_ci_fix_started(state: &WorkerState, f: &CiFix<'_>, failing_checks: &[String]) { + emit( + state, + f.team_id, + "ci_fix.started", + ci_fix_started_data(f, failing_checks), + ) + .await; +} + +pub async fn emit_ci_fix_completed( + state: &WorkerState, + f: &CiFix<'_>, + outcome: &str, + files: usize, +) { + emit( + state, + f.team_id, + "ci_fix.completed", + ci_fix_completed_data(f, outcome, files), + ) + .await; +} + +/// `plugin.run.completed`'s `data`, for a run that ended (pure). A refusal +/// is a failure with its reason. +pub fn plugin_run_data(rec: &common::plugins::run::RunRecord) -> Option { + use common::plugins::run::RunStatus; + let status = match rec.status { + RunStatus::Completed => "completed", + RunStatus::Failed | RunStatus::Refused => "failed", + RunStatus::Queued | RunStatus::Running => return None, + }; + Some(json!({ + "run_id": rec.run_id, + "plugin_id": rec.plugin_id, + "status": status, + "trigger": rec.trigger, + "error": if status == "failed" && !rec.reason.is_empty() { Some(rec.reason.as_str()) } else { None }, + })) +} + +fn ctx<'a>( + state: &'a WorkerState, + cipher: &'a common::mcp_credentials::Kms<'a>, +) -> webhooks::Ctx<'a> { + webhooks::Ctx { + dynamo: &state.dynamo, + table: &state.config.settings_table_name, + cipher, + sqs: &state.sqs, + queue_url: &state.config.webhook_queue_url, + dns: &webhooks::deliver::SystemDns, + } +} + +fn kms(state: &WorkerState) -> common::mcp_credentials::Kms<'_> { + common::mcp_credentials::Kms { + client: &state.kms, + key_id: &state.config.secrets_key_id, + } +} + +/// `webhook_emit`: keep the event and send it to every endpoint that wants it. +pub async fn dispatch(state: &WorkerState, msg: WebhookEmitMessage) -> Result<(), Error> { + let cipher = kms(state); + let c = ctx(state, &cipher); + let turned_off = webhooks::dispatch(&c, &msg.event).await?; + for ep in turned_off { + notify_disabled(state, &msg.event.team_id, &ep).await; + } + Ok(()) +} + +/// What a `webhook_send` should do now. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Due { + Now, + /// Not yet: queue it again with this delay. + Wait(i64), +} + +pub fn due(due_at: i64, now: i64) -> Due { + if due_at > now + 1 { + Due::Wait(due_at - now) + } else { + Due::Now + } +} + +/// `webhook_send`: one more try at a delivery, when it is due. +pub async fn send(state: &WorkerState, msg: WebhookSendMessage) -> Result<(), Error> { + let cipher = kms(state); + let c = ctx(state, &cipher); + let now = chrono::Utc::now().timestamp(); + if let Due::Wait(secs) = due(msg.due_at, now) { + webhooks::schedule(&c, &msg, secs).await?; + return Ok(()); + } + let table = &state.config.settings_table_name; + let Some(mut d) = + common::deliveries::get(&state.dynamo, table, &msg.team_id, &msg.delivery_id).await? + else { + info!(delivery = %msg.delivery_id, "Webhook delivery record is gone; not retrying"); + return Ok(()); + }; + if d.status.is_ok() || d.status == common::deliveries::Status::Failed { + // Already delivered (a Resend got there first) or given up. + return Ok(()); + } + let Some(st) = endpoint::get(&state.dynamo, table, &msg.team_id, &msg.endpoint_id).await? + else { + d.finish( + common::deliveries::Status::Failed, + "Endpoint deleted", + "webhook_disabled", + ); + d.next_retry_at = None; + common::deliveries::record(&state.dynamo, table, &msg.team_id, &d).await; + return Ok(()); + }; + let Some(kept) = event::get(&state.dynamo, table, &msg.team_id, &msg.event_id).await? else { + d.finish( + common::deliveries::Status::Failed, + "The event is no longer kept", + "webhook_gave_up", + ); + d.next_retry_at = None; + common::deliveries::record(&state.dynamo, table, &msg.team_id, &d).await; + return Ok(()); + }; + let out = webhooks::attempt( + &c, + &msg.team_id, + &st, + &kept.event.id, + &kept.body, + &mut d, + Mode::Automatic, + ) + .await; + if out.disabled_now { + notify_disabled(state, &msg.team_id, &st.endpoint).await; + } + Ok(()) +} + +/// The chat message for a turned-off endpoint. +pub fn disabled_message(ep: &endpoint::Endpoint, app: &str) -> common::notify::Message { + use common::notify::{Block, Button, Message, Text, Tone}; + let since = ep.failing_since.as_deref().unwrap_or("days ago"); + Message { + summary: format!("CoderHelm turned off the webhook endpoint {}", ep.host()), + blocks: vec![ + Block::Text(Text::new("A webhook endpoint was turned off").bold().color(Tone::Warning)), + Block::Text(Text::new(format!( + "Every delivery to {} has failed since {since}, so CoderHelm stopped sending to it. Fix it, turn it back on in Settings, Webhooks, and replay what it missed.", + ep.url + ))), + ], + buttons: vec![Button::new( + "Open Webhooks", + format!("{}/settings/webhooks/", app.trim_end_matches('/')), + )], + full_width: false, + } +} + +/// Tells the team's admins (email) and the team's chat channel, when it has +/// one turned on, that an endpoint was turned off. +async fn notify_disabled(state: &WorkerState, team_id: &str, ep: &endpoint::Endpoint) { + warn!(team_id, endpoint = %ep.id, "Webhook endpoint turned off after failing for days"); + let since = ep.failing_since.clone().unwrap_or_default(); + let days = chrono::DateTime::parse_from_rfc3339(&since) + .map(|t| (chrono::Utc::now() - t.with_timezone(&chrono::Utc)).num_days()) + .unwrap_or(webhooks::deliver::DISABLE_AFTER_DAYS); + let event = crate::clients::email::EmailEvent::WebhookDisabled { + url: ep.url.clone(), + host: ep.host(), + description: ep.description.clone(), + failing_since: since, + days, + }; + if let Err(e) = crate::clients::email::send_notification(state, team_id, event).await { + warn!(team_id, error = %e, "Could not email admins about a turned-off webhook endpoint"); + } + // The team's chat channel, when alert notifications are on for it. + let cipher = common::mcp_credentials::Kms { + client: &state.kms, + key_id: "", + }; + let item = state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", AttributeValue::S(team_id.into())) + .key( + "sk", + AttributeValue::S(common::alert_notify::TEAM_SETTINGS_SK.into()), + ) + .send() + .await + .ok() + .and_then(|r| r.item().cloned()); + let Some(item) = item else { return }; + let on = item + .get("enabled") + .and_then(|v| v.as_bool().ok()) + .copied() + .unwrap_or(false); + if !on { + return; + } + let channels = common::notify::store::open_all(&cipher, team_id, &item).await; + if channels.is_empty() { + return; + } + common::notify::deliver_recorded( + &common::notify::Http(&state.http), + &channels, + &disabled_message(ep, app_url(state)), + "webhook_disabled", + &state.dynamo, + &state.config.settings_table_name, + team_id, + ) + .await; +} + +#[cfg(test)] +mod tests { + use super::*; + + fn item(pairs: &[(&str, &str)]) -> HashMap { + pairs + .iter() + .map(|(k, v)| { + let v = if *k == "pr_number" { + AttributeValue::N(v.to_string()) + } else { + AttributeValue::S(v.to_string()) + }; + (k.to_string(), v) + }) + .collect() + } + + fn schema(name: &str) -> Value { + webhooks::catalog::data_schema(webhooks::catalog::find(name).unwrap()) + } + + fn conforms(schema: &Value, v: &Value) -> bool { + // The fields are exactly the schema's, and types and enums match. + let props = schema["properties"].as_object().unwrap(); + let obj = v.as_object().unwrap(); + props.keys().all(|k| obj.contains_key(k)) + && obj.keys().all(|k| props.contains_key(k)) + && props.iter().all(|(k, p)| { + let x = &obj[k]; + let types: Vec<&str> = match &p["type"] { + Value::String(s) => vec![s.as_str()], + Value::Array(a) => a.iter().filter_map(|t| t.as_str()).collect(), + _ => vec![], + }; + let ok = types.iter().any(|t| match *t { + "string" => x.is_string(), + "integer" => x.is_u64() || x.is_i64(), + "null" => x.is_null(), + "boolean" => x.is_boolean(), + "array" => x.is_array(), + _ => false, + }); + let in_enum = p["enum"].as_array().is_none_or(|e| e.contains(x)); + ok && in_enum + }) + } + + #[test] + fn run_events_carry_the_documented_fields() { + let rec = item(&[ + ("run_id", "01JBRUN"), + ("title", "Add a limit"), + ("repo", "example-org/api"), + ("ticket_source", "jira"), + ("ticket_id", "ENG-1"), + ("pr_number", "318"), + ("pr_url", "https://github.com/example-org/api/pull/318"), + ("branch", "coderhelm/eng-1"), + ("error_message", "boom"), + ("created_at", "2026-10-26T14:02:11Z"), + ("updated_at", "2026-10-26T14:31:47Z"), + ]); + for (status, ev) in [ + ("running", "run.created"), + ("completed", "run.completed"), + ("failed", "run.failed"), + ("needs_input", "run.needs_input"), + ] { + let d = run_data(&rec, status, "https://app.example.com/"); + assert!(conforms(&schema(ev), &d), "{ev}: {d}"); + assert_eq!(run_event_for(status), Some(ev)); + } + let done = run_data(&rec, "completed", "https://app.example.com"); + assert_eq!( + done["error"], + Value::Null, + "only a failure or a question carries one" + ); + assert_eq!( + done["url"], + "https://app.example.com/runs/detail/?id=01JBRUN" + ); + assert_eq!(done["pr_number"], 318); + let failed = run_data(&rec, "failed", "https://app.example.com"); + assert_eq!(failed["error"], "boom"); + // A fresh run: no PR yet, nothing optional set. + let fresh = run_data( + &item(&[("run_id", "r"), ("created_at", "t")]), + "running", + "https://a", + ); + assert!(conforms(&schema("run.created"), &fresh), "{fresh}"); + assert_eq!(fresh["pr_number"], Value::Null); + assert_eq!(fresh["updated_at"], "t"); + assert_eq!(run_event_for("awaiting_ci"), None); + assert_eq!(run_event_for("success"), Some("run.completed")); + } + + #[test] + fn pr_opened_carries_the_documented_fields() { + let pr = super::super::pr::PrResult { + pr_number: 318, + pr_url: "https://github.com/example-org/api/pull/318".into(), + branch: "coderhelm/eng-1".into(), + draft: true, + node_id: "PR_x".into(), + }; + let d = pr_opened_data("r1", "example-org/api", "Add a limit", "", &pr); + assert!(conforms(&schema("pull_request.opened"), &d), "{d}"); + assert_eq!(d["base_branch"], Value::Null); + let d = pr_opened_data("r1", "example-org/api", "Add a limit", "main", &pr); + assert_eq!(d["base_branch"], "main"); + assert_eq!(d["number"], 318); + } + + #[test] + fn review_events_carry_the_verdict_in_plain_words() { + let d = review_data( + "example-org/web", + 902, + "9f1c", + "REQUEST_CHANGES", + "COMMENT", + "Medium", + "opened", + "https://app.example.com", + ); + assert!(conforms(&schema("review.completed"), &d), "{d}"); + assert_eq!(d["verdict"], "request_changes"); + assert_eq!(d["posted_as"], "comment"); + assert_eq!(d["risk"], "medium"); + assert_eq!( + d["url"], + "https://app.example.com/reviewer/?repo=example-org%2Fweb&pr=902" + ); + assert_eq!(verdict_word("APPROVE"), "approve"); + assert_eq!(verdict_word("N/A"), "comment"); + assert_eq!( + review_data("o/r", 1, "s", "APPROVE", "APPROVE", "", "run", "https://a")["risk"], + "n/a" + ); + } + + #[test] + fn ci_fix_events_carry_the_documented_fields() { + let f = CiFix { + team_id: "T", + run_id: "r1", + repo: "example-org/api", + pr_number: 318, + branch: "coderhelm/x", + attempt: 2, + }; + let started = ci_fix_started_data(&f, &["lint".into(), "test (20.x)".into()]); + assert!(conforms(&schema("ci_fix.started"), &started), "{started}"); + for outcome in ["pushed", "no_changes", "failed"] { + let done = ci_fix_completed_data(&f, outcome, 3); + assert!(conforms(&schema("ci_fix.completed"), &done), "{done}"); + } + assert!(!conforms( + &schema("ci_fix.completed"), + &ci_fix_completed_data(&f, "exploded", 0) + )); + } + + #[test] + fn plugin_runs_report_how_they_ended() { + use common::plugins::run::{RunRecord, RunStatus}; + let mut rec = RunRecord { + run_id: "01JBPRUN".into(), + plugin_id: "release-announcer".into(), + trigger: "schedule".into(), + status: RunStatus::Completed, + ..Default::default() + }; + let d = plugin_run_data(&rec).unwrap(); + assert!(conforms(&schema("plugin.run.completed"), &d), "{d}"); + assert_eq!(d["error"], Value::Null); + rec.status = RunStatus::Refused; + rec.reason = "The plugin is turned off.".into(); + let d = plugin_run_data(&rec).unwrap(); + assert_eq!( + (d["status"].as_str(), d["error"].as_str()), + (Some("failed"), Some("The plugin is turned off.")) + ); + rec.status = RunStatus::Running; + assert!(plugin_run_data(&rec).is_none()); + } + + #[test] + fn a_retry_waits_until_it_is_due() { + assert_eq!(due(1000, 1000), Due::Now); + assert_eq!(due(1001, 1000), Due::Now); + assert_eq!(due(5000, 1000), Due::Wait(4000)); + assert_eq!(due(0, 1000), Due::Now); + } + + #[test] + fn the_turned_off_message_says_what_to_do() { + let ep = endpoint::Endpoint { + id: "ep_1".into(), + url: "https://hooks.example.com/in".into(), + failing_since: Some("2026-10-20T00:00:00Z".into()), + ..Default::default() + }; + let m = disabled_message(&ep, "https://app.example.com/"); + assert!(m.summary.contains("hooks.example.com")); + assert_eq!( + m.buttons[0].url, + "https://app.example.com/settings/webhooks/" + ); + let text = format!("{:?}", m.blocks); + assert!(text.contains("2026-10-20") && text.contains("turn it back on")); + assert!(!text.contains('→')); + } +}