Fix handling of bad requests to prevent unnecessary 500 errors (#3432)

Co-authored-by: Nicolas Dorseuil <nicolas@gitbook.io>
This commit is contained in:
conico974
2025-07-04 17:06:37 +02:00
committed by GitHub
parent ebe6eb3b39
commit 5ca5da0f21
2 changed files with 21 additions and 2 deletions
@@ -52,7 +52,8 @@ async function resolvePage(context: GitBookSiteContext, params: PagePathParams |
}
// We don't test path that are too long as GitBook doesn't support them and will return a 404 anyway.
if (rawPathname.length <= 512) {
// API has a limit of less than 512 characters for the source path, so we use the same limit here.
if (rawPathname.length < 512) {
// Duplicated the regex pattern from SiteRedirectSourcePath API type.
const SITE_REDIRECT_SOURCE_PATH_REGEX =
/^\/(?:[A-Za-z0-9\-._~]|%[0-9A-Fa-f]{2})+(?:\/(?:[A-Za-z0-9\-._~]|%[0-9A-Fa-f]{2})+)*$/;
+19 -1
View File
@@ -81,6 +81,24 @@ async function validateServerActionRequest(request: NextRequest) {
}
}
/**
* Filter malicious requests.
* @param requestURL The URL of the request to filter.
* @returns True if the request is malicious, false otherwise.
*/
function shouldFilterMaliciousRequests(requestURL: URL): boolean {
// We want to filter hostnames that contains a port here as this is likely a malicious request.
if (requestURL.host.includes(':')) {
return true;
}
// These requests will be rejected by the API anyway, we might as well do it right away.
if (requestURL.pathname.endsWith(';.jsp')) {
return true;
}
return false;
}
/**
* Handle request that are targetting the site routes group.
*/
@@ -108,7 +126,7 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
}
// We want to filter hostnames that contains a port here as this is likely a malicious request.
if (siteRequestURL.host.includes(':')) {
if (shouldFilterMaliciousRequests(siteRequestURL)) {
return new Response('Invalid request', {
status: 400,
headers: { 'content-type': 'text/plain' },