Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,17 @@ jobs:
libudev-dev
- name: Install Rust 1.85.1
uses: dtolnay/rust-toolchain@1.85.1
with:
components: rustfmt, clippy
- name: Run ESLint
run: npm run lint
- name: Check Prettier formatting
run: npm run format:check
- name: Test Desktop channel requests
run: npm run test:channel
- name: Check Rust formatting
run: npm run tauri:format:check
- name: Run Rust Clippy
run: mkdir dist && npm run tauri:lint
- name: Test channel protocol
run: cd src-tauri && cargo test channel::tests --all-features
65 changes: 65 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,79 @@ name: "release"

on:
workflow_dispatch:
inputs:
qa_only:
description: Build an unsigned QA app without creating or updating a release
type: boolean
default: false
push:
branches:
- release

# This workflow will trigger on each push to the `release` branch to create or update a GitHub release, build your app, and upload the artifacts to the release.

jobs:
build-qa:
if: github.event_name == 'workflow_dispatch' && inputs.qa_only
permissions:
contents: read
runs-on: macos-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
- uses: dtolnay/rust-toolchain@1.85.1
with:
targets: aarch64-apple-darwin
- name: Install frontend and pinned HWI dependencies
run: npm ci
- name: Prepare separate QA identity
run: |
python3 - <<'PYQA'
import json
from pathlib import Path
config = json.loads(Path("src-tauri/tauri.release.conf.json").read_text())
config["package"].update(productName="Keeper Desktop R3 QA", version="0.2.6-qa.1")
config["tauri"]["bundle"]["identifier"] = "com.keeper.desktop.r3qa"
config["tauri"]["bundle"]["macOS"]["signingIdentity"] = "-"
Path("src-tauri/tauri.qa.conf.json").write_text(json.dumps(config))
package = json.loads(Path("package.json").read_text())
package["version"] = "0.2.6-qa.1"
Path("package.json").write_text(json.dumps(package))
PYQA
- name: Build QA application only
run: npm run tauri build -- --target aarch64-apple-darwin --bundles app --config src-tauri/tauri.qa.conf.json
- name: Verify QA metadata and endpoint
run: |
python3 - <<'PYQA'
import json, plistlib, hashlib
from pathlib import Path
app = next(Path("src-tauri/target/aarch64-apple-darwin/release/bundle/macos").glob("*.app"))
info = plistlib.loads((app / "Contents/Info.plist").read_bytes())
executable = app / "Contents/MacOS" / info["CFBundleExecutable"]
binary = executable.read_bytes()
assert info["CFBundleIdentifier"] == "com.keeper.desktop.r3qa"
assert info["CFBundleShortVersionString"] == "0.2.6-qa.1"
assert b"https://channel.bitcoinkeeper.app/" in binary
assert b"https://keeper-channel.herokuapp.com/" not in binary
Path("desktop-qa-evidence.json").write_text(json.dumps({
"version": info["CFBundleShortVersionString"], "identifier": info["CFBundleIdentifier"],
"executable_sha256": hashlib.sha256(binary).hexdigest(), "live_endpoint": True,
"source": "${{ github.sha }}", "signing": "ad hoc QA; not production notarized"
}, indent=2))
PYQA
ditto -c -k --sequesterRsrc --keepParent "src-tauri/target/aarch64-apple-darwin/release/bundle/macos/Keeper Desktop R3 QA.app" keeper-desktop-r3-qa.zip
- uses: actions/upload-artifact@v4
with:
name: keeper-desktop-r3-qa-${{ github.sha }}
path: |
keeper-desktop-r3-qa.zip
desktop-qa-evidence.json
retention-days: 14

publish-tauri:
if: github.event_name != 'workflow_dispatch' || !inputs.qa_only
permissions:
contents: write
actions: read
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"lint:fix": "eslint 'src/**/*.{js,jsx,ts,tsx}' --fix",
"format": "prettier --write 'src/**/*.{js,jsx,ts,tsx,json,css,md}'",
"format:check": "prettier --check 'src/**/*.{js,jsx,ts,tsx,json,css,md}'",
"test:channel": "tsx --test src/screens/ConnectScreen/validateChannelMessage.test.ts",
"get-hwi": "tsx scripts/get-hwi.ts --cleanup",
"postinstall": "tsx scripts/get-hwi.ts",
"tauri:lint": "cd src-tauri && cargo clippy --all-targets --all-features -- -D warnings",
Expand Down
208 changes: 193 additions & 15 deletions src-tauri/src/channel.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use aes_gcm::aead::rand_core::RngCore;
use aes_gcm::aead::{Aead, KeyInit, OsRng};
use aes_gcm::{Aes256Gcm, Key, Nonce};
use aes_gcm::{Aes256Gcm, Nonce};
use log::{error, info, warn};
use rust_socketio::client::Client;
use rust_socketio::{ClientBuilder, Event, Payload};
Expand All @@ -12,10 +12,6 @@ use tauri::Manager;
use thiserror::Error;
use tokio::time::timeout;

