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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions integrations/docusign/integration.definition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ export default new IntegrationDefinition({
OAUTH_CLIENT_SECRET: {
description: "A secret that's used to establish and refresh the OAuth authentication",
},
WEBHOOK_SIGNING_SECRET: {
description: "The signing key used to validate Docusign's webhook request payloads",
},
},
states: {
configuration: {
Expand Down
8 changes: 7 additions & 1 deletion integrations/docusign/src/handler.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { exchangeAuthCodeForRefreshToken } from './docusign-api/auth-utils'
import { dispatchIntegrationEvent } from './webhooks/event-dispatcher'
import { parseWebhookEvent } from './webhooks/utils'
import { parseWebhookEvent, verifyWebhookSignature } from './webhooks/utils'
import * as bp from '.botpress'

const _isOauthRequest = ({ req }: bp.HandlerProps) => req.path === '/oauth'
Expand All @@ -14,6 +14,12 @@ export const handler = async (props: bp.HandlerProps) => {
return
}

const signatureResult = verifyWebhookSignature(props)
if (!signatureResult.success) {
props.logger.forBot().error(signatureResult.error.message, signatureResult.error)
return
}

const result = parseWebhookEvent(props)
if (!result.success) {
props.logger.forBot().error(result.error.message, result.error)
Expand Down
55 changes: 55 additions & 0 deletions integrations/docusign/src/webhooks/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import crypto from 'crypto'
import { Result } from '../types'
import { safeParseJson } from '../utils'
import { AllEnvelopeEvents, allEnvelopeEventsSchema } from './schemas'
Expand Down Expand Up @@ -29,3 +30,57 @@ export const parseWebhookEvent = (props: bp.HandlerProps): Result<AllEnvelopeEve
data: zodResult.data,
}
}

export const verifyWebhookSignature = (props: bp.HandlerProps): Result<null> => {
const { body, headers } = props.req
if (!body) {
return { success: false, error: new Error('Received empty webhook payload') }
}

const headerResult = _parseSignatureHeader(headers)
if (!headerResult.success) {
return headerResult
}
const signatureHash = headerResult.data
const signingKey = bp.secrets.WEBHOOK_SIGNING_SECRET!

try {
const computedHash = _computeHash(signingKey, body)
const isValid = _isHashValid(signatureHash, computedHash)
if (!isValid) {
return { success: false, error: new Error('Webhook failed signature verification') }
}

return { success: true, data: null }
} catch (thrown: unknown) {
const error = thrown instanceof Error ? thrown : new Error(String(thrown))
return { success: false, error }
}
}

const WEBHOOK_SIGNATURE_HEADER = 'x-docusign-signature-1' as const
const _parseSignatureHeader = (headers: Record<string, string | undefined> | undefined): Result<string> => {
const signatureHeader = headers?.[WEBHOOK_SIGNATURE_HEADER]

if (!signatureHeader || signatureHeader.length === 0) {
return { success: false, error: new Error('Docusign webhook signature header is missing from the request') }
}

return {
success: true,
data: signatureHeader,
}
}

const _computeHash = (secret: string, payload: string): string => {
const hmac = crypto.createHmac('sha256', secret)
hmac.write(payload)
hmac.end()
return hmac.read().toString('base64')
}

const _isHashValid = (signature: string, payloadHash: string) => {
const signatureBuffer = Buffer.from(signature, 'base64')
const payloadBuffer = Buffer.from(payloadHash, 'base64')
return crypto.timingSafeEqual(signatureBuffer, payloadBuffer)
}
2 changes: 1 addition & 1 deletion integrations/instagram/integration.definition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const { file: _file, ...channelMessages } = messages.defaults

export default new IntegrationDefinition({
name: INTEGRATION_NAME,
version: '3.1.1',
version: '3.1.2',
title: 'Instagram',
description: 'Automate interactions, manage comments, and send/receive messages all in real-time.',
icon: 'icon.svg',
Expand Down
2 changes: 1 addition & 1 deletion integrations/instagram/src/webhook/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const _handler: bp.IntegrationProps['handler'] = async (props: bp.HandlerProps)

const validationResult = _validateRequestAuthentication(req, props)
if (validationResult.error) {
return { status: 403, body: validationResult.message }
return { status: 401, body: validationResult.message }
}
return await messagingHandler(props)
}
Expand Down
14 changes: 14 additions & 0 deletions integrations/slack/src/misc/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,17 @@ export const getMessageFromSlackEvent = async (

return messages[0]
}

export const safeParseJson = (json: string) => {
try {
return {
success: true,
data: JSON.parse(json),
}
} catch (thrown: unknown) {
return {
success: false,
error: thrown instanceof Error ? thrown : new Error(String(thrown)),
}
}
}
9 changes: 8 additions & 1 deletion integrations/slack/src/webhook-events/handler-dispatcher.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as sdk from '@botpress/sdk'
import type { SlackEvent } from '@slack/types'
import { safeParseJson } from 'src/misc/utils'
import * as handlers from './handlers'
import { handleInteractiveRequest, isInteractiveRequest } from './handlers/interactive-request'
import { isOAuthCallback, handleOAuthCallback } from './handlers/oauth-callback'
Expand All @@ -16,7 +17,13 @@ export const handler: bp.IntegrationProps['handler'] = async ({ req, ctx, client

_verifyBodyIsPresent(req)

const data = JSON.parse(req.body)
const decoded = decodeURIComponent(req.body)
const parseRes = safeParseJson(decoded.startsWith('payload=') ? decoded.slice('payload='.length) : decoded)
if (!parseRes.success) {
const { error } = parseRes
logger.forBot().error('could not parse the JSON', error)
}
const { data } = parseRes

if (isUrlVerificationRequest(data)) {
logger.forBot().debug('Handler received request of type url_verification')
Expand Down
Loading