Skip to content

Commit

Permalink
Retain path when using fallback precompressed path
Browse files Browse the repository at this point in the history
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`.
  • Loading branch information
colatkinson committed Mar 27, 2024
1 parent 4e39bd8 commit 40bf00f
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 1 deletion.
3 changes: 2 additions & 1 deletion index.js
Expand Up @@ -174,6 +174,7 @@ async function fastifyStatic (fastify, opts) {
pumpOptions,
checkedEncodings
) {
const pathnameOrig = pathname
const options = Object.assign({}, sendOptions, pumpOptions)

if (rootPath) {
Expand Down Expand Up @@ -346,7 +347,7 @@ async function fastifyStatic (fastify, opts) {
return pumpSendToReply(
request,
reply,
pathname,
pathnameOrig,
rootPath,
rootPathOffset,
undefined,
Expand Down
5 changes: 5 additions & 0 deletions test/static-pre-compressed/dir-gz/index.html
@@ -0,0 +1,5 @@
<html>
<body>
dir-gz index
</body>
</html>
Binary file added test/static-pre-compressed/dir-gz/index.html.gz
Binary file not shown.
32 changes: 32 additions & 0 deletions test/static.test.js
Expand Up @@ -46,6 +46,9 @@ const indexBr = fs.readFileSync(
const dirIndexBr = fs.readFileSync(
'./test/static-pre-compressed/dir/index.html.br'
)
const dirIndexGz = fs.readFileSync(
'./test/static-pre-compressed/dir-gz/index.html.gz'
)
const uncompressedStatic = fs
.readFileSync('./test/static-pre-compressed/uncompressed.html')
.toString('utf8')
Expand Down Expand Up @@ -3496,6 +3499,35 @@ t.test(
}
)

t.test(
'will serve precompressed gzip index in subdir',
async (t) => {
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) => {
Expand Down

0 comments on commit 40bf00f

Please sign in to comment.