Skip to content

Commit

Permalink
Merge pull request #1609 from oasisprotocol/lw/dev-e2e
Browse files Browse the repository at this point in the history
Add security headers to dev server
  • Loading branch information
lukaw3d authored Aug 25, 2023
2 parents 4e7f83e + c907220 commit 519f2ca
Show file tree
Hide file tree
Showing 12 changed files with 91 additions and 38 deletions.
17 changes: 17 additions & 0 deletions .proxyrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// @ts-check

/**
* Add security headers to dev server
* @param {import('connect').Server} app
*/
module.exports = (app) => {
app.use((req, res, next) => {
// Re-generate headers on every request so editing the file is reflected on reload.
delete require.cache[require.resolve('./internals/getSecurityHeaders.js')];
const { getCsp, getPermissionsPolicy } = require('./internals/getSecurityHeaders.js')

res.setHeader('Content-Security-Policy', getCsp({ isDev: true, isExtension: false }))
res.setHeader('Permissions-Policy', getPermissionsPolicy())
next()
})
}
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ yarn test
yarn start
(cd playwright; yarn; npx playwright install --with-deps)
(cd playwright; yarn test)
# Or set BASE_URL and EXTENSION_PATH to test production builds and test security headers.
# Or set BASE_URL and EXTENSION_PATH to test production builds.
# Or `xvfb-run yarn test` to prevent browser windows opening.

# Run cypress tests
Expand Down
15 changes: 13 additions & 2 deletions internals/getSecurityHeaders.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,17 @@ const dappFrameAncestors = `
http://localhost:*
http://127.0.0.1:*
`
const localnet = `
http://localhost:42280
http://localhost:9001
`
const hmrWebsocket = `
ws://localhost:2222
`
const reactErrorOverlay = `'sha256-RV6I4HWPb71LvA27WVD3cEz8GsJrHlfcM/2X2Q5gV00='`
const hmrScripts = `
'unsafe-eval'
`

