Skip to content

Commit

Permalink
✨ Introduced webhook signature
Browse files Browse the repository at this point in the history
  • Loading branch information
naelob committed May 19, 2024
1 parent 2b4ce34 commit ca4f1bb
Show file tree
Hide file tree
Showing 11 changed files with 104 additions and 35 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,6 @@ const AddAuthCredentialsForm = (prop : propType) => {
console.log(prop.data)

fetchCredentials({
projectId:idProject,
type: prop.data?.type,
attributes: prop.data?.auth_type===AuthStrategy.oauth2 ? ["client_id","client_secret","scope"]
: prop.data?.auth_type===AuthStrategy.api_key ? ["api_key"] : ["username","secret"]
Expand Down Expand Up @@ -227,7 +226,6 @@ const AddAuthCredentialsForm = (prop : propType) => {
else
{
createCS({
projectId:idProject,
type: providerToType(provider_name.split("-")[0],provider_name.split("-")[1],AuthStrategy.oauth2),
attributes:["client_id","client_secret","scope"],
values:[client_id,client_secret,scope]
Expand Down Expand Up @@ -269,7 +267,6 @@ const AddAuthCredentialsForm = (prop : propType) => {
else
{
createCS({
projectId:idProject,
type: providerToType(provider_name.split("-")[0],provider_name.split("-")[1],AuthStrategy.api_key),
attributes:["api_key"],
values:[api_key]
Expand Down Expand Up @@ -319,7 +316,6 @@ const AddAuthCredentialsForm = (prop : propType) => {
else
{
createCS({
projectId:idProject,
type: providerToType(provider_name.split("-")[0],provider_name.split("-")[1],AuthStrategy.basic),
attributes:["username","secret"],
values:[username,secret]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,6 @@ export function ConnectorDisplay({ item }: ItemDisplayProps) {
});
} else {
createCS({
projectId: idProject,
type: providerToType(item?.name, item?.vertical!, AuthStrategy.oauth2),
attributes: ["client_id", "client_secret", "scope"],
values: [client_id, client_secret, scope]
Expand Down Expand Up @@ -142,7 +141,6 @@ export function ConnectorDisplay({ item }: ItemDisplayProps) {
});
} else {
createCS({
projectId: idProject,
type: providerToType(item?.name, item?.vertical!, AuthStrategy.api_key),
attributes: ["api_key"],
values: [api_key]
Expand Down Expand Up @@ -181,7 +179,6 @@ export function ConnectorDisplay({ item }: ItemDisplayProps) {
});
} else {
createCS({
projectId: idProject,
type: providerToType(item?.name, item?.vertical!, AuthStrategy.basic),
attributes: ["username", "secret"],
values: [username, secret]
Expand All @@ -200,7 +197,6 @@ export function ConnectorDisplay({ item }: ItemDisplayProps) {
useEffect(() => {
if (mappingConnectionStrategies && mappingConnectionStrategies.length > 0) {
fetchCredentials({
projectId: idProject,
type: mappingConnectionStrategies[0].type,
attributes: item?.authStrategy === AuthStrategy.oauth2 ? ["client_id", "client_secret", "scope"]
: item?.authStrategy === AuthStrategy.api_key ? ["api_key"] : ["username", "secret"]
Expand Down
4 changes: 1 addition & 3 deletions apps/client-ts/src/hooks/mutations/useConnectionStrategy.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,13 @@ import { toast } from "sonner"
import Cookies from 'js-cookie';

interface IConnectionStrategyDto {
projectId: string,
type: string,
attributes: string[],
values: string[],
}

interface IFetchConnectionStrategyDto {
id_cs:string,
projectId: string,
id_cs: string,
type: string,
attributes: string[],
values: string[],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,16 @@ interface IFetchedData {
}

interface IGetCSCredentialsData {
projectId : string,
type?:string,
attributes:string[]
}


const useConnectionStrategyAuthCredentialsMutation = () => {
// const queryClient = useQueryClient();

const getCSCredentials = async (GetCSCredentialsData : IGetCSCredentialsData): Promise<string[]> => {
const useConnectionStrategyAuthCredentialsMutation = () => {
const getCSCredentials = async (data : IGetCSCredentialsData): Promise<string[]> => {
const response = await fetch(`${config.API_URL}/connections-strategies/credentials`,{
method: 'POST',
body: JSON.stringify(GetCSCredentialsData),
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${Cookies.get('access_token')}`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,13 @@ export class ConnectionsStrategiesController {
@UseGuards(JwtAuthGuard)
@Post('create')
async createConnectionStrategy(
@Request() req: any,
@Body() connectionStrategyCreateDto: CreateConnectionStrategyDto,
) {
const { projectId, type, attributes, values } = connectionStrategyCreateDto;
const { id_project } = req.user;
const { type, attributes, values } = connectionStrategyCreateDto;
return await this.connectionsStrategiesService.createConnectionStrategy(
projectId,
id_project,
type,
attributes,
values,
Expand Down Expand Up @@ -101,12 +103,14 @@ export class ConnectionsStrategiesController {
@UseGuards(JwtAuthGuard)
@Post('credentials')
async getConnectionStrategyCredential(
@Request() req: any,
@Body() data: ConnectionStrategyCredentials,
) {
// validate user against project_id
const { attributes, projectId, type } = data;
const { id_project } = req.user;
const { attributes, type } = data;
return await this.connectionsStrategiesService.getConnectionStrategyData(
projectId,
id_project,
type,
attributes,
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import { ApiProperty } from '@nestjs/swagger';

export class CreateConnectionStrategyDto {
@ApiProperty()
projectId: string;
@ApiProperty()
type: string;
@ApiProperty()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import { ApiProperty } from '@nestjs/swagger';

export class ConnectionStrategyCredentials {
@ApiProperty()
projectId: string;
@ApiProperty()
type: string;
@ApiProperty()
Expand Down
6 changes: 6 additions & 0 deletions packages/api/src/@core/webhook/dto/webhook.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,9 @@ export class WebhookDto {
id_project: string;
scope: string[];
}

export class SignatureVerificationDto {
payload: { [key: string]: any };
signature: string;
secret: string;
}
19 changes: 18 additions & 1 deletion packages/api/src/@core/webhook/webhook.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
import { LoggerService } from '@@core/logger/logger.service';
import { ApiBody, ApiResponse, ApiTags, ApiOperation } from '@nestjs/swagger';
import { WebhookService } from './webhook.service';
import { WebhookDto } from './dto/webhook.dto';
import { SignatureVerificationDto, WebhookDto } from './dto/webhook.dto';
import { JwtAuthGuard } from '@@core/auth/guards/jwt-auth.guard';

@ApiTags('webhook')
Expand Down Expand Up @@ -60,4 +60,21 @@ export class WebhookController {
async addWebhook(@Body() data: WebhookDto) {
return this.webhookService.createWebhookEndpoint(data);
}

@ApiOperation({
operationId: 'verifyEvent',
summary: 'Verify payload sgnature of the webhook',
})
@ApiBody({ type: SignatureVerificationDto })
@ApiResponse({ status: 201 })
@UseGuards(JwtAuthGuard)
@Post('verifyEvent')
async verifyPayloadSignature(@Body() data: SignatureVerificationDto) {
const { payload, signature, secret } = data;
return this.webhookService.verifyPayloadSignature(
payload,
signature,
secret,
);
}
}
29 changes: 28 additions & 1 deletion packages/api/src/@core/webhook/webhook.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { LoggerService } from '@@core/logger/logger.service';
import { handleServiceError } from '@@core/utils/errors';
import { WebhookDto } from './dto/webhook.dto';
import axios from 'axios';
import crypto from 'crypto';

@Injectable()
export class WebhookService {
Expand All @@ -18,6 +19,13 @@ export class WebhookService {
this.logger.setContext(WebhookService.name);
}

generateSignature(payload: any, secret: string): string {
return crypto
.createHmac('sha256', secret)
.update(JSON.stringify(payload))
.digest('hex');
}

async getWebhookEndpoints(project_id: string) {
try {
return await this.prisma.webhook_endpoints.findMany({
Expand Down Expand Up @@ -187,7 +195,10 @@ export class WebhookService {
},
{
headers: {
'Panora-Signature': deliveryAttempt.webhook_endpoints.secret,
'Panora-Signature': this.generateSignature(
deliveryAttempt.webhooks_payloads.data,
deliveryAttempt.webhook_endpoints.secret,
),
},
},
);
Expand Down Expand Up @@ -248,4 +259,20 @@ export class WebhookService {
handleServiceError(error, this.logger);
}
}

async verifyPayloadSignature(
payload: { [key: string]: any },
signature: string,
secret: string,
) {
try {
const expected = this.generateSignature(payload, secret);
if (expected !== signature) {
throw new Error('Invalid signature');
}
return 200;
} catch (error) {
throw new Error(error);
}
}
}
48 changes: 40 additions & 8 deletions packages/api/swagger/swagger-spec.json
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,31 @@
]
}
},
"/webhook/verifyEvent": {
"post": {
"operationId": "verifyEvent",
"summary": "Verify payload sgnature of the webhook",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/SignatureVerificationDto"
}
}
}
},
"responses": {
"201": {
"description": ""
}
},
"tags": [
"webhook"
]
}
},
"/linked-users": {
"post": {
"operationId": "addLinkedUser",
Expand Down Expand Up @@ -4615,6 +4640,21 @@
"scope"
]
},
"SignatureVerificationDto": {
"type": "object",
"properties": {
"signature": {
"type": "string"
},
"secret": {
"type": "string"
}
},
"required": [
"signature",
"secret"
]
},
"CreateLinkedUserDto": {
"type": "object",
"properties": {
Expand Down Expand Up @@ -4786,9 +4826,6 @@
"CreateConnectionStrategyDto": {
"type": "object",
"properties": {
"projectId": {
"type": "string"
},
"type": {
"type": "string"
},
Expand All @@ -4806,7 +4843,6 @@
}
},
"required": [
"projectId",
"type",
"attributes",
"values"
Expand Down Expand Up @@ -4866,9 +4902,6 @@
"ConnectionStrategyCredentials": {
"type": "object",
"properties": {
"projectId": {
"type": "string"
},
"type": {
"type": "string"
},
Expand All @@ -4880,7 +4913,6 @@
}
},
"required": [
"projectId",
"type",
"attributes"
]
Expand Down

0 comments on commit ca4f1bb

Please sign in to comment.