tester and esp32 create signed timestamp for auth

This commit is contained in:
Evan Feenstra
2022-09-16 12:30:33 -07:00
parent 5de335c797
commit aeb48e36c3
8 changed files with 48 additions and 40 deletions

View File

@@ -13,8 +13,6 @@ use std::sync::Arc;
use std::sync::{LazyLock, Mutex}; use std::sync::{LazyLock, Mutex};
use std::time::Duration; use std::time::Duration;
const USERNAME: &str = "sphinx-key";
const PASSWORD: &str = "sphinx-key-pass";
// must get a reply within this time, or disconnects // must get a reply within this time, or disconnects
const REPLY_TIMEOUT_MS: u64 = 10000; const REPLY_TIMEOUT_MS: u64 = 10000;
@@ -148,9 +146,7 @@ fn metrics_to_status(metrics: ConnectionMetrics, client_connected: bool) -> Opti
fn config(settings: &Settings) -> Config { fn config(settings: &Settings) -> Config {
use librumqttd::rumqttlog::Config as RouterConfig; use librumqttd::rumqttlog::Config as RouterConfig;
use librumqttd::{ use librumqttd::{ConnectionSettings, ConsoleSettings, ServerSettings};
ConnectionLoginCredentials, ConnectionSettings, ConsoleSettings, ServerSettings,
};
use std::collections::HashMap; use std::collections::HashMap;
use std::net::{Ipv4Addr, SocketAddrV4}; use std::net::{Ipv4Addr, SocketAddrV4};
use std::path::PathBuf; use std::path::PathBuf;
@@ -176,10 +172,8 @@ fn config(settings: &Settings) -> Config {
max_payload_size: 5120, max_payload_size: 5120,
max_inflight_count: 200, max_inflight_count: 200,
max_inflight_size: 1024, max_inflight_size: 1024,
login_credentials: Some(vec![ConnectionLoginCredentials { login_credentials: None,
username: USERNAME.to_string(), sphinx_auth: true,
password: PASSWORD.to_string(),
}]),
}, },
}, },
); );

View File

