Skip to content

Commit

Permalink
Sign rpc request by session_manager
Browse files Browse the repository at this point in the history
  • Loading branch information
Ma233 committed Jul 15, 2023
1 parent 336e36a commit e6da325
Show file tree
Hide file tree
Showing 10 changed files with 57 additions and 50 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

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

5 changes: 3 additions & 2 deletions node/bin/rings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ use rings_node::native::endpoint::run_http_api;
use rings_node::prelude::http;
use rings_node::prelude::rings_core::ecc::SecretKey;
use rings_node::prelude::PersistenceStorage;
use rings_node::prelude::SessionManager;
use rings_node::processor::Processor;
use rings_node::processor::ProcessorBuilder;
use rings_node::processor::ProcessorConfig;
Expand Down Expand Up @@ -174,8 +175,8 @@ impl ClientArgs {
let c = config::Config::read_fs(self.config_args.config.as_str())?;

let endpoint_url = self.endpoint_url.as_ref().unwrap_or(&c.endpoint_url);

Client::new(endpoint_url.as_str(), "")
let session_manager = SessionManager::from_str(&c.session_manager)?;
Client::new(endpoint_url.as_str(), session_manager)
}
}

Expand Down
2 changes: 1 addition & 1 deletion node/src/browser/jsonrpc_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ impl JsonRpcClient {
/// Create a new `JsonRpcClient`
#[wasm_bindgen(constructor)]
pub fn new(node: String) -> JsonRpcClient {
let client = Arc::new(jsonrpc_client::SimpleClient::new_with_url(node.as_str()));
let client = Arc::new(jsonrpc_client::SimpleClient::new(node.as_str(), None));
JsonRpcClient { client }
}

Expand Down
2 changes: 2 additions & 0 deletions node/src/jsonrpc/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ pub(crate) async fn node_info(_: Params, meta: RpcMeta) -> Result<Value> {

/// Connect Peer VIA http
pub(crate) async fn connect_peer_via_http(params: Params, meta: RpcMeta) -> Result<Value> {
meta.require_authed()?;
let p: Vec<String> = params.parse()?;
let peer_url = p
.first()
Expand All @@ -125,6 +126,7 @@ pub(crate) async fn connect_peer_via_http(params: Params, meta: RpcMeta) -> Resu

/// Connect Peer with seed
pub(crate) async fn connect_with_seed(params: Params, meta: RpcMeta) -> Result<Value> {
meta.require_authed()?;
let p: Vec<Seed> = params.parse()?;
let seed = p
.first()
Expand Down
7 changes: 3 additions & 4 deletions node/src/native/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ use serde_json::json;

use crate::prelude::http;
use crate::prelude::rings_core::inspect::SwarmInspect;
use crate::prelude::rings_core::session::SessionManager;
use crate::prelude::rings_rpc::client::Client as RpcClient;
use crate::prelude::rings_rpc::types::Timeout;
use crate::seed::Seed;
Expand All @@ -37,7 +38,6 @@ use crate::util::loader::ResourceLoader;
type Output<T> = anyhow::Result<ClientOutput<T>>;

/// Wrap json_client send request between nodes or browsers.
#[derive(Clone)]
pub struct Client {
client: RpcClient,
}
Expand All @@ -51,9 +51,8 @@ pub struct ClientOutput<T> {

impl Client {
/// Creates a new Client instance with the specified endpoint URL and signature.
pub fn new(endpoint_url: &str, signature: &str) -> anyhow::Result<Self> {
let rpc_client =
RpcClient::new(endpoint_url, signature).map_err(|e| anyhow::anyhow!("{}", e))?;
pub fn new(endpoint_url: &str, session_manager: SessionManager) -> anyhow::Result<Self> {
let rpc_client = RpcClient::new(endpoint_url, Some(session_manager));
Ok(Self { client: rpc_client })
}

Expand Down
21 changes: 18 additions & 3 deletions node/src/native/endpoint/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,9 +101,24 @@ async fn jsonrpc_io_handler(
body: String,
) -> Result<JsonResponse, HttpError> {
let is_auth = if let Some(signature) = headermap.get("X-SIGNATURE") {
// TODO: check signature
tracing::debug!("signature: {:?}", signature);
true
let sig = base64::decode(signature).map_err(|e| {
tracing::debug!("signature: {:?}", signature);
tracing::error!("signature decode failed: {:?}", e);
HttpError::BadRequest
})?;
state
.processor
.swarm
.session_manager()
.session()
.verify(&body, sig)
.map_err(|e| {
tracing::debug!("body: {:?}", body);
tracing::debug!("signature: {:?}", signature);
tracing::error!("signature verify failed: {:?}", e);
e
})
.is_ok()
} else {
false
};
Expand Down
2 changes: 1 addition & 1 deletion node/src/processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ impl Processor {
// request remote offer and sand answer to remote
tracing::debug!("connect_peer_via_http: {}", peer_url);

let client = SimpleClient::new_with_url(peer_url);
let client = SimpleClient::new(peer_url, None);
let (_, offer) = self
.swarm
.create_offer()
Expand Down
3 changes: 2 additions & 1 deletion rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,13 @@ wasm = [
]

[dependencies]
base64 = { version = "0.13.0" }
http = { version = "0.2.6" }
jsonrpc-core = { version = "18.0.0" }
jsonrpc-pubsub = { version = "18.0.0" }
reqwest = { version = "0.11", features = ["json", "rustls-tls"], optional = true, default-features = false }
reqwest-wasm = { version = "0.11", features = ["json", "rustls-tls"], optional = true, default-features = false }
rings-core = { package = "rings-core", path = "../core", optional = true, default-features = false, version = "0.2.5" }
rings-core = { workspace = true, optional = true }
serde = { version = "1.0.136", features = ["derive"] }
serde_json = "1.0.70"
thiserror = "1"
26 changes: 6 additions & 20 deletions rpc/src/client.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
//! rings-rpc client

use std::sync::Arc;

use rings_core::session::SessionManager;
use serde_json::json;
use serde_json::Value;

Expand All @@ -17,29 +16,16 @@ use crate::types;
use crate::types::Timeout;

/// Wrap json_client send request between nodes or browsers.
#[derive(Clone)]
pub struct Client {
client: SimpleClient,
}

impl Client {
/// Creates a new Client instance with the specified endpoint URL and signature.
pub fn new(endpoint_url: &str, signature: &str) -> Result<Self> {
let mut default_headers = reqwest::header::HeaderMap::default();
default_headers.insert(
"X-SIGNATURE",
http::header::HeaderValue::from_str(signature).map_err(|_| Error::InvalidSignature)?,
);
let client = SimpleClient::new(
Arc::new(
reqwest::Client::builder()
.default_headers(default_headers)
.build()
.map_err(|_| Error::InvalidHeaders)?,
),
endpoint_url,
);
Ok(Self { client })
/// Creates a new Client instance with the specified endpoint URL
pub fn new(endpoint_url: &str, session_manager: Option<SessionManager>) -> Self {
Self {
client: SimpleClient::new(endpoint_url, session_manager),
}
}

/// Establishes a WebRTC connection with a remote peer using HTTP as the signaling channel.
Expand Down
38 changes: 20 additions & 18 deletions rpc/src/jsonrpc_client/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@
//! SimpleClient for jsonrpc request use reqwest::Client.
///
/// Sample:
/// let client = Simpleclient::new(reqwest::Client::default(), "http://localhost:5000");
/// let client = Simpleclient::new("http://localhost:5000", session_manager);
/// client.call_method("test", params);
use std::sync::Arc;

use jsonrpc_core::Error;
use jsonrpc_core::Params;
use jsonrpc_core::Value;
use rings_core::session::SessionManager;

use super::request::parse_response;
use super::request::RequestBuilder;
Expand All @@ -17,28 +16,21 @@ use crate::prelude::reqwest::Client as HttpClient;
/// Create a new SimpleClient
/// * client: a instance of reqwest::Client
/// * url: remote jsonrpc_server url
#[derive(Clone)]
pub struct SimpleClient {
client: Arc<HttpClient>,
client: HttpClient,
url: String,
session_manager: Option<SessionManager>,
}

impl SimpleClient {
/// * client: reqwest::Client handle http request.
/// * url: remote json_server url.
pub fn new(client: Arc<HttpClient>, url: &str) -> Self {
/// * session_key: session_key for sign request.
pub fn new(url: &str, session_manager: Option<SessionManager>) -> Self {
Self {
client,
url: url.to_owned(),
}
}

/// Create a new SimpleClient,
/// * url: remote jsonrpc_server url
pub fn new_with_url(url: &str) -> Self {
Self {
client: Arc::new(HttpClient::default()),
client: HttpClient::default(),
url: url.to_string(),
session_manager,
}
}

Expand Down Expand Up @@ -73,7 +65,7 @@ impl SimpleClient {
}
};

let resp = self
let mut req = self
.client
.post(self.url.as_str())
.header(
Expand All @@ -84,7 +76,17 @@ impl SimpleClient {
http::header::ACCEPT,
http::header::HeaderValue::from_static("application/json"),
)
.body(request)
.body(request.clone());

if let Some(session_manager) = &self.session_manager {
let sig = session_manager
.sign(&request.clone())
.map_err(|e| RpcError::Client(format!("Failed to sign request: {}", e)))?;
let encoded_sig = base64::encode(sig);
req = req.header("X-SIGNATURE", encoded_sig);
}

let resp = req
.send()
.await
.map_err(|e| RpcError::Client(e.to_string()))?;
Expand Down

0 comments on commit e6da325

Please sign in to comment.