diff --git a/services/identity/src/service.rs b/services/identity/src/service.rs index cfb12f233..829ccf288 100644 --- a/services/identity/src/service.rs +++ b/services/identity/src/service.rs @@ -1,587 +1,602 @@ use aws_sdk_dynamodb::output::GetItemOutput; use aws_sdk_dynamodb::Error as DynamoDBError; use chrono::Utc; use comm_opaque::Cipher; use constant_time_eq::constant_time_eq; use futures_core::Stream; use opaque_ke::{ServerLogin, ServerRegistration}; use rand::rngs::OsRng; use rand::{CryptoRng, Rng}; use siwe::Message; use std::collections::{HashMap, HashSet}; use std::pin::Pin; use tokio::sync::mpsc; use tokio_stream::{wrappers::ReceiverStream, StreamExt}; use tonic::{Request, Response, Status}; use tracing::{error, info, instrument}; use crate::constants::MPSC_CHANNEL_BUFFER_CAPACITY; use crate::database::{DatabaseClient, Error as DBError}; use crate::nonce::generate_nonce_data; use crate::pake_grpc; use crate::token::{AccessTokenData, AuthType}; pub use proto::identity_service_server::IdentityServiceServer; use proto::{ get_user_id_request::AuthType as ProtoAuthType, identity_service_server::IdentityService, login_request::Data::PakeLoginRequest, login_request::Data::WalletLoginRequest, login_response::Data::PakeLoginResponse, login_response::Data::WalletLoginResponse, pake_login_request::Data::PakeCredentialFinalization, pake_login_request::Data::PakeCredentialRequestAndUserId, pake_login_response::Data::AccessToken, pake_login_response::Data::PakeCredentialResponse, registration_request::Data::PakeCredentialFinalization as PakeRegistrationCredentialFinalization, registration_request::Data::PakeRegistrationRequestAndUserId, registration_request::Data::PakeRegistrationUploadAndCredentialRequest, registration_response::Data::PakeLoginResponse as PakeRegistrationLoginResponse, registration_response::Data::PakeRegistrationResponse, CompareUsersRequest, CompareUsersResponse, DeleteUserRequest, DeleteUserResponse, GenerateNonceRequest, GenerateNonceResponse, GetSessionInitializationInfoRequest, GetSessionInitializationInfoResponse, GetUserIdRequest, GetUserIdResponse, LoginRequest, LoginResponse, PakeLoginRequest as PakeLoginRequestStruct, PakeLoginResponse as PakeLoginResponseStruct, RegistrationRequest, RegistrationResponse, SessionInitializationInfo, UpdateUserRequest, UpdateUserResponse, VerifyUserTokenRequest, VerifyUserTokenResponse, WalletLoginRequest as WalletLoginRequestStruct, WalletLoginResponse as WalletLoginResponseStruct, }; mod proto { tonic::include_proto!("identity"); } mod login; mod registration; +mod update; #[derive(Debug)] enum PakeWorkflow { Registration, Login, } #[derive(derive_more::Constructor)] pub struct MyIdentityService { client: DatabaseClient, } #[tonic::async_trait] impl IdentityService for MyIdentityService { type RegisterUserStream = Pin< Box< dyn Stream> + Send + 'static, >, >; #[instrument(skip(self))] async fn register_user( &self, request: Request>, ) -> Result, Status> { let mut in_stream = request.into_inner(); let (tx, rx) = mpsc::channel(MPSC_CHANNEL_BUFFER_CAPACITY); let client = self.client.clone(); tokio::spawn(async move { let first_message = in_stream.next().await; let mut registration_state = registration::handle_registration_request( first_message, &client, tx.clone(), ) .await?; // ServerRegistration in opaque-ke v1.2 doesn't implement Clone, so we // have to take the value out of registration_state, replacing it with None let pake_state = if let Some(pake_state) = registration_state.pake_state.take() { pake_state } else { error!("registration_state is missing opaque-ke ServerRegistration"); return Err(Status::failed_precondition("internal error")); }; let second_message = in_stream.next().await; let server_login = registration::handle_registration_upload_and_credential_request( second_message, tx.clone(), &client, ®istration_state, pake_state, ) .await?; let third_message = in_stream.next().await; registration::handle_credential_finalization( third_message, tx, &client, ®istration_state, server_login, ) .await?; Ok(()) }); let out_stream = ReceiverStream::new(rx); Ok(Response::new( Box::pin(out_stream) as Self::RegisterUserStream )) } type LoginUserStream = Pin> + Send + 'static>>; #[instrument(skip(self))] async fn login_user( &self, request: Request>, ) -> Result, Status> { let mut in_stream = request.into_inner(); let (tx, rx) = mpsc::channel(MPSC_CHANNEL_BUFFER_CAPACITY); let client = self.client.clone(); tokio::spawn(async move { let first_message = in_stream.next().await; let login_state = login::handle_login_request(first_message, tx.clone(), &client).await?; // login_state will be None if user is logging in with a wallet if let Some(state) = login_state { let second_message = in_stream.next().await; login::handle_credential_finalization( second_message, tx, &client, state, ) .await?; } Ok::<(), Status>(()) }); let out_stream = ReceiverStream::new(rx); Ok(Response::new(Box::pin(out_stream) as Self::LoginUserStream)) } #[instrument(skip(self))] async fn verify_user_token( &self, request: Request, ) -> Result, Status> { info!("Received VerifyUserToken request: {:?}", request); let message = request.into_inner(); let token_valid = match self .client .get_access_token_data(message.user_id, message.signing_public_key) .await { Ok(Some(access_token_data)) => constant_time_eq( access_token_data.access_token.as_bytes(), message.access_token.as_bytes(), ), Ok(None) => false, Err(e) => return Err(handle_db_error(e)), }; let response = Response::new(VerifyUserTokenResponse { token_valid }); info!("Sending VerifyUserToken response: {:?}", response); Ok(response) } #[instrument(skip(self))] async fn get_user_id( &self, request: Request, ) -> Result, Status> { let message = request.into_inner(); let auth_type = match ProtoAuthType::from_i32(message.auth_type) { Some(ProtoAuthType::Password) => AuthType::Password, Some(ProtoAuthType::Wallet) => AuthType::Wallet, None => { error!( "Unable to parse AuthType from message: {}", message.auth_type ); return Err(Status::invalid_argument("invalid message")); } }; let user_id = match self .client .get_user_id_from_user_info(message.user_info, auth_type) .await { Ok(Some(user_id)) => user_id, Ok(None) => return Err(Status::not_found("no user ID found")), Err(e) => return Err(handle_db_error(e)), }; let response = Response::new(GetUserIdResponse { user_id }); Ok(response) } #[instrument(skip(self))] async fn delete_user( &self, request: tonic::Request, ) -> Result, tonic::Status> { let message = request.into_inner(); match self.client.delete_user(message.user_id).await { Ok(_) => Ok(Response::new(DeleteUserResponse {})), Err(e) => Err(handle_db_error(e)), } } #[instrument(skip(self))] async fn compare_users( &self, request: Request, ) -> Result, Status> { let message = request.into_inner(); let mut mysql_users_vec = message.users; let mut ddb_users_vec = match self.client.get_users().await { Ok(user_list) => user_list, Err(e) => return Err(handle_db_error(e)), }; // We use HashSets here for faster lookups let mysql_users_set = HashSet::::from_iter(mysql_users_vec.clone()); let ddb_users_set = HashSet::::from_iter(ddb_users_vec.clone()); ddb_users_vec.retain(|user| !mysql_users_set.contains(user)); mysql_users_vec.retain(|user| !ddb_users_set.contains(user)); Ok(Response::new(CompareUsersResponse { users_missing_from_keyserver: ddb_users_vec, users_missing_from_identity: mysql_users_vec, })) } #[instrument(skip(self))] async fn generate_nonce( &self, _request: Request, ) -> Result, Status> { let nonce_data = generate_nonce_data(&mut OsRng); match self .client .add_nonce_to_nonces_table(nonce_data.clone()) .await { Ok(_) => Ok(Response::new(GenerateNonceResponse { nonce: nonce_data.nonce, })), Err(e) => Err(handle_db_error(e)), } } #[instrument(skip(self))] async fn get_session_initialization_info( &self, request: Request, ) -> Result, Status> { let message = request.into_inner(); match self .client .get_session_initialization_info(&message.user_id) .await { Ok(Some(session_initialization_info)) => { let mut devices = HashMap::new(); for (device, info) in session_initialization_info { devices.insert(device, SessionInitializationInfo { info }); } Ok(Response::new(GetSessionInitializationInfoResponse { devices, })) } Ok(None) => return Err(Status::not_found("user not found")), Err(e) => Err(handle_db_error(e)), } } #[instrument(skip(self))] async fn update_user( &self, request: Request>, ) -> Result, Status> { - unimplemented!(); + let (tx, rx) = mpsc::channel(MPSC_CHANNEL_BUFFER_CAPACITY); + let db_client = self.client.clone(); + + tokio::spawn(async move { + update::handle_server_update_user_messages( + request.into_inner(), + db_client, + tx, + ) + .await; + }); + + let out_stream = ReceiverStream::new(rx); + + Ok(Response::new(Box::pin(out_stream) as Self::UpdateUserStream)) } type UpdateUserStream = Pin< Box> + Send + 'static>, >; } async fn put_token_helper( client: &DatabaseClient, auth_type: AuthType, user_id: &str, signing_public_key: &str, rng: &mut (impl Rng + CryptoRng), ) -> Result { if user_id.is_empty() || signing_public_key.is_empty() { error!( "Incomplete data: user ID \"{}\", signing public key \"{}\"", user_id, signing_public_key ); return Err(Status::aborted("user not found")); } let access_token_data = AccessTokenData::new( user_id.to_string(), signing_public_key.to_string(), auth_type, rng, ); match client .put_access_token_data(access_token_data.clone()) .await { Ok(_) => Ok(access_token_data.access_token), Err(e) => Err(handle_db_error(e)), } } fn parse_and_verify_siwe_message( user_id: &str, signing_public_key: &str, siwe_message: &str, siwe_signature: &str, ) -> Result<(), Status> { if user_id.is_empty() || signing_public_key.is_empty() { error!( "Incomplete data: user ID {}, signing public key {}", user_id, signing_public_key ); return Err(Status::aborted("user not found")); } let siwe_message: Message = match siwe_message.parse() { Ok(m) => m, Err(e) => { error!("Failed to parse SIWE message: {}", e); return Err(Status::invalid_argument("invalid message")); } }; let decoded_signature = hex::decode(siwe_signature.trim_start_matches("0x")) .map_err(|e| { error!("Failed to decode SIWE signature: {}", e); Status::invalid_argument("invalid signature") })?; match siwe_message.verify( match decoded_signature.try_into() { Ok(s) => s, Err(e) => { error!("Conversion to SIWE signature failed: {:?}", e); return Err(Status::invalid_argument("invalid message")); } }, None, None, Some(&Utc::now()), ) { Err(e) => { error!( "Signature verification failed for user {} with signing public key {}: {}", user_id, signing_public_key, e ); Err(Status::unauthenticated("message not authenticated")) } Ok(_) => Ok(()), } } async fn wallet_login_helper( client: &DatabaseClient, wallet_login_request: WalletLoginRequestStruct, rng: &mut (impl Rng + CryptoRng), ) -> Result { parse_and_verify_siwe_message( &wallet_login_request.user_id, &wallet_login_request.signing_public_key, &wallet_login_request.siwe_message, &wallet_login_request.siwe_signature, )?; client .update_users_table( wallet_login_request.user_id.clone(), Some(wallet_login_request.signing_public_key.clone()), None, None, Some( &wallet_login_request .session_initialization_info .ok_or_else(|| Status::invalid_argument("Invalid message"))? .info, ), ) .await .map_err(handle_db_error)?; Ok(LoginResponse { data: Some(WalletLoginResponse(WalletLoginResponseStruct { access_token: put_token_helper( client, AuthType::Wallet, &wallet_login_request.user_id, &wallet_login_request.signing_public_key, rng, ) .await?, })), }) } async fn pake_login_start( client: &DatabaseClient, user_id: &str, pake_credential_request: &[u8], ) -> Result { if user_id.is_empty() { error!("Incomplete data: user ID not provided"); return Err(Status::aborted("user not found")); } let server_registration = match client.get_pake_registration(user_id.to_string()).await { Ok(Some(r)) => r, Ok(None) => { return Err(Status::not_found("user not found")); } Err(e) => return Err(handle_db_error(e)), }; let server_login_start_result = pake_grpc::server_login_start( &mut OsRng, server_registration, pake_credential_request, )?; let credential_response = server_login_start_result.message.serialize().map_err(|e| { error!("Failed to serialize PAKE message: {}", e); Status::failed_precondition("internal error") })?; Ok(LoginResponseAndPakeState { response: PakeLoginResponseStruct { data: Some(PakeCredentialResponse(credential_response)), }, pake_state: server_login_start_result.state, }) } async fn pake_login_finish( user_id: &str, signing_public_key: &str, client: &DatabaseClient, server_login: ServerLogin, pake_credential_finalization: &Vec, rng: &mut (impl Rng + CryptoRng), pake_workflow: PakeWorkflow, session_initialization_info: &HashMap, ) -> Result { if user_id.is_empty() || signing_public_key.is_empty() { error!( "Incomplete data: user ID {}, signing public key {}", user_id, signing_public_key ); return Err(Status::aborted("user not found")); } pake_grpc::server_login_finish(server_login, pake_credential_finalization)?; if matches!(pake_workflow, PakeWorkflow::Login) { client .update_users_table( user_id.to_string(), Some(signing_public_key.to_string()), None, None, Some(session_initialization_info), ) .await .map_err(handle_db_error)?; } Ok(PakeLoginResponseStruct { data: Some(AccessToken( put_token_helper( client, AuthType::Password, user_id, signing_public_key, rng, ) .await?, )), }) } async fn server_register_response( registration_request_bytes: &Vec, ) -> Result { let server_registration_start_result = pake_grpc::server_registration_start( &mut OsRng, registration_request_bytes, )?; Ok(RegistrationResponseAndPakeState { response: RegistrationResponse { data: Some(PakeRegistrationResponse( server_registration_start_result.message.serialize(), )), }, pake_state: server_registration_start_result.state, }) } async fn pake_registration_finish( user_id: &str, client: &DatabaseClient, registration_upload_bytes: &Vec, server_registration: ServerRegistration, username: &str, signing_public_key: &str, session_initialization_info: &HashMap, ) -> Result<(), Status> { if user_id.is_empty() { error!("Incomplete data: user ID not provided"); return Err(Status::aborted("user not found")); } let server_registration_finish_result = pake_grpc::server_registration_finish( server_registration, registration_upload_bytes, )?; match client .add_user_to_users_table( user_id.to_string(), server_registration_finish_result, username.to_string(), signing_public_key.to_string(), session_initialization_info, ) .await { Ok(_) => Ok(()), Err(e) => Err(handle_db_error(e)), } } fn handle_db_error(db_error: DBError) -> Status { match db_error { DBError::AwsSdk(DynamoDBError::InternalServerError(_)) | DBError::AwsSdk(DynamoDBError::ProvisionedThroughputExceededException( _, )) | DBError::AwsSdk(DynamoDBError::RequestLimitExceeded(_)) => { Status::unavailable("please retry") } e => { error!("Encountered an unexpected error: {}", e); Status::failed_precondition("unexpected error") } } } struct RegistrationResponseAndPakeState { response: RegistrationResponse, pake_state: ServerRegistration, } struct LoginResponseAndPakeState { response: PakeLoginResponseStruct, pake_state: ServerLogin, } diff --git a/services/identity/src/service/update.rs b/services/identity/src/service/update.rs new file mode 100644 index 000000000..97c326844 --- /dev/null +++ b/services/identity/src/service/update.rs @@ -0,0 +1,296 @@ +use aws_sdk_dynamodb::output::GetItemOutput; +use comm_opaque::Cipher; +use opaque_ke::{ServerLogin, ServerRegistration}; +use rand::rngs::OsRng; +use tokio::sync::mpsc; +use tokio_stream::StreamExt; +use tonic::Streaming; +use tracing::{debug, error, info}; + +use super::proto::{ + pake_login_response::Data::AccessToken, update_user_request, + update_user_response, update_user_response::Data::PakeLoginResponse, + update_user_response::Data::PakeRegistrationResponse, + PakeRegistrationRequestAndUserId, PakeRegistrationUploadAndCredentialRequest, +}; +use crate::service::PakeLoginResponseStruct; +use crate::token::AuthType; +use crate::{database::DatabaseClient, pake_grpc}; + +use super::{ + handle_db_error, pake_login_start, put_token_helper, Status, + UpdateUserRequest, UpdateUserResponse, +}; + +async fn send_to_client( + tx: &tokio::sync::mpsc::Sender>, + response: Result, +) -> Result<(), Status> { + let transport_result = match response { + Ok(message) => tx.send(Ok(message)).await, + Err(status) => { + error!("{}", status.message()); + tx.send(Err(status)).await + } + }; + + transport_result.map_err(|_| Status::internal("disconnection")) +} + +pub(crate) async fn handle_server_update_user_messages( + in_stream: Streaming, + client: DatabaseClient, + tx: tokio::sync::mpsc::Sender>, +) { + match attempt_update_user(in_stream, &client, &tx).await { + Ok(user_id) => info!("Successfully updated user {}", user_id), + // Attempt to send client the failure to receive immediate feedback + Err(e) => match send_to_client(&tx, Err(e)).await { + Ok(_) => debug!("Attempted to inform user of failed update"), + Err(_) => return, + }, + }; +} + +async fn attempt_update_user( + mut in_stream: Streaming, + client: &DatabaseClient, + tx: &tokio::sync::mpsc::Sender>, +) -> Result { + let first_message = in_stream.next().await; + + let (request, registration_state) = + handle_registration_request(first_message, client, tx).await?; + + let second_message = in_stream.next().await; + let registration_upload = get_registration_upload(second_message)?; + let server_login = handle_registration_upload_and_credential_request( + registration_upload, + tx, + &client, + &request, + registration_state, + ) + .await?; + + let third_message = in_stream.next().await; + let finalization_payload = get_finalization_message(third_message)?; + handle_credential_finalization( + finalization_payload, + tx, + client, + &request, + server_login, + ) + .await?; + + Ok(request.user_id) +} + +pub async fn handle_registration_request( + message: Option>, + client: &DatabaseClient, + tx: &mpsc::Sender>, +) -> Result< + (PakeRegistrationRequestAndUserId, ServerRegistration), + Status, +> { + let request = get_register_request(message)?; + user_exists(&request.user_id, &client).await?; + let server_registration_start_result = pake_grpc::server_registration_start( + &mut OsRng, + &request.pake_registration_request, + )?; + let server_start_payload = + server_registration_start_result.message.serialize(); + let server_start_response = UpdateUserResponse { + data: Some(PakeRegistrationResponse(server_start_payload)), + }; + send_to_client(&tx, Ok(server_start_response)).await?; + + Ok((request, server_registration_start_result.state)) +} + +fn get_register_request( + message: Option>, +) -> Result { + match message { + Some(Ok(UpdateUserRequest { + data: Some(update_user_request::Data::Request(request)), + })) => Ok(request), + e => { + error!( + "Expected to receive registration request, but instead received {:?}", + e + ); + Err(Status::invalid_argument("server error")) + } + } +} + +fn get_finalization_message( + message: Option>, +) -> Result, Status> { + match message { + Some(Ok(UpdateUserRequest { + data: + Some(update_user_request::Data::PakeLoginFinalizationMessage(request)), + })) => Ok(request), + e => { + error!( + "Expected to receive login finalization message, but instead received {:?}", + e); + Err(Status::aborted("server error")) + } + } +} + +async fn user_exists( + user_id: &str, + client: &DatabaseClient, +) -> Result { + match client + .get_item_from_users_table(&user_id) + .await + .map_err(handle_db_error) + { + Ok(GetItemOutput { item: Some(_), .. }) => Ok(true), + Ok(GetItemOutput { item: None, .. }) => { + error!("Unable to find user: {}", user_id); + return Err(Status::not_found("user not found")); + } + Err(e) => Err(e), + } +} + +pub async fn handle_registration_upload_and_credential_request( + message: PakeRegistrationUploadAndCredentialRequest, + tx: &mpsc::Sender>, + client: &DatabaseClient, + request_and_user_info: &PakeRegistrationRequestAndUserId, + pake_state: ServerRegistration, +) -> Result, Status> { + pake_registration_finish( + &request_and_user_info.user_id, + client, + &message.pake_registration_upload, + pake_state, + ) + .await?; + let response_and_state = pake_login_start( + client, + &request_and_user_info.user_id, + &message.pake_credential_request, + ) + .await?; + + let registration_response = UpdateUserResponse { + data: Some(PakeLoginResponse(response_and_state.response)), + }; + + send_to_client(tx, Ok(registration_response)).await?; + Ok(response_and_state.pake_state) +} + +async fn pake_registration_finish( + user_id: &str, + client: &DatabaseClient, + registration_upload_bytes: &Vec, + server_registration: ServerRegistration, +) -> Result<(), Status> { + if user_id.is_empty() { + error!("Incomplete data: user ID not provided"); + return Err(Status::aborted("user not found")); + } + let server_registration_finish_result = + pake_grpc::server_registration_finish( + server_registration, + registration_upload_bytes, + )?; + + client + .update_users_table( + user_id.to_string(), + None, + Some(server_registration_finish_result), + None, + None, + ) + .await + .map_err(handle_db_error)?; + Ok(()) +} + +fn get_registration_upload( + message: Option>, +) -> Result< + crate::service::proto::PakeRegistrationUploadAndCredentialRequest, + Status, +> { + match message { + Some(Ok(UpdateUserRequest { + data: + Some( + update_user_request::Data::PakeRegistrationUploadAndCredentialRequest( + upload, + ), + ), + })) => Ok(upload), + e => { + error!( + "Expected to receive registration upload, but instead received {:?}", + e + ); + Err(Status::aborted("server error")) + } + } +} + +pub async fn handle_credential_finalization( + finalization_payload: Vec, + tx: &mpsc::Sender>, + client: &DatabaseClient, + request_and_user_info: &PakeRegistrationRequestAndUserId, + server_login: ServerLogin, +) -> Result<(), Status> { + let login_finish_result = pake_login_finish( + &request_and_user_info.user_id, + &request_and_user_info.signing_public_key, + client, + server_login, + &finalization_payload, + ) + .await?; + let response = UpdateUserResponse { + data: Some(update_user_response::Data::PakeLoginResponse( + login_finish_result, + )), + }; + send_to_client(tx, Ok(response)).await +} + +async fn pake_login_finish( + user_id: &str, + signing_public_key: &str, + client: &DatabaseClient, + server_login: ServerLogin, + pake_credential_finalization: &Vec, +) -> Result { + if user_id.is_empty() { + error!("Incomplete data: user ID {}", user_id); + return Err(Status::aborted("user not found")); + } + + pake_grpc::server_login_finish(server_login, pake_credential_finalization)?; + let access_token = put_token_helper( + client, + AuthType::Password, + user_id, + signing_public_key, + &mut OsRng, + ) + .await?; + Ok(PakeLoginResponseStruct { + data: Some(AccessToken(access_token)), + }) +}