Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Call 404 handler if requested path is a dotfile #225

Merged
merged 2 commits into from Aug 5, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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