Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Antavo] Escher request signing implementation #2708

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ exports[`Testing snapshot for actions-antavo destination: event action - all fie
Object {
"account": "YOUfi0^J9NW]3LPm",
"action": "YOUfi0^J9NW]3LPm",
"api_key": "YOUfi0^J9NW]3LPm",
"customer": "YOUfi0^J9NW]3LPm",
"data": Object {
"testType": "YOUfi0^J9NW]3LPm",
Expand All @@ -15,7 +14,6 @@ Object {
exports[`Testing snapshot for actions-antavo destination: event action - required fields 1`] = `
Object {
"action": "YOUfi0^J9NW]3LPm",
"api_key": "YOUfi0^J9NW]3LPm",
"customer": "YOUfi0^J9NW]3LPm",
}
`;
Expand All @@ -24,7 +22,6 @@ exports[`Testing snapshot for actions-antavo destination: profile action - all f
Object {
"account": "0$ZK&EN",
"action": "profile",
"api_key": "0$ZK&EN",
"customer": "0$ZK&EN",
"data": Object {
"birth_date": "0$ZK&EN",
Expand All @@ -42,7 +39,6 @@ Object {
exports[`Testing snapshot for actions-antavo destination: profile action - required fields 1`] = `
Object {
"action": "profile",
"api_key": "0$ZK&EN",
"customer": "0$ZK&EN",
"data": Object {},
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,241 @@
import url from 'url'
import path from 'path'
import crypto from 'crypto'

export type acceptedMethods =
'delete'
| 'get'
| 'post'
| 'put'
| 'patch'
| 'head'
| 'GET'
| 'POST'
| 'PUT'
| 'DELETE'
| 'PATCH'
| 'HEAD'

export class Escher {
private config: {
algorithmPrefix: string,
vendorKey: string
hashAlgorithm: string
credentialScope: string
authHeaderName: string
dateHeaderName: string
clockSkew: number
accessKeyId: string
apiSecret: string
}

public constructor(
environment: string,
apiKey: string,
apiSecret: string
) {
const credentialScope: string = environment + '/api/antavo_request'
this.config = {
algorithmPrefix: 'ANTAVO',
vendorKey: 'Antavo',
hashAlgorithm: 'SHA256',
credentialScope: credentialScope,
authHeaderName: 'authorization',
dateHeaderName: 'date',
clockSkew: 300,
accessKeyId: apiKey,
apiSecret: apiSecret
}
}

public signRequest(
requestOptions: {
headers: Record<string, string>,
method: acceptedMethods,
host: string,
url: string
},
body: any
): {
headers: Record<string, string>,
method: acceptedMethods,
host: string,
url: string,
json: string[],
} {
const currentDate = new Date()
const formattedDate = this.toLongDate(currentDate)
const headersMap: Record<string, string> = {}
const bodyJson = JSON.stringify(body)

requestOptions['headers']['host'] = requestOptions.host
requestOptions['headers']['date'] = formattedDate

headersMap[this.config.dateHeaderName] = formattedDate
headersMap[this.config.authHeaderName] = this.generateAuthHeader(requestOptions, bodyJson, currentDate)

return {
headers: headersMap,
method: requestOptions.method,
host: requestOptions.host,
url: requestOptions.url,
json: body
}
}

private generateAuthHeader(
requestOptions: {
headers: Record<string, string>,
method: acceptedMethods,
host: string,
url: string
},
body: string,
currentDate: Date
): string {
const algorithm = [
this.config.algorithmPrefix,
'HMAC',
this.config.hashAlgorithm
].join('-')

const fullCredentials = [
this.config.accessKeyId,
this.toShortDate(currentDate),
this.config.credentialScope
].join('/')

const signedHeaders = this.formatSignedHeaders(Object.keys(requestOptions.headers))

const signKey = this.calculateSigningKey(currentDate)
const stringToSign = this.getStringToSign(requestOptions, body, currentDate)

const signature = crypto
.createHmac(this.config.hashAlgorithm, signKey)
.update(stringToSign, 'utf8')
.digest('hex')

return (
algorithm +
' Credential=' +
fullCredentials +
', SignedHeaders=' +
signedHeaders +
', Signature=' +
signature
)
}

private canonicalizeQuery(query: string): string {
if (query === '') {
return ''
}

const encodeComponent = (component: string): string =>
encodeURIComponent(component)
.replace(/'/g, '%27')
.replace(/\(/g, '%28')
.replace(/\)/g, '%29')

const join = (key: string, value: string): string => encodeComponent(key) + '=' + encodeComponent(value)
let queryMap: Record<string, string> = {}

query.split('&').forEach(value => {
let query = value.split('=')
queryMap[query[0]] = query[1]
})

return Object.keys(queryMap)
.map(key => {
return join(key, queryMap[key])
})
.sort()
.join('&')
}


private canonicalizeRequest(
requestOptions: {
url: string;
method: acceptedMethods;
headers: Record<string, string>
},
body: string
): string {
const preparedUrl = requestOptions.url
.replace('#', '%23')
.replace('\\', '%5C')
.replace('+', '%20')
.replace('%2B', '%20')
const parsedUrl = url.parse(preparedUrl)
const headers = Object.keys(requestOptions.headers).sort()
const method = !(typeof requestOptions.method === 'undefined') ? requestOptions.method.toUpperCase() : ''
const canonicalizedHeaders = headers.map(key => key + ':' + requestOptions.headers[key])
const lines = [
method,
path.posix.normalize(parsedUrl.pathname ?? ''),
this.canonicalizeQuery(parsedUrl.query ?? ''),
canonicalizedHeaders.join('\n'),
'',
headers.join(';'),
this.hash(this.config.hashAlgorithm, body)
]
return lines.join('\n')
}

private getStringToSign(
requestOptions: {
url: string;
method: acceptedMethods;
headers: Record<string, string>
},
body: string,
currentDate: Date
): string {
return [
`${this.config.algorithmPrefix}-HMAC-${this.config.hashAlgorithm}`,
this.toLongDate(currentDate),
`${this.toShortDate(currentDate)}/${this.config.credentialScope}`,
this.hash(
this.config.hashAlgorithm,
this.canonicalizeRequest(requestOptions, body)
)
].join('\n')
}

private calculateSigningKey(currentDate: Date): string {
let signingKey: any = this.config.algorithmPrefix + this.config.apiSecret
const authKeyParts = [this.toShortDate(currentDate), ...this.config.credentialScope.split(/\//g)]
authKeyParts.forEach(data => {
signingKey = crypto.createHmac(this.config.hashAlgorithm, signingKey).update(data, 'utf8').digest()
})

return signingKey
}

private toLongDate(date: Date): string {
return date
.toISOString()
.replace(/-/g, '')
.replace(/:/g, '')
.replace(/\..*Z/, 'Z')
}

private toShortDate(date: Date): string {
return this.toLongDate(date).substring(0, 8)
}

private hash(hashAlgorithm: string, string: string): string {
return crypto
.createHash(hashAlgorithm)
.update(string, 'utf8')
.digest('hex')
}

private formatSignedHeaders(signedHeaders: string[]): string {
return signedHeaders
.map(signedHeader => signedHeader.toLowerCase())
.sort()
.join(';')
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ exports[`Testing snapshot for Antavo's event destination action: all fields 1`]
Object {
"account": "IB60PM0Tc",
"action": "IB60PM0Tc",
"api_key": "IB60PM0Tc",
"customer": "IB60PM0Tc",
"data": Object {
"testType": "IB60PM0Tc",
Expand All @@ -15,7 +14,6 @@ Object {
exports[`Testing snapshot for Antavo's event destination action: required fields 1`] = `
Object {
"action": "IB60PM0Tc",
"api_key": "IB60PM0Tc",
"customer": "IB60PM0Tc",
}
`;
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import destination from '../../index'
const testDestination = createTestIntegration(destination)
const settings = {
stack: 'test-stack',
api_key: 'testApiKey'
api_key: 'testApiKey',
api_secret: 'testApiSecret'
}

describe('Antavo (Actions)', () => {
Expand Down Expand Up @@ -53,8 +54,7 @@ describe('Antavo (Actions)', () => {
account: 'testAccount',
data: {
points: 1234
},
api_key: 'testApiKey'
}
})
})
it('Handle request without default mappings', async () => {
Expand Down Expand Up @@ -94,8 +94,7 @@ describe('Antavo (Actions)', () => {
account: 'testAccount',
data: {
points: 1234
},
api_key: 'testApiKey'
}
})
})
it('Handle request without optional fields', async () => {
Expand Down Expand Up @@ -125,8 +124,7 @@ describe('Antavo (Actions)', () => {
expect(responses[0].status).toBe(202)
expect(responses[0].options.json).toMatchObject({
customer: 'testUser',
action: 'testAction',
api_key: 'testApiKey'
action: 'testAction'
})
})
it('Throw error for missing required field: customer', async () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { ActionDefinition } from '@segment/actions-core'
import type { Settings } from '../generated-types'
import type { Payload } from './generated-types'
import { acceptedMethods, Escher } from '../escher/escher'

const action: ActionDefinition<Settings, Payload> = {
title: 'Loyalty events',
Expand Down Expand Up @@ -36,16 +37,24 @@ const action: ActionDefinition<Settings, Payload> = {
}
},
perform: (request, data) => {
const escher = new Escher(
data.settings.stack,
data.settings.api_key,
data.settings.api_secret
)
const url = `https://api.${data.settings.stack}.antavo.com/v1/webhook/segment`
const payload = {
...data.payload,
api_key: data.settings.api_key
...data.payload
}
const options = {
headers: {},
host: `api.${data.settings.stack}.antavo.com`,
method: 'POST' as acceptedMethods,
url: url
}
const signedOptions = escher.signRequest(options, payload)

return request(url, {
method: 'post',
json: payload
})
return request(url, signedOptions)
}
}

Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ const destination: DestinationDefinition<Settings> = {
description: 'The Antavo brand API key supplied to your brand in Antavo Loyalty Engine',
type: 'password',
required: true
},
api_secret: {
label: 'API Secret',
description: 'Antavo brand API secret',
type: 'password',
required: true
}
}
},
Expand Down
Loading