diff --git a/bun.lock b/bun.lock index 8247655..d26170f 100644 --- a/bun.lock +++ b/bun.lock @@ -30,6 +30,9 @@ "@httptoolkit/dbus-native": "0.1.5", "zod": "4.4.3", }, + "devDependencies": { + "fast-check": "^4.11.0", + }, }, }, "packages": { @@ -119,6 +122,8 @@ "event-stream": ["event-stream@4.0.1", "", { "dependencies": { "duplexer": "^0.1.1", "from": "^0.1.7", "map-stream": "0.0.7", "pause-stream": "^0.0.11", "split": "^1.0.1", "stream-combiner": "^0.2.2", "through": "^2.3.8" } }, "sha512-qACXdu/9VHPBzcyhdOWR5/IahhGMf0roTeZJfzz077GwylcDd90yOHLouhmv7GJ5XzPi6ekaQWd8AvPP2nOvpA=="], + "fast-check": ["fast-check@4.11.0", "", { "dependencies": { "pure-rand": "^8.0.0" } }, "sha512-V4Uc238rhQOdQlc+Gz7JG6SGBtrWnWL8d/6RyiBeCMcNKMhF6DZ0KkAVHJSyNV5r4lA0PmIpZ6iRpTVoz4qjoA=="], + "fast-xml-builder": ["fast-xml-builder@1.3.1", "", { "dependencies": { "path-expression-matcher": "^1.6.2", "xml-naming": "^0.3.0" } }, "sha512-pIM/1n3ntFXKYrUZwW7QCK0gAW7XY+wzj1YMIV3tLDvPj/V+zTGJK5e3/4WJfwj0qWw2ElNXiTixda/R+3YSug=="], "fast-xml-parser": ["fast-xml-parser@5.11.0", "", { "dependencies": { "@nodable/entities": "^3.0.0", "fast-xml-builder": "^1.2.0", "is-unsafe": "^2.0.0", "path-expression-matcher": "^1.6.2", "strnum": "^2.4.2", "xml-naming": "^0.3.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-9IGxMqvqLOnqP+Egi1nqDHKv5k8aZ7r9n558enxcucmyVGEBNPAU+MOg/8jPIS7rO7sSq4gFm1/nHtiaubMruw=="], @@ -137,6 +142,8 @@ "pause-stream": ["pause-stream@0.0.11", "", { "dependencies": { "through": "~2.3" } }, "sha512-e3FBlXLmN/D1S+zHzanP4E/4Z60oFAa3O051qt1pxa7DEJWKAyil6upYVXCWadEnuoqa4Pkc9oUx9zsxYeRv8A=="], + "pure-rand": ["pure-rand@8.4.2", "", {}, "sha512-vvuOGgcuPJAirlHvuQw1TrOiw7ptaIXXmIbNuiNOY6lNGJJH49PQ1Kj4nd783nPdQhQdicgOjVI2yI/9BD6/Ng=="], + "safe-buffer": ["safe-buffer@5.2.1", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="], "split": ["split@1.0.1", "", { "dependencies": { "through": "2" } }, "sha512-mTyOoPbrivtXnwnIxZRFYRrPNtEFKlpB2fvjSnCQUiAA6qAZzqwna5envK4uk6OIeP17CsdF3rSBGYVBsU0Tkg=="], diff --git a/control/package.json b/control/package.json index d9d56bf..a98ebee 100644 --- a/control/package.json +++ b/control/package.json @@ -56,10 +56,14 @@ "verify:consumers": "bun run scripts/verify-consumers.ts", "verify:tarball": "bun run scripts/assert-tarball-shape.ts", "test": "bun test", + "fuzz": "FUZZ_SECONDS=8 bun test --timeout 60000 src/fuzz", "typecheck": "tsc --noEmit" }, "dependencies": { "@httptoolkit/dbus-native": "0.1.5", "zod": "4.4.3" + }, + "devDependencies": { + "fast-check": "^4.11.0" } } diff --git a/control/src/fuzz/README.md b/control/src/fuzz/README.md new file mode 100644 index 0000000..cae8485 --- /dev/null +++ b/control/src/fuzz/README.md @@ -0,0 +1,19 @@ +# Property tests + +[fast-check](https://github.com/dubzzz/fast-check) properties for the parsers and +normalizers that take data from a modem, ModemManager or a router: the D-Bus body +codec, 3GPP location strings, cell info, observation normalization, the router +(HiLink, goform, HIMI) response parsers, mmcli SMS output, NMEA and the small +text parsers. They check that nothing throws on arbitrary input, that bounded +and finite values stay that way, and that accepted input round-trips. + +`bun test` runs each property for 300 cases. For a longer, time-bounded run give +every property a number of seconds: + +```sh +FUZZ_SECONDS=8 bun test --timeout 60000 src/fuzz +``` + +bun's own per-test timeout is 5 seconds, hence `--timeout`. Each property prints a `fuzz-runs ` line. A failing property prints its seed and a shrunk +counterexample; replay it with `fc.assert(property, { seed, path })` and turn it +into a regression test next to the code it covers. diff --git a/control/src/fuzz/cell-info.property.test.ts b/control/src/fuzz/cell-info.property.test.ts new file mode 100644 index 0000000..1426805 --- /dev/null +++ b/control/src/fuzz/cell-info.property.test.ts @@ -0,0 +1,96 @@ +import { describe, expect, test } from 'bun:test'; +import fc from 'fast-check'; +import { budget } from '../../test-support/fuzz-budget'; +import { + type CellReading, + compareServing, + normalizeCellInfo, + selectServingCell, +} from '../backend/cell-info'; +import type { DecodedProps } from '../backend/managed-objects'; +import { epochMillis } from '../domain'; +import type { DbusVariant } from '../transport'; + +const PROVENANCE = { source: 'Modem.GetCellInfo', observedAt: epochMillis(1) }; +const KEYS = [ + 'ci', + 'cell-id', + 'tac', + 'physical-ci', + 'rsrp', + 'rsrq', + 'sinr', + 'snr', + 'band', + 'serving', + 'cell-type', +]; + +const variantValue = fc.oneof( + fc.string({ maxLength: 12 }), + fc.integer(), + // Non-finite readings are covered next to the fix that handles them. + fc.double({ noNaN: true, noDefaultInfinity: true }), + fc.boolean(), + fc.array(fc.integer(), { maxLength: 3 }), +); +const variant: fc.Arbitrary = fc.record({ + signature: fc.constantFrom('s', 'i', 'u', 'd', 'b'), + value: variantValue as fc.Arbitrary, +}); +const cellDict: fc.Arbitrary = fc.array(fc.tuple(fc.constantFrom(...KEYS), variant), { + maxLength: 8, +}); + +// Readings as a GetCellInfo reply produces them, so the property covers what the +// normalizer lets through rather than what the type permits. +const readings = fc + .array(cellDict, { minLength: 1, maxLength: 6 }) + .map((dicts) => normalizeCellInfo(dicts, PROVENANCE) as CellReading[]); + +describe('cell-info normalization', () => { + test('never throws and keeps the pinned types', () => { + fc.assert( + fc.property(fc.array(cellDict, { maxLength: 6 }), (dicts) => { + for (const reading of normalizeCellInfo(dicts, PROVENANCE)) { + expect(typeof reading.serving).toBe('boolean'); + for (const key of ['pci', 'rsrp', 'rsrq', 'sinr'] as const) { + const value = reading[key]; + if (value !== undefined) expect(typeof value).toBe('number'); + } + } + }), + budget(), + ); + }); + + test('the serving-cell winner does not depend on input order', () => { + fc.assert( + fc.property(readings, fc.infiniteStream(fc.nat()), (cells, stream) => { + const shuffled = [...cells]; + const picks = stream[Symbol.iterator](); + for (let i = shuffled.length - 1; i > 0; i -= 1) { + const j = (picks.next().value as number) % (i + 1); + [shuffled[i], shuffled[j]] = [shuffled[j] as CellReading, shuffled[i] as CellReading]; + } + expect(JSON.stringify(selectServingCell(shuffled))).toBe( + JSON.stringify(selectServingCell(cells)), + ); + }), + budget(), + ); + }); + + test('compareServing is antisymmetric', () => { + fc.assert( + fc.property(readings, (cells) => { + for (const a of cells) { + for (const b of cells) { + expect(Math.sign(compareServing(a, b)) + Math.sign(compareServing(b, a))).toBe(0); + } + } + }), + budget(), + ); + }); +}); diff --git a/control/src/fuzz/codec.property.test.ts b/control/src/fuzz/codec.property.test.ts new file mode 100644 index 0000000..53c5bce --- /dev/null +++ b/control/src/fuzz/codec.property.test.ts @@ -0,0 +1,140 @@ +import { describe, expect, test } from 'bun:test'; +import fc from 'fast-check'; +import { budget } from '../../test-support/fuzz-budget'; +import { decodeBody, encodeBody } from '../transport/codec'; +import type { SignatureNode } from '../transport/signature'; +import type { DbusValue } from '../transport/types'; + +// A well-formed type tree for the signature subset this transport supports (no `h`). +// Dict entries only ever appear as array elements, as the D-Bus wire format requires. +const BASIC = ['y', 'b', 'n', 'q', 'i', 'u', 'x', 't', 'd', 's', 'o', 'g'] as const; +const DICT_KEYS = ['y', 'b', 'n', 'q', 'i', 'u', 'x', 't', 's', 'o', 'g'] as const; + +const node = (type: string, child: SignatureNode[] = []): SignatureNode => ({ type, child }); + +const typeTree: fc.Arbitrary = fc.letrec<{ t: SignatureNode }>((tie) => ({ + t: fc.oneof( + { depthSize: 'small', maxDepth: 3 }, + fc.constantFrom(...BASIC).map((type) => node(type)), + fc.constant(node('v')), + tie('t').map((element) => node('a', [element])), + fc + .tuple(fc.constantFrom(...DICT_KEYS), tie('t')) + .map(([key, value]) => node('a', [node('{', [node(key), value])])), + fc.array(tie('t'), { minLength: 1, maxLength: 3 }).map((members) => node('(', members)), + ), +})).t; + +function signatureOf(type: SignatureNode): string { + if (type.type === 'a') return `a${signatureOf(type.child[0] as SignatureNode)}`; + if (type.type === '(') return `(${type.child.map(signatureOf).join('')})`; + if (type.type === '{') return `{${type.child.map(signatureOf).join('')}}`; + return type.type; +} + +// What the marshalling library hands back (`lib`) next to the public value the transport +// must turn it into (`pub`). +interface Pair { + readonly lib: unknown; + readonly pub: DbusValue; +} + +const long = (value: bigint, unsigned: boolean) => ({ + low: Number(BigInt.asIntN(32, value)), + high: Number(BigInt.asIntN(32, value >> 32n)), + unsigned, + toString: () => value.toString(), +}); + +function pairFor(type: SignatureNode): fc.Arbitrary { + const same = (arb: fc.Arbitrary) => arb.map((v) => ({ lib: v, pub: v })); + switch (type.type) { + case 'y': + return same(fc.integer({ min: 0, max: 255 })); + case 'b': + return same(fc.boolean()); + case 'n': + return same(fc.integer({ min: -32768, max: 32767 })); + case 'q': + return same(fc.integer({ min: 0, max: 65535 })); + case 'i': + return same(fc.integer({ min: -(2 ** 31), max: 2 ** 31 - 1 })); + case 'u': + return same(fc.integer({ min: 0, max: 2 ** 32 - 1 })); + case 'd': + return same(fc.double({ noNaN: true })); + case 's': + case 'g': + return same(fc.string({ maxLength: 20 })); + case 'o': + return same(fc.constantFrom('/', '/org/freedesktop/ModemManager1/Modem/0')); + case 'x': + return fc + .bigInt({ min: -(2n ** 63n), max: 2n ** 63n - 1n }) + .map((v) => ({ lib: long(v, false), pub: v })); + case 't': + return fc + .bigInt({ min: 0n, max: 2n ** 64n - 1n }) + .map((v) => ({ lib: long(v, true), pub: v })); + case 'v': + return typeTree.chain((inner) => + pairFor(inner).map(({ lib, pub }) => ({ + lib: [[inner], [lib]], + pub: { signature: signatureOf(inner), value: pub }, + })), + ); + case 'a': { + const element = type.child[0] as SignatureNode; + if (element.type === 'y') { + return fc + .uint8Array({ maxLength: 16 }) + .map((bytes) => ({ lib: Buffer.from(bytes), pub: new Uint8Array(bytes) })); + } + return fc.array(pairFor(element), { maxLength: 4 }).map((items) => ({ + lib: items.map((item) => item.lib), + pub: items.map((item) => item.pub), + })); + } + case '(': + return fc.tuple(...type.child.map(pairFor)).map((members) => ({ + lib: members.map((member) => member.lib), + pub: members.map((member) => member.pub), + })); + case '{': { + const [key, value] = type.child.map(pairFor) as [fc.Arbitrary, fc.Arbitrary]; + return fc.tuple(key, value).map(([k, v]) => ({ lib: [k.lib, v.lib], pub: [k.pub, v.pub] })); + } + default: + throw new Error(`generator has no case for ${type.type}`); + } +} + +const bodies = fc.array(typeTree, { minLength: 1, maxLength: 3 }).chain((types) => + fc.tuple(...types.map(pairFor)).map((pairs) => ({ + signature: types.map(signatureOf).join(''), + lib: pairs.map((pair) => pair.lib), + pub: pairs.map((pair) => pair.pub), + })), +); + +describe('D-Bus body codec', () => { + test('decoding a library body yields the public value for every supported signature', () => { + fc.assert( + fc.property(bodies, ({ signature, lib, pub }) => { + expect(decodeBody(signature, lib)).toEqual(pub); + }), + budget(), + ); + }); + + test('what decodes can be encoded again, and decodes to the same value', () => { + fc.assert( + fc.property(bodies, ({ signature, lib }) => { + const decoded = decodeBody(signature, lib); + const encoded = encodeBody(signature, decoded); + expect(encoded).toHaveLength(decoded.length); + }), + budget(), + ); + }); +}); diff --git a/control/src/fuzz/parsers.property.test.ts b/control/src/fuzz/parsers.property.test.ts new file mode 100644 index 0000000..b20f809 --- /dev/null +++ b/control/src/fuzz/parsers.property.test.ts @@ -0,0 +1,244 @@ +import { describe, expect, test } from 'bun:test'; +import fc from 'fast-check'; +import { budget } from '../../test-support/fuzz-budget'; +import { fixtureContext, MM_FIXTURE } from '../../test-support/observation-fixtures'; +import { parseMmVersion } from '../backend/features'; +import { parseNmVersion } from '../backend/nm-auto-apn'; +import { parseTerse } from '../backend/nmcli-runner'; +import { parseProcNetDev } from '../backend/usage/proc-net-dev'; +import { parseUdevDatabase } from '../backend/usb-enumerator'; +import { + decode3gppLacCi, + decodeMmAccessTechnologies, + decodeMmState, + decodeRegistrationState, + lacCiOperatorCode, +} from '../domain'; +import { + parseHilinkCapabilities, + parseHilinkDataCapability, + parseHilinkSession, + parseHilinkSignal, + parseHilinkUserState, + parseUfiSignal, + parseZteSignal, +} from '../hardware/router-parsers'; +import { parseNmeaFix } from '../location/nmea'; +import { normalizeModemManagerObservation, type RawFieldValue } from '../observations'; +import { flattenXmlBody, parseJsonRecord } from '../observations/raw'; +import { parseSmsListOutput, parseSmsRecordOutput } from '../sms/mmcli-parse'; +import { parseUsbDevices } from '../usb-mode/usb-devices-parse'; + +const text = fc.oneof( + fc.string({ maxLength: 400 }), + fc.string({ unit: 'binary', maxLength: 200 }), + fc.stringMatching(/^[<>/A-Za-z0-9=,.:"'\s{}[\]-]{0,300}$/), +); +const numbers = fc.oneof( + fc.integer(), + fc.double({ noDefaultInfinity: false, noNaN: false }), + fc.constantFrom(Number.MAX_SAFE_INTEGER, -1, 0, 2 ** 31, 2 ** 32 - 1, 2 ** 53, Number.NaN), +); + +describe('text parsers never throw on arbitrary input', () => { + test.each([ + ['parseMmVersion', (s: string) => parseMmVersion(s)], + ['parseNmVersion', (s: string) => parseNmVersion(s)], + ['parseTerse', (s: string) => parseTerse(s)], + ['parseProcNetDev', (s: string) => parseProcNetDev(s)], + ['parseUdevDatabase', (s: string) => parseUdevDatabase(s)], + ['parseUsbDevices', (s: string) => parseUsbDevices(s)], + ['parseNmeaFix', (s: string) => parseNmeaFix(s)], + ['parseSmsListOutput', (s: string) => parseSmsListOutput(s)], + ['parseSmsRecordOutput', (s: string) => parseSmsRecordOutput(s)], + ['parseHilinkSession', (s: string) => parseHilinkSession(s)], + ['parseHilinkUserState', (s: string) => parseHilinkUserState(s)], + ['parseHilinkDataCapability', (s: string) => parseHilinkDataCapability(s)], + ['parseHilinkCapabilities', (s: string) => parseHilinkCapabilities({ netModeList: s })], + ['parseHilinkSignal', (s: string) => parseHilinkSignal({ status: s, signal: s })], + ['parseZteSignal', (s: string) => parseZteSignal(s)], + ['parseUfiSignal', (s: string) => parseUfiSignal({ sysinfo: s, overview: s, status: s })], + ['parseJsonRecord', (s: string) => parseJsonRecord(s)], + ['flattenXmlBody', (s: string) => flattenXmlBody(s, 'body')], + ['decode3gppLacCi', (s: string) => decode3gppLacCi(s)], + ])('%s', (_name, parse) => { + fc.assert( + fc.property(text, (input) => { + parse(input); + }), + budget(), + ); + }); +}); + +describe('mmcli SMS parsing stays content-free', () => { + test('a refusal never echoes message content', () => { + const secret = 'S3CRET-OTP-424242'; + fc.assert( + fc.property(fc.array(text, { maxLength: 6 }), fc.nat(5), (lines, at) => { + const body = [...lines]; + body.splice(Math.min(at, body.length), 0, `modem.messaging.sms.value[1] : ${secret}`); + for (const parsed of [ + parseSmsListOutput(body.join('\n')), + parseSmsRecordOutput(body.join('\n')), + ]) { + if (!parsed.ok) { + expect(parsed.reason).not.toContain(secret); + expect(parsed.detail).not.toContain(secret); + } + } + }), + budget(), + ); + }); +}); + +describe('numeric decoders are total', () => { + test('MM enum decoders accept any number', () => { + fc.assert( + fc.property(numbers, (n) => { + decodeMmAccessTechnologies(n); + expect(typeof decodeMmState(n)).toBe('string'); + expect(typeof decodeRegistrationState(n)).toBe('string'); + }), + budget(), + ); + }); +}); + +describe('3GPP location context', () => { + test('an accepted value reproduces its source tokens', () => { + fc.assert( + fc.property(text, (input) => { + const decoded = decode3gppLacCi(input); + if (decoded === undefined) return; + expect(decoded.mcc).not.toBe(''); + expect(decoded.mnc).not.toBe(''); + expect(decoded.cellId).not.toBe(''); + expect( + [ + decoded.mcc, + decoded.mnc, + decoded.locationAreaCode, + decoded.cellId, + decoded.trackingAreaCode, + ].join(','), + ).toBe( + input + .trim() + .split(',') + .map((token) => token.trim()) + .join(','), + ); + expect(lacCiOperatorCode(decoded)).toBe(`${decoded.mcc}${decoded.mnc}`); + }), + budget(), + ); + }); +}); + +describe('GNSS fixes', () => { + test('a returned fix is a position on Earth', () => { + fc.assert( + fc.property(text, (input) => { + const fix = parseNmeaFix(input); + if (fix === undefined) return; + expect(Math.abs(fix.latitude)).toBeLessThanOrEqual(90); + expect(Math.abs(fix.longitude)).toBeLessThanOrEqual(180); + if (fix.altitude !== undefined) expect(Number.isFinite(fix.altitude)).toBe(true); + }), + budget(), + ); + }); +}); + +describe('byte counters', () => { + test('/proc/net/dev counters are non-negative safe numbers', () => { + fc.assert( + fc.property(text, (input) => { + for (const value of parseProcNetDev(input).values()) { + expect(Number.isFinite(value)).toBe(true); + expect(value).toBeGreaterThanOrEqual(0); + } + }), + budget(), + ); + }); +}); + +describe('router signal models carry only finite readings', () => { + const metrics = (model: Record) => + ['bars', 'max_bars', 'dbm', 'rsrp', 'rsrq', 'snr', 'sinr'].map( + (key) => model[key] as { state: string; value?: number }, + ); + test('hilink, zte and ufi', () => { + const json = fc.oneof( + fc.json(), + fc + .dictionary(fc.string({ maxLength: 12 }), fc.oneof(fc.string({ maxLength: 12 }), numbers)) + .map((d) => JSON.stringify(d)), + text, + ); + fc.assert( + fc.property(text, json, (xml, body) => { + for (const model of [ + parseHilinkSignal({ status: xml, signal: xml }), + parseZteSignal(body), + parseUfiSignal({ sysinfo: body, overview: body, status: body }), + ]) { + for (const metric of metrics(model as unknown as Record)) { + if (metric.state === 'known') expect(Number.isFinite(metric.value)).toBe(true); + } + } + }), + budget(), + ); + }); +}); + +describe('ModemManager observation normalization', () => { + const rawValue: fc.Arbitrary = fc.letrec<{ v: RawFieldValue }>((tie) => ({ + v: fc.oneof( + { depthSize: 'small' }, + fc.string({ maxLength: 40 }), + numbers, + fc.boolean(), + fc.constant(null), + fc.array(tie('v'), { maxLength: 4 }), + ), + })).v; + const sections = ['modem', 'modem3gpp', 'sim', 'signal', 'location'] as const; + + test('arbitrary property values never throw and always serialize', () => { + fc.assert( + fc.property( + fc.record( + Object.fromEntries( + sections.map((section) => { + const known = Object.keys(MM_FIXTURE[section] ?? {}); + return [ + section, + fc.option( + fc.dictionary( + fc.oneof( + fc.constantFrom(...known, '3gpp-lac-ci'), + fc.string({ maxLength: 12 }), + ), + rawValue, + { maxKeys: 12 }, + ), + { nil: undefined }, + ), + ]; + }), + ), + ), + (input) => { + const envelope = normalizeModemManagerObservation(input, fixtureContext()); + JSON.stringify(envelope); + }, + ), + budget(), + ); + }); +}); diff --git a/control/test-support/fuzz-budget.ts b/control/test-support/fuzz-budget.ts new file mode 100644 index 0000000..e507c36 --- /dev/null +++ b/control/test-support/fuzz-budget.ts @@ -0,0 +1,28 @@ +import fc, { type Parameters } from 'fast-check'; + +/** + * Run budget for the property tests. + * + * `bun test` runs each property for a few hundred cases, which keeps the suite quick. + * A longer, time-bounded run is `FUZZ_SECONDS=8 bun test --timeout 60000 src/fuzz`: every property gets + * that many seconds with the case count lifted, and each property reports its case count as a `fuzz-runs` line + * (`FUZZ_SECONDS=8` across this directory is about five minutes). An interrupted run is + * not a failure; a counterexample still is. + */ +export function budget(): Parameters { + const seconds = Number(process.env.FUZZ_SECONDS ?? 0); + const timed = Number.isFinite(seconds) && seconds > 0; + return { + ...(timed + ? { + numRuns: 1_000_000_000, + interruptAfterTimeLimit: seconds * 1000, + markInterruptAsFailure: false, + } + : { numRuns: 300 }), + reporter: (details) => { + if (timed) console.log(`fuzz-runs ${details.numRuns}`); + if (details.failed) throw new Error(fc.defaultReportMessage(details)); + }, + }; +}