import 'dart:convert'; import 'ed25519.dart'; /// The Ed25519 public keys this build trusts to sign update feeds, base64 /// and comma separated (`--dart-define=PIPELINES_UPDATE_PUBLIC_KEY`). The /// installer embeds its own key and any listed in /// `~/.config/pipelines/update-trusted-keys`; see /// docs/notes/network-and-update-signing.md. const embeddedUpdateKeys = String.fromEnvironment( 'PIPELINES_UPDATE_PUBLIC_KEY', ); /// The trusted keys in [configured]; a malformed entry is dropped (the /// installer refuses to build with one), and an empty result means this is /// an unsigned development build. List> trustedUpdateKeys([String configured = embeddedUpdateKeys]) { final keys = >[]; for (final entry in configured.split(',')) { final text = entry.trim(); if (text.isEmpty) continue; try { final key = base64.decode(text); if (key.length == 32) keys.add(key); } on FormatException { continue; } } return keys; } /// Why the [feed] bytes cannot be trusted, or null when they can. /// /// [signatureDocument] is the detached `version.json.sig` /// (`{"algorithm":"ed25519","publicKey":…,"signature":…}`), null when the /// server offers none. A build with no trusted keys accepts any feed, as /// before signing existed; a build with keys requires a valid signature by /// one of them. String? feedSignatureProblem( List feed, String? signatureDocument, List> trusted, ) { if (trusted.isEmpty) return null; if (signatureDocument == null) { return 'The update feed is not signed, so it was not trusted.'; } final Object? document; try { document = jsonDecode(signatureDocument); } on FormatException { return 'The update feed signature is unreadable.'; } if (document is! Map || document['algorithm'] != 'ed25519') { return 'The update feed signature is unreadable.'; } final List key, signature; try { key = base64.decode('${document['publicKey'] ?? ''}'); signature = base64.decode('${document['signature'] ?? ''}'); } on FormatException { return 'The update feed signature is unreadable.'; } if (!trusted.any((candidate) => _same(candidate, key))) { return 'The update feed is signed by a key this app does not trust.'; } if (!ed25519Verify(publicKey: key, message: feed, signature: signature)) { return 'The update feed signature does not match; it was not trusted.'; } return null; } bool _same(List a, List b) { if (a.length != b.length) return false; for (var i = 0; i < a.length; i++) { if (a[i] != b[i]) return false; } return true; }