diff --git a/services/identity/src/client_service.rs b/services/identity/src/client_service.rs index 93d8f19f2..ef3e2aedd 100644 --- a/services/identity/src/client_service.rs +++ b/services/identity/src/client_service.rs @@ -1,270 +1,313 @@ 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, }; use aws_sdk_dynamodb::Error as DynamoDBError; pub use client_proto::identity_client_service_server::{ IdentityClientService, IdentityClientServiceServer, }; use moka::future::Cache; use rand::rngs::OsRng; use tonic::Response; use tracing::error; #[derive(Clone)] pub enum WorkflowInProgress { Registration(UserRegistrationInfo), } #[derive(Clone)] pub struct UserRegistrationInfo { - username: String, - device_id_key: String, - key_payload: String, - key_payload_signature: String, - identity_prekey: String, - identity_prekey_signature: String, - identity_onetime_keys: Vec, - notif_prekey: String, - notif_prekey_signature: String, - notif_onetime_keys: Vec, + pub username: String, + 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(comm_opaque2::grpc::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, 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, + request: tonic::Request, ) -> Result, tonic::Status> { - unimplemented!(); + 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(comm_opaque2::grpc::protocol_error_to_grpc_status)?; + + let device_id = state.device_id_key.clone(); + let user_id = self + .client + .add_user_to_users_table(state, password_file) + .await + .map_err(handle_db_error)?; + + // Create access token + let token = AccessTokenData::new( + message.session_id, + 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> { unimplemented!(); } async fn login_password_user_finish( &self, _request: tonic::Request, ) -> Result, tonic::Status> { unimplemented!(); } async fn login_wallet_user( &self, _request: tonic::Request, ) -> Result, tonic::Status> { unimplemented!(); } 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 1991bfa97..82c82b5e7 100644 --- a/services/identity/src/constants.rs +++ b/services/identity/src/constants.rs @@ -1,111 +1,102 @@ // 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 -pub mod opaque2 { - // 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, - // identityPreKey: String, - // identityPreKeySignature: String, - // identityOneTimeKeys: Vec, - // notifPreKey: String, - // notifPreKeySignature: String, - // notifOneTimeKeys: Vec, - // } - // } - // - // 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-opaque2"; - 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_KEY_PAYLOAD_ATTRIBUTE_NAME: &str = - "keyPayload"; - 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_USERNAME_INDEX: &str = "username-index"; - pub const USERS_TABLE_WALLET_ADDRESS_INDEX: &str = "walletAddress-index"; -} + +// 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, +// } +// } +// +// 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 = "pakeRegistrationData"; +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_DEVICE_ATTRIBUTE_NAME: &str = "device"; -pub const USERS_TABLE_DEVICES_MAP_ATTRIBUTE_NAME: &str = "signingPublicKey"; +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_USERNAME_INDEX: &str = "username-index"; pub const USERS_TABLE_WALLET_ADDRESS_INDEX: &str = "walletAddress-index"; -pub const USERS_TABLE_INITIALIZATION_INFO: &str = "initializationInfo"; 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 d2db544bd..47c791fa7 100644 --- a/services/identity/src/database.rs +++ b/services/identity/src/database.rs @@ -1,837 +1,771 @@ 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, UpdateItemOutput, + 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, ServerRegistration}; use serde::{Deserialize, Serialize}; use tracing::{debug, error, info, warn}; +use crate::client_service::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_ATTRIBUTE_NAME, - USERS_TABLE_DEVICE_ATTRIBUTE_NAME, USERS_TABLE_INITIALIZATION_INFO, + 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_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}; use comm_opaque::Cipher; #[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 get_pake_registration( &self, user_id: String, ) -> Result>, Error> { match self.get_item_from_users_table(&user_id).await { Ok(GetItemOutput { item: Some(mut item), .. }) => parse_registration_data_attribute( item.remove(USERS_TABLE_REGISTRATION_ATTRIBUTE), ) .map(Some) .map_err(Error::Attribute), Ok(_) => { info!( "No item found for user {} in PAKE registration table", user_id ); Ok(None) } Err(e) => { error!( "DynamoDB client failed to get registration data for user {}: {}", user_id, e ); Err(e) } } } - pub async fn get_session_initialization_info( - &self, - user_id: &str, - ) -> Result>>, Error> { - match self.get_item_from_users_table(user_id).await { - Ok(GetItemOutput { - item: Some(mut item), - .. - }) => parse_devices_attribute(item.remove(USERS_TABLE_DEVICES_ATTRIBUTE)) - .map(Some) - .map_err(Error::Attribute), - Ok(_) => { - info!("No item found for user {} in users table", user_id); - Ok(None) - } - Err(e) => { - error!( - "DynamoDB client failed to get session initialization info for user {}: {}", - user_id, e - ); - Err(e) - } - } - } - - pub async fn update_users_table( - &self, - user_id: String, - signing_public_key: Option, - registration: Option>, - username: Option, - session_initialization_info: Option<&HashMap>, - ) -> Result { - let mut update_expression_parts = Vec::new(); - let mut expression_attribute_names = HashMap::new(); - let mut expression_attribute_values = HashMap::new(); - if let Some(reg) = registration { - update_expression_parts - .push(format!("{} = :r", USERS_TABLE_REGISTRATION_ATTRIBUTE)); - expression_attribute_values.insert( - ":r".to_string(), - AttributeValue::B(Blob::new(reg.serialize())), - ); - }; - if let Some(username) = username { - update_expression_parts - .push(format!("{} = :u", USERS_TABLE_USERNAME_ATTRIBUTE)); - expression_attribute_values - .insert(":u".to_string(), AttributeValue::S(username)); - }; - if let Some(public_key) = signing_public_key { - let device_info = match session_initialization_info { - Some(info) => info - .iter() - .map(|(k, v)| (k.to_string(), AttributeValue::S(v.to_string()))) - .collect(), - None => HashMap::new(), - }; - - // How we construct the update expression will depend on whether the user - // already exists or not - if let GetItemOutput { item: Some(_), .. } = - self.get_item_from_users_table(&user_id).await? - { - update_expression_parts.push(format!( - "{}.#{} = :k", - USERS_TABLE_DEVICES_ATTRIBUTE, USERS_TABLE_DEVICES_MAP_ATTRIBUTE_NAME, - )); - expression_attribute_names.insert( - format!("#{}", USERS_TABLE_DEVICES_MAP_ATTRIBUTE_NAME), - public_key, - ); - expression_attribute_values - .insert(":k".to_string(), AttributeValue::M(device_info)); - } else { - update_expression_parts - .push(format!("{} = :k", USERS_TABLE_DEVICES_ATTRIBUTE)); - let mut devices = HashMap::new(); - devices.insert(public_key, AttributeValue::M(device_info)); - expression_attribute_values - .insert(":k".to_string(), AttributeValue::M(devices)); - }; - }; - - self - .client - .update_item() - .table_name(USERS_TABLE) - .key(USERS_TABLE_PARTITION_KEY, AttributeValue::S(user_id)) - .update_expression(format!("SET {}", update_expression_parts.join(","))) - .set_expression_attribute_names( - if expression_attribute_names.is_empty() { - None - } else { - Some(expression_attribute_names) - }, - ) - .set_expression_attribute_values( - if expression_attribute_values.is_empty() { - None - } else { - Some(expression_attribute_values) - }, - ) - .send() - .await - .map_err(|e| Error::AwsSdk(e.into())) - } - pub async fn add_user_to_users_table( &self, - user_id: String, - registration: ServerRegistration, - username: String, - signing_public_key: String, - session_initialization_info: &HashMap, - ) -> Result { - let device_info: HashMap = - session_initialization_info - .iter() - .map(|(k, v)| (k.to_string(), AttributeValue::S(v.to_string()))) - .collect(); + registration_state: UserRegistrationInfo, + password_file: Vec, + ) -> Result { + let user_id = generate_uuid(); + let 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.key_payload), + ), + ( + USERS_TABLE_DEVICES_MAP_KEY_PAYLOAD_SIGNATURE_ATTRIBUTE_NAME + .to_string(), + AttributeValue::S(registration_state.key_payload_signature), + ), + ( + USERS_TABLE_DEVICES_MAP_IDENTITY_PREKEY_ATTRIBUTE_NAME.to_string(), + AttributeValue::S(registration_state.identity_prekey), + ), + ( + USERS_TABLE_DEVICES_MAP_IDENTITY_PREKEY_SIGNATURE_ATTRIBUTE_NAME + .to_string(), + AttributeValue::S(registration_state.identity_prekey_signature), + ), + ( + USERS_TABLE_DEVICES_MAP_IDENTITY_ONETIME_KEYS_ATTRIBUTE_NAME + .to_string(), + AttributeValue::L( + registration_state + .identity_onetime_keys + .into_iter() + .map(AttributeValue::S) + .collect(), + ), + ), + ( + USERS_TABLE_DEVICES_MAP_NOTIF_PREKEY_ATTRIBUTE_NAME.to_string(), + AttributeValue::S(registration_state.notif_prekey), + ), + ( + USERS_TABLE_DEVICES_MAP_NOTIF_PREKEY_SIGNATURE_ATTRIBUTE_NAME + .to_string(), + AttributeValue::S(registration_state.notif_prekey_signature), + ), + ( + USERS_TABLE_DEVICES_MAP_NOTIF_ONETIME_KEYS_ATTRIBUTE_NAME.to_string(), + AttributeValue::L( + registration_state + .notif_onetime_keys + .into_iter() + .map(AttributeValue::S) + .collect(), + ), + ), + ]); + let devices = HashMap::from([( + registration_state.device_id_key, + AttributeValue::M(device_info), + )]); - let item = HashMap::from([ + let user = HashMap::from([ ( USERS_TABLE_PARTITION_KEY.to_string(), - AttributeValue::S(user_id), + AttributeValue::S(user_id.clone()), ), ( USERS_TABLE_USERNAME_ATTRIBUTE.to_string(), - AttributeValue::S(username), + AttributeValue::S(registration_state.username), ), ( - USERS_TABLE_REGISTRATION_ATTRIBUTE.to_string(), - AttributeValue::B(Blob::new(registration.serialize())), + USERS_TABLE_DEVICES_ATTRIBUTE.to_string(), + AttributeValue::M(devices), ), ( - USERS_TABLE_DEVICES_ATTRIBUTE.to_string(), - AttributeValue::M(HashMap::from([( - signing_public_key, - AttributeValue::M(device_info), - )])), + USERS_TABLE_REGISTRATION_ATTRIBUTE.to_string(), + AttributeValue::B(Blob::new(password_file)), ), ]); self .client .put_item() .table_name(USERS_TABLE) - .set_item(Some(item)) + .set_item(Some(user)) .send() .await - .map_err(|e| Error::AwsSdk(e.into())) - } + .map_err(|e| Error::AwsSdk(e.into()))?; + Ok(user_id) + } 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()) } pub async fn get_user_id_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(mut 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 ); } parse_string_attribute( USERS_TABLE_PARTITION_KEY, items[0].remove(USERS_TABLE_PARTITION_KEY), ) .map(Some) .map_err(Error::Attribute) } Ok(_) => { info!( "No item found for {} {} in users table", attribute_name, user_info ); Ok(None) } Err(e) => { error!( "DynamoDB client failed to get user ID from {} {}: {}", attribute_name, user_info, e ); Err(Error::AwsSdk(e.into())) } } } 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)) => { match ServerRegistration::::deserialize( server_registration_bytes.as_ref(), ) { Ok(server_registration) => Ok(server_registration), Err(e) => Err(DBItemError::new( USERS_TABLE_REGISTRATION_ATTRIBUTE, attribute, DBItemAttributeError::Pake(e), )), } } Some(_) => Err(DBItemError::new( USERS_TABLE_REGISTRATION_ATTRIBUTE, attribute, DBItemAttributeError::IncorrectType, )), None => Err(DBItemError::new( USERS_TABLE_REGISTRATION_ATTRIBUTE, attribute, DBItemAttributeError::Missing, )), } } -fn parse_devices_attribute( - attribute: Option, -) -> Result>, DBItemError> { - let mut devices = HashMap::new(); - let ddb_devices = - parse_map_attribute(USERS_TABLE_DEVICES_ATTRIBUTE, attribute)?; - - for (signing_public_key, session_initialization_info) in ddb_devices { - let session_initialization_info_map = parse_map_attribute( - USERS_TABLE_DEVICE_ATTRIBUTE_NAME, - Some(session_initialization_info), - )?; - let mut inner_hash_map = HashMap::new(); - for (initialization_component_name, initialization_component_value) in - session_initialization_info_map - { - let initialization_piece_value_string = parse_string_attribute( - USERS_TABLE_INITIALIZATION_INFO, - Some(initialization_component_value), - )?; - inner_hash_map.insert( - initialization_component_name, - initialization_piece_value_string, - ); - } - devices.insert(signing_public_key, inner_hash_map); - } - Ok(devices) -} - 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/shared/protos/identity_client.proto b/shared/protos/identity_client.proto index 89be6090c..f11719493 100644 --- a/shared/protos/identity_client.proto +++ b/shared/protos/identity_client.proto @@ -1,320 +1,322 @@ 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) // 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 = 3; } // 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 = 2; } // 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 { // Mint and return a new key 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 accessToken = 1; } // 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 = 5; } // 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; }