Skip to content

Commit

Permalink
test: mock DNS in webhooks tests (#1056)
Browse files Browse the repository at this point in the history
  • Loading branch information
mantariksh committed Feb 4, 2021
1 parent 1d750d3 commit 046a5a2
Showing 1 changed file with 27 additions and 19 deletions.
46 changes: 27 additions & 19 deletions tests/unit/backend/modules/webhook/webhook.utils.spec.ts
Original file line number Diff line number Diff line change
@@ -1,49 +1,57 @@
import { promises as dns } from 'dns'
import { mocked } from 'ts-jest/utils'

import { WebhookValidationError } from 'src/app/modules/webhook/webhook.errors'
import { validateWebhookUrl } from 'src/app/modules/webhook/webhook.utils'

jest.mock('dns', () => ({
promises: {
resolve: jest.fn(),
},
}))
const MockDns = mocked(dns, true)

const MOCK_WEBHOOK_URL = 'https://mock.webhook.url'

describe('Webhook URL validation', () => {
it('should accept valid HTTPS URLs', async () => {
await expect(
validateWebhookUrl('https://staging.form.gov.sg'),
).resolves.toEqual(undefined)
MockDns.resolve.mockResolvedValueOnce(['1.1.1.1'])
await expect(validateWebhookUrl(MOCK_WEBHOOK_URL)).resolves.toEqual(
undefined,
)
})

it('should reject non-HTTPS URLs', async () => {
await expect(
validateWebhookUrl('http://some.website'),
).rejects.toStrictEqual(
new WebhookValidationError(
'http://some.website is not a valid HTTPS URL.',
),
const httpUrl = 'http://website.com'
await expect(validateWebhookUrl(httpUrl)).rejects.toStrictEqual(
new WebhookValidationError(`${httpUrl} is not a valid HTTPS URL.`),
)
})

it('should reject URLs which do not resolve to any IP', async () => {
await expect(
validateWebhookUrl('https://some.nonsense.website'),
).rejects.toStrictEqual(
MockDns.resolve.mockRejectedValueOnce([])
await expect(validateWebhookUrl(MOCK_WEBHOOK_URL)).rejects.toStrictEqual(
new WebhookValidationError(
'Error encountered during DNS resolution for https://some.nonsense.website. Check that the URL is correct.',
`Error encountered during DNS resolution for ${MOCK_WEBHOOK_URL}. Check that the URL is correct.`,
),
)
})

it('should reject URLs which resolve to private IPs', async () => {
await expect(
validateWebhookUrl('https://localtest.me'),
).rejects.toStrictEqual(
MockDns.resolve.mockResolvedValueOnce(['127.0.0.1'])
await expect(validateWebhookUrl(MOCK_WEBHOOK_URL)).rejects.toStrictEqual(
new WebhookValidationError(
'https://localtest.me resolves to the following private IPs: 127.0.0.1',
`${MOCK_WEBHOOK_URL} resolves to the following private IPs: 127.0.0.1`,
),
)
})

it('should reject URLs in the same domain as the app URL', async () => {
await expect(
validateWebhookUrl('https://example.com/test'),
validateWebhookUrl(`${process.env.APP_URL}/test`),
).rejects.toStrictEqual(
new WebhookValidationError(
'You cannot send responses back to https://example.com.',
`You cannot send responses back to ${process.env.APP_URL}.`,
),
)
})
Expand Down

0 comments on commit 046a5a2

Please sign in to comment.