Merge branch 'worktree-agent-a5eba3669bc0e09ad' into worktree-agent-ac54c8919e940163a

This commit is contained in:
2026-11-10 01:02:08 +00:00
17 changed files with 1010 additions and 26 deletions
+12
View File
@@ -47,12 +47,18 @@ class AppUpdate {
);
/// Reads `version.json`; the APK path is relative to [base].
///
/// A [signed] feed (its signature verified with a key the build trusts)
/// must name the artifact's sha256 and, for Android, its signing
/// certificate: an unsigned build tolerates their absence, a signed one
/// does not.
static AppUpdate? parse(
String body,
Uri base, {
String platform = 'android',
String architecture = 'arm64',
String? installedSignature,
bool signed = false,
}) {
try {
final json = jsonDecode(body);
@@ -67,6 +73,7 @@ class AppUpdate {
return null;
}
final digest = '${json['sha256'] ?? ''}';
if (signed && digest.isEmpty) return null;
if (digest.isNotEmpty && !RegExp(r'^[a-fA-F0-9]{64}$').hasMatch(digest)) {
return null;
}
@@ -76,6 +83,11 @@ class AppUpdate {
!RegExp(r'^[a-fA-F0-9]{64}$').hasMatch(signer))) {
return null;
}
if (signed &&
platform == 'android' &&
(signer is! String || installedSignature == null)) {
return null;
}
if (platform == 'android' &&
signer is String &&
installedSignature != null &&
+45 -11
View File
@@ -11,6 +11,7 @@ import 'package:path_provider/path_provider.dart';
import '../../core/session/server_session.dart';
import 'app_updates.dart';
import 'linux_self_update.dart';
import 'update_feed_signature.dart';
bool get supported =>
Platform.isAndroid || Platform.isLinux || Platform.isMacOS;
@@ -57,10 +58,42 @@ Future<HttpClientResponse> _get(
Future<AppUpdate> fetchLatest(Uri base) =>
fetchLatestScoped(base, ServerSession.headersFor);
Future<AppUpdate> fetchLatestScoped(
Uri base,
/// Reads at most [limit] bytes of [response].
Future<List<int>> _body(HttpClientResponse response, int limit) async {
final chunks = <int>[];
await for (final chunk in response.timeout(const Duration(seconds: 10))) {
if (chunks.length + chunk.length > limit) {
throw const FormatException('Update metadata is too large.');
}
chunks.addAll(chunk);
}
return chunks;
}
/// The detached feed signature, or null when the server offers none.
Future<String?> _signature(
HttpClient client,
Uri feed,
Map<String, String> Function(Uri) headers,
) async {
try {
final response = await _get(
client,
feed.resolve('version.json.sig'),
headers,
);
return utf8.decode(await _body(response, 4096));
} on HttpException {
return null;
}
}
Future<AppUpdate> fetchLatestScoped(
Uri base,
Map<String, String> Function(Uri) headers, {
List<List<int>>? trustedKeys,
}) async {
final trusted = trustedKeys ?? trustedUpdateKeys();
final platform = nativePlatform;
if (platform == 'linux' && nativeArchitecture != 'x64') {
throw const FormatException(
@@ -73,15 +106,15 @@ Future<AppUpdate> fetchLatestScoped(
final client = HttpClient()..connectionTimeout = const Duration(seconds: 10);
try {
final response = await _get(client, feed.resolve('version.json'), headers);
var bytes = 0;
final chunks = <int>[];
await for (final chunk in response.timeout(const Duration(seconds: 10))) {
bytes += chunk.length;
if (bytes > 65536) {
throw const FormatException('Update metadata is too large.');
}
chunks.addAll(chunk);
}
final chunks = await _body(response, 65536);
// The signature is checked before anything in the feed (the artifact's
// sha256 above all) is believed.
final problem = feedSignatureProblem(
chunks,
trusted.isEmpty ? null : await _signature(client, feed, headers),
trusted,
);
if (problem != null) throw FormatException(problem);
final update = AppUpdate.parse(
utf8.decode(chunks),
feed,
@@ -90,6 +123,7 @@ Future<AppUpdate> fetchLatestScoped(
installedSignature: platform == 'android'
? (await PackageInfo.fromPlatform()).buildSignature
: null,
signed: trusted.isNotEmpty,
);
if (update == null) {
throw const FormatException('No compatible build is offered.');
+140
View File
@@ -0,0 +1,140 @@
import 'dart:typed_data';
import 'package:crypto/crypto.dart' as crypto;
/// Ed25519 signature verification (RFC 8032 section 5.1.7), verify only.
///
/// The update feed is checked once per update, so plain [BigInt] arithmetic
/// is fast enough and keeps this small and auditable; it never handles a
/// private key, so constant-time arithmetic is not required. Tested against
/// the RFC 8032 vectors in `test/features/updates/ed25519_test.dart`.
bool ed25519Verify({
required List<int> publicKey,
required List<int> message,
required List<int> signature,
}) {
if (publicKey.length != 32 || signature.length != 64) return false;
final a = _decode(publicKey);
final r = _decode(signature.sublist(0, 32));
if (a == null || r == null) return false;
final s = _littleEndian(signature.sublist(32));
if (s >= _l) return false;
final digest = crypto.sha512.convert([
...signature.sublist(0, 32),
...publicKey,
...message,
]);
final k = _littleEndian(digest.bytes) % _l;
final left = _multiply(_base, s);
final right = _add(r, _multiply(a, k));
return _equal(_encode(left), _encode(right));
}
final BigInt _p = (BigInt.one << 255) - BigInt.from(19);
final BigInt _l =
(BigInt.one << 252) +
BigInt.parse('27742317777372353535851937790883648493');
final BigInt _d =
(BigInt.from(-121665) * BigInt.from(121666).modInverse(_p)) % _p;
final BigInt _sqrtMinusOne = BigInt.two.modPow((_p - BigInt.one) >> 2, _p);
final _Point _base = _decode(_baseEncoding)!;
// The base point: y = 4/5, x even.
final List<int> _baseEncoding = _bytes(
(BigInt.from(4) * BigInt.from(5).modInverse(_p)) % _p,
);
/// Extended coordinates (X:Y:Z:T) with x = X/Z, y = Y/Z, x*y = T/Z.
class _Point {
const _Point(this.x, this.y, this.z, this.t);
final BigInt x, y, z, t;
}
final _Point _identity = _Point(
BigInt.zero,
BigInt.one,
BigInt.one,
BigInt.zero,
);
BigInt _littleEndian(List<int> bytes) {
var value = BigInt.zero;
for (var i = bytes.length - 1; i >= 0; i--) {
value = (value << 8) | BigInt.from(bytes[i]);
}
return value;
}
List<int> _bytes(BigInt value) {
final out = Uint8List(32);
var rest = value;
for (var i = 0; i < 32; i++) {
out[i] = (rest & BigInt.from(0xff)).toInt();
rest >>= 8;
}
return out;
}
_Point? _decode(List<int> encoded) {
final bytes = List<int>.of(encoded);
final sign = bytes[31] >> 7;
bytes[31] &= 0x7f;
final y = _littleEndian(bytes);
if (y >= _p) return null;
final y2 = y * y % _p;
final u = (y2 - BigInt.one) % _p;
final v = (_d * y2 + BigInt.one) % _p;
final v3 = v * v % _p * v % _p;
final v7 = v3 * v3 % _p * v % _p;
var x =
u * v3 % _p * (u * v7 % _p).modPow((_p - BigInt.from(5)) >> 3, _p) % _p;
final check = v * x % _p * x % _p;
if (check == u) {
// x is a square root of u/v.
} else if (check == (_p - u) % _p) {
x = x * _sqrtMinusOne % _p;
} else {
return null;
}
if (x == BigInt.zero && sign == 1) return null;
if (x.isOdd != (sign == 1)) x = _p - x;
return _Point(x, y, BigInt.one, x * y % _p);
}
List<int> _encode(_Point point) {
final inverse = point.z.modInverse(_p);
final x = point.x * inverse % _p;
final y = point.y * inverse % _p;
final out = _bytes(y);
if (x.isOdd) out[31] |= 0x80;
return out;
}
// The unified addition law (RFC 8032 section 5.1.4); it also doubles.
_Point _add(_Point p, _Point q) {
final a = (p.y - p.x) * (q.y - q.x) % _p;
final b = (p.y + p.x) * (q.y + q.x) % _p;
final c = p.t * BigInt.two * _d % _p * q.t % _p;
final d = p.z * BigInt.two * q.z % _p;
final e = (b - a) % _p, f = (d - c) % _p, g = (d + c) % _p, h = (b + a) % _p;
return _Point(e * f % _p, g * h % _p, f * g % _p, e * h % _p);
}
_Point _multiply(_Point point, BigInt scalar) {
var result = _identity;
var addend = point;
var rest = scalar;
while (rest > BigInt.zero) {
if (rest.isOdd) result = _add(result, addend);
addend = _add(addend, addend);
rest >>= 1;
}
return result;
}
bool _equal(List<int> a, List<int> 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;
}
@@ -0,0 +1,79 @@
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<List<int>> trustedUpdateKeys([String configured = embeddedUpdateKeys]) {
final keys = <List<int>>[];
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<int> feed,
String? signatureDocument,
List<List<int>> 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<int> 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<int> a, List<int> 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;
}
+102
View File
@@ -0,0 +1,102 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/updates/ed25519.dart';
List<int> hex(String text) => [
for (var i = 0; i < text.length; i += 2)
int.parse(text.substring(i, i + 2), radix: 16),
];
// RFC 8032 section 7.1, tests 1-3.
const vectors = [
(
'd75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a',
'',
'e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e06522490155'
'5fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b',
),
(
'3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c',
'72',
'92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da'
'085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00',
),
(
'fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025',
'af82',
'6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac'
'18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a',
),
];
void main() {
test('RFC 8032 vectors verify', () {
for (final (key, message, signature) in vectors) {
expect(
ed25519Verify(
publicKey: hex(key),
message: hex(message),
signature: hex(signature),
),
isTrue,
reason: key,
);
}
});
test('a changed message, signature or key is refused', () {
final (key, message, signature) = vectors[2];
bool verify(List<int> k, List<int> m, List<int> s) =>
ed25519Verify(publicKey: k, message: m, signature: s);
expect(verify(hex(key), hex('af83'), hex(signature)), isFalse);
expect(verify(hex(key), hex(''), hex(signature)), isFalse);
for (final index in [0, 31, 32, 63]) {
final changed = hex(signature)..[index] ^= 1;
expect(verify(hex(key), hex(message), changed), isFalse);
}
final otherKey = hex(vectors[1].$1);
expect(verify(otherKey, hex(message), hex(signature)), isFalse);
final changedKey = hex(key)..[0] ^= 1;
expect(verify(changedKey, hex(message), hex(signature)), isFalse);
});
test('malformed inputs are refused rather than thrown', () {
final (key, message, signature) = vectors[1];
expect(
ed25519Verify(
publicKey: hex(key).sublist(1),
message: hex(message),
signature: hex(signature),
),
isFalse,
);
expect(
ed25519Verify(
publicKey: hex(key),
message: hex(message),
signature: hex(signature).sublist(1),
),
isFalse,
);
// S must be below the group order L (no malleable second form).
final high = hex(signature)..fillRange(32, 64, 0xff);
expect(
ed25519Verify(
publicKey: hex(key),
message: hex(message),
signature: high,
),
isFalse,
);
// y = p (non-canonical) does not decode as a key.
final invalidKey = List<int>.filled(32, 0xff)..[0] = 0xed;
invalidKey[31] = 0x7f;
expect(
ed25519Verify(
publicKey: invalidKey,
message: hex(message),
signature: hex(signature),
),
isFalse,
);
});
}
@@ -0,0 +1 @@
6Jo+xjitfGvKp28mdXIziIyDfs5UUP4xzFl92+xrAAU=
@@ -0,0 +1 @@
{"versionCode": 29400000, "versionName": "0.1.29400000", "platform": "linux", "architectures": ["x64"], "file": "pipelines-linux-x64-29400000-0123abcd.tar.gz", "sha256": "abababababababababababababababababababababababababababababababab", "notes": "fixture"}
@@ -0,0 +1 @@
{"algorithm": "ed25519", "publicKey": "6Jo+xjitfGvKp28mdXIziIyDfs5UUP4xzFl92+xrAAU=", "signature": "TpyvCl63pcKcO2Nu4uVI3tCLEN7w/SZe/yQWrs82OqY8C/2cP/o/uFWZ6aRJCo0yaoyTa30wQPSExhUJ08swDg=="}
@@ -0,0 +1,157 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/updates/app_updates.dart';
import 'package:pipelines_app/features/updates/app_updates_io.dart' as io;
import 'package:pipelines_app/features/updates/update_feed_signature.dart';
// Written by scripts/update_signing.py publish_feed with a throwaway key;
// scripts/test_update_signing.py checks the same files with OpenSSL.
const fixture = 'test/features/updates/fixtures/signed_feed';
void main() {
final feed = File('$fixture/version.json').readAsBytesSync();
final signature = File('$fixture/version.json.sig').readAsStringSync();
final key = File('$fixture/public_key.txt').readAsStringSync().trim();
final trusted = trustedUpdateKeys(key);
final otherKey = base64.encode(List<int>.generate(32, (i) => i));
test('a feed signed by the Python publisher verifies', () {
expect(trusted, hasLength(1));
expect(feedSignatureProblem(feed, signature, trusted), isNull);
// Trusted among several keys (this server's and another's).
expect(
feedSignatureProblem(
feed,
signature,
trustedUpdateKeys('$otherKey, $key'),
),
isNull,
);
});
test('a tampered feed or signature is refused', () {
final tampered = utf8.encode(utf8.decode(feed).replaceFirst('"ab', '"cd'));
expect(
feedSignatureProblem(tampered, signature, trusted),
contains('does not match'),
);
final document = jsonDecode(signature) as Map;
final bytes = base64.decode(document['signature'] as String)..[5] ^= 1;
final badSignature = jsonEncode({
...document,
'signature': base64.encode(bytes),
});
expect(
feedSignatureProblem(feed, badSignature, trusted),
contains('does not match'),
);
expect(
feedSignatureProblem(feed, '{"algorithm":"rsa"}', trusted),
contains('unreadable'),
);
expect(
feedSignatureProblem(feed, 'not json', trusted),
contains('unreadable'),
);
});
test('a missing signature is refused when the app has keys', () {
expect(feedSignatureProblem(feed, null, trusted), contains('not signed'));
// A development build without embedded keys keeps the old behaviour.
expect(feedSignatureProblem(feed, null, trustedUpdateKeys('')), isNull);
});
test('a signature by a key the app does not trust is refused', () {
expect(
feedSignatureProblem(feed, signature, trustedUpdateKeys(otherKey)),
contains('does not trust'),
);
// Swapping in the attacker's own key in the document does not help.
final document = jsonDecode(signature) as Map;
final swapped = jsonEncode({...document, 'publicKey': otherKey});
expect(
feedSignatureProblem(feed, swapped, trustedUpdateKeys('$key,$otherKey')),
contains('does not match'),
);
expect(trustedUpdateKeys('short, ${base64.encode([1])}'), isEmpty);
});
test('a signed feed must carry the artifact digest and Android signer', () {
final base = Uri.parse('https://mac.test/updates/');
final signer = 'a' * 64;
String android({bool digest = true, bool certificate = true}) =>
jsonEncode({
'versionCode': 9,
'apk': 'pipelines.apk',
if (digest) 'sha256': 'b' * 64,
if (certificate) 'signingCertificateSha256': signer,
});
AppUpdate? parse(String body, {bool signed = true}) =>
AppUpdate.parse(body, base, installedSignature: signer, signed: signed);
expect(parse(android()), isNotNull);
expect(parse(android(certificate: false)), isNull);
expect(parse(android(digest: false)), isNull);
expect(
AppUpdate.parse(android(), base, signed: true),
isNull,
reason: 'the installed signature is required to compare',
);
// Unsigned builds keep accepting legacy feeds; the OS installer checks.
expect(
parse(android(certificate: false, digest: false), signed: false),
isNotNull,
);
final linux = AppUpdate.parse(
utf8.decode(feed),
base,
platform: 'linux',
architecture: 'x64',
signed: true,
);
expect(linux?.sha256, 'ab' * 32);
});
test(
'the feed reader refuses unsigned and tampered feeds over HTTP',
() async {
final previous = HttpOverrides.current;
HttpOverrides.global = null;
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
var body = feed;
String? served = signature;
server.listen((request) async {
final path = request.uri.path;
if (path.endsWith('/version.json')) {
request.response.add(body);
} else if (path.endsWith('/version.json.sig') && served != null) {
request.response.write(served);
} else {
request.response.statusCode = 404;
}
await request.response.close();
});
final base = Uri.parse('http://127.0.0.1:${server.port}/updates/');
Future<Object?> read() => io
.fetchLatestScoped(base, (_) => {}, trustedKeys: trusted)
.then<Object?>((update) => update, onError: (Object error) => error);
try {
served = null;
expect('${await read()}', contains('not signed'));
served = signature;
body = utf8.encode(utf8.decode(feed).replaceFirst('"ab', '"cd'));
expect('${await read()}', contains('does not match'));
body = feed;
// A genuine feed passes the signature; the host's platform may then
// still find the fixture's Linux build incompatible.
final result = await read();
expect('$result', isNot(contains('sign')));
expect('$result', isNot(contains('trust')));
} finally {
await server.close(force: true);
HttpOverrides.global = previous;
}
},
);
}