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/29 05:29:36 UTC

[incubator-teaclave] branch develop updated: [services] Provide both api/internal endpoints for teaclave authentication service

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 2e81682  [services] Provide both api/internal endpoints for teaclave authentication service
2e81682 is described below

commit 2e81682e5827b3bcf0f27d732810b19bc7c83d1e
Author: Mingshen Sun <bo...@mssun.me>
AuthorDate: Tue Jan 28 21:22:36 2020 -0800

    [services] Provide both api/internal endpoints for teaclave authentication service
---
 cmake/scripts/test.sh                              |  1 -
 config/runtime.config.toml                         |  1 +
 config/src/runtime.rs                              |  1 +
 services/authentication/app/src/main.rs            |  9 +++--
 services/authentication/enclave/src/lib.rs         | 42 +++++++++++++++++----
 services/authentication/enclave/src/service.rs     | 43 +++++++++++-----------
 tests/fixtures/runtime.config.toml                 |  1 +
 .../enclave/src/teaclave_authentication_service.rs |  4 +-
 8 files changed, 67 insertions(+), 35 deletions(-)

diff --git a/cmake/scripts/test.sh b/cmake/scripts/test.sh
index 7f0204a..bfa3395 100755
--- a/cmake/scripts/test.sh
+++ b/cmake/scripts/test.sh
@@ -40,7 +40,6 @@ pushd ${MESATEE_SERVICE_INSTALL_DIR}
 ./teaclave_authentication_service &
 ./teaclave_database_service &
 ./teaclave_execution_service &
-./teaclave_frontend_service &
 popd
 sleep 3
 ./teaclave_functional_tests
diff --git a/config/runtime.config.toml b/config/runtime.config.toml
index 5df1d64..b0c46fb 100644
--- a/config/runtime.config.toml
+++ b/config/runtime.config.toml
@@ -9,6 +9,7 @@ authentication = { listen_address = "0.0.0.0:7776" }
 frontend = { listen_address = "0.0.0.0:7777" }
 
 [internal_endpoints]
+authentication = { listen_address = "0.0.0.0:17776", advertised_address = "localhost:17776" }
 dbs  = { listen_address = "0.0.0.0:7778", advertised_address = "127.0.0.1:7778", inbound_services = ["frontend"] }
 execution = { listen_address = "0.0.0.0:7989", advertised_address = "127.0.0.1:7989" }
 
