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

(v3.x) fix: handle invalid url #3806

Merged
merged 3 commits into from Apr 1, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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
24 changes: 22 additions & 2 deletions lib/fourOhFour.js
Expand Up @@ -34,10 +34,10 @@ const fourOhFourContext = {
* kFourOhFourContext: the context in the reply object where the handler will be executed
*/
function fourOhFour (options) {
const { logger, genReqId } = options
const { logger, genReqId, disableRequestLogging } = options

// 404 router, used for handling encapsulated 404 handlers
const router = FindMyWay({ defaultRoute: fourOhFourFallBack })
const router = FindMyWay({ onBadUrl, defaultRoute: fourOhFourFallBack })
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am unclear how this is different from the default route. Both are handling the 404 case, correct?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, I don't understand why both are needed.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can check this issue #3127

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this is right. It's a 404. The 404 handler should handle it. As implemented, we should be exposing two 404 handlers for the Fastify user to override. Basically:

const server = fastify({
  404Handler1: () => {},
  404Handler2: () => {}
})

This is not a good dev experience, and is confusing.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When the url invalid, it cannot go to the correct /* handler. Then it fallback to defaultRoute.
The fourOhFourFallBack is actually giving the user warning in this case.

The below one should be the correct handler for 404 case.
https://github.com/fastify/fastify/blob/v3.x/lib/fourOhFour.js#L50-L59
https://github.com/fastify/fastify/blob/v3.x/lib/fourOhFour.js#L150-L151

fourOhFourFallBack should never be run.
https://github.com/fastify/fastify/blob/v3.x/lib/fourOhFour.js#L154-L171

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct. The 404 handler should handle any case where a route is not found.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the new approach is good, I will create a PR for v4.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have stepped through the new tests. Everything is working as I think it should. Without a custom 404 handler defined, the basic404 handler is invoked when a "bad url" is encountered. When a custom 404 handler is defined, it is invoked.


return { router, setNotFoundHandler, setContext, arrange404 }

Expand All @@ -58,6 +58,26 @@ function fourOhFour (options) {
})
}

function onBadUrl (path, req, res) {
const { url, method } = req
const message = `Route ${method}:${url} not found`
const body = `{"error":"Not Found","message":"${message}","statusCode":404}`

// simulate normal route logging
if (!disableRequestLogging) {
const id = genReqId(req)
const childLogger = logger.child({ reqId: id })
childLogger.info({ req }, 'incoming request')
childLogger.info({ req }, message)
}

res.writeHead(404, {
'Content-Type': 'application/json',
'Content-Length': body.length
})
res.end(body)
}

function setContext (instance, context) {
const _404Context = Object.assign({}, instance[kFourOhFourContext])
_404Context.onSend = context.onSend
Expand Down
35 changes: 35 additions & 0 deletions test/404s.test.js
Expand Up @@ -1738,6 +1738,41 @@ test('400 in case of bad url (pre find-my-way v2.2.0 was a 404)', t => {
})
})

t.test('No route registered', t => {
t.plan(3)
const fastify = Fastify()
fastify.inject({
url: '/%c0',
method: 'GET'
}, (err, response) => {
t.error(err)
t.equal(response.statusCode, 404)
t.same(JSON.parse(response.payload), {
error: 'Not Found',
message: 'Route GET:/%c0 not found',
statusCode: 404
})
})
})

t.test('Only / is registered', t => {
t.plan(3)
const fastify = Fastify({ logger: true })
fastify.get('/', () => t.fail('we should not be here'))
fastify.inject({
url: '/%c0',
method: 'GET'
}, (err, response) => {
t.error(err)
t.equal(response.statusCode, 404)
t.same(JSON.parse(response.payload), {
error: 'Not Found',
message: 'Route GET:/%c0 not found',
statusCode: 404
})
})
})

t.end()
})

Expand Down
19 changes: 19 additions & 0 deletions test/logger.test.js
Expand Up @@ -1481,6 +1481,25 @@ test('should not log incoming request and outgoing response when disabled', t =>
})
})

test('should not log incoming request and outgoing response for 404 onBadUrl when disabled', t => {
t.plan(1)
const lines = []
const dest = new stream.Writable({
write: function (chunk, enc, cb) {
lines.push(JSON.parse(chunk))
cb()
}
})
const fastify = Fastify({ disableRequestLogging: true, logger: { level: 'info', stream: dest } })

fastify.inject({
url: '/%c0',
method: 'GET'
}, (e, res) => {
t.same(lines.length, 0)
})
})

test('should pass when using unWritable props in the logger option', t => {
t.plan(1)
Fastify({
Expand Down