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(channels): bot webhooks (#3883)
Will Hutchinson5e6d6b0ac624
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/bot.ts b/js/app/packages/service-clients/service-storage/generated/schemas/bot.tsnew file mode 100644index 0000000000..913510c81d--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/bot.ts@@ -0,0 +1,40 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { BotAvatarUrl } from './botAvatarUrl';+import type { BotCreatedBy } from './botCreatedBy';+import type { BotDeletedAt } from './botDeletedAt';+import type { BotDescription } from './botDescription';+import type { BotId } from './botId';+import type { BotKind } from './botKind';+import type { BotOwnerProperty } from './botOwnerProperty';++/**+ * Bot row.+ */+export interface Bot {+ /** Optional avatar URL. */+ avatar_url?: BotAvatarUrl;+ /** Creation timestamp. */+ created_at: string;+ /** User that created this bot. */+ created_by?: BotCreatedBy;+ /** Soft-delete timestamp. */+ deleted_at?: BotDeletedAt;+ /** Optional description. */+ description?: BotDescription;+ /** Stable handle. */+ handle: string;+ /** Bot id. */+ id: BotId;+ /** Bot kind. */+ kind: BotKind;+ /** Display name. */+ name: string;+ owner?: BotOwnerProperty;+ /** Update timestamp. */+ updated_at: string;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/botAvatarUrl.ts b/js/app/packages/service-clients/service-storage/generated/schemas/botAvatarUrl.tsnew file mode 100644index 0000000000..f60225973c--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/botAvatarUrl.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Optional avatar URL.+ */+export type BotAvatarUrl = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/botCreatedBy.ts b/js/app/packages/service-clients/service-storage/generated/schemas/botCreatedBy.tsnew file mode 100644index 0000000000..f8713a0fc7--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/botCreatedBy.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * User that created this bot.+ */+export type BotCreatedBy = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/botDeletedAt.ts b/js/app/packages/service-clients/service-storage/generated/schemas/botDeletedAt.tsnew file mode 100644index 0000000000..46ada0f315--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/botDeletedAt.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 BotDeletedAt = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/botDescription.ts b/js/app/packages/service-clients/service-storage/generated/schemas/botDescription.tsnew file mode 100644index 0000000000..96d8e5f533--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/botDescription.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Optional description.+ */+export type BotDescription = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/botId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/botId.tsnew file mode 100644index 0000000000..1d586d341d--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/botId.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 BotId = string;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/botKind.ts b/js/app/packages/service-clients/service-storage/generated/schemas/botKind.tsnew file mode 100644index 0000000000..af4cb70794--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/botKind.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Bot kind.+ */+export type BotKind = (typeof BotKind)[keyof typeof BotKind];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const BotKind = {+ owned: 'owned',+ system: 'system',+} as const;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/botOwner.ts b/js/app/packages/service-clients/service-storage/generated/schemas/botOwner.tsnew file mode 100644index 0000000000..4d8562e4ad--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/botOwner.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { BotOwnerOneOf } from './botOwnerOneOf';+import type { BotOwnerOneOfThree } from './botOwnerOneOfThree';++/**+ * Bot owner.+ */+export type BotOwner = BotOwnerOneOf | BotOwnerOneOfThree;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/botOwnerOneOf.ts b/js/app/packages/service-clients/service-storage/generated/schemas/botOwnerOneOf.tsnew file mode 100644index 0000000000..1fcc6e14a1--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/botOwnerOneOf.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { BotOwnerOneOfType } from './botOwnerOneOfType';++/**+ * User-owned bot.+ */+export type BotOwnerOneOf = {+ type: BotOwnerOneOfType;+ /** Owner user id. */+ user_id: string;+};diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/botOwnerOneOfThree.ts b/js/app/packages/service-clients/service-storage/generated/schemas/botOwnerOneOfThree.tsnew file mode 100644index 0000000000..04344c1be8--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/botOwnerOneOfThree.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { BotOwnerOneOfThreeType } from './botOwnerOneOfThreeType';++/**+ * Team-owned bot.+ */+export type BotOwnerOneOfThree = {+ /** Owner team id. */+ team_id: string;+ type: BotOwnerOneOfThreeType;+};diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/botOwnerOneOfThreeType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/botOwnerOneOfThreeType.tsnew file mode 100644index 0000000000..ec7a6b753a--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/botOwnerOneOfThreeType.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type BotOwnerOneOfThreeType =+ (typeof BotOwnerOneOfThreeType)[keyof typeof BotOwnerOneOfThreeType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const BotOwnerOneOfThreeType = {+ team: 'team',+} as const;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/botOwnerOneOfType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/botOwnerOneOfType.tsnew file mode 100644index 0000000000..6cdc90ff6f--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/botOwnerOneOfType.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type BotOwnerOneOfType =+ (typeof BotOwnerOneOfType)[keyof typeof BotOwnerOneOfType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const BotOwnerOneOfType = {+ user: 'user',+} as const;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/botOwnerProperty.ts b/js/app/packages/service-clients/service-storage/generated/schemas/botOwnerProperty.tsnew file mode 100644index 0000000000..b9ee06e959--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/botOwnerProperty.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 { BotOwner } from './botOwner';++export type BotOwnerProperty = null | BotOwner;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/botToken.ts b/js/app/packages/service-clients/service-storage/generated/schemas/botToken.tsnew file mode 100644index 0000000000..b0c0fb01c7--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/botToken.ts@@ -0,0 +1,33 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { BotId } from './botId';+import type { BotTokenExpiresAt } from './botTokenExpiresAt';+import type { BotTokenLabel } from './botTokenLabel';+import type { BotTokenLastUsedAt } from './botTokenLastUsedAt';+import type { BotTokenRevokedAt } from './botTokenRevokedAt';++/**+ * Bot token metadata.+ */+export interface BotToken {+ /** Owning bot id. */+ bot_id: BotId;+ /** Creation timestamp. */+ created_at: string;+ /** Expiration timestamp. */+ expires_at?: BotTokenExpiresAt;+ /** Token id. */+ id: string;+ /** Optional token label. */+ label?: BotTokenLabel;+ /** Last successful use. */+ last_used_at?: BotTokenLastUsedAt;+ /** Revocation timestamp. */+ revoked_at?: BotTokenRevokedAt;+ /** Token lookup prefix. */+ token_prefix: string;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/botTokenExpiresAt.ts b/js/app/packages/service-clients/service-storage/generated/schemas/botTokenExpiresAt.tsnew file mode 100644index 0000000000..c7104fdb70--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/botTokenExpiresAt.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Expiration timestamp.+ */+export type BotTokenExpiresAt = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/botTokenLabel.ts b/js/app/packages/service-clients/service-storage/generated/schemas/botTokenLabel.tsnew file mode 100644index 0000000000..7170f0faf4--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/botTokenLabel.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Optional token label.+ */+export type BotTokenLabel = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/botTokenLastUsedAt.ts b/js/app/packages/service-clients/service-storage/generated/schemas/botTokenLastUsedAt.tsnew file mode 100644index 0000000000..bd08009c4d--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/botTokenLastUsedAt.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Last successful use.+ */+export type BotTokenLastUsedAt = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/botTokenRevokedAt.ts b/js/app/packages/service-clients/service-storage/generated/schemas/botTokenRevokedAt.tsnew file mode 100644index 0000000000..d46811552f--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/botTokenRevokedAt.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Revocation timestamp.+ */+export type BotTokenRevokedAt = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/channelWebhookRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/channelWebhookRequest.tsnew file mode 100644index 0000000000..f578ae6d44--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/channelWebhookRequest.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Request to post a channel webhook message.+ */+export interface ChannelWebhookRequest {+ /** Message body. */+ content: string;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/channelWebhookResponse.ts b/js/app/packages/service-clients/service-storage/generated/schemas/channelWebhookResponse.tsnew file mode 100644index 0000000000..142c504c86--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/channelWebhookResponse.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Response returned after posting a channel webhook message.+ */+export interface ChannelWebhookResponse {+ /** Created message id. */+ message_id: string;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createChannelScopedBotRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createChannelScopedBotRequest.tsnew file mode 100644index 0000000000..832ffec88f--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createChannelScopedBotRequest.ts@@ -0,0 +1,31 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { CreateChannelScopedBotRequestAvatarUrl } from './createChannelScopedBotRequestAvatarUrl';+import type { CreateChannelScopedBotRequestDescription } from './createChannelScopedBotRequestDescription';+import type { CreateChannelScopedBotRequestTeamId } from './createChannelScopedBotRequestTeamId';+import type { CreateChannelScopedBotRequestTokenExpiresAt } from './createChannelScopedBotRequestTokenExpiresAt';+import type { CreateChannelScopedBotRequestTokenLabel } from './createChannelScopedBotRequestTokenLabel';++/**+ * Request to create a bot scoped to a channel.+ */+export interface CreateChannelScopedBotRequest {+ /** Optional avatar URL. */+ avatar_url?: CreateChannelScopedBotRequestAvatarUrl;+ /** Optional description. */+ description?: CreateChannelScopedBotRequestDescription;+ /** Stable handle. */+ handle: string;+ /** Display name. */+ name: string;+ /** Team owner. Omit for a user-owned bot. */+ team_id?: CreateChannelScopedBotRequestTeamId;+ /** Optional token expiration timestamp. */+ token_expires_at?: CreateChannelScopedBotRequestTokenExpiresAt;+ /** Optional token label. */+ token_label?: CreateChannelScopedBotRequestTokenLabel;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createChannelScopedBotRequestAvatarUrl.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createChannelScopedBotRequestAvatarUrl.tsnew file mode 100644index 0000000000..a6398e8380--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createChannelScopedBotRequestAvatarUrl.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Optional avatar URL.+ */+export type CreateChannelScopedBotRequestAvatarUrl = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createChannelScopedBotRequestDescription.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createChannelScopedBotRequestDescription.tsnew file mode 100644index 0000000000..4ad0bc7b67--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createChannelScopedBotRequestDescription.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Optional description.+ */+export type CreateChannelScopedBotRequestDescription = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createChannelScopedBotRequestTeamId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createChannelScopedBotRequestTeamId.tsnew file mode 100644index 0000000000..b77598e408--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createChannelScopedBotRequestTeamId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Team owner. Omit for a user-owned bot.+ */+export type CreateChannelScopedBotRequestTeamId = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createChannelScopedBotRequestTokenExpiresAt.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createChannelScopedBotRequestTokenExpiresAt.tsnew file mode 100644index 0000000000..3ae6dc6331--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createChannelScopedBotRequestTokenExpiresAt.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Optional token expiration timestamp.+ */+export type CreateChannelScopedBotRequestTokenExpiresAt = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createChannelScopedBotRequestTokenLabel.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createChannelScopedBotRequestTokenLabel.tsnew file mode 100644index 0000000000..5c852e5652--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createChannelScopedBotRequestTokenLabel.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Optional token label.+ */+export type CreateChannelScopedBotRequestTokenLabel = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createChannelScopedBotResponse.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createChannelScopedBotResponse.tsnew file mode 100644index 0000000000..6a16b43eca--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createChannelScopedBotResponse.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { Bot } from './bot';+import type { BotToken } from './botToken';++/**+ * Response containing a newly created channel-scoped bot and token.+ */+export interface CreateChannelScopedBotResponse {+ /** Created bot. */+ bot: Bot;+ /** Raw bot token. */+ bot_token: string;+ /** Token metadata. */+ token: BotToken;+}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 5793030a7a..004742cb77 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@@ -103,6 +103,24 @@ export * from './basicDocumentSubTypeProperty';export * from './basicDocumentType';export * from './basicDocumentUpdatedAt';export * from './bomPart';+export * from './bot';+export * from './botAvatarUrl';+export * from './botCreatedBy';+export * from './botDeletedAt';+export * from './botDescription';+export * from './botId';+export * from './botKind';+export * from './botOwner';+export * from './botOwnerOneOf';+export * from './botOwnerOneOfThree';+export * from './botOwnerOneOfThreeType';+export * from './botOwnerOneOfType';+export * from './botOwnerProperty';+export * from './botToken';+export * from './botTokenExpiresAt';+export * from './botTokenLabel';+export * from './botTokenLastUsedAt';+export * from './botTokenRevokedAt';export * from './branchNameResponse';export * from './bulkWakeupRequest';export * from './bulkWakeupResponse';@@ -171,6 +189,8 @@ export * from './channelPreviewOneOfSevenAllOfType';export * from './channelSharePermission';export * from './channelTeamId';export * from './channelType';+export * from './channelWebhookRequest';+export * from './channelWebhookResponse';export * from './channelWithParticipants';export * from './chat';export * from './chatCreatedAt';@@ -204,6 +224,13 @@ export * from './createChannelRequest';export * from './createChannelRequestName';export * from './createChannelRequestTeamId';export * from './createChannelResponse';+export * from './createChannelScopedBotRequest';+export * from './createChannelScopedBotRequestAvatarUrl';+export * from './createChannelScopedBotRequestDescription';+export * from './createChannelScopedBotRequestTeamId';+export * from './createChannelScopedBotRequestTokenExpiresAt';+export * from './createChannelScopedBotRequestTokenLabel';+export * from './createChannelScopedBotResponse';export * from './createCommentRequest';export * from './createCommentRequestAnchor';export * from './createCommentRequestMentions';diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex 6a5002fd82..44cd1580a7 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -1843,6 +1843,31 @@ export const getChannelAttachmentsResponse = zod}).describe('Paginated response of channel attachments.');+/**+ * @summary Handler for `POST /channels/{channel_id}/bots/scoped`.+ */+export const createChannelScopedBotParams = zod.object({+ channel_id: zod.uuid().describe('Channel ID'),+});++export const createChannelScopedBotBody = zod+ .object({+ avatar_url: zod.string().nullish().describe('Optional avatar URL.'),+ description: zod.string().nullish().describe('Optional description.'),+ handle: zod.string().describe('Stable handle.'),+ name: zod.string().describe('Display name.'),+ team_id: zod+ .uuid()+ .nullish()+ .describe('Team owner. Omit for a user-owned bot.'),+ token_expires_at: zod.iso+ .datetime({})+ .nullish()+ .describe('Optional token expiration timestamp.'),+ token_label: zod.string().nullish().describe('Optional token label.'),+ })+ .describe('Request to create a bot scoped to a channel.');+/*** @summary Handler for `POST /channels/{channel_id}/join`.*/@@ -2634,6 +2659,31 @@ export const postTypingBody = zod}).describe('Request to emit a typing event.');+/**+ * @summary Handler for `POST /channels/{channel_id}/webhook`.+ */+export const postChannelBotWebhookParams = zod.object({+ channel_id: zod.uuid().describe('Channel ID'),+});++export const postChannelBotWebhookHeader = zod.object({+ 'x-macro-channel-bot-token': zod+ .string()+ .describe('Bot authentication token'),+});++export const postChannelBotWebhookBody = zod+ .object({+ content: zod.string().describe('Message body.'),+ })+ .describe('Request to post a channel webhook message.');++export const postChannelBotWebhookResponse = zod+ .object({+ message_id: zod.string().describe('Created message id.'),+ })+ .describe('Response returned after posting a channel webhook message.');+/*** @summary Soft-delete a CRM comment, scoped to the requesting user's team. When itwas the thread's last live comment, the thread is soft-deleted toodiff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 6ce01ba44a..0c76537959 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -2150,6 +2150,87 @@}}},+ "/channels/{channel_id}/bots/scoped": {+ "post": {+ "tags": ["bots"],+ "summary": "Handler for `POST /channels/{channel_id}/bots/scoped`.",+ "operationId": "create_channel_scoped_bot",+ "parameters": [+ {+ "name": "channel_id",+ "in": "path",+ "description": "Channel ID",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreateChannelScopedBotRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "201": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreateChannelScopedBotResponse"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/channels/{channel_id}/join": {"post": {"tags": ["channels"],@@ -3452,6 +3533,96 @@}}},+ "/channels/{channel_id}/webhook": {+ "post": {+ "tags": ["bots"],+ "summary": "Handler for `POST /channels/{channel_id}/webhook`.",+ "operationId": "post_channel_bot_webhook",+ "parameters": [+ {+ "name": "channel_id",+ "in": "path",+ "description": "Channel ID",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ },+ {+ "name": "x-macro-channel-bot-token",+ "in": "header",+ "description": "Bot authentication token",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ChannelWebhookRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ChannelWebhookResponse"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/crm/comment/{comment_id}": {"delete": {"tags": ["crm::inbound::axum_router::comments"],@@ -9472,6 +9643,162 @@}}},+ "Bot": {+ "type": "object",+ "description": "Bot row.",+ "required": [+ "id",+ "kind",+ "name",+ "handle",+ "created_at",+ "updated_at"+ ],+ "properties": {+ "avatar_url": {+ "type": ["string", "null"],+ "description": "Optional avatar URL."+ },+ "created_at": {+ "type": "string",+ "format": "date-time",+ "description": "Creation timestamp."+ },+ "created_by": {+ "type": ["string", "null"],+ "description": "User that created this bot."+ },+ "deleted_at": {+ "type": ["string", "null"],+ "format": "date-time",+ "description": "Soft-delete timestamp."+ },+ "description": {+ "type": ["string", "null"],+ "description": "Optional description."+ },+ "handle": {+ "type": "string",+ "description": "Stable handle."+ },+ "id": {+ "$ref": "#/components/schemas/BotId",+ "description": "Bot id."+ },+ "kind": {+ "$ref": "#/components/schemas/BotKind",+ "description": "Bot kind."+ },+ "name": {+ "type": "string",+ "description": "Display name."+ },+ "owner": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/BotOwner",+ "description": "Owner for owned bots."+ }+ ]+ },+ "updated_at": {+ "type": "string",+ "format": "date-time",+ "description": "Update timestamp."+ }+ }+ },+ "BotId": {+ "type": "string"+ },+ "BotKind": {+ "type": "string",+ "description": "Bot kind.",+ "enum": ["owned", "system"]+ },+ "BotOwner": {+ "oneOf": [+ {+ "type": "object",+ "description": "User-owned bot.",+ "required": ["user_id", "type"],+ "properties": {+ "type": {+ "type": "string",+ "enum": ["user"]+ },+ "user_id": {+ "type": "string",+ "description": "Owner user id."+ }+ }+ },+ {+ "type": "object",+ "description": "Team-owned bot.",+ "required": ["team_id", "type"],+ "properties": {+ "team_id": {+ "type": "string",+ "format": "uuid",+ "description": "Owner team id."+ },+ "type": {+ "type": "string",+ "enum": ["team"]+ }+ }+ }+ ],+ "description": "Bot owner."+ },+ "BotToken": {+ "type": "object",+ "description": "Bot token metadata.",+ "required": ["id", "bot_id", "token_prefix", "created_at"],+ "properties": {+ "bot_id": {+ "$ref": "#/components/schemas/BotId",+ "description": "Owning bot id."+ },+ "created_at": {+ "type": "string",+ "format": "date-time",+ "description": "Creation timestamp."+ },+ "expires_at": {+ "type": ["string", "null"],+ "format": "date-time",+ "description": "Expiration timestamp."+ },+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "Token id."+ },+ "label": {+ "type": ["string", "null"],+ "description": "Optional token label."+ },+ "last_used_at": {+ "type": ["string", "null"],+ "format": "date-time",+ "description": "Last successful use."+ },+ "revoked_at": {+ "type": ["string", "null"],+ "format": "date-time",+ "description": "Revocation timestamp."+ },+ "token_prefix": {+ "type": "string",+ "description": "Token lookup prefix."+ }+ }+ },"BranchNameResponse": {"type": "object","description": "Branch name response.",@@ -10180,6 +10507,28 @@"description": "Type of channel.","enum": ["public", "private", "direct_message", "team"]},+ "ChannelWebhookRequest": {+ "type": "object",+ "description": "Request to post a channel webhook message.",+ "required": ["content"],+ "properties": {+ "content": {+ "type": "string",+ "description": "Message body."+ }+ }+ },+ "ChannelWebhookResponse": {+ "type": "object",+ "description": "Response returned after posting a channel webhook message.",+ "required": ["message_id"],+ "properties": {+ "message_id": {+ "type": "string",+ "description": "Created message id."+ }+ }+ },"ChannelWithParticipants": {"type": "object","required": ["channel", "participants"],@@ -10479,6 +10828,62 @@}}},+ "CreateChannelScopedBotRequest": {+ "type": "object",+ "description": "Request to create a bot scoped to a channel.",+ "required": ["name", "handle"],+ "properties": {+ "avatar_url": {+ "type": ["string", "null"],+ "description": "Optional avatar URL."+ },+ "description": {+ "type": ["string", "null"],+ "description": "Optional description."+ },+ "handle": {+ "type": "string",+ "description": "Stable handle."+ },+ "name": {+ "type": "string",+ "description": "Display name."+ },+ "team_id": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Team owner. Omit for a user-owned bot."+ },+ "token_expires_at": {+ "type": ["string", "null"],+ "format": "date-time",+ "description": "Optional token expiration timestamp."+ },+ "token_label": {+ "type": ["string", "null"],+ "description": "Optional token label."+ }+ }+ },+ "CreateChannelScopedBotResponse": {+ "type": "object",+ "description": "Response containing a newly created channel-scoped bot and token.",+ "required": ["bot", "token", "bot_token"],+ "properties": {+ "bot": {+ "$ref": "#/components/schemas/Bot",+ "description": "Created bot."+ },+ "bot_token": {+ "type": "string",+ "description": "Raw bot token."+ },+ "token": {+ "$ref": "#/components/schemas/BotToken",+ "description": "Token metadata."+ }+ }+ },"CreateCommentRequest": {"type": "object","required": ["text"],diff --git a/rust/cloud-storage/.sqlx/query-6177b5abe20800c5fbfb07f78f44f933169f5ee39129b4bd6fa372311cdc15bb.json b/rust/cloud-storage/.sqlx/query-6177b5abe20800c5fbfb07f78f44f933169f5ee39129b4bd6fa372311cdc15bb.jsonnew file mode 100644index 0000000000..bcd3092856--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-6177b5abe20800c5fbfb07f78f44f933169f5ee39129b4bd6fa372311cdc15bb.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO comms_channel_participants (channel_id, user_id, role, left_at)\n VALUES ($1, $2, 'member'::comms_participant_role, NULL)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "6177b5abe20800c5fbfb07f78f44f933169f5ee39129b4bd6fa372311cdc15bb"+}diff --git a/rust/cloud-storage/.sqlx/query-cbd3dc65e8a0068465b09cf9bf7e2ca71b6832b6c46a075b432cfc5266c05115.json b/rust/cloud-storage/.sqlx/query-cbd3dc65e8a0068465b09cf9bf7e2ca71b6832b6c46a075b432cfc5266c05115.jsonnew file mode 100644index 0000000000..7813ad5fa2--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-cbd3dc65e8a0068465b09cf9bf7e2ca71b6832b6c46a075b432cfc5266c05115.json@@ -0,0 +1,77 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n bt.id AS token_id,\n bt.bot_id,\n bt.token_hash,\n bt.token_prefix,\n bt.label,\n bt.last_used_at,\n bt.expires_at,\n bt.revoked_at,\n bt.created_at,\n b.kind\n FROM bot_tokens bt\n JOIN bots b ON b.id = bt.bot_id\n JOIN comms_channel_participants cp\n ON cp.channel_id = $1\n AND cp.user_id = ('bot|' || b.id::text)\n AND cp.left_at IS NULL\n WHERE bt.token_prefix = $2\n AND b.deleted_at IS NULL\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "token_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "bot_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "token_hash",+ "type_info": "Bytea"+ },+ {+ "ordinal": 3,+ "name": "token_prefix",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "label",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "last_used_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 6,+ "name": "expires_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 7,+ "name": "revoked_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 8,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 9,+ "name": "kind",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ true,+ true,+ true,+ true,+ false,+ false+ ]+ },+ "hash": "cbd3dc65e8a0068465b09cf9bf7e2ca71b6832b6c46a075b432cfc5266c05115"+}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 4b26d299a3..b4826fe2d5 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -1727,6 +1727,7 @@ dependencies = ["anyhow","axum","bot_id",+ "channels","chrono","entity_access","hex",diff --git a/rust/cloud-storage/bots/Cargo.toml b/rust/cloud-storage/bots/Cargo.tomlindex 5f6620eb62..156fa96471 100644--- a/rust/cloud-storage/bots/Cargo.toml+++ b/rust/cloud-storage/bots/Cargo.toml@@ -8,11 +8,13 @@ version = "0.1.0"default = ["inbound", "outbound", "ports"]inbound = ["dep:axum",+ "dep:channels","dep:entity_access","entity_access/inbound","entity_access/ports","dep:model-error-response","dep:model_user",+ "dep:serde_json","dep:utoipa","ports",]@@ -23,6 +25,7 @@ ports = ["dep:tokio"]anyhow = { workspace = true }axum = { workspace = true, optional = true }bot_id = { path = "../bot_id", features = ["schema"] }+channels = { path = "../channels", optional = true, default-features = false, features = ["ports"] }chrono = { workspace = true }entity_access = { path = "../entity_access", optional = true, default-features = false }hex = { workspace = true }@@ -32,6 +35,7 @@ model-error-response = { path = "../model-error-response", optional = true }model_user = { path = "../model_user", optional = true, features = ["axum"] }rand = { workspace = true }serde = { workspace = true }+serde_json = { workspace = true, optional = true }sha2 = { workspace = true }sqlx = { workspace = true, optional = true }thiserror = { workspace = true }diff --git a/rust/cloud-storage/bots/src/domain/models.rs b/rust/cloud-storage/bots/src/domain/models.rsindex 948fea463b..e505b62184 100644--- a/rust/cloud-storage/bots/src/domain/models.rs+++ b/rust/cloud-storage/bots/src/domain/models.rs@@ -175,6 +175,26 @@ pub struct AddChannelBotRequest {pub bot_id: BotId,}+/// Request to create a bot scoped to a channel.+#[derive(Debug, Clone, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+pub struct CreateChannelScopedBotRequest {+ /// Team owner. Omit for a user-owned bot.+ pub team_id: Option<Uuid>,+ /// Display name.+ pub name: String,+ /// Stable handle.+ pub handle: String,+ /// Optional description.+ pub description: Option<String>,+ /// Optional avatar URL.+ pub avatar_url: Option<String>,+ /// Optional token label.+ pub token_label: Option<String>,+ /// Optional token expiration timestamp.+ pub token_expires_at: Option<DateTime<Utc>>,+}+/// Response containing a newly minted token. The raw token is shown once.#[derive(Debug, Clone, Serialize)]#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]@@ -184,3 +204,31 @@ pub struct CreateBotTokenResponse {/// Raw bearer token.pub bearer_token: String,}++/// Response containing a newly created channel-scoped bot and token.+#[derive(Debug, Clone, Serialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+pub struct CreateChannelScopedBotResponse {+ /// Created bot.+ pub bot: Bot,+ /// Token metadata.+ pub token: BotToken,+ /// Raw bot token.+ pub bot_token: String,+}++/// Request to post a channel webhook message.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+pub struct ChannelWebhookRequest {+ /// Message body.+ pub content: String,+}++/// Response returned after posting a channel webhook message.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+pub struct ChannelWebhookResponse {+ /// Created message id.+ pub message_id: String,+}diff --git a/rust/cloud-storage/bots/src/domain/ports.rs b/rust/cloud-storage/bots/src/domain/ports.rsindex 461ea738d1..d5d12fc7cb 100644--- a/rust/cloud-storage/bots/src/domain/ports.rs+++ b/rust/cloud-storage/bots/src/domain/ports.rs@@ -2,7 +2,8 @@use super::models::{AuthenticatedBot, Bot, BotId, BotOwner, BotToken, BotTokenCandidate, CreateBotRequest,- CreateBotTokenRequest, CreateBotTokenResponse, PatchBotRequest,+ CreateBotTokenRequest, CreateBotTokenResponse, CreateChannelScopedBotRequest,+ CreateChannelScopedBotResponse, PatchBotRequest,};use macro_user_id::user_id::MacroUserIdStr;use std::future::Future;@@ -21,6 +22,17 @@ pub trait BotRepo: Clone + Send + Sync + 'static {req: CreateBotRequest,) -> impl Future<Output = Result<Bot, Self::Err>> + Send;+ /// Create an owned bot, add it to a channel, and create a token atomically.+ fn create_channel_scoped_bot(+ &self,+ owner: BotOwner,+ created_by: MacroUserIdStr<'static>,+ channel_id: Uuid,+ token_hash: Vec<u8>,+ token_prefix: String,+ req: CreateChannelScopedBotRequest,+ ) -> impl Future<Output = Result<(Bot, BotToken), Self::Err>> + Send;+/// List active bots manageable by a caller.fn list_manageable_bots(&self,@@ -96,6 +108,13 @@ pub trait BotRepo: Clone + Send + Sync + 'static {token_prefix: &str,) -> impl Future<Output = Result<Vec<BotTokenCandidate>, Self::Err>> + Send;+ /// Lookup token candidates by channel and prefix.+ fn channel_token_candidates(+ &self,+ channel_id: Uuid,+ token_prefix: &str,+ ) -> impl Future<Output = Result<Vec<BotTokenCandidate>, Self::Err>> + Send;+/// Mark a token as used.fn mark_token_used(&self, token_id: Uuid)-> impl Future<Output = Result<(), Self::Err>> + Send;@@ -110,6 +129,14 @@ pub trait BotService: Clone + Send + Sync + 'static {req: CreateBotRequest,) -> impl Future<Output = Result<Bot, BotError>> + Send;+ /// Create a bot owned by the caller and scoped to a channel.+ fn create_channel_scoped_bot(+ &self,+ caller: MacroUserIdStr<'static>,+ channel_id: Uuid,+ req: CreateChannelScopedBotRequest,+ ) -> impl Future<Output = Result<CreateChannelScopedBotResponse, BotError>> + Send;+/// List bots manageable by the caller.fn list_bots(&self,@@ -188,6 +215,13 @@ pub trait BotService: Clone + Send + Sync + 'static {&self,token: &str,) -> impl Future<Output = Result<AuthenticatedBot, BotError>> + Send;++ /// Authenticate a raw bot token scoped to a channel.+ fn authenticate_channel_token(+ &self,+ channel_id: Uuid,+ token: &str,+ ) -> impl Future<Output = Result<AuthenticatedBot, BotError>> + Send;}/// Bot service error.diff --git a/rust/cloud-storage/bots/src/domain/service.rs b/rust/cloud-storage/bots/src/domain/service.rsindex 4e4bc3d10d..e865c54a34 100644--- a/rust/cloud-storage/bots/src/domain/service.rs+++ b/rust/cloud-storage/bots/src/domain/service.rs@@ -2,13 +2,14 @@use super::{models::{- AuthenticatedBot, Bot, BotId, BotKind, BotOwner, BotToken, CreateBotRequest,- CreateBotTokenRequest, PatchBotRequest,+ AuthenticatedBot, Bot, BotId, BotKind, BotOwner, BotToken, BotTokenCandidate,+ CreateBotRequest, CreateBotTokenRequest, CreateChannelScopedBotRequest,+ CreateChannelScopedBotResponse, PatchBotRequest,},ports::{BotError, BotRepo, BotService},tokens,};-use chrono::Utc;+use chrono::{DateTime, Utc};use macro_user_id::user_id::MacroUserIdStr;use uuid::Uuid;@@ -39,10 +40,46 @@ fn validate_handle(handle: &str) -> Result<(), BotError> {Ok(())}+fn token_candidate_is_valid(+ candidate: &BotTokenCandidate,+ hash: &[u8],+ now: &DateTime<Utc>,+) -> bool {+ candidate.token.revoked_at.is_none()+ && candidate+ .token+ .expires_at+ .as_ref()+ .is_none_or(|expires_at| expires_at > now)+ && tokens::verify_hash(&candidate.token_hash, hash)+}+impl<R> BotServiceImpl<R>whereR: BotRepo,{+ async fn owner_for_request(+ &self,+ caller: MacroUserIdStr<'static>,+ team_id: Option<Uuid>,+ ) -> Result<BotOwner, BotError> {+ if let Some(team_id) = team_id {+ if !self+ .repo+ .user_has_team(caller.clone(), team_id)+ .await+ .map_err(|err| BotError::Repo(err.into()))?+ {+ return Err(BotError::Unauthorized);+ }+ return Ok(BotOwner::Team { team_id });+ }++ Ok(BotOwner::User {+ user_id: caller.as_ref().to_string(),+ })+ }+async fn ensure_manageable(&self,caller: MacroUserIdStr<'static>,@@ -77,6 +114,26 @@ where_ => Err(BotError::Unauthorized),}}++ async fn authenticate_candidates(+ &self,+ candidates: Vec<BotTokenCandidate>,+ hash: &[u8],+ ) -> Result<AuthenticatedBot, BotError> {+ let now = Utc::now();+ for candidate in candidates {+ if token_candidate_is_valid(&candidate, hash, &now) {+ let token_id = candidate.token.id;+ let bot = candidate.bot;+ self.repo+ .mark_token_used(token_id)+ .await+ .map_err(|err| BotError::Repo(err.into()))?;+ return Ok(bot);+ }+ }+ Err(BotError::Unauthorized)+ }}impl<R> BotService for BotServiceImpl<R>@@ -89,21 +146,7 @@ wherereq: CreateBotRequest,) -> Result<Bot, BotError> {validate_handle(&req.handle)?;- let owner = if let Some(team_id) = req.team_id {- if !self- .repo- .user_has_team(caller.clone(), team_id)- .await- .map_err(|err| BotError::Repo(err.into()))?- {- return Err(BotError::Unauthorized);- }- BotOwner::Team { team_id }- } else {- BotOwner::User {- user_id: caller.as_ref().to_string(),- }- };+ let owner = self.owner_for_request(caller.clone(), req.team_id).await?;self.repo.create_owned_bot(owner, caller, req)@@ -111,6 +154,35 @@ where.map_err(|err| BotError::Repo(err.into()))}+ async fn create_channel_scoped_bot(+ &self,+ caller: MacroUserIdStr<'static>,+ channel_id: Uuid,+ req: CreateChannelScopedBotRequest,+ ) -> Result<CreateChannelScopedBotResponse, BotError> {+ validate_handle(&req.handle)?;+ let owner = self.owner_for_request(caller.clone(), req.team_id).await?;+ let generated = tokens::generate_token();+ let (bot, token) = self+ .repo+ .create_channel_scoped_bot(+ owner,+ caller,+ channel_id,+ generated.hash,+ generated.prefix,+ req,+ )+ .await+ .map_err(|err| BotError::Repo(err.into()))?;++ Ok(CreateChannelScopedBotResponse {+ bot,+ token,+ bot_token: generated.token,+ })+ }+async fn list_bots(&self, caller: MacroUserIdStr<'static>) -> Result<Vec<Bot>, BotError> {self.repo.list_manageable_bots(caller)@@ -253,26 +325,26 @@ whereasync fn authenticate_token(&self, token: &str) -> Result<AuthenticatedBot, BotError> {let prefix = tokens::token_prefix(token).ok_or(BotError::Unauthorized)?;let hash = tokens::hash_token(token);- for candidate in self+ let candidates = self.repo.token_candidates(prefix).await- .map_err(|err| BotError::Repo(err.into()))?- {- if candidate.token.revoked_at.is_none()- && candidate- .token- .expires_at- .is_none_or(|expires_at| expires_at > Utc::now())- && tokens::verify_hash(&candidate.token_hash, &hash)- {- self.repo- .mark_token_used(candidate.token.id)- .await- .map_err(|err| BotError::Repo(err.into()))?;- return Ok(candidate.bot);- }- }- Err(BotError::Unauthorized)+ .map_err(|err| BotError::Repo(err.into()))?;+ self.authenticate_candidates(candidates, &hash).await+ }++ async fn authenticate_channel_token(+ &self,+ channel_id: Uuid,+ token: &str,+ ) -> Result<AuthenticatedBot, BotError> {+ let prefix = tokens::token_prefix(token).ok_or(BotError::Unauthorized)?;+ let hash = tokens::hash_token(token);+ let candidates = self+ .repo+ .channel_token_candidates(channel_id, prefix)+ .await+ .map_err(|err| BotError::Repo(err.into()))?;+ self.authenticate_candidates(candidates, &hash).await}}diff --git a/rust/cloud-storage/bots/src/domain/tokens.rs b/rust/cloud-storage/bots/src/domain/tokens.rsindex 2034edc603..97013e1d0e 100644--- a/rust/cloud-storage/bots/src/domain/tokens.rs+++ b/rust/cloud-storage/bots/src/domain/tokens.rs@@ -75,4 +75,20 @@ mod tests {);assert!(verify_hash(&generated.hash, &hash_token(&generated.token)));}++ #[test]+ fn generated_token_is_url_path_safe() {+ let generated = generate_token();++ assert!(generated.token.is_ascii());+ assert!(+ generated+ .token+ .chars()+ .all(|ch| ch.is_ascii_alphanumeric() || ch == '_')+ );+ assert!(!generated.token.contains('/'));+ assert!(!generated.token.contains('?'));+ assert!(!generated.token.contains('#'));+ }}diff --git a/rust/cloud-storage/bots/src/inbound/axum_router/tests.rs b/rust/cloud-storage/bots/src/inbound/axum_router/tests.rsindex 52f567e699..bc7854a017 100644--- a/rust/cloud-storage/bots/src/inbound/axum_router/tests.rs+++ b/rust/cloud-storage/bots/src/inbound/axum_router/tests.rs@@ -1,5 +1,7 @@use super::*;-use crate::domain::models::AuthenticatedBot;+use crate::domain::models::{+ AuthenticatedBot, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse,+};use crate::{domain::service::BotServiceImpl, outbound::pg_bots_repo::PgBotsRepo};use axum::{Extension,@@ -63,6 +65,15 @@ impl BotService for TestBotService {unimplemented!()}+ async fn create_channel_scoped_bot(+ &self,+ _caller: MacroUserIdStr<'static>,+ _channel_id: Uuid,+ _req: CreateChannelScopedBotRequest,+ ) -> Result<CreateChannelScopedBotResponse, BotError> {+ unimplemented!()+ }+async fn list_bots(&self, _caller: MacroUserIdStr<'static>) -> Result<Vec<Bot>, BotError> {unimplemented!()}@@ -145,6 +156,14 @@ impl BotService for TestBotService {async fn authenticate_token(&self, _token: &str) -> Result<AuthenticatedBot, BotError> {unimplemented!()}++ async fn authenticate_channel_token(+ &self,+ _channel_id: Uuid,+ _token: &str,+ ) -> Result<AuthenticatedBot, BotError> {+ unimplemented!()+ }}#[derive(Clone, Copy)]diff --git a/rust/cloud-storage/bots/src/inbound/channel_webhook_router.rs b/rust/cloud-storage/bots/src/inbound/channel_webhook_router.rsnew file mode 100644index 0000000000..c6cb2b17db--- /dev/null+++ b/rust/cloud-storage/bots/src/inbound/channel_webhook_router.rs@@ -0,0 +1,364 @@+//! Axum router for channel-scoped bot creation and webhook delivery.++#[cfg(test)]+mod tests;++use crate::domain::{+ models::{+ ChannelWebhookRequest, ChannelWebhookResponse, CreateChannelScopedBotRequest,+ CreateChannelScopedBotResponse,+ },+ ports::{BotError, BotService},+};+use axum::{+ Json, Router,+ body::Bytes,+ extract::{FromRef, Path, State},+ http::{HeaderMap, StatusCode, header::CONTENT_TYPE},+ response::IntoResponse,+ routing::post,+};+use channels::domain::{+ models::{PostMessageRequest, PostMessageResponse, Sender},+ ports::{ChannelMutationErr, ChannelService},+};+use entity_access::{+ domain::{+ models::{AdminParticipantRole, EntityAccessReceipt},+ ports::EntityAccessService,+ },+ inbound::axum_extractors::ChannelAccessLevelExtractor,+};+use macro_user_id::user_id::MacroUserIdStr;+use model_error_response::ErrorResponse;+use std::{future::Future, sync::Arc};+use uuid::Uuid;++/// Header used to authenticate channel bot webhook requests.+pub const CHANNEL_BOT_TOKEN_HEADER: &str = "x-macro-channel-bot-token";++/// Narrow adapter for posting channel messages from bot webhooks.+pub trait ChannelMessagePoster: Clone + Send + Sync + 'static {+ /// Post a message to a channel.+ fn post_message(+ &self,+ actor: Sender,+ channel_id: Uuid,+ req: PostMessageRequest,+ ) -> impl Future<Output = Result<PostMessageResponse, ChannelMutationErr>> + Send;+}++impl<S> ChannelMessagePoster for Arc<S>+where+ S: ChannelService,+{+ fn post_message(+ &self,+ actor: Sender,+ channel_id: Uuid,+ req: PostMessageRequest,+ ) -> impl Future<Output = Result<PostMessageResponse, ChannelMutationErr>> + Send {+ ChannelService::post_message(self.as_ref(), actor, channel_id, req)+ }+}++/// State for the channel bot webhook router.+pub struct ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc> {+ bot_service: Arc<BotSvc>,+ channel_poster: Arc<ChannelPoster>,+ access_service: Arc<AccessSvc>,+}++impl<BotSvc, ChannelPoster, AccessSvc> Clone+ for ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc>+{+ fn clone(&self) -> Self {+ Self {+ bot_service: self.bot_service.clone(),+ channel_poster: self.channel_poster.clone(),+ access_service: self.access_service.clone(),+ }+ }+}++impl<BotSvc, ChannelPoster, AccessSvc>+ ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc>+where+ BotSvc: BotService,+ ChannelPoster: ChannelMessagePoster,+ AccessSvc: EntityAccessService,+{+ /// Create a router state.+ pub fn new(+ bot_service: BotSvc,+ channel_poster: ChannelPoster,+ access_service: AccessSvc,+ ) -> Self {+ Self {+ bot_service: Arc::new(bot_service),+ channel_poster: Arc::new(channel_poster),+ access_service: Arc::new(access_service),+ }+ }+}++impl<BotSvc, ChannelPoster, AccessSvc>+ FromRef<ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc>> for Arc<AccessSvc>+{+ fn from_ref(state: &ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc>) -> Self {+ state.access_service.clone()+ }+}++/// Channel id path.+#[derive(Debug, serde::Deserialize)]+pub struct ChannelPath {+ /// Channel id.+ pub channel_id: Uuid,+}++/// Create the authenticated channel-scoped bot creation router.+pub fn channel_scoped_bot_router<BotSvc, ChannelPoster, AccessSvc, T>(+ state: ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc>,+) -> Router<T>+where+ BotSvc: BotService,+ ChannelPoster: ChannelMessagePoster,+ AccessSvc: EntityAccessService,+ T: Send + Sync,+{+ Router::new()+ .route(+ "/channels/{channel_id}/bots/scoped",+ post(create_channel_scoped_bot_handler::<BotSvc, ChannelPoster, AccessSvc>),+ )+ .with_state(state)+}++/// Create the unauthenticated channel bot webhook router.+pub fn channel_bot_webhook_router<BotSvc, ChannelPoster, AccessSvc, T>(+ state: ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc>,+) -> Router<T>+where+ BotSvc: BotService,+ ChannelPoster: ChannelMessagePoster,+ AccessSvc: EntityAccessService,+ T: Send + Sync,+{+ Router::new()+ .route(+ "/channels/{channel_id}/webhook",+ post(post_channel_webhook_handler::<BotSvc, ChannelPoster, AccessSvc>),+ )+ .with_state(state)+}++fn caller_from_receipt(+ receipt: &EntityAccessReceipt<AdminParticipantRole>,+) -> Result<MacroUserIdStr<'static>, ChannelBotWebhookHandlerErr> {+ receipt+ .get_authenticated_user()+ .cloned()+ .map_err(|_| ChannelBotWebhookHandlerErr::BadRequest("authenticated user required"))+}++/// Handler for `POST /channels/{channel_id}/bots/scoped`.+#[utoipa::path(+ post,+ tag = "bots",+ operation_id = "create_channel_scoped_bot",+ path = "/channels/{channel_id}/bots/scoped",+ params(+ ("channel_id" = Uuid, Path, description = "Channel ID")+ ),+ request_body = CreateChannelScopedBotRequest,+ responses(+ (status = 201, body = CreateChannelScopedBotResponse),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(err, skip_all)]+pub async fn create_channel_scoped_bot_handler<BotSvc, ChannelPoster, AccessSvc>(+ State(state): State<ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc>>,+ access: ChannelAccessLevelExtractor<AdminParticipantRole, AccessSvc>,+ Path(path): Path<ChannelPath>,+ Json(req): Json<CreateChannelScopedBotRequest>,+) -> Result<(StatusCode, Json<CreateChannelScopedBotResponse>), ChannelBotWebhookHandlerErr>+where+ BotSvc: BotService,+ ChannelPoster: ChannelMessagePoster,+ AccessSvc: EntityAccessService,+{+ let caller = caller_from_receipt(&access.entity_access_receipt)?;+ let response = state+ .bot_service+ .create_channel_scoped_bot(caller, path.channel_id, req)+ .await?;+ Ok((StatusCode::CREATED, Json(response)))+}++/// Handler for `POST /channels/{channel_id}/webhook`.+#[utoipa::path(+ post,+ tag = "bots",+ operation_id = "post_channel_bot_webhook",+ path = "/channels/{channel_id}/webhook",+ params(+ ("channel_id" = Uuid, Path, description = "Channel ID"),+ ("x-macro-channel-bot-token" = String, Header, description = "Bot authentication token")+ ),+ request_body = ChannelWebhookRequest,+ responses(+ (status = 200, body = ChannelWebhookResponse),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(err, skip_all, fields(channel_id = tracing::field::Empty))]+pub async fn post_channel_webhook_handler<BotSvc, ChannelPoster, AccessSvc>(+ State(state): State<ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc>>,+ Path(path): Path<ChannelPath>,+ headers: HeaderMap,+ body: Bytes,+) -> Result<(StatusCode, Json<ChannelWebhookResponse>), ChannelBotWebhookHandlerErr>+where+ BotSvc: BotService,+ ChannelPoster: ChannelMessagePoster,+ AccessSvc: EntityAccessService,+{+ tracing::Span::current().record("channel_id", tracing::field::display(path.channel_id));++ let content = parse_webhook_content(&headers, body)?;+ let bot_auth_token = channel_bot_token(&headers)?;+ let authenticated = state+ .bot_service+ .authenticate_channel_token(path.channel_id, bot_auth_token)+ .await?;++ let response = state+ .channel_poster+ .post_message(+ Sender::Bot(authenticated.bot_id),+ path.channel_id,+ PostMessageRequest {+ content,+ mentions: Vec::new(),+ thread_id: None,+ attachments: Vec::new(),+ nonce: None,+ },+ )+ .await?;++ Ok((+ StatusCode::OK,+ Json(ChannelWebhookResponse {+ message_id: response.id,+ }),+ ))+}++fn channel_bot_token(headers: &HeaderMap) -> Result<&str, ChannelBotWebhookHandlerErr> {+ let token = headers+ .get(CHANNEL_BOT_TOKEN_HEADER)+ .and_then(|value| value.to_str().ok())+ .ok_or(ChannelBotWebhookHandlerErr::Bot(BotError::Unauthorized))?;++ if token.trim().is_empty() {+ return Err(ChannelBotWebhookHandlerErr::Bot(BotError::Unauthorized));+ }++ Ok(token)+}++fn parse_webhook_content(+ headers: &HeaderMap,+ body: Bytes,+) -> Result<String, ChannelBotWebhookHandlerErr> {+ if body.is_empty() {+ return Err(ChannelBotWebhookHandlerErr::BadRequest(+ "content is required",+ ));+ }++ if is_json_body(headers)+ && let Ok(request) = serde_json::from_slice::<ChannelWebhookRequest>(&body)+ {+ return require_non_empty_content(request.content);+ }++ let content = std::str::from_utf8(&body)+ .map_err(|_| ChannelBotWebhookHandlerErr::BadRequest("content must be valid UTF-8"))?+ .to_string();+ require_non_empty_content(content)+}++fn is_json_body(headers: &HeaderMap) -> bool {+ has_json_content_type(headers)+}++fn has_json_content_type(headers: &HeaderMap) -> bool {+ headers+ .get(CONTENT_TYPE)+ .and_then(|value| value.to_str().ok())+ .is_some_and(|value| value.to_ascii_lowercase().contains("json"))+}++fn require_non_empty_content(content: String) -> Result<String, ChannelBotWebhookHandlerErr> {+ if content.trim().is_empty() {+ return Err(ChannelBotWebhookHandlerErr::BadRequest(+ "content is required",+ ));+ }+ Ok(content)+}++/// Channel bot webhook handler error.+#[derive(Debug, thiserror::Error)]+pub enum ChannelBotWebhookHandlerErr {+ /// Bad request.+ #[error("{0}")]+ BadRequest(&'static str),+ /// Bot service error.+ #[error(transparent)]+ Bot(#[from] BotError),+ /// Channel mutation error.+ #[error(transparent)]+ Channel(#[from] ChannelMutationErr),+}++impl IntoResponse for ChannelBotWebhookHandlerErr {+ fn into_response(self) -> axum::response::Response {+ let status = match &self {+ Self::BadRequest(_) | Self::Bot(BotError::BadRequest(_)) => StatusCode::BAD_REQUEST,+ Self::Bot(BotError::Unauthorized)+ | Self::Channel(ChannelMutationErr::Unauthorized(_)) => StatusCode::UNAUTHORIZED,+ Self::Bot(BotError::NotFound(_)) | Self::Channel(ChannelMutationErr::NotFound(_)) => {+ StatusCode::NOT_FOUND+ }+ Self::Channel(ChannelMutationErr::BadRequest(_)) => StatusCode::BAD_REQUEST,+ Self::Bot(BotError::Repo(_))+ | Self::Channel(ChannelMutationErr::Repo(_))+ | Self::Channel(ChannelMutationErr::Gateway(_))+ | Self::Channel(ChannelMutationErr::Notification(_))+ | Self::Channel(ChannelMutationErr::Contacts(_)) => StatusCode::INTERNAL_SERVER_ERROR,+ };++ if status == StatusCode::INTERNAL_SERVER_ERROR {+ tracing::error!(error=?self, "channel bot webhook handler error");+ }++ (+ status,+ Json(ErrorResponse {+ message: self.to_string().into(),+ }),+ )+ .into_response()+ }+}diff --git a/rust/cloud-storage/bots/src/inbound/channel_webhook_router/tests.rs b/rust/cloud-storage/bots/src/inbound/channel_webhook_router/tests.rsnew file mode 100644index 0000000000..54286c23fb--- /dev/null+++ b/rust/cloud-storage/bots/src/inbound/channel_webhook_router/tests.rs@@ -0,0 +1,756 @@+use super::*;+use crate::domain::models::{+ AuthenticatedBot, Bot, BotId, BotKind, BotOwner, BotToken, CreateBotRequest,+ CreateBotTokenRequest, CreateBotTokenResponse, PatchBotRequest,+};+use axum::{+ Extension, Router,+ body::Body,+ http::{Request, StatusCode},+};+use channels::domain::models::PostMessageResponse;+use entity_access::domain::{+ models::{+ AccessError, AccessLevel, CallChannelInfo, EntityPermission, EntityType,+ ParticipantRole as EntityParticipantRole, RequiredPermission, UserTeamInfo,+ },+ ports::EntityAccessService,+};+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};+use model_user::UserContext;+use std::sync::{+ Arc, Mutex,+ atomic::{AtomicUsize, Ordering},+};+use tower::ServiceExt;++#[derive(Clone)]+enum TestCreateMode {+ Ok(CreateChannelScopedBotResponse),+ Unauthorized,+}++#[derive(Clone)]+enum TestAuthMode {+ Ok {+ expected_channel_id: Uuid,+ expected_token: String,+ bot_id: BotId,+ },+ Unauthorized,+}++#[derive(Debug, Clone)]+struct CreateCall {+ caller: MacroUserIdStr<'static>,+ channel_id: Uuid,+}++#[derive(Debug, Clone)]+struct AuthCall {+ channel_id: Uuid,+ token: String,+}++#[derive(Clone)]+struct TestBotService {+ create_mode: TestCreateMode,+ auth_mode: TestAuthMode,+ create_calls: Arc<AtomicUsize>,+ auth_calls: Arc<AtomicUsize>,+ last_create: Arc<Mutex<Option<CreateCall>>>,+ last_auth: Arc<Mutex<Option<AuthCall>>>,+}++impl TestBotService {+ fn for_create(response: CreateChannelScopedBotResponse) -> Self {+ Self {+ create_mode: TestCreateMode::Ok(response),+ auth_mode: TestAuthMode::Unauthorized,+ create_calls: Arc::new(AtomicUsize::new(0)),+ auth_calls: Arc::new(AtomicUsize::new(0)),+ last_create: Arc::new(Mutex::new(None)),+ last_auth: Arc::new(Mutex::new(None)),+ }+ }++ fn for_webhook(channel_id: Uuid, token: &str, bot_id: BotId) -> Self {+ Self {+ create_mode: TestCreateMode::Unauthorized,+ auth_mode: TestAuthMode::Ok {+ expected_channel_id: channel_id,+ expected_token: token.to_string(),+ bot_id,+ },+ create_calls: Arc::new(AtomicUsize::new(0)),+ auth_calls: Arc::new(AtomicUsize::new(0)),+ last_create: Arc::new(Mutex::new(None)),+ last_auth: Arc::new(Mutex::new(None)),+ }+ }++ fn unauthorized_webhook() -> Self {+ Self {+ create_mode: TestCreateMode::Unauthorized,+ auth_mode: TestAuthMode::Unauthorized,+ create_calls: Arc::new(AtomicUsize::new(0)),+ auth_calls: Arc::new(AtomicUsize::new(0)),+ last_create: Arc::new(Mutex::new(None)),+ last_auth: Arc::new(Mutex::new(None)),+ }+ }+}++impl BotService for TestBotService {+ async fn create_bot(+ &self,+ _caller: MacroUserIdStr<'static>,+ _req: CreateBotRequest,+ ) -> Result<Bot, BotError> {+ unimplemented!()+ }++ async fn create_channel_scoped_bot(+ &self,+ caller: MacroUserIdStr<'static>,+ channel_id: Uuid,+ _req: CreateChannelScopedBotRequest,+ ) -> Result<CreateChannelScopedBotResponse, BotError> {+ self.create_calls.fetch_add(1, Ordering::SeqCst);+ *self.last_create.lock().expect("create call mutex poisoned") =+ Some(CreateCall { caller, channel_id });++ match &self.create_mode {+ TestCreateMode::Ok(response) => Ok(response.clone()),+ TestCreateMode::Unauthorized => Err(BotError::Unauthorized),+ }+ }++ async fn list_bots(&self, _caller: MacroUserIdStr<'static>) -> Result<Vec<Bot>, BotError> {+ unimplemented!()+ }++ async fn get_bot(+ &self,+ _caller: MacroUserIdStr<'static>,+ _bot_id: BotId,+ ) -> Result<Bot, BotError> {+ unimplemented!()+ }++ async fn patch_bot(+ &self,+ _caller: MacroUserIdStr<'static>,+ _bot_id: BotId,+ _req: PatchBotRequest,+ ) -> Result<Bot, BotError> {+ unimplemented!()+ }++ async fn delete_bot(+ &self,+ _caller: MacroUserIdStr<'static>,+ _bot_id: BotId,+ ) -> Result<(), BotError> {+ unimplemented!()+ }++ async fn add_bot_to_channel(+ &self,+ _caller: MacroUserIdStr<'static>,+ _channel_id: Uuid,+ _bot_id: BotId,+ ) -> Result<(), BotError> {+ unimplemented!()+ }++ async fn remove_bot_from_channel(+ &self,+ _caller: MacroUserIdStr<'static>,+ _channel_id: Uuid,+ _bot_id: BotId,+ ) -> Result<(), BotError> {+ unimplemented!()+ }++ async fn list_channel_bots(&self, _channel_id: Uuid) -> Result<Vec<Bot>, BotError> {+ unimplemented!()+ }++ async fn create_token(+ &self,+ _caller: MacroUserIdStr<'static>,+ _bot_id: BotId,+ _req: CreateBotTokenRequest,+ ) -> Result<CreateBotTokenResponse, BotError> {+ unimplemented!()+ }++ async fn list_tokens(+ &self,+ _caller: MacroUserIdStr<'static>,+ _bot_id: BotId,+ ) -> Result<Vec<BotToken>, BotError> {+ unimplemented!()+ }++ async fn revoke_token(+ &self,+ _caller: MacroUserIdStr<'static>,+ _bot_id: BotId,+ _token_id: Uuid,+ ) -> Result<(), BotError> {+ unimplemented!()+ }++ async fn authenticate_token(&self, _token: &str) -> Result<AuthenticatedBot, BotError> {+ unimplemented!()+ }++ async fn authenticate_channel_token(+ &self,+ channel_id: Uuid,+ token: &str,+ ) -> Result<AuthenticatedBot, BotError> {+ self.auth_calls.fetch_add(1, Ordering::SeqCst);+ *self.last_auth.lock().expect("auth call mutex poisoned") = Some(AuthCall {+ channel_id,+ token: token.to_string(),+ });++ match &self.auth_mode {+ TestAuthMode::Ok {+ expected_channel_id,+ expected_token,+ bot_id,+ } if channel_id == *expected_channel_id && token == expected_token => {+ Ok(AuthenticatedBot {+ bot_id: *bot_id,+ kind: BotKind::Owned,+ })+ }+ _ => Err(BotError::Unauthorized),+ }+ }+}++#[derive(Clone, Copy)]+struct TestAccessService {+ role: EntityParticipantRole,+}++impl TestAccessService {+ const fn new(role: EntityParticipantRole) -> Self {+ Self { role }+ }+}++impl EntityAccessService for TestAccessService {+ async fn generate_entity_access_receipt<T: RequiredPermission>(+ &self,+ _user_id: &MacroUserId<Lowercase<'_>>,+ _user_org_id: Option<i64>,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<EntityAccessReceipt<T>, AccessError> {+ unimplemented!()+ }++ async fn get_access_level(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<Option<AccessLevel>, AccessError> {+ unimplemented!()+ }++ async fn check_access(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ _required_level: AccessLevel,+ ) -> Result<AccessLevel, AccessError> {+ unimplemented!()+ }++ async fn check_public_access(+ &self,+ _entity_id: &str,+ _entity_type: EntityType,+ _required_level: AccessLevel,+ ) -> Result<AccessLevel, AccessError> {+ unimplemented!()+ }++ async fn get_entity_permission(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ _user_org_id: Option<i64>,+ ) -> Result<EntityPermission, AccessError> {+ Ok(EntityPermission::ChannelRole { role: self.role })+ }++ async fn get_crm_entity_permission_with_team(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<(EntityPermission, uuid::Uuid), AccessError> {+ unimplemented!("channel webhook router tests do not support CRM entity access")+ }++ async fn get_users_by_entity(+ &self,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {+ unimplemented!()+ }++ async fn get_call_channel(+ &self,+ _call_id: &Uuid,+ ) -> Result<Option<CallChannelInfo>, AccessError> {+ unimplemented!()+ }++ async fn get_call_channel_by_channel_id(+ &self,+ _channel_id: &Uuid,+ ) -> Result<Option<CallChannelInfo>, AccessError> {+ unimplemented!()+ }++ async fn get_user_team(+ &self,+ _user_id: &MacroUserId<Lowercase<'_>>,+ ) -> Result<Option<UserTeamInfo>, AccessError> {+ unimplemented!()+ }+}++#[derive(Debug, Clone)]+struct PostedMessage {+ actor: Sender,+ channel_id: Uuid,+ req: PostMessageRequest,+}++#[derive(Clone, Copy)]+enum TestPostMode {+ Ok,+}++#[derive(Clone)]+struct TestChannelPoster {+ mode: TestPostMode,+ calls: Arc<Mutex<Vec<PostedMessage>>>,+}++impl TestChannelPoster {+ fn new() -> Self {+ Self {+ mode: TestPostMode::Ok,+ calls: Arc::new(Mutex::new(Vec::new())),+ }+ }+}++impl ChannelMessagePoster for TestChannelPoster {+ fn post_message(+ &self,+ actor: Sender,+ channel_id: Uuid,+ req: PostMessageRequest,+ ) -> impl Future<Output = Result<PostMessageResponse, ChannelMutationErr>> + Send {+ let calls = self.calls.clone();+ let mode = self.mode;+ async move {+ calls+ .lock()+ .expect("posted message mutex poisoned")+ .push(PostedMessage {+ actor,+ channel_id,+ req,+ });++ match mode {+ TestPostMode::Ok => Ok(PostMessageResponse {+ id: Uuid::new_v4().to_string(),+ nonce: None,+ }),+ }+ }+ }+}++fn user_extension() -> Extension<UserContext> {+ Extension(UserContext {+ user_id: "macro|[email protected]".to_string(),+ fusion_user_id: "fusion-user".to_string(),+ permissions: None,+ organization_id: None,+ })+}++fn router(+ service: TestBotService,+ poster: TestChannelPoster,+ role: EntityParticipantRole,+) -> Router {+ channel_scoped_bot_router(ChannelBotWebhookRouterState::new(+ service,+ poster,+ TestAccessService::new(role),+ ))+ .layer(user_extension())+}++fn webhook_router(service: TestBotService, poster: TestChannelPoster) -> Router {+ channel_bot_webhook_router(ChannelBotWebhookRouterState::new(+ service,+ poster,+ TestAccessService::new(EntityParticipantRole::Member),+ ))+}++fn scoped_bot_response(bot_id: BotId) -> CreateChannelScopedBotResponse {+ let now = chrono::Utc::now();+ CreateChannelScopedBotResponse {+ bot: Bot {+ id: bot_id,+ kind: BotKind::Owned,+ owner: Some(BotOwner::User {+ user_id: "macro|[email protected]".to_string(),+ }),+ name: "Datadog Alerts".to_string(),+ handle: "datadog-alerts".to_string(),+ description: Some("Posts alarm notifications".to_string()),+ avatar_url: None,+ created_by: Some("macro|[email protected]".to_string()),+ created_at: now,+ updated_at: now,+ deleted_at: None,+ },+ token: BotToken {+ id: Uuid::new_v4(),+ bot_id,+ token_prefix: "mbot_test".to_string(),+ label: Some("webhook".to_string()),+ last_used_at: None,+ expires_at: None,+ revoked_at: None,+ created_at: now,+ },+ bot_token: "mbot_test_1234".to_string(),+ }+}++fn scoped_bot_request_body() -> Body {+ Body::from(+ serde_json::json!({+ "team_id": null,+ "name": "Datadog Alerts",+ "handle": "datadog-alerts",+ "description": "Posts alarm notifications",+ "avatar_url": null,+ "token_label": "webhook",+ "token_expires_at": null,+ })+ .to_string(),+ )+}++#[tokio::test]+async fn channel_webhook_router_member_cannot_create_scoped_bot() {+ let bot_id = BotId::from_uuid(Uuid::new_v4());+ let service = TestBotService::for_create(scoped_bot_response(bot_id));+ let poster = TestChannelPoster::new();+ let channel_id = Uuid::new_v4();+ let request = Request::builder()+ .method("POST")+ .uri(format!("/channels/{channel_id}/bots/scoped"))+ .header("content-type", "application/json")+ .body(scoped_bot_request_body())+ .unwrap();++ let response = router(service.clone(), poster, EntityParticipantRole::Member)+ .oneshot(request)+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);+ assert_eq!(service.create_calls.load(Ordering::SeqCst), 0);+}++#[tokio::test]+async fn channel_webhook_router_admin_can_create_scoped_bot() {+ let bot_id = BotId::from_uuid(Uuid::new_v4());+ let service = TestBotService::for_create(scoped_bot_response(bot_id));+ let poster = TestChannelPoster::new();+ let channel_id = Uuid::new_v4();+ let request = Request::builder()+ .method("POST")+ .uri(format!("/channels/{channel_id}/bots/scoped"))+ .header("content-type", "application/json")+ .body(scoped_bot_request_body())+ .unwrap();++ let response = router(service.clone(), poster, EntityParticipantRole::Admin)+ .oneshot(request)+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::CREATED);+ assert_eq!(service.create_calls.load(Ordering::SeqCst), 1);++ let call = service+ .last_create+ .lock()+ .expect("create call mutex poisoned")+ .clone()+ .expect("create call recorded");+ assert_eq!(call.caller.as_ref(), "macro|[email protected]");+ assert_eq!(call.channel_id, channel_id);+}++#[tokio::test]+async fn channel_webhook_router_valid_json_posts_as_bot() {+ let channel_id = Uuid::new_v4();+ let bot_id = BotId::from_uuid(Uuid::new_v4());+ let token = "mbot_test_valid";+ let service = TestBotService::for_webhook(channel_id, token, bot_id);+ let poster = TestChannelPoster::new();+ let request = Request::builder()+ .method("POST")+ .uri(format!("/channels/{channel_id}/webhook"))+ .header("content-type", "application/json")+ .header(CHANNEL_BOT_TOKEN_HEADER, token)+ .body(Body::from(+ serde_json::json!({ "content": "hello" }).to_string(),+ ))+ .unwrap();++ let response = webhook_router(service.clone(), poster.clone())+ .oneshot(request)+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(service.auth_calls.load(Ordering::SeqCst), 1);++ let auth_call = service+ .last_auth+ .lock()+ .expect("auth call mutex poisoned")+ .clone()+ .expect("auth call recorded");+ assert_eq!(auth_call.channel_id, channel_id);+ assert_eq!(auth_call.token, token);++ let calls = poster.calls.lock().expect("posted message mutex poisoned");+ assert_eq!(calls.len(), 1);+ let call = &calls[0];+ assert_eq!(call.actor, Sender::Bot(bot_id));+ assert_eq!(call.channel_id, channel_id);+ assert_eq!(call.req.content, "hello");+ assert!(call.req.mentions.is_empty());+ assert!(call.req.attachments.is_empty());+ assert!(call.req.thread_id.is_none());+ assert!(call.req.nonce.is_none());+}++#[tokio::test]+async fn channel_webhook_router_raw_body_starting_with_brace_posts_as_bot() {+ let channel_id = Uuid::new_v4();+ let bot_id = BotId::from_uuid(Uuid::new_v4());+ let token = "mbot_test_valid";+ let content = "{raw alert payload";+ let service = TestBotService::for_webhook(channel_id, token, bot_id);+ let poster = TestChannelPoster::new();+ let request = Request::builder()+ .method("POST")+ .uri(format!("/channels/{channel_id}/webhook"))+ .header("content-type", "text/plain")+ .header(CHANNEL_BOT_TOKEN_HEADER, token)+ .body(Body::from(content))+ .unwrap();++ let response = webhook_router(service.clone(), poster.clone())+ .oneshot(request)+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(service.auth_calls.load(Ordering::SeqCst), 1);++ let calls = poster.calls.lock().expect("posted message mutex poisoned");+ assert_eq!(calls.len(), 1);+ let call = &calls[0];+ assert_eq!(call.actor, Sender::Bot(bot_id));+ assert_eq!(call.channel_id, channel_id);+ assert_eq!(call.req.content, content);+}++#[tokio::test]+async fn channel_webhook_router_invalid_token_returns_unauthorized_without_posting() {+ let channel_id = Uuid::new_v4();+ let bot_id = BotId::from_uuid(Uuid::new_v4());+ let service = TestBotService::for_webhook(channel_id, "mbot_test_valid", bot_id);+ let poster = TestChannelPoster::new();+ let request = Request::builder()+ .method("POST")+ .uri(format!("/channels/{channel_id}/webhook"))+ .header("content-type", "application/json")+ .header(CHANNEL_BOT_TOKEN_HEADER, "mbot_test_invalid")+ .body(Body::from(+ serde_json::json!({ "content": "hello" }).to_string(),+ ))+ .unwrap();++ let response = webhook_router(service.clone(), poster.clone())+ .oneshot(request)+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);+ assert_eq!(service.auth_calls.load(Ordering::SeqCst), 1);+ assert!(+ poster+ .calls+ .lock()+ .expect("posted message mutex poisoned")+ .is_empty()+ );+}++#[tokio::test]+async fn channel_webhook_router_missing_token_header_returns_unauthorized_without_posting() {+ let channel_id = Uuid::new_v4();+ let service = TestBotService::unauthorized_webhook();+ let poster = TestChannelPoster::new();+ let request = Request::builder()+ .method("POST")+ .uri(format!("/channels/{channel_id}/webhook"))+ .header("content-type", "application/json")+ .body(Body::from(+ serde_json::json!({ "content": "hello" }).to_string(),+ ))+ .unwrap();++ let response = webhook_router(service.clone(), poster.clone())+ .oneshot(request)+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);+ assert_eq!(service.auth_calls.load(Ordering::SeqCst), 0);+ assert!(+ poster+ .calls+ .lock()+ .expect("posted message mutex poisoned")+ .is_empty()+ );+}++#[tokio::test]+async fn channel_webhook_router_wrong_channel_returns_unauthorized_without_posting() {+ let expected_channel_id = Uuid::new_v4();+ let requested_channel_id = Uuid::new_v4();+ let bot_id = BotId::from_uuid(Uuid::new_v4());+ let token = "mbot_test_valid";+ let service = TestBotService::for_webhook(expected_channel_id, token, bot_id);+ let poster = TestChannelPoster::new();+ let request = Request::builder()+ .method("POST")+ .uri(format!("/channels/{requested_channel_id}/webhook"))+ .header("content-type", "application/json")+ .header(CHANNEL_BOT_TOKEN_HEADER, token)+ .body(Body::from(+ serde_json::json!({ "content": "hello" }).to_string(),+ ))+ .unwrap();++ let response = webhook_router(service.clone(), poster.clone())+ .oneshot(request)+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);+ assert_eq!(service.auth_calls.load(Ordering::SeqCst), 1);+ assert!(+ poster+ .calls+ .lock()+ .expect("posted message mutex poisoned")+ .is_empty()+ );+}++#[tokio::test]+async fn channel_webhook_router_revoked_token_auth_failure_returns_unauthorized() {+ let channel_id = Uuid::new_v4();+ let service = TestBotService::unauthorized_webhook();+ let poster = TestChannelPoster::new();+ let request = Request::builder()+ .method("POST")+ .uri(format!("/channels/{channel_id}/webhook"))+ .header("content-type", "application/json")+ .header(CHANNEL_BOT_TOKEN_HEADER, "mbot_test_revoked")+ .body(Body::from(+ serde_json::json!({ "content": "hello" }).to_string(),+ ))+ .unwrap();++ let response = webhook_router(service.clone(), poster.clone())+ .oneshot(request)+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);+ assert_eq!(service.auth_calls.load(Ordering::SeqCst), 1);+ assert!(+ poster+ .calls+ .lock()+ .expect("posted message mutex poisoned")+ .is_empty()+ );+}++#[tokio::test]+async fn channel_webhook_router_empty_content_returns_bad_request_without_authenticating() {+ let channel_id = Uuid::new_v4();+ let service = TestBotService::unauthorized_webhook();+ let poster = TestChannelPoster::new();+ let request = Request::builder()+ .method("POST")+ .uri(format!("/channels/{channel_id}/webhook"))+ .header("content-type", "application/json")+ .header(CHANNEL_BOT_TOKEN_HEADER, "mbot_test_valid")+ .body(Body::from(+ serde_json::json!({ "content": " \n\t" }).to_string(),+ ))+ .unwrap();++ let response = webhook_router(service.clone(), poster.clone())+ .oneshot(request)+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::BAD_REQUEST);+ assert_eq!(service.auth_calls.load(Ordering::SeqCst), 0);+ assert!(+ poster+ .calls+ .lock()+ .expect("posted message mutex poisoned")+ .is_empty()+ );+}diff --git a/rust/cloud-storage/bots/src/inbound/mod.rs b/rust/cloud-storage/bots/src/inbound/mod.rsindex 3d33942ed2..a114ce8b63 100644--- a/rust/cloud-storage/bots/src/inbound/mod.rs+++ b/rust/cloud-storage/bots/src/inbound/mod.rs@@ -2,3 +2,5 @@/// Axum router for bot management.pub mod axum_router;+/// Axum router for channel-scoped bot webhooks.+pub mod channel_webhook_router;diff --git a/rust/cloud-storage/bots/src/outbound/pg_bots_repo.rs b/rust/cloud-storage/bots/src/outbound/pg_bots_repo.rsindex 8e077067c3..3443f45491 100644--- a/rust/cloud-storage/bots/src/outbound/pg_bots_repo.rs+++ b/rust/cloud-storage/bots/src/outbound/pg_bots_repo.rs@@ -6,7 +6,7 @@ mod tests;use crate::domain::{models::{AuthenticatedBot, Bot, BotId, BotKind, BotOwner, BotToken, BotTokenCandidate,- CreateBotRequest, CreateBotTokenRequest, PatchBotRequest,+ CreateBotRequest, CreateBotTokenRequest, CreateChannelScopedBotRequest, PatchBotRequest,},ports::BotRepo,};@@ -33,6 +33,13 @@ fn principal_id(bot_id: BotId) -> String {bot_id.to_storage_string()}+fn owner_columns(owner: BotOwner) -> (Option<String>, Option<Uuid>) {+ match owner {+ BotOwner::User { user_id } => (Some(user_id), None),+ BotOwner::Team { team_id } => (None, Some(team_id)),+ }+}+#[derive(Debug)]struct BotRow {id: Uuid,@@ -164,10 +171,7 @@ impl BotRepo for PgBotsRepo {req: CreateBotRequest,) -> Result<Bot, Self::Err> {let bot_id = BotId::from_uuid(macro_uuid::generate_uuid_v7());- let (owner_user_id, team_id) = match owner {- BotOwner::User { user_id } => (Some(user_id), None),- BotOwner::Team { team_id } => (None, Some(team_id)),- };+ let (owner_user_id, team_id) = owner_columns(owner);let row = sqlx::query_as!(BotRow,r#"@@ -205,6 +209,99 @@ impl BotRepo for PgBotsRepo {map_bot_row(row)}+ async fn create_channel_scoped_bot(+ &self,+ owner: BotOwner,+ created_by: MacroUserIdStr<'static>,+ channel_id: Uuid,+ token_hash: Vec<u8>,+ token_prefix: String,+ req: CreateChannelScopedBotRequest,+ ) -> Result<(Bot, BotToken), Self::Err> {+ let bot_id = BotId::from_uuid(macro_uuid::generate_uuid_v7());+ let token_id = macro_uuid::generate_uuid_v7();+ let (owner_user_id, team_id) = owner_columns(owner);+ let mut tx = self+ .pool+ .begin()+ .await+ .context("failed to begin channel-scoped bot transaction")?;++ let bot_row = sqlx::query_as!(+ BotRow,+ r#"+ INSERT INTO bots (+ id, kind, owner_user_id, team_id, name, handle, description, avatar_url, created_by+ )+ VALUES ($1, 'owned', $2, $3, $4, $5, $6, $7, $8)+ RETURNING+ id,+ kind,+ owner_user_id,+ team_id,+ name,+ handle,+ description,+ avatar_url,+ created_by,+ created_at,+ updated_at,+ deleted_at+ "#,+ bot_id.as_uuid(),+ owner_user_id,+ team_id,+ req.name,+ req.handle,+ req.description,+ req.avatar_url,+ created_by.as_ref(),+ )+ .fetch_one(&mut *tx)+ .await+ .context("failed to create channel-scoped bot")?;++ sqlx::query!(+ r#"+ INSERT INTO comms_channel_participants (channel_id, user_id, role, left_at)+ VALUES ($1, $2, 'member'::comms_participant_role, NULL)+ "#,+ channel_id,+ principal_id(bot_id),+ )+ .execute(&mut *tx)+ .await+ .context("failed to add channel-scoped bot to channel")?;++ let token_row = sqlx::query_as!(+ BotTokenRow,+ r#"+ INSERT INTO bot_tokens (+ id, bot_id, token_hash, token_prefix, label, expires_at+ )+ VALUES ($1, $2, $3, $4, $5, $6)+ RETURNING id, bot_id, token_prefix, label, last_used_at, expires_at, revoked_at, created_at+ "#,+ token_id,+ bot_id.as_uuid(),+ token_hash,+ token_prefix,+ req.token_label,+ req.token_expires_at,+ )+ .fetch_one(&mut *tx)+ .await+ .context("failed to create channel-scoped bot token")?;++ let bot = map_bot_row(bot_row)?;+ let token = map_token_row(token_row);+ tx.commit()+ .await+ .context("failed to commit channel-scoped bot transaction")?;++ Ok((bot, token))+ }+async fn list_manageable_bots(&self,caller: MacroUserIdStr<'static>,@@ -545,6 +642,46 @@ impl BotRepo for PgBotsRepo {.collect()}+ async fn channel_token_candidates(+ &self,+ channel_id: Uuid,+ token_prefix: &str,+ ) -> Result<Vec<BotTokenCandidate>, Self::Err> {+ let rows = sqlx::query_as!(+ TokenCandidateRow,+ r#"+ SELECT+ bt.id AS token_id,+ bt.bot_id,+ bt.token_hash,+ bt.token_prefix,+ bt.label,+ bt.last_used_at,+ bt.expires_at,+ bt.revoked_at,+ bt.created_at,+ b.kind+ FROM bot_tokens bt+ JOIN bots b ON b.id = bt.bot_id+ JOIN comms_channel_participants cp+ ON cp.channel_id = $1+ AND cp.user_id = ('bot|' || b.id::text)+ AND cp.left_at IS NULL+ WHERE bt.token_prefix = $2+ AND b.deleted_at IS NULL+ "#,+ channel_id,+ token_prefix,+ )+ .fetch_all(&self.pool)+ .await+ .context("failed to lookup channel bot token candidates")?;++ rows.into_iter()+ .map(TokenCandidateRow::into_candidate)+ .collect()+ }+async fn mark_token_used(&self, token_id: Uuid) -> Result<(), Self::Err> {sqlx::query!(r#"diff --git a/rust/cloud-storage/bots/src/outbound/pg_bots_repo/tests.rs b/rust/cloud-storage/bots/src/outbound/pg_bots_repo/tests.rsindex fd0bb79a61..3d730e9f82 100644--- a/rust/cloud-storage/bots/src/outbound/pg_bots_repo/tests.rs+++ b/rust/cloud-storage/bots/src/outbound/pg_bots_repo/tests.rs@@ -1,8 +1,9 @@use super::*;use crate::domain::{- models::{CreateBotRequest, CreateBotTokenRequest},+ models::{CreateBotRequest, CreateBotTokenRequest, CreateChannelScopedBotRequest},ports::{BotError, BotService},service::BotServiceImpl,+ tokens,};use macro_db_migrator::MACRO_DB_MIGRATIONS;use sqlx::PgPool;@@ -26,6 +27,18 @@ fn create_req(handle: &str) -> CreateBotRequest {}}+fn create_channel_scoped_req(handle: &str) -> CreateChannelScopedBotRequest {+ CreateChannelScopedBotRequest {+ team_id: None,+ name: "Datadog Alerts".to_string(),+ handle: handle.to_string(),+ description: Some("Posts alarm notifications".to_string()),+ avatar_url: None,+ token_label: Some("Webhook".to_string()),+ token_expires_at: None,+ }+}+fn service(pool: &PgPool) -> BotServiceImpl<PgBotsRepo> {BotServiceImpl::new(PgBotsRepo::new(pool.clone()))}@@ -111,6 +124,46 @@ async fn insert_channel(pool: &PgPool, channel_id: Uuid) -> anyhow::Result<()> {Ok(())}+async fn active_channel_participant_count(+ pool: &PgPool,+ channel_id: Uuid,+ bot_id: BotId,+) -> anyhow::Result<i64> {+ let count = sqlx::query_scalar(+ r#"+ SELECT COUNT(*) AS "count!"+ FROM comms_channel_participants+ WHERE channel_id = $1+ AND user_id = $2+ AND left_at IS NULL+ "#,+ )+ .bind(channel_id)+ .bind(principal_id(bot_id))+ .fetch_one(pool)+ .await?;++ Ok(count)+}++async fn token_last_used_at(+ pool: &PgPool,+ token_id: Uuid,+) -> anyhow::Result<Option<chrono::DateTime<chrono::Utc>>> {+ let last_used_at = sqlx::query_scalar(+ r#"+ SELECT last_used_at+ FROM bot_tokens+ WHERE id = $1+ "#,+ )+ .bind(token_id)+ .fetch_one(pool)+ .await?;++ Ok(last_used_at)+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn create_user_owned_bot_records_user_owner(pool: PgPool) -> anyhow::Result<()> {let service = service(&pool);@@ -222,6 +275,135 @@ async fn add_remove_channel_bot_requires_bot_usability_and_soft_removes(Ok(())}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn create_channel_scoped_bot_creates_bot_participant_and_token(+ pool: PgPool,+) -> anyhow::Result<()> {+ let service = service(&pool);+ let channel_id = Uuid::new_v4();+ insert_channel(&pool, channel_id).await?;++ let created = service+ .create_channel_scoped_bot(+ user_id(USER_OWNER),+ channel_id,+ create_channel_scoped_req("scoped-alerts"),+ )+ .await?;++ assert_eq!(created.bot.kind, BotKind::Owned);+ assert_eq!(created.bot.handle, "scoped-alerts");+ assert_eq!(created.bot.created_by.as_deref(), Some(USER_OWNER));+ assert_eq!(created.token.bot_id, created.bot.id);+ assert_eq!(created.token.label.as_deref(), Some("Webhook"));+ assert_eq!(+ tokens::token_prefix(&created.bot_token),+ Some(created.token.token_prefix.as_str())+ );+ assert_eq!(+ active_channel_participant_count(&pool, channel_id, created.bot.id).await?,+ 1+ );++ let authenticated = service+ .authenticate_channel_token(channel_id, &created.bot_token)+ .await?;+ assert_eq!(authenticated.bot_id, created.bot.id);+ assert_eq!(authenticated.kind, BotKind::Owned);+ assert!(token_last_used_at(&pool, created.token.id).await?.is_some());++ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn authenticate_channel_token_rejects_wrong_channel_without_marking_used(+ pool: PgPool,+) -> anyhow::Result<()> {+ let service = service(&pool);+ let channel_id = Uuid::new_v4();+ let other_channel_id = Uuid::new_v4();+ insert_channel(&pool, channel_id).await?;+ insert_channel(&pool, other_channel_id).await?;++ let created = service+ .create_channel_scoped_bot(+ user_id(USER_OWNER),+ channel_id,+ create_channel_scoped_req("wrong-channel"),+ )+ .await?;++ let err = service+ .authenticate_channel_token(other_channel_id, &created.bot_token)+ .await+ .expect_err("channel-scoped token must not authenticate for another channel");++ assert!(matches!(err, BotError::Unauthorized));+ assert!(token_last_used_at(&pool, created.token.id).await?.is_none());++ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn authenticate_channel_token_rejects_revoked_token(pool: PgPool) -> anyhow::Result<()> {+ let service = service(&pool);+ let channel_id = Uuid::new_v4();+ insert_channel(&pool, channel_id).await?;++ let created = service+ .create_channel_scoped_bot(+ user_id(USER_OWNER),+ channel_id,+ create_channel_scoped_req("revoked-scoped"),+ )+ .await?;++ service+ .revoke_token(user_id(USER_OWNER), created.bot.id, created.token.id)+ .await?;++ let err = service+ .authenticate_channel_token(channel_id, &created.bot_token)+ .await+ .expect_err("revoked channel-scoped token must not authenticate");++ assert!(matches!(err, BotError::Unauthorized));+ assert!(token_last_used_at(&pool, created.token.id).await?.is_none());++ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn authenticate_channel_token_rejects_removed_channel_membership(+ pool: PgPool,+) -> anyhow::Result<()> {+ let service = service(&pool);+ let channel_id = Uuid::new_v4();+ insert_channel(&pool, channel_id).await?;++ let created = service+ .create_channel_scoped_bot(+ user_id(USER_OWNER),+ channel_id,+ create_channel_scoped_req("removed-scoped"),+ )+ .await?;++ service+ .remove_bot_from_channel(user_id(USER_OWNER), channel_id, created.bot.id)+ .await?;++ let err = service+ .authenticate_channel_token(channel_id, &created.bot_token)+ .await+ .expect_err("removed bot participant must not authenticate");++ assert!(matches!(err, BotError::Unauthorized));+ assert!(token_last_used_at(&pool, created.token.id).await?.is_none());++ Ok(())+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn revoke_token_prevents_future_authentication(pool: PgPool) -> anyhow::Result<()> {let service = service(&pool);diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex 05d184cf27..e6a024b6d7 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -4,7 +4,8 @@ use contacts::outbound::ingress::SqsContactsQueue;use crate::{config::Config, service::s3::S3};use axum::extract::FromRef;use bots::{- domain::service::BotServiceImpl, inbound::axum_router::BotsRouterState,+ domain::service::BotServiceImpl,+ inbound::{axum_router::BotsRouterState, channel_webhook_router::ChannelBotWebhookRouterState},outbound::pg_bots_repo::PgBotsRepo,};use cal::{@@ -238,6 +239,10 @@ pub(crate) type DssBotService = BotServiceImpl<PgBotsRepo>;/// Type alias for the bots router state.pub(crate) type DssBotsState = BotsRouterState<DssBotService, EntityAccessService>;+/// Type alias for the channel bot webhook router state.+pub(crate) type DssChannelBotWebhookState =+ ChannelBotWebhookRouterState<DssBotService, Arc<DssChannelService>, EntityAccessService>;+/// Type alias for the call connection service.pub(crate) type CallConnectionService =ConnectionServiceImpl<EntityAccessService, ConnectionGatewayImpl>;@@ -324,6 +329,7 @@ pub(crate) struct ApiContext {pub documents_state: DocumentsState,pub channels_state: DssChannelsState,pub bots_state: DssBotsState,+ pub channel_bot_webhook_state: DssChannelBotWebhookState,pub call_state: DssCallState,pub call_webhook_state: DssCallWebhookState,pub call_internal_state: DssCallInternalState,diff --git a/rust/cloud-storage/document_storage_service/src/api/mod.rs b/rust/cloud-storage/document_storage_service/src/api/mod.rsindex c1c193fe0c..d8b3fbcff8 100644--- a/rust/cloud-storage/document_storage_service/src/api/mod.rs+++ b/rust/cloud-storage/document_storage_service/src/api/mod.rs@@ -212,6 +212,11 @@ fn api_router(state: ApiContext) -> Router {.merge(bots::inbound::axum_router::bots_router(state.bots_state.clone(),))+ .merge(+ bots::inbound::channel_webhook_router::channel_scoped_bot_router(+ state.channel_bot_webhook_state.clone(),+ ),+ ).nest("/foreign_entity",foreign_entity::inbound::axum_router::foreign_entity_router(@@ -236,6 +241,12 @@ fn api_router(state: ApiContext) -> Router {macro_middleware::auth::attach_user::handler,)),)+ // Merge after the user-auth layer so webhook calls authenticate only with the bot token.+ .merge(+ bots::inbound::channel_webhook_router::channel_bot_webhook_router(+ state.channel_bot_webhook_state.clone(),+ ),+ ).nest("/internal",internal::router(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 e058670233..5a1df390d1 100644--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs@@ -228,6 +228,10 @@ use utoipa::OpenApi;channels::inbound::axum_router::get_activity_handler,channels::inbound::axum_router::post_activity_handler,+ // bots+ bots::inbound::channel_webhook_router::create_channel_scoped_bot_handler,+ bots::inbound::channel_webhook_router::post_channel_webhook_handler,+// callscall::inbound::axum_router::get_or_create_call_handler,call::inbound::axum_router::check_active_call_handler,@@ -441,6 +445,16 @@ use utoipa::OpenApi;ApiActivity,PostActivityRequest,+ // Bots+ bots::domain::models::Bot,+ bots::domain::models::BotKind,+ bots::domain::models::BotOwner,+ bots::domain::models::BotToken,+ bots::domain::models::ChannelWebhookRequest,+ bots::domain::models::ChannelWebhookResponse,+ bots::domain::models::CreateChannelScopedBotRequest,+ bots::domain::models::CreateChannelScopedBotResponse,+// Callscall::domain::models::CallTokenResponse,call::domain::models::CallActiveResponse,diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex 9edacceeda..a7e031575c 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -632,6 +632,13 @@ async fn main() -> anyhow::Result<()> {);bot_trigger_router.spawn(bot_trigger_receiver);+ let channel_bot_webhook_state =+ bots::inbound::channel_webhook_router::ChannelBotWebhookRouterState::new(+ bots_service.clone(),+ channels_service.clone(),+ (*entity_access_service).clone(),+ );+let api_context = ApiContext {contacts_ingress: contacts_ingress.clone(),soup_router_state: SoupRouterState::new(@@ -688,6 +695,7 @@ async fn main() -> anyhow::Result<()> {bots_service.clone(),(*entity_access_service).clone(),),+ channel_bot_webhook_state,call_state,call_webhook_state,call_internal_state,