Skip to content

Commit 3677646

Browse files
authored
fix: use @fastify/error for forbidden path errors (#624)
1 parent d4e7392 commit 3677646

4 files changed

Lines changed: 14 additions & 7 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -575,6 +575,7 @@ The following errors may be thrown by the plugin:
575575
| FST_STATIC_INVALID_OPTION_VALUE | Option provided with unsupported type. |
576576
| FST_STATIC_MULTIROOT_LIST_CONFLICT | Multi `root` and `list` option cannot be used together. |
577577
| FST_STATIC_INVALID_REDIRECT_URL | Cannot redirect to the provided URL. |
578+
| FST_STATIC_FORBIDDEN_PATH | The request path is not allowed. |
578579
579580
### Payload `stream.path`
580581

‎index.js‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@ const errors = require('./lib/errors')
1616
const {
1717
FST_STATIC_INVALID_OPTION,
1818
FST_STATIC_INVALID_OPTION_VALUE,
19-
FST_STATIC_INVALID_REDIRECT_URL
19+
FST_STATIC_INVALID_REDIRECT_URL,
20+
FST_STATIC_FORBIDDEN_PATH
2021
} = errors
2122

2223
const endForwardSlashRegex = /\/$/u
@@ -679,13 +680,10 @@ function getContentType (path) {
679680
}
680681

681682
/**
682-
* @returns {Error & { status?: number, statusCode?: number }}
683+
* @returns {Error & { code: string, statusCode: number }}
683684
*/
684685
function forbiddenPathError () {
685-
const error = new Error('Forbidden')
686-
error.status = 403
687-
error.statusCode = 403
688-
return error
686+
return new FST_STATIC_FORBIDDEN_PATH()
689687
}
690688

691689
/**

‎lib/errors.js‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,10 @@ module.exports.FST_STATIC_INVALID_REDIRECT_URL = createError(
2828
'Invalid redirect URL: "%s"',
2929
400
3030
)
31+
32+
// Error for request paths that the plugin refuses to serve
33+
module.exports.FST_STATIC_FORBIDDEN_PATH = createError(
34+
'FST_STATIC_FORBIDDEN_PATH',
35+
'Forbidden',
36+
403
37+
)

‎test/static.test.js‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1098,10 +1098,11 @@ test('allowedPath option - pathname is normalized before filtering', async (t) =
10981098
})
10991099

11001100
await t.test('//foobar.html forbidden (non-canonical path)', async (t) => {
1101-
t.plan(1 + GENERIC_ERROR_RESPONSE_CHECK_COUNT)
1101+
t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT)
11021102

11031103
const response = await rawRequest(address, '//foobar.html')
11041104
t.assert.deepStrictEqual(response.statusCode, 403)
1105+
t.assert.deepStrictEqual(JSON.parse(response.body).code, 'FST_STATIC_FORBIDDEN_PATH')
11051106
genericErrorResponseChecks(t, response)
11061107
})
11071108

0 commit comments

Comments
 (0)