From 40bf00ffb8589ecf6539d6eea63912278bccb4fd Mon Sep 17 00:00:00 2001 From: Colin Atkinson Date: Wed, 27 Mar 2024 16:09:15 -0400 Subject: [PATCH] Retain path when using fallback precompressed path If there is no brotli-encoded asset and instead only a gzip-encoded one, the code first tries to serve the brotli-encoded form and then falls back on the gzip-encoded one. When doing so, however, it uses a path name that has been overwritten which leads to the wrong file being served. For instance, if a request is for `/dir/`, then `pathname` will first be changed to `index.html`. On the retry, `index.html` will be used as the base pathname and thus `/index.html` will be served instead of `/dir/index.html`. --- index.js | 3 +- test/static-pre-compressed/dir-gz/index.html | 5 +++ .../dir-gz/index.html.gz | Bin 0 -> 69 bytes test/static.test.js | 32 ++++++++++++++++++ 4 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 test/static-pre-compressed/dir-gz/index.html create mode 100644 test/static-pre-compressed/dir-gz/index.html.gz diff --git a/index.js b/index.js index 1831e5a..74027fc 100644 --- a/index.js +++ b/index.js @@ -174,6 +174,7 @@ async function fastifyStatic (fastify, opts) { pumpOptions, checkedEncodings ) { + const pathnameOrig = pathname const options = Object.assign({}, sendOptions, pumpOptions) if (rootPath) { @@ -346,7 +347,7 @@ async function fastifyStatic (fastify, opts) { return pumpSendToReply( request, reply, - pathname, + pathnameOrig, rootPath, rootPathOffset, undefined, diff --git a/test/static-pre-compressed/dir-gz/index.html b/test/static-pre-compressed/dir-gz/index.html new file mode 100644 index 0000000..8551365 --- /dev/null +++ b/test/static-pre-compressed/dir-gz/index.html @@ -0,0 +1,5 @@ + + + dir-gz index + + diff --git a/test/static-pre-compressed/dir-gz/index.html.gz b/test/static-pre-compressed/dir-gz/index.html.gz new file mode 100644 index 0000000000000000000000000000000000000000..4de92ee46a2a9d8cfa13aa21fcb6c772265b62b0 GIT binary patch literal 69 zcmb2|=HRfeVo76S&df_mt { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + preCompressed: true + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.teardown(fastify.close.bind(fastify)) + + const response = await fastify.inject({ + method: 'GET', + url: '/dir-gz', + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + + genericResponseChecks(t, response) + t.equal(response.headers['content-encoding'], 'gzip') + t.equal(response.statusCode, 200) + t.same(response.rawPayload, dirIndexGz) + t.end() + } +) + t.test( 'will serve precompressed index with alternative index option', async (t) => {