Skip to content

Commit

Permalink
fix(instr-express): normalize paths with double slashes (#1995)
Browse files Browse the repository at this point in the history
* fix(instr-express): normalize paths with double slashes

* remove unnecessary listener count from test

---------

Co-authored-by: Marc Pichler <marc.pichler@dynatrace.com>
  • Loading branch information
JamieDanielson and pichlermarc committed Mar 7, 2024
1 parent 98f43cd commit 65a9553
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
Expand Up @@ -197,7 +197,9 @@ export class ExpressInstrumentation extends InstrumentationBase<
storeLayerPath(req, layerPath);
const route = (req[_LAYERS_STORE_PROPERTY] as string[])
.filter(path => path !== '/' && path !== '/*')
.join('');
.join('')
// remove duplicate slashes to normalize route
.replace(/\/{2,}/g, '/');

const attributes: Attributes = {
[SemanticAttributes.HTTP_ROUTE]: route.length > 0 ? route : '/',
Expand Down
Expand Up @@ -455,6 +455,39 @@ describe('ExpressInstrumentation', () => {
}
);
});

it('should ignore double slashes in routes', async () => {
const rootSpan = tracer.startSpan('rootSpan');
let rpcMetadata: RPCMetadata | undefined;
const httpServer = await serverWithMiddleware(tracer, rootSpan, app => {
app.use(express.json());
app.use((req, res, next) => {
rpcMetadata = getRPCMetadata(context.active());
next();
});
});
server = httpServer.server;
port = httpServer.port;
assert.strictEqual(memoryExporter.getFinishedSpans().length, 0);
await context.with(
trace.setSpan(context.active(), rootSpan),
async () => {
const response = await httpRequest.get(
`http://localhost:${port}/double-slashes/foo`
);
assert.strictEqual(response, 'foo');
rootSpan.end();
const requestHandlerSpan = memoryExporter
.getFinishedSpans()
.find(span => span.name.includes('request handler'));
assert.strictEqual(
requestHandlerSpan?.attributes[SemanticAttributes.HTTP_ROUTE],
'/double-slashes/:id'
);
assert.strictEqual(rpcMetadata?.route, '/double-slashes/:id');
}
);
});
});

describe('Disabling plugin', () => {
Expand Down
Expand Up @@ -66,6 +66,7 @@ export async function serverWithMiddleware(

const router = express.Router();
app.use('/toto', router);
app.use('/double-slashes/', router);
router.get('/:id', (req, res) => {
setImmediate(() => {
res.status(200).end(req.params.id);
Expand Down

0 comments on commit 65a9553

Please sign in to comment.