From c7ee3e2e17d5332723e3c2fe1a6d89a2e5a03352 Mon Sep 17 00:00:00 2001 From: Peter White <1788320+peterwhite@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:58:55 +0100 Subject: [PATCH] Harden visitor claim and rison parsing against reserved keys (#4872) --- .changeset/harden-visitor-claim-parsing.md | 5 +++ packages/gitbook/src/app/utils.ts | 4 +- packages/gitbook/src/lib/customization.ts | 6 +-- packages/gitbook/src/lib/data/lookup.ts | 2 +- packages/gitbook/src/lib/rison.test.ts | 27 ++++++++++++ packages/gitbook/src/lib/rison.ts | 48 +++++++++++++++++++++ packages/gitbook/src/lib/visitors.test.ts | 49 ++++++++++++++++++++++ packages/gitbook/src/lib/visitors.ts | 48 +++++++++++++++++---- packages/gitbook/src/middleware.test.ts | 35 ++++++++++++++++ packages/gitbook/src/middleware.ts | 19 ++++++--- packages/gitbook/src/routes/icon.tsx | 2 +- 11 files changed, 226 insertions(+), 19 deletions(-) create mode 100644 .changeset/harden-visitor-claim-parsing.md create mode 100644 packages/gitbook/src/lib/rison.test.ts create mode 100644 packages/gitbook/src/lib/rison.ts diff --git a/.changeset/harden-visitor-claim-parsing.md b/.changeset/harden-visitor-claim-parsing.md new file mode 100644 index 000000000..6fc778892 --- /dev/null +++ b/.changeset/harden-visitor-claim-parsing.md @@ -0,0 +1,5 @@ +--- +"gitbook": patch +--- + +Reject reserved prototype keys when parsing visitor claims and Rison payloads. diff --git a/packages/gitbook/src/app/utils.ts b/packages/gitbook/src/app/utils.ts index 2655e28ba..bb48bd8be 100644 --- a/packages/gitbook/src/app/utils.ts +++ b/packages/gitbook/src/app/utils.ts @@ -1,13 +1,13 @@ import { jwtDecode } from 'jwt-decode'; import { forbidden, notFound } from 'next/navigation'; import { cache } from 'react'; -import rison from 'rison'; import type { SiteAPIToken } from '@gitbook/api'; import { getVisitorAuthClaims, getVisitorAuthClaimsFromToken } from '@/lib/adaptive'; import { type SiteURLData, fetchSiteContextByURLLookup, getBaseContext } from '@/lib/context'; import { getDynamicCustomizationSettings } from '@/lib/customization'; +import { decodeRison } from '@/lib/rison'; export type RouteParamMode = 'url-host' | 'url'; @@ -143,7 +143,7 @@ function getModeFromParams(mode: string): RouteParamMode { export function getSiteURLDataFromParams(params: RouteLayoutParams): SiteURLData { try { const decoded = decodeURIComponent(params.siteData); - return rison.decode(decoded); + return decodeRison(decoded); } catch (error) { console.error( `Returning 404 after failing to decode site data ${params.siteData}: ${error}` diff --git a/packages/gitbook/src/lib/customization.ts b/packages/gitbook/src/lib/customization.ts index 34b834f39..8ec4ccd5c 100644 --- a/packages/gitbook/src/lib/customization.ts +++ b/packages/gitbook/src/lib/customization.ts @@ -1,9 +1,9 @@ import { headers } from 'next/headers'; -import rison from 'rison'; import type { SiteCustomizationSettings } from '@gitbook/api'; import { MiddlewareHeaders } from '@/lib/middleware'; +import { decodeRisonObject } from '@/lib/rison'; /** * Selects the customization settings from the x-gitbook-customization header if present, @@ -19,7 +19,7 @@ export async function getDynamicCustomizationSettings( try { // We need to decode it first as it is URL encoded, then decode the Rison object const unencoded = decodeURIComponent(extend); - const parsedSettings = rison.decode_object(unencoded); + const parsedSettings = decodeRisonObject(unencoded); return parsedSettings; } catch (_error) {} @@ -33,7 +33,7 @@ export async function getDynamicCustomizationSettings( */ export function validateSerializedCustomization(raw: string): boolean { try { - rison.decode_object(raw); + decodeRisonObject(raw); return true; } catch { return false; diff --git a/packages/gitbook/src/lib/data/lookup.ts b/packages/gitbook/src/lib/data/lookup.ts index 4b8a0a7bc..8cbe80c94 100644 --- a/packages/gitbook/src/lib/data/lookup.ts +++ b/packages/gitbook/src/lib/data/lookup.ts @@ -64,7 +64,7 @@ export async function lookupPublishedContentByUrl( data: { data }, } = callResult; - if (!('redirect' in data)) { + if (!Object.hasOwn(data, 'redirect') || !('redirect' in data)) { return { data }; } diff --git a/packages/gitbook/src/lib/rison.test.ts b/packages/gitbook/src/lib/rison.test.ts new file mode 100644 index 000000000..0ef242b35 --- /dev/null +++ b/packages/gitbook/src/lib/rison.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from 'bun:test'; + +import { validateSerializedCustomization } from './customization'; +import { decodeRison, decodeRisonObject } from './rison'; + +describe('safe rison decoding', () => { + it('decodes legitimate rison payloads', () => { + expect(decodeRison>('(site:site_1,flags:!(a,b))')).toStrictEqual({ + site: 'site_1', + flags: ['a', 'b'], + }); + expect(decodeRisonObject>('styling:(theme:clean)')).toStrictEqual({ + styling: { theme: 'clean' }, + }); + expect(validateSerializedCustomization('styling:(theme:clean)')).toBe(true); + }); + + it('rejects payloads that alter object prototypes or set reserved keys', () => { + expect(() => decodeRison('(__proto__:(polluted:!t))')).toThrow(); + expect(() => decodeRison('(__proto__:!n)')).toThrow(); + expect(() => decodeRison('(nested:(constructor:(prototype:(x:1))))')).toThrow(); + expect(() => decodeRison('(items:!((prototype:(x:1))))')).toThrow(); + expect(validateSerializedCustomization('__proto__:(ai:(mode:search))')).toBe(false); + expect(validateSerializedCustomization('constructor:(x:1)')).toBe(false); + expect(Object.hasOwn(Object.prototype, 'polluted')).toBe(false); + }); +}); diff --git a/packages/gitbook/src/lib/rison.ts b/packages/gitbook/src/lib/rison.ts new file mode 100644 index 000000000..b9d5d4358 --- /dev/null +++ b/packages/gitbook/src/lib/rison.ts @@ -0,0 +1,48 @@ +import rison from 'rison'; + +const RESERVED_KEYS = new Set(['__proto__', 'constructor', 'prototype']); + +/** + * Reject decoded objects whose prototype was altered (via `__proto__`) or that define reserved keys. + */ +function assertSafeRisonValue(value: unknown): void { + if (typeof value !== 'object' || value === null) { + return; + } + + if (Array.isArray(value)) { + for (const item of value) { + assertSafeRisonValue(item); + } + return; + } + + if (Object.getPrototypeOf(value) !== Object.prototype) { + throw new Error('Unsafe prototype in decoded rison value'); + } + + for (const [key, entry] of Object.entries(value)) { + if (RESERVED_KEYS.has(key)) { + throw new Error(`Reserved key "${key}" in decoded rison value`); + } + assertSafeRisonValue(entry); + } +} + +/** + * Decode a Rison string and reject payloads that tamper with prototypes or reserved keys. + */ +export function decodeRison(input: string): T { + const decoded = rison.decode(input); + assertSafeRisonValue(decoded); + return decoded; +} + +/** + * Decode an O-Rison object string and reject payloads that tamper with prototypes or reserved keys. + */ +export function decodeRisonObject>(input: string): T { + const decoded = rison.decode_object(input); + assertSafeRisonValue(decoded); + return decoded; +} diff --git a/packages/gitbook/src/lib/visitors.test.ts b/packages/gitbook/src/lib/visitors.test.ts index ead0d7ea1..36b6cb7dd 100644 --- a/packages/gitbook/src/lib/visitors.test.ts +++ b/packages/gitbook/src/lib/visitors.test.ts @@ -567,6 +567,55 @@ describe('getVisitorUnsignedClaims', () => { }, }); }); + + it('should ignore query params with reserved prototype keys without mutating Object.prototype', () => { + try { + const url = new URL( + 'https://example.com/?visitor.__proto__.polluted=1&visitor.constructor.prototype.polluted=1&visitor.a.__proto__.polluted=1&visitor.a.prototype.polluted=1&visitor.user.plan=pro' + ); + + const claims = getVisitorUnsignedClaims({ cookies: [], url }); + + expect(Object.hasOwn(Object.prototype, 'polluted')).toBe(false); + expect(Object.getPrototypeOf(claims.all)).toBe(Object.prototype); + expect(Object.getPrototypeOf(claims.fromVisitorParams)).toBe(Object.prototype); + expect(claims.all).toStrictEqual({ user: { plan: 'pro' } }); + expect(claims.fromVisitorParams).toStrictEqual({ user: { plan: 'pro' } }); + } finally { + delete (Object.prototype as Record).polluted; + } + }); + + it('should strip reserved keys from public cookie JSON and query JSON values', () => { + try { + const cookies = [ + { + name: 'gitbook-visitor-public', + value: '{"__proto__":{"polluted":true},"constructor":{"prototype":{"polluted":true}},"role":"admin","nested":{"prototype":{"x":1},"items":[{"__proto__":{"polluted":true},"id":1}]}}', + }, + ]; + const url = new URL( + `https://example.com/?visitor.profile=${encodeURIComponent('{"__proto__":{"polluted":true},"constructor":{"x":1},"tier":"pro"}')}` + ); + + const claims = getVisitorUnsignedClaims({ cookies, url }); + + expect(Object.hasOwn(Object.prototype, 'polluted')).toBe(false); + expect(Object.getPrototypeOf(claims.all)).toBe(Object.prototype); + expect(Object.getPrototypeOf(claims.all.profile)).toBe(Object.prototype); + expect('polluted' in claims.all).toBe(false); + expect(claims.all).toStrictEqual({ + role: 'admin', + nested: { items: [{ id: 1 }] }, + profile: { tier: 'pro' }, + }); + expect(claims.fromVisitorParams).toStrictEqual({ + profile: { tier: 'pro' }, + }); + } finally { + delete (Object.prototype as Record).polluted; + } + }); }); describe('normalizeVisitorURL', () => { diff --git a/packages/gitbook/src/lib/visitors.ts b/packages/gitbook/src/lib/visitors.ts index 2e58350d5..5d0230a3a 100644 --- a/packages/gitbook/src/lib/visitors.ts +++ b/packages/gitbook/src/lib/visitors.ts @@ -316,6 +316,8 @@ export function getVisitorToken({ } } +const RESERVED_CLAIM_KEYS = new Set(['__proto__', 'constructor', 'prototype']); + /** * Get the visitor unsigned/public claims for the request. They can either be in `visitor.` query * parameters or stored in special `gitbook-visitor-public-*` cookies. @@ -340,9 +342,14 @@ export function getVisitorUnsignedClaims(args: { for (const cookie of cookies) { if (cookie.name.startsWith(VISITOR_UNSIGNED_CLAIMS_PREFIX)) { try { - const parsed = JSON.parse(cookie.value); - if (typeof parsed === 'object' && parsed !== null) { - Object.assign(claims, parsed); + const parsed: unknown = JSON.parse(cookie.value); + if (isClaimPrimitiveObject(parsed)) { + for (const [key, value] of Object.entries(parsed)) { + if (isReservedClaimKey(key)) { + continue; + } + claims[key] = sanitizeClaimValue(value); + } } } catch { console.warn(`Invalid JSON in unsigned claim cookie "${cookie.name}"`); @@ -372,6 +379,10 @@ function setVisitorClaimByPath( value: ClaimPrimitive ): void { const keys = keyPath.split('.'); + if (keys.some(isReservedClaimKey)) { + return; + } + let current = claims; for (let index = 0; index < keys.length; index++) { @@ -380,7 +391,7 @@ function setVisitorClaimByPath( if (index === keys.length - 1) { current[key] = value; } else { - if (!(key in current) || !isClaimPrimitiveObject(current[key])) { + if (!Object.hasOwn(current, key) || !isClaimPrimitiveObject(current[key])) { current[key] = {}; } @@ -389,8 +400,31 @@ function setVisitorClaimByPath( } } +function isReservedClaimKey(key: string): boolean { + return RESERVED_CLAIM_KEYS.has(key); +} + function isClaimPrimitiveObject(value: unknown): value is Record { - return typeof value === 'object' && value !== null; + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function sanitizeClaimValue(value: unknown): ClaimPrimitive { + if (Array.isArray(value)) { + return value.map((item) => sanitizeClaimValue(item)); + } + + if (isClaimPrimitiveObject(value)) { + const sanitized: Record = {}; + for (const [key, entry] of Object.entries(value)) { + if (isReservedClaimKey(key)) { + continue; + } + sanitized[key] = sanitizeClaimValue(entry); + } + return sanitized; + } + + return value as ClaimPrimitive; } /** @@ -419,9 +453,9 @@ function parseVisitorQueryParamValue(value: string): ClaimPrimitive { } try { - const parsed = JSON.parse(value); + const parsed: unknown = JSON.parse(value); if (typeof parsed === 'object' && parsed !== null) { - return parsed; + return sanitizeClaimValue(parsed); } } catch {} diff --git a/packages/gitbook/src/middleware.test.ts b/packages/gitbook/src/middleware.test.ts index 2e5ed2dc2..bcd53adb7 100644 --- a/packages/gitbook/src/middleware.test.ts +++ b/packages/gitbook/src/middleware.test.ts @@ -336,3 +336,38 @@ describe('Trailing-slash normalization middleware', () => { expect(response.headers.get('x-robots-tag')).toBe('noindex, nofollow'); }); }); + +describe('Prototype safety in middleware', () => { + it('does not crash when a page pathname matches an Object.prototype key', async () => { + const url = new URL('https://docs.example.com/toString'); + fetchSpy.mockResolvedValueOnce( + Response.json({ + site: 'site', + siteSpace: 'variant', + space: 'space', + organization: 'org', + apiToken: 'content-token', + pathname: 'toString', + basePath: '', + siteBasePath: '', + canonicalUrl: url.toString(), + complete: true, + }) + ); + + const request = new NextRequest(url, { headers: { 'x-forwarded-host': url.host } }); + const cookiesSpy = spyOn(nextHeaders, 'cookies').mockResolvedValue( + RequestCookiesAdapter.seal(request.cookies) + ); + let response; + try { + response = await middleware(request); + } finally { + cookiesSpy.mockRestore(); + } + + const rewrite = response.headers.get('x-middleware-rewrite'); + expect(rewrite).not.toBeNull(); + expect(new URL(rewrite!).pathname).toEndWith('/toString'); + }); +}); diff --git a/packages/gitbook/src/middleware.ts b/packages/gitbook/src/middleware.ts index 7c3e96a7f..91f96a3d2 100644 --- a/packages/gitbook/src/middleware.ts +++ b/packages/gitbook/src/middleware.ts @@ -10,6 +10,7 @@ import { ContentType, CustomizationDefaultThemeMode, CustomizationThemeMode, + type PublishedContentRedirect, SiteInsightsDisplayContext, type SiteInsightsEventLocation, SiteInsightsLLMSVariant, @@ -420,7 +421,7 @@ async function serveSiteRequest(requestURL: URL, request: NextRequest, match: UR // // Handle redirects // - if ('redirect' in siteURLData) { + if (isPublishedContentRedirect(siteURLData)) { /** * When it is an unauthenticated request to an OAuth protected resources (like MCP) in an authenticated sites * we handle it through an OAuth Protected Resource flow (RFC 9728). @@ -1155,7 +1156,9 @@ function encodePathInSiteContent( }; } - pathname = PATH_ALIASES[pathname] || pathname; + if (Object.hasOwn(PATH_ALIASES, pathname)) { + pathname = PATH_ALIASES[pathname]!; + } switch (pathname) { case '~gitbook/embed': case '~gitbook/embed/assistant': @@ -1377,19 +1380,25 @@ function acceptsMarkdown(request: Request): boolean { return htmlIndex === -1 || markdownIndex < htmlIndex; } +function isPublishedContentRedirect( + data: PublishedSiteContent | PublishedContentRedirect +): data is PublishedContentRedirect { + return Object.hasOwn(data, 'redirect'); +} + /** * The revision, change request or site revision a URL previews: at most one of them. */ function getPreviewedContent( content: PublishedSiteContent ): Pick { - if ('revision' in content) { + if (Object.hasOwn(content, 'revision') && 'revision' in content) { return { revision: content.revision }; } - if ('changeRequest' in content) { + if (Object.hasOwn(content, 'changeRequest') && 'changeRequest' in content) { return { changeRequest: content.changeRequest }; } - if ('siteRevision' in content) { + if (Object.hasOwn(content, 'siteRevision') && 'siteRevision' in content) { return { siteRevision: content.siteRevision }; } return {}; diff --git a/packages/gitbook/src/routes/icon.tsx b/packages/gitbook/src/routes/icon.tsx index 79757d40a..e434bfbd0 100644 --- a/packages/gitbook/src/routes/icon.tsx +++ b/packages/gitbook/src/routes/icon.tsx @@ -169,7 +169,7 @@ function getOptions(inputUrl: string): { const themeParam = url.searchParams.get('theme') ?? 'light'; const borderParam = url.searchParams.get('border') !== 'false'; - if (!SIZES[sizeParam] || !['light', 'dark'].includes(themeParam)) { + if (!Object.hasOwn(SIZES, sizeParam) || !['light', 'dark'].includes(themeParam)) { notFound(); }