This is an automated email from the ASF dual-hosted git repository.

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


The following commit(s) were added to refs/heads/develop by this push:
     new dcf3ec4  [worker] Support encrypted/raw input with tests (#210)
dcf3ec4 is described below

commit dcf3ec40163fed73c0101939634d558fde952e29
Author: Zhaofeng Chen <[email protected]>
AuthorDate: Wed Jan 29 11:04:51 2020 -0800

    [worker] Support encrypted/raw input with tests (#210)
---
 cmake/scripts/prep.sh                              |   4 +-
 .../enclave/src/teaclave_execution_service.rs      |  37 +++++---
 .../enclave/src/teaclave_worker.rs                 |  23 ++++-
 tests/unit_tests/enclave/Cargo.toml                |   1 +
 tests/unit_tests/enclave/src/lib.rs                |   1 +
 types/Cargo.toml                                   |  12 ++-
 types/src/crypto.rs                                | 103 +++++++++++++++++++++
 types/src/lib.rs                                   |  13 +++
 types/src/unittest.rs                              |  86 +++++++++++++++++
 types/src/worker.rs                                |  74 ++++++++++++++-
 worker/src/function/gbdt_training.rs               |   4 +-
 worker/src/lib.rs                                  |   1 +
 worker/src/runtime/default.rs                      |   5 +-
 worker/src/runtime/mod.rs                          |  18 ++++
 worker/src/runtime/{raw.rs => raw_io.rs}           |  23 ++---
 15 files changed, 374 insertions(+), 31 deletions(-)

diff --git a/cmake/scripts/prep.sh b/cmake/scripts/prep.sh
index a6acf37..45ae028 100755
--- a/cmake/scripts/prep.sh
+++ b/cmake/scripts/prep.sh
@@ -21,8 +21,10 @@ mkdir -p ${MESATEE_OUT_DIR} ${MESATEE_TARGET_DIR} 
${MESATEE_SERVICE_INSTALL_DIR}
 cp -RT ${CMAKE_SOURCE_DIR}/keys/auditors/ ${MESATEE_AUDITORS_DIR}/
 cp ${CMAKE_SOURCE_DIR}/config/runtime.config.toml 
${MESATEE_SERVICE_INSTALL_DIR}
 cp ${CMAKE_SOURCE_DIR}/config/runtime.config.toml ${MESATEE_TEST_INSTALL_DIR}
-cp -r ${CMAKE_SOURCE_DIR}/tests/test_cases/ ${MESATEE_SERVICE_INSTALL_DIR}
 cp -r ${CMAKE_SOURCE_DIR}/tests/test_cases/ ${MESATEE_TEST_INSTALL_DIR}
+# temporary workaround for sharing test_cases directory between tests and 
services
+rm -f ${MESATEE_SERVICE_INSTALL_DIR}/test_cases
+ln -s ${MESATEE_TEST_INSTALL_DIR}/test_cases 
${MESATEE_SERVICE_INSTALL_DIR}/test_cases
 cp -r ${CMAKE_SOURCE_DIR}/tests/fixtures/ ${MESATEE_SERVICE_INSTALL_DIR}
 cp -r ${CMAKE_SOURCE_DIR}/tests/fixtures/ ${MESATEE_TEST_INSTALL_DIR}
 # create the following symlinks to make remapped paths accessible and avoid 
repeated building
diff --git a/tests/functional_tests/enclave/src/teaclave_execution_service.rs 
b/tests/functional_tests/enclave/src/teaclave_execution_service.rs
index 7f9e75a..3b43dc2 100644
--- a/tests/functional_tests/enclave/src/teaclave_execution_service.rs
+++ b/tests/functional_tests/enclave/src/teaclave_execution_service.rs
@@ -1,19 +1,16 @@
+use anyhow;
 use serde_json;
 use sgx_tunittest::*;
+use std::io::Write;
 use std::prelude::v1::*;
+use std::untrusted::fs;
+
 use teaclave_proto::teaclave_execution_service::*;
 use teaclave_rpc::endpoint::Endpoint;
+use teaclave_types::AesGcm128CryptoInfo;
 
 pub fn run_tests() {
-    rsgx_unit_tests!(
-        test_get_success,
-        //test_get_fail,
-        //test_put_success,
-        //test_delete_success,
-        //test_enqueue_success,
-        //test_dequeue_success,
-        //test_dequeue_fail,
-    );
+    rsgx_unit_tests!(test_invoke_success,);
 }
 
 fn setup_client() -> TeaclaveExecutionClient {
@@ -21,7 +18,24 @@ fn setup_client() -> TeaclaveExecutionClient {
     TeaclaveExecutionClient::new(channel).unwrap()
 }
 
-fn test_get_success() {
+fn enc_input_file() -> anyhow::Result<()> {
+    let crypto_info_str = r#"{
+            "key": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
+            "iv": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
+    }"#;
+    let crypto_info: AesGcm128CryptoInfo = 
serde_json::from_str(crypto_info_str)?;
+
+    let plain_input = "test_cases/gbdt_training/train.txt";
+    let enc_input = "test_cases/gbdt_training/train.enc";
+    let mut bytes = fs::read_to_string(plain_input)?.into_bytes();
+    crypto_info.encrypt(&mut bytes)?;
+
+    let mut file = fs::File::create(enc_input)?;
+    file.write_all(&bytes)?;
+    Ok(())
+}
+
+fn test_invoke_success() {
     let request_payload = r#"{
         "runtime_name": "default",
         "executor_type": "native",
@@ -40,7 +54,7 @@ fn test_get_success() {
         },
         "input_files": {
             "training_data": {
-                "path": "test_cases/gbdt_training/train.txt",
+                "path": "test_cases/gbdt_training/train.enc",
                 "crypto_info": {
                     "aes_gcm128": {
                         "key": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 
14, 15],
@@ -63,6 +77,7 @@ fn test_get_success() {
     }"#;
 
     let request: StagedFunctionExecuteRequest = 
serde_json::from_str(request_payload).unwrap();
+    enc_input_file().unwrap();
 
     let mut client = setup_client();
     let response_result = client.invoke_function(request.into());
diff --git a/tests/integration_tests/enclave/src/teaclave_worker.rs 
b/tests/integration_tests/enclave/src/teaclave_worker.rs
index 6068be3..58fa711 100644
--- a/tests/integration_tests/enclave/src/teaclave_worker.rs
+++ b/tests/integration_tests/enclave/src/teaclave_worker.rs
@@ -1,12 +1,32 @@
 use sgx_tunittest::*;
+use std::io::Write;
 use std::prelude::v1::*;
 use std::untrusted::fs;
 
 use serde_json;
 
+use anyhow;
+use teaclave_types::AesGcm128CryptoInfo;
 use teaclave_types::WorkerInvocation;
 use teaclave_worker::Worker;
 
+fn enc_input_file() -> anyhow::Result<()> {
+    let crypto_info_str = r#"{
+            "key": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
+            "iv": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
+    }"#;
+    let crypto_info: AesGcm128CryptoInfo = 
serde_json::from_str(crypto_info_str)?;
+
+    let plain_input = "test_cases/gbdt_training/train.txt";
+    let enc_input = "test_cases/gbdt_training/train.enc";
+    let mut bytes = fs::read_to_string(plain_input)?.into_bytes();
+    crypto_info.encrypt(&mut bytes)?;
+
+    let mut file = fs::File::create(enc_input)?;
+    file.write_all(&bytes)?;
+    Ok(())
+}
+
 fn test_start_worker() {
     let request_payload = r#"{
         "runtime_name": "default",
@@ -26,7 +46,7 @@ fn test_start_worker() {
         },
         "input_files": {
             "training_data": {
-                "path": "test_cases/gbdt_training/train.txt",
+                "path": "test_cases/gbdt_training/train.enc",
                 "crypto_info": {
                     "aes_gcm128": {
                         "key": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 
14, 15],
@@ -48,6 +68,7 @@ fn test_start_worker() {
         }
     }"#;
 
+    enc_input_file().unwrap();
     let plain_output = "test_cases/gbdt_training/model.txt.out";
     let expected_output = "test_cases/gbdt_training/expected_model.txt";
     let request: WorkerInvocation = 
serde_json::from_str(request_payload).unwrap();
diff --git a/tests/unit_tests/enclave/Cargo.toml 
b/tests/unit_tests/enclave/Cargo.toml
index 584a377..8362c64 100644
--- a/tests/unit_tests/enclave/Cargo.toml
+++ b/tests/unit_tests/enclave/Cargo.toml
@@ -19,6 +19,7 @@ mesalock_sgx = [
   "teaclave_rpc/mesalock_sgx",
   "teaclave_service_enclave_utils/mesalock_sgx",
   "teaclave_types/mesalock_sgx",
+  "teaclave_types/enclave_unit_test",
   "teaclave_config/mesalock_sgx",
   "teaclave_authentication_service_enclave/mesalock_sgx",
   "teaclave_authentication_service_enclave/enclave_unit_test",
diff --git a/tests/unit_tests/enclave/src/lib.rs 
b/tests/unit_tests/enclave/src/lib.rs
index b29d6de..7082239 100644
--- a/tests/unit_tests/enclave/src/lib.rs
+++ b/tests/unit_tests/enclave/src/lib.rs
@@ -44,6 +44,7 @@ fn handle_run_test(_args: &RunTestInput) -> 
Result<RunTestOutput> {
     teaclave_execution_service_enclave::tests::run_tests();
     teaclave_authentication_service_enclave::tests::run_tests();
     teaclave_worker::tests::run_tests();
+    teaclave_types::tests::run_tests();
 
     Ok(RunTestOutput::default())
 }
diff --git a/types/Cargo.toml b/types/Cargo.toml
index 7e12e9d..a3aeb5e 100644
--- a/types/Cargo.toml
+++ b/types/Cargo.toml
@@ -7,10 +7,18 @@ license = "Apache-2.0"
 edition = "2018"
 
 [features]
-default = []
-mesalock_sgx = ["sgx_tstd"]
+default = [
+    "protected_fs_rs/default",
+]
+mesalock_sgx = [
+    "sgx_tstd",
+    "protected_fs_rs/mesalock_sgx",
+]
+enclave_unit_test = []
 
 [dependencies]
+protected_fs_rs  = { path = "../common/protected_fs_rs", default-features = 
false}
+
 anyhow       = { version = "1.0.26" }
 sgx_types    = { version = "1.1.0" }
 hex          = { version = "0.4.0" }
diff --git a/types/src/crypto.rs b/types/src/crypto.rs
index 96662c4..04bc7d3 100644
--- a/types/src/crypto.rs
+++ b/types/src/crypto.rs
@@ -2,6 +2,7 @@
 use std::prelude::v1::*;
 
 use anyhow;
+use ring;
 use serde::{Deserialize, Serialize};
 use std::format;
 
@@ -31,6 +32,17 @@ impl AesGcm256CryptoInfo {
         info.iv.copy_from_slice(iv);
         Ok(info)
     }
+
+    pub fn decrypt(&self, in_out: &mut Vec<u8>) -> anyhow::Result<()> {
+        let plaintext_len =
+            aead_decrypt(&ring::aead::AES_256_GCM, in_out, &self.key, 
&self.iv)?.len();
+        in_out.truncate(plaintext_len);
+        Ok(())
+    }
+
+    pub fn encrypt(&self, in_out: &mut Vec<u8>) -> anyhow::Result<()> {
+        aead_encrypt(&ring::aead::AES_128_GCM, in_out, &self.key, &self.iv)
+    }
 }
 
 const AES_GCM_128_KEY_LENGTH: usize = 16;
@@ -61,6 +73,17 @@ impl AesGcm128CryptoInfo {
         info.iv.copy_from_slice(iv);
         Ok(info)
     }
+
+    pub fn decrypt(&self, in_out: &mut Vec<u8>) -> anyhow::Result<()> {
+        let plaintext_len =
+            aead_decrypt(&ring::aead::AES_128_GCM, in_out, &self.key, 
&self.iv)?.len();
+        in_out.truncate(plaintext_len);
+        Ok(())
+    }
+
+    pub fn encrypt(&self, in_out: &mut Vec<u8>) -> anyhow::Result<()> {
+        aead_encrypt(&ring::aead::AES_128_GCM, in_out, &self.key, &self.iv)
+    }
 }
 
 const TEACLAVE_FILE_ROOT_KEY_128_LENGTH: usize = 16;
@@ -90,3 +113,83 @@ pub enum TeaclaveFileCryptoInfo {
     AesGcm256(AesGcm256CryptoInfo),
     TeaclaveFileRootKey128(TeaclaveFileRootKey128),
 }
+
+fn make_teaclave_aad() -> ring::aead::Aad<[u8; 8]> {
+    let bytes = [0u8; 8];
+    ring::aead::Aad::from(bytes)
+}
+
+pub fn aead_decrypt<'a>(
+    alg: &'static ring::aead::Algorithm,
+    in_out: &'a mut [u8],
+    key: &[u8],
+    iv: &[u8],
+) -> anyhow::Result<&'a mut [u8]> {
+    let key = ring::aead::UnboundKey::new(alg, key)
+        .map_err(|_| anyhow::anyhow!("Aead unbound key init error"))?;
+    let nonce = ring::aead::Nonce::try_assume_unique_for_key(iv)
+        .map_err(|_| anyhow::anyhow!("Aead iv init error"))?;
+    let aad = make_teaclave_aad();
+
+    let dec_key = ring::aead::LessSafeKey::new(key);
+    let slice = dec_key
+        .open_in_place(nonce, aad, in_out)
+        .map_err(|_| anyhow::anyhow!("Aead open_in_place error"))?;
+    Ok(slice)
+}
+
+pub fn aead_encrypt(
+    alg: &'static ring::aead::Algorithm,
+    in_out: &mut Vec<u8>,
+    key: &[u8],
+    iv: &[u8],
+) -> anyhow::Result<()> {
+    let key = ring::aead::UnboundKey::new(alg, key)
+        .map_err(|_| anyhow::anyhow!("Aead unbound key init error"))?;
+    let nonce = ring::aead::Nonce::try_assume_unique_for_key(iv)
+        .map_err(|_| anyhow::anyhow!("Aead iv init error"))?;
+    let aad = make_teaclave_aad();
+
+    let enc_key = ring::aead::LessSafeKey::new(key);
+    enc_key
+        .seal_in_place_append_tag(nonce, aad, in_out)
+        .map_err(|_| anyhow::anyhow!("Aead seal_in_place_append_tag error"))?;
+    Ok(())
+}
+
+#[cfg(feature = "enclave_unit_test")]
+pub mod tests {
+    use super::*;
+    use crate::unit_tests;
+    use crate::unittest::*;
+
+    pub fn run_tests() -> usize {
+        unit_tests!(test_aead_enc_then_dec, test_crypto_info,)
+    }
+
+    fn test_aead_enc_then_dec() {
+        let plain_text: [u8; 5] = [0xde, 0xff, 0xab, 0xcd, 0x90];
+        let key = [0x90u8; AES_GCM_128_KEY_LENGTH];
+        let iv = [0x89u8; 12];
+
+        let mut buf = plain_text.to_vec();
+        aead_encrypt(&ring::aead::AES_128_GCM, &mut buf, &key, &iv).unwrap();
+        let result = aead_decrypt(&ring::aead::AES_128_GCM, &mut buf, &key, 
&iv).unwrap();
+        assert_eq!(&result[..], &plain_text[..]);
+    }
+
+    fn test_crypto_info() {
+        let key = [0x90u8; AES_GCM_128_KEY_LENGTH];
+        let iv = [0x89u8; AES_GCM_128_IV_LENGTH];
+        let crypto_info = AesGcm128CryptoInfo { key, iv };
+
+        let plain_text: [u8; 5] = [0xde, 0xff, 0xab, 0xcd, 0x90];
+        let mut buf = plain_text.to_vec();
+
+        crypto_info.encrypt(&mut buf).unwrap();
+        assert_ne!(&buf[..], &plain_text[..]);
+
+        crypto_info.decrypt(&mut buf).unwrap();
+        assert_eq!(&buf[..], &plain_text[..]);
+    }
+}
diff --git a/types/src/lib.rs b/types/src/lib.rs
index 97b0af1..6d88c23 100644
--- a/types/src/lib.rs
+++ b/types/src/lib.rs
@@ -1,5 +1,6 @@
 #![cfg_attr(feature = "mesalock_sgx", no_std)]
 #[cfg(feature = "mesalock_sgx")]
+#[macro_use]
 extern crate sgx_tstd as std;
 
 #[cfg(feature = "mesalock_sgx")]
@@ -18,6 +19,8 @@ mod crypto;
 pub use crypto::*;
 mod worker;
 pub use worker::*;
+mod unittest;
+pub use unittest::*;
 
 /// Status for Ecall
 #[repr(C)]
@@ -170,3 +173,13 @@ pub enum TeaclaveServiceResponseError {
 }
 
 pub type TeaclaveServiceResponseResult<T> = std::result::Result<T, 
TeaclaveServiceResponseError>;
+
+#[cfg(feature = "enclave_unit_test")]
+pub mod tests {
+    use super::*;
+
+    pub fn run_tests() {
+        worker::tests::run_tests();
+        crypto::tests::run_tests();
+    }
+}
diff --git a/types/src/unittest.rs b/types/src/unittest.rs
new file mode 100644
index 0000000..47c438c
--- /dev/null
+++ b/types/src/unittest.rs
@@ -0,0 +1,86 @@
+// 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.
+
+#[cfg(feature = "mesalock_sgx")]
+use std::prelude::v1::*;
+
+use std::string::String;
+use std::vec::Vec;
+
+#[macro_export]
+macro_rules! unit_tests {
+    (
+        $($f : expr),* $(,)?
+    ) => {
+        {
+            unit_test_start();
+            let mut ntestcases : u64 = 0u64;
+            let mut failurecases : Vec<String> = Vec::new();
+            $(unit_test(&mut ntestcases, &mut failurecases, 
$f,stringify!($f));)*
+            unit_test_end(ntestcases, failurecases)
+        }
+    }
+}
+
+pub fn unit_test_start() {
+    println!("\nstart running tests");
+}
+
+pub fn unit_test_end(ntestcases: u64, failurecases: Vec<String>) -> usize {
+    let ntotal = ntestcases as usize;
+    let nsucc = ntestcases as usize - failurecases.len();
+
+    if !failurecases.is_empty() {
+        print!("\nfailures: ");
+        println!(
+            "    {}",
+            failurecases
+                .iter()
+                .fold(String::new(), |s, per| s + "\n    " + per)
+        );
+    }
+
+    if ntotal == nsucc {
+        print!("\ntest result \x1B[1;32mok\x1B[0m. ");
+    } else {
+        print!("\ntest result \x1B[1;31mFAILED\x1B[0m. ");
+    }
+
+    println!(
+        "{} tested, {} passed, {} failed",
+        ntotal,
+        nsucc,
+        ntotal - nsucc
+    );
+    failurecases.len()
+}
+
+pub fn unit_test<F, R>(ncases: &mut u64, failurecases: &mut Vec<String>, f: F, 
name: &str)
+where
+    F: FnOnce() -> R + std::panic::UnwindSafe,
+{
+    *ncases += 1;
+    let ret = std::panic::catch_unwind(|| {
+        f();
+    });
+    if ret.is_ok() {
+        println!("testing {} ... \x1B[1;32mok\x1B[0m!", name);
+    } else {
+        println!("testing {} ... \x1B[1;31mfailed\x1B[0m!", name);
+        failurecases.push(String::from(name));
+    }
+}
diff --git a/types/src/worker.rs b/types/src/worker.rs
index bc42861..29a4248 100644
--- a/types/src/worker.rs
+++ b/types/src/worker.rs
@@ -3,9 +3,18 @@ use std::prelude::v1::*;
 
 use serde::{Deserialize, Serialize};
 use std::collections::HashMap;
+use std::format;
+use std::io::{self, Read};
+
+use protected_fs::ProtectedFile;
+
+#[cfg(feature = "mesalock_sgx")]
+use std::untrusted::fs::File;
+
+#[cfg(not(feature = "mesalock_sgx"))]
+use std::fs::File;
 
 use anyhow;
-use std::format;
 
 use crate::TeaclaveFileCryptoInfo;
 
@@ -38,12 +47,63 @@ impl std::fmt::Display for TeaclaveExecutorSelector {
     }
 }
 
+pub struct ReadBuffer {
+    bytes: Vec<u8>,
+    remaining: usize,
+}
+
+impl ReadBuffer {
+    pub fn from_vec(bytes: Vec<u8>) -> Self {
+        let remaining = bytes.len();
+        ReadBuffer { bytes, remaining }
+    }
+}
+
+impl io::Read for ReadBuffer {
+    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
+        let amt = std::cmp::min(buf.len(), self.remaining);
+        let cur = self.bytes.len() - self.remaining;
+        buf[..amt].copy_from_slice(&self.bytes[cur..cur + amt]);
+        self.remaining -= amt;
+        Ok(amt)
+    }
+}
+
 #[derive(Serialize, Deserialize, Debug)]
 pub struct TeaclaveWorkerFileInfo {
     pub path: std::path::PathBuf,
     pub crypto_info: TeaclaveFileCryptoInfo,
 }
 
+fn read_all_bytes<P: AsRef<std::path::Path>>(path: P) -> 
anyhow::Result<Vec<u8>> {
+    let mut content = Vec::new();
+    let mut file = File::open(path)?;
+    file.read_to_end(&mut content)?;
+    Ok(content)
+}
+
+impl TeaclaveWorkerFileInfo {
+    pub fn get_readable_io(&self) -> anyhow::Result<Box<dyn io::Read>> {
+        let readable: Box<dyn io::Read> = match &self.crypto_info {
+            TeaclaveFileCryptoInfo::AesGcm128(crypto) => {
+                let mut bytes = read_all_bytes(&self.path)?;
+                crypto.decrypt(&mut bytes)?;
+                Box::new(ReadBuffer::from_vec(bytes))
+            }
+            TeaclaveFileCryptoInfo::AesGcm256(crypto) => {
+                let mut bytes = read_all_bytes(&self.path)?;
+                crypto.decrypt(&mut bytes)?;
+                Box::new(ReadBuffer::from_vec(bytes))
+            }
+            TeaclaveFileCryptoInfo::TeaclaveFileRootKey128(crypto) => {
+                let f = ProtectedFile::open_ex(&self.path, &crypto.key)?;
+                Box::new(f)
+            }
+        };
+        Ok(readable)
+    }
+}
+
 #[derive(Serialize, Deserialize, Debug)]
 pub struct TeaclaveWorkerFileRegistry {
     #[serde(flatten)]
@@ -111,3 +171,15 @@ pub struct WorkerInvocation {
     pub input_files: TeaclaveWorkerFileRegistry,
     pub output_files: TeaclaveWorkerFileRegistry,
 }
+
+#[cfg(feature = "enclave_unit_test")]
+pub mod tests {
+    use super::*;
+    //use crate::unit_tests;
+    //use crate::unittest::*;
+
+    pub fn run_tests() -> usize {
+        //unit_tests!()
+        0
+    }
+}
diff --git a/worker/src/function/gbdt_training.rs 
b/worker/src/function/gbdt_training.rs
index c4c79f6..b597f02 100644
--- a/worker/src/function/gbdt_training.rs
+++ b/worker/src/function/gbdt_training.rs
@@ -126,7 +126,7 @@ fn parse_training_data(input: impl io::Read, feature_size: 
usize) -> anyhow::Res
 pub mod tests {
     use super::*;
     use crate::function::TeaclaveFunction;
-    use crate::runtime::DefaultRuntime;
+    use crate::runtime::RawIoRuntime;
     use std::untrusted::fs;
     use teaclave_types::{TeaclaveFunctionArguments, 
TeaclaveWorkerFileRegistry};
 
@@ -176,7 +176,7 @@ pub mod tests {
         let func_args: TeaclaveFunctionArguments = 
serde_json::from_str(&args_json).unwrap();
         let input_files: TeaclaveWorkerFileRegistry = 
serde_json::from_str(&input_json).unwrap();
         let output_files: TeaclaveWorkerFileRegistry = 
serde_json::from_str(&output_json).unwrap();
-        let runtime = Box::new(DefaultRuntime::new(input_files, output_files));
+        let runtime = Box::new(RawIoRuntime::new(input_files, output_files));
 
         let function = GbdtTraining;
         let summary = function.execute(runtime, func_args).unwrap();
diff --git a/worker/src/lib.rs b/worker/src/lib.rs
index 2d6ebfe..a5be765 100644
--- a/worker/src/lib.rs
+++ b/worker/src/lib.rs
@@ -37,5 +37,6 @@ pub mod tests {
 
     pub fn run_tests() {
         function::tests::run_tests();
+        runtime::tests::run_tests();
     }
 }
diff --git a/worker/src/runtime/default.rs b/worker/src/runtime/default.rs
index 0ef07fb..1f0a361 100644
--- a/worker/src/runtime/default.rs
+++ b/worker/src/runtime/default.rs
@@ -50,8 +50,9 @@ impl TeaclaveRuntime for DefaultRuntime {
             .entries
             .get(identifier)
             .ok_or_else(|| anyhow::anyhow!("Invalid input file identifier."))?;
-        let f = File::open(&file_info.path)?;
-        Ok(Box::new(f))
+
+        let readable = file_info.get_readable_io()?;
+        Ok(readable)
     }
 
     fn create_output(&self, identifier: &str) -> anyhow::Result<Box<dyn 
io::Write>> {
diff --git a/worker/src/runtime/mod.rs b/worker/src/runtime/mod.rs
index c5c1ecf..f702054 100644
--- a/worker/src/runtime/mod.rs
+++ b/worker/src/runtime/mod.rs
@@ -28,3 +28,21 @@ pub trait TeaclaveRuntime {
 
 mod default;
 pub use default::DefaultRuntime;
+
+#[cfg(feature = "enclave_unit_test")]
+mod raw_io;
+#[cfg(feature = "enclave_unit_test")]
+pub use raw_io::RawIoRuntime;
+
+#[cfg(feature = "enclave_unit_test")]
+pub mod tests {
+    use super::*;
+    use sgx_tunittest::*;
+
+    pub fn run_tests() -> usize {
+        rsgx_unit_tests!(
+            //DefultRuntime::tests::test_open_input();
+            //DefultRuntime::tests::test_create_output();
+        )
+    }
+}
diff --git a/worker/src/runtime/raw.rs b/worker/src/runtime/raw_io.rs
similarity index 78%
rename from worker/src/runtime/raw.rs
rename to worker/src/runtime/raw_io.rs
index c5fbca3..1d47262 100644
--- a/worker/src/runtime/raw.rs
+++ b/worker/src/runtime/raw_io.rs
@@ -18,36 +18,36 @@
 #[cfg(feature = "mesalock_sgx")]
 use std::prelude::v1::*;
 
-use std::collections::HashMap;
 use std::io;
 use std::untrusted::fs::File;
 
 use anyhow;
 
 use super::TeaclaveRuntime;
-use crate::worker::TeaclaveWorkerFileInfo;
+use teaclave_types::TeaclaveWorkerFileRegistry;
 
-pub struct DefaultRuntime {
-    input_files: HashMap<String, TeaclaveWorkerFileInfo>,
-    output_files: HashMap<String, TeaclaveWorkerFileInfo>,
+pub struct RawIoRuntime {
+    input_files: TeaclaveWorkerFileRegistry,
+    output_files: TeaclaveWorkerFileRegistry,
 }
 
-impl DefaultRuntime {
+impl RawIoRuntime {
     pub fn new(
-        input_files: HashMap<String, TeaclaveWorkerFileInfo>,
-        output_files: HashMap<String, TeaclaveWorkerFileInfo>,
-    ) -> DefaultRuntime {
-        DefaultRuntime {
+        input_files: TeaclaveWorkerFileRegistry,
+        output_files: TeaclaveWorkerFileRegistry,
+    ) -> RawIoRuntime {
+        RawIoRuntime {
             input_files,
             output_files,
         }
     }
 }
 
-impl TeaclaveRuntime for DefaultRuntime {
+impl TeaclaveRuntime for RawIoRuntime {
     fn open_input(&self, identifier: &str) -> anyhow::Result<Box<dyn 
io::Read>> {
         let file_info = self
             .input_files
+            .entries
             .get(identifier)
             .ok_or_else(|| anyhow::anyhow!("Invalid input file identifier."))?;
         let f = File::open(&file_info.path)?;
@@ -57,6 +57,7 @@ impl TeaclaveRuntime for DefaultRuntime {
     fn create_output(&self, identifier: &str) -> anyhow::Result<Box<dyn 
io::Write>> {
         let file_info = self
             .output_files
+            .entries
             .get(identifier)
             .ok_or_else(|| anyhow::anyhow!("Invalide output file 
identifier"))?;
         let f = File::create(&file_info.path)?;


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to