Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cap parsed numbers at Number.MAX_SAFE_INTEGER #458

Merged
merged 1 commit into from
May 24, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/core/parser/BaseParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,12 @@ class BaseParser {
throw new NumberParsingError(this.bytes.position(), value);
}

if (numberValue > Number.MAX_SAFE_INTEGER) {
const msg = `Parsed number that is too large for some PDF readers: ${value}, using Number.MAX_SAFE_INTEGER instead.`;
console.warn(msg);
return Number.MAX_SAFE_INTEGER;
}

return numberValue;
}

Expand Down
41 changes: 41 additions & 0 deletions tests/core/parser/PDFObjectParser.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
PDFRef,
PDFString,
typedArrayFor,
numberToString,
} from 'src/index';

const parse = (value: string | Uint8Array) => {
Expand All @@ -30,6 +31,28 @@ const expectParseStr = (value: string | Uint8Array) =>
expect(String(parse(value)));

describe(`PDFObjectParser`, () => {
const origConsoleWarn = console.warn;

beforeAll(() => {
console.warn = jest.fn((...args) => {
if (
!args[0].includes(
'Parsed number that is too large for some PDF readers:',
)
) {
origConsoleWarn(...args);
}
});
});

beforeEach(() => {
jest.clearAllMocks();
});

afterAll(() => {
console.warn = origConsoleWarn;
});

it(`throws an error when given empty input`, () => {
expect(() => parse('')).toThrow();
});
Expand Down Expand Up @@ -130,6 +153,24 @@ describe(`PDFObjectParser`, () => {
expect(parser.parseObject().toString()).toBe('-2');
expect(parser.parseObject().toString()).toBe('-0.1');
});

it(`caps numbers at Number.MAX_SAFE_INTEGER`, () => {
expectParseStr(numberToString(Number.MAX_SAFE_INTEGER - 1)).toBe(
'9007199254740990',
);
expectParseStr(numberToString(Number.MAX_SAFE_INTEGER)).toBe(
'9007199254740991',
);
expectParseStr(numberToString(Number.MAX_SAFE_INTEGER + 1)).toBe(
'9007199254740991',
);
expectParseStr('340282346638528900000000000000000000000').toBe(
'9007199254740991',
);
expectParseStr('340282346638528859811704183484516925440').toBe(
'9007199254740991',
);
});
});

describe(`when parsing literal strings`, () => {
Expand Down