Skip to content
Closed
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: 6 additions & 1 deletion cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,19 @@ intent only — `apply` binds it to the selected modem's live identity:
{
"slot": "Modem/0",
"enabled": true,
"connection": { "apn": "auto", "ipFamily": "ipv4v6" },
"connection": { "apn": "auto" },
"roaming": false,
"radio": { "preferenceOrdered": ["5gnr", "lte", "umts", "gsm"] },
"recovery": { "enabled": false },
"usage": { "cycleDay": 1, "thresholdBytes": 5000000000 }
}
```

`connection.ipFamily` is optional in JSON files and defaults to `ipv4v6` when
converted to the required 1.x policy field. `ipv4`, `ipv6`, or `ipv4v6` selects the
[profile method mapping](../control/README.md#opt-in-networkmanager-ip-family);
existing files with `ipv4v6` now explicitly request both automatic methods.

## Develop

From the repository root (single Bun workspace):
Expand Down
32 changes: 32 additions & 0 deletions cli/src/policy-family.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { expect, test } from 'bun:test';
import { imeiEquipmentId } from '@ceralive/modem-control';
import { parsePolicyText, toDesiredPolicy } from './policy-file';

const base = {
enabled: true,
connection: { apn: 'auto' },
roaming: false,
radio: { preferenceOrdered: ['lte'] },
};
const binding = { equipmentId: imeiEquipmentId('490154203237518') };

test('policy files default omission to dual stack and preserve each explicit family', () => {
const omitted = toDesiredPolicy(parsePolicyText(JSON.stringify(base), 'policy.json'), binding);
expect(omitted.connection).toEqual({ apn: 'auto', ipFamily: 'ipv4v6' });
for (const ipFamily of ['ipv4', 'ipv6', 'ipv4v6'] as const) {
const input = { ...base, connection: { apn: 'auto', ipFamily } };
expect(
toDesiredPolicy(parsePolicyText(JSON.stringify(input), 'policy.json'), binding).connection
.ipFamily,
).toBe(ipFamily);
}
});

test('policy files reject unknown family values', () => {
expect(() =>
parsePolicyText(
JSON.stringify({ ...base, connection: { apn: 'auto', ipFamily: 'any' } }),
'policy.json',
),
).toThrow('connection.ipFamily');
});
4 changes: 2 additions & 2 deletions cli/src/policy-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const authSchema = z
const connectionSchema = z
.object({
apn: z.string().min(1),
ipFamily: z.enum(['ipv4', 'ipv6', 'ipv4v6']),
ipFamily: z.enum(['ipv4', 'ipv6', 'ipv4v6']).optional(),
auth: authSchema.optional(),
networkId: z.string().optional(),
})
Expand Down Expand Up @@ -106,7 +106,7 @@ export function toDesiredPolicy(
enabled: spec.enabled,
connection: {
apn: spec.connection.apn,
ipFamily: spec.connection.ipFamily,
ipFamily: spec.connection.ipFamily ?? 'ipv4v6',
...(spec.connection.auth !== undefined ? { auth: toAuth(spec.connection.auth) } : {}),
...(spec.connection.networkId !== undefined ? { networkId: spec.connection.networkId } : {}),
},
Expand Down
40 changes: 40 additions & 0 deletions control/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,46 @@ The declared entries live in `scripts/entries.ts` and the test additionally spel
seven specifiers out as a literal, so a subpath cannot be dropped without a reviewable
change to the public contract.

## Opt-in NetworkManager IP family

Set `connection.ipFamily` in a desired cellular policy, or `ipFamily` on a
`GsmProfileInput` / `GsmProfilePatch`, to request saved NetworkManager methods:

| Request | `ipv4.method` | `ipv6.method` |
| -------- | ------------- | ------------- |
| `ipv4` | `auto` | `disabled` |
| `ipv6` | `disabled` | `auto` |
| `ipv4v6` | `auto` | `auto` |

At the low-level port, omitting the family retains the previous writer behavior:
creation supplies neither method, and patches leave existing methods untouched.
`DesiredConnection.ipFamily` remains required for 1.x type compatibility, and
`defaultCellularPolicy()` retains `ipv4v6`. Policy-driven writes now honor that
value; CLI files that omit it default to `ipv4v6`. IPv4-only profiles use
`ipv6.method disabled`, which requires NetworkManager 1.20 or newer.

NetworkManager's `nmcli --offline connection add type gsm con-name example gsm.auto-config yes`
produces `auto` for both methods (verified with NM 1.54.3),
so omission must not be described as an IPv4-only default. Existing profile values
and NetworkManager configuration remain authoritative. See the
[NetworkManager settings reference](https://networkmanager.pages.freedesktop.org/NetworkManager/NetworkManager/nm-settings-nmcli.html)
for `auto`, `disabled` and `may-fail` semantics. No `may-fail`, route, DNS, CLAT or
APN-ownership setting is changed by this option.

Readback reports `GsmProfile.ipFamily` only for the exact method pairs above;
manual, ignored or unknown combinations leave it absent. This is saved intent,
not proof of the carrier-granted addresses. Feed this readback into the planner's
`AppliedCellularState.appliedIpFamily`: a known mismatch remains `pending`,
and matching saved methods yield an `applied` connection receipt. An absent
readback is unknown and causes no family reconciliation, so existing consumers
do not repeatedly update a profile until they add readback support. APN and
roaming changes still reconcile normally; creation includes the requested family.

Profile writes do not reconnect an active device. The consumer still owns when
to activate a changed profile and must retain its disruption and recovery rules.
IPv6-only service also requires family-aware consumers and an IPv4 service path
such as CLAT for IPv4 hotspot clients; this option does not provide those.

## License

AGPL-3.0
30 changes: 28 additions & 2 deletions control/src/backend/nm-gsm-fields.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// Pure nmcli GSM-connection argv builders — the FULL nine-field write parity today's
// Pure nmcli GSM-connection argv builders — base fields plus optional IP methods.
// Preserves the GSM write parity today's
// CeraUI carried (modem-registration.ts `sanitizeModemConfigForNetworkManager` +
// `addConnectionForModem`), rebuilt from scratch for the device-exact adapter so the
// greenfield port loses nothing the wrap-first path wrote.
Expand All @@ -14,6 +15,7 @@
// connection.autoconnect — always "yes"
// connection.autoconnect-retries — "2"

import type { IpFamily } from '../domain';
import type { ConnectionId, GsmProfile, GsmProfileInput, GsmProfilePatch } from '../ports';

// Empty-string fallback; Bun runtime limitation with empty CLI args: a bare
Expand Down Expand Up @@ -47,6 +49,18 @@ export function gsmFieldPairs(input: GsmProfileInput): Array<[string, string]> {
['gsm.auto-config', auto ? 'yes' : 'no'],
['connection.autoconnect', 'yes'],
['connection.autoconnect-retries', '2'],
...ipMethodPairs(input.ipFamily),
];
}

/** Only an explicit request owns the two IP methods; may-fail stays NM-owned. */
function ipMethodPairs(family: IpFamily | undefined): Array<[string, string]> {
if (family === undefined) {
return [];
}
return [
['ipv4.method', family === 'ipv6' ? 'disabled' : 'auto'],
['ipv6.method', family === 'ipv4' ? 'disabled' : 'auto'],
];
}

Expand All @@ -55,7 +69,7 @@ export function flattenPairs(pairs: ReadonlyArray<readonly [string, string]>): s
return pairs.flat();
}

/** `connection add type gsm con-name <name> <nine fields>` — device-exact create argv. */
/** `connection add type gsm con-name <name> <base fields> [IP methods]` — device-exact create argv. */
export function createGsmArgs(input: GsmProfileInput): string[] {
return [
'connection',
Expand Down Expand Up @@ -101,16 +115,28 @@ export function patchPairs(patch: GsmProfilePatch): string[] {
} else if (patch.networkId !== undefined) {
pairs.push('gsm.network-id', cliArg(patch.networkId));
}
pairs.push(...flattenPairs(ipMethodPairs(patch.ipFamily)));
return pairs;
}

/** Map an nmcli terse readback back onto a `GsmProfile` (inverse of the write parity). */
export function buildProfile(id: ConnectionId, settings: Map<string, string>): GsmProfile {
const v4 = settings.get('ipv4.method');
const v6 = settings.get('ipv6.method');
const ipFamily: IpFamily | undefined =
v4 === 'auto' && v6 === 'auto'
? 'ipv4v6'
: v4 === 'auto' && v6 === 'disabled'
? 'ipv4'
: v4 === 'disabled' && v6 === 'auto'
? 'ipv6'
: undefined;
const username = settings.get('gsm.username') ?? '';
const password = settings.get('gsm.password') ?? '';
const networkId = settings.get('gsm.network-id') ?? '';
return {
connectionId: id,
...(ipFamily !== undefined ? { ipFamily } : {}),
connectionName: settings.get('connection.id') ?? '',
apn: settings.get('gsm.apn') ?? '',
homeOnly: settings.get('gsm.home-only') === 'yes',
Expand Down
171 changes: 171 additions & 0 deletions control/src/backend/nm-ip-family.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
import { expect, test } from 'bun:test';
import { FakeNetworkManagerPort } from '../../test-support/fake-nm/fake-network-manager';
import { StatefulNmcliRunner } from '../../test-support/fake-nm/nmcli-runner';
import { defaultCellularPolicy, type IpFamily, imeiEquipmentId } from '../domain';
import { connectionId } from '../ports';
import { planReconcile } from '../ports/reconcile';
import { buildProfile, createGsmArgs, patchPairs } from './nm-gsm-fields';
import { NmcliNmPort } from './nmcli-nm-port';

const profile = { connectionName: 'cellular', apn: '', homeOnly: true, autoConfig: true };
const policy = defaultCellularPolicy({ equipmentId: imeiEquipmentId('490154203237518') });
const capabilities = {
supportedRats: new Set(['lte'] as const),
simSlotCount: 1,
supportsAutoApn: true,
};
const current = {
hasProfile: true,
connectionId: connectionId('test'),
nmActivation: 'activated' as const,
appliedApn: 'auto',
appliedRoaming: false,
};

for (const [family, v4, v6] of [
['ipv4', 'auto', 'disabled'],
['ipv6', 'disabled', 'auto'],
['ipv4v6', 'auto', 'auto'],
] as const) {
test(`${family}: create, patch and saved readback`, async () => {
const input = { ...profile, ipFamily: family };
const methods = ['ipv4.method', v4, 'ipv6.method', v6];
expect(createGsmArgs(input).slice(-4)).toEqual(methods);
expect(patchPairs({ ipFamily: family })).toEqual(methods);
const runner = new StatefulNmcliRunner();
const port = new NmcliNmPort({ runner });
const saved = await port.createGsmProfile(input);
expect(saved.ipFamily).toBe(family);
const fake = new FakeNetworkManagerPort();
const fakeSaved = await fake.createGsmProfile(input);
expect(fakeSaved.ipFamily).toBe(family);
expect(
(await fake.updateGsmProfile(fakeSaved.connectionId, { ipFamily: 'ipv6' })).ipFamily,
).toBe('ipv6');
for (const next of ['ipv4', 'ipv6', 'ipv4v6'] as const) {
expect((await port.updateGsmProfile(saved.connectionId, { ipFamily: next })).ipFamily).toBe(
next,
);
}
await port.updateGsmProfile(saved.connectionId, { apn: 'changed' });
expect((await port.readGsmProfile(saved.connectionId))?.ipFamily).toBe('ipv4v6');
expect(runner.calls.some((call) => call.includes('up') || call.includes('disconnect'))).toBe(
false,
);
});
test(`${family}: planner writes until readback matches, without reconnect`, () => {
const desired = { ...policy, connection: { apn: 'auto', ipFamily: family } };
const plan = planReconcile(
{ ...current, appliedIpFamily: family === 'ipv4' ? 'ipv6' : 'ipv4' },
desired,
capabilities,
);
const writes = plan.ops.filter((op) => op.port === 'nm');
expect(writes).toEqual([
{
port: 'nm',
op: {
kind: 'updateGsmProfile',
connectionId: current.connectionId,
patch: { ...profile, connectionName: 'ceralive-cellular', ipFamily: family },
},
},
]);
expect(plan.receipts.find((r) => r.dimension === 'connection')?.status).toBe('pending');
const matched = planReconcile(
{ ...current, appliedIpFamily: family as IpFamily },
desired,
capabilities,
);
expect(matched.ops.filter((op) => op.port === 'nm')).toEqual([]);
expect(matched.receipts.find((r) => r.dimension === 'connection')?.status).toBe('applied');
const create = planReconcile({ ...current, hasProfile: false }, desired, capabilities);
expect(create.ops[0]).toMatchObject({
port: 'nm',
op: { kind: 'createGsmProfile', profile: { ipFamily: family } },
});
});
}

test('omission preserves the legacy port argv and the default retains its 1.x family', () => {
expect(createGsmArgs(profile)).toEqual([
'connection',
'add',
'type',
'gsm',
'con-name',
'cellular',
'gsm.apn',
'',
'gsm.username',
'',
'gsm.password',
'',
'gsm.password-flags',
'4',
'gsm.home-only',
'yes',
'gsm.network-id',
'',
'gsm.auto-config',
'yes',
'connection.autoconnect',
'yes',
'connection.autoconnect-retries',
'2',
]);
expect(patchPairs({ apn: 'changed' })).toEqual(['gsm.apn', 'changed']);
const family: IpFamily = policy.connection.ipFamily;
expect(family).toBe('ipv4v6');
expect(planReconcile(current, policy, capabilities).ops.filter((op) => op.port === 'nm')).toEqual(
[],
);
});

test('readback never invents a family for unsupported method combinations', () => {
for (const [v4, v6] of [
['manual', 'auto'],
['disabled', 'disabled'],
['auto', 'ignore'],
] as const) {
expect(
buildProfile(
connectionId('test'),
new Map([
['ipv4.method', v4],
['ipv6.method', v6],
]),
).ipFamily,
).toBeUndefined();
}
});

for (const ipFamily of ['ipv4', 'ipv6', 'ipv4v6'] as const) {
test(`${ipFamily}: unknown applied family causes no reconcile write`, () => {
const desired = { ...policy, connection: { apn: 'auto', ipFamily } };
for (let pass = 0; pass < 2; pass++) {
const plan = planReconcile(current, desired, capabilities);
expect(plan.ops.filter((op) => op.port === 'nm')).toEqual([]);
expect(plan.receipts.find((r) => r.dimension === 'connection')?.status).toBe('applied');
}
});
}

test('saved readback follows independently written methods rather than the request', async () => {
const runner = new StatefulNmcliRunner();
const port = new NmcliNmPort({ runner });
const saved = await port.createGsmProfile({ ...profile, ipFamily: 'ipv4' });
const fake = new FakeNetworkManagerPort(runner);
for (const [v4, v6, expected] of [
['disabled', 'auto', 'ipv6'],
['auto', 'auto', 'ipv4v6'],
['auto', 'disabled', 'ipv4'],
['auto', 'ignore', undefined],
['manual', 'auto', undefined],
['disabled', 'disabled', undefined],
] as const) {
runner.run(['connection', 'modify', saved.connectionId, 'ipv4.method', v4, 'ipv6.method', v6]);
expect((await port.readGsmProfile(saved.connectionId))?.ipFamily).toBe(expected);
expect((await fake.readGsmProfile(saved.connectionId))?.ipFamily).toBe(expected);
}
});
2 changes: 2 additions & 0 deletions control/src/backend/nmcli-nm-port.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ import { buildProfile, createGsmArgs, patchPairs } from './nm-gsm-fields';
import { type NmcliResult, type NmcliRunner, parseTerse, runNmcli } from './nmcli-runner';

const READBACK_FIELDS = [
'ipv4.method',
'ipv6.method',
'connection.id',
'gsm.apn',
'gsm.username',
Expand Down
3 changes: 2 additions & 1 deletion control/src/domain/policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export interface DesiredAuth {
/** The data-connection intent. `apn: "auto"` selects NM Auto-APN (A4.1). */
export interface DesiredConnection {
readonly apn: 'auto' | string;
/** Requested saved-profile family; retained as a required field for 1.x consumers. */
readonly ipFamily: IpFamily;
readonly auth?: DesiredAuth;
/**
Expand Down Expand Up @@ -107,7 +108,7 @@ export const RECOVERY_DISABLED: DesiredRecovery = { enabled: false };

/**
* Build a sensible default policy for a bindable identity: NM activation on,
* Auto-APN, dual-stack IP, roaming off, prefer newest RAT down to GSM, recovery
* Auto-APN, dual-stack IP request, roaming off, prefer newest RAT down to GSM, recovery
* disabled, no usage limits. Concrete adapters and the planner refine from here.
*/
export function defaultCellularPolicy(boundTo: PolicyBindingKey): DesiredCellularPolicy {
Expand Down
Loading
Loading