feat(#403): parse YAML into a config-profile model

Adds the yaml dependency and parseConfigProfile(): YAML -> ConfigProfile
(#402). Strict by design since profiles are untrusted input (#139) — unknown
keys, wrong types, out-of-range/duplicate broker slots, and unknown
transport/auth values all throw ConfigProfileFormatException with a
user-facing message. Only keys present populate the model. 11 unit tests.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
feat/393-app-log-share
Strycher 4 months ago
parent 7e46e8522f
commit e73c2b5a10

@ -0,0 +1,231 @@
import 'package:yaml/yaml.dart';
import '../models/config_profile.dart';
/// Thrown when a config-profile document is not valid (#403).
///
/// Message is user-facing: the import flow shows it verbatim, so it names the
/// offending key/value rather than a stack position.
class ConfigProfileFormatException implements Exception {
const ConfigProfileFormatException(this.message);
final String message;
@override
String toString() => 'ConfigProfileFormatException: $message';
}
/// Parse a YAML config profile into a [ConfigProfile] (#402 model).
///
/// Strict by design — profiles are untrusted input (#139 trust note), so an
/// unknown key or a wrong type is an error, not a silent skip. Only keys present
/// in the document appear in the model; everything else stays null so the apply
/// engines touch only what the profile sets.
///
/// Expected shape:
/// ```yaml
/// schema_version: 1
/// name: "US wide-area" # optional label, not applied
/// wifi: { ssid: "...", password: "...", enabled: true }
/// region: "IAD" # -> mqtt.iata
/// status_interval: 60
/// brokers:
/// - slot: 0
/// enabled: true
/// url: "..."
/// port: 8883
/// transport: tls # tcp | tls | wss
/// auth_type: basic # none | basic | jwt
/// username: "..."
/// ...
/// ```
ConfigProfile parseConfigProfile(String source) {
final dynamic doc;
try {
doc = loadYaml(source);
} on YamlException catch (e) {
throw ConfigProfileFormatException('Not valid YAML: ${e.message}');
}
final root = _asMap(doc, 'document root');
final version = _requireInt(root, 'schema_version');
if (version > kConfigProfileSchemaVersion) {
throw ConfigProfileFormatException(
'Profile schema_version $version is newer than this app supports '
'($kConfigProfileSchemaVersion). Update the app.',
);
}
_rejectUnknownKeys(root, const {
'schema_version',
'name',
'wifi',
'region',
'status_interval',
'brokers',
}, 'document root');
return ConfigProfile(
schemaVersion: version,
name: _optString(root, 'name'),
wifi: _parseWifi(root['wifi']),
regionIata: _optString(root, 'region'),
statusInterval: _optInt(root, 'status_interval'),
brokers: _parseBrokers(root['brokers']),
);
}
WifiConfig? _parseWifi(dynamic node) {
if (node == null) return null;
final map = _asMap(node, 'wifi');
_rejectUnknownKeys(map, const {'ssid', 'password', 'enabled'}, 'wifi');
return WifiConfig(
ssid: _optString(map, 'ssid'),
password: _optString(map, 'password'),
enabled: _optBool(map, 'enabled'),
);
}
List<BrokerConfig> _parseBrokers(dynamic node) {
if (node == null) return const [];
if (node is! YamlList) {
throw const ConfigProfileFormatException('"brokers" must be a list');
}
final seenSlots = <int>{};
final brokers = <BrokerConfig>[];
for (var i = 0; i < node.length; i++) {
final map = _asMap(node[i], 'brokers[$i]');
_rejectUnknownKeys(map, const {
'slot',
'enabled',
'url',
'port',
'transport',
'auth_type',
'username',
'password',
'jwt_token',
'jwt_aud',
'jwt_refresh',
'jwt_owner',
'jwt_email',
'ca_cert',
'topic_prefix',
'iata_override',
}, 'brokers[$i]');
final slot = _requireInt(map, 'slot', context: 'brokers[$i]');
if (slot < 0 || slot >= kMaxBrokerSlots) {
throw ConfigProfileFormatException(
'brokers[$i].slot must be 0..${kMaxBrokerSlots - 1}, got $slot',
);
}
if (!seenSlots.add(slot)) {
throw ConfigProfileFormatException('duplicate broker slot $slot');
}
brokers.add(
BrokerConfig(
slot: slot,
enabled: _optBool(map, 'enabled'),
url: _optString(map, 'url'),
port: _optInt(map, 'port'),
transport: _optEnum(
map,
'transport',
MqttTransport.fromWire,
'tcp/tls/wss',
),
authType: _optEnum(
map,
'auth_type',
MqttAuthType.fromWire,
'none/basic/jwt',
),
username: _optString(map, 'username'),
password: _optString(map, 'password'),
jwtToken: _optString(map, 'jwt_token'),
jwtAudience: _optString(map, 'jwt_aud'),
jwtRefresh: _optInt(map, 'jwt_refresh'),
jwtOwner: _optString(map, 'jwt_owner'),
jwtEmail: _optString(map, 'jwt_email'),
caCert: _optString(map, 'ca_cert'),
topicPrefix: _optString(map, 'topic_prefix'),
iataOverride: _optString(map, 'iata_override'),
),
);
}
return brokers;
}
// --- typed accessors -------------------------------------------------------
Map _asMap(dynamic node, String what) {
if (node is Map) return node;
throw ConfigProfileFormatException('$what must be a mapping');
}
void _rejectUnknownKeys(Map map, Set<String> allowed, String what) {
for (final key in map.keys) {
if (!allowed.contains(key)) {
throw ConfigProfileFormatException('unknown key "$key" in $what');
}
}
}
int _requireInt(Map map, String key, {String context = 'document root'}) {
final v = map[key];
if (v == null) {
throw ConfigProfileFormatException('$context is missing required "$key"');
}
if (v is! int) {
throw ConfigProfileFormatException('$context."$key" must be an integer');
}
return v;
}
String? _optString(Map map, String key) {
final v = map[key];
if (v == null) return null;
if (v is! String) {
throw ConfigProfileFormatException('"$key" must be a string');
}
return v;
}
int? _optInt(Map map, String key) {
final v = map[key];
if (v == null) return null;
if (v is! int) {
throw ConfigProfileFormatException('"$key" must be an integer');
}
return v;
}
bool? _optBool(Map map, String key) {
final v = map[key];
if (v == null) return null;
if (v is! bool) {
throw ConfigProfileFormatException('"$key" must be true or false');
}
return v;
}
T? _optEnum<T>(
Map map,
String key,
T? Function(String?) fromWire,
String allowed,
) {
final v = map[key];
if (v == null) return null;
if (v is! String) {
throw ConfigProfileFormatException('"$key" must be a string ($allowed)');
}
final parsed = fromWire(v);
if (parsed == null) {
throw ConfigProfileFormatException(
'"$key" must be one of $allowed, got "$v"',
);
}
return parsed;
}

@ -1571,6 +1571,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "15.2.0"
wakelock_plus:
dependency: "direct main"
description:
name: wakelock_plus
sha256: ddf3db70eaa10c37558ff817519b85d527dbd21034fd5d8e1c2e85f31588f1c1
url: "https://pub.dev"
source: hosted
version: "1.5.2"
wakelock_plus_platform_interface:
dependency: transitive
description:
name: wakelock_plus_platform_interface
sha256: "0618d1799f0b28bcf98255b4ee8313e6fc4d38589dc4ee5fe5840d57d1aff6da"
url: "https://pub.dev"
source: hosted
version: "1.6.0"
watcher:
dependency: transitive
description:
@ -1660,7 +1676,7 @@ packages:
source: hosted
version: "2.0.0"
yaml:
dependency: transitive
dependency: "direct main"
description:
name: yaml
sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce

@ -63,6 +63,7 @@ dependencies:
url_launcher: ^6.3.0 # Launch URLs in system browser
flutter_linkify: ^6.0.0 # Auto-detect and linkify URLs in text
gpx: ^2.3.0
yaml: ^3.1.2 # Parse importable device config profiles (#403)
path_provider: ^2.1.6
share_plus: ^12.0.1
build_pipe: ^0.3.1

@ -0,0 +1,131 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/helpers/config_profile_parser.dart';
import 'package:meshcore_open/models/config_profile.dart';
void main() {
group('parseConfigProfile', () {
test('parses a full profile', () {
final p = parseConfigProfile('''
schema_version: 1
name: US wide-area
wifi:
ssid: MyNet
password: secret
enabled: true
region: IAD
status_interval: 60
brokers:
- slot: 0
enabled: true
url: mqtt.example.org
port: 8883
transport: tls
auth_type: basic
username: u
password: p
topic_prefix: meshcore
- slot: 2
enabled: false
transport: wss
auth_type: jwt
jwt_refresh: 3600
''');
expect(p.schemaVersion, 1);
expect(p.name, 'US wide-area');
expect(p.wifi?.ssid, 'MyNet');
expect(p.wifi?.enabled, true);
expect(p.regionIata, 'IAD');
expect(p.statusInterval, 60);
expect(p.brokers.length, 2);
final b0 = p.brokers.firstWhere((b) => b.slot == 0);
expect(b0.url, 'mqtt.example.org');
expect(b0.port, 8883);
expect(b0.transport, MqttTransport.tls);
expect(b0.authType, MqttAuthType.basic);
final b2 = p.brokers.firstWhere((b) => b.slot == 2);
expect(b2.enabled, false);
expect(b2.transport, MqttTransport.wss);
expect(b2.authType, MqttAuthType.jwt);
expect(b2.jwtRefresh, 3600);
});
test('leaves unset keys null (partial profile)', () {
final p = parseConfigProfile('schema_version: 1\nregion: LHR\n');
expect(p.regionIata, 'LHR');
expect(p.wifi, isNull);
expect(p.statusInterval, isNull);
expect(p.brokers, isEmpty);
});
test('rejects invalid YAML', () {
expect(
() => parseConfigProfile('schema_version: 1\n : bad'),
throwsA(isA<ConfigProfileFormatException>()),
);
});
test('requires schema_version', () {
expect(
() => parseConfigProfile('region: IAD\n'),
throwsA(isA<ConfigProfileFormatException>()),
);
});
test('rejects a newer schema_version', () {
expect(
() => parseConfigProfile('schema_version: 999\n'),
throwsA(isA<ConfigProfileFormatException>()),
);
});
test('rejects unknown top-level key', () {
expect(
() => parseConfigProfile('schema_version: 1\nbogus: 1\n'),
throwsA(isA<ConfigProfileFormatException>()),
);
});
test('rejects unknown broker key', () {
expect(
() => parseConfigProfile(
'schema_version: 1\nbrokers:\n - slot: 0\n nope: 1\n',
),
throwsA(isA<ConfigProfileFormatException>()),
);
});
test('rejects an out-of-range broker slot', () {
expect(
() => parseConfigProfile('schema_version: 1\nbrokers:\n - slot: 9\n'),
throwsA(isA<ConfigProfileFormatException>()),
);
});
test('rejects a duplicate broker slot', () {
expect(
() => parseConfigProfile(
'schema_version: 1\nbrokers:\n - slot: 0\n - slot: 0\n',
),
throwsA(isA<ConfigProfileFormatException>()),
);
});
test('rejects an unknown transport value', () {
expect(
() => parseConfigProfile(
'schema_version: 1\nbrokers:\n - slot: 0\n transport: carrier-pigeon\n',
),
throwsA(isA<ConfigProfileFormatException>()),
);
});
test('rejects a wrong type', () {
expect(
() => parseConfigProfile('schema_version: 1\nstatus_interval: soon\n'),
throwsA(isA<ConfigProfileFormatException>()),
);
});
});
}
Loading…
Cancel
Save

Powered by TurnKey Linux.