Compare commits

...

2 Commits

Author SHA1 Message Date
Peter White acf9b05f1f changeset 2026-11-25 08:02:00 +00:00
Peter White ff3d454d2a Prevent adaptive content redirect loops and hidden target disclosure 2026-11-25 08:02:00 +00:00
5 changed files with 370 additions and 11 deletions
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Prevent self-redirect loops and skip redirects targeting hidden adaptive content.
@@ -1,6 +1,6 @@
import { describe, expect, it, mock } from 'bun:test';
import type { RevisionPageDocument } from '@gitbook/api';
import type { RevisionPageDocument, SiteRedirectDestination } from '@gitbook/api';
import type { GitBookSiteContext } from '@/lib/context';
@@ -23,15 +23,28 @@ const page = {
describe('resolveMissingPagePath', () => {
function createRedirectContext(options: {
siteRedirect?: { source?: string; target: string; permanent?: boolean };
siteRedirect?: {
source?: string;
target: string;
permanent?: boolean;
destination?: SiteRedirectDestination;
};
spaceRedirectPageId?: string;
contextId?: string;
structure?: GitBookSiteContext['structure'];
revisionsBySpace?: Record<string, RevisionPageDocument[]>;
}) {
const getSiteRedirectBySource = mock(async ({ source }: { source: string }) =>
options.siteRedirect && source === (options.siteRedirect.source ?? '/old')
? {
data: {
target: options.siteRedirect.target,
redirect: { permanent: options.siteRedirect.permanent ?? false },
redirect: {
permanent: options.siteRedirect.permanent ?? false,
...(options.siteRedirect.destination
? { destination: options.siteRedirect.destination }
: {}),
},
},
}
: { error: { code: 404, message: 'Not found' } }
@@ -41,19 +54,35 @@ describe('resolveMissingPagePath', () => {
? { data: { id: options.spaceRedirectPageId } }
: { error: { code: 404, message: 'Not found' } }
);
const getRevision = mock(async ({ spaceId }: { spaceId: string }) =>
options.revisionsBySpace?.[spaceId]
? { data: { pages: options.revisionsBySpace[spaceId] } }
: { error: { code: 404, message: 'Not found' } }
);
const defaultSiteSpace = {
id: 'site-space-1',
space: { id: 'space-1', revision: 'revision-1' },
};
return {
organizationId: 'org-1',
site: { id: 'site-1' },
siteSpace: defaultSiteSpace,
structure: options.structure ?? {
type: 'siteSpaces',
structure: [defaultSiteSpace],
},
space: { id: 'space-1', revision: 'revision-1' },
revisionId: 'revision-1',
revision: { pages: [page] },
contextId: options.contextId,
linker: {
toPathInSpace: (path: string) => path,
toRelativePathInSite: (path: string) => path,
toLinkForContent: (url: string) => new URL(url).pathname,
},
dataFetcher: { getSiteRedirectBySource, getRevisionPageByPath },
dataFetcher: { getSiteRedirectBySource, getRevisionPageByPath, getRevision },
} as unknown as GitBookSiteContext;
}
@@ -87,6 +116,224 @@ describe('resolveMissingPagePath', () => {
});
});
it('ignores a site redirect that targets the current path', async () => {
const context = createRedirectContext({
siteRedirect: {
source: '/release-notes/restricted',
target: 'https://docs.example.com/release-notes/restricted',
},
});
expect(await resolveMissingPagePath(context, 'release-notes/restricted')).toBeUndefined();
});
it('ignores a site redirect that targets the current path with trailing slash, case, or query differences', async () => {
const context = createRedirectContext({
siteRedirect: {
source: '/release-notes/restricted',
target: 'https://docs.example.com/Release-Notes/Restricted/?tab=1#top',
},
});
expect(await resolveMissingPagePath(context, 'release-notes/restricted')).toBeUndefined();
});
it('ignores a space-relative redirect that resolves back to the current section path', async () => {
const context = {
...createRedirectContext({
siteRedirect: {
source: '/v3/getting-started',
target: 'https://docs.example.com/docs/v3/getting-started',
},
}),
linker: createLinker({
host: 'docs.example.com',
siteBasePath: '/',
spaceBasePath: '/docs/',
}),
} as unknown as GitBookSiteContext;
expect(await resolveMissingPagePath(context, 'v3/getting-started')).toBeUndefined();
});
it('ignores a site redirect targeting a hidden site space on an adaptive site', async () => {
const context = createRedirectContext({
contextId: 'adaptive-ctx',
siteRedirect: {
source: '/getting-started',
target: 'https://docs.example.com/docs/v3/getting-started',
destination: {
kind: 'site-page',
siteSpaceId: 'site-space-hidden',
pageId: 'page-v3',
},
},
});
expect(await resolveMissingPagePath(context, 'getting-started')).toBeUndefined();
});
it('ignores a site redirect targeting a hidden section on an adaptive site', async () => {
const context = createRedirectContext({
contextId: 'adaptive-ctx',
structure: {
type: 'sections',
structure: [
{
object: 'site-section',
id: 'section-visible',
siteSpaces: [
{
id: 'site-space-1',
space: { id: 'space-1', revision: 'revision-1' },
},
],
},
],
} as unknown as GitBookSiteContext['structure'],
siteRedirect: {
source: '/old-section',
target: 'https://docs.example.com/hidden-section',
destination: {
kind: 'site-section',
siteSectionId: 'section-hidden',
},
},
});
expect(await resolveMissingPagePath(context, 'old-section')).toBeUndefined();
});
it('ignores a site redirect targeting a hidden page in the current space on an adaptive site', async () => {
const context = createRedirectContext({
contextId: 'adaptive-ctx',
siteRedirect: {
source: '/release-notes/restricted.html',
target: 'https://docs.example.com/release-notes/restricted',
destination: {
kind: 'site-page',
siteSpaceId: 'site-space-1',
pageId: 'hidden-page',
},
},
});
expect(
await resolveMissingPagePath(context, 'release-notes/restricted.html')
).toBeUndefined();
});
it('checks target page visibility in another accessible space on an adaptive site', async () => {
const otherSpace = {
id: 'site-space-2',
space: { id: 'space-2', revision: 'revision-2' },
};
const structure = {
type: 'siteSpaces',
structure: [
{ id: 'site-space-1', space: { id: 'space-1', revision: 'revision-1' } },
otherSpace,
],
} as unknown as GitBookSiteContext['structure'];
const hiddenContext = createRedirectContext({
contextId: 'adaptive-ctx',
structure,
revisionsBySpace: { 'space-2': [] },
siteRedirect: {
source: '/old',
target: 'https://docs.example.com/other/secret',
destination: {
kind: 'site-page',
siteSpaceId: 'site-space-2',
pageId: 'page-secret',
},
},
});
expect(await resolveMissingPagePath(hiddenContext, 'old')).toBeUndefined();
const visibleContext = createRedirectContext({
contextId: 'adaptive-ctx',
structure,
revisionsBySpace: { 'space-2': [{ ...page, id: 'page-secret', path: 'secret' }] },
siteRedirect: {
source: '/old',
target: 'https://docs.example.com/other/secret',
destination: {
kind: 'site-page',
siteSpaceId: 'site-space-2',
pageId: 'page-secret',
},
},
});
expect(await resolveMissingPagePath(visibleContext, 'old')).toEqual({
type: 'redirect',
destination: '/other/secret',
permanent: false,
});
});
it('ignores a site redirect targeting the reassigned default variant path of the current space', async () => {
const context = {
...createRedirectContext({
contextId: 'adaptive-ctx',
siteRedirect: {
source: '/guide/missing',
target: 'https://docs.example.com/guide/v3/missing',
destination: {
kind: 'site-space',
siteSpaceId: 'site-space-v3',
},
},
structure: {
type: 'sections',
structure: [
{
object: 'site-section',
id: 'section-guide',
siteSpaces: [
{
id: 'site-space-v3',
path: 'v3',
default: true,
space: { id: 'space-v3', revision: 'revision-1' },
},
],
},
],
} as unknown as GitBookSiteContext['structure'],
}),
siteSpace: {
id: 'site-space-v3',
path: 'v3',
default: true,
space: { id: 'space-v3', revision: 'revision-1' },
},
linker: createLinker({
host: 'docs.example.com',
siteBasePath: '/',
spaceBasePath: '/guide/',
}),
} as unknown as GitBookSiteContext;
expect(await resolveMissingPagePath(context, 'missing')).toBeUndefined();
});
it('keeps a redirect whose current path contains a literal question mark', async () => {
const context = createRedirectContext({
siteRedirect: {
source: '/foo/bar%3Fbaz',
target: 'https://docs.example.com/foo/bar',
},
});
expect(await resolveMissingPagePath(context, 'foo/bar?baz')).toEqual({
type: 'redirect',
destination: '/foo/bar',
permanent: false,
});
});
it('resolves a space redirect to a page', async () => {
const context = createRedirectContext({ spaceRedirectPageId: page.id });
@@ -2,6 +2,7 @@ import { permanentRedirect, redirect } from 'next/navigation';
import {
type RevisionPageDocument,
type SiteRedirect,
SITE_REDIRECT_SOURCE_PATH_MAX_LENGTH,
SITE_REDIRECT_SOURCE_PATH_PATTERN,
} from '@gitbook/api';
@@ -10,7 +11,12 @@ import { type GitBookSiteContext, fetchSiteContextForSiteSpace } from '@/lib/con
import { getDataOrNull } from '@/lib/data';
import { type ResolvedPagePath, resolvePageId } from '@/lib/pages';
import { withLeadingSlash } from '@/lib/paths';
import { findSiteSpaceByUrl, resolveSiteSpacePagePath } from '@/lib/sites';
import {
findSiteSpaceBy,
findSiteSpaceByUrl,
getSiteStructureSections,
resolveSiteSpacePagePath,
} from '@/lib/sites';
const MAX_PAGE_URL_REDIRECTS = 5;
@@ -113,6 +119,14 @@ export async function resolveMissingPagePath(
.filter((source) => SITE_REDIRECT_SOURCE_PATH_REGEX.test(source))
);
const currentPath = linker.toPathInSpace(redirectPathname);
let currentPathWithDefaultVariant: string | null = null;
if (context.siteSpace.default && context.siteSpace.path) {
currentPathWithDefaultVariant = linker.toPathInSpace(
`/${context.siteSpace.path}${redirectPathname}`
);
}
for (const source of redirectSources) {
// We try to resolve the site redirect
const resolvedSiteRedirect =
@@ -126,6 +140,18 @@ export async function resolveMissingPagePath(
})
));
if (resolvedSiteRedirect) {
const destination = linker.toLinkForContent(resolvedSiteRedirect.target);
// Skip self-redirects (including default-variant canonical aliases) and hidden adaptive targets.
const targetsCurrentPath =
isSameRedirectPath(currentPath, destination) ||
(currentPathWithDefaultVariant !== null &&
isSameRedirectPath(currentPathWithDefaultVariant, destination));
if (
targetsCurrentPath ||
!(await isRedirectDestinationAccessible(context, resolvedSiteRedirect.redirect))
) {
break;
}
const isPublicLiveContext =
!shareKey &&
!context.changeRequest &&
@@ -134,7 +160,7 @@ export async function resolveMissingPagePath(
!context.isLoggedInVisitor;
return {
type: 'redirect',
destination: linker.toLinkForContent(resolvedSiteRedirect.target),
destination,
permanent: Boolean(
resolvedSiteRedirect.redirect?.permanent &&
!resolvedSiteRedirect.redirect.draft &&
@@ -202,6 +228,17 @@ export async function resolveSitePageFromURL(
return null;
}
export function isSameRedirectPath(currentPath: string, destination: string): boolean {
if (!destination.startsWith('/') || destination.startsWith('//')) {
return false;
}
const destinationPathname = new URL(destination, 'https://gitbook.invalid').pathname;
return (
normalizeRedirectPathname(currentPath) === normalizeRedirectPathname(destinationPathname)
);
}
/**
* Transform a pathname into a candidate source for site redirect matching.
* The pathname is already percent-encoded, so each segment is decoded before being encoded
@@ -226,6 +263,60 @@ function safeDecodeURIComponent(segment: string): string {
}
}
async function isRedirectDestinationAccessible(
context: GitBookSiteContext,
siteRedirect: SiteRedirect | null
): Promise<boolean> {
if (!context.contextId || !siteRedirect?.destination) {
return true;
}
const { destination } = siteRedirect;
switch (destination.kind) {
case 'external':
return true;
case 'site-section':
return getSiteStructureSections(context.structure, { ignoreGroups: true }).some(
(section) => section.id === destination.siteSectionId
);
case 'site-space':
return Boolean(
findSiteSpaceBy(context.structure, (entry) => entry.id === destination.siteSpaceId)
);
case 'site-page': {
const target = findSiteSpaceBy(
context.structure,
(entry) => entry.id === destination.siteSpaceId
);
if (!target) {
return false;
}
if (destination.siteSpaceId === context.siteSpace.id) {
return Boolean(resolvePageId(context.revision.pages, destination.pageId));
}
const targetRevision = await getDataOrNull(
context.dataFetcher.getRevision({
spaceId: target.siteSpace.space.id,
revisionId: target.siteSpace.space.revision,
})
);
if (!targetRevision) {
return false;
}
return Boolean(resolvePageId(targetRevision.pages, destination.pageId));
}
}
}
function normalizeRedirectPathname(pathname: string): string {
const normalized = pathname
.split('/')
.filter(Boolean)
.map((segment) => safeDecodeURIComponent(segment).toLowerCase())
.join('/');
return `/${normalized}`;
}
/**
* Get the page path from the params.
*/
@@ -94,6 +94,17 @@ describe('servePageMarkdown', () => {
expect(response.headers.get('Location')).toBe('/docs/new-page.md');
});
it('returns not-found markdown instead of looping when a site redirect targets the same markdown path', async () => {
const context = createContext({
siteRedirect: { target: 'https://docs.example.com/docs/old-page.md', permanent: false },
});
const response = await servePageMarkdown(context, 'old-page');
expect(response.status).toBe(200);
expect(await response.text()).toContain('# Page Not Found');
});
it('redirects to the markdown version of a space redirect target', async () => {
const context = createContext({ spaceRedirectPageId: page.id });
+10 -5
View File
@@ -1,6 +1,6 @@
import type { RevisionPageDocument, RevisionPageGroup } from '@gitbook/api';
import { resolveMissingPagePath } from '@/components/SitePage/fetch';
import { isSameRedirectPath, resolveMissingPagePath } from '@/components/SitePage/fetch';
import { isAIEnabled } from '@/components/utils/isAIChatEnabled';
import { renderPageAgentInstructions, renderQueryingDocumentation } from '@/lib/ask-prompt';
import type { GitBookSiteContext } from '@/lib/context';
@@ -38,10 +38,15 @@ export async function servePageMarkdown(baseContext: GitBookSiteContext, pagePat
if (!pageLookup) {
const fallback = await resolveMissingPagePath(baseContext, pagePath);
if (fallback?.type === 'redirect') {
return markdownRedirect(
toMarkdownDestination(fallback.destination),
fallback.permanent
);
const destination = toMarkdownDestination(fallback.destination);
if (
!isSameRedirectPath(
context.linker.toPathForPagePath({ path: pagePath }),
destination
)
) {
return markdownRedirect(destination, fallback.permanent);
}
}
if (fallback?.type === 'page') {
return markdownRedirect(