diff --git a/config/src/runtime.rs b/config/src/runtime.rs
index fa9db20..07f4235 100644
--- a/config/src/runtime.rs
+++ b/config/src/runtime.rs
@@ -30,6 +30,7 @@ pub struct ApiEndpointsConfig {
 
 #[derive(Debug, Serialize, Deserialize)]
 pub struct InternalEndpointsConfig {
+    pub authentication: InternalEndpoint,
     pub dbs: InternalEndpoint,
     pub execution: InternalEndpoint,
 }
diff --git a/services/authentication/app/src/main.rs b/services/authentication/app/src/main.rs
index 147c54f..3966a3b 100644
--- a/services/authentication/app/src/main.rs
+++ b/services/authentication/app/src/main.rs
@@ -37,9 +37,12 @@ fn main() -> Result<()> {
 fn start_enclave_service(tee: &TeeBinder) -> Result<()> {
     info!("Start enclave service");
     let config = teaclave_config::RuntimeConfig::from_toml("runtime.config.toml")?;
-    let listen_address = &config.api_endpoints.authentication.listen_address;
-    let listener = TcpListener::bind(listen_address)?;
-    let fds = vec![listener.into_raw_fd()];
+    let api_listen_address = &config.api_endpoints.authentication.listen_address;
+    let internal_listen_address = &config.internal_endpoints.authentication.listen_address;
+    let api_listener = TcpListener::bind(api_listen_address)?;
+    let internal_listener = TcpListener::bind(internal_listen_address)?;
+    let fds = vec![api_listener.into_raw_fd(), internal_listener.into_raw_fd()];
+
     let input = StartServiceInput { fds, config };
     let cmd = ECallCommand::StartService;
     let _ = tee.invoke::<StartServiceInput, StartServiceOutput>(cmd.into(), input);
diff --git a/services/authentication/enclave/src/lib.rs b/services/authentication/enclave/src/lib.rs
index 1ff037f..1fb5a45 100644
--- a/services/authentication/enclave/src/lib.rs
+++ b/services/authentication/enclave/src/lib.rs
@@ -25,6 +25,8 @@ extern crate log;
 
 use anyhow::Result;
 use std::prelude::v1::*;
+use std::sync::Arc;
+use std::thread;
 use teaclave_attestation::RemoteAttestation;
 use teaclave_ipc::proto::{
     ECallCommand, FinalizeEnclaveInput, FinalizeEnclaveOutput, InitEnclaveInput, InitEnclaveOutput,
@@ -42,13 +44,11 @@ mod service;
 mod user_db;
 mod user_info;
 
-#[handle_ecall]
-fn handle_start_service(args: &StartServiceInput) -> Result<StartServiceOutput> {
-    debug!("handle_start_service");
-    let listener = std::net::TcpListener::new(args.fds[0])?;
-    let ias_config = &args.config.ias.as_ref().unwrap();
-    let attestation =
-        RemoteAttestation::generate_and_endorse(&ias_config.ias_key, &ias_config.ias_spid).unwrap();
+fn start_endpoint(
+    listener: std::net::TcpListener,
+    db_client: user_db::DbClient,
+    attestation: Arc<RemoteAttestation>,
+) {
     let config = SgxTrustedTlsServerConfig::new_without_verifier(
         &attestation.cert,
         &attestation.private_key,
@@ -60,13 +60,39 @@ fn handle_start_service(args: &StartServiceInput) -> Result<StartServiceOutput>
         TeaclaveAuthenticationRequest,
     >::new(listener, &config);
 
-    let service = service::TeaclaveAuthenticationService::init().unwrap();
+    let service = service::TeaclaveAuthenticationService::new(db_client).unwrap();
     match server.start(service) {
         Ok(_) => (),
         Err(e) => {
             error!("Service exit, error: {}.", e);
         }
     }
+}
+
+#[handle_ecall]
+fn handle_start_service(args: &StartServiceInput) -> Result<StartServiceOutput> {
+    debug!("handle_start_service");
+    let api_listener = std::net::TcpListener::new(args.fds[0])?;
+    let internal_listener = std::net::TcpListener::new(args.fds[1])?;
+    let ias_config = &args.config.ias.as_ref().unwrap();
+    let attestation = Arc::new(
+        RemoteAttestation::generate_and_endorse(&ias_config.ias_key, &ias_config.ias_spid).unwrap(),
+    );
+    let database = user_db::Database::open()?;
+
+    let attestation_ref = attestation.clone();
+    let client = database.get_client();
+    let api_endpoint_thread_handler = thread::spawn(move || {
+        start_endpoint(api_listener, client, attestation_ref);
+    });
+
+    let client = database.get_client();
+    let internal_endpoint_thread_handler = thread::spawn(move || {
+        start_endpoint(internal_listener, client, attestation);
+    });
+
+    api_endpoint_thread_handler.join().unwrap();
+    internal_endpoint_thread_handler.join().unwrap();
 
     Ok(StartServiceOutput::default())
 }
diff --git a/services/authentication/enclave/src/service.rs b/services/authentication/enclave/src/service.rs
index f0a9be7..f574906 100644
--- a/services/authentication/enclave/src/service.rs
+++ b/services/authentication/enclave/src/service.rs
@@ -1,4 +1,4 @@
-use crate::user_db::{Database, DbClient, DbError};
+use crate::user_db::{DbClient, DbError};
 use crate::user_info::{UserInfo, JWT_SECRET_LEN};
 use rand::RngCore;
 use std::prelude::v1::*;
@@ -38,18 +38,17 @@ impl From<TeaclaveAuthenticationError> for TeaclaveServiceResponseError {
 #[derive(Clone)]
 pub(crate) struct TeaclaveAuthenticationService {
     db_client: DbClient,
-    secret: Vec<u8>,
+    jwt_secret: Vec<u8>,
 }
 
 impl TeaclaveAuthenticationService {
-    pub(crate) fn init() -> anyhow::Result<Self> {
-        let database = Database::open()?;
-        let mut secret = vec![0; JWT_SECRET_LEN];
+    pub(crate) fn new(db_client: DbClient) -> anyhow::Result<Self> {
+        let mut jwt_secret = vec![0; JWT_SECRET_LEN];
         let mut rng = rand::thread_rng();
-        rng.fill_bytes(&mut secret);
+        rng.fill_bytes(&mut jwt_secret);
         Ok(Self {
-            db_client: database.get_client(),
-            secret,
+            db_client,
+            jwt_secret,
         })
     }
 }
@@ -94,7 +93,7 @@ impl TeaclaveAuthentication for TeaclaveAuthenticationService {
                 .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) {
+            match user.get_token(exp, &self.jwt_secret) {
                 Ok(token) => Ok(UserLoginResponse { token }),
                 Err(_) => Err(TeaclaveAuthenticationError::ServiceUnavailable.into()),
             }
@@ -113,7 +112,7 @@ impl TeaclaveAuthentication for TeaclaveAuthenticationService {
             Err(_) => return Ok(UserAuthenticateResponse { accept: false }),
         };
         Ok(UserAuthenticateResponse {
-            accept: user.validate_token(&self.secret, &request.credential.token),
+            accept: user.validate_token(&self.jwt_secret, &request.credential.token),
         })
     }
 }
@@ -121,12 +120,14 @@ impl TeaclaveAuthentication for TeaclaveAuthenticationService {
 #[cfg(feature = "enclave_unit_test")]
 pub mod tests {
     use super::*;
+    use crate::user_db::*;
     use crate::user_info::*;
     use std::vec;
     use teaclave_proto::teaclave_common::UserCredential;
 
     fn get_mock_service() -> TeaclaveAuthenticationService {
-        TeaclaveAuthenticationService::init().unwrap()
+        let database = Database::open().unwrap();
+        TeaclaveAuthenticationService::new(database.get_client()).unwrap()
     }
 
     pub fn test_user_register() {
@@ -177,7 +178,7 @@ pub mod tests {
         };
         let token = service.user_login(request).unwrap().token;
         info!("login token: {}", token);
-        dump_token(&service.secret, &token);
+        dump_token(&service.jwt_secret, &token);
 
         let response = get_authenticate_response(id, &token, &service);
         assert!(response.accept);
@@ -187,40 +188,40 @@ pub mod tests {
         let token = gen_token(
             my_claims,
             Some(jsonwebtoken::Algorithm::HS256),
-            &service.secret,
+            &service.jwt_secret,
         );
-        dump_token(&service.secret, &token);
+        dump_token(&service.jwt_secret, &token);
         let response = get_authenticate_response(id, &token, &service);
         assert!(!response.accept);
 
         info!("test wrong issuer");
         let mut my_claims = get_correct_claim();
         my_claims.iss = "wrong issuer".to_string();
-        let token = gen_token(my_claims, None, &service.secret);
-        dump_token(&service.secret, &token);
+        let token = gen_token(my_claims, None, &service.jwt_secret);
+        dump_token(&service.jwt_secret, &token);
         let response = get_authenticate_response(id, &token, &service);
         assert!(!response.accept);
 
         info!("test wrong user");
         let mut my_claims = get_correct_claim();
         my_claims.sub = "wrong user".to_string();
-        let token = gen_token(my_claims, None, &service.secret);
-        dump_token(&service.secret, &token);
+        let token = gen_token(my_claims, None, &service.jwt_secret);
+        dump_token(&service.jwt_secret, &token);
         let response = get_authenticate_response(id, &token, &service);
         assert!(!response.accept);
 
         info!("test expired token");
         let mut my_claims = get_correct_claim();
         my_claims.exp -= 24 * 60 + 1;
-        let token = gen_token(my_claims, None, &service.secret);
-        dump_token(&service.secret, &token);
+        let token = gen_token(my_claims, None, &service.jwt_secret);
+        dump_token(&service.jwt_secret, &token);
         let response = get_authenticate_response(id, &token, &service);
         assert!(!response.accept);
 
         info!("test wrong secret");
         let my_claims = get_correct_claim();
         let token = gen_token(my_claims, None, b"bad secret");
-        dump_token(&service.secret, &token);
+        dump_token(&service.jwt_secret, &token);
         let response = get_authenticate_response(id, &token, &service);
         assert!(!response.accept);
     }
diff --git a/tests/fixtures/runtime.config.toml b/tests/fixtures/runtime.config.toml
index 4c728b4..b10d432 100644
--- a/tests/fixtures/runtime.config.toml
+++ b/tests/fixtures/runtime.config.toml
@@ -3,6 +3,7 @@ authentication = { listen_address = "0.0.0.0:7776" }
 frontend = { listen_address = "0.0.0.0:7777" }
 
 [internal_endpoints]
+authentication = { listen_address = "0.0.0.0:17776", advertised_address = "localhost:17776" }
 dbs  = { listen_address = "0.0.0.0:7778", advertised_address = "127.0.0.1:7778", inbound_services = ["frontend"] }
 execution = { listen_address = "0.0.0.0:7989", advertised_address = "127.0.0.1:7989" }
 
diff --git a/tests/functional_tests/enclave/src/teaclave_authentication_service.rs b/tests/functional_tests/enclave/src/teaclave_authentication_service.rs
index 8db8f92..51ae2c2 100644
--- a/tests/functional_tests/enclave/src/teaclave_authentication_service.rs
+++ b/tests/functional_tests/enclave/src/teaclave_authentication_service.rs
@@ -78,7 +78,7 @@ fn test_login_fail() {
 }
 
 fn test_authenticate_success() {
-    let channel = Endpoint::new("localhost:7776").connect().unwrap();
+    let channel = Endpoint::new("localhost:17776").connect().unwrap();
     let mut client = TeaclaveAuthenticationClient::new(channel).unwrap();
     let request = UserRegisterRequest {
         id: "test_authenticate_id1".to_string(),
@@ -106,7 +106,7 @@ fn test_authenticate_success() {
 }
 
 fn test_authenticate_fail() {
-    let channel = Endpoint::new("localhost:7776").connect().unwrap();
+    let channel = Endpoint::new("localhost:17776").connect().unwrap();
     let mut client = TeaclaveAuthenticationClient::new(channel).unwrap();
     let request = UserRegisterRequest {
         id: "test_authenticate_id2".to_string(),


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