Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5,535 changes: 5,256 additions & 279 deletions docs/api/openapi.json

Large diffs are not rendered by default.

14 changes: 14 additions & 0 deletions infra/lib/api-stack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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). */
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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({
Expand Down
3 changes: 3 additions & 0 deletions infra/lib/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 ---
Expand Down Expand Up @@ -156,6 +158,7 @@ export function buildApp(app: cdk.App, cfg: ResolvedConfig) {
awsInsightsTable: database.awsInsightsTable,
settingsTable: database.settingsTable,
secretsKey: database.secretsKey,
webhookQueue: api.webhookQueue,
});
}

Expand Down
31 changes: 31 additions & 0 deletions infra/lib/email-stack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
Expand Down Expand Up @@ -285,6 +295,27 @@ Error: {{error}}

View run: __APP_URL__`;

const WEBHOOK_DISABLED_HTML = EMAIL_WRAPPER(`
<h1 style="color:#f59e0b;font-size:20px;margin:0 0 16px">A webhook endpoint was turned off</h1>
<p style="color:#ccc;font-size:15px;line-height:1.6;margin:0 0 16px">
Every delivery to <code style="background:#1a1a1a;padding:2px 6px;border-radius:4px;color:#ccc;word-break:break-word">{{url}}</code> has failed since {{failing_since}} ({{days}} days), so CoderHelm stopped sending to it.
</p>
<p style="color:#ccc;font-size:15px;line-height:1.6;margin:0 0 16px">{{description}}</p>
<p style="color:#ccc;font-size:15px;line-height:1.6;margin:0 0 16px">
Fix the endpoint, turn it back on in Settings, Webhooks, and replay the events it missed (they are kept 14 days).
</p>
<a href="__APP_URL__/settings/webhooks" style="display:inline-block;background:#fff;color:#000;padding:10px 20px;border-radius:6px;text-decoration:none;font-weight:600;margin-top:8px">Open Webhooks</a>
`);

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(`
<h1 style="color:#fff;font-size:20px;margin:0 0 16px">Weekly Summary — {{org}}</h1>
<p style="color:#888;font-size:14px;margin:0 0 20px">{{period}}</p>
Expand Down
5 changes: 5 additions & 0 deletions infra/lib/log-analyzer-stack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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 {
Expand Down Expand Up @@ -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),
},
});
Expand All @@ -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);
Expand Down
4 changes: 4 additions & 0 deletions infra/lib/streaming-stack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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
Expand Down
13 changes: 13 additions & 0 deletions infra/lib/worker-stack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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(
Expand Down
46 changes: 46 additions & 0 deletions infra/test/synth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
});
65 changes: 65 additions & 0 deletions lambda/log-analyzer/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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 ──────────────────────────────────

Expand Down Expand Up @@ -709,13 +715,71 @@ 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}")
if resolved_count:
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]
Expand Down Expand Up @@ -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"],
Expand Down
Loading
Loading