From 0b81461cec7e4657709109121bdba79885b24118 Mon Sep 17 00:00:00 2001 From: Paul Golmann Date: Sat, 14 Nov 2026 01:52:05 +0100 Subject: [PATCH 1/2] feat(network): honor explicit profile IP family requests --- cli/README.md | 7 +- cli/src/policy-family.test.ts | 32 +++++ cli/src/policy-file.ts | 4 +- control/README.md | 36 +++++ control/src/backend/nm-gsm-fields.ts | 25 ++++ control/src/backend/nm-ip-family.test.ts | 136 ++++++++++++++++++ control/src/backend/nmcli-nm-port.ts | 2 + control/src/domain/policy.ts | 7 +- control/src/ports/README.md | 23 +-- control/src/ports/network-manager.ts | 4 +- control/src/ports/reconcile.ts | 18 ++- .../fake-nm/fake-network-manager.ts | 21 +-- 12 files changed, 277 insertions(+), 38 deletions(-) create mode 100644 cli/src/policy-family.test.ts create mode 100644 control/src/backend/nm-ip-family.test.ts diff --git a/cli/README.md b/cli/README.md index 1dcf991..3695e58 100644 --- a/cli/README.md +++ b/cli/README.md @@ -34,7 +34,7 @@ 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 }, @@ -42,6 +42,11 @@ intent only — `apply` binds it to the selected modem's live identity: } ``` +`connection.ipFamily` is optional. Omit it to preserve NetworkManager defaults or +existing profile methods. Explicit `ipv4`, `ipv6`, or `ipv4v6` opts into 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): diff --git a/cli/src/policy-family.test.ts b/cli/src/policy-family.test.ts new file mode 100644 index 0000000..7843a01 --- /dev/null +++ b/cli/src/policy-family.test.ts @@ -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 preserve omission and each explicit family', () => { + const omitted = toDesiredPolicy(parsePolicyText(JSON.stringify(base), 'policy.json'), binding); + expect(omitted.connection).toEqual({ apn: 'auto' }); + 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'); +}); diff --git a/cli/src/policy-file.ts b/cli/src/policy-file.ts index 1aab4cd..ce862de 100644 --- a/cli/src/policy-file.ts +++ b/cli/src/policy-file.ts @@ -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(), }) @@ -106,7 +106,7 @@ export function toDesiredPolicy( enabled: spec.enabled, connection: { apn: spec.connection.apn, - ipFamily: spec.connection.ipFamily, + ...(spec.connection.ipFamily !== undefined ? { ipFamily: spec.connection.ipFamily } : {}), ...(spec.connection.auth !== undefined ? { auth: toAuth(spec.connection.auth) } : {}), ...(spec.connection.networkId !== undefined ? { networkId: spec.connection.networkId } : {}), }, diff --git a/control/README.md b/control/README.md index ead8cf2..9766443 100644 --- a/control/README.md +++ b/control/README.md @@ -420,6 +420,42 @@ 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` | + +Omit the family to retain the previous writer behavior: creation supplies neither +method, and patches leave existing methods untouched. `defaultCellularPolicy()` +therefore omits the family; its former nominal `ipv4v6` value was never written. +An explicit `ipv4v6` now opts in, including in existing policy files. + +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 requested mismatch remains `pending`, +and matching saved methods yield an `applied` connection receipt. With no family +request, the planner does not compare or reconcile methods. + +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 diff --git a/control/src/backend/nm-gsm-fields.ts b/control/src/backend/nm-gsm-fields.ts index 30e268c..04d18cc 100644 --- a/control/src/backend/nm-gsm-fields.ts +++ b/control/src/backend/nm-gsm-fields.ts @@ -14,6 +14,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 @@ -47,6 +48,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'], ]; } @@ -101,16 +114,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): 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', diff --git a/control/src/backend/nm-ip-family.test.ts b/control/src/backend/nm-ip-family.test.ts new file mode 100644 index 0000000..a265d87 --- /dev/null +++ b/control/src/backend/nm-ip-family.test.ts @@ -0,0 +1,136 @@ +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, 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 argv and default policy does not opt in', () => { + 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']); + expect(policy.connection.ipFamily).toBeUndefined(); + 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(); + } +}); diff --git a/control/src/backend/nmcli-nm-port.ts b/control/src/backend/nmcli-nm-port.ts index a4c098f..6ea347f 100644 --- a/control/src/backend/nmcli-nm-port.ts +++ b/control/src/backend/nmcli-nm-port.ts @@ -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', diff --git a/control/src/domain/policy.ts b/control/src/domain/policy.ts index c62f98f..0296bea 100644 --- a/control/src/domain/policy.ts +++ b/control/src/domain/policy.ts @@ -39,7 +39,8 @@ export interface DesiredAuth { /** The data-connection intent. `apn: "auto"` selects NM Auto-APN (A4.1). */ export interface DesiredConnection { readonly apn: 'auto' | string; - readonly ipFamily: IpFamily; + /** Omit to preserve NetworkManager defaults / existing profile methods. */ + readonly ipFamily?: IpFamily; readonly auth?: DesiredAuth; /** * Manual operator selection (`gsm.network-id`) — pin registration to a specific @@ -107,14 +108,14 @@ 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, NetworkManager IP defaults, 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 { return { boundTo, enabled: true, - connection: { apn: 'auto', ipFamily: 'ipv4v6' }, + connection: { apn: 'auto' }, roaming: false, radio: { preferenceOrdered: ['5gnr', 'lte', 'umts', 'gsm'] }, recovery: RECOVERY_DISABLED, diff --git a/control/src/ports/README.md b/control/src/ports/README.md index c1fee76..3fee2d8 100644 --- a/control/src/ports/README.md +++ b/control/src/ports/README.md @@ -25,17 +25,18 @@ the NM-owns-bearers architecture the whole package is built around (independent review correction, draft §Oracle #1): the controller is a reconciler over two adapters, never a second writer of the same resource. -| Resource | Sole writer | Port / owner | -| ------------------------------------------------ | ---------------- | ------------------------------------------------------ | -| APN | NetworkManager | `NetworkManagerPort` (`gsm.apn` / auto-config) | -| Connection auth (username / password) | NetworkManager | `NetworkManagerPort` (`gsm.username` / `gsm.password`) | -| Roaming | NetworkManager | `NetworkManagerPort` (`gsm.home-only`) | -| Autoconnect | NetworkManager | `NetworkManagerPort` (`connection.autoconnect`) | -| Activation (bearer lifecycle) | NetworkManager | `NetworkManagerPort` (`activate`/`deactivate`) | -| Radio access-technology modes | ModemManager | `ModemManagerPort.setRadioModes` | -| SIM operations (PIN / PUK / primary slot / scan) | ModemManager | `ModemManagerPort` | -| Recovery ladder | Local controller | policy `recovery` (disabled by default, A3.4) | -| Usage policy (cycle / threshold) | Local controller | policy `usage` (A4.3 sampler) | +| Resource | Sole writer | Port / owner | +| ------------------------------------------------ | ---------------- | --------------------------------------------------------------------------- | +| APN | NetworkManager | `NetworkManagerPort` (`gsm.apn` / auto-config) | +| Saved IP family methods | NetworkManager | `NetworkManagerPort` (explicit `ipFamily` only; omission preserves methods) | +| Connection auth (username / password) | NetworkManager | `NetworkManagerPort` (`gsm.username` / `gsm.password`) | +| Roaming | NetworkManager | `NetworkManagerPort` (`gsm.home-only`) | +| Autoconnect | NetworkManager | `NetworkManagerPort` (`connection.autoconnect`) | +| Activation (bearer lifecycle) | NetworkManager | `NetworkManagerPort` (`activate`/`deactivate`) | +| Radio access-technology modes | ModemManager | `ModemManagerPort.setRadioModes` | +| SIM operations (PIN / PUK / primary slot / scan) | ModemManager | `ModemManagerPort` | +| Recovery ladder | Local controller | policy `recovery` (disabled by default, A3.4) | +| Usage policy (cycle / threshold) | Local controller | policy `usage` (A4.3 sampler) | ### The bearer invariant (safety-critical) diff --git a/control/src/ports/network-manager.ts b/control/src/ports/network-manager.ts index c30c47c..261b801 100644 --- a/control/src/ports/network-manager.ts +++ b/control/src/ports/network-manager.ts @@ -3,7 +3,7 @@ // way the controller touches any of those resources; the ModemManager port has no // bearer / connection verbs at all. -import type { Brand, EpochMillis } from '../domain'; +import type { Brand, EpochMillis, IpFamily } from '../domain'; import { nonEmptyString } from '../domain'; import type { Receipt } from './receipts'; @@ -30,6 +30,8 @@ export function deviceIfname(value: string): DeviceIfname { * contract that adapter fulfils. */ export interface GsmProfileInput { + /** Explicit saved IP methods; omission leaves methods untouched. */ + readonly ipFamily?: IpFamily; readonly connectionName: string; /** Concrete APN, or the empty string when `autoConfig` drives it (A4.1). */ readonly apn: string; diff --git a/control/src/ports/reconcile.ts b/control/src/ports/reconcile.ts index a63f2eb..6a78fe2 100644 --- a/control/src/ports/reconcile.ts +++ b/control/src/ports/reconcile.ts @@ -4,7 +4,12 @@ // side effects: the same inputs always yield the same ops and receipts, which is // what makes re-applying a policy idempotent (see reconcile.test.ts). -import type { DesiredCellularPolicy, NmActivation, RadioAccessTechnology } from '../domain'; +import type { + DesiredCellularPolicy, + IpFamily, + NmActivation, + RadioAccessTechnology, +} from '../domain'; import type { ConnectionId, DeviceIfname, GsmProfileInput } from './network-manager'; import { mmOp, nmOp, type PortTaggedOp } from './ops'; import { type Receipt, receipt } from './receipts'; @@ -27,6 +32,8 @@ export interface AppliedCellularState { readonly connectionId?: ConnectionId; readonly deviceIfname?: DeviceIfname; readonly appliedApn?: 'auto' | string; + /** Saved profile methods from NM readback, not the carrier-granted addresses. */ + readonly appliedIpFamily?: IpFamily; readonly appliedRoaming?: boolean; readonly appliedRadioPreference?: readonly RadioAccessTechnology[]; readonly activePrimarySlot?: number; @@ -83,6 +90,7 @@ function profileFromPolicy(desired: DesiredCellularPolicy): GsmProfileInput { const auto = desired.connection.apn === 'auto'; const base: GsmProfileInput = { connectionName: 'ceralive-cellular', + ...(desired.connection.ipFamily !== undefined ? { ipFamily: desired.connection.ipFamily } : {}), apn: auto ? '' : desired.connection.apn, homeOnly: !desired.roaming, autoConfig: auto, @@ -124,13 +132,15 @@ function planNmProfile( const needsWrite = !current.hasProfile || current.appliedApn !== desired.connection.apn || - current.appliedRoaming !== desired.roaming; + current.appliedRoaming !== desired.roaming || + (desired.connection.ipFamily !== undefined && + current.appliedIpFamily !== desired.connection.ipFamily); if (!needsWrite) { return { connection: receipt( 'connection', 'applied', - `connection APN '${desired.connection.apn}' already configured`, + `connection APN '${desired.connection.apn}'${desired.connection.ipFamily ? ` (${desired.connection.ipFamily})` : ''} already configured`, ), roaming: receipt( 'roaming', @@ -152,7 +162,7 @@ function planNmProfile( connection: receipt( 'connection', 'pending', - `${verb} connection profile for APN '${desired.connection.apn}'`, + `${verb} connection profile for APN '${desired.connection.apn}'${desired.connection.ipFamily ? ` (${desired.connection.ipFamily})` : ''}`, ), roaming: receipt( 'roaming', diff --git a/control/test-support/fake-nm/fake-network-manager.ts b/control/test-support/fake-nm/fake-network-manager.ts index 7182fd7..17cb20e 100644 --- a/control/test-support/fake-nm/fake-network-manager.ts +++ b/control/test-support/fake-nm/fake-network-manager.ts @@ -8,6 +8,7 @@ // carries. A4.1's `NmcliNmPort` owns the full nine-field GSM write parity and the // atomic Auto-APN transitions; this harness is what A4.1 injects to assert them. +import { buildProfile, patchPairs } from '../../src/backend/nm-gsm-fields'; import { epochMillis } from '../../src/domain'; import { type ConnectionId, @@ -24,6 +25,8 @@ import { import { type NmcliResult, StatefulNmcliRunner } from './nmcli-runner'; const READBACK_FIELDS = [ + 'ipv4.method', + 'ipv6.method', 'connection.id', 'gsm.apn', 'gsm.username', @@ -71,6 +74,7 @@ export class FakeNetworkManagerPort implements NetworkManagerPort { if (profile.networkId !== undefined) { argv.push('gsm.network-id', profile.networkId); } + argv.push(...patchPairs(profile.ipFamily !== undefined ? { ipFamily: profile.ipFamily } : {})); const result = this.#runner.run(argv); const uuid = /\(([^)]+)\) successfully added/.exec(result.stdout)?.[1]; if (uuid === undefined) { @@ -121,6 +125,7 @@ export class FakeNetworkManagerPort implements NetworkManagerPort { if (patch.networkId !== undefined) { argv.push('gsm.network-id', patch.networkId); } + argv.push(...patchPairs(patch.ipFamily !== undefined ? { ipFamily: patch.ipFamily } : {})); const result = this.#runner.run(argv); if (result.exitCode !== 0) { throw new Error(`fake nmcli: modify failed (${result.stderr})`); @@ -188,19 +193,3 @@ function parseTerse(stdout: string): Map { } return settings; } - -function buildProfile(id: ConnectionId, settings: Map): GsmProfile { - const username = settings.get('gsm.username') ?? ''; - const password = settings.get('gsm.password') ?? ''; - const networkId = settings.get('gsm.network-id') ?? ''; - return { - connectionId: id, - connectionName: settings.get('connection.id') ?? '', - apn: settings.get('gsm.apn') ?? '', - homeOnly: settings.get('gsm.home-only') === 'yes', - autoConfig: settings.get('gsm.auto-config') === 'yes', - ...(username !== '' ? { username } : {}), - ...(password !== '' ? { password } : {}), - ...(networkId !== '' ? { networkId } : {}), - }; -} From 06a3cd54f3ea374b016cabb3879edd0c31243e6e Mon Sep 17 00:00:00 2001 From: Paul Golmann Date: Sat, 14 Nov 2026 02:13:28 +0100 Subject: [PATCH 2/2] fix(network): preserve policy compatibility and unknown family readback --- cli/README.md | 4 +- cli/src/policy-family.test.ts | 4 +- cli/src/policy-file.ts | 2 +- control/README.md | 18 ++++--- control/src/backend/nm-gsm-fields.ts | 5 +- control/src/backend/nm-ip-family.test.ts | 41 ++++++++++++++-- control/src/domain/policy.ts | 8 ++-- control/src/ports/reconcile.ts | 4 +- .../fake-nm/fake-network-manager.ts | 48 +++++++++++++++++-- 9 files changed, 107 insertions(+), 27 deletions(-) diff --git a/cli/README.md b/cli/README.md index 3695e58..e102d2a 100644 --- a/cli/README.md +++ b/cli/README.md @@ -42,8 +42,8 @@ intent only — `apply` binds it to the selected modem's live identity: } ``` -`connection.ipFamily` is optional. Omit it to preserve NetworkManager defaults or -existing profile methods. Explicit `ipv4`, `ipv6`, or `ipv4v6` opts into the +`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. diff --git a/cli/src/policy-family.test.ts b/cli/src/policy-family.test.ts index 7843a01..3753d61 100644 --- a/cli/src/policy-family.test.ts +++ b/cli/src/policy-family.test.ts @@ -10,9 +10,9 @@ const base = { }; const binding = { equipmentId: imeiEquipmentId('490154203237518') }; -test('policy files preserve omission and each explicit family', () => { +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' }); + 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( diff --git a/cli/src/policy-file.ts b/cli/src/policy-file.ts index ce862de..04a47e1 100644 --- a/cli/src/policy-file.ts +++ b/cli/src/policy-file.ts @@ -106,7 +106,7 @@ export function toDesiredPolicy( enabled: spec.enabled, connection: { apn: spec.connection.apn, - ...(spec.connection.ipFamily !== undefined ? { 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 } : {}), }, diff --git a/control/README.md b/control/README.md index 9766443..73105c9 100644 --- a/control/README.md +++ b/control/README.md @@ -431,10 +431,12 @@ Set `connection.ipFamily` in a desired cellular policy, or `ipFamily` on a | `ipv6` | `disabled` | `auto` | | `ipv4v6` | `auto` | `auto` | -Omit the family to retain the previous writer behavior: creation supplies neither -method, and patches leave existing methods untouched. `defaultCellularPolicy()` -therefore omits the family; its former nominal `ipv4v6` value was never written. -An explicit `ipv4v6` now opts in, including in existing policy files. +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), @@ -447,9 +449,11 @@ 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 requested mismatch remains `pending`, -and matching saved methods yield an `applied` connection receipt. With no family -request, the planner does not compare or reconcile methods. +`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. diff --git a/control/src/backend/nm-gsm-fields.ts b/control/src/backend/nm-gsm-fields.ts index 04d18cc..bb826f9 100644 --- a/control/src/backend/nm-gsm-fields.ts +++ b/control/src/backend/nm-gsm-fields.ts @@ -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. @@ -68,7 +69,7 @@ export function flattenPairs(pairs: ReadonlyArray): s return pairs.flat(); } -/** `connection add type gsm con-name ` — device-exact create argv. */ +/** `connection add type gsm con-name [IP methods]` — device-exact create argv. */ export function createGsmArgs(input: GsmProfileInput): string[] { return [ 'connection', diff --git a/control/src/backend/nm-ip-family.test.ts b/control/src/backend/nm-ip-family.test.ts index a265d87..dc77c39 100644 --- a/control/src/backend/nm-ip-family.test.ts +++ b/control/src/backend/nm-ip-family.test.ts @@ -55,7 +55,11 @@ for (const [family, v4, v6] of [ }); test(`${family}: planner writes until readback matches, without reconnect`, () => { const desired = { ...policy, connection: { apn: 'auto', ipFamily: family } }; - const plan = planReconcile(current, desired, capabilities); + const plan = planReconcile( + { ...current, appliedIpFamily: family === 'ipv4' ? 'ipv6' : 'ipv4' }, + desired, + capabilities, + ); const writes = plan.ops.filter((op) => op.port === 'nm'); expect(writes).toEqual([ { @@ -83,7 +87,7 @@ for (const [family, v4, v6] of [ }); } -test('omission preserves the legacy argv and default policy does not opt in', () => { +test('omission preserves the legacy port argv and the default retains its 1.x family', () => { expect(createGsmArgs(profile)).toEqual([ 'connection', 'add', @@ -111,7 +115,8 @@ test('omission preserves the legacy argv and default policy does not opt in', () '2', ]); expect(patchPairs({ apn: 'changed' })).toEqual(['gsm.apn', 'changed']); - expect(policy.connection.ipFamily).toBeUndefined(); + const family: IpFamily = policy.connection.ipFamily; + expect(family).toBe('ipv4v6'); expect(planReconcile(current, policy, capabilities).ops.filter((op) => op.port === 'nm')).toEqual( [], ); @@ -134,3 +139,33 @@ test('readback never invents a family for unsupported method combinations', () = ).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); + } +}); diff --git a/control/src/domain/policy.ts b/control/src/domain/policy.ts index 0296bea..7a789da 100644 --- a/control/src/domain/policy.ts +++ b/control/src/domain/policy.ts @@ -39,8 +39,8 @@ export interface DesiredAuth { /** The data-connection intent. `apn: "auto"` selects NM Auto-APN (A4.1). */ export interface DesiredConnection { readonly apn: 'auto' | string; - /** Omit to preserve NetworkManager defaults / existing profile methods. */ - readonly ipFamily?: IpFamily; + /** Requested saved-profile family; retained as a required field for 1.x consumers. */ + readonly ipFamily: IpFamily; readonly auth?: DesiredAuth; /** * Manual operator selection (`gsm.network-id`) — pin registration to a specific @@ -108,14 +108,14 @@ export const RECOVERY_DISABLED: DesiredRecovery = { enabled: false }; /** * Build a sensible default policy for a bindable identity: NM activation on, - * Auto-APN, NetworkManager IP defaults, 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 { return { boundTo, enabled: true, - connection: { apn: 'auto' }, + connection: { apn: 'auto', ipFamily: 'ipv4v6' }, roaming: false, radio: { preferenceOrdered: ['5gnr', 'lte', 'umts', 'gsm'] }, recovery: RECOVERY_DISABLED, diff --git a/control/src/ports/reconcile.ts b/control/src/ports/reconcile.ts index 6a78fe2..95b8492 100644 --- a/control/src/ports/reconcile.ts +++ b/control/src/ports/reconcile.ts @@ -32,7 +32,7 @@ export interface AppliedCellularState { readonly connectionId?: ConnectionId; readonly deviceIfname?: DeviceIfname; readonly appliedApn?: 'auto' | string; - /** Saved profile methods from NM readback, not the carrier-granted addresses. */ + /** Saved profile methods, not carrier-granted addresses. Absent means unknown: no family drift. */ readonly appliedIpFamily?: IpFamily; readonly appliedRoaming?: boolean; readonly appliedRadioPreference?: readonly RadioAccessTechnology[]; @@ -133,7 +133,7 @@ function planNmProfile( !current.hasProfile || current.appliedApn !== desired.connection.apn || current.appliedRoaming !== desired.roaming || - (desired.connection.ipFamily !== undefined && + (current.appliedIpFamily !== undefined && current.appliedIpFamily !== desired.connection.ipFamily); if (!needsWrite) { return { diff --git a/control/test-support/fake-nm/fake-network-manager.ts b/control/test-support/fake-nm/fake-network-manager.ts index 17cb20e..95e3b62 100644 --- a/control/test-support/fake-nm/fake-network-manager.ts +++ b/control/test-support/fake-nm/fake-network-manager.ts @@ -5,10 +5,9 @@ // so a `readGsmProfile` after a `createGsmProfile`/`updateGsmProfile` returns exactly // what was written — a genuine readback double for reconcile/observer tests. It is a // TEST DOUBLE, not the shipping adapter: it wires only the fields the port interface -// carries. A4.1's `NmcliNmPort` owns the full nine-field GSM write parity and the +// carries. A4.1's `NmcliNmPort` owns the base GSM fields plus optional IP methods and the // atomic Auto-APN transitions; this harness is what A4.1 injects to assert them. -import { buildProfile, patchPairs } from '../../src/backend/nm-gsm-fields'; import { epochMillis } from '../../src/domain'; import { type ConnectionId, @@ -74,7 +73,14 @@ export class FakeNetworkManagerPort implements NetworkManagerPort { if (profile.networkId !== undefined) { argv.push('gsm.network-id', profile.networkId); } - argv.push(...patchPairs(profile.ipFamily !== undefined ? { ipFamily: profile.ipFamily } : {})); + if (profile.ipFamily !== undefined) { + argv.push( + 'ipv4.method', + profile.ipFamily === 'ipv6' ? 'disabled' : 'auto', + 'ipv6.method', + profile.ipFamily === 'ipv4' ? 'disabled' : 'auto', + ); + } const result = this.#runner.run(argv); const uuid = /\(([^)]+)\) successfully added/.exec(result.stdout)?.[1]; if (uuid === undefined) { @@ -125,7 +131,14 @@ export class FakeNetworkManagerPort implements NetworkManagerPort { if (patch.networkId !== undefined) { argv.push('gsm.network-id', patch.networkId); } - argv.push(...patchPairs(patch.ipFamily !== undefined ? { ipFamily: patch.ipFamily } : {})); + if (patch.ipFamily !== undefined) { + argv.push( + 'ipv4.method', + patch.ipFamily === 'ipv6' ? 'disabled' : 'auto', + 'ipv6.method', + patch.ipFamily === 'ipv4' ? 'disabled' : 'auto', + ); + } const result = this.#runner.run(argv); if (result.exitCode !== 0) { throw new Error(`fake nmcli: modify failed (${result.stderr})`); @@ -193,3 +206,30 @@ function parseTerse(stdout: string): Map { } return settings; } + +function buildProfile(id: ConnectionId, settings: Map): GsmProfile { + const username = settings.get('gsm.username') ?? ''; + const password = settings.get('gsm.password') ?? ''; + const networkId = settings.get('gsm.network-id') ?? ''; + const v4 = settings.get('ipv4.method'); + const v6 = settings.get('ipv6.method'); + const ipFamily = + v4 === 'auto' && v6 === 'disabled' + ? ('ipv4' as const) + : v4 === 'disabled' && v6 === 'auto' + ? ('ipv6' as const) + : v4 === 'auto' && v6 === 'auto' + ? ('ipv4v6' as const) + : undefined; + return { + ...(ipFamily !== undefined ? { ipFamily } : {}), + connectionId: id, + connectionName: settings.get('connection.id') ?? '', + apn: settings.get('gsm.apn') ?? '', + homeOnly: settings.get('gsm.home-only') === 'yes', + autoConfig: settings.get('gsm.auto-config') === 'yes', + ...(username !== '' ? { username } : {}), + ...(password !== '' ? { password } : {}), + ...(networkId !== '' ? { networkId } : {}), + }; +}