You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@teaclave.apache.org by ms...@apache.org on 2020/01/28 04:50:16 UTC

[incubator-teaclave] branch develop updated: [services] Fix struct/funcs visibility issues

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 2d3b932  [services] Fix struct/funcs visibility issues
2d3b932 is described below

commit 2d3b932270d5cd00dba19bd370ea000667731d2f
Author: Mingshen Sun <bo...@mssun.me>
AuthorDate: Mon Jan 27 20:43:23 2020 -0800

    [services] Fix struct/funcs visibility issues
---
 services/authentication/enclave/src/service.rs   | 25 ++++++++++++------------
 services/authentication/enclave/src/user_db.rs   | 18 ++++++++---------
 services/authentication/enclave/src/user_info.rs | 25 ++++++++++++------------
 services/database/enclave/src/proxy.rs           |  4 ++--
 services/database/enclave/src/service.rs         | 14 ++++++-------
 5 files changed, 43 insertions(+), 43 deletions(-)

diff --git a/services/authentication/enclave/src/service.rs b/services/authentication/enclave/src/service.rs
index d4ea73c..f0a9be7 100644
--- a/services/authentication/enclave/src/service.rs
+++ b/services/authentication/enclave/src/service.rs
@@ -1,8 +1,8 @@
 use crate::user_db::{Database, DbClient, DbError};
 use crate::user_info::{UserInfo, JWT_SECRET_LEN};
-use rand::prelude::RngCore;
+use rand::RngCore;
 use std::prelude::v1::*;
