teaclave-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ms...@apache.org
Subject [incubator-mesatee] branch master updated: [services/kms] Use protobuf to define and generate KMS protocol (#112)
Date Tue, 03 Dec 2019 01:03:13 GMT
This is an automated email from the ASF dual-hosted git repository.

mssun pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-mesatee.git


The following commit(s) were added to refs/heads/master by this push:
     new 64d76d0  [services/kms] Use protobuf to define and generate KMS protocol (#112)
64d76d0 is described below

commit 64d76d0bb46d37694066e87c006ba089c5c4e667
Author: TX <litongxin1991@gmail.com>
AuthorDate: Mon Dec 2 17:03:03 2019 -0800

    [services/kms] Use protobuf to define and generate KMS protocol (#112)
---
 cmake/tomls/Cargo.sgx_trusted_lib.toml             |   4 +
 mesatee_core/src/error.rs                          |   5 +
 mesatee_services/common/prost_build_generator.rs   | 210 +++++++++++++++++++++
 mesatee_services/kms/client/Cargo.toml             |  22 ---
 mesatee_services/kms/client/src/kms_client.rs      |  68 -------
 mesatee_services/kms/proto/Cargo.toml              |   6 +
 .../kms/{client/src/lib.rs => proto/build.rs}      |  34 +++-
 mesatee_services/kms/proto/src/kms.proto           |  54 ++++++
 mesatee_services/kms/proto/src/kms.rs              | 207 ++++++++++++++++++++
 mesatee_services/kms/proto/src/lib.rs              |  33 +++-
 .../kms/proto/src/prost_generated/kms_proto.rs     | 151 +++++++++++++++
 mesatee_services/kms/proto/src/proto.rs            | 166 ----------------
 mesatee_services/kms/sgx_app/Cargo.toml            |   3 +
 mesatee_services/kms/sgx_trusted_lib/Cargo.toml    |   1 +
 mesatee_services/kms/sgx_trusted_lib/src/kms.rs    |  97 ++++------
 mesatee_services/tdfs/external/proto/src/key.rs    |   2 +-
 mesatee_services/tdfs/external/proto/src/lib.rs    |   2 +-
 mesatee_services/tdfs/external/proto/src/proto.rs  |  10 +-
 mesatee_services/tdfs/internal/client/Cargo.toml   |   4 +-
 .../tdfs/internal/client/src/tdfs_client.rs        |  12 +-
 mesatee_services/tdfs/internal/proto/src/proto.rs  |   6 +-
 mesatee_services/tdfs/sgx_trusted_lib/Cargo.toml   |   5 +-
 .../tdfs/sgx_trusted_lib/src/tdfs_external.rs      |  33 +++-
 .../tdfs/sgx_trusted_lib/src/tdfs_internal.rs      |  14 +-
 tests/functional_test/sgx_trusted_lib/Cargo.toml   |   4 +-
 .../sgx_trusted_lib/src/tests/common_setup.rs      |   2 +-
 .../sgx_trusted_lib/src/tests/kms_test.rs          |  17 +-
 27 files changed, 809 insertions(+), 363 deletions(-)

diff --git a/cmake/tomls/Cargo.sgx_trusted_lib.toml b/cmake/tomls/Cargo.sgx_trusted_lib.toml
index 3022578..1dc5378 100644
--- a/cmake/tomls/Cargo.sgx_trusted_lib.toml
+++ b/cmake/tomls/Cargo.sgx_trusted_lib.toml
@@ -88,3 +88,7 @@ webpki            = { git = "https://github.com/mesalock-linux/webpki", branch =
 webpki-roots      = { git = "https://github.com/mesalock-linux/webpki-roots", branch = "mesalock_sgx" }
 yasna             = { git = "https://github.com/mesalock-linux/yasna.rs-sgx" }
 rusty-machine     = { git = "https://github.com/mesalock-linux/rusty-machine-sgx" }
+prost-build       = { git = "https://github.com/mesalock-linux/prost-build-sgx-fake"}
+bytes        = { git = "https://github.com/mesalock-linux/bytes-sgx" }
+prost        = { git = "https://github.com/mesalock-linux/prost-sgx" }
+prost-types  = { git = "https://github.com/mesalock-linux/prost-sgx" }
diff --git a/mesatee_core/src/error.rs b/mesatee_core/src/error.rs
index f92c278..1ed297c 100644
--- a/mesatee_core/src/error.rs
+++ b/mesatee_core/src/error.rs
@@ -122,6 +122,8 @@ pub enum ErrorKind {
     MsgSizeLimitExceedError,
     /// Unhandled MesaPy exception encountered
     MesaPyError,
+    /// RPC input/output is invalid.
+    RpcProtocolError,
     /// Others.
     Unknown,
 }
@@ -195,6 +197,7 @@ impl ErrorKind {
             ErrorKind::NoValidWorkerError => "no valid worker error",
             ErrorKind::MsgSizeLimitExceedError => "message size exceeds limit",
             ErrorKind::MesaPyError => "unhandled mesapy exception",
+            ErrorKind::RpcProtocolError => "invalid rpc protocol",
             ErrorKind::Unknown => "unknown error",
         }
     }
@@ -247,6 +250,7 @@ impl From<u32> for Error {
             0x0000_1012 => ErrorKind::NoValidWorkerError,
             0x0000_1013 => ErrorKind::MsgSizeLimitExceedError,
             0x0000_1014 => ErrorKind::MesaPyError,
+            0x0000_1015 => ErrorKind::RpcProtocolError,
             _ => ErrorKind::Unknown,
         };
 
@@ -295,6 +299,7 @@ impl Into<u32> for Error {
             ErrorKind::NoValidWorkerError => 0x0000_1012,
             ErrorKind::MsgSizeLimitExceedError => 0x0000_1013,
             ErrorKind::MesaPyError => 0x0000_1014,
+            ErrorKind::RpcProtocolError => 0x0000_1015,
             ErrorKind::Unknown => 0xffff_ffff,
         }
     }
diff --git a/mesatee_services/common/prost_build_generator.rs b/mesatee_services/common/prost_build_generator.rs
new file mode 100644
index 0000000..4bbcb8f
--- /dev/null
+++ b/mesatee_services/common/prost_build_generator.rs
@@ -0,0 +1,210 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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 prost_build;
+use std::path::PathBuf;
+
+#[derive(Debug)]
+pub struct MesaTEEServiceGenerator;
+
+/// How to use prost. See kms as an example.
+/// 1. Define rpc messages with protobuf 2/3 syntax. protobuf 2 is recommended because we can avoid unneccessary option.
+/// 2. Define services. Prost will generate corresponding sevices and clients.
+/// 3. Include ```prost_build_generator.rs``` and modify ```main function``` in the ```build.rs``` of the target library.  
+/// 4. Todo: add support for automatic authentication
+const LINE_ENDING: &'static str = "\n";
+impl MesaTEEServiceGenerator {
+    fn generate_structure(&mut self, service: &prost_build::Service, buf: &mut String) {
+        let request_name = format!("{}{}", &service.proto_name, "Request");
+        let response_name = format!("{}{}", &service.proto_name, "Response");
+        // Generate request enum structure
+        buf.push_str("#[derive(Clone, serde_derive::Serialize, serde_derive::Deserialize, Debug)]");
+        buf.push_str(LINE_ENDING);
+        buf.push_str(r#"#[serde(tag = "type")]"#);
+
+        buf.push_str(&format!("pub enum {} {{", &request_name));
+        buf.push_str(LINE_ENDING);
+        for method in &service.methods {
+            buf.push_str(&format!(
+                "    {}({}),",
+                method.proto_name, method.input_type
+            ));
+            buf.push_str(LINE_ENDING);
+        }
+        buf.push_str("}");
+        buf.push_str(LINE_ENDING);
+
+        // Generate response enum structure
+        buf.push_str("#[derive(Clone, serde_derive::Serialize, serde_derive::Deserialize, Debug)]");
+        buf.push_str(LINE_ENDING);
+        buf.push_str(r#"#[serde(tag = "type")]"#);
+        buf.push_str(LINE_ENDING);
+        buf.push_str(&format!("pub enum {} {{", &response_name));
+        buf.push_str(LINE_ENDING);
+        for method in &service.methods {
+            buf.push_str(&format!(
+                "    {}({}),",
+                method.proto_name, method.output_type
+            ));
+            buf.push_str(LINE_ENDING);
+        }
+        buf.push_str("}");
+        buf.push_str(LINE_ENDING);
+    }
+
+    fn generate_service(&mut self, service: &prost_build::Service, buf: &mut String) {
+        let request_name = format!("{}{}", &service.proto_name, "Request");
+        let response_name = format!("{}{}", &service.proto_name, "Response");
+        let service_name = format!("{}{}", &service.proto_name, "Service");
+        // Genreate trait
+        buf.push_str(&format!("pub trait {} {{", &service_name));
+        buf.push_str(LINE_ENDING);
+        for method in &service.methods {
+            buf.push_str(&format!(
+                "    fn {}(req: {}) -> mesatee_core::Result<{}>;",
+                method.name, method.input_type, method.output_type
+            ));
+            buf.push_str(LINE_ENDING);
+        }
+        // Generate dispatch
+        buf.push_str(&format!(
+            "    fn dispatch(&self, req: {}) -> mesatee_core::Result<{}> {{",
+            &request_name, &response_name
+        ));
+        buf.push_str(LINE_ENDING);
+
+        // authentication
+        let mut need_authentication: bool = false;
+        for comment in service.comments.leading.iter() {
+            if comment.contains("@need_authentication") {
+                need_authentication = true;
+            }
+        }
+        if need_authentication {
+            buf.push_str("        let authenticated = match req {");
+            buf.push_str(LINE_ENDING);
+            for method in &service.methods {
+                buf.push_str(&format!(
+                    "            {}::{}(ref req) => req.creds.auth(),",
+                    &request_name, &method.proto_name
+                ));
+                buf.push_str(LINE_ENDING);
+            }
+            buf.push_str("        };");
+            buf.push_str(
+                r#"
+        if !authenticated {
+            return Err(mesatee_core::Error::from(mesatee_core::ErrorKind::PermissionDenied));
+        }
+"#,
+            )
+        }
+
+        // dispatch request
+        buf.push_str("        match req {");
+        buf.push_str(LINE_ENDING);
+        for method in &service.methods {
+            buf.push_str(&format!(
+                "            {}::{}(req) => Self::{}(req).map({}::{}),",
+                &request_name, &method.proto_name, method.name, &response_name, &method.proto_name
+            ));
+        }
+        buf.push_str("        }");
+        buf.push_str(LINE_ENDING);
+        buf.push_str("    }");
+        buf.push_str(LINE_ENDING);
+        buf.push_str("}");
+        buf.push_str(LINE_ENDING);
+    }
+
+    fn generate_client(&mut self, service: &prost_build::Service, buf: &mut String) {
+        let request_name = format!("{}{}", &service.proto_name, "Request");
+        let response_name = format!("{}{}", &service.proto_name, "Response");
+        let client_name = format!("{}{}", &service.proto_name, "Client");
+        buf.push_str(&format!("pub struct {} {{", &client_name));
+        buf.push_str(LINE_ENDING);
+        buf.push_str(&format!(
+            "    channel: mesatee_core::rpc::channel::SgxTrustedChannel<{}, {}>,",
+            request_name, response_name
+        ));
+        buf.push_str(LINE_ENDING);
+        buf.push_str("}");
+        buf.push_str(LINE_ENDING);
+
+        // impl new
+        buf.push_str(&format!(
+            r#"
+impl {} {{
+    pub fn new(target: mesatee_core::config::TargetDesc) -> mesatee_core::Result<Self> {{
+        let addr = target.addr;
+        let channel = match target.desc {{
+            mesatee_core::config::OutboundDesc::Sgx(enclave_addr) => {{
+                mesatee_core::rpc::channel::SgxTrustedChannel::<{}, {}>::new(addr, enclave_addr)?
+            }}
+        }};
+        Ok({} {{ channel }})
+    }}
+}}
+"#,
+            client_name, request_name, response_name, client_name
+        ));
+
+        // impl operation
+        buf.push_str(&format!("impl {} {{", client_name));
+        for method in &service.methods {
+            buf.push_str(&format!(
+                r#"
+    pub fn {}(&mut self, req: {}) -> mesatee_core::Result<{}> {{
+        let req = {}::{}(req);
+        let resp = self.channel.invoke(req)?;
+        match resp {{
+            {}::{}(resp) => Ok(resp),
+            _ => Err(mesatee_core::Error::from(mesatee_core::ErrorKind::RPCResponseError)),
+        }}
+    }}
+"#,
+                &method.name,
+                &method.input_type,
+                &method.output_type,
+                &request_name,
+                &method.proto_name,
+                &response_name,
+                &method.proto_name
+            ));
+        }
+        buf.push_str("}");
+        buf.push_str(LINE_ENDING);
+    }
+}
+
+impl prost_build::ServiceGenerator for MesaTEEServiceGenerator {
+    fn generate(&mut self, service: prost_build::Service, buf: &mut String) {
+        self.generate_structure(&service, buf);
+        self.generate_service(&service, buf);
+        self.generate_client(&service, buf);
+    }
+}
+
+pub fn get_default_config() -> prost_build::Config {
+    let mut config = prost_build::Config::new();
+    config.service_generator(Box::new(MesaTEEServiceGenerator));
+    config.type_attribute(
+        ".",
+        "#[derive(serde_derive::Serialize, serde_derive::Deserialize)]",
+    );
+    config
+}
diff --git a/mesatee_services/kms/client/Cargo.toml b/mesatee_services/kms/client/Cargo.toml
deleted file mode 100644
index 812461d..0000000
--- a/mesatee_services/kms/client/Cargo.toml
+++ /dev/null
@@ -1,22 +0,0 @@
-[package]
-name = "kms_client"
-version = "0.1.0"
-authors = ["MesaTEE Authors <developers@mesatee.org>"]
-description = "RPC client of KMS."
-license = "Apache-2.0"
-edition = "2018"
-
-[features]
-default = []
-mesalock_sgx = ["sgx_tstd", "mesatee_core/mesalock_sgx", "kms_proto/mesalock_sgx"]
-cov = ["sgx_cov"]
-
-[dependencies]
-cfg-if          = { version = "0.1.9" }
-kms_proto       = { path = "../proto" }
-
-mesatee_core    = { version = "0.1.0" }
-
-sgx_types       = { version = "1.0.9" }
-sgx_cov         = { version = "0.1.0", optional = true }
-sgx_tstd        = { version = "1.0.9", optional = true }
diff --git a/mesatee_services/kms/client/src/kms_client.rs b/mesatee_services/kms/client/src/kms_client.rs
deleted file mode 100644
index ee781ea..0000000
--- a/mesatee_services/kms/client/src/kms_client.rs
+++ /dev/null
@@ -1,68 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements.  See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.  The ASF licenses this file
-// to you 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.
-
-// Insert std prelude in the top for the sgx feature
-#[cfg(feature = "mesalock_sgx")]
-use std::prelude::v1::*;
-
-use kms_proto::{CreateKeyResponse, DeleteKeyResponse, GetKeyResponse, KMSRequest, KMSResponse};
-use mesatee_core::config::{OutboundDesc, TargetDesc};
-use mesatee_core::rpc::channel::SgxTrustedChannel;
-use mesatee_core::{Error, ErrorKind, Result};
-
-pub struct KMSClient {
-    channel: SgxTrustedChannel<KMSRequest, KMSResponse>,
-}
-
-impl KMSClient {
-    pub fn new(target: TargetDesc) -> Result<Self> {
-        let addr = target.addr;
-        let channel = match target.desc {
-            OutboundDesc::Sgx(enclave_addr) => {
-                SgxTrustedChannel::<KMSRequest, KMSResponse>::new(addr, enclave_addr)?
-            }
-        };
-        Ok(KMSClient { channel })
-    }
-
-    pub fn request_create_key(&mut self) -> Result<CreateKeyResponse> {
-        let req = KMSRequest::new_create_key();
-        let resp = self.channel.invoke(req)?;
-        match resp {
-            KMSResponse::Create(resp) => Ok(resp),
-            _ => Err(Error::from(ErrorKind::RPCResponseError)),
-        }
-    }
-
-    pub fn request_get_key(&mut self, key_id: &str) -> Result<GetKeyResponse> {
-        let req = KMSRequest::new_get_key(key_id);
-        let resp = self.channel.invoke(req)?;
-        match resp {
-            KMSResponse::Get(resp) => Ok(resp),
-            _ => Err(Error::from(ErrorKind::RPCResponseError)),
-        }
-    }
-
-    pub fn request_del_key(&mut self, key_id: &str) -> Result<DeleteKeyResponse> {
-        let req = KMSRequest::new_del_key(key_id);
-        let resp = self.channel.invoke(req)?;
-        match resp {
-            KMSResponse::Delete(resp) => Ok(resp),
-            _ => Err(Error::from(ErrorKind::RPCResponseError)),
-        }
-    }
-}
diff --git a/mesatee_services/kms/proto/Cargo.toml b/mesatee_services/kms/proto/Cargo.toml
index 17d23bf..f1b076b 100644
--- a/mesatee_services/kms/proto/Cargo.toml
+++ b/mesatee_services/kms/proto/Cargo.toml
@@ -12,6 +12,9 @@ mesalock_sgx = ["sgx_tstd", "mesatee_core/mesalock_sgx"]
 cov = ["sgx_cov"]
 
 [dependencies]
+prost = { version = "0.5.0" }
+bytes = { version = ">= 0.4.12"} # unix app depends on 0.4.12, while sgx lib depends on 0.5.0
+prost-types = { version = "0.5.0" }
 cfg-if       = { version = "0.1.9" }
 serde        = { version = "1.0.39" }
 serde_json   = { version = "1.0.39" }
@@ -23,3 +26,6 @@ mesatee_core = { version = "0.1.0" }
 sgx_cov      = { version = "0.1.0", optional = true }
 sgx_tstd     = { version = "1.0.9", features = ["net", "backtrace"], optional = true }
 sgx_types    = { version = "1.0.9" }
+
+[build-dependencies]
+prost-build = { version = "0.5.0" }
\ No newline at end of file
diff --git a/mesatee_services/kms/client/src/lib.rs b/mesatee_services/kms/proto/build.rs
similarity index 50%
rename from mesatee_services/kms/client/src/lib.rs
rename to mesatee_services/kms/proto/build.rs
index 809b694..70c792f 100644
--- a/mesatee_services/kms/client/src/lib.rs
+++ b/mesatee_services/kms/proto/build.rs
@@ -15,10 +15,32 @@
 // specific language governing permissions and limitations
 // under the License.
 
-// Use sgx_tstd to replace Rust's default std
-#![cfg_attr(feature = "mesalock_sgx", no_std)]
-#[cfg(feature = "mesalock_sgx")]
-extern crate sgx_tstd as std;
+#[cfg(not(feature = "mesalock_sgx"))]
+include!("../../common/prost_build_generator.rs");
+
+#[cfg(not(feature = "mesalock_sgx"))]
+fn main() {
+    let src = PathBuf::from("src");
+    let output = src.join("prost_generated");
+    if !output.exists() {
+        std::fs::create_dir(&output).expect("failed to create prost_generated dir");
+    }
+    let includes = &[src.clone()];
+    let mut config = get_default_config();
+    config.out_dir(output);
+    let base64_field = [
+        "AeadConfig.key",
+        "AeadConfig.nonce",
+        "AeadConfig.ad",
+        "ProtectedFsConfig.key",
+    ];
+    for field_name in base64_field.iter() {
+        config.field_attribute(field_name, "#[serde(with = \"crate::base64_coder\")]");
+    }
+    config
+        .compile_protos(&[src.join("kms.proto")], includes)
+        .unwrap();
+}
 
-mod kms_client;
-pub use kms_client::KMSClient;
+#[cfg(feature = "mesalock_sgx")]
+fn main() {}
diff --git a/mesatee_services/kms/proto/src/kms.proto b/mesatee_services/kms/proto/src/kms.proto
new file mode 100644
index 0000000..7ff1418
--- /dev/null
+++ b/mesatee_services/kms/proto/src/kms.proto
@@ -0,0 +1,54 @@
+syntax = "proto2";
+package kms_proto;
+
+enum EncType {
+  Aead = 0;
+  ProtectedFs = 1;
+}
+
+message CreateKeyRequest {
+  required EncType enc_type = 1;
+}
+
+message AeadConfig {
+  required bytes key = 1;
+  required bytes nonce = 2;
+  required bytes ad = 3;
+}
+
+message ProtectedFsConfig {
+  required bytes key = 1;
+}
+
+message KeyConfig {
+  oneof config {
+    AeadConfig Aead = 1;
+    ProtectedFsConfig ProtectedFs = 2;
+  }
+}
+message CreateKeyResponse {
+  required string key_id = 1;
+  required KeyConfig config = 2;
+}
+
+message GetKeyRequest {
+  required string key_id = 1;
+}
+
+message GetKeyResponse {
+  required KeyConfig config = 1;
+}
+
+message DeleteKeyRequest {
+  required string key_id = 1;
+}
+
+message DeleteKeyResponse {
+  required KeyConfig config = 1;
+}
+
+service KMS {
+  rpc GetKey(GetKeyRequest) returns (GetKeyResponse);
+  rpc DelKey(DeleteKeyRequest) returns (DeleteKeyResponse);
+  rpc CreateKey(CreateKeyRequest) returns (CreateKeyResponse);
+}
\ No newline at end of file
diff --git a/mesatee_services/kms/proto/src/kms.rs b/mesatee_services/kms/proto/src/kms.rs
new file mode 100644
index 0000000..eebf006
--- /dev/null
+++ b/mesatee_services/kms/proto/src/kms.rs
@@ -0,0 +1,207 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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::proto;
+use mesatee_core::{Error, ErrorKind, Result};
+use rand::prelude::RngCore;
+use std::convert::TryFrom;
+#[cfg(feature = "mesalock_sgx")]
+use std::prelude::v1::*;
+
+#[derive(Clone, Debug)]
+pub enum EncType {
+    Aead,
+    ProtectedFs,
+}
+
+#[derive(Clone, PartialEq, Debug, serde_derive::Serialize, serde_derive::Deserialize)]
+pub enum KeyConfig {
+    Aead(AEADKeyConfig),
+    ProtectedFs([u8; 16]),
+}
+
+#[derive(Clone, PartialEq, Debug, serde_derive::Serialize, serde_derive::Deserialize)]
+pub struct AEADKeyConfig {
+    pub key: [u8; 32],
+    pub nonce: [u8; 12],
+    pub ad: [u8; 5], // ToDo: removed ad; ad is the authentication tag for AEAD. It can be public and hardcoded.
+}
+
+impl KeyConfig {
+    pub fn new_aead_config() -> KeyConfig {
+        let mut key_config = AEADKeyConfig {
+            key: [0; 32],
+            nonce: [0; 12],
+            ad: [0; 5],
+        };
+        let mut rng = rand::thread_rng();
+        rng.fill_bytes(&mut key_config.key);
+        rng.fill_bytes(&mut key_config.nonce);
+        rng.fill_bytes(&mut key_config.ad);
+        KeyConfig::Aead(key_config)
+    }
+    pub fn new_protected_fs_config() -> KeyConfig {
+        let mut key = [0; 16];
+        let mut rng = rand::thread_rng();
+        rng.fill_bytes(&mut key);
+        KeyConfig::ProtectedFs(key)
+    }
+}
+
+impl From<AEADKeyConfig> for proto::AeadConfig {
+    fn from(config: AEADKeyConfig) -> Self {
+        proto::AeadConfig {
+            key: config.key.to_vec(),
+            nonce: config.nonce.to_vec(),
+            ad: config.ad.to_vec(),
+        }
+    }
+}
+impl TryFrom<proto::AeadConfig> for AEADKeyConfig {
+    type Error = Error;
+    fn try_from(config: proto::AeadConfig) -> Result<Self> {
+        if config.key.len() != 32 || config.nonce.len() != 12 || config.ad.len() != 5 {
+            return Err(Error::from(ErrorKind::RpcProtocolError));
+        }
+        let mut result = AEADKeyConfig {
+            key: [0; 32],
+            nonce: [0; 12],
+            ad: [0; 5],
+        };
+        result.key.copy_from_slice(&config.key[0..32]);
+        result.nonce.copy_from_slice(&config.nonce[0..12]);
+        result.ad.copy_from_slice(&config.ad[0..5]);
+        Ok(result)
+    }
+}
+impl From<KeyConfig> for proto::KeyConfig {
+    fn from(config: KeyConfig) -> Self {
+        let key_config = match config {
+            KeyConfig::Aead(config) => crate::proto::key_config::Config::Aead(config.into()),
+            KeyConfig::ProtectedFs(key) => {
+                proto::key_config::Config::ProtectedFs(proto::ProtectedFsConfig {
+                    key: key.to_vec(),
+                })
+            }
+        };
+        proto::KeyConfig {
+            config: Some(key_config),
+        }
+    }
+}
+
+impl TryFrom<proto::KeyConfig> for KeyConfig {
+    type Error = Error;
+    fn try_from(config: proto::KeyConfig) -> Result<Self> {
+        let config = match config.config {
+            Some(v) => v,
+            None => return Err(Error::from(ErrorKind::RpcProtocolError)),
+        };
+        match config {
+            proto::key_config::Config::Aead(config) => {
+                AEADKeyConfig::try_from(config).map(KeyConfig::Aead)
+            }
+            proto::key_config::Config::ProtectedFs(config) => {
+                if config.key.len() != 16 {
+                    Err(Error::from(ErrorKind::RpcProtocolError))
+                } else {
+                    let mut key = [0; 16];
+                    key.copy_from_slice(&config.key[0..16]);
+                    Ok(KeyConfig::ProtectedFs(key))
+                }
+            }
+        }
+    }
+}
+
+impl proto::CreateKeyRequest {
+    pub fn new(enc_type: EncType) -> Self {
+        let proto_enc_type = match enc_type {
+            EncType::Aead => proto::EncType::Aead,
+            EncType::ProtectedFs => proto::EncType::ProtectedFs,
+        };
+        proto::CreateKeyRequest {
+            enc_type: proto_enc_type as i32,
+        }
+    }
+    pub fn get_enc_type(&self) -> Result<EncType> {
+        match proto::EncType::from_i32(self.enc_type) {
+            Some(proto::EncType::Aead) => Ok(EncType::Aead),
+            Some(proto::EncType::ProtectedFs) => Ok(EncType::ProtectedFs),
+            None => Err(Error::from(ErrorKind::InvalidInputError)),
+        }
+    }
+}
+
+impl proto::CreateKeyResponse {
+    pub fn new(key_id: &str, config: &KeyConfig) -> Self {
+        proto::CreateKeyResponse {
+            key_id: key_id.to_owned(),
+            config: proto::KeyConfig::from(config.clone()),
+        }
+    }
+    pub fn get_key_id(&self) -> String {
+        self.key_id.clone()
+    }
+    pub fn get_key_config(&self) -> Result<KeyConfig> {
+        KeyConfig::try_from(self.config.clone())
+    }
+}
+
+impl proto::DeleteKeyRequest {
+    pub fn new(key_id: &str) -> Self {
+        proto::DeleteKeyRequest {
+            key_id: key_id.to_owned(),
+        }
+    }
+    pub fn get_key_id(&self) -> String {
+        self.key_id.clone()
+    }
+}
+
+impl proto::DeleteKeyResponse {
+    pub fn new(config: &KeyConfig) -> Self {
+        proto::DeleteKeyResponse {
+            config: proto::KeyConfig::from(config.clone()),
+        }
+    }
+    pub fn get_key_config(&self) -> Result<KeyConfig> {
+        KeyConfig::try_from(self.config.clone())
+    }
+}
+
+impl proto::GetKeyRequest {
+    pub fn new(key_id: &str) -> Self {
+        proto::GetKeyRequest {
+            key_id: key_id.to_owned(),
+        }
+    }
+    pub fn get_key_id(&self) -> String {
+        self.key_id.clone()
+    }
+}
+
+impl proto::GetKeyResponse {
+    pub fn new(config: &KeyConfig) -> Self {
+        proto::GetKeyResponse {
+            config: proto::KeyConfig::from(config.clone()),
+        }
+    }
+    pub fn get_key_config(&self) -> Result<KeyConfig> {
+        KeyConfig::try_from(self.config.clone())
+    }
+}
diff --git a/mesatee_services/kms/proto/src/lib.rs b/mesatee_services/kms/proto/src/lib.rs
index d6542af..40427d8 100644
--- a/mesatee_services/kms/proto/src/lib.rs
+++ b/mesatee_services/kms/proto/src/lib.rs
@@ -19,5 +19,34 @@
 #[macro_use]
 extern crate sgx_tstd as std;
 
-mod proto;
-pub use proto::*;
+pub use crate::kms::*;
+pub use crate::proto::KMSClient;
+mod kms;
+pub mod proto {
+    #![allow(warnings)]
+    #![allow(clippy)]
+    #![allow(unknown_lints)]
+    include!("prost_generated/kms_proto.rs");
+}
+
+mod base64_coder {
+    use base64;
+    use serde::{de, Deserialize, Deserializer, Serializer};
+    #[cfg(feature = "mesalock_sgx")]
+    use std::prelude::v1::*;
+
+    pub fn serialize<S>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error>
+    where
+        S: Serializer,
+    {
+        serializer.serialize_str(&base64::encode(bytes))
+    }
+
+    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
+    where
+        D: Deserializer<'de>,
+    {
+        let s = <&str>::deserialize(deserializer)?;
+        base64::decode(s).map_err(de::Error::custom)
+    }
+}
diff --git a/mesatee_services/kms/proto/src/prost_generated/kms_proto.rs b/mesatee_services/kms/proto/src/prost_generated/kms_proto.rs
new file mode 100644
index 0000000..44484d6
--- /dev/null
+++ b/mesatee_services/kms/proto/src/prost_generated/kms_proto.rs
@@ -0,0 +1,151 @@
+#[derive(Clone, PartialEq, ::prost::Message, serde_derive::Serialize, serde_derive::Deserialize)]
+pub struct CreateKeyRequest {
+    #[prost(enumeration = "EncType", required, tag = "1")]
+    pub enc_type: i32,
+}
+#[derive(Clone, PartialEq, ::prost::Message, serde_derive::Serialize, serde_derive::Deserialize)]
+pub struct AeadConfig {
+    #[prost(bytes, required, tag = "1")]
+    #[serde(with = "crate::base64_coder")]
+    pub key: std::vec::Vec<u8>,
+    #[prost(bytes, required, tag = "2")]
+    #[serde(with = "crate::base64_coder")]
+    pub nonce: std::vec::Vec<u8>,
+    #[prost(bytes, required, tag = "3")]
+    #[serde(with = "crate::base64_coder")]
+    pub ad: std::vec::Vec<u8>,
+}
+#[derive(Clone, PartialEq, ::prost::Message, serde_derive::Serialize, serde_derive::Deserialize)]
+pub struct ProtectedFsConfig {
+    #[prost(bytes, required, tag = "1")]
+    #[serde(with = "crate::base64_coder")]
+    pub key: std::vec::Vec<u8>,
+}
+#[derive(Clone, PartialEq, ::prost::Message, serde_derive::Serialize, serde_derive::Deserialize)]
+pub struct KeyConfig {
+    #[prost(oneof = "key_config::Config", tags = "1, 2")]
+    pub config: ::std::option::Option<key_config::Config>,
+}
+pub mod key_config {
+    #[derive(
+        Clone, PartialEq, ::prost::Oneof, serde_derive::Serialize, serde_derive::Deserialize,
+    )]
+    pub enum Config {
+        #[prost(message, tag = "1")]
+        Aead(super::AeadConfig),
+        #[prost(message, tag = "2")]
+        ProtectedFs(super::ProtectedFsConfig),
+    }
+}
+#[derive(Clone, PartialEq, ::prost::Message, serde_derive::Serialize, serde_derive::Deserialize)]
+pub struct CreateKeyResponse {
+    #[prost(string, required, tag = "1")]
+    pub key_id: std::string::String,
+    #[prost(message, required, tag = "2")]
+    pub config: KeyConfig,
+}
+#[derive(Clone, PartialEq, ::prost::Message, serde_derive::Serialize, serde_derive::Deserialize)]
+pub struct GetKeyRequest {
+    #[prost(string, required, tag = "1")]
+    pub key_id: std::string::String,
+}
+#[derive(Clone, PartialEq, ::prost::Message, serde_derive::Serialize, serde_derive::Deserialize)]
+pub struct GetKeyResponse {
+    #[prost(message, required, tag = "1")]
+    pub config: KeyConfig,
+}
+#[derive(Clone, PartialEq, ::prost::Message, serde_derive::Serialize, serde_derive::Deserialize)]
+pub struct DeleteKeyRequest {
+    #[prost(string, required, tag = "1")]
+    pub key_id: std::string::String,
+}
+#[derive(Clone, PartialEq, ::prost::Message, serde_derive::Serialize, serde_derive::Deserialize)]
+pub struct DeleteKeyResponse {
+    #[prost(message, required, tag = "1")]
+    pub config: KeyConfig,
+}
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
+#[repr(i32)]
+#[derive(serde_derive::Serialize, serde_derive::Deserialize)]
+pub enum EncType {
+    Aead = 0,
+    ProtectedFs = 1,
+}
+#[derive(Clone, serde_derive::Serialize, serde_derive::Deserialize, Debug)]
+#[serde(tag = "type")]
+pub enum KMSRequest {
+    GetKey(GetKeyRequest),
+    DelKey(DeleteKeyRequest),
+    CreateKey(CreateKeyRequest),
+}
+#[derive(Clone, serde_derive::Serialize, serde_derive::Deserialize, Debug)]
+#[serde(tag = "type")]
+pub enum KMSResponse {
+    GetKey(GetKeyResponse),
+    DelKey(DeleteKeyResponse),
+    CreateKey(CreateKeyResponse),
+}
+pub trait KMSService {
+    fn get_key(req: GetKeyRequest) -> mesatee_core::Result<GetKeyResponse>;
+    fn del_key(req: DeleteKeyRequest) -> mesatee_core::Result<DeleteKeyResponse>;
+    fn create_key(req: CreateKeyRequest) -> mesatee_core::Result<CreateKeyResponse>;
+    fn dispatch(&self, req: KMSRequest) -> mesatee_core::Result<KMSResponse> {
+        match req {
+            KMSRequest::GetKey(req) => Self::get_key(req).map(KMSResponse::GetKey),
+            KMSRequest::DelKey(req) => Self::del_key(req).map(KMSResponse::DelKey),
+            KMSRequest::CreateKey(req) => Self::create_key(req).map(KMSResponse::CreateKey),
+        }
+    }
+}
+pub struct KMSClient {
+    channel: mesatee_core::rpc::channel::SgxTrustedChannel<KMSRequest, KMSResponse>,
+}
+
+impl KMSClient {
+    pub fn new(target: mesatee_core::config::TargetDesc) -> mesatee_core::Result<Self> {
+        let addr = target.addr;
+        let channel = match target.desc {
+            mesatee_core::config::OutboundDesc::Sgx(enclave_addr) => {
+                mesatee_core::rpc::channel::SgxTrustedChannel::<KMSRequest, KMSResponse>::new(
+                    addr,
+                    enclave_addr,
+                )?
+            }
+        };
+        Ok(KMSClient { channel })
+    }
+}
+impl KMSClient {
+    pub fn get_key(&mut self, req: GetKeyRequest) -> mesatee_core::Result<GetKeyResponse> {
+        let req = KMSRequest::GetKey(req);
+        let resp = self.channel.invoke(req)?;
+        match resp {
+            KMSResponse::GetKey(resp) => Ok(resp),
+            _ => Err(mesatee_core::Error::from(
+                mesatee_core::ErrorKind::RPCResponseError,
+            )),
+        }
+    }
+
+    pub fn del_key(&mut self, req: DeleteKeyRequest) -> mesatee_core::Result<DeleteKeyResponse> {
+        let req = KMSRequest::DelKey(req);
+        let resp = self.channel.invoke(req)?;
+        match resp {
+            KMSResponse::DelKey(resp) => Ok(resp),
+            _ => Err(mesatee_core::Error::from(
+                mesatee_core::ErrorKind::RPCResponseError,
+            )),
+        }
+    }
+
+    pub fn create_key(&mut self, req: CreateKeyRequest) -> mesatee_core::Result<CreateKeyResponse> {
+        let req = KMSRequest::CreateKey(req);
+        let resp = self.channel.invoke(req)?;
+        match resp {
+            KMSResponse::CreateKey(resp) => Ok(resp),
+            _ => Err(mesatee_core::Error::from(
+                mesatee_core::ErrorKind::RPCResponseError,
+            )),
+        }
+    }
+}
diff --git a/mesatee_services/kms/proto/src/proto.rs b/mesatee_services/kms/proto/src/proto.rs
deleted file mode 100644
index cbd914f..0000000
--- a/mesatee_services/kms/proto/src/proto.rs
+++ /dev/null
@@ -1,166 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements.  See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.  The ASF licenses this file
-// to you 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.
-
-// Insert std prelude in the top for the sgx feature
-#[cfg(feature = "mesalock_sgx")]
-use std::prelude::v1::*;
-
-use mesatee_core;
-use mesatee_core::Result;
-use serde_derive::*;
-
-#[derive(Clone, Serialize, Deserialize, Debug)]
-#[serde(tag = "type")]
-pub enum KMSRequest {
-    Create(CreateKeyRequest),
-    Get(GetKeyRequest),
-    Delete(DeleteKeyRequest),
-}
-
-#[derive(Clone, Serialize, Deserialize, Debug)]
-#[serde(tag = "type")]
-pub enum KMSResponse {
-    Create(CreateKeyResponse),
-    Get(GetKeyResponse),
-    Delete(DeleteKeyResponse),
-}
-
-#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
-pub struct AEADKeyConfig {
-    #[serde(with = "base64_coder")]
-    pub key: Vec<u8>,
-    #[serde(with = "base64_coder")]
-    pub nonce: Vec<u8>,
-    #[serde(with = "base64_coder")]
-    pub ad: Vec<u8>,
-}
-
-#[derive(Clone, Serialize, Deserialize, Debug)]
-pub struct CreateKeyRequest {}
-
-#[derive(Clone, Serialize, Deserialize, Debug)]
-pub struct CreateKeyResponse {
-    pub key_id: String,
-    pub config: AEADKeyConfig,
-}
-
-#[derive(Clone, Serialize, Deserialize, Debug)]
-pub struct GetKeyRequest {
-    pub key_id: String,
-}
-
-#[derive(Clone, Serialize, Deserialize, Debug)]
-pub struct GetKeyResponse {
-    pub config: AEADKeyConfig,
-}
-
-#[derive(Clone, Serialize, Deserialize, Debug)]
-pub struct DeleteKeyRequest {
-    pub key_id: String,
-}
-
-#[derive(Clone, Serialize, Deserialize, Debug)]
-pub struct DeleteKeyResponse {
-    pub config: AEADKeyConfig,
-}
-
-impl KMSRequest {
-    pub fn new_create_key() -> KMSRequest {
-        KMSRequest::Create(CreateKeyRequest {})
-    }
-
-    pub fn new_get_key(key_id: &str) -> KMSRequest {
-        let req = GetKeyRequest {
-            key_id: key_id.to_owned(),
-        };
-        KMSRequest::Get(req)
-    }
-
-    pub fn new_del_key(key_id: &str) -> KMSRequest {
-        let req = DeleteKeyRequest {
-            key_id: key_id.to_owned(),
-        };
-        KMSRequest::Delete(req)
-    }
-}
-
-impl KMSResponse {
-    pub fn new_create_key(key_id: &str, key: &AEADKeyConfig) -> KMSResponse {
-        let resp = CreateKeyResponse {
-            key_id: key_id.to_owned(),
-            config: key.clone(),
-        };
-        KMSResponse::Create(resp)
-    }
-
-    pub fn new_get_key(config: &AEADKeyConfig) -> KMSResponse {
-        let resp = GetKeyResponse {
-            config: config.clone(),
-        };
-        KMSResponse::Get(resp)
-    }
-
-    pub fn new_del_key(config: &AEADKeyConfig) -> KMSResponse {
-        let resp = DeleteKeyResponse {
-            config: config.clone(),
-        };
-        KMSResponse::Delete(resp)
-    }
-}
-
-impl AEADKeyConfig {
-    pub fn new() -> Result<Self> {
-        use rand::prelude::RngCore;
-
-        let mut key_config = AEADKeyConfig {
-            key: vec![0; 32],
-            nonce: vec![0; 12],
-            ad: vec![0; 5],
-        };
-
-        let mut rng = rand::thread_rng();
-        rng.fill_bytes(&mut key_config.key);
-        rng.fill_bytes(&mut key_config.nonce);
-        rng.fill_bytes(&mut key_config.ad);
-
-        Ok(key_config)
-    }
-}
-
-mod base64_coder {
-    // Insert std prelude in the top for the sgx feature
-    #[cfg(feature = "mesalock_sgx")]
-    use std::prelude::v1::*;
-
-    extern crate base64;
-    use serde::{de, Deserialize, Deserializer, Serializer};
-
-    pub fn serialize<S>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error>
-    where
-        S: Serializer,
-    {
-        serializer.serialize_str(&base64::encode(bytes))
-    }
-
-    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
-    where
-        D: Deserializer<'de>,
-    {
-        let s = <&str>::deserialize(deserializer)?;
-        base64::decode(s).map_err(de::Error::custom)
-    }
-}
diff --git a/mesatee_services/kms/sgx_app/Cargo.toml b/mesatee_services/kms/sgx_app/Cargo.toml
index 66308f9..089bb19 100644
--- a/mesatee_services/kms/sgx_app/Cargo.toml
+++ b/mesatee_services/kms/sgx_app/Cargo.toml
@@ -21,3 +21,6 @@ ctrlc           = { version = "3.1.2" }
 log             = { version = "0.4.6" }
 env_logger      = { version = "0.7.1" }
 threadpool      = { version = "1.0" }
+
+[build-dependencies]
+kms_proto       = { path = "../proto" }
\ No newline at end of file
diff --git a/mesatee_services/kms/sgx_trusted_lib/Cargo.toml b/mesatee_services/kms/sgx_trusted_lib/Cargo.toml
index a8f055d..c1c61d9 100644
--- a/mesatee_services/kms/sgx_trusted_lib/Cargo.toml
+++ b/mesatee_services/kms/sgx_trusted_lib/Cargo.toml
@@ -21,6 +21,7 @@ lazy_static     = { version = "1.0.2", features = ["spin_no_std"] }
 log             = { version = "0.4.6" }
 env_logger      = { version = "0.7.1" }
 uuid            = { version = "0.7.4", features = ["v4"] }
+rand            = { version = "0.7.0" }
 
 kms_proto       = { path = "../proto", optional = true}
 mesatee_core    = { version = "0.1.0" }
diff --git a/mesatee_services/kms/sgx_trusted_lib/src/kms.rs b/mesatee_services/kms/sgx_trusted_lib/src/kms.rs
index f9289d6..60225c0 100644
--- a/mesatee_services/kms/sgx_trusted_lib/src/kms.rs
+++ b/mesatee_services/kms/sgx_trusted_lib/src/kms.rs
@@ -18,87 +18,73 @@
 // Insert std prelude in the top for the sgx feature
 #[cfg(feature = "mesalock_sgx")]
 use std::prelude::v1::*;
-use std::vec;
 
 use uuid::Uuid;
 
+use kms_proto::proto::{
+    CreateKeyRequest, CreateKeyResponse, DeleteKeyRequest, DeleteKeyResponse, GetKeyRequest,
+    GetKeyResponse, KMSRequest, KMSResponse, KMSService,
+};
+use kms_proto::{AEADKeyConfig, EncType, KeyConfig};
+use lazy_static::lazy_static;
 use mesatee_core::db::Memdb;
 use mesatee_core::rpc::EnclaveService;
 use mesatee_core::{Error, ErrorKind, Result};
 use std::marker::PhantomData;
 
-use kms_proto::AEADKeyConfig;
-use kms_proto::KMSResponse;
-use kms_proto::{CreateKeyRequest, DeleteKeyRequest, GetKeyRequest, KMSRequest};
-
-use lazy_static::lazy_static;
-
 lazy_static! {
-    static ref KEY_STORE: Memdb<String, AEADKeyConfig> = {
-        let db = Memdb::<String, AEADKeyConfig>::open().expect("cannot open memdb");
-        let fake_record = AEADKeyConfig {
-            key: vec![65; 32],
-            nonce: vec![65; 12],
-            ad: vec![65; 5],
-        };
+    static ref KEY_STORE: Memdb<String, KeyConfig> = {
+        let db = Memdb::<String, KeyConfig>::open().expect("cannot open memdb");
+        let fake_record = KeyConfig::Aead(AEADKeyConfig {
+            key: [65; 32],
+            nonce: [65; 12],
+            ad: [65; 5],
+        });
         let _ = db.set(&"fake_kms_record".to_string(), &fake_record);
         let _ = db.set(&"fake_kms_record_to_be_deleted".to_string(), &fake_record);
         db
     };
 }
 
-pub trait HandleRequest {
-    fn handle_request(&self) -> Result<KMSResponse>;
+pub struct KMSEnclave<S, T> {
+    x: PhantomData<(S, T)>,
 }
 
-impl HandleRequest for CreateKeyRequest {
-    fn handle_request(&self) -> Result<KMSResponse> {
-        let key_config = AEADKeyConfig::new()?;
-        let key_id = Uuid::new_v4().to_string();
-        if KEY_STORE.get(&key_id)?.is_some() {
-            return Err(Error::from(ErrorKind::UUIDError));
+impl<S, T> Default for KMSEnclave<S, T> {
+    fn default() -> Self {
+        KMSEnclave {
+            x: PhantomData::<(S, T)>,
         }
-        KEY_STORE.set(&key_id, &key_config)?;
-        let resp = KMSResponse::new_create_key(&key_id, &key_config);
-        Ok(resp)
     }
 }
 
-impl HandleRequest for GetKeyRequest {
-    fn handle_request(&self) -> Result<KMSResponse> {
+impl KMSService for KMSEnclave<KMSRequest, KMSResponse> {
+    fn get_key(req: GetKeyRequest) -> mesatee_core::Result<GetKeyResponse> {
         let key_config = KEY_STORE
-            .get(&self.key_id)?
+            .get(&req.key_id)?
             .ok_or_else(|| Error::from(ErrorKind::MissingValue))?;
 
-        let resp = KMSResponse::new_get_key(&key_config);
-        Ok(resp)
+        Ok(GetKeyResponse::new(&key_config))
     }
-}
-
-impl HandleRequest for DeleteKeyRequest {
-    fn handle_request(&self) -> Result<KMSResponse> {
+    fn del_key(req: DeleteKeyRequest) -> mesatee_core::Result<DeleteKeyResponse> {
         let key_config = KEY_STORE
-            .del(&self.key_id)?
+            .del(&req.key_id)?
             .ok_or_else(|| Error::from(ErrorKind::MissingValue))?;
 
-        let resp = KMSResponse::new_del_key(&key_config);
-        Ok(resp)
+        Ok(DeleteKeyResponse::new(&key_config))
     }
-}
-
-pub struct KMSEnclave<S, T> {
-    state: i32,
-    x: PhantomData<S>,
-    y: PhantomData<T>,
-}
-
-impl<S, T> Default for KMSEnclave<S, T> {
-    fn default() -> Self {
-        KMSEnclave {
-            state: 0,
-            x: PhantomData::<S>,
-            y: PhantomData::<T>,
+    fn create_key(req: CreateKeyRequest) -> mesatee_core::Result<CreateKeyResponse> {
+        let enc_type = req.get_enc_type()?;
+        let config = match enc_type {
+            EncType::Aead => KeyConfig::new_aead_config(),
+            EncType::ProtectedFs => KeyConfig::new_protected_fs_config(),
+        };
+        let key_id = Uuid::new_v4().to_string();
+        if KEY_STORE.get(&key_id)?.is_some() {
+            return Err(Error::from(ErrorKind::UUIDError));
         }
+        KEY_STORE.set(&key_id, &config)?;
+        Ok(CreateKeyResponse::new(&key_id, &config))
     }
 }
 
@@ -106,13 +92,6 @@ impl EnclaveService<KMSRequest, KMSResponse> for KMSEnclave<KMSRequest, KMSRespo
     fn handle_invoke(&mut self, input: KMSRequest) -> Result<KMSResponse> {
         trace!("handle_invoke invoked!");
         trace!("incoming payload = {:?}", input);
-        self.state += 1;
-        let response = match input {
-            KMSRequest::Create(req) => req.handle_request()?,
-            KMSRequest::Get(req) => req.handle_request()?,
-            KMSRequest::Delete(req) => req.handle_request()?,
-        };
-        trace!("{}th round complete!", self.state);
-        Ok(response)
+        self.dispatch(input)
     }
 }
diff --git a/mesatee_services/tdfs/external/proto/src/key.rs b/mesatee_services/tdfs/external/proto/src/key.rs
index 88e3c95..3b11b2e 100644
--- a/mesatee_services/tdfs/external/proto/src/key.rs
+++ b/mesatee_services/tdfs/external/proto/src/key.rs
@@ -18,7 +18,7 @@
 use serde_derive::*;
 
 #[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
-pub struct AEADKeyConfig {
+pub struct AeadConfig {
     #[serde(with = "base64_coder")]
     pub key: Vec<u8>,
     #[serde(with = "base64_coder")]
diff --git a/mesatee_services/tdfs/external/proto/src/lib.rs b/mesatee_services/tdfs/external/proto/src/lib.rs
index 33581bb..1f78480 100644
--- a/mesatee_services/tdfs/external/proto/src/lib.rs
+++ b/mesatee_services/tdfs/external/proto/src/lib.rs
@@ -23,7 +23,7 @@ cfg_if! {
     if #[cfg(feature = "mesalock_sgx")]  {
     } else {
         mod key;
-        pub use key::AEADKeyConfig;
+        pub use key::AeadConfig;
     }
 }
 
diff --git a/mesatee_services/tdfs/external/proto/src/proto.rs b/mesatee_services/tdfs/external/proto/src/proto.rs
index 7d17526..ffc9cc8 100644
--- a/mesatee_services/tdfs/external/proto/src/proto.rs
+++ b/mesatee_services/tdfs/external/proto/src/proto.rs
@@ -20,9 +20,9 @@
 use std::prelude::v1::*;
 
 #[cfg(not(feature = "mesalock_sgx"))]
-use crate::key::AEADKeyConfig;
+use crate::key::AeadConfig;
 #[cfg(feature = "mesalock_sgx")]
-use kms_proto::AEADKeyConfig;
+use kms_proto::proto::AeadConfig;
 
 use serde_derive::*;
 
@@ -57,7 +57,7 @@ pub struct CreateFileRequest {
 pub struct CreateFileResponse {
     pub file_id: String,
     pub access_path: String,
-    pub key_config: AEADKeyConfig,
+    pub key_config: AeadConfig,
 }
 
 #[derive(Clone, Serialize, Deserialize, Debug)]
@@ -93,7 +93,7 @@ pub struct FileInfo {
     pub access_path: String,
     pub task_id: Option<String>,
     pub collaborator_list: Vec<String>,
-    pub key_config: AEADKeyConfig,
+    pub key_config: AeadConfig,
 }
 
 #[derive(Clone, Serialize, Deserialize, Debug)]
@@ -152,7 +152,7 @@ impl DFSResponse {
     pub fn new_create_file(
         file_id: &str,
         access_path: &str,
-        key_config: &AEADKeyConfig,
+        key_config: &AeadConfig,
     ) -> DFSResponse {
         DFSResponse::Create(CreateFileResponse {
             file_id: file_id.to_owned(),
diff --git a/mesatee_services/tdfs/internal/client/Cargo.toml b/mesatee_services/tdfs/internal/client/Cargo.toml
index 6d7c112..10eea2b 100644
--- a/mesatee_services/tdfs/internal/client/Cargo.toml
+++ b/mesatee_services/tdfs/internal/client/Cargo.toml
@@ -8,7 +8,7 @@ edition = "2018"
 
 [features]
 default = []
-mesalock_sgx = ["sgx_tstd", "mesatee_core/mesalock_sgx", "kms_client/mesalock_sgx", "tdfs_internal_proto/mesalock_sgx"]
+mesalock_sgx = ["sgx_tstd", "mesatee_core/mesalock_sgx", "kms_proto/mesalock_sgx", "tdfs_internal_proto/mesalock_sgx"]
 cov = ["sgx_cov"]
 
 [dependencies]
@@ -16,7 +16,7 @@ cfg-if       = { version = "0.1.9" }
 ring         = { version = "0.16.5" }
 net2         = { version = "0.2.33" }
 
-kms_client          = { path = "../../../kms/client", optional = true}
+kms_proto          = { path = "../../../kms/proto", optional = true}
 tdfs_internal_proto = { path = "../proto", optional = true}
 
 mesatee_core    = { version = "0.1.0" }
diff --git a/mesatee_services/tdfs/internal/client/src/tdfs_client.rs b/mesatee_services/tdfs/internal/client/src/tdfs_client.rs
index 6a23c1a..d9b1f2e 100644
--- a/mesatee_services/tdfs/internal/client/src/tdfs_client.rs
+++ b/mesatee_services/tdfs/internal/client/src/tdfs_client.rs
@@ -19,7 +19,8 @@ use std::prelude::v1::*;
 
 use crate::file_util;
 use core::convert::TryInto;
-use kms_client::KMSClient;
+use kms_proto;
+use kms_proto::KMSClient;
 use mesatee_core::config::{self, OutboundDesc, TargetDesc};
 use mesatee_core::rpc::channel::SgxTrustedChannel;
 use mesatee_core::{self, Result};
@@ -143,8 +144,13 @@ impl TDFSClient {
 
         let target = config::Internal::target_kms();
         let mut client = KMSClient::new(target)?;
-        let key_resp = client.request_get_key(&file_info.key_id)?;
-        let key_config = key_resp.config;
+        let key_req = kms_proto::proto::GetKeyRequest::new(&file_info.key_id);
+        let key_resp = client.get_key(key_req)?;
+        let key_config = key_resp.get_key_config()?;
+        let key_config = match key_config {
+            kms_proto::KeyConfig::Aead(config) => kms_proto::proto::AeadConfig::from(config),
+            kms_proto::KeyConfig::ProtectedFs(_config) => unimplemented!(), // ProtectedFS is not used by TDFS yet. Config of ProtectedFs will not be generated neither.
+        };
         let access_path = &file_info.access_path;
         let mut f = fs::File::open(access_path)?;
         let capacity: usize = file_info.file_size.try_into().unwrap_or(1024 * 1024) + 1024;
diff --git a/mesatee_services/tdfs/internal/proto/src/proto.rs b/mesatee_services/tdfs/internal/proto/src/proto.rs
index 21c04ed..20138f6 100644
--- a/mesatee_services/tdfs/internal/proto/src/proto.rs
+++ b/mesatee_services/tdfs/internal/proto/src/proto.rs
@@ -17,7 +17,7 @@
 #[cfg(feature = "mesalock_sgx")]
 use std::prelude::v1::*;
 
-use kms_proto::AEADKeyConfig;
+use kms_proto::proto::AeadConfig;
 use serde_derive::*;
 
 #[derive(Clone, Serialize, Deserialize, Debug)]
@@ -71,7 +71,7 @@ pub struct CreateFileRequest {
 pub struct CreateFileResponse {
     pub file_id: String,
     pub access_path: String,
-    pub key_config: AEADKeyConfig,
+    pub key_config: AeadConfig,
 }
 
 impl DFSRequest {
@@ -102,7 +102,7 @@ impl DFSRequest {
 }
 
 impl DFSResponse {
-    pub fn new_create_file(file_id: &str, access_path: &str, key: &AEADKeyConfig) -> DFSResponse {
+    pub fn new_create_file(file_id: &str, access_path: &str, key: &AeadConfig) -> DFSResponse {
         let resp = CreateFileResponse {
             file_id: file_id.to_owned(),
             access_path: access_path.to_owned(),
diff --git a/mesatee_services/tdfs/sgx_trusted_lib/Cargo.toml b/mesatee_services/tdfs/sgx_trusted_lib/Cargo.toml
index 13c5de6..d85137d 100644
--- a/mesatee_services/tdfs/sgx_trusted_lib/Cargo.toml
+++ b/mesatee_services/tdfs/sgx_trusted_lib/Cargo.toml
@@ -10,7 +10,7 @@ crate-type = ["staticlib"]
 
 [features]
 default = []
-mesalock_sgx = ["sgx_tstd", "mesatee_core/mesalock_sgx", "tdfs_internal_proto/mesalock_sgx", "tdfs_external_proto/mesalock_sgx", "kms_client/mesalock_sgx"]
+mesalock_sgx = ["sgx_tstd", "mesatee_core/mesalock_sgx", "tdfs_internal_proto/mesalock_sgx", "tdfs_external_proto/mesalock_sgx", "kms_proto/mesalock_sgx"]
 cov = ["sgx_cov"]
 
 [dependencies]
@@ -24,7 +24,8 @@ mesatee_core        = { version = "0.1.0" }
 
 tdfs_internal_proto = { path = "../internal/proto", optional = true }
 tdfs_external_proto = { path = "../external/proto", optional = true }
-kms_client          = { path = "../../kms/client", optional = true }
+kms_proto           = { path = "../../kms/proto", optional = true}
+
 
 sgx_cov             = { version = "0.1.0", optional = true }
 sgx_tstd            = { version = "1.0.9", features = ["net", "backtrace"], optional = true }
diff --git a/mesatee_services/tdfs/sgx_trusted_lib/src/tdfs_external.rs b/mesatee_services/tdfs/sgx_trusted_lib/src/tdfs_external.rs
index 9676171..d80c9a6 100644
--- a/mesatee_services/tdfs/sgx_trusted_lib/src/tdfs_external.rs
+++ b/mesatee_services/tdfs/sgx_trusted_lib/src/tdfs_external.rs
@@ -20,7 +20,8 @@
 use std::prelude::v1::*;
 
 use crate::data_store::{self, verify_user, FileMeta, FILE_STORE, USER_FILE_STORE};
-use kms_client::KMSClient;
+use kms_proto;
+use kms_proto::KMSClient;
 use mesatee_core::config;
 use mesatee_core::rpc::EnclaveService;
 use mesatee_core::{Error, ErrorKind, Result};
@@ -44,9 +45,14 @@ impl HandleRequest for CreateFileRequest {
 
         let target = config::Internal::target_kms();
         let mut client = KMSClient::new(target)?;
-        let resp = client.request_create_key()?;
-        let key_id = resp.key_id;
-        let key_config = resp.config;
+        let req = kms_proto::proto::CreateKeyRequest::new(kms_proto::EncType::Aead);
+        let resp = client.create_key(req)?;
+        let key_id = resp.get_key_id();
+        let key_config = resp.get_key_config()?;
+        let key_config = match key_config {
+            kms_proto::KeyConfig::Aead(config) => kms_proto::proto::AeadConfig::from(config),
+            kms_proto::KeyConfig::ProtectedFs(_config) => unimplemented!(), // ProtectedFS is not used by TDFS yet. Config of ProtectedFs will not be generated neither.
+        };
 
         let file_id = Uuid::new_v4().to_string();
         let file_meta = FileMeta {
@@ -93,9 +99,13 @@ impl HandleRequest for GetFileRequest {
 
         let target = config::Internal::target_kms();
         let mut client = KMSClient::new(target)?;
-        let key_resp = client.request_get_key(&file_meta.key_id)?;
-        let key_config = key_resp.config;
-
+        let key_request = kms_proto::proto::GetKeyRequest::new(&file_meta.key_id);
+        let key_resp = client.get_key(key_request)?;
+        let key_config = key_resp.get_key_config()?;
+        let key_config = match key_config {
+            kms_proto::KeyConfig::Aead(config) => kms_proto::proto::AeadConfig::from(config),
+            kms_proto::KeyConfig::ProtectedFs(_config) => unimplemented!(), // ProtectedFS is not used by TDFS yet. Config of ProtectedFs will not be generated neither.
+        };
         let access_path = file_meta.get_access_path();
         let file_info = tdfs_external_proto::FileInfo {
             user_id: file_meta.user_id,
@@ -135,8 +145,13 @@ impl HandleRequest for DeleteFileRequest {
 
         let target = config::Internal::target_kms();
         let mut client = KMSClient::new(target)?;
-        let key_resp = client.request_del_key(&file_meta.key_id)?;
-        let key_config = key_resp.config;
+        let key_req = kms_proto::proto::DeleteKeyRequest::new(&file_meta.key_id);
+        let key_resp = client.del_key(key_req)?;
+        let key_config = key_resp.get_key_config()?;
+        let key_config = match key_config {
+            kms_proto::KeyConfig::Aead(config) => kms_proto::proto::AeadConfig::from(config),
+            kms_proto::KeyConfig::ProtectedFs(_config) => unimplemented!(), // ProtectedFS is not used by TDFS yet. Config of ProtectedFs will not be generated neither.
+        };
 
         let access_path = file_meta.get_access_path();
         let file_info = tdfs_external_proto::FileInfo {
diff --git a/mesatee_services/tdfs/sgx_trusted_lib/src/tdfs_internal.rs b/mesatee_services/tdfs/sgx_trusted_lib/src/tdfs_internal.rs
index a648b2b..7b84416 100644
--- a/mesatee_services/tdfs/sgx_trusted_lib/src/tdfs_internal.rs
+++ b/mesatee_services/tdfs/sgx_trusted_lib/src/tdfs_internal.rs
@@ -19,7 +19,7 @@
 use std::prelude::v1::*;
 
 use crate::data_store::{self, FileMeta, FILE_STORE};
-use kms_client::KMSClient;
+use kms_proto::{self, KMSClient};
 use mesatee_core::config;
 use mesatee_core::rpc::EnclaveService;
 use mesatee_core::{Error, ErrorKind, Result};
@@ -35,10 +35,14 @@ impl HandleRequest for CreateFileRequest {
     fn handle_request(&self) -> Result<DFSResponse> {
         let target = config::Internal::target_kms();
         let mut client = KMSClient::new(target)?;
-
-        let resp = client.request_create_key()?;
-        let key_id = resp.key_id;
-        let key_config = resp.config;
+        let req = kms_proto::proto::CreateKeyRequest::new(kms_proto::EncType::Aead);
+        let resp = client.create_key(req)?;
+        let key_id = resp.get_key_id();
+        let key_config = resp.get_key_config()?;
+        let key_config = match key_config {
+            kms_proto::KeyConfig::Aead(config) => kms_proto::proto::AeadConfig::from(config),
+            kms_proto::KeyConfig::ProtectedFs(_config) => unimplemented!(), // ProtectedFS is not used by TDFS yet. Config of ProtectedFs will not be generated neither.
+        };
 
         let file_id = Uuid::new_v4().to_string();
         let file_meta = FileMeta {
diff --git a/tests/functional_test/sgx_trusted_lib/Cargo.toml b/tests/functional_test/sgx_trusted_lib/Cargo.toml
index 65b052d..56af9bf 100644
--- a/tests/functional_test/sgx_trusted_lib/Cargo.toml
+++ b/tests/functional_test/sgx_trusted_lib/Cargo.toml
@@ -12,7 +12,7 @@ crate-type = ["staticlib"]
 
 [features]
 default = []
-mesalock_sgx = ["sgx_tstd", "sgx_tunittest", "mesatee_core/mesalock_sgx", "kms_client/mesalock_sgx", "acs_client/mesalock_sgx", "tdfs_internal_client/mesalock_sgx", "tms_internal_client/mesalock_sgx", "tms_internal_proto/mesalock_sgx", "protected_fs_rs/mesalock_sgx"]
+mesalock_sgx = ["sgx_tstd", "sgx_tunittest", "mesatee_core/mesalock_sgx", "kms_proto/mesalock_sgx", "acs_client/mesalock_sgx", "tdfs_internal_client/mesalock_sgx", "tms_internal_client/mesalock_sgx", "tms_internal_proto/mesalock_sgx", "protected_fs_rs/mesalock_sgx"]
 cov = ["sgx_cov"]
 
 [dependencies]
@@ -21,7 +21,7 @@ log             = { version = "0.4.6" }
 env_logger      = { version = "0.7.1" }
 rand            = { version = "0.7" }
 
-kms_client      = { path = "../../../mesatee_services/kms/client", optional = true }
+kms_proto      = { path = "../../../mesatee_services/kms/proto", optional = true }
 acs_client      = { path = "../../../mesatee_services/acs/client", optional = true }
 tdfs_internal_client = { path = "../../../mesatee_services/tdfs/internal/client", optional = true }
 tms_internal_client = { path = "../../../mesatee_services/tms/internal/client", optional = true }
diff --git a/tests/functional_test/sgx_trusted_lib/src/tests/common_setup.rs b/tests/functional_test/sgx_trusted_lib/src/tests/common_setup.rs
index fa5a8a2..515fe11 100644
--- a/tests/functional_test/sgx_trusted_lib/src/tests/common_setup.rs
+++ b/tests/functional_test/sgx_trusted_lib/src/tests/common_setup.rs
@@ -15,7 +15,7 @@
 // specific language governing permissions and limitations
 // under the License.
 use acs_client::ACSClient;
-use kms_client::KMSClient;
+use kms_proto::KMSClient;
 use mesatee_core::config;
 use tdfs_internal_client::TDFSClient;
 use tms_internal_client::TMSClient;
diff --git a/tests/functional_test/sgx_trusted_lib/src/tests/kms_test.rs b/tests/functional_test/sgx_trusted_lib/src/tests/kms_test.rs
index d2c08a7..dee1146 100644
--- a/tests/functional_test/sgx_trusted_lib/src/tests/kms_test.rs
+++ b/tests/functional_test/sgx_trusted_lib/src/tests/kms_test.rs
@@ -16,22 +16,27 @@
 // under the License.
 
 use super::common_setup::setup_kms_internal_client;
+use kms_proto::proto::{CreateKeyRequest, GetKeyRequest};
+use kms_proto::EncType;
 
 pub fn api_create_key() {
     trace!("Test kms: api_create_key.");
     let mut client = setup_kms_internal_client();
-    let resp = client.request_create_key().unwrap();
+    let req = CreateKeyRequest::new(EncType::Aead);
+    let resp = client.create_key(req).unwrap();
 
-    let key_id = resp.key_id;
-    let key_config = resp.config;
-    let resp = client.request_get_key(&key_id).unwrap();
+    let key_id = resp.get_key_id();
+    let key_config = resp.get_key_config().unwrap();
+    let req = GetKeyRequest::new(&key_id);
+    let resp = client.get_key(req).unwrap();
 
-    assert_eq!(key_config, resp.config);
+    assert_eq!(key_config, resp.get_key_config().unwrap());
 }
 
 pub fn api_get_deleted_key() {
     trace!("Test kms: api get deleted key.");
     let mut client = setup_kms_internal_client();
-    let resp = client.request_get_key("fake_kms_record_to_be_deleted");
+    let req = GetKeyRequest::new("fake_kms_record_to_be_deleted");
+    let resp = client.get_key(req);
     assert!(resp.is_err());
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@mesatee.apache.org
For additional commands, e-mail: commits-help@mesatee.apache.org


Mime
View raw message