Files
openchamber-android-native/test/relay_crypto_test.dart
T

67 lines
2.7 KiB
Dart
Raw Normal View History

import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/relay_crypto.dart';
Uint8List _bytes(String text) => Uint8List.fromList(utf8.encode(text));
void main() {
test('P-256 JWK round-trips and fingerprints stably', () {
final pair = newRelayKeyPair();
final jwk = publicJwk(pair.publicKey);
expect(jwk['kty'], 'EC');
expect(jwk['crv'], 'P-256');
final imported = importPublicJwk(jwk);
expect(publicJwk(imported), jwk);
expect(jwkFingerprint(jwk), jwkFingerprint(Map<String, dynamic>.from(jwk)));
expect(jwkFingerprint(jwk), isNot(contains('"d"')));
});
test('both sides derive the same directional keys and can talk', () {
final client = newRelayKeyPair();
final host = newRelayKeyPair();
final nonce = randomBytes(16);
final clientKeys = deriveSessionKeys(client.privateKey, host.publicKey, nonce);
final hostKeys = deriveSessionKeys(host.privateKey, client.publicKey, nonce);
expect(clientKeys.clientToHost, hostKeys.clientToHost);
expect(clientKeys.hostToClient, hostKeys.hostToClient);
expect(clientKeys.clientToHost, isNot(clientKeys.hostToClient));
final encryptor = RelayEncryptor(clientKeys.clientToHost);
final decryptor = RelayDecryptor(hostKeys.clientToHost);
final frame = encryptor.encrypt(_bytes('hello over the relay'));
expect(frame.first, encryptedFrameVersion);
expect(utf8.decode(decryptor.decrypt(frame)), 'hello over the relay');
// A second frame works; a replayed counter does not.
final second = encryptor.encrypt(_bytes('hello over the relay'));
expect(utf8.decode(decryptor.decrypt(second)), 'hello over the relay');
expect(() => decryptor.decrypt(second), throwsA(isA<RelayCryptoError>()));
// A different nonce gives different keys.
final otherKeys =
deriveSessionKeys(client.privateKey, host.publicKey, randomBytes(16));
expect(otherKeys.clientToHost, isNot(clientKeys.clientToHost));
});
test('tampered frames fail closed', () {
final a = newRelayKeyPair();
final b = newRelayKeyPair();
final nonce = randomBytes(16);
final keys = deriveSessionKeys(a.privateKey, b.publicKey, nonce);
final frame = RelayEncryptor(keys.clientToHost).encrypt(_bytes('tamper me'));
final bad = Uint8List.fromList(frame)..[frame.length - 1] ^= 0xff;
expect(() => RelayDecryptor(keys.clientToHost).decrypt(bad),
throwsA(isA<RelayCryptoError>()));
});
test('base64url helpers follow the protocol (no padding)', () {
final bytes = Uint8List.fromList([0, 1, 2, 250, 255]);
final encoded = base64UrlEncodeBytes(bytes);
expect(encoded, isNot(contains('=')));
expect(base64UrlDecodeBytes(encoded), bytes);
});
}