Skip to content

Commit

Permalink
feat: move session_sk to a separate file in config (#501)
Browse files Browse the repository at this point in the history
* Move session_sk to a separate file in config
  • Loading branch information
Ma233 authored Dec 6, 2023
1 parent d5a1660 commit b5e75da
Show file tree
Hide file tree
Showing 8 changed files with 195 additions and 62 deletions.
20 changes: 15 additions & 5 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ resolver = "2"
members = ["core", "transport", "node", "rpc", "derive"]

[workspace.package]
version = "0.4.0"
version = "0.4.1"
edition = "2021"
license = "GPL-3.0"
authors = ["RND <[email protected]>"]
Expand Down
2 changes: 1 addition & 1 deletion core/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
//! let account_type = "secp256k1".to_string();
//! let account_entity = user_secret_key_did.to_string();
//!
//! let mut builder = SessionSkBuilder::new(account_entity, account_type);
//! let builder = SessionSkBuilder::new(account_entity, account_type);
//! let unsigned_proof = builder.unsigned_proof();
//!
//! // Sign the unsigned proof with user's secret key.
Expand Down
2 changes: 2 additions & 0 deletions node/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ node = [
"rings-transport/native-webrtc",
"wasmer/default",
"wasmer-types",
"home",
]
browser = [
"backtrace",
Expand Down Expand Up @@ -99,6 +100,7 @@ axum = { version = "0.6.10", optional = true }
backtrace = { version = "0.3.6", optional = true }
clap = { version = "4.0.14", features = ["derive", "env"], optional = true }
form_urlencoded = { version = "1.0.1", optional = true }
home = { version = "0.5.5", optional = true }
hyper = { version = "0.14.25", features = ["full"], optional = true }
lazy_static = { version = "1.4.0", optional = true }
opentelemetry = { version = "0.18.0", default-features = false, features = ["trace", "rt-tokio"], optional = true }
Expand Down
87 changes: 74 additions & 13 deletions node/bin/rings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ use futures::pin_mut;
use futures::select;
use futures::StreamExt;
use futures_timer::Delay;
use rings_core::dht::Did;
use rings_core::session::SessionSkBuilder;
use rings_node::backend::native::Backend;
use rings_node::backend::native::BackendConfig;
use rings_node::logging::init_logging;
Expand All @@ -25,6 +27,8 @@ use rings_node::prelude::PersistenceStorage;
use rings_node::processor::Processor;
use rings_node::processor::ProcessorBuilder;
use rings_node::processor::ProcessorConfig;
use rings_node::util::ensure_parent_dir;
use rings_node::util::expand_home;
use tokio::io;
use tokio::io::AsyncBufReadExt;

Expand All @@ -43,6 +47,8 @@ struct Cli {
enum Command {
#[command(about = "Initializes a node with the given configuration.")]
Init(InitCommand),
#[command(about = "Creates a new session secret key.")]
NewSession(NewSessionCommand),
#[command(about = "Starts a long-running node daemon.")]
Run(RunCommand),
#[command(about = "Provides chat room-like functionality on the Rings Network.")]
Expand Down Expand Up @@ -75,19 +81,21 @@ struct ConfigArgs {

#[derive(Args, Debug)]
struct InitCommand {
#[command(flatten)]
session_args: SessionArgs,

#[arg(
long,
default_value = "~/.rings/config.yaml",
help = "The location of config file"
)]
pub location: String,
}

#[arg(
long = "key",
short = 'k',
help = "Your ecdsa_key. If not provided, a new key will be generated"
)]
pub ecdsa_key: Option<SecretKey>,
#[derive(Args, Debug)]
struct NewSessionCommand {
#[command(flatten)]
session_args: SessionArgs,
}

#[derive(Args, Debug)]
Expand All @@ -102,7 +110,6 @@ struct RunCommand {

#[arg(
long,
short = 's',
help = "ICE server list. If not provided, use ice_servers in config file or stun://stun.l.google.com:19302",
env
)]
Expand Down Expand Up @@ -177,6 +184,59 @@ impl ClientArgs {
}
}

#[derive(Args, Debug)]
struct SessionArgs {
#[arg(
long,
short = 's',
default_value = "~/.rings/session_sk",
help = "The location of session_sk file"
)]
pub session_sk: String,

#[arg(
long,
short = 'k',
help = "Your ecdsa_key. If not provided, a random key will be used"
)]
pub ecdsa_key: Option<SecretKey>,

#[arg(
long,
default_value = "2592000",
help = "The ttl of session file in seconds"
)]
pub ttl: u64,
}

impl SessionArgs {
fn new_session_then_write_to_fs(&self) -> anyhow::Result<&std::path::Path> {
let key = self.ecdsa_key.unwrap_or_else(|| {
let rand_key = SecretKey::random();
println!("Your random ecdsa key is: {}", rand_key.to_string());
rand_key
});
let key_did: Did = key.address().into();

let ssk_builder = SessionSkBuilder::new(key_did.to_string(), "secp256k1".to_string())
.set_ttl(self.ttl * 1000);
let unsigned_proof = ssk_builder.unsigned_proof();

let sig = key.sign(&unsigned_proof).to_vec();
let ssk_builder = ssk_builder.set_session_sig(sig);

let ssk = ssk_builder.build()?;
let ssk_dump = ssk.dump()?;

let ssk_path = std::path::Path::new(&self.session_sk);
ensure_parent_dir(ssk_path)?;
std::fs::write(expand_home(ssk_path)?, ssk_dump)?;
println!("Your session_sk file has saved to: {}", ssk_path.display());

Ok(ssk_path)
}
}

