Add init_api_secure function (#206)

* adding initial version of init_secure_api

* rustfmt

* fix ECDH algo

* rustfmt

* trying to figure out best way of doing encryption

* refactor secure requests and responses into json-rpc responses, with base64 payload for encrypted messages

* rustfmt

* return proper errors from encrypted api, include tests covering encrypted API error cases

* rustfmt

* add test for normal error (unencrypted)

* rustfmt

* change ports for test, add foreign listener to V2 sanity tests, add ability to select owner api port via command line

* rustfmt

* turn it to 11

* explicit teardown after rpc tests

* update tests with explicit teardowns

* update tests to perform explicit teardown

* fix warnings, ensure all tests teardown

* log output to diagnose CI windows build failures

* disable owner api doctests on windows

* rustfmt
This commit is contained in:
Yeastplume
2019-08-19 13:05:21 +01:00
committed by GitHub
parent 62d976f9ef
commit a58cae651e
33 changed files with 1224 additions and 294 deletions
+4 -1
View File
@@ -15,10 +15,13 @@ failure_derive = "0.1"
log = "0.4"
uuid = { version = "0.7", features = ["serde", "v4"] }
serde = "1"
rand = "0.5"
serde_derive = "1"
serde_json = "1"
easy-jsonrpc = "0.5.1"
easy-jsonrpc-mw = "0.5.3"
chrono = { version = "0.4.4", features = ["serde"] }
ring = "0.13"
base64 = "0.9"
grin_wallet_libwallet = { path = "../libwallet", version = "2.1.0-beta.1" }
grin_wallet_config = { path = "../config", version = "2.1.0-beta.1" }
+8 -6
View File
@@ -20,13 +20,13 @@ use crate::libwallet::{
NodeVersionInfo, Slate, VersionInfo, VersionedSlate, WalletLCProvider,
};
use crate::{Foreign, ForeignCheckMiddlewareFn};
use easy_jsonrpc;
use easy_jsonrpc_mw;
/// Public definition used to generate Foreign jsonrpc api.
/// * When running `grin-wallet listen` with defaults, the V2 api is available at
/// `localhost:3415/v2/foreign`
/// * The endpoint only supports POST operations, with the json-rpc request as the body
#[easy_jsonrpc::rpc]
#[easy_jsonrpc_mw::rpc]
pub trait ForeignRpc {
/**
Networked version of [Foreign::check_version](struct.Foreign.html#method.check_version).
@@ -577,7 +577,7 @@ pub fn run_doctest_foreign(
init_tx: bool,
init_invoice_tx: bool,
) -> Result<Option<serde_json::Value>, String> {
use easy_jsonrpc::Handler;
use easy_jsonrpc_mw::Handler;
use grin_wallet_impls::test_framework::{self, LocalWalletClient, WalletProxy};
use grin_wallet_impls::{DefaultLCProvider, DefaultWalletImpl};
use grin_wallet_libwallet::{api_impl, WalletInst};
@@ -613,7 +613,7 @@ pub fn run_doctest_foreign(
let mut wallet1 =
Box::new(DefaultWalletImpl::<LocalWalletClient>::new(client1.clone()).unwrap())
as Box<
WalletInst<
dyn WalletInst<
'static,
DefaultLCProvider<LocalWalletClient, ExtKeychain>,
LocalWalletClient,
@@ -648,7 +648,7 @@ pub fn run_doctest_foreign(
let mut wallet2 =
Box::new(DefaultWalletImpl::<LocalWalletClient>::new(client2.clone()).unwrap())
as Box<
WalletInst<
dyn WalletInst<
'static,
DefaultLCProvider<LocalWalletClient, ExtKeychain>,
LocalWalletClient,
@@ -751,7 +751,9 @@ pub fn run_doctest_foreign(
};
api_foreign.doctest_mode = true;
let foreign_api = &api_foreign as &dyn ForeignRpc;
Ok(foreign_api.handle_request(request).as_option())
let res = foreign_api.handle_request(request).as_option();
let _ = fs::remove_dir_all(test_dir);
Ok(res)
}
#[doc(hidden)]
+3 -10
View File
@@ -43,6 +43,8 @@ mod owner;
mod owner_rpc;
mod owner_rpc_s;
mod types;
pub use crate::foreign::{Foreign, ForeignCheckMiddleware, ForeignCheckMiddlewareFn};
pub use crate::foreign_rpc::ForeignRpc;
pub use crate::owner::Owner;
@@ -53,13 +55,4 @@ pub use crate::foreign_rpc::foreign_rpc as foreign_rpc_client;
pub use crate::foreign_rpc::run_doctest_foreign;
pub use crate::owner_rpc::run_doctest_owner;
use grin_wallet_util::grin_core::libtx::secp_ser;
use util::secp::key::SecretKey;
/// Wrapper for API Tokens
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(transparent)]
pub struct Token {
#[serde(with = "secp_ser::option_seckey_serde")]
keychain_mask: Option<SecretKey>,
}
pub use types::{ECDHPubkey, EncryptedRequest, EncryptedResponse, EncryptionErrorResponse, Token};
+3
View File
@@ -54,6 +54,8 @@ where
pub wallet_inst: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
/// Flag to normalize some output during testing. Can mostly be ignored.
pub doctest_mode: bool,
/// Share ECDH key
pub shared_key: Arc<Mutex<Option<SecretKey>>>,
}
impl<'a, L, C, K> Owner<'a, L, C, K>
@@ -141,6 +143,7 @@ where
Owner {
wallet_inst,
doctest_mode: false,
shared_key: Arc::new(Mutex::new(None)),
}
}
+49 -40
View File
@@ -24,15 +24,15 @@ use crate::libwallet::{
};
use crate::util::Mutex;
use crate::{Owner, OwnerRpcS};
use easy_jsonrpc;
use easy_jsonrpc_mw;
use std::sync::Arc;
/// Public definition used to generate Owner jsonrpc api.
/// * When running `grin-wallet owner_api` with defaults, the V2 api is available at
/// `localhost:3420/v2/owner`
/// * The endpoint only supports POST operations, with the json-rpc request as the body
#[easy_jsonrpc::rpc]
pub trait OwnerRpc {
#[easy_jsonrpc_mw::rpc]
pub trait OwnerRpc: Sync + Send {
/**
Networked version of [Owner::accounts](struct.Owner.html#method.accounts).
@@ -1148,7 +1148,7 @@ pub trait OwnerRpc {
}
}
# "#
# ,false, 5 ,true, false, false);
# ,false, 0 ,false, false, false);
```
*/
fn verify_slate_messages(&self, slate: VersionedSlate) -> Result<(), ErrorKind>;
@@ -1370,7 +1370,7 @@ pub fn run_doctest_owner(
lock_tx: bool,
finalize_tx: bool,
) -> Result<Option<serde_json::Value>, String> {
use easy_jsonrpc::Handler;
use easy_jsonrpc_mw::Handler;
use grin_wallet_impls::test_framework::{self, LocalWalletClient, WalletProxy};
use grin_wallet_impls::{DefaultLCProvider, DefaultWalletImpl};
use grin_wallet_libwallet::{api_impl, WalletInst};
@@ -1404,7 +1404,7 @@ pub fn run_doctest_owner(
let mut wallet1 =
Box::new(DefaultWalletImpl::<LocalWalletClient>::new(client1.clone()).unwrap())
as Box<
WalletInst<
dyn WalletInst<
'static,
DefaultLCProvider<LocalWalletClient, ExtKeychain>,
LocalWalletClient,
@@ -1439,7 +1439,7 @@ pub fn run_doctest_owner(
let mut wallet2 =
Box::new(DefaultWalletImpl::<LocalWalletClient>::new(client2.clone()).unwrap())
as Box<
WalletInst<
dyn WalletInst<
'static,
DefaultLCProvider<LocalWalletClient, ExtKeychain>,
LocalWalletClient,
@@ -1547,13 +1547,15 @@ pub fn run_doctest_owner(
let mut api_owner = Owner::new(wallet1);
api_owner.doctest_mode = true;
if use_token {
let res = if use_token {
let owner_api = &api_owner as &dyn OwnerRpcS;
Ok(owner_api.handle_request(request).as_option())
owner_api.handle_request(request).as_option()
} else {
let owner_api = &api_owner as &dyn OwnerRpc;
Ok(owner_api.handle_request(request).as_option())
}
owner_api.handle_request(request).as_option()
};
let _ = fs::remove_dir_all(test_dir);
Ok(res)
}
#[doc(hidden)]
@@ -1563,39 +1565,46 @@ macro_rules! doctest_helper_json_rpc_owner_assert_response {
// create temporary wallet, run jsonrpc request on owner api of wallet, delete wallet, return
// json response.
// In order to prevent leaking tempdirs, This function should not panic.
use grin_wallet_api::run_doctest_owner;
use serde_json;
use serde_json::Value;
use tempfile::tempdir;
let dir = tempdir().map_err(|e| format!("{:#?}", e)).unwrap();
let dir = dir
.path()
.to_str()
.ok_or("Failed to convert tmpdir path to string.".to_owned())
// These cause LMDB to run out of disk space on CircleCI
// disable for now on windows
// TODO: Fix properly
#[cfg(not(target_os = "windows"))]
{
use grin_wallet_api::run_doctest_owner;
use serde_json;
use serde_json::Value;
use tempfile::tempdir;
let dir = tempdir().map_err(|e| format!("{:#?}", e)).unwrap();
let dir = dir
.path()
.to_str()
.ok_or("Failed to convert tmpdir path to string.".to_owned())
.unwrap();
let request_val: Value = serde_json::from_str($request).unwrap();
let expected_response: Value = serde_json::from_str($expected_response).unwrap();
let response = run_doctest_owner(
request_val,
dir,
$use_token,
$blocks_to_mine,
$perform_tx,
$lock_tx,
$finalize_tx,
)
.unwrap()
.unwrap();
let request_val: Value = serde_json::from_str($request).unwrap();
let expected_response: Value = serde_json::from_str($expected_response).unwrap();
let response = run_doctest_owner(
request_val,
dir,
$use_token,
$blocks_to_mine,
$perform_tx,
$lock_tx,
$finalize_tx,
)
.unwrap()
.unwrap();
if response != expected_response {
panic!(
"(left != right) \nleft: {}\nright: {}",
serde_json::to_string_pretty(&response).unwrap(),
serde_json::to_string_pretty(&expected_response).unwrap()
if response != expected_response {
panic!(
"(left != right) \nleft: {}\nright: {}",
serde_json::to_string_pretty(&response).unwrap(),
serde_json::to_string_pretty(&expected_response).unwrap()
);
}
}
};
}
+40 -4
View File
@@ -22,12 +22,15 @@ use crate::libwallet::{
OutputCommitMapping, Slate, SlateVersion, TxLogEntry, VersionedSlate, WalletInfo,
WalletLCProvider,
};
use crate::{Owner, Token};
use easy_jsonrpc;
use crate::util::secp::key::{PublicKey, SecretKey};
use crate::util::static_secp_instance;
use crate::{ECDHPubkey, Owner, Token};
use easy_jsonrpc_mw;
use rand::thread_rng;
/// Public definition used to generate Owner jsonrpc api.
/// Secure version, that should be used when running the owner API in 'Secure' Mode
#[easy_jsonrpc::rpc]
#[easy_jsonrpc_mw::rpc]
pub trait OwnerRpcS {
/**
Networked version of [Owner::accounts](struct.Owner.html#method.accounts).
@@ -1199,7 +1202,7 @@ pub trait OwnerRpcS {
}
}
# "#
# ,true, 5 ,true, false, false);
# ,true, 0 ,false, false, false);
```
*/
fn verify_slate_messages(&self, token: Token, slate: VersionedSlate) -> Result<(), ErrorKind>;
@@ -1300,6 +1303,13 @@ pub trait OwnerRpcS {
```
*/
fn node_height(&self, token: Token) -> Result<NodeHeightResult, ErrorKind>;
/**
Initializes the secure RPC-JSON API
(Documentation TBD)
*/
fn init_secure_api(&self, ecdh_pubkey: ECDHPubkey) -> Result<ECDHPubkey, ErrorKind>;
}
impl<'a, L, C, K> OwnerRpcS for Owner<'a, L, C, K>
@@ -1471,4 +1481,30 @@ where
fn node_height(&self, token: Token) -> Result<NodeHeightResult, ErrorKind> {
Owner::node_height(self, (&token.keychain_mask).as_ref()).map_err(|e| e.kind())
}
fn init_secure_api(&self, ecdh_pubkey: ECDHPubkey) -> Result<ECDHPubkey, ErrorKind> {
let secp_inst = static_secp_instance();
let secp = secp_inst.lock();
let sec_key = SecretKey::new(&secp, &mut thread_rng());
let mut shared_pubkey = ecdh_pubkey.ecdh_pubkey.clone();
shared_pubkey
.mul_assign(&secp, &sec_key)
.map_err(|e| ErrorKind::Secp(e))?;
let x_coord = shared_pubkey.serialize_vec(&secp, true);
let shared_key =
SecretKey::from_slice(&secp, &x_coord[1..]).map_err(|e| ErrorKind::Secp(e))?;
{
let mut s = self.shared_key.lock();
*s = Some(shared_key);
}
let pub_key =
PublicKey::from_secret_key(&secp, &sec_key).map_err(|e| ErrorKind::Secp(e))?;
Ok(ECDHPubkey {
ecdh_pubkey: pub_key,
})
}
}
+308
View File
@@ -0,0 +1,308 @@
// Copyright 2019 The Grin Developers
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::core::libtx::secp_ser;
use crate::libwallet::{Error, ErrorKind};
use crate::util::secp::key::{PublicKey, SecretKey};
use crate::util::{from_hex, to_hex};
use failure::ResultExt;
use base64;
use rand::{thread_rng, Rng};
use ring::aead;
use serde_json::{self, Value};
use std::collections::HashMap;
/// Wrapper for API Tokens
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(transparent)]
pub struct Token {
#[serde(with = "secp_ser::option_seckey_serde")]
/// Token to XOR mask against the stored wallet seed
pub keychain_mask: Option<SecretKey>,
}
/// Wrapper for ECDH Public keys
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(transparent)]
pub struct ECDHPubkey {
/// public key, flattened
#[serde(with = "secp_ser::pubkey_serde")]
pub ecdh_pubkey: PublicKey,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct EncryptedBody {
/// nonce used for encryption
pub nonce: String,
/// Encrypted base64 body request
pub body_enc: String,
}
impl EncryptedBody {
/// Encrypts and encodes json as base 64
pub fn from_json(json_in: &Value, enc_key: &SecretKey) -> Result<Self, Error> {
let mut to_encrypt = serde_json::to_string(&json_in)
.context(ErrorKind::APIEncryption(
"EncryptedBody Enc: Unable to encode JSON".to_owned(),
))?
.as_bytes()
.to_vec();
let sealing_key = aead::SealingKey::new(&aead::AES_256_GCM, &enc_key.0).context(
ErrorKind::APIEncryption("EncryptedBody Enc: Unable to create key".to_owned()),
)?;
let nonce: [u8; 12] = thread_rng().gen();
let suffix_len = aead::AES_256_GCM.tag_len();
for _ in 0..suffix_len {
to_encrypt.push(0);
}
aead::seal_in_place(&sealing_key, &nonce, &[], &mut to_encrypt, suffix_len).context(
ErrorKind::APIEncryption("EncryptedBody: Encryption Failed".to_owned()),
)?;
Ok(EncryptedBody {
nonce: to_hex(nonce.to_vec()),
body_enc: base64::encode(&to_encrypt),
})
}
/// return serialize JSON self
pub fn as_json_value(&self) -> Result<Value, Error> {
let res = serde_json::to_value(self).context(ErrorKind::APIEncryption(
"EncryptedBody: JSON serialization failed".to_owned(),
))?;
Ok(res)
}
/// return serialized JSON self as string
pub fn as_json_str(&self) -> Result<String, Error> {
let res = self.as_json_value()?;
let res = serde_json::to_string(&res).context(ErrorKind::APIEncryption(
"EncryptedBody: JSON String serialization failed".to_owned(),
))?;
Ok(res)
}
/// Return original request
pub fn decrypt(&self, dec_key: &SecretKey) -> Result<Value, Error> {
let mut to_decrypt = base64::decode(&self.body_enc).context(ErrorKind::APIEncryption(
"EncryptedBody Dec: Encrypted request contains invalid Base64".to_string(),
))?;
let opening_key = aead::OpeningKey::new(&aead::AES_256_GCM, &dec_key.0).context(
ErrorKind::APIEncryption("EncryptedBody Dec: Unable to create key".to_owned()),
)?;
let nonce = from_hex(self.nonce.clone()).context(ErrorKind::APIEncryption(
"EncryptedBody Dec: Invalid Nonce".to_string(),
))?;
aead::open_in_place(&opening_key, &nonce, &[], 0, &mut to_decrypt).context(
ErrorKind::APIEncryption(
"EncryptedBody Dec: Decryption Failed (is key correct?)".to_string(),
),
)?;
for _ in 0..aead::AES_256_GCM.tag_len() {
to_decrypt.pop();
}
let decrypted = String::from_utf8(to_decrypt).context(ErrorKind::APIEncryption(
"EncryptedBody Dec: Invalid UTF-8".to_string(),
))?;
Ok(
serde_json::from_str(&decrypted).context(ErrorKind::APIEncryption(
"EncryptedBody Dec: Invalid JSON".to_string(),
))?,
)
}
}
/// Wrapper for secure JSON requests
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct EncryptedRequest {
/// JSON RPC response
pub jsonrpc: String,
/// method
pub method: String,
/// id
pub id: u32,
/// Body params, which includes nonce and encrypted request
pub params: EncryptedBody,
}
impl EncryptedRequest {
/// from json
pub fn from_json(id: u32, json_in: &Value, enc_key: &SecretKey) -> Result<Self, Error> {
Ok(EncryptedRequest {
jsonrpc: "2.0".to_owned(),
method: "encrypted_request_v3".to_owned(),
id: id,
params: EncryptedBody::from_json(json_in, enc_key)?,
})
}
/// return serialize JSON self
pub fn as_json_value(&self) -> Result<Value, Error> {
let res = serde_json::to_value(self).context(ErrorKind::APIEncryption(
"EncryptedRequest: JSON serialization failed".to_owned(),
))?;
Ok(res)
}
/// return serialized JSON self as string
pub fn as_json_str(&self) -> Result<String, Error> {
let res = self.as_json_value()?;
let res = serde_json::to_string(&res).context(ErrorKind::APIEncryption(
"EncryptedRequest: JSON String serialization failed".to_owned(),
))?;
Ok(res)
}
/// Return decrypted body
pub fn decrypt(&self, dec_key: &SecretKey) -> Result<Value, Error> {
self.params.decrypt(dec_key)
}
}
/// Wrapper for secure JSON requests
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct EncryptedResponse {
/// JSON RPC response
pub jsonrpc: String,
/// id
pub id: u32,
/// result
pub result: HashMap<String, EncryptedBody>,
}
impl EncryptedResponse {
/// from json
pub fn from_json(id: u32, json_in: &Value, enc_key: &SecretKey) -> Result<Self, Error> {
let mut result_set = HashMap::new();
result_set.insert(
"Ok".to_string(),
EncryptedBody::from_json(json_in, enc_key)?,
);
Ok(EncryptedResponse {
jsonrpc: "2.0".to_owned(),
id: id,
result: result_set,
})
}
/// return serialize JSON self
pub fn as_json_value(&self) -> Result<Value, Error> {
let res = serde_json::to_value(self).context(ErrorKind::APIEncryption(
"EncryptedResponse: JSON serialization failed".to_owned(),
))?;
Ok(res)
}
/// return serialized JSON self as string
pub fn as_json_str(&self) -> Result<String, Error> {
let res = self.as_json_value()?;
let res = serde_json::to_string(&res).context(ErrorKind::APIEncryption(
"EncryptedResponse: JSON String serialization failed".to_owned(),
))?;
Ok(res)
}
/// Return decrypted body
pub fn decrypt(&self, dec_key: &SecretKey) -> Result<Value, Error> {
self.result.get("Ok").unwrap().decrypt(dec_key)
}
}
/// Wrapper for encryption error responses
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct EncryptionError {
/// code
pub code: i32,
/// message
pub message: String,
}
/// Wrapper for encryption error responses
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct EncryptionErrorResponse {
/// JSON RPC response
pub jsonrpc: String,
/// id
pub id: u32,
/// error
pub error: EncryptionError,
}
impl EncryptionErrorResponse {
/// Create new response
pub fn new(id: u32, code: i32, message: &str) -> Self {
EncryptionErrorResponse {
jsonrpc: "2.0".to_owned(),
id: id,
error: EncryptionError {
code: code,
message: message.to_owned(),
},
}
}
/// return serialized JSON self
pub fn as_json_value(&self) -> Value {
let res = serde_json::to_value(self).context(ErrorKind::APIEncryption(
"EncryptedResponse: JSON serialization failed".to_owned(),
));
match res {
Ok(r) => r,
// proverbial "should never happen"
Err(r) => serde_json::json!({
"json_rpc" : "2.0",
"id" : "1",
"error" : {
"message": format!("internal error serialising json error response {}", r),
"code": -32000
}
}
),
}
}
}
#[test]
fn encrypted_request() -> Result<(), Error> {
use crate::util::{from_hex, static_secp_instance};
let sec_key_str = "e00dcc4a009e3427c6b1e1a550c538179d46f3827a13ed74c759c860761caf1e";
let shared_key = {
let secp_inst = static_secp_instance();
let secp = secp_inst.lock();
let sec_key_bytes = from_hex(sec_key_str.to_owned()).unwrap();
SecretKey::from_slice(&secp, &sec_key_bytes)?
};
let req = serde_json::json!({
"jsonrpc": "2.0",
"method": "accounts",
"id": 1,
"params": {
"token": "d202964900000000d302964900000000d402964900000000d502964900000000"
}
});
let enc_req = EncryptedRequest::from_json(1, &req, &shared_key)?;
println!("{:?}", enc_req);
let dec_req = enc_req.decrypt(&shared_key)?;
println!("{:?}", dec_req);
assert_eq!(req, dec_req);
let enc_res = EncryptedResponse::from_json(1, &req, &shared_key)?;
println!("{:?}", enc_res);
println!("{:?}", enc_res.as_json_str()?);
let dec_res = enc_res.decrypt(&shared_key)?;
println!("{:?}", dec_res);
assert_eq!(req, dec_res);
Ok(())
}