Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(webhooks): macro event webhooks (#4360)
Will Hutchinson98ce26ca2a4d
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex 3269751794..617992f950 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -1406,6 +1406,7 @@"teams","unfurl","user_quota",+ "webhook","workspace-hack"],"document_storage_service_client": [@@ -4549,6 +4550,16 @@"user_quota","workspace-hack"],+ "webhook": [+ "cowlike",+ "macro_user_id",+ "macro_uuid",+ "model-error-response",+ "model_user",+ "rate_limit",+ "webhook",+ "workspace-hack"+ ],"worker_trigger": ["macro_aws_config","macro_entrypoint",diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/bTreeMap.ts b/js/app/packages/service-clients/service-storage/generated/schemas/bTreeMap.tsnew file mode 100644index 0000000000..e82b20374e--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/bTreeMap.ts@@ -0,0 +1,10 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export interface BTreeMap {+ [key: string]: string;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createWebhookRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createWebhookRequest.tsnew file mode 100644index 0000000000..bb58d79aca--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createWebhookRequest.ts@@ -0,0 +1,23 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { CreateWebhookRequestHeaders } from './createWebhookRequestHeaders';+import type { WebhookScope } from './webhookScope';++/**+ * Request to create a webhook.+ */+export interface CreateWebhookRequest {+ /** HTTPS endpoint URL. */+ endpoint_url: string;+ headers?: CreateWebhookRequestHeaders;+ /** Display name. */+ name: string;+ /** Rule definition used to match events. */+ rule: unknown;+ /** Scope that owns the webhook. */+ scope: WebhookScope;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createWebhookRequestHeaders.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createWebhookRequestHeaders.tsnew file mode 100644index 0000000000..6cb6b7f86d--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createWebhookRequestHeaders.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { BTreeMap } from './bTreeMap';++export type CreateWebhookRequestHeaders = null | BTreeMap;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.tsindex 1c71c329ca..04bb5d0bba 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts@@ -137,6 +137,7 @@ export * from './botTokenLabel';export * from './botTokenLastUsedAt';export * from './botTokenRevokedAt';export * from './branchNameResponse';+export * from './bTreeMap';export * from './bulkWakeupRequest';export * from './bulkWakeupResponse';export * from './callActiveResponse';@@ -314,6 +315,8 @@ export * from './createUnthreadedPdfAnchorRequestOneOf';export * from './createUnthreadedPdfAnchorRequestOneOfAllOf';export * from './createUnthreadedPdfAnchorRequestOneOfAllOfAnchorType';export * from './createViewRequest';+export * from './createWebhookRequest';+export * from './createWebhookRequestHeaders';export * from './crmComment';export * from './crmCommentDeletedAt';export * from './crmCommentEntityType';@@ -660,6 +663,11 @@ export * from './patchProjectRequestV2SharePermission';export * from './patchThreadRequestV2';export * from './patchThreadRequestV2ProjectId';export * from './patchThreadRequestV2SharePermission';+export * from './patchWebhookRequest';+export * from './patchWebhookRequestEndpointUrl';+export * from './patchWebhookRequestHeaders';+export * from './patchWebhookRequestName';+export * from './patchWebhookRequestStatus';export * from './pdfAnchor';export * from './pdfAnchorId';export * from './pdfAnchorIdOneOf';@@ -932,6 +940,7 @@ export * from './soupThreadInfo';export * from './soupThreadInfoLatestReplyAt';export * from './soupThreadReply';export * from './soupThreadReplyEditedAt';+export * from './string';export * from './successResponse';export * from './syncServiceVersionID';export * from './taskFilters';@@ -980,10 +989,17 @@ export * from './userDocumentViewLocationResponse';export * from './userDocumentViewLocationResponseLocation';export * from './userPinsResponse';export * from './userViewsResponse';+export * from './validateWebhookResponse';+export * from './validateWebhookResponseMessage';+export * from './validateWebhookResponseResponseStatus';export * from './view';export * from './viewPatch';export * from './viewPatchName';export * from './viewsResponse';+export * from './webhook';+export * from './webhookDeletedAt';+export * from './webhookScope';+export * from './webhookStatus';export * from './withCallId';export * from './withChannelId';export * from './withDocumentId';diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/patchWebhookRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/patchWebhookRequest.tsnew file mode 100644index 0000000000..8da69bf410--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/patchWebhookRequest.ts@@ -0,0 +1,24 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { PatchWebhookRequestEndpointUrl } from './patchWebhookRequestEndpointUrl';+import type { PatchWebhookRequestHeaders } from './patchWebhookRequestHeaders';+import type { PatchWebhookRequestName } from './patchWebhookRequestName';+import type { PatchWebhookRequestStatus } from './patchWebhookRequestStatus';++/**+ * Request to patch a webhook.+ */+export interface PatchWebhookRequest {+ /** HTTPS endpoint URL. */+ endpoint_url?: PatchWebhookRequestEndpointUrl;+ headers?: PatchWebhookRequestHeaders;+ /** Display name. */+ name?: PatchWebhookRequestName;+ /** Rule definition used to match events. */+ rule?: unknown;+ status?: PatchWebhookRequestStatus;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/patchWebhookRequestEndpointUrl.ts b/js/app/packages/service-clients/service-storage/generated/schemas/patchWebhookRequestEndpointUrl.tsnew file mode 100644index 0000000000..6aa42093a7--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/patchWebhookRequestEndpointUrl.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * HTTPS endpoint URL.+ */+export type PatchWebhookRequestEndpointUrl = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/patchWebhookRequestHeaders.ts b/js/app/packages/service-clients/service-storage/generated/schemas/patchWebhookRequestHeaders.tsnew file mode 100644index 0000000000..9bc1e4d7b3--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/patchWebhookRequestHeaders.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { BTreeMap } from './bTreeMap';++export type PatchWebhookRequestHeaders = null | BTreeMap;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/patchWebhookRequestName.ts b/js/app/packages/service-clients/service-storage/generated/schemas/patchWebhookRequestName.tsnew file mode 100644index 0000000000..8c89ddfce5--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/patchWebhookRequestName.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Display name.+ */+export type PatchWebhookRequestName = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/patchWebhookRequestStatus.ts b/js/app/packages/service-clients/service-storage/generated/schemas/patchWebhookRequestStatus.tsnew file mode 100644index 0000000000..307172bdea--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/patchWebhookRequestStatus.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { WebhookStatus } from './webhookStatus';++export type PatchWebhookRequestStatus = null | WebhookStatus;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/string.ts b/js/app/packages/service-clients/service-storage/generated/schemas/string.tsnew file mode 100644index 0000000000..0341ea2de1--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/string.ts@@ -0,0 +1,8 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type String = string;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/validateWebhookResponse.ts b/js/app/packages/service-clients/service-storage/generated/schemas/validateWebhookResponse.tsnew file mode 100644index 0000000000..031052268f--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/validateWebhookResponse.ts@@ -0,0 +1,27 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++import type { String } from './string';+import type { ValidateWebhookResponseMessage } from './validateWebhookResponseMessage';+import type { ValidateWebhookResponseResponseStatus } from './validateWebhookResponseResponseStatus';++/**+ * Sanitized result of validating a webhook endpoint.+ */+export interface ValidateWebhookResponse {+ /** Whether the endpoint accepted the signed validation delivery. */+ is_valid: boolean;+ /** Sanitized message explaining validation failure. */+ message?: ValidateWebhookResponseMessage;+ /**+ * HTTP response status returned by the webhook endpoint, when available.+ * @minimum 0+ */+ response_status?: ValidateWebhookResponseResponseStatus;+ /** Webhook id that was validated. */+ webhook_id: String;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/validateWebhookResponseMessage.ts b/js/app/packages/service-clients/service-storage/generated/schemas/validateWebhookResponseMessage.tsnew file mode 100644index 0000000000..4aac7322a2--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/validateWebhookResponseMessage.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Sanitized message explaining validation failure.+ */+export type ValidateWebhookResponseMessage = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/validateWebhookResponseResponseStatus.ts b/js/app/packages/service-clients/service-storage/generated/schemas/validateWebhookResponseResponseStatus.tsnew file mode 100644index 0000000000..a75ddfc0ed--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/validateWebhookResponseResponseStatus.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * HTTP response status returned by the webhook endpoint, when available.+ * @minimum 0+ */+export type ValidateWebhookResponseResponseStatus = number | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/webhook.ts b/js/app/packages/service-clients/service-storage/generated/schemas/webhook.tsnew file mode 100644index 0000000000..a6db02e5bb--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/webhook.ts@@ -0,0 +1,41 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++import type { BTreeMap } from './bTreeMap';+import type { String } from './string';+import type { WebhookDeletedAt } from './webhookDeletedAt';+import type { WebhookStatus } from './webhookStatus';++/**+ * Webhook row returned by application APIs.+ */+export interface Webhook {+ /** Creation timestamp. */+ created_at: string;+ /** User that created the webhook. */+ created_by_user_id: string;+ /** Soft-delete timestamp. */+ deleted_at?: WebhookDeletedAt;+ /** HTTPS endpoint URL. */+ endpoint_url: string;+ /** Custom delivery headers, after decryption by the repository. */+ headers: BTreeMap;+ /** Webhook id. */+ id: String;+ /** Whether the current endpoint configuration has passed validation. */+ is_valid: boolean;+ /** Display name. */+ name: string;+ /** Event matching rule. */+ rule: unknown;+ /** Webhook lifecycle status. */+ status: WebhookStatus;+ /** Update timestamp. */+ updated_at: string;+ /** Owning workspace id. */+ workspace_id: string;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/webhookDeletedAt.ts b/js/app/packages/service-clients/service-storage/generated/schemas/webhookDeletedAt.tsnew file mode 100644index 0000000000..56109e455f--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/webhookDeletedAt.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Soft-delete timestamp.+ */+export type WebhookDeletedAt = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/webhookScope.ts b/js/app/packages/service-clients/service-storage/generated/schemas/webhookScope.tsnew file mode 100644index 0000000000..4d7870a94d--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/webhookScope.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Scope that owns a newly-created webhook.+ */+export type WebhookScope = (typeof WebhookScope)[keyof typeof WebhookScope];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const WebhookScope = {+ user: 'user',+ team: 'team',+} as const;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/webhookStatus.ts b/js/app/packages/service-clients/service-storage/generated/schemas/webhookStatus.tsnew file mode 100644index 0000000000..09690e90c3--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/webhookStatus.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Webhook lifecycle status.+ */+export type WebhookStatus = (typeof WebhookStatus)[keyof typeof WebhookStatus];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const WebhookStatus = {+ active: 'active',+ paused: 'paused',+ disabled: 'disabled',+} as const;diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex 406bcfe2d6..ee471fa531 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -18897,3 +18897,113 @@ export const editProjectV2Response = zod.object({}),error: zod.boolean().describe('Indicates if an error occurred'),});++/**+ * @summary Create a webhook.+ */+export const createWebhookBody = zod+ .object({+ endpoint_url: zod.string().describe('HTTPS endpoint URL.'),+ headers: zod+ .union([zod.null(), zod.record(zod.string(), zod.string())])+ .optional(),+ name: zod.string().describe('Display name.'),+ rule: zod.unknown().describe('Rule definition used to match events.'),+ scope: zod+ .enum(['user', 'team'])+ .describe('Scope that owns a newly-created webhook.'),+ })+ .describe('Request to create a webhook.');++/**+ * @summary Delete a webhook.+ */+export const deleteWebhookParams = zod.object({+ webhook_id: zod.string().describe('Webhook id'),+});++/**+ * @summary Patch a webhook.+ */+export const patchWebhookParams = zod.object({+ webhook_id: zod.string().describe('Webhook id'),+});++export const patchWebhookBody = zod+ .object({+ endpoint_url: zod.string().nullish().describe('HTTPS endpoint URL.'),+ headers: zod+ .union([zod.null(), zod.record(zod.string(), zod.string())])+ .optional(),+ name: zod.string().nullish().describe('Display name.'),+ rule: zod+ .unknown()+ .optional()+ .describe('Rule definition used to match events.'),+ status: zod+ .union([+ zod.null(),+ zod+ .enum(['active', 'paused', 'disabled'])+ .describe('Webhook lifecycle status.'),+ ])+ .optional(),+ })+ .describe('Request to patch a webhook.');++export const patchWebhookResponse = zod+ .object({+ created_at: zod.iso.datetime({}).describe('Creation timestamp.'),+ created_by_user_id: zod.string().describe('User that created the webhook.'),+ deleted_at: zod.iso+ .datetime({})+ .nullish()+ .describe('Soft-delete timestamp.'),+ endpoint_url: zod.string().describe('HTTPS endpoint URL.'),+ headers: zod.record(zod.string(), zod.string()),+ id: zod.string(),+ is_valid: zod+ .boolean()+ .describe(+ 'Whether the current endpoint configuration has passed validation.'+ ),+ name: zod.string().describe('Display name.'),+ rule: zod.unknown().describe('Event matching rule.'),+ status: zod+ .enum(['active', 'paused', 'disabled'])+ .describe('Webhook lifecycle status.'),+ updated_at: zod.iso.datetime({}).describe('Update timestamp.'),+ workspace_id: zod.string().describe('Owning workspace id.'),+ })+ .describe('Webhook row returned by application APIs.');++/**+ * @summary Validate a webhook endpoint.+ */+export const validateWebhookParams = zod.object({+ webhook_id: zod.string().describe('Webhook id'),+});++export const validateWebhookResponseResponseStatusMin = 0;++export const validateWebhookResponse = zod+ .object({+ is_valid: zod+ .boolean()+ .describe(+ 'Whether the endpoint accepted the signed validation delivery.'+ ),+ message: zod+ .string()+ .nullish()+ .describe('Sanitized message explaining validation failure.'),+ response_status: zod+ .number()+ .min(validateWebhookResponseResponseStatusMin)+ .nullish()+ .describe(+ 'HTTP response status returned by the webhook endpoint, when available.'+ ),+ webhook_id: zod.string(),+ })+ .describe('Sanitized result of validating a webhook endpoint.');diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 7d078e07fb..494cb6a94c 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -8982,6 +8982,266 @@}}}+ },+ "/webhook/webhooks": {+ "post": {+ "tags": ["webhook"],+ "summary": "Create a webhook.",+ "operationId": "create_webhook",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreateWebhookRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "201": {+ "description": "Webhook created",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/Webhook"+ }+ }+ }+ },+ "400": {+ "description": "Bad request",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "Forbidden",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "Internal server error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/webhook/webhooks/{webhook_id}": {+ "delete": {+ "tags": ["webhook"],+ "summary": "Delete a webhook.",+ "operationId": "delete_webhook",+ "parameters": [+ {+ "name": "webhook_id",+ "in": "path",+ "description": "Webhook id",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "204": {+ "description": "Webhook deleted"+ },+ "403": {+ "description": "Forbidden",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "Webhook not found",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "Internal server error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ },+ "patch": {+ "tags": ["webhook"],+ "summary": "Patch a webhook.",+ "operationId": "patch_webhook",+ "parameters": [+ {+ "name": "webhook_id",+ "in": "path",+ "description": "Webhook id",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PatchWebhookRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "Webhook updated",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/Webhook"+ }+ }+ }+ },+ "400": {+ "description": "Bad request",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "Forbidden",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "Webhook not found",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "Internal server error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/webhook/webhooks/{webhook_id}/validate": {+ "post": {+ "tags": ["webhook"],+ "summary": "Validate a webhook endpoint.",+ "operationId": "validate_webhook",+ "parameters": [+ {+ "name": "webhook_id",+ "in": "path",+ "description": "Webhook id",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Webhook validation result",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ValidateWebhookResponse"+ }+ }+ }+ },+ "403": {+ "description": "Forbidden",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "Webhook not found",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "429": {+ "description": "Rate limited",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "Internal server error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }}},"components": {@@ -10103,6 +10363,15 @@}}},+ "BTreeMap": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ },+ "propertyNames": {+ "type": "string"+ }+ },"BasicDocument": {"type": "object","required": ["id", "documentVersionId", "owner", "name"],@@ -12043,6 +12312,39 @@}}},+ "CreateWebhookRequest": {+ "type": "object",+ "description": "Request to create a webhook.",+ "required": ["scope", "name", "endpoint_url", "rule"],+ "properties": {+ "endpoint_url": {+ "type": "string",+ "description": "HTTPS endpoint URL."+ },+ "headers": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/BTreeMap",+ "description": "Optional custom delivery headers."+ }+ ]+ },+ "name": {+ "type": "string",+ "description": "Display name."+ },+ "rule": {+ "description": "Rule definition used to match events."+ },+ "scope": {+ "$ref": "#/components/schemas/WebhookScope",+ "description": "Scope that owns the webhook."+ }+ }+ },"CrmComment": {"type": "object","description": "A single comment within a [`CrmThread`].",@@ -15591,6 +15893,45 @@}}},+ "PatchWebhookRequest": {+ "type": "object",+ "description": "Request to patch a webhook.",+ "properties": {+ "endpoint_url": {+ "type": ["string", "null"],+ "description": "HTTPS endpoint URL."+ },+ "headers": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/BTreeMap",+ "description": "Optional custom delivery headers. When present, replaces existing headers."+ }+ ]+ },+ "name": {+ "type": ["string", "null"],+ "description": "Display name."+ },+ "rule": {+ "description": "Rule definition used to match events."+ },+ "status": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/WebhookStatus",+ "description": "Webhook lifecycle status."+ }+ ]+ }+ }+ },"PdfAnchor": {"oneOf": [{@@ -18476,6 +18817,9 @@}}},+ "String": {+ "type": "string"+ },"SuccessResponse": {"type": "object","required": ["error", "data"],@@ -18880,6 +19224,31 @@}}},+ "ValidateWebhookResponse": {+ "type": "object",+ "description": "Sanitized result of validating a webhook endpoint.",+ "required": ["webhook_id", "is_valid"],+ "properties": {+ "is_valid": {+ "type": "boolean",+ "description": "Whether the endpoint accepted the signed validation delivery."+ },+ "message": {+ "type": ["string", "null"],+ "description": "Sanitized message explaining validation failure."+ },+ "response_status": {+ "type": ["integer", "null"],+ "format": "int32",+ "description": "HTTP response status returned by the webhook endpoint, when available.",+ "minimum": 0+ },+ "webhook_id": {+ "$ref": "#/components/schemas/String",+ "description": "Webhook id that was validated."+ }+ }+ },"View": {"type": "object","required": [@@ -18941,6 +19310,85 @@}}},+ "Webhook": {+ "type": "object",+ "description": "Webhook row returned by application APIs.",+ "required": [+ "id",+ "workspace_id",+ "name",+ "endpoint_url",+ "headers",+ "status",+ "is_valid",+ "created_by_user_id",+ "created_at",+ "updated_at",+ "rule"+ ],+ "properties": {+ "created_at": {+ "type": "string",+ "format": "date-time",+ "description": "Creation timestamp."+ },+ "created_by_user_id": {+ "type": "string",+ "description": "User that created the webhook."+ },+ "deleted_at": {+ "type": ["string", "null"],+ "format": "date-time",+ "description": "Soft-delete timestamp."+ },+ "endpoint_url": {+ "type": "string",+ "description": "HTTPS endpoint URL."+ },+ "headers": {+ "$ref": "#/components/schemas/BTreeMap",+ "description": "Custom delivery headers, after decryption by the repository."+ },+ "id": {+ "$ref": "#/components/schemas/String",+ "description": "Webhook id."+ },+ "is_valid": {+ "type": "boolean",+ "description": "Whether the current endpoint configuration has passed validation."+ },+ "name": {+ "type": "string",+ "description": "Display name."+ },+ "rule": {+ "description": "Event matching rule."+ },+ "status": {+ "$ref": "#/components/schemas/WebhookStatus",+ "description": "Webhook lifecycle status."+ },+ "updated_at": {+ "type": "string",+ "format": "date-time",+ "description": "Update timestamp."+ },+ "workspace_id": {+ "type": "string",+ "description": "Owning workspace id."+ }+ }+ },+ "WebhookScope": {+ "type": "string",+ "description": "Scope that owns a newly-created webhook.",+ "enum": ["user", "team"]+ },+ "WebhookStatus": {+ "type": "string",+ "description": "Webhook lifecycle status.",+ "enum": ["active", "paused", "disabled"]+ },"WithCallId": {"type": "object","description": "Wrapper carrying just a call id. Used by the [`CallRecordPreview::DoesNotExist`]\nvariant.",diff --git a/js/bun.lock b/js/bun.lockindex 5498e98b42..add29b5d74 100644--- a/js/bun.lock+++ b/js/bun.lock@@ -883,7 +883,7 @@"@img/sharp-win32-x64": ["@img/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw=="],- "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#26537c8", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-26537c8"],+ "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#26537c8", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-26537c8", "sha512-6p5xQAkS6Uw6J8Uh0vlj6MjKZXWps5E1Gu0hciBFq1E2BfPBZAgdeeafKnR3diNb4SXWK0JML49nAr+o5PhwKw=="],"@inquirer/external-editor": ["@inquirer/[email protected]", "", { "dependencies": { "chardet": "^2.1.1", "iconv-lite": "^0.7.0" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-RWbSrDiYmO4LbejWY7ttpxczuwQyZLBUyygsA9Nsv95hpzUWwnNTVQmAq3xuh7vNwCp07UTmE5i11XAEExx4RA=="],@@ -2613,7 +2613,7 @@"pathval": ["[email protected]", "", {}, "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ=="],- "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6"],+ "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6", "sha512-HDFaPbCxLG2GHpf1smUG97nku5aPGBGaCcIbK05dGdp07TBLUlDcXsM4WcE82mO5W4RBPIBVYobX5N/6M6NFrA=="],"performance-now": ["[email protected]", "", {}, "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow=="],diff --git a/rust/cloud-storage/.sqlx/query-375b7acdbb50fedf3b5612b7b8a7de5ae1aac2bc12fa6c2f35f0ee1d1482987f.json b/rust/cloud-storage/.sqlx/query-375b7acdbb50fedf3b5612b7b8a7de5ae1aac2bc12fa6c2f35f0ee1d1482987f.jsonnew file mode 100644index 0000000000..cd1d89d6b9--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-375b7acdbb50fedf3b5612b7b8a7de5ae1aac2bc12fa6c2f35f0ee1d1482987f.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE webhook\n SET is_valid = $2, updated_at = now()\n WHERE id = $1 AND deleted_at IS NULL\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Bool"+ ]+ },+ "nullable": []+ },+ "hash": "375b7acdbb50fedf3b5612b7b8a7de5ae1aac2bc12fa6c2f35f0ee1d1482987f"+}diff --git a/rust/cloud-storage/.sqlx/query-6d5ff497c9de27eec22be9c2cbc195cab89cacf08b09dd95a51b2fc70d699a35.json b/rust/cloud-storage/.sqlx/query-6d5ff497c9de27eec22be9c2cbc195cab89cacf08b09dd95a51b2fc70d699a35.jsonnew file mode 100644index 0000000000..96428e9cb5--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-6d5ff497c9de27eec22be9c2cbc195cab89cacf08b09dd95a51b2fc70d699a35.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE webhook\n SET deleted_at = now(), updated_at = now()\n WHERE id = $1 AND deleted_at IS NULL\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "6d5ff497c9de27eec22be9c2cbc195cab89cacf08b09dd95a51b2fc70d699a35"+}diff --git a/rust/cloud-storage/.sqlx/query-72a8a4591d37bad783027764bfe1da50aa233032cef86a6ed61db543ef416f9c.json b/rust/cloud-storage/.sqlx/query-72a8a4591d37bad783027764bfe1da50aa233032cef86a6ed61db543ef416f9c.jsonnew file mode 100644index 0000000000..e669513d1f--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-72a8a4591d37bad783027764bfe1da50aa233032cef86a6ed61db543ef416f9c.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO webhook (\n id, workspace_id, name, endpoint_url, signing_secret, headers,\n rule, status, is_valid, created_by_user_id\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, false, $9)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Text",+ "Text",+ "Text",+ "Jsonb",+ "Jsonb",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "72a8a4591d37bad783027764bfe1da50aa233032cef86a6ed61db543ef416f9c"+}diff --git a/rust/cloud-storage/.sqlx/query-848c7af0d60329aaee7bca5ad6c771d971197200816018eabb15ae456a448b1d.json b/rust/cloud-storage/.sqlx/query-848c7af0d60329aaee7bca5ad6c771d971197200816018eabb15ae456a448b1d.jsonnew file mode 100644index 0000000000..310e74c5dc--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-848c7af0d60329aaee7bca5ad6c771d971197200816018eabb15ae456a448b1d.json@@ -0,0 +1,94 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n w.id,\n w.workspace_id,\n w.name,\n w.endpoint_url,\n w.signing_secret,\n w.headers,\n w.status,\n w.is_valid,\n w.created_by_user_id,\n w.created_at,\n w.updated_at,\n w.deleted_at,\n w.rule\n FROM webhook w\n WHERE w.id = $1\n AND w.deleted_at IS NULL\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "workspace_id",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "endpoint_url",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "signing_secret",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "headers",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 6,+ "name": "status",+ "type_info": "Text"+ },+ {+ "ordinal": 7,+ "name": "is_valid",+ "type_info": "Bool"+ },+ {+ "ordinal": 8,+ "name": "created_by_user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 9,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 10,+ "name": "updated_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 11,+ "name": "deleted_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 12,+ "name": "rule",+ "type_info": "Jsonb"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false,+ false,+ false,+ false,+ false,+ false,+ true,+ false+ ]+ },+ "hash": "848c7af0d60329aaee7bca5ad6c771d971197200816018eabb15ae456a448b1d"+}diff --git a/rust/cloud-storage/.sqlx/query-909a58ec4730ff19d1c4609b4142b95c458a83d75e7f04aeecaeafa4dd65e705.json b/rust/cloud-storage/.sqlx/query-909a58ec4730ff19d1c4609b4142b95c458a83d75e7f04aeecaeafa4dd65e705.jsonnew file mode 100644index 0000000000..2970a74d10--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-909a58ec4730ff19d1c4609b4142b95c458a83d75e7f04aeecaeafa4dd65e705.json@@ -0,0 +1,19 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE webhook\n SET\n name = COALESCE($2, name),\n endpoint_url = COALESCE($3, endpoint_url),\n headers = COALESCE($4, headers),\n rule = COALESCE($5, rule),\n status = COALESCE($6, status),\n is_valid = CASE WHEN $3::TEXT IS NOT NULL OR $4::JSONB IS NOT NULL THEN false ELSE is_valid END,\n updated_at = now()\n WHERE id = $1 AND deleted_at IS NULL\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Text",+ "Jsonb",+ "Jsonb",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "909a58ec4730ff19d1c4609b4142b95c458a83d75e7f04aeecaeafa4dd65e705"+}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex f41df86e66..02325456c3 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -3905,6 +3905,7 @@ dependencies = ["properties","properties_db_client","properties_service",+ "rate_limit","rayon","readonly_pool","redis",@@ -3935,6 +3936,7 @@ dependencies = ["utoipa","utoipa-swagger-ui","uuid",+ "webhook","workspace-hack","zip 2.4.2",]@@ -13941,6 +13943,37 @@ dependencies = ["string_cache_codegen",]+[[package]]+name = "webhook"+version = "0.1.0"+dependencies = [+ "anyhow",+ "axum",+ "axum-extra",+ "chrono",+ "hex",+ "hmac 0.12.1",+ "macro_db_migrator",+ "macro_user_id",+ "macro_uuid",+ "model-error-response",+ "model_user",+ "rate_limit",+ "reqwest 0.13.4",+ "rootcause",+ "serde",+ "serde_json",+ "sha2 0.10.9",+ "sqlx",+ "thiserror 2.0.18",+ "tokio",+ "tower 0.5.3",+ "tracing",+ "url",+ "utoipa",+ "workspace-hack",+]+[[package]]name = "webp"version = "0.3.1"diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex ab342039f2..662fa98e7c 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -54,6 +54,7 @@ members = ["tools/native_app_server","unfurl","unfurl_service",+ "webhook","upload_extractor_lambda_handler","upload_extractor_lambda_trigger","user_link_cleanup_handler",diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.tomlindex 94642b184b..9036cacd1c 100644--- a/rust/cloud-storage/document_storage_service/Cargo.toml+++ b/rust/cloud-storage/document_storage_service/Cargo.toml@@ -124,6 +124,7 @@ properties = { path = "../properties" }properties_db_client = { path = "../properties_db_client" }properties_service = { path = "../properties_service" }rayon = "1.10.0"+rate_limit = { path = "../rate_limit", default-features = false, features = ["axum"] }readonly_pool = { path = "../readonly_pool" }redis = { workspace = true, features = ["aio",@@ -160,6 +161,7 @@ utoipa = { workspace = true, features = ["axum_extras"] }utoipa-swagger-ui = { workspace = true, features = ["axum"] }uuid = { workspace = true }zip = { workspace = true }+webhook = { path = "../webhook", features = ["inbound", "outbound"] }workspace-hack = { version = "0.1", path = "../workspace-hack" }macro_config = { path = "../macro_config" }doppler-config = { workspace = true }diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex bb4b39411a..33505bb95e 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -80,6 +80,14 @@ use system_properties::{PgSystemPropertiesRepository, StatusOption, SystemPropertiesService as _,SystemPropertiesServiceImpl,};+use webhook::{+ domain::service::WebhookServiceImpl,+ inbound::axum_router::WebhookRouterState as MacroWebhookRouterState,+ outbound::{+ http_validator::ReqwestWebhookValidationClient,+ pg_repository::PgRepository as PgWebhookRepo,+ },+};#[derive(Debug, Clone)]pub struct InternalFlag {@@ -294,6 +302,17 @@ pub(crate) type CalWebhookServiceType = CalWebhookServiceImpl<AnalyticsClientSin/// Type alias for the cal.com webhook router state.pub(crate) type DssCalWebhookState = CalWebhookRouterState<CalWebhookServiceType>;+/// Type alias for the product webhook service.+pub(crate) type DssWebhookService =+ WebhookServiceImpl<PgWebhookRepo, ReqwestWebhookValidationClient>;++/// Type alias for the product webhook rate limiter.+pub(crate) type DssWebhookRateLimiter =+ rate_limit::RateLimitServiceImpl<rate_limit::RedisRateLimitAdapter<redis::Client>>;++/// Type alias for the product webhook router state.+pub(crate) type DssWebhookState = MacroWebhookRouterState<DssWebhookService, DssWebhookRateLimiter>;+#[derive(Clone, FromRef)]pub(crate) struct ApiContext {pub db: PgPool,@@ -331,6 +350,7 @@ pub(crate) struct ApiContext {pub channel_bot_webhook_state: DssChannelBotWebhookState,pub call_state: DssCallState,pub call_webhook_state: DssCallWebhookState,+ pub webhook_state: DssWebhookState,pub call_internal_state: DssCallInternalState,pub cal_webhook_state: DssCalWebhookState,pub entity_access_management_service: EntityAccessManagementService,diff --git a/rust/cloud-storage/document_storage_service/src/api/mod.rs b/rust/cloud-storage/document_storage_service/src/api/mod.rsindex 8da10a2f97..e3e6fcb370 100644--- a/rust/cloud-storage/document_storage_service/src/api/mod.rs+++ b/rust/cloud-storage/document_storage_service/src/api/mod.rs@@ -234,6 +234,10 @@ fn api_router(state: ApiContext) -> Router {"/call",call::inbound::axum_router::call_router(state.call_state.clone()),)+ .nest(+ "/webhook",+ webhook::inbound::axum_router::webhook_router(state.webhook_state.clone()),+ ).nest("/crm",crm::inbound::axum_router::crm_router(state.crm_state.clone()),diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rsindex 832a60b421..5cc0fed1fc 100644--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs@@ -254,6 +254,10 @@ use utoipa::OpenApi;call::inbound::axum_router::toggle_share_with_team_handler,call::inbound::axum_router::get_batch_call_record_preview_handler,call::inbound::axum_router::webhook_handler,+ webhook::inbound::axum_router::create_webhook,+ webhook::inbound::axum_router::delete_webhook,+ webhook::inbound::axum_router::patch_webhook,+ webhook::inbound::axum_router::validate_webhook,call::inbound::axum_router::ring_status_handler,call::inbound::axum_router::transcript_handler,@@ -503,6 +507,13 @@ use utoipa::OpenApi;SoupCallRecord,SoupCallRecordParticipant,+ // Webhooks+ webhook::domain::models::CreateWebhookRequest,+ webhook::domain::models::PatchWebhookRequest,+ webhook::domain::models::ValidateWebhookResponse,+ webhook::domain::models::Webhook,+ webhook::domain::models::WebhookStatus,+DocumentSubType,diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex de9f0d01b3..9ac261f7e6 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -77,6 +77,7 @@ use opensearch_client::OpensearchClient;use properties::{NotificationServiceImpl, PermissionServiceImpl, PropertiesPgRepo, PropertiesServiceImpl,};+use rate_limit::{RateLimitServiceImpl, RedisRateLimitAdapter};use secretsmanager_client::SecretManager;use soup::{domain::service::SoupImpl, inbound::axum_router::SoupRouterState,@@ -552,6 +553,20 @@ async fn main() -> anyhow::Result<()> {let call_state = CallRouterState::new(call_service.clone(), entity_access_service.clone());let call_webhook_state = WebhookRouterState::new(call_service.clone());+ let webhook_service = webhook::domain::service::WebhookServiceImpl::new(+ webhook::outbound::pg_repository::PgRepository::new(db.clone()),+ webhook::outbound::http_validator::ReqwestWebhookValidationClient::new()+ .context("failed to create webhook validation client")?,+ );+ let webhook_rate_limiter = RateLimitServiceImpl {+ repo: RedisRateLimitAdapter {+ redis: redis_client.clone(),+ },+ };+ let webhook_state = webhook::inbound::axum_router::WebhookRouterState::new(+ webhook_service,+ webhook_rate_limiter,+ );let call_internal_state = InternalCallRouterState::new(call_service.clone());// Create the SQS worker for delete document processing before config is moved.@@ -702,6 +717,7 @@ async fn main() -> anyhow::Result<()> {channel_bot_webhook_state,call_state,call_webhook_state,+ webhook_state,call_internal_state,cal_webhook_state,entity_access_management_service,diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfileindex 62e957c8fc..c55c95dc87 100644--- a/rust/cloud-storage/justfile+++ b/rust/cloud-storage/justfile@@ -116,6 +116,7 @@ setup_test_envs:echo "DATABASE_URL={{ DATABASE_URL }}" >> ./share_permission_db_utils/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./ai_projections/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./ai_projections_refresh_handler/.env+ echo "DATABASE_URL={{ DATABASE_URL }}" >> ./webhook/.envsetup_macrodb:just macro_db_client/create_dbdiff --git a/rust/cloud-storage/macro_db_client/migrations/20260629135403_webhooks_core_schema.sql b/rust/cloud-storage/macro_db_client/migrations/20260629135403_webhooks_core_schema.sqlnew file mode 100644index 0000000000..1b2985b858--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260629135403_webhooks_core_schema.sql@@ -0,0 +1,90 @@+CREATE TABLE webhook (+ id TEXT PRIMARY KEY,+ workspace_id TEXT NOT NULL,+ owner_user_id TEXT NULL,+ owner_bot_id TEXT NULL,+ name TEXT NOT NULL,+ endpoint_url TEXT NOT NULL,+ signing_secret TEXT NOT NULL,+ headers JSONB NOT NULL DEFAULT '{}'::jsonb,+ rule JSONB NOT NULL,+ status TEXT NOT NULL DEFAULT 'active'+ CONSTRAINT webhook_status CHECK (status IN ('active', 'paused', 'disabled')),+ is_valid BOOLEAN NOT NULL DEFAULT false,+ paused_at TIMESTAMPTZ NULL,+ pause_reason TEXT NULL,+ last_success_at TIMESTAMPTZ NULL,+ last_failure_at TIMESTAMPTZ NULL,+ created_by_user_id TEXT NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ deleted_at TIMESTAMPTZ NULL+);++CREATE INDEX webhook_workspace_status_idx+ ON webhook (workspace_id, status, is_valid);++CREATE INDEX webhook_events_gin_idx+ ON webhook USING GIN ((rule -> 'events'));++CREATE TABLE webhook_delivery (+ id TEXT PRIMARY KEY,+ webhook_id TEXT NOT NULL REFERENCES webhook(id),+ event_id TEXT NOT NULL,+ event TEXT NOT NULL,+ event_schema_version INTEGER NOT NULL,+ event_occurred_at TIMESTAMPTZ NOT NULL,+ event_entity_type TEXT NOT NULL,+ event_entity_id TEXT NOT NULL,+ event_ordering_key TEXT NOT NULL,+ status TEXT NOT NULL DEFAULT 'queued',+ request_url TEXT NOT NULL,+ request_headers_redacted JSONB NOT NULL DEFAULT '{}'::jsonb,+ request_body JSONB NOT NULL,+ next_attempt_at TIMESTAMPTZ NULL,+ attempt_count INTEGER NOT NULL DEFAULT 0,+ first_attempt_at TIMESTAMPTZ NULL,+ last_attempt_at TIMESTAMPTZ NULL,+ delivered_at TIMESTAMPTZ NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (webhook_id, event_id),+ CONSTRAINT webhook_delivery_attempt_count_non_negative CHECK (attempt_count >= 0),+ CONSTRAINT webhook_delivery_attempt_window_valid CHECK (+ first_attempt_at IS NULL+ OR last_attempt_at IS NULL+ OR last_attempt_at >= first_attempt_at+ )+);++CREATE INDEX webhook_delivery_webhook_created_idx+ ON webhook_delivery (webhook_id, created_at);++CREATE INDEX webhook_delivery_status_next_attempt_idx+ ON webhook_delivery (status, next_attempt_at);++CREATE INDEX webhook_delivery_event_ordering_idx+ ON webhook_delivery (event_ordering_key);++CREATE TABLE webhook_delivery_attempt (+ id TEXT PRIMARY KEY,+ webhook_delivery_id TEXT NOT NULL REFERENCES webhook_delivery(id),+ attempt_number INTEGER NOT NULL,+ status TEXT NOT NULL,+ started_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ completed_at TIMESTAMPTZ NULL,+ duration_ms INTEGER NULL,+ response_status INTEGER NULL,+ response_headers_redacted JSONB NULL,+ response_body_preview TEXT NULL,+ error_kind TEXT NULL,+ error_message TEXT NULL,+ UNIQUE (webhook_delivery_id, attempt_number),+ CONSTRAINT webhook_delivery_attempt_number_non_negative CHECK (attempt_number >= 0),+ CONSTRAINT webhook_delivery_attempt_duration_non_negative CHECK (+ duration_ms IS NULL OR duration_ms >= 0+ ),+ CONSTRAINT webhook_delivery_attempt_completed_after_started CHECK (+ completed_at IS NULL OR completed_at >= started_at+ )+);diff --git a/rust/cloud-storage/webhook/Cargo.toml b/rust/cloud-storage/webhook/Cargo.tomlnew file mode 100644index 0000000000..c908a16883--- /dev/null+++ b/rust/cloud-storage/webhook/Cargo.toml@@ -0,0 +1,64 @@+[package]+edition = "2024"+name = "webhook"+publish = false+version = "0.1.0"++[features]+default = ["inbound", "outbound", "ports"]+inbound = [+ "dep:axum",+ "dep:axum-extra",+ "dep:model-error-response",+ "dep:model_user",+ "dep:rate_limit",+ "rate_limit/axum",+ "dep:serde_json",+ "dep:utoipa",+ "ports",+]+outbound = [+ "dep:hex",+ "dep:hmac",+ "dep:reqwest",+ "dep:sha2",+ "dep:macro_uuid",+ "dep:sqlx",+ "dep:tokio",+ "dep:url",+ "ports",+]+ports = ["dep:serde_json", "dep:url"]++[dependencies]+anyhow = { workspace = true }+axum = { workspace = true, optional = true }+axum-extra = { workspace = true, optional = true }+chrono = { workspace = true }+hex = { workspace = true, optional = true }+hmac = { workspace = true, optional = true }+macro_user_id = { path = "../macro_user_id" }+macro_uuid = { path = "../macro_uuid", optional = true }+model-error-response = { path = "../model-error-response", optional = true }+model_user = { path = "../model_user", optional = true, features = ["axum"] }+rate_limit = { path = "../rate_limit", optional = true, default-features = false }+reqwest = { workspace = true, optional = true }+serde = { workspace = true }+serde_json = { workspace = true, optional = true }+sha2 = { workspace = true, optional = true }+sqlx = { workspace = true, optional = true }+thiserror = { workspace = true }+tokio = { workspace = true, optional = true }+tracing = { workspace = true }+url = { workspace = true, optional = true }+utoipa = { workspace = true, optional = true }+workspace-hack = { version = "0.1", path = "../workspace-hack" }++[dev-dependencies]+macro_db_migrator = { path = "../macro_db_migrator" }+rate_limit = { path = "../rate_limit", default-features = false, features = [+ "axum",+ "testing",+] }+rootcause = { workspace = true }+tower = { workspace = true }diff --git a/rust/cloud-storage/webhook/README.md b/rust/cloud-storage/webhook/README.mdnew file mode 100644index 0000000000..28dbd90650--- /dev/null+++ b/rust/cloud-storage/webhook/README.md@@ -0,0 +1,24 @@+# Webhook crate++This crate currently contains the core application-layer webhook pieces for the first iteration.++## Current scope++- Database tables are present for event ingestion, webhooks, deliveries, and delivery attempts.+- The Postgres repository supports creating, loading, patching, and updating webhook validity through the `is_valid` field.+- The inbound Axum API supports:+ - `POST /webhooks`+ - `PATCH /webhooks/{webhook_id}`+ - `POST /webhooks/{webhook_id}/validate`+- Validation sends a signed `webhook.validation.test` event to the webhook endpoint and persists the result by updating `is_valid`.+- Validation attempts are rate limited with the existing `rate_limit` crate. The validation key is `per-user-validate-webhook:{macro_user_id}:{webhook_id}` and the current limit is 10 attempts per 3600-second window.++## Temporary limitations++- Webhook IDs currently use prefixed UUIDv7 strings (`wh_<uuid_v7>`). They can be swapped for true ULIDs later.+- Webhook signing secrets are generated by the service and stored in plaintext in `signing_secret`, matching the existing bot secret storage approach.+- Custom headers are stored as JSON in the `headers` column.++## Intentionally out of scope++Delivery workers, SQS/SNS infrastructure, event ingestion, redelivery, and auto-pause behavior are intentionally out of scope for this crate iteration.diff --git a/rust/cloud-storage/webhook/src/domain/mod.rs b/rust/cloud-storage/webhook/src/domain/mod.rsnew file mode 100644index 0000000000..c1065db13e--- /dev/null+++ b/rust/cloud-storage/webhook/src/domain/mod.rs@@ -0,0 +1,12 @@+//! Domain layer for webhooks.++/// Webhook domain models.+pub mod models;+#[cfg(feature = "ports")]+/// Webhook ports.+pub mod ports;+#[cfg(feature = "ports")]+/// Webhook service implementation.+pub mod service;+#[cfg(test)]+mod service_test;diff --git a/rust/cloud-storage/webhook/src/domain/models.rs b/rust/cloud-storage/webhook/src/domain/models.rsnew file mode 100644index 0000000000..8c782a3ac5--- /dev/null+++ b/rust/cloud-storage/webhook/src/domain/models.rs@@ -0,0 +1,150 @@+//! Webhook domain models.++use chrono::{DateTime, Utc};+use serde::{Deserialize, Serialize};+use serde_json::Value;+use std::collections::BTreeMap;++/// Webhook id. Webhook ids are stored with a `wh_` prefix.+pub type WebhookId = String;++/// Custom headers supplied for webhook delivery.+pub type WebhookHeaders = BTreeMap<String, String>;++/// Webhook lifecycle status.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+#[serde(rename_all = "snake_case")]+pub enum WebhookStatus {+ /// Webhook is active and eligible for delivery once validated.+ Active,+ /// Webhook is paused and should not receive deliveries.+ Paused,+ /// Webhook was disabled by the system.+ Disabled,+}++impl WebhookStatus {+ /// Storage representation.+ pub const fn as_str(self) -> &'static str {+ match self {+ Self::Active => "active",+ Self::Paused => "paused",+ Self::Disabled => "disabled",+ }+ }+}++impl std::str::FromStr for WebhookStatus {+ type Err = String;++ fn from_str(value: &str) -> Result<Self, Self::Err> {+ match value {+ "active" => Ok(Self::Active),+ "paused" => Ok(Self::Paused),+ "disabled" => Ok(Self::Disabled),+ other => Err(format!("unknown webhook status: {other}")),+ }+ }+}++/// Scope that owns a newly-created webhook.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+#[serde(rename_all = "snake_case")]+pub enum WebhookScope {+ /// The authenticated user's personal workspace.+ User,+ /// The authenticated user's team workspace.+ Team,+}++/// Request to create a webhook.+#[derive(Debug, Clone, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+pub struct CreateWebhookRequest {+ /// Scope that owns the webhook.+ pub scope: WebhookScope,+ /// Display name.+ pub name: String,+ /// HTTPS endpoint URL.+ pub endpoint_url: String,+ /// Optional custom delivery headers.+ pub headers: Option<WebhookHeaders>,+ /// Rule definition used to match events.+ pub rule: Value,+}++/// Request to patch a webhook.+#[derive(Debug, Clone, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+pub struct PatchWebhookRequest {+ /// Display name.+ pub name: Option<String>,+ /// HTTPS endpoint URL.+ pub endpoint_url: Option<String>,+ /// Optional custom delivery headers. When present, replaces existing headers.+ pub headers: Option<WebhookHeaders>,+ /// Rule definition used to match events.+ pub rule: Option<Value>,+ /// Webhook lifecycle status.+ pub status: Option<WebhookStatus>,+}++/// Webhook row returned by application APIs.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+pub struct Webhook {+ /// Webhook id.+ pub id: WebhookId,+ /// Owning workspace id.+ pub workspace_id: String,+ /// Display name.+ pub name: String,+ /// HTTPS endpoint URL.+ pub endpoint_url: String,+ /// Signing secret used by outbound adapters. This is never serialized by APIs.+ #[serde(default, skip_serializing)]+ pub signing_secret: String,+ /// Custom delivery headers, after decryption by the repository.+ pub headers: WebhookHeaders,+ /// Webhook lifecycle status.+ pub status: WebhookStatus,+ /// Whether the current endpoint configuration has passed validation.+ pub is_valid: bool,+ /// User that created the webhook.+ pub created_by_user_id: String,+ /// Creation timestamp.+ pub created_at: DateTime<Utc>,+ /// Update timestamp.+ pub updated_at: DateTime<Utc>,+ /// Soft-delete timestamp.+ pub deleted_at: Option<DateTime<Utc>>,+ /// Event matching rule.+ pub rule: Value,+}++/// Sanitized result of validating a webhook endpoint.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+pub struct ValidateWebhookResponse {+ /// Webhook id that was validated.+ pub webhook_id: WebhookId,+ /// Whether the endpoint accepted the signed validation delivery.+ pub is_valid: bool,+ /// HTTP response status returned by the webhook endpoint, when available.+ pub response_status: Option<u16>,+ /// Sanitized message explaining validation failure.+ pub message: Option<String>,+}++/// Sanitized result returned by the validation client port.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct WebhookValidationResult {+ /// Whether the endpoint accepted the signed validation delivery.+ pub is_valid: bool,+ /// HTTP response status returned by the webhook endpoint, when available.+ pub response_status: Option<u16>,+ /// Sanitized success or failure message.+ pub message: Option<String>,+}diff --git a/rust/cloud-storage/webhook/src/domain/ports.rs b/rust/cloud-storage/webhook/src/domain/ports.rsnew file mode 100644index 0000000000..44ccb897b5--- /dev/null+++ b/rust/cloud-storage/webhook/src/domain/ports.rs@@ -0,0 +1,117 @@+//! Webhook domain ports.++use super::models::{+ CreateWebhookRequest, PatchWebhookRequest, ValidateWebhookResponse, Webhook, WebhookId,+ WebhookValidationResult,+};+use macro_user_id::user_id::MacroUserIdStr;+use std::future::Future;++/// Webhook repository.+pub trait WebhookRepo: Clone + Send + Sync + 'static {+ /// Repository error.+ type Err: Into<anyhow::Error> + Send;++ /// Create a webhook and its initial rule.+ fn create_webhook(+ &self,+ created_by_user_id: MacroUserIdStr<'static>,+ workspace_id: String,+ request: CreateWebhookRequest,+ signing_secret: String,+ headers: serde_json::Value,+ ) -> impl Future<Output = Result<Webhook, Self::Err>> + Send;++ /// Get an active webhook by id.+ fn get_webhook(+ &self,+ webhook_id: WebhookId,+ ) -> impl Future<Output = Result<Option<Webhook>, Self::Err>> + Send;++ /// Patch an active webhook.+ fn patch_webhook(+ &self,+ webhook_id: WebhookId,+ request: PatchWebhookRequest,+ ) -> impl Future<Output = Result<Option<Webhook>, Self::Err>> + Send;++ /// Soft-delete an active webhook.+ fn delete_webhook(+ &self,+ webhook_id: WebhookId,+ ) -> impl Future<Output = Result<Option<Webhook>, Self::Err>> + Send;++ /// Set the validation state for an active webhook.+ fn set_webhook_validity(+ &self,+ webhook_id: WebhookId,+ is_valid: bool,+ ) -> impl Future<Output = Result<Option<Webhook>, Self::Err>> + Send;++ /// Look up the team workspace id for a user.+ fn get_user_team_workspace_id(+ &self,+ user_id: MacroUserIdStr<'static>,+ ) -> impl Future<Output = Result<Option<String>, Self::Err>> + Send;+}++/// Client used to send a signed webhook validation delivery.+pub trait WebhookValidationClient: Clone + Send + Sync + 'static {+ /// Client error.+ type Err: Into<anyhow::Error> + Send;++ /// Attempt a signed test delivery to the current endpoint.+ fn validate_webhook(+ &self,+ webhook: Webhook,+ ) -> impl Future<Output = Result<WebhookValidationResult, Self::Err>> + Send;+}++/// Webhook service.+pub trait WebhookService: Clone + Send + Sync + 'static {+ /// Create a webhook.+ fn create_webhook(+ &self,+ caller: MacroUserIdStr<'static>,+ request: CreateWebhookRequest,+ ) -> impl Future<Output = Result<Webhook, WebhookError>> + Send;++ /// Patch a webhook.+ fn patch_webhook(+ &self,+ caller: MacroUserIdStr<'static>,+ webhook_id: WebhookId,+ request: PatchWebhookRequest,+ ) -> impl Future<Output = Result<Webhook, WebhookError>> + Send;++ /// Validate a webhook endpoint.+ fn validate_webhook(+ &self,+ caller: MacroUserIdStr<'static>,+ webhook_id: WebhookId,+ ) -> impl Future<Output = Result<ValidateWebhookResponse, WebhookError>> + Send;++ /// Delete a webhook.+ fn delete_webhook(+ &self,+ caller: MacroUserIdStr<'static>,+ webhook_id: WebhookId,+ ) -> impl Future<Output = Result<(), WebhookError>> + Send;+}++/// Webhook service error.+#[derive(Debug, thiserror::Error)]+pub enum WebhookError {+ /// Bad request.+ #[error("{0}")]+ BadRequest(String),+ /// Unauthorized.+ #[error("unauthorized")]+ Unauthorized,+ /// Not found.+ #[error("{0}")]+ NotFound(String),+ /// Repository or adapter error.+ #[error(transparent)]+ Repo(#[from] anyhow::Error),+}diff --git a/rust/cloud-storage/webhook/src/domain/service.rs b/rust/cloud-storage/webhook/src/domain/service.rsnew file mode 100644index 0000000000..ed10907a0c--- /dev/null+++ b/rust/cloud-storage/webhook/src/domain/service.rs@@ -0,0 +1,327 @@+//! Webhook service implementation.++use super::{+ models::{+ CreateWebhookRequest, PatchWebhookRequest, ValidateWebhookResponse, Webhook, WebhookId,+ WebhookScope, WebhookValidationResult,+ },+ ports::{WebhookError, WebhookRepo, WebhookService, WebhookValidationClient},+};+use chrono::Utc;+use macro_user_id::user_id::MacroUserIdStr;+use std::net::IpAddr;+use url::Url;++const MAX_NAME_LEN: usize = 128;+const VALIDATION_EVENT_NAME: &str = "webhook.validation.test";++/// Webhook service implementation.+#[derive(Debug, Clone)]+pub struct WebhookServiceImpl<R, V> {+ repo: R,+ validation_client: V,+}++impl<R, V> WebhookServiceImpl<R, V> {+ /// Create a webhook service.+ pub fn new(repo: R, validation_client: V) -> Self {+ Self {+ repo,+ validation_client,+ }+ }+}++fn validate_name(name: &str) -> Result<(), WebhookError> {+ let name = name.trim();+ if name.is_empty() || name.len() > MAX_NAME_LEN {+ return Err(WebhookError::BadRequest(format!(+ "name must be non-empty and at most {MAX_NAME_LEN} characters"+ )));+ }+ Ok(())+}++fn validate_endpoint_url(endpoint_url: &str) -> Result<(), WebhookError> {+ let url = Url::parse(endpoint_url)+ .map_err(|_| WebhookError::BadRequest("endpoint_url must be a valid URL".to_string()))?;++ if url.scheme() != "https" {+ return Err(WebhookError::BadRequest(+ "endpoint_url must use https".to_string(),+ ));+ }++ let Some(host) = url.host_str() else {+ return Err(WebhookError::BadRequest(+ "endpoint_url must include a host".to_string(),+ ));+ };++ if is_blocked_endpoint_host(host) {+ return Err(WebhookError::BadRequest(+ "endpoint_url host is not allowed".to_string(),+ ));+ }++ Ok(())+}++fn is_blocked_endpoint_host(host: &str) -> bool {+ let host = host.trim_matches(['[', ']']).to_ascii_lowercase();+ if host == "localhost" || host.ends_with(".localhost") {+ return true;+ }++ host.parse::<IpAddr>().is_ok_and(is_blocked_endpoint_ip)+}++fn is_blocked_endpoint_ip(ip: IpAddr) -> bool {+ match ip {+ IpAddr::V4(ip) => {+ ip.is_private()+ || ip.is_loopback()+ || ip.is_link_local()+ || ip.is_broadcast()+ || ip.is_unspecified()+ || ip.octets() == [169, 254, 169, 254]+ }+ IpAddr::V6(ip) => {+ ip.is_loopback()+ || ip.is_unspecified()+ || ip.is_unique_local()+ || (ip.segments()[0] & 0xffc0) == 0xfe80+ }+ }+}++fn validate_rule(rule: &serde_json::Value) -> Result<(), WebhookError> {+ let events = rule+ .get("events")+ .and_then(serde_json::Value::as_array)+ .ok_or_else(|| WebhookError::BadRequest("rule.events must be an array".to_string()))?;++ if events.is_empty() || !events.iter().all(|event| event.as_str().is_some()) {+ return Err(WebhookError::BadRequest(+ "rule.events must be a non-empty array of strings".to_string(),+ ));+ }++ Ok(())+}++fn validate_create_request(request: &CreateWebhookRequest) -> Result<(), WebhookError> {+ validate_name(&request.name)?;+ validate_endpoint_url(&request.endpoint_url)?;+ validate_rule(&request.rule)+}++fn validate_patch_request(request: &PatchWebhookRequest) -> Result<(), WebhookError> {+ if let Some(name) = &request.name {+ validate_name(name)?;+ }+ if let Some(endpoint_url) = &request.endpoint_url {+ validate_endpoint_url(endpoint_url)?;+ }+ if let Some(rule) = &request.rule {+ validate_rule(rule)?;+ }+ Ok(())+}++fn webhook_is_missing(webhook: &Webhook) -> bool {+ webhook.deleted_at.is_some()+}++fn generate_signing_secret(caller: &MacroUserIdStr<'_>) -> String {+ format!(+ "whsec_{}_{}",+ caller.as_ref(),+ Utc::now().timestamp_nanos_opt().unwrap_or_default()+ )+}++fn validation_response(+ webhook_id: WebhookId,+ result: WebhookValidationResult,+) -> ValidateWebhookResponse {+ ValidateWebhookResponse {+ webhook_id,+ is_valid: result.is_valid,+ response_status: result.response_status,+ message: result.message,+ }+}++impl<R, V> WebhookServiceImpl<R, V>+where+ R: WebhookRepo,+ V: WebhookValidationClient,+{+ async fn workspace_id_for_scope(+ &self,+ caller: MacroUserIdStr<'static>,+ scope: WebhookScope,+ ) -> Result<String, WebhookError> {+ match scope {+ WebhookScope::User => Ok(caller.as_ref().to_string()),+ WebhookScope::Team => self+ .repo+ .get_user_team_workspace_id(caller)+ .await+ .map_err(|err| WebhookError::Repo(err.into()))?+ .ok_or_else(|| {+ WebhookError::BadRequest(+ "team scope requires the user to belong to a team".to_string(),+ )+ }),+ }+ }++ async fn caller_owns_workspace(+ &self,+ caller: MacroUserIdStr<'static>,+ workspace_id: &str,+ ) -> Result<bool, WebhookError> {+ if workspace_id == caller.as_ref() {+ return Ok(true);+ }++ let team_workspace_id = self+ .repo+ .get_user_team_workspace_id(caller)+ .await+ .map_err(|err| WebhookError::Repo(err.into()))?;++ Ok(team_workspace_id.as_deref() == Some(workspace_id))+ }++ async fn load_authorized_webhook(+ &self,+ caller: MacroUserIdStr<'static>,+ webhook_id: WebhookId,+ ) -> Result<Webhook, WebhookError> {+ let webhook = self+ .repo+ .get_webhook(webhook_id)+ .await+ .map_err(|err| WebhookError::Repo(err.into()))?+ .filter(|webhook| !webhook_is_missing(webhook))+ .ok_or_else(|| WebhookError::NotFound("webhook not found".to_string()))?;++ if !self+ .caller_owns_workspace(caller, &webhook.workspace_id)+ .await?+ {+ return Err(WebhookError::Unauthorized);+ }++ Ok(webhook)+ }+}++impl<R, V> WebhookService for WebhookServiceImpl<R, V>+where+ R: WebhookRepo,+ V: WebhookValidationClient,+{+ async fn create_webhook(+ &self,+ caller: MacroUserIdStr<'static>,+ request: CreateWebhookRequest,+ ) -> Result<Webhook, WebhookError> {+ validate_create_request(&request)?;++ let workspace_id = self+ .workspace_id_for_scope(caller.clone(), request.scope)+ .await?;++ let signing_secret = generate_signing_secret(&caller);+ let headers = serde_json::to_value(request.headers.clone().unwrap_or_default())+ .map_err(|err| WebhookError::Repo(err.into()))?;+ let mut webhook = self+ .repo+ .create_webhook(caller, workspace_id, request, signing_secret, headers)+ .await+ .map_err(|err| WebhookError::Repo(err.into()))?;+ webhook.is_valid = false;+ Ok(webhook)+ }++ async fn patch_webhook(+ &self,+ caller: MacroUserIdStr<'static>,+ webhook_id: WebhookId,+ request: PatchWebhookRequest,+ ) -> Result<Webhook, WebhookError> {+ let webhook = self+ .load_authorized_webhook(caller, webhook_id.clone())+ .await?;+ validate_patch_request(&request)?;+ let reset_validity = request.endpoint_url.is_some() || request.headers.is_some();++ let patched = self+ .repo+ .patch_webhook(webhook.id, request)+ .await+ .map_err(|err| WebhookError::Repo(err.into()))?+ .ok_or_else(|| WebhookError::NotFound("webhook not found".to_string()))?;++ if !reset_validity {+ return Ok(patched);+ }++ self.repo+ .set_webhook_validity(patched.id, false)+ .await+ .map_err(|err| WebhookError::Repo(err.into()))?+ .ok_or_else(|| WebhookError::NotFound("webhook not found".to_string()))+ }++ async fn validate_webhook(+ &self,+ caller: MacroUserIdStr<'static>,+ webhook_id: WebhookId,+ ) -> Result<ValidateWebhookResponse, WebhookError> {+ let webhook = self+ .load_authorized_webhook(caller, webhook_id.clone())+ .await?;+ let result = self+ .validation_client+ .validate_webhook(webhook)+ .await+ .map_err(|err| WebhookError::Repo(err.into()))?;+ let is_valid = result.is_valid;++ self.repo+ .set_webhook_validity(webhook_id.clone(), is_valid)+ .await+ .map_err(|err| WebhookError::Repo(err.into()))?+ .ok_or_else(|| WebhookError::NotFound("webhook not found".to_string()))?;++ Ok(validation_response(webhook_id, result))+ }++ async fn delete_webhook(+ &self,+ caller: MacroUserIdStr<'static>,+ webhook_id: WebhookId,+ ) -> Result<(), WebhookError> {+ let webhook = self+ .load_authorized_webhook(caller, webhook_id.clone())+ .await?;++ self.repo+ .delete_webhook(webhook.id)+ .await+ .map_err(|err| WebhookError::Repo(err.into()))?+ .ok_or_else(|| WebhookError::NotFound("webhook not found".to_string()))?;++ Ok(())+ }+}++/// Test event name used by validation adapters.+pub const fn validation_event_name() -> &'static str {+ VALIDATION_EVENT_NAME+}diff --git a/rust/cloud-storage/webhook/src/domain/service_test.rs b/rust/cloud-storage/webhook/src/domain/service_test.rsnew file mode 100644index 0000000000..e459d3260f--- /dev/null+++ b/rust/cloud-storage/webhook/src/domain/service_test.rs@@ -0,0 +1,392 @@+use super::{+ models::{+ CreateWebhookRequest, PatchWebhookRequest, ValidateWebhookResponse, Webhook, WebhookScope,+ WebhookStatus, WebhookValidationResult,+ },+ ports::{WebhookError, WebhookRepo, WebhookService, WebhookValidationClient},+ service::WebhookServiceImpl,+};+use chrono::Utc;+use macro_user_id::user_id::MacroUserIdStr;+use std::{collections::BTreeMap, sync::Arc};+use tokio::sync::Mutex;++#[derive(Debug, Default)]+struct RepoState {+ team_workspace_id: Option<String>,+ webhook: Option<Webhook>,+ validation_updates: Vec<bool>,+}++#[derive(Clone, Default)]+struct FakeRepo {+ state: Arc<Mutex<RepoState>>,+}++impl FakeRepo {+ async fn with_webhook(webhook: Webhook, team_workspace_id: Option<String>) -> Self {+ let repo = Self::default();+ let mut state = repo.state.lock().await;+ state.webhook = Some(webhook);+ state.team_workspace_id = team_workspace_id;+ drop(state);+ repo+ }+}++impl WebhookRepo for FakeRepo {+ type Err = anyhow::Error;++ async fn create_webhook(+ &self,+ created_by_user_id: MacroUserIdStr<'static>,+ workspace_id: String,+ request: CreateWebhookRequest,+ _signing_secret: String,+ _headers: serde_json::Value,+ ) -> Result<Webhook, Self::Err> {+ let webhook = webhook_from_create(created_by_user_id, workspace_id, request);+ self.state.lock().await.webhook = Some(webhook.clone());+ Ok(webhook)+ }++ async fn get_webhook(&self, webhook_id: String) -> Result<Option<Webhook>, Self::Err> {+ Ok(self+ .state+ .lock()+ .await+ .webhook+ .clone()+ .filter(|webhook| webhook.id == webhook_id))+ }++ async fn patch_webhook(+ &self,+ webhook_id: String,+ request: PatchWebhookRequest,+ ) -> Result<Option<Webhook>, Self::Err> {+ let mut state = self.state.lock().await;+ let Some(webhook) = state+ .webhook+ .as_mut()+ .filter(|webhook| webhook.id == webhook_id)+ else {+ return Ok(None);+ };+ if let Some(name) = request.name {+ webhook.name = name;+ }+ if let Some(endpoint_url) = request.endpoint_url {+ webhook.endpoint_url = endpoint_url;+ }+ if let Some(headers) = request.headers {+ webhook.headers = headers;+ }+ if let Some(rule) = request.rule {+ webhook.rule = rule;+ }+ if let Some(status) = request.status {+ webhook.status = status;+ }+ Ok(Some(webhook.clone()))+ }++ async fn delete_webhook(&self, webhook_id: String) -> Result<Option<Webhook>, Self::Err> {+ let mut state = self.state.lock().await;+ let webhook = state+ .webhook+ .as_mut()+ .filter(|webhook| webhook.id == webhook_id)+ .map(|webhook| {+ webhook.deleted_at = Some(Utc::now());+ webhook.clone()+ });+ Ok(webhook)+ }++ async fn set_webhook_validity(+ &self,+ webhook_id: String,+ is_valid: bool,+ ) -> Result<Option<Webhook>, Self::Err> {+ let mut state = self.state.lock().await;+ state.validation_updates.push(is_valid);+ let Some(webhook) = state+ .webhook+ .as_mut()+ .filter(|webhook| webhook.id == webhook_id)+ else {+ return Ok(None);+ };+ webhook.is_valid = is_valid;+ Ok(Some(webhook.clone()))+ }++ async fn get_user_team_workspace_id(+ &self,+ _user_id: MacroUserIdStr<'static>,+ ) -> Result<Option<String>, Self::Err> {+ Ok(self.state.lock().await.team_workspace_id.clone())+ }+}++#[derive(Clone)]+struct FakeValidationClient {+ result: WebhookValidationResult,+ calls: Arc<Mutex<usize>>,+}++impl FakeValidationClient {+ fn succeeds() -> Self {+ Self::new(WebhookValidationResult {+ is_valid: true,+ response_status: Some(204),+ message: None,+ })+ }++ fn fails() -> Self {+ Self::new(WebhookValidationResult {+ is_valid: false,+ response_status: Some(500),+ message: Some("webhook returned HTTP 500".to_string()),+ })+ }++ fn new(result: WebhookValidationResult) -> Self {+ Self {+ result,+ calls: Arc::new(Mutex::new(0)),+ }+ }++ async fn call_count(&self) -> usize {+ *self.calls.lock().await+ }+}++impl Default for FakeValidationClient {+ fn default() -> Self {+ Self::succeeds()+ }+}++impl WebhookValidationClient for FakeValidationClient {+ type Err = anyhow::Error;++ async fn validate_webhook(+ &self,+ _webhook: Webhook,+ ) -> Result<WebhookValidationResult, Self::Err> {+ *self.calls.lock().await += 1;+ Ok(self.result.clone())+ }+}++fn caller() -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from_email("[email protected]").unwrap()+}++fn valid_rule() -> serde_json::Value {+ serde_json::json!({ "events": ["file.created"] })+}++fn create_request() -> CreateWebhookRequest {+ CreateWebhookRequest {+ scope: WebhookScope::User,+ name: "Files".to_string(),+ endpoint_url: "https://example.com/webhook".to_string(),+ headers: Some(BTreeMap::from([(+ "X-Custom".to_string(),+ "value".to_string(),+ )])),+ rule: valid_rule(),+ }+}++fn patch_request() -> PatchWebhookRequest {+ PatchWebhookRequest {+ name: Some("Updated".to_string()),+ endpoint_url: None,+ headers: None,+ rule: None,+ status: None,+ }+}++fn webhook_from_create(+ created_by_user_id: MacroUserIdStr<'static>,+ workspace_id: String,+ request: CreateWebhookRequest,+) -> Webhook {+ let now = Utc::now();+ Webhook {+ id: "wh_test".to_string(),+ workspace_id,+ name: request.name,+ endpoint_url: request.endpoint_url,+ signing_secret: "secret".to_string(),+ headers: request.headers.unwrap_or_default(),+ status: WebhookStatus::Active,+ is_valid: true,+ created_by_user_id: created_by_user_id.as_ref().to_string(),+ created_at: now,+ updated_at: now,+ deleted_at: None,+ rule: request.rule,+ }+}++fn existing_webhook() -> Webhook {+ webhook_from_create(caller(), caller().as_ref().to_string(), create_request())+}++fn assert_bad_request<T>(result: Result<T, WebhookError>) {+ assert!(matches!(result, Err(WebhookError::BadRequest(_))));+}++#[tokio::test]+async fn create_succeeds_for_user_scope() {+ let repo = FakeRepo::default();+ let service = WebhookServiceImpl::new(repo, FakeValidationClient::default());++ let webhook = service+ .create_webhook(caller(), create_request())+ .await+ .unwrap();++ assert_eq!(webhook.id, "wh_test");+ assert!(!webhook.is_valid);+}++#[tokio::test]+async fn create_fails_bad_request_when_team_scope_user_has_no_team() {+ let service = WebhookServiceImpl::new(FakeRepo::default(), FakeValidationClient::default());+ let mut request = create_request();+ request.scope = WebhookScope::Team;++ let result = service.create_webhook(caller(), request).await;++ assert!(matches!(+ result,+ Err(WebhookError::BadRequest(message)) if message == "team scope requires the user to belong to a team"+ ));+}++#[tokio::test]+async fn patch_fails_not_found_for_missing_id() {+ let repo = FakeRepo::default();+ let service = WebhookServiceImpl::new(repo, FakeValidationClient::default());++ let result = service+ .patch_webhook(caller(), "wh_missing".to_string(), patch_request())+ .await;++ assert!(matches!(result, Err(WebhookError::NotFound(_))));+}++#[tokio::test]+async fn patch_fails_unauthorized_when_caller_does_not_own_workspace() {+ let mut webhook = existing_webhook();+ webhook.workspace_id = "other_workspace".to_string();+ let repo = FakeRepo::with_webhook(webhook, None).await;+ let service = WebhookServiceImpl::new(repo, FakeValidationClient::default());++ let result = service+ .patch_webhook(caller(), "wh_test".to_string(), patch_request())+ .await;++ assert!(matches!(result, Err(WebhookError::Unauthorized)));+}++#[tokio::test]+async fn invalid_http_endpoint_is_rejected() {+ let repo = FakeRepo::default();+ let service = WebhookServiceImpl::new(repo, FakeValidationClient::default());+ let mut request = create_request();+ request.endpoint_url = "http://example.com/webhook".to_string();++ assert_bad_request(service.create_webhook(caller(), request).await);+}++#[tokio::test]+async fn private_and_link_local_endpoints_are_rejected() {+ let repo = FakeRepo::default();+ let service = WebhookServiceImpl::new(repo, FakeValidationClient::default());++ for endpoint_url in [+ "https://localhost/webhook",+ "https://10.1.2.3/webhook",+ "https://172.16.0.1/webhook",+ "https://192.168.1.1/webhook",+ "https://169.254.169.254/latest/meta-data",+ "https://[fe80::1]/webhook",+ ] {+ let mut request = create_request();+ request.endpoint_url = endpoint_url.to_string();++ assert_bad_request(service.create_webhook(caller(), request).await);+ }+}++#[tokio::test]+async fn empty_events_array_is_rejected() {+ let repo = FakeRepo::default();+ let service = WebhookServiceImpl::new(repo, FakeValidationClient::default());+ let mut request = create_request();+ request.rule = serde_json::json!({ "events": [] });++ assert_bad_request(service.create_webhook(caller(), request).await);+}++#[tokio::test]+async fn validate_succeeds_and_sets_webhook_validity() {+ let repo = FakeRepo::with_webhook(existing_webhook(), None).await;+ let service = WebhookServiceImpl::new(repo.clone(), FakeValidationClient::succeeds());++ let response = service+ .validate_webhook(caller(), "wh_test".to_string())+ .await+ .unwrap();++ assert!(response.is_valid);+ assert_eq!(response.response_status, Some(204));+ assert_eq!(repo.state.lock().await.validation_updates, vec![true]);+}++#[tokio::test]+async fn validate_fails_unauthorized_before_calling_validation_client() {+ let mut webhook = existing_webhook();+ webhook.workspace_id = "other_workspace".to_string();+ let repo = FakeRepo::with_webhook(webhook, None).await;+ let validation_client = FakeValidationClient::succeeds();+ let service = WebhookServiceImpl::new(repo, validation_client.clone());++ let result = service+ .validate_webhook(caller(), "wh_test".to_string())+ .await;++ assert!(matches!(result, Err(WebhookError::Unauthorized)));+ assert_eq!(validation_client.call_count().await, 0);+}++#[tokio::test]+async fn validate_records_invalid_and_returns_sanitized_failure() {+ let repo = FakeRepo::with_webhook(existing_webhook(), None).await;+ let service = WebhookServiceImpl::new(repo.clone(), FakeValidationClient::fails());++ let ValidateWebhookResponse {+ is_valid,+ response_status,+ message,+ ..+ } = service+ .validate_webhook(caller(), "wh_test".to_string())+ .await+ .unwrap();++ assert!(!is_valid);+ assert_eq!(response_status, Some(500));+ assert_eq!(message.as_deref(), Some("webhook returned HTTP 500"));+ assert_eq!(repo.state.lock().await.validation_updates, vec![false]);+}diff --git a/rust/cloud-storage/webhook/src/inbound/axum_router.rs b/rust/cloud-storage/webhook/src/inbound/axum_router.rsnew file mode 100644index 0000000000..e8585db1b7--- /dev/null+++ b/rust/cloud-storage/webhook/src/inbound/axum_router.rs@@ -0,0 +1,271 @@+//! Axum router for webhook APIs.++use crate::domain::{+ models::{+ CreateWebhookRequest, PatchWebhookRequest, ValidateWebhookResponse, Webhook, WebhookId,+ },+ ports::{WebhookError, WebhookService},+};+use axum::{+ Json, RequestPartsExt, Router,+ extract::{FromRef, FromRequestParts, Path, State},+ http::StatusCode,+ response::{IntoResponse, Response},+ routing::{patch, post},+};+use axum_extra::extract::Cached;+use model_error_response::ErrorResponse;+use model_user::axum_extractor::MacroUserExtractor;+use rate_limit::inbound::{RateLimitExtractable, rate_limit_middleware};+use rate_limit::{RateLimitConfig, RateLimitKey, RateLimitService};+use std::sync::Arc;+use std::time::Duration;++/// State for the webhook router.+pub struct WebhookRouterState<S, R> {+ service: Arc<S>,+ rate_limiter: R,+}++impl<S, R: Clone> Clone for WebhookRouterState<S, R> {+ fn clone(&self) -> Self {+ Self {+ service: self.service.clone(),+ rate_limiter: self.rate_limiter.clone(),+ }+ }+}++impl<S: WebhookService, R: RateLimitService + Clone> WebhookRouterState<S, R> {+ /// Create webhook router state.+ pub fn new(service: S, rate_limiter: R) -> Self {+ Self {+ service: Arc::new(service),+ rate_limiter,+ }+ }+}++impl<S, R: Clone> FromRef<WebhookRouterState<S, R>> for Arc<S> {+ fn from_ref(state: &WebhookRouterState<S, R>) -> Self {+ state.service.clone()+ }+}++/// Webhook path parameters.+#[derive(Debug, serde::Deserialize)]+pub struct WebhookPath {+ /// Webhook id.+ pub webhook_id: WebhookId,+}++/// Per-user validation attempt rate limit.+pub struct PerUserValidateWebhookRateLimit {+ user: MacroUserExtractor,+ webhook_id: WebhookId,+}++impl<S> RateLimitExtractable<S> for PerUserValidateWebhookRateLimit+where+ S: Send + Sync,+{+ fn config() -> RateLimitConfig {+ RateLimitConfig {+ max_count: 10,+ window: Duration::from_secs(3600),+ }+ }++ fn key(&self) -> RateLimitKey {+ RateLimitKey::builder(&"per-user-validate-webhook")+ .append(&self.user.macro_user_id.as_ref())+ .append(&self.webhook_id)+ .finish()+ }+}++impl<S> FromRequestParts<S> for PerUserValidateWebhookRateLimit+where+ S: Send + Sync,+{+ type Rejection = Response;++ async fn from_request_parts(+ parts: &mut axum::http::request::Parts,+ state: &S,+ ) -> Result<Self, Self::Rejection> {+ let Cached(user): Cached<MacroUserExtractor> = parts+ .extract_with_state(state)+ .await+ .map_err(IntoResponse::into_response)?;+ let Path(path): Path<WebhookPath> = parts+ .extract_with_state(state)+ .await+ .map_err(IntoResponse::into_response)?;++ Ok(Self {+ user,+ webhook_id: path.webhook_id,+ })+ }+}++/// Create a webhook API router.+pub fn webhook_router<S, R, T>(state: WebhookRouterState<S, R>) -> Router<T>+where+ S: WebhookService,+ R: RateLimitService + Clone,+ T: Send + Sync,+{+ let validate_route = Router::new()+ .route(+ "/webhooks/{webhook_id}/validate",+ post(validate_webhook::<S>),+ )+ .layer(axum::middleware::from_fn_with_state(+ state.rate_limiter.clone(),+ rate_limit_middleware::<R, PerUserValidateWebhookRateLimit, R>,+ ));++ Router::new()+ .route("/webhooks", post(create_webhook::<S>))+ .route(+ "/webhooks/{webhook_id}",+ patch(patch_webhook::<S>).delete(delete_webhook::<S>),+ )+ .merge(validate_route)+ .with_state(state)+}++/// Create a webhook.+#[utoipa::path(+ post,+ path = "/webhook/webhooks",+ request_body = CreateWebhookRequest,+ responses(+ (status = 201, description = "Webhook created", body = Webhook),+ (status = 400, description = "Bad request", body = ErrorResponse),+ (status = 403, description = "Forbidden", body = ErrorResponse),+ (status = 500, description = "Internal server error", body = ErrorResponse),+ ),+ tag = "webhook"+)]+pub async fn create_webhook<S: WebhookService>(+ State(service): State<Arc<S>>,+ user: MacroUserExtractor,+ Json(request): Json<CreateWebhookRequest>,+) -> Result<(StatusCode, Json<Webhook>), WebhookHandlerError> {+ let webhook = service.create_webhook(user.macro_user_id, request).await?;+ Ok((StatusCode::CREATED, Json(webhook)))+}++/// Patch a webhook.+#[utoipa::path(+ patch,+ path = "/webhook/webhooks/{webhook_id}",+ params(("webhook_id" = String, Path, description = "Webhook id")),+ request_body = PatchWebhookRequest,+ responses(+ (status = 200, description = "Webhook updated", body = Webhook),+ (status = 400, description = "Bad request", body = ErrorResponse),+ (status = 403, description = "Forbidden", body = ErrorResponse),+ (status = 404, description = "Webhook not found", body = ErrorResponse),+ (status = 500, description = "Internal server error", body = ErrorResponse),+ ),+ tag = "webhook"+)]+pub async fn patch_webhook<S: WebhookService>(+ State(service): State<Arc<S>>,+ user: MacroUserExtractor,+ Path(path): Path<WebhookPath>,+ Json(request): Json<PatchWebhookRequest>,+) -> Result<Json<Webhook>, WebhookHandlerError> {+ Ok(Json(+ service+ .patch_webhook(user.macro_user_id, path.webhook_id, request)+ .await?,+ ))+}++/// Delete a webhook.+#[utoipa::path(+ delete,+ path = "/webhook/webhooks/{webhook_id}",+ params(("webhook_id" = String, Path, description = "Webhook id")),+ responses(+ (status = 204, description = "Webhook deleted"),+ (status = 403, description = "Forbidden", body = ErrorResponse),+ (status = 404, description = "Webhook not found", body = ErrorResponse),+ (status = 500, description = "Internal server error", body = ErrorResponse),+ ),+ tag = "webhook"+)]+pub async fn delete_webhook<S: WebhookService>(+ State(service): State<Arc<S>>,+ user: MacroUserExtractor,+ Path(path): Path<WebhookPath>,+) -> Result<StatusCode, WebhookHandlerError> {+ service+ .delete_webhook(user.macro_user_id, path.webhook_id)+ .await?;+ Ok(StatusCode::NO_CONTENT)+}++/// Validate a webhook endpoint.+#[utoipa::path(+ post,+ path = "/webhook/webhooks/{webhook_id}/validate",+ params(("webhook_id" = String, Path, description = "Webhook id")),+ responses(+ (status = 200, description = "Webhook validation result", body = ValidateWebhookResponse),+ (status = 403, description = "Forbidden", body = ErrorResponse),+ (status = 404, description = "Webhook not found", body = ErrorResponse),+ (status = 429, description = "Rate limited", body = ErrorResponse),+ (status = 500, description = "Internal server error", body = ErrorResponse),+ ),+ tag = "webhook"+)]+pub async fn validate_webhook<S: WebhookService>(+ State(service): State<Arc<S>>,+ user: MacroUserExtractor,+ Path(path): Path<WebhookPath>,+) -> Result<Json<ValidateWebhookResponse>, WebhookHandlerError> {+ Ok(Json(+ service+ .validate_webhook(user.macro_user_id, path.webhook_id)+ .await?,+ ))+}++/// Webhook handler error.+pub struct WebhookHandlerError(WebhookError);++impl From<WebhookError> for WebhookHandlerError {+ fn from(error: WebhookError) -> Self {+ Self(error)+ }+}++impl IntoResponse for WebhookHandlerError {+ fn into_response(self) -> Response {+ let status = match self.0 {+ WebhookError::BadRequest(_) => StatusCode::BAD_REQUEST,+ WebhookError::Unauthorized => StatusCode::FORBIDDEN,+ WebhookError::NotFound(_) => StatusCode::NOT_FOUND,+ WebhookError::Repo(_) => StatusCode::INTERNAL_SERVER_ERROR,+ };+ let message = if status == StatusCode::INTERNAL_SERVER_ERROR {+ tracing::error!(error=?self.0, "webhook handler error");+ "internal server error".to_string()+ } else {+ self.0.to_string()+ };+ (+ status,+ Json(ErrorResponse {+ message: message.into(),+ }),+ )+ .into_response()+ }+}diff --git a/rust/cloud-storage/webhook/src/inbound/axum_router_test.rs b/rust/cloud-storage/webhook/src/inbound/axum_router_test.rsnew file mode 100644index 0000000000..403cd4af7f--- /dev/null+++ b/rust/cloud-storage/webhook/src/inbound/axum_router_test.rs@@ -0,0 +1,435 @@+use super::axum_router::{WebhookRouterState, webhook_router};+use crate::domain::{+ models::{+ CreateWebhookRequest, PatchWebhookRequest, ValidateWebhookResponse, Webhook, WebhookId,+ },+ ports::{WebhookError, WebhookService},+};+use axum::{+ body::{Body, to_bytes},+ http::{Request, StatusCode},+};+use macro_user_id::user_id::MacroUserIdStr;+use model_user::UserContext;+use rate_limit::{RateLimitConfig, RateLimitKey, RateLimitService};+use serde_json::json;+use std::sync::{Arc, Mutex};+use tower::ServiceExt;++#[derive(Clone, Default)]+struct FakeService {+ calls: Arc<Mutex<Vec<ServiceCall>>>,+ response: Arc<Mutex<Option<Result<ServiceResponse, WebhookError>>>>,+}++#[derive(Debug)]+enum ServiceCall {+ Create(MacroUserIdStr<'static>, CreateWebhookRequest),+ Patch(MacroUserIdStr<'static>, WebhookId, PatchWebhookRequest),+ Validate(MacroUserIdStr<'static>, WebhookId),+ Delete(MacroUserIdStr<'static>, WebhookId),+}++enum ServiceResponse {+ Webhook(Webhook),+ Validate(ValidateWebhookResponse),+}++impl FakeService {+ fn set_response(&self, response: Result<ServiceResponse, WebhookError>) {+ *self.response.lock().unwrap() = Some(response);+ }++ fn calls(&self) -> Vec<ServiceCall> {+ self.calls.lock().unwrap().clone()+ }+}++impl Clone for ServiceCall {+ fn clone(&self) -> Self {+ match self {+ Self::Create(user, request) => Self::Create(user.clone(), request.clone()),+ Self::Patch(user, id, request) => {+ Self::Patch(user.clone(), id.clone(), request.clone())+ }+ Self::Validate(user, id) => Self::Validate(user.clone(), id.clone()),+ Self::Delete(user, id) => Self::Delete(user.clone(), id.clone()),+ }+ }+}++impl WebhookService for FakeService {+ async fn create_webhook(+ &self,+ caller: MacroUserIdStr<'static>,+ request: CreateWebhookRequest,+ ) -> Result<Webhook, WebhookError> {+ self.calls+ .lock()+ .unwrap()+ .push(ServiceCall::Create(caller, request));+ match self+ .response+ .lock()+ .unwrap()+ .take()+ .unwrap_or_else(|| Ok(ServiceResponse::Webhook(webhook())))?+ {+ ServiceResponse::Webhook(webhook) => Ok(webhook),+ ServiceResponse::Validate(_) => panic!("unexpected validate response"),+ }+ }++ async fn patch_webhook(+ &self,+ caller: MacroUserIdStr<'static>,+ webhook_id: WebhookId,+ request: PatchWebhookRequest,+ ) -> Result<Webhook, WebhookError> {+ self.calls+ .lock()+ .unwrap()+ .push(ServiceCall::Patch(caller, webhook_id, request));+ match self+ .response+ .lock()+ .unwrap()+ .take()+ .unwrap_or_else(|| Ok(ServiceResponse::Webhook(webhook())))?+ {+ ServiceResponse::Webhook(webhook) => Ok(webhook),+ ServiceResponse::Validate(_) => panic!("unexpected validate response"),+ }+ }++ async fn validate_webhook(+ &self,+ caller: MacroUserIdStr<'static>,+ webhook_id: WebhookId,+ ) -> Result<ValidateWebhookResponse, WebhookError> {+ self.calls+ .lock()+ .unwrap()+ .push(ServiceCall::Validate(caller, webhook_id));+ match self+ .response+ .lock()+ .unwrap()+ .take()+ .unwrap_or_else(|| Ok(ServiceResponse::Validate(validate_response(true))))?+ {+ ServiceResponse::Validate(response) => Ok(response),+ ServiceResponse::Webhook(_) => panic!("unexpected webhook response"),+ }+ }++ async fn delete_webhook(+ &self,+ caller: MacroUserIdStr<'static>,+ webhook_id: WebhookId,+ ) -> Result<(), WebhookError> {+ self.calls+ .lock()+ .unwrap()+ .push(ServiceCall::Delete(caller, webhook_id));+ match self.response.lock().unwrap().take() {+ Some(Err(error)) => Err(error),+ _ => Ok(()),+ }+ }+}++#[derive(Clone, Default)]+struct FakeRateLimiter {+ exceeded: bool,+ checks: Arc<Mutex<usize>>,+ rollbacks: Arc<Mutex<usize>>,+}++impl FakeRateLimiter {+ fn exceeded() -> Self {+ Self {+ exceeded: true,+ ..Self::default()+ }+ }++ fn checks(&self) -> usize {+ *self.checks.lock().unwrap()+ }+}++impl RateLimitService for FakeRateLimiter {+ async fn check_rate_limit(+ &self,+ key: RateLimitKey,+ config: RateLimitConfig,+ ) -> Result<rate_limit::RateLimitResult, rootcause::Report> {+ *self.checks.lock().unwrap() += 1;+ if self.exceeded {+ return Ok(Err(rate_limit::RateLimitExceeded {+ current_count: config.max_count,+ max_count: config.max_count,+ retry_after: config.window,+ }));+ }+ Ok(Ok(+ rate_limit::domain::models::RateLimitOk::new_testing_value(1, key, config),+ ))+ }++ async fn rollback_ticket(+ &self,+ _ticket: rate_limit::domain::models::RateLimitOk,+ ) -> Result<(), rootcause::Report> {+ *self.rollbacks.lock().unwrap() += 1;+ Ok(())+ }+}++#[tokio::test]+async fn create_passes_authenticated_user_and_body_to_service() {+ let service = FakeService::default();+ let response = send(+ service.clone(),+ FakeRateLimiter::default(),+ "POST",+ "/webhooks",+ create_body(),+ )+ .await;++ assert_eq!(response.status(), StatusCode::CREATED);+ match &service.calls()[0] {+ ServiceCall::Create(user, request) => {+ assert_eq!(user.as_ref(), user_id());+ assert_eq!(request.name, "Events");+ }+ other => panic!("unexpected call: {other:?}"),+ }+}++#[tokio::test]+async fn patch_passes_authenticated_user_path_and_body_to_service() {+ let service = FakeService::default();+ let response = send(+ service.clone(),+ FakeRateLimiter::default(),+ "PATCH",+ "/webhooks/wh_123",+ json!({"name":"Renamed"}),+ )+ .await;++ assert_eq!(response.status(), StatusCode::OK);+ match &service.calls()[0] {+ ServiceCall::Patch(user, webhook_id, request) => {+ assert_eq!(user.as_ref(), user_id());+ assert_eq!(webhook_id, "wh_123");+ assert_eq!(request.name.as_deref(), Some("Renamed"));+ }+ other => panic!("unexpected call: {other:?}"),+ }+}++#[tokio::test]+async fn validate_passes_authenticated_user_and_path_to_service() {+ let service = FakeService::default();+ let limiter = FakeRateLimiter::default();+ let response = send(+ service.clone(),+ limiter.clone(),+ "POST",+ "/webhooks/wh_123/validate",+ json!({}),+ )+ .await;++ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(limiter.checks(), 1);+ match &service.calls()[0] {+ ServiceCall::Validate(user, webhook_id) => {+ assert_eq!(user.as_ref(), user_id());+ assert_eq!(webhook_id, "wh_123");+ }+ other => panic!("unexpected call: {other:?}"),+ }+}++#[tokio::test]+async fn validate_remote_failure_returns_ok_and_consumes_rate_limit() {+ let service = FakeService::default();+ service.set_response(Ok(ServiceResponse::Validate(ValidateWebhookResponse {+ webhook_id: "wh_123".to_string(),+ is_valid: false,+ response_status: Some(500),+ message: Some("webhook returned HTTP 500".to_string()),+ })));+ let limiter = FakeRateLimiter::default();++ let response = send(+ service,+ limiter.clone(),+ "POST",+ "/webhooks/wh_123/validate",+ json!({}),+ )+ .await;+ let status = response.status();+ let body = response_json(response).await;++ assert_eq!(status, StatusCode::OK);+ assert_eq!(body["is_valid"], false);+ assert_eq!(body["message"], "webhook returned HTTP 500");+ assert_eq!(limiter.checks(), 1);+}++#[tokio::test]+async fn validation_rate_limit_exceeded_maps_to_429_and_skips_service() {+ let service = FakeService::default();+ let response = send(+ service.clone(),+ FakeRateLimiter::exceeded(),+ "POST",+ "/webhooks/wh_123/validate",+ json!({}),+ )+ .await;++ assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);+ assert!(service.calls().is_empty());+}++#[tokio::test]+async fn create_and_patch_are_not_rate_limited() {+ let service = FakeService::default();+ let limiter = FakeRateLimiter::exceeded();++ let create_response = send(+ service.clone(),+ limiter.clone(),+ "POST",+ "/webhooks",+ create_body(),+ )+ .await;+ let patch_response = send(+ service,+ limiter.clone(),+ "PATCH",+ "/webhooks/wh_123",+ json!({"name":"Renamed"}),+ )+ .await;++ assert_eq!(create_response.status(), StatusCode::CREATED);+ assert_eq!(patch_response.status(), StatusCode::OK);+ assert_eq!(limiter.checks(), 0);+}++#[tokio::test]+async fn service_unauthorized_maps_to_403() {+ let service = FakeService::default();+ service.set_response(Err(WebhookError::Unauthorized));++ let response = send(+ service,+ FakeRateLimiter::default(),+ "POST",+ "/webhooks",+ create_body(),+ )+ .await;++ assert_eq!(response.status(), StatusCode::FORBIDDEN);+}++#[tokio::test]+async fn bad_request_maps_to_400() {+ let service = FakeService::default();+ service.set_response(Err(WebhookError::BadRequest(+ "invalid endpoint".to_string(),+ )));++ let response = send(+ service,+ FakeRateLimiter::default(),+ "POST",+ "/webhooks",+ create_body(),+ )+ .await;++ assert_eq!(response.status(), StatusCode::BAD_REQUEST);+}++async fn send(+ service: FakeService,+ limiter: FakeRateLimiter,+ method: &str,+ uri: &str,+ body: serde_json::Value,+) -> axum::response::Response {+ let router = webhook_router::<_, _, ()>(WebhookRouterState::new(service, limiter));+ router+ .oneshot(+ Request::builder()+ .method(method)+ .uri(uri)+ .extension(UserContext {+ user_id: user_id().to_string(),+ ..UserContext::default()+ })+ .header("content-type", "application/json")+ .body(Body::from(body.to_string()))+ .unwrap(),+ )+ .await+ .unwrap()+}++async fn response_json(response: axum::response::Response) -> serde_json::Value {+ let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();+ serde_json::from_slice(&bytes).unwrap()+}++fn create_body() -> serde_json::Value {+ json!({+ "scope": "user",+ "name": "Events",+ "endpoint_url": "https://example.com/webhook",+ "headers": {"x-custom": "value"},+ "rule": {"events": ["document.created"]}+ })+}++fn validate_response(is_valid: bool) -> ValidateWebhookResponse {+ ValidateWebhookResponse {+ webhook_id: "wh_123".to_string(),+ is_valid,+ response_status: Some(200),+ message: None,+ }+}++fn webhook() -> Webhook {+ serde_json::from_value(json!({+ "id": "wh_123",+ "workspace_id": "workspace_1",+ "name": "Events",+ "endpoint_url": "https://example.com/webhook",+ "headers": {},+ "status": "active",+ "is_valid": false,+ "created_by_user_id": user_id(),+ "created_at": "2026-06-29T00:00:00Z",+ "updated_at": "2026-06-29T00:00:00Z",+ "deleted_at": null,+ "rule": {"events": ["document.created"]}+ }))+ .unwrap()+}++fn user_id() -> &'static str {+ "macro|[email protected]"+}diff --git a/rust/cloud-storage/webhook/src/inbound/mod.rs b/rust/cloud-storage/webhook/src/inbound/mod.rsnew file mode 100644index 0000000000..33f3d31aba--- /dev/null+++ b/rust/cloud-storage/webhook/src/inbound/mod.rs@@ -0,0 +1,6 @@+//! Inbound HTTP adapters.++pub mod axum_router;++#[cfg(test)]+mod axum_router_test;diff --git a/rust/cloud-storage/webhook/src/lib.rs b/rust/cloud-storage/webhook/src/lib.rsnew file mode 100644index 0000000000..116059b185--- /dev/null+++ b/rust/cloud-storage/webhook/src/lib.rs@@ -0,0 +1,34 @@+#![deny(missing_docs)]+//! Webhook management hex crate.+//!+//! This crate currently contains the core application-layer webhook pieces for+//! the first iteration:+//!+//! - database tables for event ingestion, webhooks, deliveries, and delivery+//! attempts;+//! - a repository that can create, get, patch, and update webhook validity via+//! `is_valid`;+//! - inbound handlers for `POST /webhooks`, `PATCH /webhooks/{webhook_id}`, and+//! `POST /webhooks/{webhook_id}/validate`;+//! - validation that sends a signed `webhook.validation.test` event and persists+//! the result in `is_valid`;+//! - validation attempt rate limiting with the existing `rate_limit` crate using+//! the key shape `per-user-validate-webhook:{macro_user_id}:{webhook_id}` and+//! a limit of 10 attempts per 3600-second window.+//!+//! The current implementation intentionally excludes delivery workers, SQS/SNS+//! infrastructure, event ingestion, redelivery, and auto-pause behavior.+//!+//! Temporary limitations: IDs use prefixed UUIDv7 strings (`wh_<uuid_v7>`)+//! rather than true ULIDs. Custom headers are stored as JSON in `headers`.+//! Webhook signing secrets are intentionally stored as plaintext in+//! `signing_secret`, matching the existing bot secret storage approach.++/// Domain models, ports, and service.+pub mod domain;+#[cfg(feature = "inbound")]+/// HTTP adapters.+pub mod inbound;+#[cfg(feature = "outbound")]+/// Postgres and HTTP adapters.+pub mod outbound;diff --git a/rust/cloud-storage/webhook/src/outbound.rs b/rust/cloud-storage/webhook/src/outbound.rsnew file mode 100644index 0000000000..6e941a08e0--- /dev/null+++ b/rust/cloud-storage/webhook/src/outbound.rs@@ -0,0 +1,7 @@+//! Outbound adapters.++pub mod http_validator;+pub mod pg_repository;++pub use http_validator::ReqwestWebhookValidationClient;+pub use pg_repository::PgRepository;diff --git a/rust/cloud-storage/webhook/src/outbound/http_validator.rs b/rust/cloud-storage/webhook/src/outbound/http_validator.rsnew file mode 100644index 0000000000..592387ee4f--- /dev/null+++ b/rust/cloud-storage/webhook/src/outbound/http_validator.rs@@ -0,0 +1,207 @@+//! HTTP webhook validation client.++#[cfg(test)]+#[path = "http_validator_test.rs"]+mod http_validator_test;++use crate::domain::{+ models::{Webhook, WebhookValidationResult},+ ports::WebhookValidationClient,+};+use hmac::{Hmac, Mac};+use reqwest::{Client, StatusCode, Url, redirect::Policy};+use serde_json::json;+use sha2::Sha256;+use std::{net::IpAddr, time::Duration};+use tokio::net::lookup_host;++const EVENT_NAME: &str = "webhook.validation.test";+const REQUEST_TIMEOUT: Duration = Duration::from_secs(5);++type HmacSha256 = Hmac<Sha256>;++/// Reqwest-backed implementation of [`WebhookValidationClient`].+#[derive(Clone)]+pub struct ReqwestWebhookValidationClient {+ client: Client,+}++impl ReqwestWebhookValidationClient {+ /// Create a validation client with the required webhook delivery limits.+ pub fn new() -> Result<Self, reqwest::Error> {+ let client = Client::builder()+ .timeout(REQUEST_TIMEOUT)+ .redirect(Policy::none())+ .build()?;++ Ok(Self { client })+ }+}++impl WebhookValidationClient for ReqwestWebhookValidationClient {+ type Err = anyhow::Error;++ async fn validate_webhook(+ &self,+ webhook: Webhook,+ ) -> Result<WebhookValidationResult, Self::Err> {+ let url = match validate_resolved_endpoint_url(&webhook.endpoint_url).await {+ Ok(url) => url,+ Err(message) => return Ok(failure(None, message)),+ };++ let event_id = new_validation_event_id();+ let timestamp = chrono::Utc::now().timestamp().to_string();+ let body = validation_body(&webhook.id, &event_id)?;+ let signature = signature_header(&webhook.signing_secret, ×tamp, &body)?;++ let mut request = self+ .client+ .post(url)+ .header(reqwest::header::CONTENT_TYPE, "application/json")+ .header("X-Macro-Event", EVENT_NAME)+ .header("X-Macro-Event-Id", event_id)+ .header("X-Macro-Timestamp", ×tamp)+ .header("X-Macro-Signature", signature);++ for (name, value) in webhook.headers {+ if is_reserved_macro_header(&name) {+ return Ok(failure(None, "reserved Macro headers cannot be overridden"));+ }+ request = request.header(name, value);+ }++ let response = match request.body(body).send().await {+ Ok(response) => response,+ Err(error) if error.is_timeout() => {+ return Ok(failure(None, "validation timed out after 5 seconds"));+ }+ Err(_) => return Ok(failure(None, "webhook endpoint could not be reached")),+ };++ let status = response.status();+ if status.is_success() {+ return Ok(WebhookValidationResult {+ is_valid: true,+ response_status: Some(status.as_u16()),+ message: None,+ });+ }++ Ok(failure(+ Some(status),+ format!("webhook returned HTTP {}", status.as_u16()),+ ))+ }+}++fn new_validation_event_id() -> String {+ format!("evt_{}", macro_uuid::generate_uuid_v7())+}++fn validation_body(webhook_id: &str, event_id: &str) -> Result<Vec<u8>, serde_json::Error> {+ serde_json::to_vec(&json!({+ "id": event_id,+ "event": EVENT_NAME,+ "webhook_id": webhook_id,+ }))+}++fn signature_header(+ secret: &str,+ timestamp: &str,+ raw_body: &[u8],+) -> Result<String, anyhow::Error> {+ let mut mac = HmacSha256::new_from_slice(secret.as_bytes())?;+ mac.update(timestamp.as_bytes());+ mac.update(b".");+ mac.update(raw_body);+ Ok(format!("v1={}", hex::encode(mac.finalize().into_bytes())))+}++async fn validate_resolved_endpoint_url(value: &str) -> Result<Url, &'static str> {+ let url = validate_endpoint_url(value)?;+ let Some(host) = url.host_str().map(str::to_owned) else {+ return Err("webhook endpoint URL host is invalid");+ };+ let Some(port) = url.port_or_known_default() else {+ return Err("webhook endpoint URL port is invalid");+ };++ let mut resolved = lookup_host((host.as_str(), port))+ .await+ .map_err(|_| "webhook endpoint host could not be resolved")?;+ let mut saw_address = false;+ for address in resolved.by_ref() {+ saw_address = true;+ if is_blocked_ip(address.ip()) {+ return Err("webhook endpoint host resolves to a disallowed address");+ }+ }++ if !saw_address {+ return Err("webhook endpoint host could not be resolved");+ }++ Ok(url)+}++fn validate_endpoint_url(value: &str) -> Result<Url, &'static str> {+ let url = Url::parse(value).map_err(|_| "webhook endpoint URL is invalid")?;+ if url.scheme() != "https" {+ return Err("webhook endpoint URL must use HTTPS");+ }++ let Some(host) = url.host_str() else {+ return Err("webhook endpoint URL host is invalid");+ };++ if is_blocked_host(host) {+ return Err("webhook endpoint host is not allowed");+ }++ Ok(url)+}++fn is_blocked_host(host: &str) -> bool {+ let host = host.trim_matches(['[', ']']).to_ascii_lowercase();+ if host == "localhost" || host.ends_with(".localhost") {+ return true;+ }++ host.parse::<IpAddr>().is_ok_and(is_blocked_ip)+}++fn is_blocked_ip(ip: IpAddr) -> bool {+ match ip {+ IpAddr::V4(ip) => {+ ip.is_private()+ || ip.is_loopback()+ || ip.is_link_local()+ || ip.is_broadcast()+ || ip.is_unspecified()+ || ip.octets() == [169, 254, 169, 254]+ }+ IpAddr::V6(ip) => {+ ip.is_loopback()+ || ip.is_unspecified()+ || ip.is_unique_local()+ || (ip.segments()[0] & 0xffc0) == 0xfe80+ }+ }+}++fn is_reserved_macro_header(name: &str) -> bool {+ matches!(+ name.to_ascii_lowercase().as_str(),+ "x-macro-event" | "x-macro-event-id" | "x-macro-timestamp" | "x-macro-signature"+ )+}++fn failure(status: Option<StatusCode>, message: impl Into<String>) -> WebhookValidationResult {+ WebhookValidationResult {+ is_valid: false,+ response_status: status.map(|status| status.as_u16()),+ message: Some(message.into()),+ }+}diff --git a/rust/cloud-storage/webhook/src/outbound/http_validator_test.rs b/rust/cloud-storage/webhook/src/outbound/http_validator_test.rsnew file mode 100644index 0000000000..20bce9cb95--- /dev/null+++ b/rust/cloud-storage/webhook/src/outbound/http_validator_test.rs@@ -0,0 +1,79 @@+use super::*;++#[test]+fn builds_deterministic_validation_body() {+ let body = validation_body("wh_test", "evt_test").expect("body should serialize");+ let value: serde_json::Value = serde_json::from_slice(&body).expect("body should be json");++ assert_eq!(value["id"], "evt_test");+ assert_eq!(value["event"], EVENT_NAME);+ assert_eq!(value["webhook_id"], "wh_test");+}++#[test]+fn generates_unique_validation_event_ids() {+ let first = new_validation_event_id();+ let second = new_validation_event_id();++ assert!(first.starts_with("evt_"));+ assert!(second.starts_with("evt_"));+ assert_ne!(first, second);+}++#[test]+fn signs_timestamp_and_raw_body() {+ let body = br#"{"event":"webhook.validation.test"}"#;+ let signature = signature_header("secret", "123", body).expect("signature should be created");++ assert_eq!(+ signature,+ "v1=5837022b9dec7b19dc354f820eeac2a9d4935737b6686363613a5e691095b8e5"+ );+}++#[test]+fn rejects_non_https_endpoint() {+ let error = validate_endpoint_url("http://example.com/webhook").expect_err("http is invalid");++ assert_eq!(error, "webhook endpoint URL must use HTTPS");+}++#[test]+fn rejects_localhost_and_private_ips() {+ assert!(validate_endpoint_url("https://localhost/webhook").is_err());+ assert!(validate_endpoint_url("https://127.0.0.1/webhook").is_err());+ assert!(validate_endpoint_url("https://10.1.2.3/webhook").is_err());+ assert!(validate_endpoint_url("https://169.254.169.254/latest/meta-data").is_err());+ assert!(validate_endpoint_url("https://[::1]/webhook").is_err());+ assert!(validate_endpoint_url("https://[fe80::1]/webhook").is_err());+}++#[tokio::test]+async fn rejects_hosts_that_resolve_to_blocked_addresses() {+ let error = validate_resolved_endpoint_url("https://localhost/webhook")+ .await+ .expect_err("localhost is invalid");++ assert_eq!(error, "webhook endpoint host is not allowed");+}++#[test]+fn blocks_ipv6_link_local_addresses() {+ let ip = "fe80::1".parse().expect("valid ipv6");++ assert!(is_blocked_ip(ip));+}++#[test]+fn accepts_public_https_endpoint() {+ let url = validate_endpoint_url("https://example.com/webhook").expect("public https is valid");++ assert_eq!(url.host_str(), Some("example.com"));+}++#[test]+fn detects_reserved_headers_case_insensitively() {+ assert!(is_reserved_macro_header("X-Macro-Signature"));+ assert!(is_reserved_macro_header("x-macro-event-id"));+ assert!(!is_reserved_macro_header("X-External-Trace"));+}diff --git a/rust/cloud-storage/webhook/src/outbound/pg_repository.rs b/rust/cloud-storage/webhook/src/outbound/pg_repository.rsnew file mode 100644index 0000000000..e234197fb1--- /dev/null+++ b/rust/cloud-storage/webhook/src/outbound/pg_repository.rs@@ -0,0 +1,258 @@+//! PostgreSQL webhook repository.+#[cfg(test)]+#[path = "pg_repository_test.rs"]+mod pg_repository_test;++use crate::domain::{+ models::{+ CreateWebhookRequest, PatchWebhookRequest, Webhook, WebhookHeaders, WebhookId,+ WebhookStatus,+ },+ ports::WebhookRepo,+};+use macro_user_id::user_id::MacroUserIdStr;+use serde_json::Value;+use sqlx::PgPool;+use std::str::FromStr;++/// PostgreSQL-backed implementation of [`WebhookRepo`].+#[derive(Clone)]+pub struct PgRepository {+ pool: PgPool,+}++impl PgRepository {+ /// Create a new PgRepository.+ pub fn new(pool: PgPool) -> Self {+ Self { pool }+ }+}++#[derive(sqlx::FromRow)]+struct WebhookRow {+ id: String,+ workspace_id: String,+ name: String,+ endpoint_url: String,+ signing_secret: String,+ headers: Value,+ status: String,+ is_valid: bool,+ created_by_user_id: String,+ created_at: chrono::DateTime<chrono::Utc>,+ updated_at: chrono::DateTime<chrono::Utc>,+ deleted_at: Option<chrono::DateTime<chrono::Utc>>,+ rule: Value,+}++fn new_webhook_id() -> String {+ // Temporary prefixed UUIDv7 ids. This can be swapped for true ULIDs later.+ format!("wh_{}", macro_uuid::generate_uuid_v7())+}++fn parse_headers(value: Value) -> WebhookHeaders {+ serde_json::from_value(value).unwrap_or_default()+}++fn row_to_webhook(row: WebhookRow) -> Result<Webhook, sqlx::Error> {+ let status =+ WebhookStatus::from_str(&row.status).map_err(|message| sqlx::Error::ColumnDecode {+ index: "status".to_string(),+ source: message.into(),+ })?;++ Ok(Webhook {+ id: row.id.clone(),+ workspace_id: row.workspace_id.clone(),+ name: row.name,+ endpoint_url: row.endpoint_url,+ signing_secret: row.signing_secret,+ headers: parse_headers(row.headers),+ status,+ is_valid: row.is_valid,+ created_by_user_id: row.created_by_user_id,+ created_at: row.created_at,+ updated_at: row.updated_at,+ deleted_at: row.deleted_at,+ rule: row.rule,+ })+}++async fn fetch_webhook(pool: &PgPool, webhook_id: &str) -> Result<Option<Webhook>, sqlx::Error> {+ let row = sqlx::query_as!(+ WebhookRow,+ r#"+ SELECT+ w.id,+ w.workspace_id,+ w.name,+ w.endpoint_url,+ w.signing_secret,+ w.headers,+ w.status,+ w.is_valid,+ w.created_by_user_id,+ w.created_at,+ w.updated_at,+ w.deleted_at,+ w.rule+ FROM webhook w+ WHERE w.id = $1+ AND w.deleted_at IS NULL+ "#,+ webhook_id+ )+ .fetch_optional(pool)+ .await?;++ row.map(row_to_webhook).transpose()+}++impl WebhookRepo for PgRepository {+ type Err = sqlx::Error;++ #[tracing::instrument(skip(self, request, signing_secret, headers), err)]+ async fn create_webhook(+ &self,+ created_by_user_id: MacroUserIdStr<'static>,+ workspace_id: String,+ request: CreateWebhookRequest,+ signing_secret: String,+ headers: Value,+ ) -> Result<Webhook, Self::Err> {+ let webhook_id = new_webhook_id();+ let status = WebhookStatus::Active.as_str();+ let created_by_user_id = created_by_user_id.as_ref();+ sqlx::query!(+ r#"+ INSERT INTO webhook (+ id, workspace_id, name, endpoint_url, signing_secret, headers,+ rule, status, is_valid, created_by_user_id+ )+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, false, $9)+ "#,+ webhook_id,+ workspace_id,+ request.name,+ request.endpoint_url,+ signing_secret,+ headers,+ request.rule,+ status,+ created_by_user_id+ )+ .execute(&self.pool)+ .await?;+ fetch_webhook(&self.pool, &webhook_id)+ .await?+ .ok_or(sqlx::Error::RowNotFound)+ }++ #[tracing::instrument(skip(self), err)]+ async fn get_webhook(&self, webhook_id: WebhookId) -> Result<Option<Webhook>, Self::Err> {+ fetch_webhook(&self.pool, &webhook_id).await+ }++ #[tracing::instrument(skip(self, request), err)]+ async fn patch_webhook(+ &self,+ webhook_id: WebhookId,+ request: PatchWebhookRequest,+ ) -> Result<Option<Webhook>, Self::Err> {+ let headers = request.headers.map(|headers| {+ serde_json::to_value(headers).unwrap_or_else(|_| Value::Object(Default::default()))+ });+ let status = request.status.map(WebhookStatus::as_str);+ let updated = sqlx::query!(+ r#"+ UPDATE webhook+ SET+ name = COALESCE($2, name),+ endpoint_url = COALESCE($3, endpoint_url),+ headers = COALESCE($4, headers),+ rule = COALESCE($5, rule),+ status = COALESCE($6, status),+ is_valid = CASE WHEN $3::TEXT IS NOT NULL OR $4::JSONB IS NOT NULL THEN false ELSE is_valid END,+ updated_at = now()+ WHERE id = $1 AND deleted_at IS NULL+ "#,+ webhook_id,+ request.name,+ request.endpoint_url,+ headers,+ request.rule,+ status+ )+ .execute(&self.pool)+ .await?;++ if updated.rows_affected() == 0 {+ return Ok(None);+ }+ fetch_webhook(&self.pool, &webhook_id).await+ }++ #[tracing::instrument(skip(self), err)]+ async fn delete_webhook(&self, webhook_id: WebhookId) -> Result<Option<Webhook>, Self::Err> {+ let webhook = fetch_webhook(&self.pool, &webhook_id).await?;+ if webhook.is_none() {+ return Ok(None);+ }++ sqlx::query!(+ r#"+ UPDATE webhook+ SET deleted_at = now(), updated_at = now()+ WHERE id = $1 AND deleted_at IS NULL+ "#,+ webhook_id+ )+ .execute(&self.pool)+ .await?;++ Ok(webhook)+ }++ #[tracing::instrument(skip(self), err)]+ async fn set_webhook_validity(+ &self,+ webhook_id: WebhookId,+ is_valid: bool,+ ) -> Result<Option<Webhook>, Self::Err> {+ sqlx::query!(+ r#"+ UPDATE webhook+ SET is_valid = $2, updated_at = now()+ WHERE id = $1 AND deleted_at IS NULL+ "#,+ webhook_id,+ is_valid+ )+ .execute(&self.pool)+ .await?;++ fetch_webhook(&self.pool, &webhook_id).await+ }++ #[tracing::instrument(skip(self), err)]+ async fn get_user_team_workspace_id(+ &self,+ user_id: MacroUserIdStr<'static>,+ ) -> Result<Option<String>, Self::Err> {+ let user_id = user_id.as_ref();+ let team_id = sqlx::query_scalar!(+ r#"+ SELECT team_id+ FROM team_user+ WHERE user_id = $1+ ORDER BY team_role DESC+ LIMIT 1+ "#,+ user_id+ )+ .fetch_optional(&self.pool)+ .await?;++ Ok(team_id.map(|id| id.to_string()))+ }+}diff --git a/rust/cloud-storage/webhook/src/outbound/pg_repository_test.rs b/rust/cloud-storage/webhook/src/outbound/pg_repository_test.rsnew file mode 100644index 0000000000..433beca8e2--- /dev/null+++ b/rust/cloud-storage/webhook/src/outbound/pg_repository_test.rs@@ -0,0 +1,173 @@+use super::*;+use crate::domain::ports::WebhookRepo;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use macro_user_id::user_id::MacroUserIdStr;+use serde_json::json;+use sqlx::{PgPool, types::Uuid};++const USER_ID: &str = "macro|[email protected]";+const TEAM_ID: &str = "11111111-1111-1111-1111-111111111111";++fn user_id() -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from(USER_ID.to_string()).expect("valid macro user id")+}++fn create_request() -> CreateWebhookRequest {+ CreateWebhookRequest {+ scope: crate::domain::models::WebhookScope::User,+ name: "Build events".to_string(),+ endpoint_url: "https://example.com/webhook".to_string(),+ headers: None,+ rule: json!({ "events": ["build.created"] }),+ }+}++async fn insert_user(pool: &PgPool) -> anyhow::Result<()> {+ let macro_user_id = macro_uuid::generate_uuid_v7();+ let stripe_customer_id = format!("stripe_{macro_user_id}");+ sqlx::query!(+ r#"+ INSERT INTO macro_user (id, username, email, stripe_customer_id)+ VALUES ($1, $2, $3, $4)+ ON CONFLICT (id) DO NOTHING+ "#,+ macro_user_id,+ "[email protected]",+ "[email protected]",+ stripe_customer_id+ )+ .execute(pool)+ .await?;++ sqlx::query!(+ r#"+ INSERT INTO "User" (id, email, macro_user_id)+ VALUES ($1, $2, $3)+ ON CONFLICT (id) DO NOTHING+ "#,+ USER_ID,+ "[email protected]",+ macro_user_id+ )+ .execute(pool)+ .await?;++ Ok(())+}++async fn create_webhook(repo: &PgRepository) -> Webhook {+ repo.create_webhook(+ user_id(),+ USER_ID.to_string(),+ create_request(),+ "signing-secret".to_string(),+ json!({ "X-Test": "true" }),+ )+ .await+ .expect("create webhook")+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn create_inserts_webhook_with_rule(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool).await?;+ let repo = PgRepository::new(pool.clone());++ let webhook = create_webhook(&repo).await;++ assert!(webhook.id.starts_with("wh_"));+ assert_eq!(webhook.rule, json!({ "events": ["build.created"] }));+ assert!(!webhook.is_valid);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn patch_updates_endpoint_and_resets_validity(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool).await?;+ let repo = PgRepository::new(pool.clone());+ let webhook = create_webhook(&repo).await;+ repo.set_webhook_validity(webhook.id.clone(), true).await?;++ let patched = repo+ .patch_webhook(+ webhook.id,+ PatchWebhookRequest {+ name: Some("Deploy events".to_string()),+ endpoint_url: Some("https://example.com/deploy".to_string()),+ headers: None,+ rule: None,+ status: None,+ },+ )+ .await?+ .expect("patched webhook");++ assert_eq!(patched.name, "Deploy events");+ assert_eq!(patched.endpoint_url, "https://example.com/deploy");+ assert!(!patched.is_valid);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn set_webhook_validity_marks_valid_and_invalid(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool).await?;+ let repo = PgRepository::new(pool);+ let webhook = create_webhook(&repo).await;++ let valid = repo+ .set_webhook_validity(webhook.id.clone(), true)+ .await?+ .expect("valid webhook");+ let invalid = repo+ .set_webhook_validity(webhook.id, false)+ .await?+ .expect("invalid webhook");++ assert!(valid.is_valid);+ assert!(!invalid.is_valid);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_webhook_excludes_deleted_rows(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool).await?;+ let repo = PgRepository::new(pool.clone());+ let webhook = create_webhook(&repo).await;++ sqlx::query!(+ "UPDATE webhook SET deleted_at = now() WHERE id = $1",+ webhook.id+ )+ .execute(&pool)+ .await?;++ assert!(repo.get_webhook(webhook.id).await?.is_none());+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_user_team_workspace_id_returns_team_membership(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool).await?;+ let team_id = Uuid::parse_str(TEAM_ID)?;+ sqlx::query!(+ r#"INSERT INTO team (id, owner_id, name) VALUES ($1, $2, $3)"#,+ team_id,+ USER_ID,+ team_id.to_string(),+ )+ .execute(&pool)+ .await?;+ sqlx::query!(+ r#"INSERT INTO team_user (user_id, team_id, team_role) VALUES ($1, $2, 'member')"#,+ USER_ID,+ team_id+ )+ .execute(&pool)+ .await?;+ let repo = PgRepository::new(pool);++ assert_eq!(+ repo.get_user_team_workspace_id(user_id()).await?,+ Some(TEAM_ID.to_string())+ );+ Ok(())+}