Skip to content

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 3 commits into from
Apr 5, 2024
Merged
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
1 change: 1 addition & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1051,6 +1051,7 @@ jobs:
# 'node-hapi-app',
'node-nestjs-app',
'node-exports-test-app',
'node-koa-app',
'vue-3',
'webpack-4',
'webpack-5'
Expand Down
2 changes: 2 additions & 0 deletions dev-packages/e2e-tests/test-applications/node-koa-app/.npmrc
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 dev-packages/e2e-tests/test-applications/node-koa-app/index.js
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}`);

Check failure

Code scanning / CodeQL

Server-side request forgery

The [URL](1) of this request depends on a [user-provided value](2).
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 failure

Code 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 dev-packages/e2e-tests/test-applications/node-koa-app/package.json
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"
}
}
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;
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',
});
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),
});
});
Loading