-use std::time::{SystemTime, UNIX_EPOCH};
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
 use std::untrusted::time::SystemTimeEx;
 use teaclave_proto::teaclave_authentication_service::{
     TeaclaveAuthentication, UserAuthenticateRequest, UserAuthenticateResponse, UserLoginRequest,
@@ -13,7 +13,7 @@ use teaclave_types::{TeaclaveServiceResponseError, TeaclaveServiceResponseResult
 use thiserror::Error;
 
 #[derive(Error, Debug)]
-pub enum TeaclaveAuthenticationError {
+enum TeaclaveAuthenticationError {
     #[error("permission denied")]
     PermissionDenied,
     #[error("invalid userid")]
@@ -42,7 +42,7 @@ pub(crate) struct TeaclaveAuthenticationService {
 }
 
 impl TeaclaveAuthenticationService {
-    pub fn init() -> anyhow::Result<Self> {
+    pub(crate) fn init() -> anyhow::Result<Self> {
         let database = Database::open()?;
         let mut secret = vec![0; JWT_SECRET_LEN];
         let mut rng = rand::thread_rng();
@@ -83,18 +83,17 @@ impl TeaclaveAuthentication for TeaclaveAuthenticationService {
         if request.password.is_empty() {
             return Err(TeaclaveAuthenticationError::InvalidPassword.into());
         }
-        let user: UserInfo = match self.db_client.get_user(&request.id) {
-            Ok(value) => value,
-            Err(_) => return Err(TeaclaveAuthenticationError::PermissionDenied.into()),
-        };
+        let user = self
+            .db_client
+            .get_user(&request.id)
+            .map_err(|_| TeaclaveAuthenticationError::PermissionDenied)?;
         if !user.verify_password(&request.password) {
             Err(TeaclaveAuthenticationError::PermissionDenied.into())
         } else {
-            let now = match SystemTime::now().duration_since(UNIX_EPOCH) {
-                Ok(timestamp) => timestamp.as_secs(),
-                Err(_) => return Err(TeaclaveAuthenticationError::ServiceUnavailable.into()),
-            };
-            let exp = now + 24 * 60;
+            let now = SystemTime::now()
+                .duration_since(UNIX_EPOCH)
+                .map_err(|_| TeaclaveAuthenticationError::ServiceUnavailable)?;
+            let exp = (now + Duration::from_secs(24 * 60)).as_secs();
             match user.get_token(exp, &self.secret) {
                 Ok(token) => Ok(UserLoginResponse { token }),
                 Err(_) => Err(TeaclaveAuthenticationError::ServiceUnavailable.into()),
diff --git a/services/authentication/enclave/src/user_db.rs b/services/authentication/enclave/src/user_db.rs
index 2d1a9b8..7ff422a 100644
--- a/services/authentication/enclave/src/user_db.rs
+++ b/services/authentication/enclave/src/user_db.rs
@@ -23,7 +23,7 @@ use std::thread;
 use thiserror::Error;
 
 #[derive(Error, Debug)]
-pub enum DbError {
+pub(crate) enum DbError {
     #[error("user not exist")]
     UserNotExist,
     #[error("user exist")]
@@ -31,7 +31,7 @@ pub enum DbError {
     #[error("mpsc error")]
     ConnectionError,
     #[error("leveldb error")]
-    LevelDbError,
+    LevelDbInternalError,
     #[error("invalid response")]
     InvalidResponse,
     #[error("invalid request")]
@@ -85,12 +85,12 @@ struct DBCall {
     pub request: DbRequest,
 }
 
-pub struct Database {
+pub(crate) struct Database {
     sender: Sender<DBCall>,
 }
 
 impl Database {
-    pub fn open() -> Result<Self, DbError> {
+    pub(crate) fn open() -> Result<Self, DbError> {
         let (sender, receiver) = channel();
         thread::spawn(move || {
             let opt = rusty_leveldb::in_memory();
@@ -113,7 +113,7 @@ impl Database {
                         Some(_) => Err(DbError::UserExist),
                         None => match database.put(&request.key, &request.value) {
                             Ok(_) => Ok(DbResponse::Create),
-                            Err(_) => Err(DbError::LevelDbError),
+                            Err(_) => Err(DbError::LevelDbInternalError),
                         },
                     },
                     DbRequest::Ping => Ok(DbResponse::Ping),
@@ -134,7 +134,7 @@ impl Database {
         Ok(database)
     }
 
-    pub fn get_client(&self) -> DbClient {
+    pub(crate) fn get_client(&self) -> DbClient {
         DbClient {
             sender: self.sender.clone(),
         }
@@ -142,12 +142,12 @@ impl Database {
 }
 
 #[derive(Clone)]
-pub struct DbClient {
+pub(crate) struct DbClient {
     sender: Sender<DBCall>,
 }
 
 impl DbClient {
-    pub fn get_user(&self, id: &str) -> Result<UserInfo, DbError> {
+    pub(crate) fn get_user(&self, id: &str) -> Result<UserInfo, DbError> {
         let (sender, receiver) = channel();
         let request = DbRequest::Get(GetRequest {
             key: id.as_bytes().to_vec(),
@@ -166,7 +166,7 @@ impl DbClient {
         }
     }
 
-    pub fn create_user(&self, user: &UserInfo) -> Result<(), DbError> {
+    pub(crate) fn create_user(&self, user: &UserInfo) -> Result<(), DbError> {
         let (sender, receiver) = channel();
         let user_bytes = serde_json::to_vec(&user).map_err(|_| DbError::InvalidRequest)?;
         let request = DbRequest::Create(CreateRequest {
diff --git a/services/authentication/enclave/src/user_info.rs b/services/authentication/enclave/src/user_info.rs
index 0c780d1..aed6643 100644
--- a/services/authentication/enclave/src/user_info.rs
+++ b/services/authentication/enclave/src/user_info.rs
@@ -33,7 +33,7 @@ pub static JWT_ALG: jwt::Algorithm = jwt::Algorithm::HS512;
 pub const JWT_SECRET_LEN: usize = 512;
 
 #[derive(Clone, Serialize, Deserialize, Debug)]
-pub struct UserInfo {
+pub(crate) struct UserInfo {
     pub id: String,
     pub salt: Vec<u8>,
     pub salted_password_hash: Vec<u8>,
@@ -50,7 +50,7 @@ pub struct Claims {
 }
 
 impl UserInfo {
-    pub fn new(id: &str, password: &str) -> Self {
+    pub(crate) fn new(id: &str, password: &str) -> Self {
         let mut rng = rand::thread_rng();
         let mut salt = vec![0u8; SALT_LEN];
         rng.fill_bytes(&mut salt);
@@ -70,7 +70,7 @@ impl UserInfo {
         }
     }
 
-    pub fn verify_password(&self, password: &str) -> bool {
+    pub(crate) fn verify_password(&self, password: &str) -> bool {
         let pbkdf2_iterations = num::NonZeroU32::new(PBKDF2_ITERATIONS).unwrap();
         pbkdf2::verify(
             PBKDF2_ALG,
@@ -82,23 +82,24 @@ impl UserInfo {
         .is_ok()
     }
 
-    pub fn get_token(&self, exp: u64, secret: &[u8]) -> Result<String> {
-        let my_claims = Claims {
-            sub: self.id.clone(),
-            iss: ISSUER_NAME.to_string(),
+    pub(crate) fn get_token(&self, exp: u64, secret: &[u8]) -> Result<String> {
+        let iss = ISSUER_NAME.to_string();
+        let claims = Claims {
+            sub: self.id.to_string(),
+            iss,
             exp,
         };
         let mut header = jwt::Header::default();
         header.alg = JWT_ALG;
-        let token = jwt::encode(&header, &my_claims, secret)?;
+        let token = jwt::encode(&header, &claims, secret)?;
         Ok(token)
     }
 
-    pub fn validate_token(&self, secret: &[u8], token: &str) -> bool {
+    pub(crate) fn validate_token(&self, secret: &[u8], token: &str) -> bool {
+        let iss = ISSUER_NAME.to_string();
         let mut validation = jwt::Validation::new(JWT_ALG);
-        validation.iss = Some(ISSUER_NAME.to_string());
+        validation.iss = Some(iss);
         validation.sub = Some(self.id.to_string());
-        let token_data = jwt::decode::<Claims>(token, secret, &validation);
-        token_data.is_ok()
+        jwt::decode::<Claims>(token, secret, &validation).is_ok()
     }
 }
diff --git a/services/database/enclave/src/proxy.rs b/services/database/enclave/src/proxy.rs
index 232ac02..3d5145e 100644
--- a/services/database/enclave/src/proxy.rs
+++ b/services/database/enclave/src/proxy.rs
@@ -7,7 +7,7 @@ use teaclave_proto::teaclave_database_service::{
 use teaclave_types::TeaclaveServiceResponseResult;
 
 #[derive(Clone)]
-pub struct ProxyService {
+pub(crate) struct ProxyService {
     pub sender: Sender<ProxyRequest>,
 }
 
@@ -29,7 +29,7 @@ impl teaclave_rpc::TeaclaveService<TeaclaveDatabaseRequest, TeaclaveDatabaseResp
 }
 
 #[derive(Clone)]
-pub struct ProxyRequest {
+pub(crate) struct ProxyRequest {
     pub sender: Sender<TeaclaveServiceResponseResult<TeaclaveDatabaseResponse>>,
     pub request: TeaclaveDatabaseRequest,
 }
diff --git a/services/database/enclave/src/service.rs b/services/database/enclave/src/service.rs
index d7715fe..6eda1f8 100644
--- a/services/database/enclave/src/service.rs
+++ b/services/database/enclave/src/service.rs
@@ -12,7 +12,7 @@ use teaclave_types::{TeaclaveServiceResponseError, TeaclaveServiceResponseResult
 use thiserror::Error;
 
 #[derive(Error, Debug)]
-pub enum TeaclaveDatabaseError {
+pub(crate) enum TeaclaveDatabaseError {
     #[error("key not exist")]
     KeyNotExist,
     #[error("mpsc error")]
@@ -30,10 +30,10 @@ impl From<TeaclaveDatabaseError> for TeaclaveServiceResponseError {
 }
 
 #[teaclave_service(teaclave_database_service, TeaclaveDatabase, TeaclaveDatabaseError)]
-pub struct TeaclaveDatabaseService {
-    // LevelDB uses ```&mut self``` in its apis, but the service will use ```&self``` in each request,
-    // so we need to wrap the DB with RefCell.
-    // The service is running in a single thread, it's safe to use RefCell
+pub(crate) struct TeaclaveDatabaseService {
+    // Current LevelDB implementation is not concurrent, so we need to wrap the
+    // DB with RefCell. This service is running in a single thread, it's safe to
+    // use RefCell.
     pub database: RefCell<DB>,
     pub receiver: Receiver<ProxyRequest>,
 }
@@ -134,7 +134,7 @@ impl<'a> DBQueue<'a> {
 }
 
 impl TeaclaveDatabaseService {
-    pub fn start(&mut self) {
+    pub(crate) fn start(&mut self) {
         #[cfg(test_mode)]
         test_mode::repalce_with_mock_database(self);
 
@@ -195,7 +195,7 @@ impl TeaclaveDatabase for TeaclaveDatabaseService {
 #[cfg(test_mode)]
 mod test_mode {
     use super::*;
-    pub fn repalce_with_mock_database(service: &mut TeaclaveDatabaseService) {
+    pub(crate) fn repalce_with_mock_database(service: &mut TeaclaveDatabaseService) {
         let opt = rusty_leveldb::in_memory();
         let mut database = DB::open("mock_db", opt).unwrap();
         database.put(b"test_get_key", b"test_get_value").unwrap();


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