Skip to content
Draft
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
7 changes: 7 additions & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions control/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
}
19 changes: 19 additions & 0 deletions control/src/fuzz/README.md
Original file line number Diff line number Diff line change
@@ -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 <cases>` 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.
96 changes: 96 additions & 0 deletions control/src/fuzz/cell-info.property.test.ts
Original file line number Diff line number Diff line change
@@ -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<DbusVariant> = fc.record({
signature: fc.constantFrom('s', 'i', 'u', 'd', 'b'),
value: variantValue as fc.Arbitrary<DbusVariant['value']>,
});
const cellDict: fc.Arbitrary<DecodedProps> = 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(),
);
});
});
140 changes: 140 additions & 0 deletions control/src/fuzz/codec.property.test.ts
Original file line number Diff line number Diff line change
@@ -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<SignatureNode> = 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<Pair> {
const same = <T extends DbusValue>(arb: fc.Arbitrary<T>) => 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<Pair>, fc.Arbitrary<Pair>];
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(),
);
});
});
Loading