Skip to content

Commit 5ca5da0

Browse files
conico974Nicolas Dorseuil
andauthored
Fix handling of bad requests to prevent unnecessary 500 errors (#3432)
Co-authored-by: Nicolas Dorseuil <nicolas@gitbook.io>
1 parent ebe6eb3 commit 5ca5da0

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

packages/gitbook/src/components/SitePage/fetch.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,8 @@ async function resolvePage(context: GitBookSiteContext, params: PagePathParams |
5252
}
5353

5454
// We don't test path that are too long as GitBook doesn't support them and will return a 404 anyway.
55-
if (rawPathname.length <= 512) {
55+
// API has a limit of less than 512 characters for the source path, so we use the same limit here.
56+
if (rawPathname.length < 512) {
5657
// Duplicated the regex pattern from SiteRedirectSourcePath API type.
5758
const SITE_REDIRECT_SOURCE_PATH_REGEX =
5859
/^\/(?:[A-Za-z0-9\-._~]|%[0-9A-Fa-f]{2})+(?:\/(?:[A-Za-z0-9\-._~]|%[0-9A-Fa-f]{2})+)*$/;

packages/gitbook/src/middleware.ts

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,24 @@ async function validateServerActionRequest(request: NextRequest) {
8181
}
8282
}
8383

84+
/**
85+
* Filter malicious requests.
86+
* @param requestURL The URL of the request to filter.
87+
* @returns True if the request is malicious, false otherwise.
88+
*/
89+
function shouldFilterMaliciousRequests(requestURL: URL): boolean {
90+
// We want to filter hostnames that contains a port here as this is likely a malicious request.
91+
if (requestURL.host.includes(':')) {
92+
return true;
93+
}
94+
// These requests will be rejected by the API anyway, we might as well do it right away.
95+
if (requestURL.pathname.endsWith(';.jsp')) {
96+
return true;
97+
}
98+
99+
return false;
100+
}
101+
84102
/**
85103
* Handle request that are targetting the site routes group.
86104
*/
@@ -108,7 +126,7 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
108126
}
109127

110128
// We want to filter hostnames that contains a port here as this is likely a malicious request.
111-
if (siteRequestURL.host.includes(':')) {
129+
if (shouldFilterMaliciousRequests(siteRequestURL)) {
112130
return new Response('Invalid request', {
113131
status: 400,
114132
headers: { 'content-type': 'text/plain' },

0 commit comments

Comments
 (0)