-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
feat(node): Add Koa error handler #11403
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
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
@sentry:registry=http://127.0.0.1:4873 | ||
@sentry-internal:registry=http://127.0.0.1:4873 |
145 changes: 145 additions & 0 deletions
145
dev-packages/e2e-tests/test-applications/node-koa-app/index.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,145 @@ | ||
const Sentry = require('@sentry/node'); | ||
|
||
Sentry.init({ | ||
environment: 'qa', // dynamic sampling bias to keep transactions | ||
dsn: process.env.E2E_TEST_DSN, | ||
includeLocalVariables: true, | ||
debug: true, | ||
tunnel: `http://localhost:3031/`, // proxy server | ||
tracesSampleRate: 1, | ||
tracePropagationTargets: ['http://localhost:3030', 'external-allowed'], | ||
}); | ||
|
||
const port1 = 3030; | ||
const port2 = 3040; | ||
|
||
const Koa = require('koa'); | ||
const Router = require('@koa/router'); | ||
const http = require('http'); | ||
|
||
const app1 = new Koa(); | ||
|
||
Sentry.setupKoaErrorHandler(app1); | ||
|
||
const router1 = new Router(); | ||
|
||
router1.get('/test-success', ctx => { | ||
ctx.body = { version: 'v1' }; | ||
}); | ||
|
||
router1.get('/test-param/:param', ctx => { | ||
ctx.body = { paramWas: ctx.params.param }; | ||
}); | ||
|
||
router1.get('/test-inbound-headers/:id', ctx => { | ||
const headers = ctx.request.headers; | ||
|
||
ctx.body = { | ||
headers, | ||
id: ctx.params.id, | ||
}; | ||
}); | ||
|
||
router1.get('/test-outgoing-http/:id', async ctx => { | ||
const id = ctx.params.id; | ||
const data = await makeHttpRequest(`http://localhost:3030/test-inbound-headers/${id}`); | ||
|
||
ctx.body = data; | ||
}); | ||
|
||
router1.get('/test-outgoing-fetch/:id', async ctx => { | ||
const id = ctx.params.id; | ||
const response = await fetch(`http://localhost:3030/test-inbound-headers/${id}`); | ||
const data = await response.json(); | ||
|
||
ctx.body = data; | ||
}); | ||
|
||
router1.get('/test-transaction', ctx => { | ||
Sentry.startSpan({ name: 'test-span' }, () => { | ||
Sentry.startSpan({ name: 'child-span' }, () => {}); | ||
}); | ||
|
||
ctx.body = {}; | ||
}); | ||
|
||
router1.get('/test-error', async ctx => { | ||
const exceptionId = Sentry.captureException(new Error('This is an error')); | ||
|
||
await Sentry.flush(2000); | ||
|
||
ctx.body = { exceptionId }; | ||
}); | ||
|
||
router1.get('/test-exception', async ctx => { | ||
throw new Error('This is an exception'); | ||
}); | ||
|
||
router1.get('/test-outgoing-fetch-external-allowed', async ctx => { | ||
const fetchResponse = await fetch(`http://localhost:${port2}/external-allowed`); | ||
const data = await fetchResponse.json(); | ||
|
||
ctx.body = data; | ||
}); | ||
|
||
router1.get('/test-outgoing-fetch-external-disallowed', async ctx => { | ||
const fetchResponse = await fetch(`http://localhost:${port2}/external-disallowed`); | ||
const data = await fetchResponse.json(); | ||
|
||
ctx.body = data; | ||
}); | ||
|
||
router1.get('/test-outgoing-http-external-allowed', async ctx => { | ||
const data = await makeHttpRequest(`http://localhost:${port2}/external-allowed`); | ||
ctx.body = data; | ||
}); | ||
|
||
router1.get('/test-outgoing-http-external-disallowed', async ctx => { | ||
const data = await makeHttpRequest(`http://localhost:${port2}/external-disallowed`); | ||
ctx.body = data; | ||
}); | ||
|
||
app1.use(router1.routes()).use(router1.allowedMethods()); | ||
|
||
app1.listen(port1); | ||
|
||
const app2 = new Koa(); | ||
const router2 = new Router(); | ||
|
||
router2.get('/external-allowed', ctx => { | ||
const headers = ctx.headers; | ||
ctx.body = { headers, route: '/external-allowed' }; | ||
}); | ||
|
||
router2.get('/external-disallowed', ctx => { | ||
const headers = ctx.headers; | ||
ctx.body = { headers, route: '/external-disallowed' }; | ||
}); | ||
|
||
app2.use(router2.routes()).use(router2.allowedMethods()); | ||
app2.listen(port2); | ||
|
||
function makeHttpRequest(url) { | ||
return new Promise(resolve => { | ||
const data = []; | ||
|
||
http | ||
.request(url, httpRes => { | ||
httpRes.on('data', chunk => { | ||
data.push(chunk); | ||
}); | ||
httpRes.on('error', error => { | ||
resolve({ error: error.message, url }); | ||
}); | ||
httpRes.on('end', () => { | ||
try { | ||
const json = JSON.parse(Buffer.concat(data).toString()); | ||
resolve(json); | ||
} catch { | ||
resolve({ data: Buffer.concat(data).toString(), url }); | ||
} | ||
}); | ||
}) | ||
Comment on lines
+126
to
+142
Check failureCode scanning / CodeQL Server-side request forgery
The [URL](1) of this request depends on a [user-provided value](2).
|
||
.end(); | ||
}); | ||
} |
28 changes: 28 additions & 0 deletions
28
dev-packages/e2e-tests/test-applications/node-koa-app/package.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
{ | ||
"name": "node-koa-app", | ||
"version": "1.0.0", | ||
"private": true, | ||
"scripts": { | ||
"start": "node index.js", | ||
"test": "playwright test", | ||
"clean": "npx rimraf node_modules,pnpm-lock.yaml", | ||
"test:build": "pnpm install", | ||
"test:assert": "pnpm test" | ||
}, | ||
"dependencies": { | ||
"@koa/router": "^12.0.1", | ||
"@sentry/node": "latest || *", | ||
"@sentry/types": "latest || *", | ||
"@types/node": "18.15.1", | ||
"koa": "^2.15.2", | ||
"typescript": "4.9.5" | ||
}, | ||
"devDependencies": { | ||
"@sentry-internal/event-proxy-server": "link:../../../event-proxy-server", | ||
"@playwright/test": "^1.27.1", | ||
"ts-node": "10.9.1" | ||
}, | ||
"volta": { | ||
"extends": "../../package.json" | ||
} | ||
} |
77 changes: 77 additions & 0 deletions
77
dev-packages/e2e-tests/test-applications/node-koa-app/playwright.config.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
import type { PlaywrightTestConfig } from '@playwright/test'; | ||
import { devices } from '@playwright/test'; | ||
|
||
const koaPort = 3030; | ||
const eventProxyPort = 3031; | ||
|
||
/** | ||
* See https://playwright.dev/docs/test-configuration. | ||
*/ | ||
const config: PlaywrightTestConfig = { | ||
testDir: './tests', | ||
/* Maximum time one test can run for. */ | ||
timeout: 150_000, | ||
expect: { | ||
/** | ||
* Maximum time expect() should wait for the condition to be met. | ||
* For example in `await expect(locator).toHaveText();` | ||
*/ | ||
timeout: 5000, | ||
}, | ||
/* Run tests in files in parallel */ | ||
fullyParallel: true, | ||
/* Fail the build on CI if you accidentally left test.only in the source code. */ | ||
forbidOnly: !!process.env.CI, | ||
/* Retry on CI only */ | ||
retries: 0, | ||
/* Reporter to use. See https://playwright.dev/docs/test-reporters */ | ||
reporter: 'list', | ||
/* 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: 0, | ||
|
||
/* Base URL to use in actions like `await page.goto('/')`. */ | ||
baseURL: `http://localhost:${koaPort}`, | ||
|
||
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */ | ||
trace: 'on-first-retry', | ||
}, | ||
|
||
/* Configure projects for major browsers */ | ||
projects: [ | ||
{ | ||
name: 'chromium', | ||
use: { | ||
...devices['Desktop Chrome'], | ||
}, | ||
}, | ||
// For now we only test Chrome! | ||
// { | ||
// name: 'firefox', | ||
// use: { | ||
// ...devices['Desktop Firefox'], | ||
// }, | ||
// }, | ||
// { | ||
// name: 'webkit', | ||
// use: { | ||
// ...devices['Desktop Safari'], | ||
// }, | ||
// }, | ||
], | ||
|
||
/* Run your local dev server before starting the tests */ | ||
webServer: [ | ||
{ | ||
command: 'pnpm ts-node-script start-event-proxy.ts', | ||
port: eventProxyPort, | ||
}, | ||
{ | ||
command: 'pnpm start', | ||
port: koaPort, | ||
}, | ||
], | ||
}; | ||
|
||
export default config; |
6 changes: 6 additions & 0 deletions
6
dev-packages/e2e-tests/test-applications/node-koa-app/start-event-proxy.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
import { startEventProxyServer } from '@sentry-internal/event-proxy-server'; | ||
|
||
startEventProxyServer({ | ||
port: 3031, | ||
proxyServerName: 'node-koa-app', | ||
}); |
72 changes: 72 additions & 0 deletions
72
dev-packages/e2e-tests/test-applications/node-koa-app/tests/errors.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
import { expect, test } from '@playwright/test'; | ||
import { waitForError } from '@sentry-internal/event-proxy-server'; | ||
import axios, { AxiosError } from 'axios'; | ||
|
||
const authToken = process.env.E2E_TEST_AUTH_TOKEN; | ||
const sentryTestOrgSlug = process.env.E2E_TEST_SENTRY_ORG_SLUG; | ||
const sentryTestProject = process.env.E2E_TEST_SENTRY_TEST_PROJECT; | ||
const EVENT_POLLING_TIMEOUT = 90_000; | ||
|
||
test('Sends exception to Sentry', async ({ baseURL }) => { | ||
const { data } = await axios.get(`${baseURL}/test-error`); | ||
const { exceptionId } = data; | ||
|
||
const url = `https://sentry.io/api/0/projects/${sentryTestOrgSlug}/${sentryTestProject}/events/${exceptionId}/`; | ||
|
||
console.log(`Polling for error eventId: ${exceptionId}`); | ||
|
||
await expect | ||
.poll( | ||
async () => { | ||
try { | ||
const response = await axios.get(url, { headers: { Authorization: `Bearer ${authToken}` } }); | ||
|
||
return response.status; | ||
} catch (e) { | ||
if (e instanceof AxiosError && e.response) { | ||
if (e.response.status !== 404) { | ||
throw e; | ||
} else { | ||
return e.response.status; | ||
} | ||
} else { | ||
throw e; | ||
} | ||
} | ||
}, | ||
{ timeout: EVENT_POLLING_TIMEOUT }, | ||
) | ||
.toBe(200); | ||
}); | ||
|
||
test('Sends correct error event', async ({ baseURL }) => { | ||
const errorEventPromise = waitForError('node-koa-app', event => { | ||
return !event.type && event.exception?.values?.[0]?.value === 'This is an exception'; | ||
}); | ||
|
||
try { | ||
await axios.get(`${baseURL}/test-exception`); | ||
} catch { | ||
// this results in an error, but we don't care - we want to check the error event | ||
} | ||
|
||
const errorEvent = await errorEventPromise; | ||
|
||
expect(errorEvent.exception?.values).toHaveLength(1); | ||
expect(errorEvent.exception?.values?.[0]?.value).toBe('This is an exception'); | ||
|
||
expect(errorEvent.request).toEqual({ | ||
method: 'GET', | ||
cookies: {}, | ||
headers: expect.any(Object), | ||
url: 'http://localhost:3030/test-exception', | ||
}); | ||
|
||
expect(errorEvent.transaction).toEqual('GET /test-exception'); | ||
|
||
expect(errorEvent.contexts?.trace).toEqual({ | ||
trace_id: expect.any(String), | ||
span_id: expect.any(String), | ||
parent_span_id: expect.any(String), | ||
}); | ||
}); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Check failure
Code scanning / CodeQL
Server-side request forgery