#[derive(Subcommand, Debug)]
#[command(rename_all = "kebab-case")]
enum ConnectCommand {
Expand Down Expand Up @@ -553,15 +613,16 @@ async fn main() -> anyhow::Result<()> {
Ok(())
}
Command::Init(args) => {
let config = if let Some(key) = args.ecdsa_key {
config::Config::new_with_key(key)
} else {
config::Config::default()
};
let p = config.write_fs(args.location.as_str())?;
let session_sk_path = args.session_args.new_session_then_write_to_fs()?;
let config = config::Config::new(session_sk_path);
let p = config.write_fs(&args.location)?;
println!("Your config file has saved to: {}", p);
Ok(())
}
Command::NewSession(args) => {
args.session_args.new_session_then_write_to_fs()?;
Ok(())
}
Command::Inspect(args) => {
args.client_args
.new_client()
Expand Down
4 changes: 4 additions & 0 deletions node/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,10 @@ pub enum Error {
OpenFileError(String) = 901,
#[error("Acquire lock failed")]
Lock = 902,
#[error("Cannot find home directory")]
HomeDirError = 903,
#[error("Cannot find parent directory")]
ParentDirError = 904,
#[error("Serde json error: {0}")]
SerdeJsonError(#[from] serde_json::Error) = 1000,
#[error("Serde yaml error: {0}")]
Expand Down
60 changes: 18 additions & 42 deletions node/src/native/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ use crate::prelude::rings_core::ecc::SecretKey;
use crate::prelude::SessionSk;
use crate::processor::ProcessorConfig;
use crate::processor::ProcessorConfigSerialized;
use crate::util::ensure_parent_dir;
use crate::util::expand_home;

lazy_static::lazy_static! {
static ref DEFAULT_DATA_STORAGE_CONFIG: StorageConfig = StorageConfig {
Expand Down Expand Up @@ -55,6 +57,7 @@ pub struct Config {
pub endpoint_url: String,
pub ice_servers: String,
pub stabilize_timeout: usize,
#[serde(skip_serializing_if = "Option::is_none")]
pub external_ip: Option<String>,
/// When there is no configuration in the YAML file,
/// its deserialization is equivalent to `vec![]` in Rust.
Expand All @@ -78,12 +81,18 @@ impl TryFrom<Config> for ProcessorConfigSerialized {
.expect("create session sk failed")
.dump()
.expect("dump session sk failed")
} else if let Some(dk) = config.session_manager {
} else if let Some(ssk) = config.session_manager {
tracing::warn!("Field `session_manager` is deprecated, use `session_sk` instead.");
dk
ssk
} else {
config.session_sk.expect("session_sk is not set.")
let ssk_file = config.session_sk.expect("session_sk is not set.");
let ssk_file_expand_home = expand_home(&ssk_file)?;
fs::read_to_string(ssk_file_expand_home).unwrap_or_else(|e| {
tracing::warn!("Read session_sk file failed: {e:?}. Handling it as raw session_sk string. This mode is deprecated. please use a file path.");
ssk_file
})
};

if let Some(ext_ip) = config.external_ip {
Ok(Self::new_with_ext_addr(
config.ice_servers,
Expand Down Expand Up @@ -118,12 +127,9 @@ impl From<Config> for BackendConfig {
}

impl Config {
pub fn new_with_key(key: SecretKey) -> Self {
let session_sk = SessionSk::new_with_seckey(&key)
.expect("create session sk failed")
.dump()
.expect("dump session sk failed");

pub fn new<P>(session_sk: P) -> Self
where P: AsRef<std::path::Path> {
let session_sk = session_sk.as_ref().to_string_lossy().to_string();
Self {
ecdsa_key: None,
session_manager: None,
Expand All @@ -142,21 +148,8 @@ impl Config {

pub fn write_fs<P>(&self, path: P) -> Result<String>
where P: AsRef<std::path::Path> {
let path = match path.as_ref().strip_prefix("~") {
Ok(stripped) => {
let home_dir = env::var_os("HOME").map(PathBuf::from);
home_dir.map(|mut p| {
p.push(stripped);
p
})
}
Err(_) => Some(path.as_ref().to_owned()),
}
.unwrap();
let parent = path.parent().expect("no parent directory");
if !parent.is_dir() {
fs::create_dir_all(parent).map_err(|e| Error::CreateFileError(e.to_string()))?;
};
let path = expand_home(path)?;
ensure_parent_dir(&path)?;
let f =
fs::File::create(path.as_path()).map_err(|e| Error::CreateFileError(e.to_string()))?;
let f_writer = io::BufWriter::new(f);
Expand All @@ -166,31 +159,14 @@ impl Config {

pub fn read_fs<P>(path: P) -> Result<Config>
where P: AsRef<std::path::Path> {
let path = match path.as_ref().strip_prefix("~") {
Ok(stripped) => {
let home_dir = env::var_os("HOME").map(PathBuf::from);
home_dir.map(|mut p| {
p.push(stripped);
p
})
}
Err(_) => Some(path.as_ref().to_owned()),
}
.unwrap();
let path = expand_home(path)?;
tracing::debug!("Read config from: {:?}", path);
let f = fs::File::open(path).map_err(|e| Error::OpenFileError(e.to_string()))?;
let f_rdr = io::BufReader::new(f);
serde_yaml::from_reader(f_rdr).map_err(|_| Error::EncodeError)
}
}

impl Default for Config {
fn default() -> Self {
let ecdsa_key = SecretKey::random();
Self::new_with_key(ecdsa_key)
}
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct StorageConfig {
pub path: String,
Expand Down
Loading

0 comments on commit b5e75da

Please sign in to comment.