#[cfg(not(feature = "release"))]
static URL: &str = "https://keeper-channel-dev-8d01fa5233d0.herokuapp.com/";

#[cfg(feature = "release")]
static URL: &str = "https://channel.bitcoinkeeper.app/";

#[derive(Error, Debug)]
Expand All @@ -26,6 +22,8 @@ pub enum ChannelError {
NoRoom,
#[error("No encryption key set")]
NoEncryptionKey,
#[error("Invalid encryption key")]
InvalidEncryptionKey,
#[error("Invalid IV")]
InvalidIV,
#[error("Invalid encrypted data")]
Expand Down Expand Up @@ -150,8 +148,8 @@ impl Channel {
.ok_or(ChannelError::NoEncryptionKey)?;
let key_bytes = hex::decode(encryption_key)?;

let key = Key::<Aes256Gcm>::from_slice(&key_bytes);
let cipher = Aes256Gcm::new(key);
let cipher = Aes256Gcm::new_from_slice(&key_bytes)
.map_err(|_| ChannelError::InvalidEncryptionKey)?;

let mut nonce_bytes = [0u8; 12];
OsRng.fill_bytes(&mut nonce_bytes);
Expand Down Expand Up @@ -185,8 +183,8 @@ impl Channel {
.ok_or(ChannelError::NoEncryptionKey)?;
let key_bytes = hex::decode(encryption_key)?;

let key = Key::<Aes256Gcm>::from_slice(&key_bytes);
let cipher = Aes256Gcm::new(key);
let cipher = Aes256Gcm::new_from_slice(&key_bytes)
.map_err(|_| ChannelError::InvalidEncryptionKey)?;

let nonce = hex::decode(encrypted["iv"].as_str().ok_or(ChannelError::InvalidIV)?)?;
let encrypted_data = hex::decode(
Expand All @@ -200,6 +198,12 @@ impl Channel {
.ok_or(ChannelError::InvalidEncryptedData)?,
)?;

if nonce.len() != 12 {
return Err(ChannelError::InvalidIV);
}
if auth_tag.len() != 16 {
return Err(ChannelError::InvalidEncryptedData);
}
let nonce = Nonce::from_slice(&nonce);

let mut combined_data = Vec::with_capacity(encrypted_data.len() + auth_tag.len());
Expand All @@ -224,6 +228,11 @@ impl Channel {
.and_then(|arr| arr.first())
.ok_or("Failed to parse message")?;

let room = self.room.as_deref().ok_or("No active channel room")?;
if data.get("room").and_then(|value| value.as_str()) != Some(room) {
return Err("Message received from inactive room".to_string());
}

let request_data = data
.get("requestData")
.ok_or("Failed to parse message data")?;
Expand All @@ -232,12 +241,9 @@ impl Channel {
.get("network")
.ok_or("Failed to parse message network")?;

let data = if request_data.get("encryptedData").is_some() {
self.decrypt_data(request_data)
.map_err(|_| "Failed to decrypt message from channel")?
} else {
request_data.clone()
};
let data = self
.decrypt_data(request_data)
.map_err(|_| "Failed to decrypt message from channel")?;

Ok(json!({ "data": data, "network": network }))
}
Expand Down Expand Up @@ -302,3 +308,175 @@ fn create_client(app_handle: tauri::AppHandle) -> Result<Client, ChannelError> {
.connect()
.map_err(|e| ChannelError::SocketIoError(e.to_string()))
}

#[cfg(test)]
mod tests {
use super::*;

fn fixture() -> serde_json::Value {
serde_json::from_str(include_str!("fixtures/channel-crypto-vectors.json")).unwrap()
}

fn test_channel(key: &str) -> Channel {
Channel {
client: None,
room: Some(hex::encode(Sha256::digest(key))),
encryption_key: Some(key.to_string()),
}
}

fn request_message(room: &str, request_data: serde_json::Value) -> serde_json::Value {
json!([{"room": room, "requestData": request_data, "network": "TESTNET"}])
}

#[test]
fn mobile_signing_vector_is_accepted_with_testnet_network() {
let fixture = fixture();
let channel = test_channel(fixture["key"].as_str().unwrap());
let message = request_message(
channel.room.as_deref().unwrap(),
fixture["request"]["ciphertext"].clone(),
);
assert_eq!(
channel.process_channel_message(&message).unwrap(),
json!({"data": fixture["request"]["plaintext"], "network": "TESTNET"})
);
}

#[test]
fn missing_or_inactive_room_never_reaches_desktop() {
let fixture = fixture();
let mut channel = test_channel(fixture["key"].as_str().unwrap());
let ciphertext = fixture["request"]["ciphertext"].clone();
let missing_room = json!([{"requestData": ciphertext.clone(), "network": "TESTNET"}]);
assert!(channel.process_channel_message(&missing_room).is_err());

let old_room = request_message(&"00".repeat(32), ciphertext.clone());
assert!(channel.process_channel_message(&old_room).is_err());

let current_room = request_message(channel.room.as_deref().unwrap(), ciphertext);
channel.room = None;
assert!(channel.process_channel_message(&current_room).is_err());
}

#[test]
fn plaintext_or_incomplete_envelope_is_rejected_in_active_room() {
let fixture = fixture();
let channel = test_channel(fixture["key"].as_str().unwrap());
let room = channel.room.as_deref().unwrap();
let plaintext = request_message(room, fixture["request"]["plaintext"].clone());
assert!(channel.process_channel_message(&plaintext).is_err());

let mut incomplete = fixture["request"]["ciphertext"].clone();
incomplete.as_object_mut().unwrap().remove("authTag");
assert!(channel
.process_channel_message(&request_message(room, incomplete))
.is_err());
}

#[test]
fn rotating_qr_rejects_old_room_and_accepts_new_session() {
let fixture = fixture();
let mut channel = test_channel(fixture["key"].as_str().unwrap());
let old_request = request_message(
channel.room.as_deref().unwrap(),
fixture["request"]["ciphertext"].clone(),
);

let new_key = "01".repeat(32);
channel.room = Some(hex::encode(Sha256::digest(&new_key)));
channel.encryption_key = Some(new_key);
assert!(channel.process_channel_message(&old_request).is_err());

let new_ciphertext = channel
.encrypt_data(fixture["request"]["plaintext"].clone())
.unwrap();
let new_request = request_message(channel.room.as_deref().unwrap(), new_ciphertext);
assert_eq!(
channel.process_channel_message(&new_request).unwrap(),
json!({"data": fixture["request"]["plaintext"], "network": "TESTNET"})
);
}

#[test]
fn desktop_response_keeps_mobile_event_data_response_shape() {
let fixture = fixture();
let channel = test_channel(fixture["key"].as_str().unwrap());
let encrypted = channel
.encrypt_data(fixture["response"]["plaintext"].clone())
.unwrap();
assert_eq!(encrypted["iv"].as_str().unwrap().len(), 24);
assert_eq!(encrypted["authTag"].as_str().unwrap().len(), 32);
assert_eq!(
channel.decrypt_data(&encrypted).unwrap(),
fixture["response"]["plaintext"]
);
assert_eq!(
channel
.decrypt_data(&fixture["response"]["ciphertext"])
.unwrap(),
fixture["response"]["plaintext"]
);
}

#[test]
fn malformed_nonce_returns_error_without_panicking() {
let fixture = fixture();
let channel = test_channel(fixture["key"].as_str().unwrap());
for iv in ["", "00", "000102030405060708090a0b0c"] {
let mut encrypted = fixture["request"]["ciphertext"].clone();
encrypted["iv"] = json!(iv);
assert!(matches!(
channel.decrypt_data(&encrypted),
Err(ChannelError::InvalidIV)
));
}
}

#[test]
fn malformed_key_returns_error_without_panicking() {
let fixture = fixture();
for key in ["", "00", "000102030405060708090a0b0c0d0e0f"] {
let channel = test_channel(key);
assert!(matches!(
channel.decrypt_data(&fixture["request"]["ciphertext"]),
Err(ChannelError::InvalidEncryptionKey)
));
assert!(matches!(
channel.encrypt_data(json!({"action": "SIGN_TX"})),
Err(ChannelError::InvalidEncryptionKey)
));
}
}

#[test]
fn invalid_auth_tag_or_ciphertext_never_returns_signing_data() {
let fixture = fixture();
let channel = test_channel(fixture["key"].as_str().unwrap());
let mut encrypted = fixture["request"]["ciphertext"].clone();
encrypted["authTag"] = json!("00");
assert!(matches!(
channel.decrypt_data(&encrypted),
Err(ChannelError::InvalidEncryptedData)
));
for field in ["iv", "encryptedData", "authTag"] {
let mut encrypted = fixture["request"]["ciphertext"].clone();
let original = encrypted[field].as_str().unwrap();
let altered = format!(
"{}{}",
if original.starts_with('0') { '1' } else { '0' },
&original[1..]
);
encrypted[field] = json!(altered);
assert!(channel.decrypt_data(&encrypted).is_err());
}
}

#[test]
fn different_qr_session_cannot_decrypt_request() {
let fixture = fixture();
assert!(test_channel(&"01".repeat(32))
.decrypt_data(&fixture["request"]["ciphertext"])
.is_err());
}
}
Loading
Loading