Harden visitor claim and rison parsing against reserved keys (#4872)

This commit is contained in:
Peter White
2026-12-02 10:58:55 +01:00
committed by GitHub
parent 87a4f327c6
commit c7ee3e2e17
11 changed files with 226 additions and 19 deletions
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Reject reserved prototype keys when parsing visitor claims and Rison payloads.
+2 -2
View File
@@ -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<SiteURLData>(decoded);
} catch (error) {
console.error(
`Returning 404 after failing to decode site data ${params.siteData}: ${error}`
+3 -3
View File
@@ -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<SiteCustomizationSettings>(unencoded);
const parsedSettings = decodeRisonObject<SiteCustomizationSettings>(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;
+1 -1
View File
@@ -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 };
}
+27
View File
@@ -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<Record<string, unknown>>('(site:site_1,flags:!(a,b))')).toStrictEqual({
site: 'site_1',
flags: ['a', 'b'],
});
expect(decodeRisonObject<Record<string, unknown>>('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);
});
});
+48
View File
@@ -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<T = unknown>(input: string): T {
const decoded = rison.decode<T>(input);
assertSafeRisonValue(decoded);
return decoded;
}
/**
* Decode an O-Rison object string and reject payloads that tamper with prototypes or reserved keys.
*/
export function decodeRisonObject<T = Record<string, unknown>>(input: string): T {
const decoded = rison.decode_object<T>(input);
assertSafeRisonValue(decoded);
return decoded;
}
+49
View File
@@ -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<string, unknown>).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<string, unknown>).polluted;
}
});
});
describe('normalizeVisitorURL', () => {
+41 -7
View File
@@ -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<string, ClaimPrimitive> {
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<string, ClaimPrimitive> = {};
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 {}
+35
View File
@@ -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');
});
});
+14 -5
View File
@@ -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<SiteURLData, 'revision' | 'changeRequest' | 'siteRevision'> {
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 {};
+1 -1
View File
@@ -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();
}