@@ -8,7 +8,7 @@ vls-protocol = { git = "https://gitlab.com/lightning-signer/validating-lightning
serde = { version = "1.0", default-features = false } serde = { version = "1.0", default-features = false }
rmp-serde = "1.1.0" rmp-serde = "1.1.0"
serde_bolt = { version = "0.2", default-features = false } serde_bolt = { version = "0.2", default-features = false }
sphinx-auther = "0.1.10" sphinx-auther = "0.1.12"
sphinx-glyph = "0.1.0" sphinx-glyph = "0.1.0"
anyhow = "1" anyhow = "1"

View File

@@ -1,6 +1,7 @@
use anyhow::Result; use anyhow::Result;
use sphinx_auther::nonce; use sphinx_auther::nonce;
use sphinx_auther::secp256k1::{PublicKey, SecretKey}; use sphinx_auther::secp256k1::{PublicKey, SecretKey};
use sphinx_auther::token::Token;
pub use sphinx_glyph::types::{Config, ControlMessage, ControlResponse, Interval, Policy}; pub use sphinx_glyph::types::{Config, ControlMessage, ControlResponse, Interval, Policy};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
@@ -21,6 +22,16 @@ impl Controller {
let nonce = store.read_nonce().unwrap_or(0); let nonce = store.read_nonce().unwrap_or(0);
Self(sk, pk, nonce, per) Self(sk, pk, nonce, per)
} }
pub fn make_auth_token(&self) -> Result<String> {
let t = Token::new();
Ok(t.sign_to_base64(&self.0)?)
}
pub fn pubkey(&self) -> PublicKey {
self.1
}
pub fn nonce(&self) -> u64 {
self.2
}
pub fn build_msg(&mut self, msg: ControlMessage) -> anyhow::Result<Vec<u8>> { pub fn build_msg(&mut self, msg: ControlMessage) -> anyhow::Result<Vec<u8>> {
let data = rmp_serde::to_vec(&msg)?; let data = rmp_serde::to_vec(&msg)?;
self.2 = self.2 + 1; self.2 = self.2 + 1;

4
sphinx-key/Cargo.lock generated
View File

@@ -1971,9 +1971,9 @@ dependencies = [
[[package]] [[package]]
name = "sphinx-auther" name = "sphinx-auther"
version = "0.1.10" version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "452ac3986f03e8d403a21f81883d0f5058152af4ae006a26ee00e3a31af20302" checksum = "33bd24149ede6f4ec091326eacf550cfa3fc00492d4e627a045c1bd690255362"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"base64", "base64",

View File

@@ -13,13 +13,13 @@ use log::*;
use std::sync::mpsc; use std::sync::mpsc;
use std::thread; use std::thread;
pub const USERNAME: &str = "sphinx-key";
pub const PASSWORD: &str = "sphinx-key-pass";
pub const QOS: QoS = QoS::AtMostOnce; pub const QOS: QoS = QoS::AtMostOnce;
pub fn make_client( pub fn make_client(
broker: &str, broker: &str,
client_id: &str, client_id: &str,
username: &str,
password: &str,
) -> Result<( ) -> Result<(
EspMqttClient<ConnState<MessageImpl, EspError>>, EspMqttClient<ConnState<MessageImpl, EspError>>,
MqttConnection<Condvar, MessageImpl, EspError>, MqttConnection<Condvar, MessageImpl, EspError>,
@@ -29,8 +29,8 @@ pub fn make_client(
client_id: Some(client_id), client_id: Some(client_id),
buffer_size: 4096, buffer_size: 4096,
task_stack: 12288, task_stack: 12288,
username: Some(USERNAME), username: Some(username),
password: Some(PASSWORD), password: Some(password),
// FIXME - mqtts // FIXME - mqtts
// crt_bundle_attach: Some(esp_idf_sys::esp_crt_bundle_attach), // crt_bundle_attach: Some(esp_idf_sys::esp_crt_bundle_attach),
..Default::default() ..Default::default()

View File

@@ -1,11 +1,10 @@
use crate::conn::mqtt::QOS; use crate::conn::mqtt::QOS;
use crate::core::control::{controller_from_seed, FlashPersister};
use sphinx_key_signer::control::{Config, ControlMessage, ControlResponse, Policy}; use sphinx_key_signer::control::{Config, ControlMessage, ControlResponse, Controller, Policy};
use sphinx_key_signer::lightning_signer::bitcoin::Network; use sphinx_key_signer::lightning_signer::bitcoin::Network;
use sphinx_key_signer::vls_protocol::model::PubKey; use sphinx_key_signer::vls_protocol::model::PubKey;
use sphinx_key_signer::{self, make_init_msg, topics, InitResponse, ParserError, RootHandler}; use sphinx_key_signer::{self, make_init_msg, topics, InitResponse, ParserError, RootHandler};
use std::sync::{mpsc, Arc, Mutex}; use std::sync::mpsc;
use embedded_svc::httpd::Result; use embedded_svc::httpd::Result;
use embedded_svc::mqtt::client::utils::ConnState; use embedded_svc::mqtt::client::utils::ConnState;
@@ -46,7 +45,7 @@ pub fn make_event_loop(
config: Config, config: Config,
seed: [u8; 32], seed: [u8; 32],
policy: &Policy, policy: &Policy,
flash: Arc<Mutex<FlashPersister>>, mut ctrlr: Controller,
) -> Result<()> { ) -> Result<()> {
while let Ok(event) = rx.recv() { while let Ok(event) = rx.recv() {
log::info!("BROKER IP AND PORT: {}", config.broker); log::info!("BROKER IP AND PORT: {}", config.broker);
@@ -72,9 +71,6 @@ pub fn make_event_loop(
init_reply: _, init_reply: _,
} = sphinx_key_signer::init(init_msg, network, policy).expect("failed to init signer"); } = sphinx_key_signer::init(init_msg, network, policy).expect("failed to init signer");
// make the controller to validate Control messages
let mut ctrlr = controller_from_seed(&network, &seed[..], flash);
// signing loop // signing loop
let dummy_peer = PubKey([0; 33]); let dummy_peer = PubKey([0; 33]);
while let Ok(event) = rx.recv() { while let Ok(event) = rx.recv() {
@@ -179,7 +175,7 @@ pub fn make_event_loop(
_config: Config, _config: Config,
_seed: [u8; 32], _seed: [u8; 32],
_policy: &Policy, _policy: &Policy,
_flash: Arc<Mutex<FlashPersister>>, mut _ctrlr: Controller,
) -> Result<()> { ) -> Result<()> {
log::info!("About to subscribe to the mpsc channel"); log::info!("About to subscribe to the mpsc channel");
while let Ok(event) = rx.recv() { while let Ok(event) = rx.recv() {

View File

@@ -3,7 +3,7 @@ mod conn;
mod core; mod core;
mod periph; mod periph;
use crate::core::control::FlashPersister; use crate::core::control::{controller_from_seed, FlashPersister};
use crate::core::{config::*, events::*}; use crate::core::{config::*, events::*};
use crate::periph::led::led_control_loop; use crate::periph::led::led_control_loop;
#[allow(unused_imports)] #[allow(unused_imports)]
@@ -122,11 +122,7 @@ fn make_and_launch_client(
flash: Arc<Mutex<FlashPersister>>, flash: Arc<Mutex<FlashPersister>>,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
let (tx, rx) = mpsc::channel(); let (tx, rx) = mpsc::channel();
let (mqtt, connection) = conn::mqtt::make_client(&config.broker, CLIENT_ID)?;
let mqtt_client = conn::mqtt::start_listening(mqtt, connection, tx)?;
// this blocks forever... the "main thread"
let do_log = true;
let network = match config.network.as_str() { let network = match config.network.as_str() {
"bitcoin" => Network::Bitcoin, "bitcoin" => Network::Bitcoin,
"mainnet" => Network::Bitcoin, "mainnet" => Network::Bitcoin,
@@ -135,9 +131,21 @@ fn make_and_launch_client(
"regtest" => Network::Regtest, "regtest" => Network::Regtest,
_ => Network::Regtest, _ => Network::Regtest,
}; };
// make the controller to validate Control messages
let ctrlr = controller_from_seed(&network, &seed[..], flash);
let pubkey = hex::encode(ctrlr.pubkey().serialize());
let token = ctrlr.make_auth_token().expect("couldnt make auth token");
let (mqtt, connection) = conn::mqtt::make_client(&config.broker, CLIENT_ID, &pubkey, &token)?;
let mqtt_client = conn::mqtt::start_listening(mqtt, connection, tx)?;
// this blocks forever... the "main thread"
let do_log = true;
log::info!("Network set to {:?}", network); log::info!("Network set to {:?}", network);
log::info!(">>>>>>>>>>> blocking forever..."); log::info!(">>>>>>>>>>> blocking forever...");
log::info!("{:?}", config); log::info!("{:?}", config);
make_event_loop( make_event_loop(
mqtt_client, mqtt_client,
rx, rx,
@@ -147,7 +155,7 @@ fn make_and_launch_client(
config, config,
seed, seed,
policy, policy,
flash, ctrlr,
)?; )?;
Ok(()) Ok(())
} }

View File

@@ -14,9 +14,6 @@ use std::error::Error;
use std::str::FromStr; use std::str::FromStr;
use std::time::Duration; use std::time::Duration;
const USERNAME: &str = "sphinx-key";
const PASSWORD: &str = "sphinx-key-pass";
#[tokio::main(worker_threads = 1)] #[tokio::main(worker_threads = 1)]
async fn main() -> Result<(), Box<dyn Error>> { async fn main() -> Result<(), Box<dyn Error>> {
setup_logging("sphinx-key-tester ", "info"); setup_logging("sphinx-key-tester ", "info");
@@ -37,9 +34,17 @@ async fn main() -> Result<(), Box<dyn Error>> {
// main loop - alternate between "reconnection" and "handler" // main loop - alternate between "reconnection" and "handler"
loop { loop {
let mut try_i = 0; let mut try_i = 0;
let network = Network::Regtest;
let seed_string: String = env::var("SEED").expect("no seed");
let seed = hex::decode(seed_string).expect("couldnt decode seed");
// make the controller to validate Control messages
let mut ctrlr = controller_from_seed(&network, &seed);
let pubkey = hex::encode(&ctrlr.pubkey().serialize());
let token = ctrlr.make_auth_token()?;
let (client, mut eventloop) = loop { let (client, mut eventloop) = loop {
let mut mqttoptions = MqttOptions::new("test-1", "localhost", 1883); let mut mqttoptions = MqttOptions::new("test-1", "localhost", 1883);
mqttoptions.set_credentials(USERNAME, PASSWORD); mqttoptions.set_credentials(pubkey.clone(), token.clone());
mqttoptions.set_keep_alive(Duration::from_secs(5)); mqttoptions.set_keep_alive(Duration::from_secs(5));
let (client, mut eventloop) = AsyncClient::new(mqttoptions, 10); let (client, mut eventloop) = AsyncClient::new(mqttoptions, 10);
match eventloop.poll().await { match eventloop.poll().await {
@@ -66,12 +71,6 @@ async fn main() -> Result<(), Box<dyn Error>> {
.await .await
.expect("could not mqtt subscribe"); .expect("could not mqtt subscribe");
let network = Network::Regtest;
let seed_string: String = env::var("SEED").expect("no seed");
let seed = hex::decode(seed_string).expect("couldnt decode seed");
// make the controller to validate Control messages
let mut ctrlr = controller_from_seed(&network, &seed);
if is_test { if is_test {
// test handler loop // test handler loop
loop { loop {