Skip to content
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
6 changes: 2 additions & 4 deletions dev-packages/deno-integration-tests/node-suites/excludes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ const NO_SENTRY_DENO_EXPORT = [
'suites/cron/node-cron/base/test.ts',
'suites/cron/node-cron/isolateTrace/test.ts',
'suites/cron/node-schedule/test.ts',
'suites/esm/modules-integration/test.ts',
'suites/express/multiple-init/test.ts',
'suites/express/with-http/maxIncomingRequestBodySize/test.ts',
'suites/fs-instrumentation/test.ts',
Expand Down Expand Up @@ -65,12 +64,11 @@ const NO_CLIENT_TRACER = ['suites/tracing/tracer-start-active-span-error/test.ts
const NO_NODE_LOGGER_PARAMETERS = ['suites/public-api/logs/test.ts'];

// The test expects data that a default integration of `@sentry/node` adds and `@sentry/deno` does
// not have: process sessions, child process breadcrumbs, the `modules` of the event, the
// `node_system_error` context, and the context attributes of `nodeContextIntegration` on spans.
// not have: process sessions, child process breadcrumbs, the `node_system_error` context, and the
// context attributes of `nodeContextIntegration` on spans.
const NO_NODE_DEFAULT_INTEGRATION = [
'suites/child-process/test.ts',
'suites/context/test.ts',
'suites/modules/test.ts',
'suites/public-api/startSpan/basic-usage/with-children/test.ts',
'suites/sessions/process-session/test.ts',
'suites/sessions/server-without-process-session/test.ts',
Expand Down
11 changes: 8 additions & 3 deletions dev-packages/node-integration-tests/suites/modules/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { SDK_VERSION } from '@sentry/core';
import { copyFileSync, cpSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'fs';
import { dirname, join } from 'path';
import { afterAll, describe, expect, test } from 'vitest';
import { supports } from '../../utils';
import { cleanupChildProcesses, createRunner } from '../../utils/runner';

// Each test writes its packages into a folder of its own, because the Bun integration tests run this suite in
Expand All @@ -10,12 +11,16 @@ function makeTempDir(): string {
return mkdtempSync(join(__dirname, 'tmp-'));
}

// The Deno integration cannot see packages that were loaded but not declared in `package.json`, because it does not
// read the CommonJS module cache.
const READS_LOADED_MODULES = supports({ runtimes: ['node', 'bun'] });

describe('modulesIntegration', () => {
afterAll(() => {
cleanupChildProcesses();
});

test('CJS', async () => {
test.runIf(READS_LOADED_MODULES)('CJS', async () => {
await createRunner(__dirname, 'scenario.js')
.expect({
event: {
Expand All @@ -33,7 +38,7 @@ describe('modulesIntegration', () => {
.completed();
});

test('CJS with the isolated layouts of pnpm and Bun', async () => {
test.runIf(READS_LOADED_MODULES)('CJS with the isolated layouts of pnpm and Bun', async () => {
const tempDir = makeTempDir();
copyFileSync(join(__dirname, 'scenario-isolated.js'), join(tempDir, 'scenario-isolated.js'));
const nodeModulesDir = join(tempDir, 'node_modules');
Expand Down Expand Up @@ -90,7 +95,7 @@ describe('modulesIntegration', () => {
.completed();
});

test('ESM app in a subfolder with its own package.json', async () => {
test.runIf(READS_LOADED_MODULES)('ESM app in a subfolder with its own package.json', async () => {
const tempDir = makeTempDir();
const appDir = join(tempDir, 'esm-app');
cpSync(join(__dirname, 'esm-app'), appDir, { recursive: true });
Expand Down
1 change: 1 addition & 0 deletions packages/deno/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ export type { DenoServeIntegrationOptions } from './integrations/deno-serve';
export { fetchIntegration } from './integrations/fetch';
export type { FetchIntegrationOptions } from '@sentry/core';
export { denoHttpIntegration } from './integrations/http';
export { modulesIntegration } from './integrations/modules';
export type { DenoHttpIntegrationOptions } from './integrations/http';

// The orchestrion channel integrations, re-exported from `@sentry/server-utils`.
Expand Down
67 changes: 67 additions & 0 deletions packages/deno/src/integrations/modules.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { fileURLToPath } from 'node:url';
import type { IntegrationFn } from '@sentry/core';
import { defineIntegration, dirname, join } from '@sentry/core';
import { collectInstalledModules } from '@sentry/server-utils';

/** Reads only with granted permission, so it never prompts. */
function readFile(path?: string): string | undefined {
try {
if (Deno.permissions.querySync({ name: 'read', path }).state === 'granted') {
return path ? Deno.readTextFileSync(path) : Deno.cwd();
}
} catch {
// not readable
}
return undefined;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cwd is never found with scoped read permission

Low Severity

readFile() with no path also acts as the cwd getter. It calls Deno.permissions.querySync with path: undefined, which only reports granted when read access to everything is allowed. With a scoped permission such as --allow-read=., cwd is always undefined. When the main module isn't a file: URL, nothing is collected even though the files can be read.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 550c807. Configure here.


/** Exact versions of the `jsr:` and `npm:` specifiers in the nearest `deno.lock` (versions 3 to 5). */
function getDenoLockModules(startDir: string): Record<string, string> {
const modules: Record<string, string> = {};
for (let dir = startDir, prev = ''; dir !== prev && dir !== '.'; prev = dir, dir = dirname(dir)) {
const content = readFile(join(dir, 'deno.lock'));
if (content) {
try {
const lock = JSON.parse(content) as { specifiers?: object; packages?: { specifiers?: object } };
for (const [specifier, resolved] of Object.entries(lock.specifiers || lock.packages?.specifiers || {})) {
const name = /^(?:npm|jsr):(@?[^@]+)@/.exec(specifier)?.[1];
// v3 stores `npm:express@4.21.2`, later versions `4.21.2`; npm versions can end in `_<peer deps>`.
const version = typeof resolved === 'string' && resolved.replace(/^(?:npm|jsr):@?[^@]+@/, '').split('_')[0];
if (name && version) {
modules[name] = version;
}
}
} catch {
// invalid lockfile
}
break;
}
}
return modules;
}

function collectModules(): Record<string, string> {
const entryPath = Deno.mainModule.startsWith('file:') ? fileURLToPath(Deno.mainModule) : undefined;
const cwd = readFile();
const modules = collectInstalledModules({ readFile, entryPath, cwd });
const startDir = (entryPath ? dirname(entryPath.replace(/\\/g, '/')) : cwd?.replace(/\\/g, '/')) || '.';
// Without `node_modules`, `modules` only has declared ranges, so the exact versions from `deno.lock` win.
return { ...modules, ...getDenoLockModules(startDir) };
}

const _modulesIntegration = (() => {
let modules: Record<string, string> | undefined;
return {
name: 'Modules' as const,
processEvent(event) {
modules = modules || collectModules();
Comment thread
sentry-warden[bot] marked this conversation as resolved.
Resolved
event.modules = { ...event.modules, ...modules };
return event;
},
};
}) satisfies IntegrationFn;

/**
* Adds the app's packages and versions to events, from `deno.lock` and from `package.json` and `node_modules`.
*/
export const modulesIntegration = defineIntegration(_modulesIntegration);
2 changes: 2 additions & 0 deletions packages/deno/src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { denoServeIntegration } from './integrations/deno-serve';
import { fetchIntegration } from './integrations/fetch';
import { denoHttpIntegration } from './integrations/http';
import { globalHandlersIntegration } from './integrations/globalhandlers';
import { modulesIntegration } from './integrations/modules';
import { normalizePathsIntegration } from './integrations/normalizepaths';
import { setupOpenTelemetryTracer } from './opentelemetry/tracer';
import { makeFetchTransport } from './transports';
Expand All @@ -54,6 +55,7 @@ export function getDefaultIntegrationsWithoutPerformance(): Integration[] {
fetchIntegration(),
denoHttpIntegration(),
contextLinesIntegration(),
modulesIntegration(),
normalizePathsIntegration(),
globalHandlersIntegration(),
// server-utils integrations
Expand Down
9 changes: 9 additions & 0 deletions packages/deno/test/__snapshots__/mod.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ snapshot[`captureMessage 1`] = `
event_id: "{{id}}",
level: "info",
message: "Some error message",
modules: {
"{{modules}}": "{{version}}",
},
platform: "javascript",
sdk: {
integrations: [
Expand Down Expand Up @@ -114,6 +117,9 @@ snapshot[`captureMessage twice 1`] = `
event_id: "{{id}}",
level: "info",
message: "Some error message",
modules: {
"{{modules}}": "{{version}}",
},
platform: "javascript",
sdk: {
integrations: [
Expand Down Expand Up @@ -191,6 +197,9 @@ snapshot[`captureMessage twice 2`] = `
event_id: "{{id}}",
level: "info",
message: "Another error message",
modules: {
"{{modules}}": "{{version}}",
},
platform: "javascript",
sdk: {
integrations: [
Expand Down
1 change: 1 addition & 0 deletions packages/deno/test/exports.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ const EXPECTED_FUNCTION_EXPORTS = [
// ./sdk
'initWithoutDefaultIntegrations',
'getDefaultIntegrationsWithoutPerformance',
'modulesIntegration',
];

for (const name of EXPECTED_FUNCTION_EXPORTS) {
Expand Down
8 changes: 8 additions & 0 deletions packages/deno/test/fixtures/modules/deno.lock

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

15 changes: 15 additions & 0 deletions packages/deno/test/fixtures/modules/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import * as Sentry from '../../../build/esm/index.js';

Sentry.init({
dsn: 'https://username@domain/123',
defaultIntegrations: false,
integrations: [Sentry.modulesIntegration()],
beforeSend(event) {
// oxlint-disable-next-line no-console
console.log(JSON.stringify(event.modules));
return null;
},
});

Sentry.captureException(new Error('test'));
await Sentry.flush();
7 changes: 7 additions & 0 deletions packages/deno/test/fixtures/modules/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"name": "deno-modules-fixture",
"private": true,
"dependencies": {
"left-pad": "^1.3.0"
}
}
27 changes: 27 additions & 0 deletions packages/deno/test/modules.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { assertEquals } from 'https://deno.land/std@0.212.0/assert/assert_equals.ts';

const fixtureDir = new URL('./fixtures/modules/', import.meta.url);

async function runFixture(permissions: string[]): Promise<unknown> {
const { stdout, stderr, success } = await new Deno.Command(Deno.execPath(), {
// `--no-lock` keeps Deno from rewriting the fixture lockfile.
args: ['run', '--no-prompt', '--no-lock', ...permissions, new URL('main.ts', fixtureDir).pathname],
cwd: fixtureDir.pathname,
stdin: 'null',
}).output();
assertEquals(success, true, new TextDecoder().decode(stderr));
return JSON.parse(new TextDecoder().decode(stdout).trim());
}

Deno.test('modulesIntegration reads deno.lock and package.json', async () => {
assertEquals(await runFixture([`--allow-read=${fixtureDir.pathname}`]), {
'left-pad': '^1.3.0',
'@std/assert': '1.0.13',
'@types/react-dom': '18.3.0',
express: '4.21.2',
});
});

Deno.test('modulesIntegration reads nothing without read permission', async () => {
assertEquals(await runFixture([]), {});
});
5 changes: 5 additions & 0 deletions packages/deno/test/normalize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,11 @@ function normalizeEvent(event: Event): Event {
event.sdk.integrations = ['{{integrations}}'];
}

// Installed packages depend on the checkout, so collapse them to a placeholder.
if (event.modules) {
event.modules = { '{{modules}}': '{{version}}' };
}

if (event.contexts?.app?.app_start_time) {
event.contexts.app.app_start_time = '{{time}}';
}
Expand Down
Loading