diff --git a/services/identity/src/client_service.rs b/services/identity/src/client_service.rs index 287fe70e5..bbd26151e 100644 --- a/services/identity/src/client_service.rs +++ b/services/identity/src/client_service.rs @@ -1,445 +1,556 @@ 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, - token::AccessTokenData, + 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_user_to_users_table(state, password_file) + .add_password_user_to_users_table(state, password_file) .await .map_err(handle_db_error)?; // Create access token let token = AccessTokenData::new( - message.session_id, + 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_device_to_users_table(state.clone()) + .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( - message.session_id, + 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, + request: tonic::Request, ) -> Result, tonic::Status> { - unimplemented!(); + 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, ) -> Result, tonic::Status> { unimplemented!(); } 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/constants.rs b/services/identity/src/constants.rs index 82c82b5e7..22d7243dd 100644 --- a/services/identity/src/constants.rs +++ b/services/identity/src/constants.rs @@ -1,102 +1,105 @@ // Secrets pub const SECRETS_DIRECTORY: &str = "secrets"; pub const SECRETS_FILE_NAME: &str = "secret_key"; pub const SECRETS_FILE_EXTENSION: &str = "txt"; pub const SECRETS_SETUP_FILE: &str = "server_setup.txt"; // DynamoDB // User table information, supporting opaque_ke 2.0 and X3DH information // Users can sign in either through username+password or Eth wallet. // // This structure should be aligned with the messages defined in // shared/protos/identity_client.proto // // Structure for a user should be: // { // userID: String, // opaqueRegistrationData: Option, // username: Option, // walletAddress: Option, // devices: HashMap // } // // A device is defined as: // { // deviceType: String, # client or keyserver // keyPayload: String, // keyPayloadSignature: String, // identityPreKey: String, // identityPreKeySignature: String, // identityOneTimeKeys: Vec, // notifPreKey: String, // notifPreKeySignature: String, // notifOneTimeKeys: Vec, +// socialProof: Option // } // } // // Additional context: // "devices" uses the signing public identity key of the device as a key for the devices map // "keyPayload" is a JSON encoded string containing identity and notif keys (both signature and verification) // if "deviceType" == "keyserver", then the device will not have any notif key information pub const USERS_TABLE: &str = "identity-users"; pub const USERS_TABLE_PARTITION_KEY: &str = "userID"; pub const USERS_TABLE_REGISTRATION_ATTRIBUTE: &str = "opaqueRegistrationData"; pub const USERS_TABLE_USERNAME_ATTRIBUTE: &str = "username"; pub const USERS_TABLE_DEVICES_ATTRIBUTE: &str = "devices"; pub const USERS_TABLE_DEVICES_MAP_DEVICE_TYPE_ATTRIBUTE_NAME: &str = "deviceType"; pub const USERS_TABLE_DEVICES_MAP_KEY_PAYLOAD_ATTRIBUTE_NAME: &str = "keyPayload"; pub const USERS_TABLE_DEVICES_MAP_KEY_PAYLOAD_SIGNATURE_ATTRIBUTE_NAME: &str = "keyPayloadSignature"; pub const USERS_TABLE_DEVICES_MAP_IDENTITY_PREKEY_ATTRIBUTE_NAME: &str = "identityPreKey"; pub const USERS_TABLE_DEVICES_MAP_IDENTITY_PREKEY_SIGNATURE_ATTRIBUTE_NAME: &str = "identityPreKeySignature"; pub const USERS_TABLE_DEVICES_MAP_IDENTITY_ONETIME_KEYS_ATTRIBUTE_NAME: &str = "identityOneTimeKeys"; pub const USERS_TABLE_DEVICES_MAP_NOTIF_PREKEY_ATTRIBUTE_NAME: &str = "preKey"; pub const USERS_TABLE_DEVICES_MAP_NOTIF_PREKEY_SIGNATURE_ATTRIBUTE_NAME: &str = "preKeySignature"; pub const USERS_TABLE_DEVICES_MAP_NOTIF_ONETIME_KEYS_ATTRIBUTE_NAME: &str = "notifOneTimeKeys"; pub const USERS_TABLE_WALLET_ADDRESS_ATTRIBUTE: &str = "walletAddress"; +pub const USERS_TABLE_DEVICES_MAP_SOCIAL_PROOF_ATTRIBUTE_NAME: &str = + "socialProof"; pub const USERS_TABLE_USERNAME_INDEX: &str = "username-index"; pub const USERS_TABLE_WALLET_ADDRESS_INDEX: &str = "walletAddress-index"; pub const ACCESS_TOKEN_TABLE: &str = "identity-tokens"; pub const ACCESS_TOKEN_TABLE_PARTITION_KEY: &str = "userID"; pub const ACCESS_TOKEN_SORT_KEY: &str = "signingPublicKey"; pub const ACCESS_TOKEN_TABLE_CREATED_ATTRIBUTE: &str = "created"; pub const ACCESS_TOKEN_TABLE_AUTH_TYPE_ATTRIBUTE: &str = "authType"; pub const ACCESS_TOKEN_TABLE_VALID_ATTRIBUTE: &str = "valid"; pub const ACCESS_TOKEN_TABLE_TOKEN_ATTRIBUTE: &str = "token"; pub const NONCE_TABLE: &str = "identity-nonces"; pub const NONCE_TABLE_PARTITION_KEY: &str = "nonce"; pub const NONCE_TABLE_CREATED_ATTRIBUTE: &str = "created"; // Tokio pub const MPSC_CHANNEL_BUFFER_CAPACITY: usize = 1; pub const IDENTITY_SERVICE_SOCKET_ADDR: &str = "[::]:50054"; // Token pub const ACCESS_TOKEN_LENGTH: usize = 512; // Temporary config pub const AUTH_TOKEN: &str = "COMM_IDENTITY_SERVICE_AUTH_TOKEN"; // Nonce pub const NONCE_LENGTH: usize = 17; // LocalStack pub const LOCALSTACK_ENDPOINT: &str = "LOCALSTACK_ENDPOINT"; diff --git a/services/identity/src/database.rs b/services/identity/src/database.rs index b5901d10d..cc8224f44 100644 --- a/services/identity/src/database.rs +++ b/services/identity/src/database.rs @@ -1,907 +1,953 @@ use std::collections::HashMap; use std::fmt::{Display, Formatter, Result as FmtResult}; use std::str::FromStr; use std::sync::Arc; use aws_config::SdkConfig; use aws_sdk_dynamodb::model::AttributeValue; use aws_sdk_dynamodb::output::{ DeleteItemOutput, GetItemOutput, PutItemOutput, QueryOutput, }; use aws_sdk_dynamodb::types::Blob; use aws_sdk_dynamodb::{Client, Error as DynamoDBError}; use chrono::{DateTime, Utc}; use opaque_ke::errors::ProtocolError; use serde::{Deserialize, Serialize}; use tracing::{debug, error, info, warn}; -use crate::client_service::{UserLoginInfo, UserRegistrationInfo}; +use crate::client_service::{FlattenedDeviceKeyUpload, UserRegistrationInfo}; use crate::config::CONFIG; use crate::constants::{ ACCESS_TOKEN_SORT_KEY, ACCESS_TOKEN_TABLE, ACCESS_TOKEN_TABLE_AUTH_TYPE_ATTRIBUTE, ACCESS_TOKEN_TABLE_CREATED_ATTRIBUTE, ACCESS_TOKEN_TABLE_PARTITION_KEY, ACCESS_TOKEN_TABLE_TOKEN_ATTRIBUTE, ACCESS_TOKEN_TABLE_VALID_ATTRIBUTE, NONCE_TABLE, NONCE_TABLE_CREATED_ATTRIBUTE, NONCE_TABLE_PARTITION_KEY, USERS_TABLE, USERS_TABLE_DEVICES_ATTRIBUTE, USERS_TABLE_DEVICES_MAP_DEVICE_TYPE_ATTRIBUTE_NAME, USERS_TABLE_DEVICES_MAP_IDENTITY_ONETIME_KEYS_ATTRIBUTE_NAME, USERS_TABLE_DEVICES_MAP_IDENTITY_PREKEY_ATTRIBUTE_NAME, USERS_TABLE_DEVICES_MAP_IDENTITY_PREKEY_SIGNATURE_ATTRIBUTE_NAME, USERS_TABLE_DEVICES_MAP_KEY_PAYLOAD_ATTRIBUTE_NAME, USERS_TABLE_DEVICES_MAP_KEY_PAYLOAD_SIGNATURE_ATTRIBUTE_NAME, USERS_TABLE_DEVICES_MAP_NOTIF_ONETIME_KEYS_ATTRIBUTE_NAME, USERS_TABLE_DEVICES_MAP_NOTIF_PREKEY_ATTRIBUTE_NAME, USERS_TABLE_DEVICES_MAP_NOTIF_PREKEY_SIGNATURE_ATTRIBUTE_NAME, + USERS_TABLE_DEVICES_MAP_SOCIAL_PROOF_ATTRIBUTE_NAME, USERS_TABLE_PARTITION_KEY, USERS_TABLE_REGISTRATION_ATTRIBUTE, USERS_TABLE_USERNAME_ATTRIBUTE, USERS_TABLE_USERNAME_INDEX, USERS_TABLE_WALLET_ADDRESS_ATTRIBUTE, USERS_TABLE_WALLET_ADDRESS_INDEX, }; use crate::id::generate_uuid; use crate::nonce::NonceData; use crate::token::{AccessTokenData, AuthType}; #[derive(Serialize, Deserialize)] pub struct OlmKeys { pub curve25519: String, pub ed25519: String, } #[derive(Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct KeyPayload { pub notification_identity_public_keys: OlmKeys, pub primary_identity_public_keys: OlmKeys, } impl FromStr for KeyPayload { type Err = serde_json::Error; // The payload is held in the database as an escaped JSON payload. // Escaped double quotes need to be trimmed before attempting to serialize fn from_str(payload: &str) -> Result { serde_json::from_str(&payload.replace(r#"\""#, r#"""#)) } } pub enum Device { Client, Keyserver, } impl Display for Device { fn fmt(&self, f: &mut Formatter) -> FmtResult { match self { Device::Client => write!(f, "client"), Device::Keyserver => write!(f, "keyserver"), } } } #[derive(Clone)] pub struct DatabaseClient { client: Arc, } impl DatabaseClient { pub fn new(aws_config: &SdkConfig) -> Self { let client = match &CONFIG.localstack_endpoint { Some(endpoint) => { info!( "Configuring DynamoDB client to use LocalStack endpoint: {}", endpoint ); let ddb_config_builder = aws_sdk_dynamodb::config::Builder::from(aws_config) .endpoint_url(endpoint); Client::from_conf(ddb_config_builder.build()) } None => Client::new(aws_config), }; DatabaseClient { client: Arc::new(client), } } - pub async fn add_user_to_users_table( + pub async fn add_password_user_to_users_table( &self, registration_state: UserRegistrationInfo, password_file: Vec, + ) -> Result { + self + .add_user_to_users_table( + registration_state.flattened_device_key_upload, + Some((registration_state.username, Blob::new(password_file))), + None, + None, + ) + .await + } + + pub async fn add_wallet_user_to_users_table( + &self, + flattened_device_key_upload: FlattenedDeviceKeyUpload, + wallet_address: String, + social_proof: String, + ) -> Result { + self + .add_user_to_users_table( + flattened_device_key_upload, + None, + Some(wallet_address), + Some(social_proof), + ) + .await + } + + async fn add_user_to_users_table( + &self, + flattened_device_key_upload: FlattenedDeviceKeyUpload, + username_and_password_file: Option<(String, Blob)>, + wallet_address: Option, + social_proof: Option, ) -> Result { let user_id = generate_uuid(); - let device_info = HashMap::from([ + let mut device_info = HashMap::from([ ( USERS_TABLE_DEVICES_MAP_DEVICE_TYPE_ATTRIBUTE_NAME.to_string(), AttributeValue::S(Device::Client.to_string()), ), ( USERS_TABLE_DEVICES_MAP_KEY_PAYLOAD_ATTRIBUTE_NAME.to_string(), - AttributeValue::S( - registration_state.flattened_device_key_upload.key_payload, - ), + AttributeValue::S(flattened_device_key_upload.key_payload), ), ( USERS_TABLE_DEVICES_MAP_KEY_PAYLOAD_SIGNATURE_ATTRIBUTE_NAME .to_string(), - AttributeValue::S( - registration_state - .flattened_device_key_upload - .key_payload_signature, - ), + AttributeValue::S(flattened_device_key_upload.key_payload_signature), ), ( USERS_TABLE_DEVICES_MAP_IDENTITY_PREKEY_ATTRIBUTE_NAME.to_string(), - AttributeValue::S( - registration_state - .flattened_device_key_upload - .identity_prekey, - ), + AttributeValue::S(flattened_device_key_upload.identity_prekey), ), ( USERS_TABLE_DEVICES_MAP_IDENTITY_PREKEY_SIGNATURE_ATTRIBUTE_NAME .to_string(), AttributeValue::S( - registration_state - .flattened_device_key_upload - .identity_prekey_signature, + flattened_device_key_upload.identity_prekey_signature, ), ), ( USERS_TABLE_DEVICES_MAP_IDENTITY_ONETIME_KEYS_ATTRIBUTE_NAME .to_string(), AttributeValue::L( - registration_state - .flattened_device_key_upload + flattened_device_key_upload .identity_onetime_keys .into_iter() .map(AttributeValue::S) .collect(), ), ), ( USERS_TABLE_DEVICES_MAP_NOTIF_PREKEY_ATTRIBUTE_NAME.to_string(), - AttributeValue::S( - registration_state.flattened_device_key_upload.notif_prekey, - ), + AttributeValue::S(flattened_device_key_upload.notif_prekey), ), ( USERS_TABLE_DEVICES_MAP_NOTIF_PREKEY_SIGNATURE_ATTRIBUTE_NAME .to_string(), - AttributeValue::S( - registration_state - .flattened_device_key_upload - .notif_prekey_signature, - ), + AttributeValue::S(flattened_device_key_upload.notif_prekey_signature), ), ( USERS_TABLE_DEVICES_MAP_NOTIF_ONETIME_KEYS_ATTRIBUTE_NAME.to_string(), AttributeValue::L( - registration_state - .flattened_device_key_upload + flattened_device_key_upload .notif_onetime_keys .into_iter() .map(AttributeValue::S) .collect(), ), ), ]); + + if let Some(social_proof) = social_proof { + device_info.insert( + USERS_TABLE_DEVICES_MAP_SOCIAL_PROOF_ATTRIBUTE_NAME.to_string(), + AttributeValue::S(social_proof), + ); + } let devices = HashMap::from([( - registration_state.flattened_device_key_upload.device_id_key, + flattened_device_key_upload.device_id_key, AttributeValue::M(device_info), )]); - - let user = HashMap::from([ + let mut user = HashMap::from([ ( USERS_TABLE_PARTITION_KEY.to_string(), AttributeValue::S(user_id.clone()), ), - ( - USERS_TABLE_USERNAME_ATTRIBUTE.to_string(), - AttributeValue::S(registration_state.username), - ), ( USERS_TABLE_DEVICES_ATTRIBUTE.to_string(), AttributeValue::M(devices), ), - ( - USERS_TABLE_REGISTRATION_ATTRIBUTE.to_string(), - AttributeValue::B(Blob::new(password_file)), - ), ]); + if let Some((username, password_file)) = username_and_password_file { + user.insert( + USERS_TABLE_USERNAME_ATTRIBUTE.to_string(), + AttributeValue::S(username), + ); + user.insert( + USERS_TABLE_REGISTRATION_ATTRIBUTE.to_string(), + AttributeValue::B(password_file), + ); + } + + if let Some(address) = wallet_address { + user.insert( + USERS_TABLE_WALLET_ADDRESS_ATTRIBUTE.to_string(), + AttributeValue::S(address), + ); + } + self .client .put_item() .table_name(USERS_TABLE) .set_item(Some(user)) .send() .await .map_err(|e| Error::AwsSdk(e.into()))?; Ok(user_id) } - pub async fn add_device_to_users_table( + pub async fn add_password_user_device_to_users_table( + &self, + user_id: String, + flattened_device_key_upload: FlattenedDeviceKeyUpload, + ) -> Result<(), Error> { + self + .add_device_to_users_table(user_id, flattened_device_key_upload, None) + .await + } + + pub async fn add_wallet_user_device_to_users_table( + &self, + user_id: String, + flattened_device_key_upload: FlattenedDeviceKeyUpload, + social_proof: String, + ) -> Result<(), Error> { + self + .add_device_to_users_table( + user_id, + flattened_device_key_upload, + Some(social_proof), + ) + .await + } + + async fn add_device_to_users_table( &self, - login_state: UserLoginInfo, + user_id: String, + flattened_device_key_upload: FlattenedDeviceKeyUpload, + social_proof: Option, ) -> Result<(), Error> { - let device_info = HashMap::from([ + let mut device_info = HashMap::from([ ( USERS_TABLE_DEVICES_MAP_DEVICE_TYPE_ATTRIBUTE_NAME.to_string(), AttributeValue::S(Device::Client.to_string()), ), ( USERS_TABLE_DEVICES_MAP_KEY_PAYLOAD_ATTRIBUTE_NAME.to_string(), - AttributeValue::S(login_state.flattened_device_key_upload.key_payload), + AttributeValue::S(flattened_device_key_upload.key_payload), ), ( USERS_TABLE_DEVICES_MAP_KEY_PAYLOAD_SIGNATURE_ATTRIBUTE_NAME .to_string(), - AttributeValue::S( - login_state - .flattened_device_key_upload - .key_payload_signature, - ), + AttributeValue::S(flattened_device_key_upload.key_payload_signature), ), ( USERS_TABLE_DEVICES_MAP_IDENTITY_PREKEY_ATTRIBUTE_NAME.to_string(), - AttributeValue::S( - login_state.flattened_device_key_upload.identity_prekey, - ), + AttributeValue::S(flattened_device_key_upload.identity_prekey), ), ( USERS_TABLE_DEVICES_MAP_IDENTITY_PREKEY_SIGNATURE_ATTRIBUTE_NAME .to_string(), AttributeValue::S( - login_state - .flattened_device_key_upload - .identity_prekey_signature, + flattened_device_key_upload.identity_prekey_signature, ), ), ( USERS_TABLE_DEVICES_MAP_IDENTITY_ONETIME_KEYS_ATTRIBUTE_NAME .to_string(), AttributeValue::L( - login_state - .flattened_device_key_upload + flattened_device_key_upload .identity_onetime_keys .into_iter() .map(AttributeValue::S) .collect(), ), ), ( USERS_TABLE_DEVICES_MAP_NOTIF_PREKEY_ATTRIBUTE_NAME.to_string(), - AttributeValue::S(login_state.flattened_device_key_upload.notif_prekey), + AttributeValue::S(flattened_device_key_upload.notif_prekey), ), ( USERS_TABLE_DEVICES_MAP_NOTIF_PREKEY_SIGNATURE_ATTRIBUTE_NAME .to_string(), - AttributeValue::S( - login_state - .flattened_device_key_upload - .notif_prekey_signature, - ), + AttributeValue::S(flattened_device_key_upload.notif_prekey_signature), ), ( USERS_TABLE_DEVICES_MAP_NOTIF_ONETIME_KEYS_ATTRIBUTE_NAME.to_string(), AttributeValue::L( - login_state - .flattened_device_key_upload + flattened_device_key_upload .notif_onetime_keys .into_iter() .map(AttributeValue::S) .collect(), ), ), ]); + if let Some(social_proof) = social_proof { + device_info.insert( + USERS_TABLE_DEVICES_MAP_SOCIAL_PROOF_ATTRIBUTE_NAME.to_string(), + AttributeValue::S(social_proof), + ); + } let update_expression = format!("SET {}.#{} = :v", USERS_TABLE_DEVICES_ATTRIBUTE, "deviceID",); let expression_attribute_names = HashMap::from([( format!("#{}", "deviceID"), - login_state.flattened_device_key_upload.device_id_key, + flattened_device_key_upload.device_id_key, )]); let expression_attribute_values = HashMap::from([(":v".to_string(), AttributeValue::M(device_info))]); self .client .update_item() .table_name(USERS_TABLE) - .key( - USERS_TABLE_PARTITION_KEY, - AttributeValue::S(login_state.user_id), - ) + .key(USERS_TABLE_PARTITION_KEY, AttributeValue::S(user_id)) .update_expression(update_expression) .set_expression_attribute_names(Some(expression_attribute_names)) .set_expression_attribute_values(Some(expression_attribute_values)) .send() .await .map_err(|e| Error::AwsSdk(e.into()))?; Ok(()) } pub async fn delete_user( &self, user_id: String, ) -> Result { debug!("Attempting to delete user: {}", user_id); match self .client .delete_item() .table_name(USERS_TABLE) .key( USERS_TABLE_PARTITION_KEY, AttributeValue::S(user_id.clone()), ) .send() .await { Ok(out) => { info!("User has been deleted {}", user_id); Ok(out) } Err(e) => { error!("DynamoDB client failed to delete user {}", user_id); Err(Error::AwsSdk(e.into())) } } } pub async fn get_access_token_data( &self, user_id: String, signing_public_key: String, ) -> Result, Error> { let primary_key = create_composite_primary_key( ( ACCESS_TOKEN_TABLE_PARTITION_KEY.to_string(), user_id.clone(), ), ( ACCESS_TOKEN_SORT_KEY.to_string(), signing_public_key.clone(), ), ); let get_item_result = self .client .get_item() .table_name(ACCESS_TOKEN_TABLE) .set_key(Some(primary_key)) .consistent_read(true) .send() .await; match get_item_result { Ok(GetItemOutput { item: Some(mut item), .. }) => { let created = parse_created_attribute( item.remove(ACCESS_TOKEN_TABLE_CREATED_ATTRIBUTE), )?; let auth_type = parse_auth_type_attribute( item.remove(ACCESS_TOKEN_TABLE_AUTH_TYPE_ATTRIBUTE), )?; let valid = parse_valid_attribute( item.remove(ACCESS_TOKEN_TABLE_VALID_ATTRIBUTE), )?; let access_token = parse_token_attribute( item.remove(ACCESS_TOKEN_TABLE_TOKEN_ATTRIBUTE), )?; Ok(Some(AccessTokenData { user_id, signing_public_key, access_token, created, auth_type, valid, })) } Ok(_) => { info!( "No item found for user {} and signing public key {} in token table", user_id, signing_public_key ); Ok(None) } Err(e) => { error!( "DynamoDB client failed to get token for user {} with signing public key {}: {}", user_id, signing_public_key, e ); Err(Error::AwsSdk(e.into())) } } } pub async fn put_access_token_data( &self, access_token_data: AccessTokenData, ) -> Result { let item = HashMap::from([ ( ACCESS_TOKEN_TABLE_PARTITION_KEY.to_string(), AttributeValue::S(access_token_data.user_id), ), ( ACCESS_TOKEN_SORT_KEY.to_string(), AttributeValue::S(access_token_data.signing_public_key), ), ( ACCESS_TOKEN_TABLE_TOKEN_ATTRIBUTE.to_string(), AttributeValue::S(access_token_data.access_token), ), ( ACCESS_TOKEN_TABLE_CREATED_ATTRIBUTE.to_string(), AttributeValue::S(access_token_data.created.to_rfc3339()), ), ( ACCESS_TOKEN_TABLE_AUTH_TYPE_ATTRIBUTE.to_string(), AttributeValue::S(match access_token_data.auth_type { AuthType::Password => "password".to_string(), AuthType::Wallet => "wallet".to_string(), }), ), ( ACCESS_TOKEN_TABLE_VALID_ATTRIBUTE.to_string(), AttributeValue::Bool(access_token_data.valid), ), ]); self .client .put_item() .table_name(ACCESS_TOKEN_TABLE) .set_item(Some(item)) .send() .await .map_err(|e| Error::AwsSdk(e.into())) } pub async fn username_taken(&self, username: String) -> Result { let result = self .get_user_id_from_user_info(username, AuthType::Password) .await?; Ok(result.is_some()) } async fn get_user_from_user_info( &self, user_info: String, auth_type: AuthType, ) -> Result>, Error> { let (index, attribute_name) = match auth_type { AuthType::Password => { (USERS_TABLE_USERNAME_INDEX, USERS_TABLE_USERNAME_ATTRIBUTE) } AuthType::Wallet => ( USERS_TABLE_WALLET_ADDRESS_INDEX, USERS_TABLE_WALLET_ADDRESS_ATTRIBUTE, ), }; match self .client .query() .table_name(USERS_TABLE) .index_name(index) .key_condition_expression(format!("{} = :u", attribute_name)) .expression_attribute_values(":u", AttributeValue::S(user_info.clone())) .send() .await { Ok(QueryOutput { items: Some(items), .. }) => { let num_items = items.len(); if num_items == 0 { return Ok(None); } if num_items > 1 { warn!( "{} user IDs associated with {} {}: {:?}", num_items, attribute_name, user_info, items ); } let first_item = items[0].clone(); Ok(Some(first_item)) } Ok(_) => { info!( "No item found for {} {} in users table", attribute_name, user_info ); Ok(None) } Err(e) => { error!( "DynamoDB client failed to get user from {} {}: {}", attribute_name, user_info, e ); Err(Error::AwsSdk(e.into())) } } } pub async fn get_user_id_from_user_info( &self, user_info: String, auth_type: AuthType, ) -> Result, Error> { match self .get_user_from_user_info(user_info.clone(), auth_type) .await { Ok(Some(mut user)) => parse_string_attribute( USERS_TABLE_PARTITION_KEY, user.remove(USERS_TABLE_PARTITION_KEY), ) .map(Some) .map_err(Error::Attribute), Ok(_) => Ok(None), Err(e) => Err(e), } } pub async fn get_user_id_and_password_file_from_username( &self, username: &str, ) -> Result)>, Error> { match self .get_user_from_user_info(username.to_string(), AuthType::Password) .await { Ok(Some(mut user)) => { let user_id = parse_string_attribute( USERS_TABLE_PARTITION_KEY, user.remove(USERS_TABLE_PARTITION_KEY), )?; let password_file = parse_registration_data_attribute( user.remove(USERS_TABLE_REGISTRATION_ATTRIBUTE), )?; Ok(Some((user_id, password_file))) } Ok(_) => { info!( "No item found for user {} in PAKE registration table", username ); Ok(None) } Err(e) => { error!( "DynamoDB client failed to get registration data for user {}: {}", username, e ); Err(e) } } } pub async fn get_item_from_users_table( &self, user_id: &str, ) -> Result { let primary_key = create_simple_primary_key(( USERS_TABLE_PARTITION_KEY.to_string(), user_id.to_string(), )); self .client .get_item() .table_name(USERS_TABLE) .set_key(Some(primary_key)) .consistent_read(true) .send() .await .map_err(|e| Error::AwsSdk(e.into())) } pub async fn get_users(&self) -> Result, Error> { let scan_output = self .client .scan() .table_name(USERS_TABLE) .projection_expression(USERS_TABLE_PARTITION_KEY) .send() .await .map_err(|e| Error::AwsSdk(e.into()))?; let mut result = Vec::new(); if let Some(attributes) = scan_output.items { for mut attribute in attributes { let id = parse_string_attribute( USERS_TABLE_PARTITION_KEY, attribute.remove(USERS_TABLE_PARTITION_KEY), ) .map_err(Error::Attribute)?; result.push(id); } } Ok(result) } pub async fn add_nonce_to_nonces_table( &self, nonce_data: NonceData, ) -> Result { let item = HashMap::from([ ( NONCE_TABLE_PARTITION_KEY.to_string(), AttributeValue::S(nonce_data.nonce), ), ( NONCE_TABLE_CREATED_ATTRIBUTE.to_string(), AttributeValue::S(nonce_data.created.to_rfc3339()), ), ]); self .client .put_item() .table_name(NONCE_TABLE) .set_item(Some(item)) .send() .await .map_err(|e| Error::AwsSdk(e.into())) } } #[derive( Debug, derive_more::Display, derive_more::From, derive_more::Error, )] pub enum Error { #[display(...)] AwsSdk(DynamoDBError), #[display(...)] Attribute(DBItemError), } #[derive(Debug, derive_more::Error, derive_more::Constructor)] pub struct DBItemError { attribute_name: &'static str, attribute_value: Option, attribute_error: DBItemAttributeError, } impl Display for DBItemError { fn fmt(&self, f: &mut Formatter) -> FmtResult { match &self.attribute_error { DBItemAttributeError::Missing => { write!(f, "Attribute {} is missing", self.attribute_name) } DBItemAttributeError::IncorrectType => write!( f, "Value for attribute {} has incorrect type: {:?}", self.attribute_name, self.attribute_value ), error => write!( f, "Error regarding attribute {} with value {:?}: {}", self.attribute_name, self.attribute_value, error ), } } } #[derive(Debug, derive_more::Display, derive_more::Error)] pub enum DBItemAttributeError { #[display(...)] Missing, #[display(...)] IncorrectType, #[display(...)] InvalidTimestamp(chrono::ParseError), #[display(...)] Pake(ProtocolError), } type AttributeName = String; fn create_simple_primary_key( partition_key: (AttributeName, String), ) -> HashMap { HashMap::from([(partition_key.0, AttributeValue::S(partition_key.1))]) } fn create_composite_primary_key( partition_key: (AttributeName, String), sort_key: (AttributeName, String), ) -> HashMap { let mut primary_key = create_simple_primary_key(partition_key); primary_key.insert(sort_key.0, AttributeValue::S(sort_key.1)); primary_key } fn parse_created_attribute( attribute: Option, ) -> Result, DBItemError> { if let Some(AttributeValue::S(created)) = &attribute { created.parse().map_err(|e| { DBItemError::new( ACCESS_TOKEN_TABLE_CREATED_ATTRIBUTE, attribute, DBItemAttributeError::InvalidTimestamp(e), ) }) } else { Err(DBItemError::new( ACCESS_TOKEN_TABLE_CREATED_ATTRIBUTE, attribute, DBItemAttributeError::Missing, )) } } fn parse_auth_type_attribute( attribute: Option, ) -> Result { if let Some(AttributeValue::S(auth_type)) = &attribute { match auth_type.as_str() { "password" => Ok(AuthType::Password), "wallet" => Ok(AuthType::Wallet), _ => Err(DBItemError::new( ACCESS_TOKEN_TABLE_AUTH_TYPE_ATTRIBUTE, attribute, DBItemAttributeError::IncorrectType, )), } } else { Err(DBItemError::new( ACCESS_TOKEN_TABLE_AUTH_TYPE_ATTRIBUTE, attribute, DBItemAttributeError::Missing, )) } } fn parse_valid_attribute( attribute: Option, ) -> Result { match attribute { Some(AttributeValue::Bool(valid)) => Ok(valid), Some(_) => Err(DBItemError::new( ACCESS_TOKEN_TABLE_VALID_ATTRIBUTE, attribute, DBItemAttributeError::IncorrectType, )), None => Err(DBItemError::new( ACCESS_TOKEN_TABLE_VALID_ATTRIBUTE, attribute, DBItemAttributeError::Missing, )), } } fn parse_token_attribute( attribute: Option, ) -> Result { match attribute { Some(AttributeValue::S(token)) => Ok(token), Some(_) => Err(DBItemError::new( ACCESS_TOKEN_TABLE_TOKEN_ATTRIBUTE, attribute, DBItemAttributeError::IncorrectType, )), None => Err(DBItemError::new( ACCESS_TOKEN_TABLE_TOKEN_ATTRIBUTE, attribute, DBItemAttributeError::Missing, )), } } fn parse_registration_data_attribute( attribute: Option, ) -> Result, DBItemError> { match attribute { Some(AttributeValue::B(server_registration_bytes)) => { Ok(server_registration_bytes.into_inner()) } Some(_) => Err(DBItemError::new( USERS_TABLE_REGISTRATION_ATTRIBUTE, attribute, DBItemAttributeError::IncorrectType, )), None => Err(DBItemError::new( USERS_TABLE_REGISTRATION_ATTRIBUTE, attribute, DBItemAttributeError::Missing, )), } } fn parse_map_attribute( attribute_name: &'static str, attribute_value: Option, ) -> Result, DBItemError> { match attribute_value { Some(AttributeValue::M(map)) => Ok(map), Some(_) => Err(DBItemError::new( attribute_name, attribute_value, DBItemAttributeError::IncorrectType, )), None => Err(DBItemError::new( attribute_name, attribute_value, DBItemAttributeError::Missing, )), } } fn parse_string_attribute( attribute_name: &'static str, attribute_value: Option, ) -> Result { match attribute_value { Some(AttributeValue::S(value)) => Ok(value), Some(_) => Err(DBItemError::new( attribute_name, attribute_value, DBItemAttributeError::IncorrectType, )), None => Err(DBItemError::new( attribute_name, attribute_value, DBItemAttributeError::Missing, )), } } #[cfg(test)] mod tests { use super::*; #[test] fn test_create_simple_primary_key() { let partition_key_name = "userID".to_string(); let partition_key_value = "12345".to_string(); let partition_key = (partition_key_name.clone(), partition_key_value.clone()); let mut primary_key = create_simple_primary_key(partition_key); assert_eq!(primary_key.len(), 1); let attribute = primary_key.remove(&partition_key_name); assert!(attribute.is_some()); assert_eq!(attribute, Some(AttributeValue::S(partition_key_value))); } #[test] fn test_create_composite_primary_key() { let partition_key_name = "userID".to_string(); let partition_key_value = "12345".to_string(); let partition_key = (partition_key_name.clone(), partition_key_value.clone()); let sort_key_name = "deviceID".to_string(); let sort_key_value = "54321".to_string(); let sort_key = (sort_key_name.clone(), sort_key_value.clone()); let mut primary_key = create_composite_primary_key(partition_key, sort_key); assert_eq!(primary_key.len(), 2); let partition_key_attribute = primary_key.remove(&partition_key_name); assert!(partition_key_attribute.is_some()); assert_eq!( partition_key_attribute, Some(AttributeValue::S(partition_key_value)) ); let sort_key_attribute = primary_key.remove(&sort_key_name); assert!(sort_key_attribute.is_some()); assert_eq!(sort_key_attribute, Some(AttributeValue::S(sort_key_value))) } #[test] fn validate_keys() { // Taken from test user let example_payload = r#"{\"notificationIdentityPublicKeys\":{\"curve25519\":\"DYmV8VdkjwG/VtC8C53morogNJhpTPT/4jzW0/cxzQo\",\"ed25519\":\"D0BV2Y7Qm36VUtjwyQTJJWYAycN7aMSJmhEsRJpW2mk\"},\"primaryIdentityPublicKeys\":{\"curve25519\":\"Y4ZIqzpE1nv83kKGfvFP6rifya0itRg2hifqYtsISnk\",\"ed25519\":\"cSlL+VLLJDgtKSPlIwoCZg0h0EmHlQoJC08uV/O+jvg\"}}"#; let serialized_payload = KeyPayload::from_str(&example_payload).unwrap(); assert_eq!( serialized_payload .notification_identity_public_keys .curve25519, "DYmV8VdkjwG/VtC8C53morogNJhpTPT/4jzW0/cxzQo" ); } } diff --git a/services/identity/src/main.rs b/services/identity/src/main.rs index 63c31c4a2..1a49cb473 100644 --- a/services/identity/src/main.rs +++ b/services/identity/src/main.rs @@ -1,79 +1,80 @@ use std::time::Duration; use clap::{Parser, Subcommand}; use database::DatabaseClient; use moka::future::Cache; use tonic::transport::Server; use tracing_subscriber::FmtSubscriber; mod client_service; mod config; pub mod constants; mod database; mod id; mod interceptor; mod keygen; mod nonce; +mod siwe; mod token; use config::load_config; use constants::{IDENTITY_SERVICE_SOCKET_ADDR, SECRETS_DIRECTORY}; use keygen::generate_and_persist_keypair; use tracing::info; use client_service::{ClientService, IdentityClientServiceServer}; #[derive(Parser)] #[clap(author, version, about, long_about = None)] #[clap(propagate_version = true)] struct Cli { #[clap(subcommand)] command: Commands, } #[derive(Subcommand)] enum Commands { /// Runs the server Server, /// Generates and persists a keypair to use for PAKE registration and login Keygen { #[clap(short, long)] #[clap(default_value_t = String::from(SECRETS_DIRECTORY))] dir: String, }, /// Populates the `identity-users` table in DynamoDB from MySQL PopulateDB, } #[tokio::main] async fn main() -> Result<(), Box> { let subscriber = FmtSubscriber::new(); tracing::subscriber::set_global_default(subscriber)?; let cli = Cli::parse(); match &cli.command { Commands::Keygen { dir } => { generate_and_persist_keypair(dir)?; } Commands::Server => { load_config(); let addr = IDENTITY_SERVICE_SOCKET_ADDR.parse()?; let aws_config = aws_config::from_env().region("us-east-2").load().await; let database_client = DatabaseClient::new(&aws_config); let workflow_cache = Cache::builder() .time_to_live(Duration::from_secs(10)) .build(); let client_service = IdentityClientServiceServer::new( ClientService::new(database_client, workflow_cache), ); info!("Listening to gRPC traffic on {}", addr); Server::builder() .accept_http1(true) .add_service(tonic_web::enable(client_service)) .serve(addr) .await?; } Commands::PopulateDB => unimplemented!(), } Ok(()) } diff --git a/services/identity/src/siwe.rs b/services/identity/src/siwe.rs new file mode 100644 index 000000000..f70325f2d --- /dev/null +++ b/services/identity/src/siwe.rs @@ -0,0 +1,34 @@ +use chrono::Utc; +use siwe::{eip55, Message}; +use tonic::Status; +use tracing::error; + +pub fn parse_and_verify_siwe_message( + siwe_message: &str, + siwe_signature: &str, +) -> Result { + let siwe_message: Message = siwe_message.parse().map_err(|e| { + error!("Failed to parse SIWE message: {}", e); + 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") + })?; + + let signature = decoded_signature.try_into().map_err(|e| { + error!("Conversion to SIWE signature failed: {:?}", e); + Status::invalid_argument("invalid message") + })?; + + siwe_message + .verify(signature, None, None, Some(&Utc::now())) + .map_err(|e| { + error!("Signature verification failed: {}", e); + Status::unauthenticated("message not authenticated") + })?; + + Ok(eip55(&siwe_message.address)) +} diff --git a/shared/protos/identity_client.proto b/shared/protos/identity_client.proto index ee72ffbfe..a63800f0c 100644 --- a/shared/protos/identity_client.proto +++ b/shared/protos/identity_client.proto @@ -1,325 +1,325 @@ 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 (optional) + // 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; } // 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; }