/**
* Keep this synced with deployment headers
Expand All @@ -24,6 +32,8 @@ const getCsp = ({ isExtension, isDev }) =>
default-src 'none';
script-src
'self'
${isDev ? reactErrorOverlay : ''}
${isDev ? hmrScripts : ''}
'report-sample';
style-src
'self'
Expand All @@ -37,6 +47,7 @@ const getCsp = ({ isExtension, isDev }) =>
https://testnet.grpc.oasis.dev
https://api.oasisscan.com
https://monitor.oasis.dev
${isDev ? localnet : ''}
${isDev ? hmrWebsocket : ''}
;
frame-ancestors
Expand Down Expand Up @@ -65,7 +76,7 @@ const getPermissionsPolicy = () =>
camera=*,
cross-origin-isolated=(),
display-capture=(),
document-domain=(),
document-domain=(self),
encrypted-media=*,
execution-while-not-rendered=(),
execution-while-out-of-viewport=(),
Expand Down Expand Up @@ -93,4 +104,4 @@ const getPermissionsPolicy = () =>
.join(' ')
.replace(/ ,/g, ',')

module.exports = { getCsp, getPermissionsPolicy }
module.exports = { getCsp, getPermissionsPolicy, reactErrorOverlay }
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@
"@testing-library/react": "13.4.0",
"@testing-library/user-event": "14.4.3",
"@types/body-scroll-lock": "3.1.0",
"@types/connect": "3.4.35",
"@types/jest": "29.5.4",
"@types/jest-when": "3.5.2",
"@types/lodash": "4.14.197",
Expand Down
8 changes: 5 additions & 3 deletions playwright/playwright.config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import type { PlaywrightTestConfig } from '@playwright/test'
import { devices } from '@playwright/test'

const doubleIfDev = (time: number) => (process.env.BASE_URL ? time : time * 2)

/**
* Read environment variables from file.
* https://github.com/motdotla/dotenv
Expand All @@ -13,13 +15,13 @@ import { devices } from '@playwright/test'
const config: PlaywrightTestConfig = {
testDir: './tests',
/* Maximum time one test can run for. */
timeout: 30 * 1000,
timeout: doubleIfDev(30 * 1000),
expect: {
/**
* Maximum time expect() should wait for the condition to be met.
* For example in `await expect(locator).toHaveText();`
*/
timeout: 8000,
timeout: doubleIfDev(8000),
},
/* Run tests in files in parallel */
fullyParallel: true,
Expand All @@ -34,7 +36,7 @@ const config: PlaywrightTestConfig = {
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
/* Maximum time each action such as `click()` can take. Defaults to 0 (no limit). */
actionTimeout: 3000,
actionTimeout: doubleIfDev(3000),
/* Base URL to use in actions like `await page.goto('/')`. */
/* Test dev server by default, but also allow testing `start:prod`. */
baseURL: process.env.BASE_URL ?? 'http://localhost:3000',
Expand Down
12 changes: 12 additions & 0 deletions playwright/tests/csp-react-error-overlay.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { test, expect } from '@playwright/test'
import { reactErrorOverlay } from '../../internals/getSecurityHeaders.js'

test('Dev Content-Security-Policy should allow react-error-overlay', async ({ page, baseURL }) => {
if (baseURL !== 'http://localhost:3000') test.skip()
expect((await page.request.head('/')).headers()).toHaveProperty('content-security-policy')
expect((await page.request.head('/')).headers()['content-security-policy']).toContain(reactErrorOverlay)
await page.goto('/e2e')
await page.getByRole('button', { name: 'Trigger uncaught error' }).click()
await expect(page.locator('iframe')).toBeVisible()
await expect(page.frameLocator('iframe').getByText('ReferenceError')).toBeVisible()
})
8 changes: 7 additions & 1 deletion playwright/tests/extension.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,13 @@ test.describe('The extension popup should load', () => {
})

test('should allow embedded Transak widget', async ({ page, extensionId }) => {
await expectNoErrorsInConsole(page)
await expectNoErrorsInConsole(page, {
ignoreError: msg => {
// Odd errors inside Transak
if (msg.text().includes('responded with a status of 403')) return true
if (msg.text().includes('`sessionKey` is a required property')) return true
},
})
await page.goto(`chrome-extension://${extensionId}/${popupFile}#/open-wallet/private-key`)
await fillPrivateKeyWithoutPassword(page, {
privateKey: privateKey,
Expand Down
42 changes: 17 additions & 25 deletions playwright/tests/fiat.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,15 @@ async function setup(page: Page) {
}

test.describe('Fiat on-ramp', () => {
test('Content-Security-Policy should allow embedded Transak widget', async ({ page, baseURL }) => {
expect(baseURL).toBe('http://localhost:5000')
test('Content-Security-Policy should allow embedded Transak widget', async ({ page }) => {
expect((await page.request.head('/')).headers()).toHaveProperty('content-security-policy')
await expectNoErrorsInConsole(page)
await expectNoErrorsInConsole(page, {
ignoreError: msg => {
// Odd errors inside Transak
if (msg.text().includes('responded with a status of 403')) return true
if (msg.text().includes('`sessionKey` is a required property')) return true
},
})
await setup(page)
await page
.getByText(
Expand All @@ -37,18 +42,12 @@ test.describe('Fiat on-ramp', () => {
await expect(page.frameLocator('iframe')!.getByText('Please Enter Your Email')).toBeVisible()
})

test('Content-Security-Policy should also allow Transak staging iframe', async ({ page, baseURL }) => {
expect(baseURL).toBe('http://localhost:5000')
test('Content-Security-Policy should also allow Transak staging iframe', async ({ page }) => {
expect((await page.request.head('/')).headers()).toHaveProperty('content-security-policy')
await expectNoErrorsInConsole(page)
await setup(page)
await page.route('https://global.transak.com/*', route =>
route.fulfill({
status: 301,
headers: {
Location: 'https://global-stg.transak.com/',
},
}),
await page.route('https://*.transak.com/?*', route =>
route.fulfill({ status: 301, headers: { Location: 'https://global-stg.transak.com/' } }),
)

await page
Expand All @@ -58,19 +57,13 @@ test.describe('Fiat on-ramp', () => {
.click()
})

test('Content-Security-Policy should block unknown iframe and fail', async ({ page, baseURL }) => {
test('Content-Security-Policy should block unknown iframe and fail', async ({ page }) => {
test.fail()
expect(baseURL).toBe('http://localhost:5000')
expect((await page.request.head('/')).headers()).toHaveProperty('content-security-policy')
// await expectNoErrorsInConsole(page) // TODO: revert when playwright doesn't skip other tests because of this
await setup(page)
await page.route('https://global.transak.com/*', route =>
route.fulfill({
status: 301,
headers: {
Location: 'https://phishing-transak.com/',
},
}),
await page.route('https://*.transak.com/*', route =>
route.fulfill({ status: 301, headers: { Location: 'https://phishing-transak.com/' } }),
)
await page.route('https://phishing-transak.com/', route => route.fulfill({ body: `phishing` }))

Expand All @@ -84,11 +77,11 @@ test.describe('Fiat on-ramp', () => {
])
})

test('Sandbox should block top-navigation from iframe and fail', async ({ page, baseURL }) => {
test('Sandbox should block top-navigation from iframe and fail', async ({ page }) => {
test.fail()
// await expectNoErrorsInConsole(page) // TODO: revert when playwright doesn't skip other tests because of this
await setup(page)
await page.route('https://global.transak.com/*', route =>
await page.route('https://*.transak.com/*', route =>
route.fulfill({
body: `<script>window.top.location = 'https://phishing-wallet.com/';</script>`,
}),
Expand All @@ -106,8 +99,7 @@ test.describe('Fiat on-ramp', () => {
await expect(page).toHaveURL('https://phishing-wallet.com/')
})

test('Permissions-Policy should contain Transak permissions', async ({ page, baseURL }) => {
expect(baseURL).toBe('http://localhost:5000')
test('Permissions-Policy should contain Transak permissions', async ({ page }) => {
expect((await page.request.head('/')).headers()).toHaveProperty('permissions-policy')
await expectNoErrorsInConsole(page)
await setup(page)
Expand Down
3 changes: 1 addition & 2 deletions playwright/tests/ledger.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ import { test, expect } from '@playwright/test'
import { expectNoErrorsInConsole } from '../utils/expectNoErrorsInConsole'

test.describe('Ledger', () => {
test('Permissions-Policy should allow USB', async ({ page, baseURL }) => {
expect(baseURL).toBe('http://localhost:5000')
test('Permissions-Policy should allow USB', async ({ page }) => {
expect((await page.request.head('/')).headers()).toHaveProperty('permissions-policy')
await expectNoErrorsInConsole(page)

Expand Down
3 changes: 1 addition & 2 deletions playwright/tests/validators.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,7 @@ test.beforeEach(async ({ page }) => {
})

test.describe('Validators', () => {
test('Content-Security-Policy should allow validator icons', async ({ page, baseURL }) => {
expect(baseURL).toBe('http://localhost:5000')
test('Content-Security-Policy should allow validator icons', async ({ page }) => {
expect((await page.request.head('/')).headers()).toHaveProperty('content-security-policy')

const someValidatorIconPromise = page.waitForResponse(
Expand Down
11 changes: 9 additions & 2 deletions src/app/pages/E2EPage/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export function E2EPage() {
<br />
<TestUnsafeInputs></TestUnsafeInputs>
<br />
<TriggerFatalError></TriggerFatalError>
<TriggerError></TriggerError>
<br />
<DemoAlertBoxes></DemoAlertBoxes>
</div>
Expand Down Expand Up @@ -118,7 +118,7 @@ function UnsafePasswordField(props: {
)
}

function TriggerFatalError() {
function TriggerError() {
const dispatch = useDispatch()
return (
<div>
Expand All @@ -128,6 +128,13 @@ function TriggerFatalError() {
dispatch(walletActions.openWalletFromPrivateKey({ privateKey: '0xAA', choosePassword: undefined }))
}}
/>
<Button
label="Trigger uncaught error"
onClick={() => {
// @ts-expect-error Function does not exist
functionDoesNotExist()
}}
/>
</div>
)
}
Expand Down
7 changes: 7 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3554,6 +3554,13 @@
resolved "https://registry.yarnpkg.com/@types/body-scroll-lock/-/body-scroll-lock-3.1.0.tgz#435f6abf682bf58640e1c2ee5978320b891970e7"
integrity sha512-3owAC4iJub5WPqRhxd8INarF2bWeQq1yQHBgYhN0XLBJMpd5ED10RrJ3aKiAwlTyL5wK7RkBD4SZUQz2AAAMdA==

"@types/[email protected]":
version "3.4.35"
resolved "https://registry.yarnpkg.com/@types/connect/-/connect-3.4.35.tgz#5fcf6ae445e4021d1fc2219a4873cc73a3bb2ad1"
integrity sha512-cdeYyv4KWoEgpBISTxWvqYsVy444DOqehiF3fM3ne10AmJ62RSyNkUnxMJXHQWRQQX2eR94m5y1IZyDwBjV9FQ==
dependencies:
"@types/node" "*"

"@types/graceful-fs@^4.1.3":
version "4.1.5"
resolved "https://registry.yarnpkg.com/@types/graceful-fs/-/graceful-fs-4.1.5.tgz#21ffba0d98da4350db64891f92a9e5db3cdb4e15"
Expand Down

0 comments on commit 519f2ca

Please sign in to comment.