Skip to content

Commit

Permalink
fix: call 404 handler if requested path is a dotfile (#225)
Browse files Browse the repository at this point in the history
* fix: handle NotFoundError

* fix: Add regression test to call 404 handler when send ignores a dotfile (#218)

Co-authored-by: BlackGlory <woshenmedoubuzhidao@blackglory.me>
Co-authored-by: Gorman Fletcher <git@gormanfletcher.com>
  • Loading branch information
3 people committed Aug 5, 2021
1 parent 5656185 commit fa907a0
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
11 changes: 11 additions & 0 deletions index.js
Expand Up @@ -187,6 +187,17 @@ async function fastifyStatic (fastify, opts) {

return reply.callNotFound()
}

// The `send` library terminates the request with a 404 if the requested
// path contains a dotfile and `send` is initialized with `{dotfiles:
// 'ignore'}`. `send` aborts the request before getting far enough to
// check if the file exists (hence, a 404 `NotFoundError` instead of
// `ENOENT`).
// https://github.com/pillarjs/send/blob/de073ed3237ade9ff71c61673a34474b30e5d45b/index.js#L582
if (err.status === 404) {
return reply.callNotFound()
}

reply.send(err)
})

Expand Down
43 changes: 43 additions & 0 deletions test/static.test.js
Expand Up @@ -748,6 +748,49 @@ t.test('not found responses can be customized with fastify.setNotFoundHandler()'
})
})

t.test('fastify.setNotFoundHandler() is called for dotfiles when when send is configured to ignore dotfiles', t => {
t.plan(2)

const pluginOptions = {
root: path.join(__dirname, '/static'),
send: {
dotfiles: 'ignore'
}
}
const fastify = Fastify()

fastify.setNotFoundHandler(function notFoundHandler (request, reply) {
reply.code(404).type('text/plain').send(request.raw.url + ' Not Found')
})

fastify.register(fastifyStatic, pluginOptions)

t.teardown(fastify.close.bind(fastify))

fastify.listen(0, err => {
t.error(err)

fastify.server.unref()

// Requesting files with a leading dot doesn't follow the same code path as
// other 404 errors
t.test('/path/does/not/.exist.html', t => {
t.plan(4)

simple.concat({
method: 'GET',
url: 'http://localhost:' + fastify.server.address().port + '/path/does/not/.exist.html',
followRedirect: false
}, (err, response, body) => {
t.error(err)
t.equal(response.statusCode, 404)
t.equal(response.headers['content-type'], 'text/plain')
t.equal(body.toString(), '/path/does/not/.exist.html Not Found')
})
})
})
})

t.test('serving disabled', (t) => {
t.plan(3)

Expand Down

0 comments on commit fa907a0

Please sign in to comment.