fix: clamp payload length in MMKVParser to prevent overflow

- Updated the MMKVParser to ensure the calculated length does not exceed the DataView's byte length.
- Added tests to verify behavior at the payload boundary, including cases for oversized payloads and exact matches.
This commit is contained in:
鲁树人 committed 2026-10-27 09:01:42 +09:00
1 parent 10e857a903
commit 75d786c747
2 files changed
+56 -1

No files matched your search

+1 -1
View File
@@ -7,7 +7,7 @@ export class MMKVParser {
constructor(private view: DataView<ArrayBuffer>) {
const payloadLength = view.getUint32(0, true);
this.length = 4 + payloadLength;
this.length = Math.min(4 + payloadLength, view.byteLength);
// skip unused str
this.readInt();
+55
View File
@@ -26,3 +26,58 @@ test('able to handle empty value', () => {
expect(parser.readKey()).toEqual('1');
expect(parser.readStringValue()).toEqual('2');
});
describe('eof payload boundary', () => {
// Small string records: "a" -> "one" and "b" -> "two".
const firstRecord = Buffer.from([0x01, 0x61, 0x04, 0x03, 0x6f, 0x6e, 0x65]);
const secondRecord = Buffer.from([0x01, 0x62, 0x04, 0x03, 0x74, 0x77, 0x6f]);
const payload = Buffer.concat([Buffer.from([0x7f]), firstRecord, secondRecord]);
const allEntries = [
['a', 'one'],
['b', 'two'],
];
const makeView = (payloadLength: number) => {
const header = Buffer.alloc(4);
header.writeUInt32LE(payloadLength);
return makeViewFromBuffer(Buffer.concat([header, payload]));
};
const readEntries = (parser: MMKVParser) => {
const entries: [string, string | null][] = [];
while (!parser.eof) {
entries.push([parser.readKey(), parser.readStringValue()]);
}
return entries;
};
test.each([payload.byteLength + 4, 0xffffffff])('clamps oversized payload length %i to the view', (payloadLength) => {
const parser = new MMKVParser(makeView(payloadLength));
expect(readEntries(parser)).toEqual(allEntries);
expect(parser.eof).toBe(true);
});
test('reads all records when the payload length is exact', () => {
const parser = new MMKVParser(makeView(payload.byteLength));
expect(readEntries(parser)).toEqual(allEntries);
expect(parser.eof).toBe(true);
});
test('stops at the declared payload boundary with another valid record remaining', () => {
const parser = new MMKVParser(makeView(1 + firstRecord.byteLength));
expect(readEntries(parser)).toEqual([allEntries[0]]);
expect(parser.eof).toBe(true);
});
test('clamps to the DataView length with another valid record outside the view', () => {
const fullView = makeView(payload.byteLength + 4);
const view = new DataView(fullView.buffer, 0, 4 + 1 + firstRecord.byteLength);
const parser = new MMKVParser(view);
expect(readEntries(parser)).toEqual([allEntries[0]]);
expect(parser.eof).toBe(true);
});
});