diff --git a/services/identity/src/client_service.rs b/services/identity/src/client_service.rs index bbd26151e..53bbbb09d 100644 --- a/services/identity/src/client_service.rs +++ b/services/identity/src/client_service.rs @@ -1,556 +1,580 @@ pub mod client_proto { tonic::include_proto!("identity.client"); } use std::str::FromStr; use crate::{ client_service::client_proto::{ DeleteUserRequest, Empty, GenerateNonceResponse, KeyserverKeysRequest, KeyserverKeysResponse, OpaqueLoginFinishRequest, OpaqueLoginFinishResponse, OpaqueLoginStartRequest, OpaqueLoginStartResponse, ReceiverKeysForUserRequest, ReceiverKeysForUserResponse, RefreshUserPreKeysRequest, RegistrationFinishRequest, RegistrationFinishResponse, RegistrationStartRequest, RegistrationStartResponse, SenderKeysForUserRequest, SenderKeysForUserResponse, UpdateUserPasswordFinishRequest, UpdateUserPasswordFinishResponse, UpdateUserPasswordStartRequest, UpdateUserPasswordStartResponse, UploadOneTimeKeysRequest, VerifyUserAccessTokenRequest, VerifyUserAccessTokenResponse, WalletLoginRequest, WalletLoginResponse, }, config::CONFIG, database::{DatabaseClient, Error as DBError, KeyPayload}, id::generate_uuid, nonce::generate_nonce_data, siwe::parse_and_verify_siwe_message, token::{AccessTokenData, AuthType}, }; use aws_sdk_dynamodb::Error as DynamoDBError; pub use client_proto::identity_client_service_server::{ IdentityClientService, IdentityClientServiceServer, }; use comm_opaque2::grpc::protocol_error_to_grpc_status; use moka::future::Cache; use rand::rngs::OsRng; use tonic::Response; use tracing::error; #[derive(Clone)] pub enum WorkflowInProgress { Registration(UserRegistrationInfo), Login(UserLoginInfo), } #[derive(Clone)] pub struct UserRegistrationInfo { pub username: String, pub flattened_device_key_upload: FlattenedDeviceKeyUpload, } #[derive(Clone)] pub struct UserLoginInfo { pub user_id: String, pub flattened_device_key_upload: FlattenedDeviceKeyUpload, pub opaque_server_login: comm_opaque2::server::Login, } #[derive(Clone)] pub struct FlattenedDeviceKeyUpload { pub device_id_key: String, pub key_payload: String, pub key_payload_signature: String, pub identity_prekey: String, pub identity_prekey_signature: String, pub identity_onetime_keys: Vec, pub notif_prekey: String, pub notif_prekey_signature: String, pub notif_onetime_keys: Vec, } #[derive(derive_more::Constructor)] pub struct ClientService { client: DatabaseClient, cache: Cache, } #[tonic::async_trait] impl IdentityClientService for ClientService { async fn register_password_user_start( &self, request: tonic::Request, ) -> Result, tonic::Status> { let message = request.into_inner(); let username_taken = self .client .username_taken(message.username.clone()) .await .map_err(handle_db_error)?; if username_taken { return Err(tonic::Status::already_exists("username already exists")); } if CONFIG.reserved_usernames.contains(&message.username) { return Err(tonic::Status::invalid_argument("username reserved")); } if let client_proto::RegistrationStartRequest { opaque_registration_request: register_message, username, device_key_upload: Some(client_proto::DeviceKeyUpload { device_key_info: Some(client_proto::IdentityKeyInfo { payload, payload_signature, social_proof: _social_proof, }), identity_upload: Some(client_proto::PreKey { pre_key: identity_prekey, pre_key_signature: identity_prekey_signature, }), notif_upload: Some(client_proto::PreKey { pre_key: notif_prekey, pre_key_signature: notif_prekey_signature, }), onetime_identity_prekeys, onetime_notif_prekeys, }), } = message { let server_registration = comm_opaque2::server::Registration::new(); let server_message = server_registration .start(&CONFIG.server_setup, ®ister_message, username.as_bytes()) .map_err(protocol_error_to_grpc_status)?; let key_info = KeyPayload::from_str(&payload) .map_err(|_| tonic::Status::invalid_argument("malformed payload"))?; let registration_state = UserRegistrationInfo { username, flattened_device_key_upload: FlattenedDeviceKeyUpload { device_id_key: key_info.primary_identity_public_keys.curve25519, key_payload: payload, key_payload_signature: payload_signature, identity_prekey, identity_prekey_signature, identity_onetime_keys: onetime_identity_prekeys, notif_prekey, notif_prekey_signature, notif_onetime_keys: onetime_notif_prekeys, }, }; let session_id = generate_uuid(); self .cache .insert( session_id.clone(), WorkflowInProgress::Registration(registration_state), ) .await; let response = RegistrationStartResponse { session_id, opaque_registration_response: server_message, }; Ok(Response::new(response)) } else { Err(tonic::Status::invalid_argument("unexpected message data")) } } async fn register_password_user_finish( &self, request: tonic::Request, ) -> Result, tonic::Status> { let message = request.into_inner(); if let Some(WorkflowInProgress::Registration(state)) = self.cache.get(&message.session_id) { self.cache.invalidate(&message.session_id).await; let server_registration = comm_opaque2::server::Registration::new(); let password_file = server_registration .finish(&message.opaque_registration_upload) .map_err(protocol_error_to_grpc_status)?; let device_id = state.flattened_device_key_upload.device_id_key.clone(); let user_id = self .client .add_password_user_to_users_table(state, password_file) .await .map_err(handle_db_error)?; // Create access token let token = AccessTokenData::new( user_id.clone(), device_id, crate::token::AuthType::Password, &mut OsRng, ); let access_token = token.access_token.clone(); self .client .put_access_token_data(token) .await .map_err(handle_db_error)?; let response = RegistrationFinishResponse { user_id, access_token, }; Ok(Response::new(response)) } else { Err(tonic::Status::not_found("session not found")) } } async fn update_user_password_start( &self, _request: tonic::Request, ) -> Result, tonic::Status> { unimplemented!(); } async fn update_user_password_finish( &self, _request: tonic::Request, ) -> Result, tonic::Status> { unimplemented!(); } async fn login_password_user_start( &self, request: tonic::Request, ) -> Result, tonic::Status> { let message = request.into_inner(); let (user_id, password_file_bytes) = self .client .get_user_id_and_password_file_from_username(&message.username) .await .map_err(handle_db_error)? .ok_or(tonic::Status::not_found("user not found"))?; if let client_proto::OpaqueLoginStartRequest { opaque_login_request: login_message, username, device_key_upload: Some(client_proto::DeviceKeyUpload { device_key_info: Some(client_proto::IdentityKeyInfo { payload, payload_signature, social_proof: _social_proof, }), identity_upload: Some(client_proto::PreKey { pre_key: identity_prekey, pre_key_signature: identity_prekey_signature, }), notif_upload: Some(client_proto::PreKey { pre_key: notif_prekey, pre_key_signature: notif_prekey_signature, }), onetime_identity_prekeys, onetime_notif_prekeys, }), } = message { let mut server_login = comm_opaque2::server::Login::new(); let server_response = server_login .start( &CONFIG.server_setup, &password_file_bytes, &login_message, username.as_bytes(), ) .map_err(protocol_error_to_grpc_status)?; let key_info = KeyPayload::from_str(&payload) .map_err(|_| tonic::Status::invalid_argument("malformed payload"))?; let login_state = UserLoginInfo { user_id, opaque_server_login: server_login, flattened_device_key_upload: FlattenedDeviceKeyUpload { device_id_key: key_info.primary_identity_public_keys.curve25519, key_payload: payload, key_payload_signature: payload_signature, identity_prekey, identity_prekey_signature, identity_onetime_keys: onetime_identity_prekeys, notif_prekey, notif_prekey_signature, notif_onetime_keys: onetime_notif_prekeys, }, }; let session_id = generate_uuid(); self .cache .insert(session_id.clone(), WorkflowInProgress::Login(login_state)) .await; let response = Response::new(OpaqueLoginStartResponse { session_id, opaque_login_response: server_response, }); Ok(response) } else { Err(tonic::Status::invalid_argument("unexpected message data")) } } async fn login_password_user_finish( &self, request: tonic::Request, ) -> Result, tonic::Status> { let message = request.into_inner(); if let Some(WorkflowInProgress::Login(state)) = self.cache.get(&message.session_id) { self.cache.invalidate(&message.session_id).await; let mut server_login = state.opaque_server_login.clone(); server_login .finish(&message.opaque_login_upload) .map_err(protocol_error_to_grpc_status)?; self .client .add_password_user_device_to_users_table( state.user_id.clone(), state.flattened_device_key_upload.clone(), ) .await .map_err(handle_db_error)?; // Create access token let token = AccessTokenData::new( state.user_id.clone(), state.flattened_device_key_upload.device_id_key, crate::token::AuthType::Password, &mut OsRng, ); let access_token = token.access_token.clone(); self .client .put_access_token_data(token) .await .map_err(handle_db_error)?; let response = OpaqueLoginFinishResponse { user_id: state.user_id, access_token, }; Ok(Response::new(response)) } else { Err(tonic::Status::not_found("session not found")) } } async fn login_wallet_user( &self, request: tonic::Request, ) -> Result, tonic::Status> { let message = request.into_inner(); let wallet_address = parse_and_verify_siwe_message( &message.siwe_message, &message.siwe_signature, )?; let (flattened_device_key_upload, social_proof) = if let client_proto::WalletLoginRequest { siwe_message: _, siwe_signature: _, device_key_upload: Some(client_proto::DeviceKeyUpload { device_key_info: Some(client_proto::IdentityKeyInfo { payload, payload_signature, social_proof: Some(social_proof), }), identity_upload: Some(client_proto::PreKey { pre_key: identity_prekey, pre_key_signature: identity_prekey_signature, }), notif_upload: Some(client_proto::PreKey { pre_key: notif_prekey, pre_key_signature: notif_prekey_signature, }), onetime_identity_prekeys, onetime_notif_prekeys, }), } = message { let key_info = KeyPayload::from_str(&payload) .map_err(|_| tonic::Status::invalid_argument("malformed payload"))?; ( FlattenedDeviceKeyUpload { device_id_key: key_info.primary_identity_public_keys.curve25519, key_payload: payload, key_payload_signature: payload_signature, identity_prekey, identity_prekey_signature, identity_onetime_keys: onetime_identity_prekeys, notif_prekey, notif_prekey_signature, notif_onetime_keys: onetime_notif_prekeys, }, social_proof, ) } else { return Err(tonic::Status::invalid_argument("unexpected message data")); }; let user_id = match self .client .get_user_id_from_user_info(wallet_address.clone(), AuthType::Wallet) .await .map_err(handle_db_error)? { Some(id) => { // User already exists, so we should update the DDB item self .client .add_wallet_user_device_to_users_table( id.clone(), flattened_device_key_upload.clone(), social_proof, ) .await .map_err(handle_db_error)?; id } None => { // User doesn't exist yet, so we should add a new user in DDB self .client .add_wallet_user_to_users_table( flattened_device_key_upload.clone(), wallet_address, social_proof, ) .await .map_err(handle_db_error)? } }; // Create access token let token = AccessTokenData::new( user_id.clone(), flattened_device_key_upload.device_id_key, crate::token::AuthType::Password, &mut OsRng, ); let access_token = token.access_token.clone(); self .client .put_access_token_data(token) .await .map_err(handle_db_error)?; let response = WalletLoginResponse { user_id: user_id, access_token, }; Ok(Response::new(response)) } async fn delete_user( &self, - _request: tonic::Request, + request: tonic::Request, ) -> Result, tonic::Status> { - unimplemented!(); + let message = request.into_inner(); + + let access_token = self + .client + .get_access_token_data(message.user_id.clone(), message.device_id_key) + .await + .map_err(handle_db_error)?; + + if let Some(token) = access_token { + if !token.is_valid() || token.access_token != message.access_token { + return Err(tonic::Status::permission_denied("bad token")); + } + + self + .client + .delete_user(message.user_id) + .await + .map_err(handle_db_error)?; + + let response = Empty {}; + + Ok(Response::new(response)) + } else { + Err(tonic::Status::permission_denied("bad token")) + } } async fn generate_nonce( &self, _request: tonic::Request, ) -> Result, tonic::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)), } } async fn get_receiver_keys_for_user( &self, _request: tonic::Request, ) -> Result, tonic::Status> { unimplemented!(); } async fn get_sender_keys_for_user( &self, _request: tonic::Request, ) -> Result, tonic::Status> { unimplemented!(); } async fn get_keyserver_keys( &self, _request: tonic::Request, ) -> Result, tonic::Status> { unimplemented!(); } async fn upload_one_time_keys( &self, _request: tonic::Request, ) -> Result, tonic::Status> { unimplemented!(); } async fn refresh_user_pre_keys( &self, _request: tonic::Request, ) -> Result, tonic::Status> { unimplemented!(); } async fn verify_user_access_token( &self, _request: tonic::Request, ) -> Result, tonic::Status> { unimplemented!(); } } pub fn handle_db_error(db_error: DBError) -> tonic::Status { match db_error { DBError::AwsSdk(DynamoDBError::InternalServerError(_)) | DBError::AwsSdk(DynamoDBError::ProvisionedThroughputExceededException( _, )) | DBError::AwsSdk(DynamoDBError::RequestLimitExceeded(_)) => { tonic::Status::unavailable("please retry") } e => { error!("Encountered an unexpected error: {}", e); tonic::Status::failed_precondition("unexpected error") } } } diff --git a/services/identity/src/token.rs b/services/identity/src/token.rs index 786b8f1b6..ef3a10e99 100644 --- a/services/identity/src/token.rs +++ b/services/identity/src/token.rs @@ -1,41 +1,45 @@ use chrono::{DateTime, Utc}; use rand::{ distributions::{Alphanumeric, DistString}, CryptoRng, Rng, }; use crate::constants::ACCESS_TOKEN_LENGTH; #[derive(Clone)] pub enum AuthType { Password, Wallet, } #[derive(Clone)] pub struct AccessTokenData { pub user_id: String, pub signing_public_key: String, pub access_token: String, pub created: DateTime, pub auth_type: AuthType, pub valid: bool, } impl AccessTokenData { pub fn new( user_id: String, signing_public_key: String, auth_type: AuthType, rng: &mut (impl Rng + CryptoRng), ) -> Self { AccessTokenData { user_id, signing_public_key, access_token: Alphanumeric.sample_string(rng, ACCESS_TOKEN_LENGTH), created: Utc::now(), auth_type, valid: true, } } + + pub fn is_valid(&self) -> bool { + self.valid + } } diff --git a/shared/protos/identity_client.proto b/shared/protos/identity_client.proto index a63800f0c..da28e4c5a 100644 --- a/shared/protos/identity_client.proto +++ b/shared/protos/identity_client.proto @@ -1,325 +1,329 @@ syntax = "proto3"; package identity.client; // RPCs from a client (iOS, Android, or web) to identity service service IdentityClientService { // Account actions // Called by user to register with the Identity Service (PAKE only) // Due to limitations of grpc-web, the Opaque challenge+response // needs to be split up over two unary requests // Start/Finish is used here to align with opaque protocol rpc RegisterPasswordUserStart(RegistrationStartRequest) returns ( RegistrationStartResponse) {} rpc RegisterPasswordUserFinish(RegistrationFinishRequest) returns ( RegistrationFinishResponse) {} // Called by user to update password and receive new access token rpc UpdateUserPasswordStart(UpdateUserPasswordStartRequest) returns (UpdateUserPasswordStartResponse) {} rpc UpdateUserPasswordFinish(UpdateUserPasswordFinishRequest) returns (UpdateUserPasswordFinishResponse) {} // Called by user to register device and get an access token rpc LoginPasswordUserStart(OpaqueLoginStartRequest) returns (OpaqueLoginStartResponse) {} rpc LoginPasswordUserFinish(OpaqueLoginFinishRequest) returns (OpaqueLoginFinishResponse) {} rpc LoginWalletUser(WalletLoginRequest) returns (WalletLoginResponse) {} // Called by a user to delete their own account rpc DeleteUser(DeleteUserRequest) returns (Empty) {} // Sign-In with Ethereum actions // Called by clients to get a nonce for a Sign-In with Ethereum message rpc GenerateNonce(Empty) returns (GenerateNonceResponse) {} // X3DH actions // Called by clients to get all device keys associated with a user in order // to open a new channel of communication on any of their devices. // Specially, this will return the following per device: // - Identity keys // - PreKey (including preKey signature) // - One-time PreKey rpc GetReceiverKeysForUser(ReceiverKeysForUserRequest) returns (ReceiverKeysForUserResponse) {} // Called by receivers of a communication request. The reponse will only // return identity and prekeys per device, but will not contain one-time keys. rpc GetSenderKeysForUser(SenderKeysForUserRequest) returns (SenderKeysForUserResponse) {} // Called by clients to get required keys for opening a connection // to a keyserver rpc GetKeyserverKeys(KeyserverKeysRequest) returns (KeyserverKeysResponse) {} // Replenish one-time preKeys rpc UploadOneTimeKeys(UploadOneTimeKeysRequest) returns (Empty) {} // Rotate a devices preKey and preKey signature // Rotated for deniability of older messages rpc RefreshUserPreKeys(RefreshUserPreKeysRequest) returns (Empty) {} // Service actions // Called by other services to verify a user's access token rpc VerifyUserAccessToken(VerifyUserAccessTokenRequest) returns (VerifyUserAccessTokenResponse) {} } // Helper types message Empty {} message PreKey { string preKey = 1; string preKeySignature = 2; } // Key information needed for starting a X3DH session message IdentityKeyInfo { // JSON payload containing Olm Identity keys // Sessions for users will contain both IdentityKeys and NotifKeys // For keyservers, this will only contain IdentityKeys string payload = 1; // Payload signed with the signing ed25519 key string payloadSignature = 2; // Signed message used for SIWE // This correlates a given wallet with the identity of a device optional string socialProof = 3; } // RegisterUser // Ephemeral information provided so others can create initial message // to this device // // Prekeys are generally rotated periodically // One-time Prekeys are "consumed" after first use, so many need to // be provide to avoid exhausting them. // Bundle of information needed for creating an initial message using X3DH message DeviceKeyUpload { IdentityKeyInfo deviceKeyInfo = 1; PreKey identityUpload = 2; PreKey notifUpload = 3; repeated string onetimeIdentityPrekeys = 4; repeated string onetimeNotifPrekeys = 5; } // Request for registering a new user message RegistrationStartRequest { // Message sent to initiate PAKE registration (step 1) bytes opaqueRegistrationRequest = 1; string username = 2; // Information needed to open a new channel to current user's device DeviceKeyUpload deviceKeyUpload = 3; } // Messages sent from a client to Identity Service message RegistrationFinishRequest { // Identifier to correlate RegisterStart session string sessionID = 1; // Final message in PAKE registration bytes opaqueRegistrationUpload = 2; } // Messages sent from Identity Service to client message RegistrationStartResponse { // Identifier used to correlate start request with finish request string sessionID = 1; // sent to the user upon reception of the PAKE registration attempt // (step 2) bytes opaqueRegistrationResponse = 2; } message RegistrationFinishResponse { // Unique identifier for newly registered user string userID = 1; // After successful unpacking of user credentials, return token string accessToken = 2; } // UpdateUserPassword // Request for updating a user, similar to registration but need a // access token to validate user before updating password message UpdateUserPasswordStartRequest { // Message sent to initiate PAKE registration (step 1) bytes opaqueRegistrationRequest = 1; // Used to validate user, before attempting to update password string accessToken = 2; } // Do a user registration, but overwrite the existing credentials // after validation of user message UpdateUserPasswordFinishRequest { // Identifier used to correlate start and finish request string sessionID = 1; // Opaque client registration upload (step 3) bytes opaqueRegistrationUpload = 2; } message UpdateUserPasswordStartResponse { // Identifier used to correlate start request with finish request string sessionID = 1; bytes opaqueRegistrationResponse = 2; } message UpdateUserPasswordFinishResponse { // After validating client reponse, mint a new token string accessToken = 1; } // LoginUser message OpaqueLoginStartRequest { string username = 1; // Message sent to initiate PAKE login (step 1) bytes opaqueLoginRequest = 2; // Information specific to a user's device needed to open a new channel of // communication with this user DeviceKeyUpload deviceKeyUpload = 3; } message OpaqueLoginFinishRequest { // Identifier used to correlate start request with finish request string sessionID = 1; // Message containing client's reponse to server challenge. // Used to verify that client holds password secret (Step 3) bytes opaqueLoginUpload = 2; } message OpaqueLoginStartResponse { // Identifier used to correlate start request with finish request string sessionID = 1; // Opaque challenge sent from server to client attempting to login (Step 2) bytes opaqueLoginResponse = 2; } message OpaqueLoginFinishResponse { string userID = 1; // Mint and return a new access token upon successful login string accessToken = 2; } message WalletLoginRequest { string siweMessage = 1; string siweSignature = 2; // Information specific to a user's device needed to open a new channel of // communication with this user DeviceKeyUpload deviceKeyUpload = 3; } message WalletLoginResponse { string userID = 1; string accessToken = 2; } // DeleteUser message DeleteUserRequest { string accessToken = 1; + string userID = 2; + // Public ed25519 key used for signing. We need this to look up a device's + // access token + string deviceIDKey = 3; } // GenerateNonce message GenerateNonceResponse{ string nonce = 1; } // GetReceiverKeysForUser // Information needed when establishing communication to someone else's device message ReceiverKeyInfo { IdentityKeyInfo identityInfo = 1; PreKey identityPrekey = 2; PreKey notifPrekey = 3; optional string onetimeIdentityPrekey = 4; optional string onetimeNotifPrekey = 5; } // Information needed by a device to establish communcation when responding // to a request. // The device receiving a request only needs the identity and prekeys. message ReceiverKeysForUserRequest { oneof identifier { string username = 1; string walletAddress = 2; } } message ReceiverKeysForUserResponse { // Map is keyed on devices' public ed25519 key used for signing map devices = 1; } // GetSenderKeysForUser message SenderKeyInfo { IdentityKeyInfo identityInfo = 1; PreKey identityPrekey = 2; PreKey notifPrekey = 3; } message SenderKeysForUserRequest { oneof identifier { string username = 1; string walletAddress = 2; } } message SenderKeysForUserResponse { // Map is keyed on devices' public ed25519 key used for signing map devices = 1; } // GetKeyserverKeys // Information needed when establishing communication to a keyserver message KeyserverSessionInfo { IdentityKeyInfo identityInfo = 1; PreKey identityPrekeys = 2; optional string onetimeIdentityPrekey = 3; } // All keyserver must be registered with an existing user. // Conversely, one or zero keyservers can registered to a user. message KeyserverKeysRequest { oneof identifier { string username = 1; string walletAddress = 2; } } message KeyserverKeysResponse { KeyserverSessionInfo keyserverInfo = 1; } // UploadOneTimeKeys // As OPKs get exhausted, they need to be refreshed message UploadOneTimeKeysRequest { // Use device associated with token to insert OPKs string accessToken = 1; repeated string oneTimePreKeys = 2; } // RefreshUserPreKeys message RefreshUserPreKeysRequest { string accessToken = 1; PreKey newPreKeys = 2; } // VerifyUserAccessToken message VerifyUserAccessTokenRequest { string userID = 1; // signing ed25519 key for the given user's device string signingPublicKey = 2; string accessToken = 3; } message VerifyUserAccessTokenResponse { bool tokenValid = 1; }