(feat): rename example-usage to just example
Some checks failed
CI / rustfmt (push) Successful in 17s
CI / clippy (push) Failing after 1m16s
CI / wasm build (push) Successful in 1m17s
CI / example (push) Successful in 1m29s
CI / test (push) Successful in 1m49s
CI / duplicate code (push) Successful in 12s
CI / web client (push) Failing after 27s
CI / cargo-machete (push) Successful in 1m10s
CI / cargo-deny (push) Failing after 2m20s
Some checks failed
CI / rustfmt (push) Successful in 17s
CI / clippy (push) Failing after 1m16s
CI / wasm build (push) Successful in 1m17s
CI / example (push) Successful in 1m29s
CI / test (push) Successful in 1m49s
CI / duplicate code (push) Successful in 12s
CI / web client (push) Failing after 27s
CI / cargo-machete (push) Successful in 1m10s
CI / cargo-deny (push) Failing after 2m20s
(feat): add the example's web-client dist folder to a gitignore (fix): format issues (fix): a lot of duplicate code
This commit is contained in:
parent
22245e673d
commit
89a20044a5
43 changed files with 528 additions and 1619 deletions
25
example/server/src/clients.rs
Normal file
25
example/server/src/clients.rs
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use mtp::crypto::PublicKeyBundle;
|
||||
|
||||
pub fn load_client_db(
|
||||
path: &str,
|
||||
) -> Result<(Arc<Mutex<HashMap<u64, PublicKeyBundle>>>, Arc<Mutex<u64>>), Box<dyn std::error::Error>>
|
||||
{
|
||||
let clients_map = match fs::read_to_string(path) {
|
||||
Ok(data) => match serde_json::from_str(&data) {
|
||||
Ok(clients) => clients,
|
||||
Err(e) => {
|
||||
eprintln!("Failed to parse {path}; starting with empty client database: {e}");
|
||||
HashMap::new()
|
||||
}
|
||||
},
|
||||
Err(_) => HashMap::new(),
|
||||
};
|
||||
let clients: Arc<Mutex<HashMap<u64, PublicKeyBundle>>> = Arc::new(Mutex::new(clients_map));
|
||||
let next_value = clients.lock().unwrap().keys().max().unwrap_or(&999) + 1;
|
||||
let next_id = Arc::new(Mutex::new(next_value));
|
||||
Ok((clients, next_id))
|
||||
}
|
||||
135
example/server/src/handlers.rs
Normal file
135
example/server/src/handlers.rs
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
use mtp::codec::{CommunicationType, CommunicationValue, DataType, DataTypeId, DataValue, TypeMap};
|
||||
use mtp::crypto::{
|
||||
CryptoError, Keyring, SignaturePublicKey, SignatureScheme, verify_ed25519,
|
||||
};
|
||||
|
||||
struct Ed25519Verifier(SignaturePublicKey);
|
||||
|
||||
impl SignatureScheme for Ed25519Verifier {
|
||||
fn sign(&self, _msg: &[u8]) -> Result<Vec<u8>, CryptoError> {
|
||||
Err(CryptoError::SigningFailed)
|
||||
}
|
||||
fn verify(&self, msg: &[u8], signature: &[u8]) -> Result<(), CryptoError> {
|
||||
verify_ed25519(&self.0, msg, signature)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn process_and_respond(
|
||||
msg: &CommunicationValue,
|
||||
tm: &TypeMap,
|
||||
client_pk: Option<&mtp::crypto::PublicKeyBundle>,
|
||||
host_keyring: &Keyring,
|
||||
) -> CommunicationValue {
|
||||
let desc_id = DataTypeId(tm.data_id_enum(DataType::Description).unwrap());
|
||||
let ts_id = DataTypeId(tm.data_id_enum(DataType::Timestamp).unwrap());
|
||||
let data_id = DataTypeId(tm.data_id_enum(DataType::Data).unwrap());
|
||||
let flags_id = DataTypeId(tm.data_id_enum(DataType::Flags).unwrap());
|
||||
let value_id = DataTypeId(tm.data_id_enum(DataType::Value).unwrap());
|
||||
let bin_id = DataTypeId(tm.data_id_enum(DataType::BinaryData).unwrap());
|
||||
let items_id = DataTypeId(tm.data_id_enum(DataType::Items).unwrap());
|
||||
let enc_id = DataTypeId(tm.data_id_enum(DataType::EncryptedPayload).unwrap());
|
||||
let sig_id = DataTypeId(tm.data_id_enum(DataType::SignedPayload).unwrap());
|
||||
let secure_id = DataTypeId(tm.data_id_enum(DataType::SecurePayload).unwrap());
|
||||
|
||||
let description = msg.get_data(desc_id);
|
||||
let timestamp = msg.get_data(ts_id);
|
||||
let data = msg.get_data(data_id);
|
||||
let flags = msg.get_data(flags_id);
|
||||
let value = msg.get_data(value_id);
|
||||
let binary = msg.get_data(bin_id);
|
||||
let items = msg.get_data(items_id);
|
||||
|
||||
println!(
|
||||
" Description: {}",
|
||||
description.as_str().unwrap_or("(missing)")
|
||||
);
|
||||
println!(" Timestamp: {:?}", timestamp.as_unsigned_number());
|
||||
println!(" Data: {}", data.as_str().unwrap_or("(missing)"));
|
||||
println!(" Flags: {:?}", flags.as_bool());
|
||||
println!(" Value: {:?}", value.as_float());
|
||||
println!(" Binary: {:?}", binary.as_bytes());
|
||||
println!(" Items: {:?}", items.as_array());
|
||||
|
||||
let mut enc_status = String::from("EncryptedPayload: not present");
|
||||
let mut sig_status = String::from("SignedPayload: not present");
|
||||
let mut secure_status = String::from("SecurePayload: not present");
|
||||
|
||||
let enc = msg.get_data(enc_id);
|
||||
if matches!(enc, DataValue::EncryptedContainer(_)) {
|
||||
let mut dv = enc.clone();
|
||||
if dv.decrypt_into_container(host_keyring, b"demo-aad").is_some() {
|
||||
if let Some(entries) = dv.as_container() {
|
||||
println!(" Decrypted EncryptedPayload: {:?}", entries);
|
||||
enc_status = format!("EncryptedPayload decrypted OK ({} entries)", entries.len());
|
||||
}
|
||||
} else {
|
||||
eprintln!(" EncryptedPayload decryption failed");
|
||||
enc_status = String::from("EncryptedPayload: decryption FAILED");
|
||||
}
|
||||
}
|
||||
|
||||
let sig = msg.get_data(sig_id);
|
||||
if matches!(sig, DataValue::SignedContainer(_)) {
|
||||
if let Some(pk_bundle) = client_pk {
|
||||
let verifier = Ed25519Verifier(pk_bundle.sig_cl_public_key.clone());
|
||||
let mut dv = sig.clone();
|
||||
if dv.verify_into_container(&verifier).is_some() {
|
||||
if let Some(entries) = dv.as_container() {
|
||||
println!(" Verified SignedPayload: {:?}", entries);
|
||||
sig_status = format!("SignedPayload verified OK ({} entries)", entries.len());
|
||||
}
|
||||
} else {
|
||||
eprintln!(" SignedPayload verification failed");
|
||||
sig_status = String::from("SignedPayload: verification FAILED");
|
||||
}
|
||||
} else {
|
||||
eprintln!(" SignedPayload cannot be verified; no client public key available");
|
||||
sig_status = String::from("SignedPayload: no client public key available");
|
||||
}
|
||||
}
|
||||
|
||||
let secure = msg.get_data(secure_id);
|
||||
if matches!(secure, DataValue::SignedEncryptedContainer(_)) {
|
||||
if let Some(pk_bundle) = client_pk {
|
||||
let verifier = Ed25519Verifier(pk_bundle.sig_cl_public_key.clone());
|
||||
let mut dv = secure.clone();
|
||||
if dv.decrypt_signed_encrypted_container(host_keyring, b"demo-aad").is_some()
|
||||
&& dv.verify_into_container(&verifier).is_some()
|
||||
{
|
||||
if let Some(entries) = dv.as_container() {
|
||||
println!(" Verified SecurePayload: {:?}", entries);
|
||||
secure_status = format!(
|
||||
"SecurePayload decrypted+verified OK ({} entries)",
|
||||
entries.len()
|
||||
);
|
||||
}
|
||||
} else {
|
||||
eprintln!(" SecurePayload decryption/verification failed");
|
||||
secure_status = String::from("SecurePayload: decryption/verification FAILED");
|
||||
}
|
||||
} else {
|
||||
eprintln!(" SecurePayload cannot be verified; no client public key available");
|
||||
secure_status = String::from("SecurePayload: no client public key available");
|
||||
}
|
||||
}
|
||||
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs();
|
||||
|
||||
CommunicationValue::from_comm(CommunicationType::Pong, tm)
|
||||
.add_data(desc_id, description.clone())
|
||||
.add_data(ts_id, DataValue::UnsignedNumber(now as u128))
|
||||
.add_data(
|
||||
data_id,
|
||||
DataValue::Str(format!(
|
||||
"{}. {}. {}.",
|
||||
enc_status, sig_status, secure_status
|
||||
)),
|
||||
)
|
||||
.add_data(flags_id, flags.clone())
|
||||
.add_data(value_id, value.clone())
|
||||
.add_data(bin_id, binary.clone())
|
||||
.add_data(items_id, items.clone())
|
||||
}
|
||||
50
example/server/src/keys.rs
Normal file
50
example/server/src/keys.rs
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
use std::fs;
|
||||
|
||||
use mtp::crypto::kem::HybridKem;
|
||||
use mtp::crypto::{Ed25519Signer, Keyring, MlDsaSigner};
|
||||
|
||||
pub fn load_or_generate_host_keys(
|
||||
path: &str,
|
||||
) -> Result<(u64, Keyring), Box<dyn std::error::Error>> {
|
||||
if let Ok(data) = fs::read_to_string(path) {
|
||||
let json: serde_json::Value = serde_json::from_str(&data)?;
|
||||
let hid = json["host_id"].as_u64().unwrap_or(1);
|
||||
let keyring = Keyring::from_bytes(&hex::decode(json["keyring"].as_str().unwrap())?)?;
|
||||
println!("Loaded host keys (ID: {})", hid);
|
||||
return Ok((hid, keyring));
|
||||
}
|
||||
|
||||
let (_ed_signer, sig_sk, sig_pk) = Ed25519Signer::generate();
|
||||
let (_pq_signer, sig_pq_sk, sig_pq_pk) = MlDsaSigner::generate();
|
||||
let (kem_sk, kem_pk) = HybridKem::generate_keypair();
|
||||
let keyring = Keyring::new(kem_pk, kem_sk, sig_pq_pk, sig_pq_sk, sig_pk, sig_sk);
|
||||
|
||||
let json = serde_json::json!({
|
||||
"host_id": 1,
|
||||
"keyring": hex::encode(keyring.to_bytes()),
|
||||
});
|
||||
fs::write(path, serde_json::to_string_pretty(&json)?)?;
|
||||
println!("Generated host keys -> {path}");
|
||||
Ok((1u64, keyring))
|
||||
}
|
||||
|
||||
pub fn export_host_public_keys(host_keyring: &Keyring) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let public_key_bundle_hex = hex::encode(host_keyring.public_key_bundle().as_bytes());
|
||||
|
||||
fs::write("host_public_key_bundle.hex", &public_key_bundle_hex)?;
|
||||
fs::create_dir_all("web-client/public")?;
|
||||
fs::write(
|
||||
"web-client/public/host_public_key_bundle.hex",
|
||||
&public_key_bundle_hex,
|
||||
)?;
|
||||
fs::write(
|
||||
"host_enc_kem_pk.bin",
|
||||
host_keyring.kem_public_key.as_bytes(),
|
||||
)?;
|
||||
fs::write("host_sig_pk.bin", host_keyring.sig_cl_public_key.as_bytes())?;
|
||||
fs::write(
|
||||
"host_sig_pq_pk.bin",
|
||||
host_keyring.sig_pq_public_key.as_bytes(),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
125
example/server/src/main.rs
Normal file
125
example/server/src/main.rs
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
mod clients;
|
||||
mod handlers;
|
||||
mod keys;
|
||||
mod tls;
|
||||
|
||||
use mtp::host::{HostConfig, MTPHost};
|
||||
use mtp::type_map::TypeMap;
|
||||
use std::path::Path;
|
||||
|
||||
fn dev_cert_paths() -> (String, String) {
|
||||
let cert = std::env::var("MTP_DEV_CERT").unwrap_or_else(|_| {
|
||||
if Path::new("example/dev-cert/cert.pem").exists() {
|
||||
"example/dev-cert/cert.pem".to_string()
|
||||
} else {
|
||||
"dev-cert/cert.pem".to_string()
|
||||
}
|
||||
});
|
||||
let key = std::env::var("MTP_DEV_KEY").unwrap_or_else(|_| {
|
||||
if Path::new("example/dev-cert/key.pem").exists() {
|
||||
"example/dev-cert/key.pem".to_string()
|
||||
} else {
|
||||
"dev-cert/key.pem".to_string()
|
||||
}
|
||||
});
|
||||
(cert, key)
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let (cert_path, key_path) = dev_cert_paths();
|
||||
let (cert_pem, key_pem) = tls::load_or_generate_tls(&cert_path, &key_path)?;
|
||||
let cert_hash = tls::certificate_sha256_hex(&cert_pem)?;
|
||||
tls::export_webtransport_cert_hash(&cert_hash)?;
|
||||
println!("WebTransport certificate sha256: {cert_hash}");
|
||||
|
||||
let (host_id, host_keyring) = keys::load_or_generate_host_keys("host_keys.json")?;
|
||||
keys::export_host_public_keys(&host_keyring)?;
|
||||
|
||||
// The keyring is moved into the host config; keep a copy for decrypting the
|
||||
// demo payloads clients encrypt to our KEM public key.
|
||||
let decrypt_keyring = mtp::crypto::Keyring::from_bytes(&host_keyring.to_bytes())
|
||||
.expect("re-load host keyring for decryption");
|
||||
|
||||
let (clients, next_id) = clients::load_client_db("clients.json")?;
|
||||
|
||||
let clients_for_get = clients.clone();
|
||||
let get_existing_user = Box::new(move |id: u64| -> Option<mtp::crypto::PublicKeyBundle> {
|
||||
let result = clients_for_get.lock().unwrap().get(&id).cloned();
|
||||
if result.is_some() {
|
||||
println!("Auth lookup: client ID {id} found");
|
||||
} else {
|
||||
eprintln!("Auth lookup: unknown client ID {id}");
|
||||
}
|
||||
result
|
||||
});
|
||||
|
||||
let clients_for_register = clients.clone();
|
||||
let next_id_for_register = next_id.clone();
|
||||
let clients_path = "clients.json".to_string();
|
||||
let complete_register = Box::new(move |bundle: mtp::crypto::PublicKeyBundle| -> u64 {
|
||||
let mut db = clients_for_register.lock().unwrap();
|
||||
let mut nid = next_id_for_register.lock().unwrap();
|
||||
let id = *nid;
|
||||
*nid += 1;
|
||||
db.insert(id, bundle);
|
||||
match serde_json::to_string_pretty(&*db) {
|
||||
Ok(json) => match std::fs::write(&clients_path, json) {
|
||||
Ok(()) => {}
|
||||
Err(e) => eprintln!("Failed to persist client database to {clients_path}: {e}"),
|
||||
},
|
||||
Err(e) => eprintln!("Failed to serialize client database after registering {id}: {e}"),
|
||||
}
|
||||
println!("Registered new client with ID: {}", id);
|
||||
id
|
||||
});
|
||||
|
||||
println!("Starting MTP server on port 8080 ...");
|
||||
|
||||
let config = HostConfig {
|
||||
ip: std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED),
|
||||
port: 8080,
|
||||
tls_fullchain: cert_pem,
|
||||
tls_key: key_pem,
|
||||
require_authentication: true,
|
||||
host_id,
|
||||
host_keyring,
|
||||
get_existing_user,
|
||||
complete_register,
|
||||
};
|
||||
|
||||
let mut host = MTPHost::new(config).await?;
|
||||
println!("Server listening on {}", host.local_addr());
|
||||
|
||||
while let Some(conn) = host.accept().await {
|
||||
println!(
|
||||
"\n--- New authenticated connection (version {}) ---",
|
||||
conn.version
|
||||
);
|
||||
println!("Client ID: {}", conn.client_id);
|
||||
|
||||
let tm: &TypeMap = conn.codec.registry().get(&conn.version).unwrap();
|
||||
|
||||
match conn.receiver.receive().await {
|
||||
Ok(msg) => {
|
||||
println!("Received: {msg}");
|
||||
let response = handlers::process_and_respond(
|
||||
&msg,
|
||||
tm,
|
||||
conn.client_public_key.as_ref(),
|
||||
&decrypt_keyring,
|
||||
);
|
||||
println!("Sending: {response}");
|
||||
conn.sender.send(&response).await?;
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("Receive error: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
conn.sender.close();
|
||||
println!("Connection closed\n");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
70
example/server/src/tls.rs
Normal file
70
example/server/src/tls.rs
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use base64::Engine;
|
||||
|
||||
pub fn load_or_generate_tls(
|
||||
cert_path: &str,
|
||||
key_path: &str,
|
||||
) -> Result<(Vec<u8>, Vec<u8>), Box<dyn std::error::Error>> {
|
||||
if let (Ok(c), Ok(k)) = (fs::read(cert_path), fs::read(key_path)) {
|
||||
println!("Using existing TLS cert from {cert_path}");
|
||||
return Ok((c, k));
|
||||
}
|
||||
|
||||
println!("Generating self-signed TLS certificate ...");
|
||||
if let Some(parent) = Path::new(cert_path).parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
if let Some(parent) = Path::new(key_path).parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
let key_pair = rcgen::KeyPair::generate()?;
|
||||
let params = rcgen::CertificateParams::new(vec!["localhost".into(), "127.0.0.1".into()])?;
|
||||
let cert = params.self_signed(&key_pair)?;
|
||||
|
||||
let cert_str = cert.pem();
|
||||
let key_str = key_pair.serialize_pem();
|
||||
|
||||
fs::write(cert_path, cert_str.as_bytes())?;
|
||||
fs::write(key_path, key_str.as_bytes())?;
|
||||
println!("Wrote {cert_path} and {key_path}");
|
||||
|
||||
Ok((cert_str.into_bytes(), key_str.into_bytes()))
|
||||
}
|
||||
|
||||
pub fn certificate_sha256_hex(cert: &[u8]) -> Result<String, Box<dyn std::error::Error>> {
|
||||
let der = if cert.starts_with(b"-----BEGIN CERTIFICATE-----") {
|
||||
let pem = std::str::from_utf8(cert)?;
|
||||
let base64 = pem
|
||||
.lines()
|
||||
.filter(|line| !line.starts_with("-----"))
|
||||
.collect::<String>();
|
||||
base64::engine::general_purpose::STANDARD.decode(base64)?
|
||||
} else {
|
||||
cert.to_vec()
|
||||
};
|
||||
|
||||
Ok(hex::encode(mtp::crypto::sha256(&der)))
|
||||
}
|
||||
|
||||
pub fn export_webtransport_cert_hash(hash: &str) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let public_dir = if Path::new("web-client").exists() {
|
||||
Path::new("web-client/public")
|
||||
} else {
|
||||
Path::new("example/web-client/public")
|
||||
};
|
||||
fs::create_dir_all(public_dir)?;
|
||||
fs::write(public_dir.join("mtp_dev_cert_hash.txt"), hash)?;
|
||||
|
||||
let dev_cert_dir = if Path::new("dev-cert").exists() {
|
||||
Path::new("dev-cert")
|
||||
} else {
|
||||
Path::new("example/dev-cert")
|
||||
};
|
||||
if dev_cert_dir.exists() {
|
||||
fs::write(dev_cert_dir.join("sha256.txt"), hash)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Loading…
Reference in a new issue