diff --git a/.sqlx/query-4ee84adf4a01a20c49eb53336525708cde3d375c26458caed10dc17b9f899cd6.json b/.sqlx/query-4ee84adf4a01a20c49eb53336525708cde3d375c26458caed10dc17b9f899cd6.json deleted file mode 100644 index 3d9abf6..0000000 --- a/.sqlx/query-4ee84adf4a01a20c49eb53336525708cde3d375c26458caed10dc17b9f899cd6.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO discoveries VALUES ($1, $2, $3, $4)", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Text", - "Text", - { - "Custom": { - "name": "discovery_type", - "kind": { - "Enum": [ - "instance", - "repository" - ] - } - } - }, - "Text" - ] - }, - "nullable": [] - }, - "hash": "4ee84adf4a01a20c49eb53336525708cde3d375c26458caed10dc17b9f899cd6" -} diff --git a/src/authentication.rs b/src/authentication.rs index 55be9ff..af1a134 100644 --- a/src/authentication.rs +++ b/src/authentication.rs @@ -6,13 +6,7 @@ use tokio::{fs::File, io::AsyncReadExt}; use toml::Table; use crate::{ - messages::{ - authentication::{ - AuthenticationTokenRequest, AuthenticationTokenResponse, TokenExtensionRequest, - TokenExtensionResponse, - }, - InstanceAuthenticated, - }, + messages::authentication::{AuthenticationTokenResponse, TokenExtensionResponse}, model::{authenticated::UserAuthenticationToken, instance::Instance, user::User}, }; @@ -76,7 +70,7 @@ impl AuthenticationTokenGranter { &mut self, issued_for: impl ToOwned, username: String, - password: String, + _password: String, ) -> Result { let private_key = { let mut file = File::open( diff --git a/src/backend/discovery.rs b/src/backend/discovery.rs index 5d81dfb..a4d9a7a 100644 --- a/src/backend/discovery.rs +++ b/src/backend/discovery.rs @@ -1,21 +1,9 @@ -use std::{ - collections::hash_map::DefaultHasher, - hash::{Hash, Hasher}, -}; +use std::hash::Hash; -use anyhow::Error; -use base64::{engine::general_purpose::STANDARD, Engine as _}; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use sqlx::PgPool; -use crate::{ - messages::discovery::{DiscoveryMessage, DiscoveryMessageKind}, - model::{discovery::DiscoveryItem, repository::Repository}, -}; - -use super::DiscoveryBackend; - pub struct GiteratedDiscoveryProtocol { pub pool: PgPool, } @@ -27,78 +15,6 @@ pub enum DiscoveryType { Repository, } -#[async_trait::async_trait] -impl DiscoveryBackend for GiteratedDiscoveryProtocol { - async fn try_handle(&mut self, request: &DiscoveryMessage) -> Result { - if request - .message - .validate(&request.message.instance) - .await - .is_err() - { - return Ok(false); - } - - let inner = request.message.inner().await.clone(); - - match inner { - DiscoveryMessageKind::Discoveries(mut discoveries) => { - let discoveries = discoveries.discoveries.drain(..).map(|discovery| { - let hash = { - let mut hasher = DefaultHasher::new(); - discovery.hash(&mut hasher); - STANDARD.encode(hasher.finish().to_be_bytes()) - }; - - let (discovery_type, discovery) = match discovery { - DiscoveryItem::Instance { - instance, - signature, - } => (DiscoveryType::Instance, instance.to_string()), - DiscoveryItem::Repository { - repository, - signature, - } => (DiscoveryType::Repository, repository.to_string()), - }; - - DiscoveriesRow { - discovery_hash: hash, - discovery_time: Utc::now(), - discovery_type, - discovery, - } - }); - - for row in discoveries { - let result = sqlx::query!( - r#"INSERT INTO discoveries VALUES ($1, $2, $3, $4)"#, - row.discovery_hash, - row.discovery_time.to_string(), - row.discovery_type as _, - row.discovery - ) - .execute(&self.pool) - .await; - - match result { - Ok(_) => {} - Err(err) => { - error!("Error inserting discovery. {:?}", err); - } - } - } - Ok(true) - } - DiscoveryMessageKind::Offer(offer) => Ok(true), - DiscoveryMessageKind::Request(request) => Ok(true), - } - } - - async fn search(&mut self, _search: &str) -> Result, Error> { - todo!() - } -} - #[derive(Debug, sqlx::FromRow, sqlx::Type)] pub struct DiscoveriesRow { discovery_hash: String, diff --git a/src/backend/git.rs b/src/backend/git.rs index 892b8f4..a2d5899 100644 --- a/src/backend/git.rs +++ b/src/backend/git.rs @@ -6,8 +6,6 @@ use sqlx::{Either, PgPool}; use std::path::{Path, PathBuf}; use thiserror::Error; -use crate::messages::ValidatedUserAuthenticated; - use crate::model::instance::Instance; use crate::model::repository::{ Commit, Repository, RepositoryObjectType, RepositorySummary, RepositoryTreeEntry, @@ -212,7 +210,7 @@ impl GitBackend { impl RepositoryBackend for GitBackend { async fn create_repository( &mut self, - user: &User, + _user: &User, request: &CreateRepositoryRequest, ) -> Result { // Check if repository already exists in the database @@ -439,7 +437,7 @@ impl RepositoryBackend for GitBackend { async fn repository_file_inspect( &mut self, - requester: Option<&User>, + _requester: Option<&User>, _request: &RepositoryFileInspectRequest, ) -> Result { todo!() @@ -480,21 +478,24 @@ impl RepositoryBackend for GitBackend { impl IssuesBackend for GitBackend { fn issues_count( &mut self, - _request: &ValidatedUserAuthenticated, + _requester: Option<&User>, + _request: &RepositoryIssuesCountRequest, ) -> Result { todo!() } fn issue_labels( &mut self, - _request: &ValidatedUserAuthenticated, + _requester: Option<&User>, + _request: &RepositoryIssueLabelsRequest, ) -> Result { todo!() } fn issues( &mut self, - _request: &ValidatedUserAuthenticated, + _requester: Option<&User>, + _request: &RepositoryIssuesRequest, ) -> Result { todo!() } diff --git a/src/backend/mod.rs b/src/backend/mod.rs index a861980..dd6efae 100644 --- a/src/backend/mod.rs +++ b/src/backend/mod.rs @@ -12,7 +12,6 @@ use crate::{ AuthenticationTokenRequest, AuthenticationTokenResponse, RegisterAccountRequest, RegisterAccountResponse, }, - discovery::DiscoveryMessage, repository::{ CreateRepositoryRequest, CreateRepositoryResponse, RepositoryFileInspectRequest, RepositoryFileInspectionResponse, RepositoryInfoRequest, RepositoryIssueLabelsRequest, @@ -23,10 +22,9 @@ use crate::{ UserBioRequest, UserBioResponse, UserDisplayImageRequest, UserDisplayImageResponse, UserDisplayNameRequest, UserDisplayNameResponse, }, - ValidatedUserAuthenticated, }, model::{ - repository::{Repository, RepositorySummary, RepositoryView}, + repository::{RepositorySummary, RepositoryView}, user::User, }, }; @@ -55,15 +53,18 @@ pub trait RepositoryBackend: IssuesBackend { pub trait IssuesBackend { fn issues_count( &mut self, - request: &ValidatedUserAuthenticated, + requester: Option<&User>, + request: &RepositoryIssuesCountRequest, ) -> Result; fn issue_labels( &mut self, - request: &ValidatedUserAuthenticated, + requester: Option<&User>, + request: &RepositoryIssueLabelsRequest, ) -> Result; fn issues( &mut self, - request: &ValidatedUserAuthenticated, + requester: Option<&User>, + request: &RepositoryIssuesRequest, ) -> Result; } @@ -95,9 +96,3 @@ pub trait UserBackend: AuthBackend { async fn bio(&mut self, request: UserBioRequest) -> Result; async fn exists(&mut self, user: &User) -> Result; } - -#[async_trait::async_trait] -pub trait DiscoveryBackend { - async fn try_handle(&mut self, request: &DiscoveryMessage) -> Result; - async fn search(&mut self, search: &str) -> Result, Error>; -} diff --git a/src/backend/user.rs b/src/backend/user.rs index cff3644..3fc2bca 100644 --- a/src/backend/user.rs +++ b/src/backend/user.rs @@ -203,6 +203,7 @@ impl AuthBackend for UserAuth { } } +#[allow(unused)] #[derive(Debug, sqlx::FromRow)] struct UserRow { pub username: String, diff --git a/src/connection.rs b/src/connection.rs index 4c39159..fb14a52 100644 --- a/src/connection.rs +++ b/src/connection.rs @@ -4,47 +4,16 @@ pub mod repository; pub mod user; pub mod wrapper; -use std::{any::type_name, collections::HashMap, net::SocketAddr, str::FromStr, sync::Arc}; +use std::{any::type_name, collections::HashMap}; use anyhow::Error; -use futures_util::{stream::StreamExt, SinkExt}; -use semver::Version; use serde::{de::DeserializeOwned, Serialize}; -use tokio::{ - net::TcpStream, - sync::{ - broadcast::{Receiver, Sender}, - Mutex, - }, - task::JoinHandle, -}; -use tokio_tungstenite::{tungstenite::Message, WebSocketStream}; +use tokio::{net::TcpStream, task::JoinHandle}; +use tokio_tungstenite::WebSocketStream; use crate::{ - authentication::AuthenticationTokenGranter, - backend::{DiscoveryBackend, RepositoryBackend, UserBackend}, - handshake::{HandshakeFinalize, HandshakeMessage, HandshakeResponse}, - listener::Listeners, - messages::{ - authentication::{ - AuthenticationMessage, AuthenticationRequest, AuthenticationResponse, - TokenExtensionResponse, - }, - repository::{ - RepositoryMessage, RepositoryMessageKind, RepositoryRequest, RepositoryResponse, - }, - user::{ - UserMessage, UserMessageKind, UserMessageRequest, UserMessageResponse, - UserRepositoriesResponse, - }, - ErrorMessage, MessageKind, - }, - model::{ - instance::{Instance, InstanceMeta}, - repository::Repository, - user::User, - }, - validate_version, version, + messages::ErrorMessage, + model::instance::{Instance, InstanceMeta}, }; #[derive(Debug, thiserror::Error)] @@ -63,7 +32,6 @@ pub struct RawConnection { pub struct InstanceConnection { pub instance: InstanceMeta, - pub sender: Sender, pub task: JoinHandle<()>, } @@ -78,212 +46,6 @@ pub struct Connections { pub instance_connections: HashMap, } -pub async fn connection_worker( - mut socket: &mut WebSocketStream, - handshaked: &mut bool, - listeners: &Arc>, - connections: &Arc>, - backend: &Arc>, - user_backend: &Arc>, - auth_granter: &Arc>, - discovery_backend: &Arc>, - addr: &SocketAddr, -) -> Result<(), ConnectionError> { - let this_instance = Instance { - url: String::from("giterated.dev"), - }; - - let message = socket - .next() - .await - .ok_or_else(|| ConnectionError::Shutdown)? - .map_err(|e| Error::from(e))?; - - let payload = match message { - Message::Text(text) => text.into_bytes(), - Message::Binary(bytes) => bytes, - Message::Ping(_) => return Ok(()), - Message::Pong(_) => return Ok(()), - Message::Close(_) => { - info!("Closing connection with {}.", addr); - - return Err(ConnectionError::Shutdown); - } - _ => unreachable!(), - }; - - let message = serde_json::from_slice::(&payload).map_err(|e| Error::from(e))?; - - if let MessageKind::Handshake(handshake) = message { - match handshake { - HandshakeMessage::Initiate(request) => { - unimplemented!() - } - HandshakeMessage::Response(response) => { - unimplemented!() - } - HandshakeMessage::Finalize(response) => { - unimplemented!() - } - } - } - - if !*handshaked { - return Ok(()); - } - - if let MessageKind::Repository(repository) = &message { - if repository.target.instance != this_instance { - info!("Forwarding command to {}", repository.target.instance.url); - // We need to send this command to a different instance - - let mut listener = send_and_get_listener(message, &listeners, &connections).await; - - // Wait for response - while let Ok(message) = listener.recv().await { - if let MessageKind::Repository(RepositoryMessage { - command: RepositoryMessageKind::Response(_), - .. - }) = message - { - let _result = send(&mut socket, message).await; - } - } - - return Ok(()); - } else { - // This message is targeting this instance - match &repository.command { - RepositoryMessageKind::Request(request) => match request.clone() { - RepositoryRequest::CreateRepository(request) => { - unimplemented!(); - } - RepositoryRequest::RepositoryFileInspect(request) => { - unimplemented!() - } - RepositoryRequest::RepositoryInfo(request) => { - unimplemented!() - } - RepositoryRequest::IssuesCount(request) => { - unimplemented!() - } - RepositoryRequest::IssueLabels(request) => { - unimplemented!() - } - RepositoryRequest::Issues(request) => { - unimplemented!(); - } - }, - RepositoryMessageKind::Response(_response) => { - unreachable!() - } - } - } - } - - if let MessageKind::Authentication(authentication) = &message { - match authentication { - AuthenticationMessage::Request(request) => match request { - AuthenticationRequest::AuthenticationToken(token) => { - unimplemented!() - } - AuthenticationRequest::TokenExtension(request) => { - unimplemented!() - } - AuthenticationRequest::RegisterAccount(request) => { - unimplemented!() - } - }, - AuthenticationMessage::Response(_) => unreachable!(), - } - } - - if let MessageKind::Discovery(message) = &message { - let mut backend = discovery_backend.lock().await; - backend.try_handle(message).await?; - - return Ok(()); - } - - if let MessageKind::User(message) = &message { - match &message.message { - UserMessageKind::Request(request) => match request { - UserMessageRequest::DisplayName(request) => { - unimplemented!() - } - UserMessageRequest::DisplayImage(request) => { - unimplemented!() - } - UserMessageRequest::Bio(request) => { - unimplemented!() - } - UserMessageRequest::Repositories(request) => { - unimplemented!() - } - }, - UserMessageKind::Response(_) => unreachable!(), - } - } - - Ok(()) -} - -async fn send_and_get_listener( - message: MessageKind, - listeners: &Arc>, - connections: &Arc>, -) -> Receiver { - let (instance, user, repository): (Option, Option, Option) = - match &message { - MessageKind::Handshake(_) => { - todo!() - } - MessageKind::Repository(repository) => (None, None, Some(repository.target.clone())), - MessageKind::Authentication(_) => todo!(), - MessageKind::Discovery(_) => todo!(), - MessageKind::User(user) => todo!(), - MessageKind::Error(_) => todo!(), - }; - - let target = match (&instance, &user, &repository) { - (Some(instance), _, _) => instance.clone(), - (_, Some(user), _) => user.instance.clone(), - (_, _, Some(repository)) => repository.instance.clone(), - _ => unreachable!(), - }; - - let mut listeners = listeners.lock().await; - let listener = listeners.add(instance, user, repository); - drop(listeners); - - let connections = connections.lock().await; - - if let Some(connection) = connections.instance_connections.get(&target) { - if let Err(_) = connection.sender.send(message) { - error!("Error sending message."); - } - } else { - error!("Unable to message {}, this is a bug.", target.url); - - panic!(); - } - - drop(connections); - - listener -} - -async fn send( - socket: &mut WebSocketStream, - message: T, -) -> Result<(), Error> { - socket - .send(Message::Binary(serde_json::to_vec(&message)?)) - .await?; - - Ok(()) -} - #[derive(Debug, thiserror::Error)] #[error("handler did not handle")] pub struct HandlerUnhandled; diff --git a/src/connection/authentication.rs b/src/connection/authentication.rs index b773f5e..25cff28 100644 --- a/src/connection/authentication.rs +++ b/src/connection/authentication.rs @@ -1,12 +1,11 @@ use anyhow::Error; use thiserror::Error; -use crate::messages::authentication::{AuthenticationMessage, AuthenticationResponse}; -use crate::model::authenticated::MessageHandler; -use crate::{ - messages::{authentication::AuthenticationRequest, MessageKind}, - model::authenticated::{AuthenticatedInstance, NetworkMessage, State}, +use crate::messages::authentication::{ + AuthenticationTokenRequest, RegisterAccountRequest, TokenExtensionRequest, }; +use crate::model::authenticated::{AuthenticatedInstance, NetworkMessage, State}; +use crate::model::authenticated::{Message, MessageHandler}; use super::wrapper::ConnectionState; use super::HandlerUnhandled; @@ -15,42 +14,34 @@ pub async fn authentication_handle( message: &NetworkMessage, state: &ConnectionState, ) -> Result<(), Error> { - let message_kind: MessageKind = serde_json::from_slice(&message.0).unwrap(); - - match message_kind { - MessageKind::Authentication(AuthenticationMessage::Request(request)) => match request { - AuthenticationRequest::RegisterAccount(_) => { - register_account_request - .handle_message(message, state) - .await - } - AuthenticationRequest::AuthenticationToken(_) => { - authentication_token_request - .handle_message(message, state) - .await - } - AuthenticationRequest::TokenExtension(_) => { - token_extension_request.handle_message(message, state).await - } - }, - _ => Err(Error::from(HandlerUnhandled)), + if register_account_request + .handle_message(&message, state) + .await + .is_ok() + { + Ok(()) + } else if authentication_token_request + .handle_message(&message, state) + .await + .is_ok() + { + Ok(()) + } else if token_extension_request + .handle_message(&message, state) + .await + .is_ok() + { + Ok(()) + } else { + Err(Error::from(HandlerUnhandled)) } } async fn register_account_request( State(connection_state): State, - request: MessageKind, + Message(request): Message, instance: AuthenticatedInstance, ) -> Result<(), AuthenticationConnectionError> { - let request = if let MessageKind::Authentication(AuthenticationMessage::Request( - AuthenticationRequest::RegisterAccount(request), - )) = request - { - request - } else { - return Err(AuthenticationConnectionError::InvalidRequest); - }; - if *instance.inner() != connection_state.instance { return Err(AuthenticationConnectionError::SameInstance); } @@ -64,9 +55,7 @@ async fn register_account_request( drop(user_backend); connection_state - .send(MessageKind::Authentication( - AuthenticationMessage::Response(AuthenticationResponse::RegisterAccount(response)), - )) + .send(response) .await .map_err(|e| AuthenticationConnectionError::Sending(e))?; @@ -75,18 +64,9 @@ async fn register_account_request( async fn authentication_token_request( State(connection_state): State, - request: MessageKind, + Message(request): Message, instance: AuthenticatedInstance, ) -> Result<(), AuthenticationConnectionError> { - let request = if let MessageKind::Authentication(AuthenticationMessage::Request( - AuthenticationRequest::AuthenticationToken(request), - )) = request - { - request - } else { - return Err(AuthenticationConnectionError::InvalidRequest); - }; - let issued_for = instance.inner().clone(); let mut token_granter = connection_state.auth_granter.lock().await; @@ -97,9 +77,7 @@ async fn authentication_token_request( .map_err(|e| AuthenticationConnectionError::TokenIssuance(e))?; connection_state - .send(MessageKind::Authentication( - AuthenticationMessage::Response(AuthenticationResponse::AuthenticationToken(response)), - )) + .send(response) .await .map_err(|e| AuthenticationConnectionError::Sending(e))?; @@ -108,18 +86,9 @@ async fn authentication_token_request( async fn token_extension_request( State(connection_state): State, - request: MessageKind, + Message(request): Message, instance: AuthenticatedInstance, ) -> Result<(), AuthenticationConnectionError> { - let request = if let MessageKind::Authentication(AuthenticationMessage::Request( - AuthenticationRequest::TokenExtension(request), - )) = request - { - request - } else { - return Err(AuthenticationConnectionError::InvalidRequest); - }; - let issued_for = instance.inner().clone(); let mut token_granter = connection_state.auth_granter.lock().await; @@ -130,21 +99,13 @@ async fn token_extension_request( .map_err(|e| AuthenticationConnectionError::TokenIssuance(e))?; connection_state - .send(MessageKind::Authentication( - AuthenticationMessage::Response(AuthenticationResponse::TokenExtension(response)), - )) + .send(response) .await .map_err(|e| AuthenticationConnectionError::Sending(e))?; Ok(()) } -async fn verify(state: ConnectionState) { - register_account_request - .handle_message(&NetworkMessage(vec![]), &state) - .await; -} - #[derive(Debug, Error)] pub enum AuthenticationConnectionError { #[error("the request was invalid")] diff --git a/src/connection/handshake.rs b/src/connection/handshake.rs index bf77de9..86febba 100644 --- a/src/connection/handshake.rs +++ b/src/connection/handshake.rs @@ -2,7 +2,6 @@ use std::{str::FromStr, sync::atomic::Ordering}; use anyhow::Error; use semver::Version; -use thiserror::Error; use crate::model::authenticated::MessageHandler; use crate::{ diff --git a/src/connection/repository.rs b/src/connection/repository.rs index 96a5eb6..7f4b30f 100644 --- a/src/connection/repository.rs +++ b/src/connection/repository.rs @@ -4,7 +4,6 @@ use crate::{ messages::repository::{ CreateRepositoryRequest, RepositoryFileInspectRequest, RepositoryInfoRequest, RepositoryIssueLabelsRequest, RepositoryIssuesCountRequest, RepositoryIssuesRequest, - RepositoryRequest, }, model::authenticated::{AuthenticatedUser, Message, MessageHandler, NetworkMessage, State}, }; @@ -100,25 +99,25 @@ async fn repository_info( } async fn issues_count( - Message(request): Message, - State(connection_state): State, - user: Option, + Message(_request): Message, + State(_connection_state): State, + _user: Option, ) -> Result<(), RepositoryError> { unimplemented!(); } async fn issue_labels( - Message(request): Message, - State(connection_state): State, - user: Option, + Message(_request): Message, + State(_connection_state): State, + _user: Option, ) -> Result<(), RepositoryError> { unimplemented!(); } async fn issues( - Message(request): Message, - State(connection_state): State, - user: Option, + Message(_request): Message, + State(_connection_state): State, + _user: Option, ) -> Result<(), RepositoryError> { unimplemented!(); } diff --git a/src/connection/user.rs b/src/connection/user.rs index a6b0067..7d8f91c 100644 --- a/src/connection/user.rs +++ b/src/connection/user.rs @@ -17,6 +17,8 @@ pub async fn user_handle(message: &NetworkMessage, state: &ConnectionState) -> R Ok(()) } else if bio.handle_message(&message, state).await.is_ok() { Ok(()) + } else if repositories.handle_message(&message, state).await.is_ok() { + Ok(()) } else { Err(Error::from(HandlerUnhandled)) } diff --git a/src/connection/wrapper.rs b/src/connection/wrapper.rs index a78830a..8639f93 100644 --- a/src/connection/wrapper.rs +++ b/src/connection/wrapper.rs @@ -14,36 +14,30 @@ use tokio_tungstenite::{tungstenite::Message, WebSocketStream}; use crate::{ authentication::AuthenticationTokenGranter, - backend::{DiscoveryBackend, RepositoryBackend, UserBackend}, - connection::ConnectionError, - listener::Listeners, + backend::{RepositoryBackend, UserBackend}, model::{authenticated::NetworkMessage, instance::Instance}, }; use super::{ - authentication::authentication_handle, connection_worker, handshake::handshake_handle, + authentication::authentication_handle, handshake::handshake_handle, repository::repository_handle, user::user_handle, Connections, }; pub async fn connection_wrapper( - mut socket: WebSocketStream, - listeners: Arc>, + socket: WebSocketStream, connections: Arc>, repository_backend: Arc>, user_backend: Arc>, auth_granter: Arc>, - discovery_backend: Arc>, addr: SocketAddr, instance: impl ToOwned, ) { - let mut connection_state = ConnectionState { + let connection_state = ConnectionState { socket: Arc::new(Mutex::new(socket)), - listeners, connections, repository_backend, user_backend, auth_granter, - discovery_backend, addr, instance: instance.to_owned(), handshaked: Arc::new(AtomicBool::new(false)), @@ -62,7 +56,7 @@ pub async fn connection_wrapper( Message::Binary(payload) => payload, Message::Ping(_) => { let mut socket = connection_state.socket.lock().await; - socket.send(Message::Pong(vec![])).await; + let _ = socket.send(Message::Pong(vec![])).await; drop(socket); continue; } @@ -105,12 +99,10 @@ pub async fn connection_wrapper( #[derive(Clone)] pub struct ConnectionState { socket: Arc>>, - pub listeners: Arc>, pub connections: Arc>, pub repository_backend: Arc>, pub user_backend: Arc>, pub auth_granter: Arc>, - pub discovery_backend: Arc>, pub addr: SocketAddr, pub instance: Instance, pub handshaked: Arc, diff --git a/src/lib.rs b/src/lib.rs index bc3ddf5..4baf7fa 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,7 +6,6 @@ pub mod authentication; pub mod backend; pub mod connection; pub mod handshake; -pub mod listener; pub mod messages; pub mod model; diff --git a/src/listener.rs b/src/listener.rs deleted file mode 100644 index 4fd1954..0000000 --- a/src/listener.rs +++ /dev/null @@ -1,31 +0,0 @@ -use std::collections::HashMap; - -use tokio::sync::broadcast::{Receiver, Sender}; - -use crate::{ - messages::{repository::RepositoryMessage, MessageKind}, - model::{instance::Instance, repository::Repository, user::User}, -}; - -#[derive(Default)] -pub struct Listeners { - listeners: HashMap, Receiver)>, -} - -impl Listeners { - pub fn add( - &mut self, - _instance: Option, - _user: Option, - _repository: Option, - ) -> Receiver { - todo!() - } -} - -#[derive(Hash)] -pub struct ListenerTarget { - pub instance: Option, - pub user: Option, - pub repository: Option, -} diff --git a/src/main.rs b/src/main.rs index 4f84048..db7a852 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,15 +2,10 @@ use anyhow::Error; use connection::{Connections, RawConnection}; use giterated_daemon::{ authentication::AuthenticationTokenGranter, - backend::{ - discovery::GiteratedDiscoveryProtocol, git::GitBackend, user::UserAuth, DiscoveryBackend, - RepositoryBackend, UserBackend, - }, + backend::{git::GitBackend, user::UserAuth, RepositoryBackend, UserBackend}, connection::{self, wrapper::connection_wrapper}, - listener, model::instance::Instance, }; -use listener::Listeners; use sqlx::{postgres::PgConnectOptions, ConnectOptions, PgPool}; use std::{net::SocketAddr, str::FromStr, sync::Arc}; use tokio::{ @@ -30,7 +25,6 @@ async fn main() -> Result<(), Error> { tracing_subscriber::fmt::init(); let mut listener = TcpListener::bind("0.0.0.0:7270").await?; let connections: Arc> = Arc::default(); - let listeners: Arc> = Arc::default(); let config: Table = { let mut file = File::open("Giterated.toml").await?; let mut text = String::new(); @@ -72,11 +66,6 @@ async fn main() -> Result<(), Error> { token_granter.clone(), ))); - let discovery_backend: Arc> = - Arc::new(Mutex::new(GiteratedDiscoveryProtocol { - pool: db_pool.clone(), - })); - info!("Connected"); loop { @@ -111,12 +100,10 @@ async fn main() -> Result<(), Error> { let connection = RawConnection { task: tokio::spawn(connection_wrapper( connection, - listeners.clone(), connections.clone(), repository_backend.clone(), user_backend.clone(), token_granter.clone(), - discovery_backend.clone(), address, Instance::from_str("giterated.dev").unwrap(), )), diff --git a/src/messages/authentication.rs b/src/messages/authentication.rs index 0c560ae..bb02aa3 100644 --- a/src/messages/authentication.rs +++ b/src/messages/authentication.rs @@ -2,61 +2,11 @@ use serde::{Deserialize, Serialize}; use crate::model::authenticated::UserAuthenticationToken; -use super::InstanceAuthenticated; - -/// An authentication message. +/// An account registration request. /// -/// View request documentation, authentication, and authorization -/// details in the associated type, [`AuthenticationRequest`]. -#[derive(Clone, Serialize, Deserialize)] -pub enum AuthenticationMessage { - Request(AuthenticationRequest), - Response(AuthenticationResponse), -} - -#[derive(Clone, Serialize, Deserialize)] -pub enum AuthenticationRequest { - /// An account registration request. - /// - /// # Authentication - /// - Instance Authentication - /// - **ONLY ACCEPTED WHEN SAME-INSTANCE** - RegisterAccount(RegisterAccountRequest), - - /// An authentication token request. - /// - /// AKA Login Request - /// - /// # Authentication - /// - Instance Authentication - /// - Identifies the Instance to issue the token for - /// # Authorization - /// - Credentials ([`crate::backend::AuthBackend`]-based) - /// - Identifies the User account to issue a token for - /// - Decrypts user private key to issue to - AuthenticationToken(AuthenticationTokenRequest), - - /// An authentication token extension request. - /// - /// # Authentication - /// - Instance Authentication - /// - Identifies the Instance to issue the token for - /// - User Authentication - /// - Authenticates the validity of the token - /// # Authorization - /// - Token-based - /// - Validates authorization using token's authenticity - TokenExtension(TokenExtensionRequest), -} - -#[derive(Clone, Serialize, Deserialize)] -pub enum AuthenticationResponse { - RegisterAccount(RegisterAccountResponse), - AuthenticationToken(AuthenticationTokenResponse), - TokenExtension(TokenExtensionResponse), -} - -/// See [`AuthenticationRequest::RegisterAccount`]'s documentation. +/// # Authentication +/// - Instance Authentication +/// - **ONLY ACCEPTED WHEN SAME-INSTANCE** #[derive(Clone, Serialize, Deserialize)] pub struct RegisterAccountRequest { pub username: String, @@ -69,7 +19,17 @@ pub struct RegisterAccountResponse { pub token: String, } -/// See [`AuthenticationRequest::AuthenticationToken`]'s documentation. +/// An authentication token request. +/// +/// AKA Login Request +/// +/// # Authentication +/// - Instance Authentication +/// - Identifies the Instance to issue the token for +/// # Authorization +/// - Credentials ([`crate::backend::AuthBackend`]-based) +/// - Identifies the User account to issue a token for +/// - Decrypts user private key to issue to #[derive(Clone, Serialize, Deserialize)] pub struct AuthenticationTokenRequest { pub username: String, @@ -81,7 +41,16 @@ pub struct AuthenticationTokenResponse { pub token: String, } -/// See [`AuthenticationRequest::TokenExtension`]'s documentation. +/// An authentication token extension request. +/// +/// # Authentication +/// - Instance Authentication +/// - Identifies the Instance to issue the token for +/// - User Authentication +/// - Authenticates the validity of the token +/// # Authorization +/// - Token-based +/// - Validates authorization using token's authenticity #[derive(Clone, Serialize, Deserialize)] pub struct TokenExtensionRequest { pub token: UserAuthenticationToken, diff --git a/src/messages/discovery.rs b/src/messages/discovery.rs index 43534f4..3b4387d 100644 --- a/src/messages/discovery.rs +++ b/src/messages/discovery.rs @@ -3,20 +3,6 @@ use serde::{Deserialize, Serialize}; use crate::model::discovery::DiscoveryItem; -use super::InstanceAuthenticated; - -#[derive(Clone, Hash, PartialEq, Eq, Debug, Serialize, Deserialize)] -pub struct DiscoveryMessage { - pub message: InstanceAuthenticated, -} - -#[derive(Clone, Hash, PartialEq, Eq, Debug, Serialize, Deserialize)] -pub enum DiscoveryMessageKind { - Offer(DiscoveryOffer), - Request(DiscoveryRequest), - Discoveries(Discoveries), -} - #[derive(Clone, Hash, PartialEq, Eq, Debug, Serialize, Deserialize)] pub struct DiscoveryOffer { pub earliest: DateTime, diff --git a/src/messages/mod.rs b/src/messages/mod.rs index 1af76c2..b19d96e 100644 --- a/src/messages/mod.rs +++ b/src/messages/mod.rs @@ -1,25 +1,7 @@ -use anyhow::Error; -use jsonwebtoken::{decode, Algorithm, DecodingKey, TokenData, Validation}; -use rsa::{ - pkcs1::{DecodeRsaPrivateKey, DecodeRsaPublicKey}, - pss::{Signature, SigningKey, VerifyingKey}, - sha2::Sha256, - signature::{RandomizedSigner, SignatureEncoding, Verifier}, - RsaPrivateKey, RsaPublicKey, -}; use serde::{Deserialize, Serialize}; use std::fmt::Debug; -use crate::{ - authentication::UserTokenMetadata, - handshake::HandshakeMessage, - model::{instance::Instance, user::User}, -}; - -use self::{ - authentication::AuthenticationMessage, discovery::DiscoveryMessage, - repository::RepositoryMessage, user::UserMessage, -}; +use crate::model::user::User; pub mod authentication; pub mod discovery; @@ -27,16 +9,6 @@ pub mod issues; pub mod repository; pub mod user; -#[derive(Clone, Serialize, Deserialize)] -pub enum MessageKind { - Handshake(HandshakeMessage), - Repository(RepositoryMessage), - Authentication(AuthenticationMessage), - Discovery(DiscoveryMessage), - User(UserMessage), - Error(ErrorMessage), -} - #[derive(Clone, Debug, Serialize, Deserialize, thiserror::Error)] pub enum ErrorMessage { #[error("user {0} doesn't exist or isn't valid in this context")] @@ -44,262 +16,3 @@ pub enum ErrorMessage { #[error("internal error: shutdown")] Shutdown, } - -/// An authenticated message, where the instance is authenticating -/// a request it is making for itself. -#[derive(Serialize, Deserialize)] -pub struct InstanceAuthenticated { - message: T, - pub instance: Instance, - signature: Vec, -} - -impl PartialEq for InstanceAuthenticated -where - T: PartialEq + Serialize, -{ - fn eq(&self, other: &Self) -> bool { - self.message == other.message - && self.instance == other.instance - && self.signature == other.signature - } -} - -impl Eq for InstanceAuthenticated where T: Eq + Serialize {} - -impl std::hash::Hash for InstanceAuthenticated -where - T: std::hash::Hash + Serialize, -{ - fn hash(&self, state: &mut H) { - self.message.hash(state); - self.instance.hash(state); - self.signature.hash(state); - } -} - -impl Clone for InstanceAuthenticated -where - T: Clone + Serialize, -{ - fn clone(&self) -> Self { - Self { - message: self.message.clone(), - instance: self.instance.clone(), - signature: self.signature.clone(), - } - } -} - -impl Debug for InstanceAuthenticated -where - T: Debug + Serialize, -{ - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("Authenticated") - .field("message", &self.message) - .field("instance", &self.instance) - .field("signature", &self.signature) - .finish() - } -} - -impl InstanceAuthenticated { - pub fn new(message: T, instance: Instance, private_key: String) -> Result { - let mut rng = rand::thread_rng(); - - let private_key = RsaPrivateKey::from_pkcs1_pem(&private_key)?; - let signing_key = SigningKey::::new(private_key); - - let message_json = serde_json::to_vec(&message)?; - - let signature = signing_key.sign_with_rng(&mut rng, &message_json); - - Ok(Self { - message, - instance, - signature: signature.to_vec(), - }) - } - - pub async fn inner(&self) -> &T { - &self.message - } - - pub async fn validate(&self, instance: &Instance) -> Result<(), Error> { - let public_key = public_key(instance).await?; - let public_key = RsaPublicKey::from_pkcs1_pem(&public_key).unwrap(); - - let verifying_key: VerifyingKey = VerifyingKey::new(public_key); - - let message_json = serde_json::to_vec(&self.message).unwrap(); - - verifying_key - .verify( - &message_json, - &Signature::try_from(self.signature.as_ref()).unwrap(), - ) - .unwrap(); - - Ok(()) - } -} - -/// An authenticated message. -/// -/// Includes the message, with a digest generated with -/// our private key. -#[derive(Serialize, Deserialize)] -pub struct ValidatedUserAuthenticated { - #[serde(flatten)] - message: T, - pub(crate) user: User, -} - -impl Clone for ValidatedUserAuthenticated -where - T: Clone + Serialize, -{ - fn clone(&self) -> Self { - Self { - message: self.message.clone(), - user: self.user.clone(), - } - } -} - -impl Debug for ValidatedUserAuthenticated -where - T: Debug + Serialize, -{ - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("Authenticated") - .field("message", &self.message) - .field("user", &self.user) - .finish() - } -} - -impl ValidatedUserAuthenticated { - pub async fn inner(&self) -> &T { - &self.message - } - - pub async fn user(&self) -> &User { - &self.user - } -} - -/// An unvalidated authenticated message. -/// -/// Includes the message, with a digest generated with -/// our private key. -#[derive(Serialize, Deserialize)] -pub struct UnvalidatedUserAuthenticated { - #[serde(flatten)] - message: T, - token: String, - digest: Vec, -} - -impl Clone for UnvalidatedUserAuthenticated -where - T: Clone + Serialize, -{ - fn clone(&self) -> Self { - Self { - message: self.message.clone(), - token: self.token.clone(), - digest: self.digest.clone(), - } - } -} - -impl Debug for UnvalidatedUserAuthenticated -where - T: Debug + Serialize, -{ - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("Authenticated") - .field("message", &self.message) - .field("token", &self.token) - .field("digest", &self.digest) - .finish() - } -} - -impl UnvalidatedUserAuthenticated { - pub fn new(message: T, token: String, private_key: String) -> Result { - let mut rng = rand::thread_rng(); - - let private_key = RsaPrivateKey::from_pkcs1_pem(&private_key)?; - let signing_key = SigningKey::::new(private_key); - - let message_json = serde_json::to_vec(&message)?; - - let signature = signing_key.sign_with_rng(&mut rng, &message_json); - - Ok(Self { - message, - token, - digest: signature.to_vec(), - }) - } - - pub async fn inner(&self) -> &T { - &self.message - } - - pub async fn validate(self) -> Result, Error> { - let instance = { - let mut validation = Validation::new(Algorithm::RS256); - validation.insecure_disable_signature_validation(); - - info!("Value: {:?}", self.token); - - let value: TokenData = - decode(&self.token, &DecodingKey::from_secret(b"test"), &validation).unwrap(); - - value.claims.generated_for.clone() - }; - - let public_key_raw = public_key(&instance).await?; - let public_key = RsaPublicKey::from_pkcs1_pem(&public_key_raw).unwrap(); - - let verifying_key: VerifyingKey = VerifyingKey::new(public_key); - - let message_json = serde_json::to_vec(&self.message).unwrap(); - - verifying_key - .verify( - &message_json, - &Signature::try_from(self.digest.as_ref()).unwrap(), - ) - .unwrap(); - - let verification_key = DecodingKey::from_rsa_pem(public_key_raw.as_bytes()).unwrap(); - - let data: TokenData = decode( - &self.token, - &verification_key, - &Validation::new(Algorithm::RS256), - ) - .unwrap(); - - assert_eq!(data.claims.generated_for, instance); - - Ok(ValidatedUserAuthenticated { - message: self.message, - user: data.claims.user, - }) - } -} - -async fn public_key(instance: &Instance) -> Result { - let key = reqwest::get(format!("https://{}/.giterated/pubkey.pem", instance.url)) - .await? - .text() - .await?; - - Ok(key) -} diff --git a/src/messages/repository.rs b/src/messages/repository.rs index fe7d5cd..82fd3bc 100644 --- a/src/messages/repository.rs +++ b/src/messages/repository.rs @@ -2,112 +2,23 @@ use serde::{Deserialize, Serialize}; use crate::model::repository::RepositoryVisibility; use crate::model::{ - repository::{Commit, Repository, RepositoryTreeEntry, RepositoryView}, + repository::{Commit, Repository, RepositoryTreeEntry}, user::User, }; -use super::UnvalidatedUserAuthenticated; - -/// A repository message. +/// A request to create a repository. /// -/// View request documentation, authentication, and authorization -/// details in the associated type, [`RepositoryRequest`]. -#[derive(Clone, Serialize, Deserialize)] -pub struct RepositoryMessage { - pub target: Repository, - pub command: RepositoryMessageKind, -} - -#[derive(Clone, Serialize, Deserialize)] -pub enum RepositoryMessageKind { - Request(RepositoryRequest), - Response(RepositoryResponse), -} - -#[derive(Clone, Serialize, Deserialize)] -pub enum RepositoryRequest { - /// A request to create a repository. - /// - /// # Authentication - /// - Instance Authentication - /// - Used to validate User token `issued_for` - /// - User Authentication - /// - Used to source owning user - /// - Used to authorize user token against user's instance - /// # Authorization - /// - Instance Authorization - /// - Used to authorize action using User token requiring a correct `issued_for` and valid issuance from user's instance - /// - User Authorization - /// - Potential User permissions checks - CreateRepository(UnvalidatedUserAuthenticated), - - /// A request to inspect the tree of a repository. - /// - /// # Authentication - /// - Instance Authentication - /// - Validate request against the `issued_for` public key - /// - Validate User token against the user's instance's public key - /// # Authorization - /// - User Authorization - /// - Potential User permissions checks - RepositoryFileInspect(UnvalidatedUserAuthenticated), - - /// A request to get a repository's information. - /// - /// # Authentication - /// - Instance Authentication - /// - Validate request against the `issued_for` public key - /// - Validate User token against the user's instance's public key - /// # Authorization - /// - User Authorization - /// - Potential User permissions checks - RepositoryInfo(UnvalidatedUserAuthenticated), - - /// A request to get a repository's issues count. - /// - /// # Authentication - /// - Instance Authentication - /// - Validate request against the `issued_for` public key - /// - Validate User token against the user's instance's public key - /// # Authorization - /// - User Authorization - /// - Potential User permissions checks - IssuesCount(UnvalidatedUserAuthenticated), - - /// A request to get a repository's issue labels. - /// - /// # Authentication - /// - Instance Authentication - /// - Validate request against the `issued_for` public key - /// - Validate User token against the user's instance's public key - /// # Authorization - /// - User Authorization - /// - Potential User permissions checks - IssueLabels(UnvalidatedUserAuthenticated), - - /// A request to get a repository's issues. - /// - /// # Authentication - /// - Instance Authentication - /// - Validate request against the `issued_for` public key - /// - Validate User token against the user's instance's public key - /// # Authorization - /// - User Authorization - /// - Potential User permissions checks - Issues(UnvalidatedUserAuthenticated), -} - -#[derive(Clone, Serialize, Deserialize)] -pub enum RepositoryResponse { - CreateRepository(CreateRepositoryResponse), - RepositoryFileInspection(RepositoryFileInspectionResponse), - RepositoryInfo(RepositoryView), - IssuesCount(RepositoryIssuesCountResponse), - IssueLabels(RepositoryIssueLabelsResponse), - Issues(RepositoryIssuesResponse), -} - -/// See [`RepositoryRequest::CreateRepository`]'s documentation. +/// # Authentication +/// - Instance Authentication +/// - Used to validate User token `issued_for` +/// - User Authentication +/// - Used to source owning user +/// - Used to authorize user token against user's instance +/// # Authorization +/// - Instance Authorization +/// - Used to authorize action using User token requiring a correct `issued_for` and valid issuance from user's instance +/// - User Authorization +/// - Potential User permissions checks #[derive(Clone, Serialize, Deserialize)] pub struct CreateRepositoryRequest { pub name: String, @@ -123,7 +34,15 @@ pub enum CreateRepositoryResponse { Failed, } -/// See [`RepositoryRequest::RepositoryFileInspect`]'s documentation. +/// A request to inspect the tree of a repository. +/// +/// # Authentication +/// - Instance Authentication +/// - Validate request against the `issued_for` public key +/// - Validate User token against the user's instance's public key +/// # Authorization +/// - User Authorization +/// - Potential User permissions checks #[derive(Clone, Serialize, Deserialize)] pub struct RepositoryFileInspectRequest { pub path: RepositoryTreeEntry, @@ -143,7 +62,15 @@ pub enum RepositoryFileInspectionResponse { }, } -/// See [`RepositoryRequest::IssuesCount`]'s documentation. +/// A request to get a repository's information. +/// +/// # Authentication +/// - Instance Authentication +/// - Validate request against the `issued_for` public key +/// - Validate User token against the user's instance's public key +/// # Authorization +/// - User Authorization +/// - Potential User permissions checks #[derive(Clone, Serialize, Deserialize)] pub struct RepositoryIssuesCountRequest; @@ -152,7 +79,15 @@ pub struct RepositoryIssuesCountResponse { pub count: u64, } -/// See [`RepositoryRequest::IssueLabels`]'s documentation. +/// A request to get a repository's issues count. +/// +/// # Authentication +/// - Instance Authentication +/// - Validate request against the `issued_for` public key +/// - Validate User token against the user's instance's public key +/// # Authorization +/// - User Authorization +/// - Potential User permissions checks #[derive(Clone, Serialize, Deserialize)] pub struct RepositoryIssueLabelsRequest; @@ -167,7 +102,15 @@ pub struct IssueLabel { pub color: String, } -/// See [`RepositoryRequest::Issues`]'s documentation. +/// A request to get a repository's issue labels. +/// +/// # Authentication +/// - Instance Authentication +/// - Validate request against the `issued_for` public key +/// - Validate User token against the user's instance's public key +/// # Authorization +/// - User Authorization +/// - Potential User permissions checks #[derive(Clone, Serialize, Deserialize)] pub struct RepositoryIssuesRequest; @@ -176,6 +119,15 @@ pub struct RepositoryIssuesResponse { pub issues: Vec, } +/// A request to get a repository's issues. +/// +/// # Authentication +/// - Instance Authentication +/// - Validate request against the `issued_for` public key +/// - Validate User token against the user's instance's public key +/// # Authorization +/// - User Authorization +/// - Potential User permissions checks #[derive(Clone, Serialize, Deserialize)] pub struct RepositoryIssue { pub author: User, diff --git a/src/messages/user.rs b/src/messages/user.rs index 77cc030..6fe1431 100644 --- a/src/messages/user.rs +++ b/src/messages/user.rs @@ -1,38 +1,6 @@ use serde::{Deserialize, Serialize}; -use crate::model::{ - instance::Instance, - repository::{Repository, RepositorySummary}, - user::User, -}; - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct UserMessage { - pub instance: Instance, - pub message: UserMessageKind, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub enum UserMessageKind { - Request(UserMessageRequest), - Response(UserMessageResponse), -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub enum UserMessageRequest { - DisplayName(UserDisplayNameRequest), - DisplayImage(UserDisplayImageRequest), - Bio(UserBioRequest), - Repositories(UserRepositoriesRequest), -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub enum UserMessageResponse { - DisplayName(UserDisplayNameResponse), - DisplayImage(UserDisplayImageResponse), - Bio(UserBioResponse), - Repositories(UserRepositoriesResponse), -} +use crate::model::{repository::RepositorySummary, user::User}; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct UserDisplayNameRequest { diff --git a/src/model/authenticated.rs b/src/model/authenticated.rs index 8775949..adc78cc 100644 --- a/src/model/authenticated.rs +++ b/src/model/authenticated.rs @@ -1,14 +1,12 @@ -use std::{any::type_name, ops::Deref, pin::Pin, str::FromStr}; +use std::{any::type_name, collections::HashMap, ops::Deref}; use anyhow::Error; -use futures_util::{future::BoxFuture, Future, FutureExt}; +use futures_util::Future; use jsonwebtoken::{decode, Algorithm, DecodingKey, TokenData, Validation}; -use rsa::{pkcs1::DecodeRsaPublicKey, RsaPublicKey}; use serde::{de::DeserializeOwned, Deserialize, Serialize}; +use serde_json::Value; -use crate::{ - authentication::UserTokenMetadata, connection::wrapper::ConnectionState, messages::MessageKind, -}; +use crate::{authentication::UserTokenMetadata, connection::wrapper::ConnectionState}; use super::{instance::Instance, user::User}; @@ -88,7 +86,7 @@ pub struct UserAuthenticator { } impl AuthenticationSourceProvider for UserAuthenticator { - fn authenticate(self, payload: &Vec) -> AuthenticationSource { + fn authenticate(self, _payload: &Vec) -> AuthenticationSource { AuthenticationSource::User { user: self.user, token: self.token, @@ -103,7 +101,7 @@ pub struct InstanceAuthenticator<'a> { } impl AuthenticationSourceProvider for InstanceAuthenticator<'_> { - fn authenticate(self, payload: &Vec) -> AuthenticationSource { + fn authenticate(self, _payload: &Vec) -> AuthenticationSource { todo!() } } @@ -188,7 +186,7 @@ impl FromMessage for AuthenticatedUser { network_message: &NetworkMessage, state: &ConnectionState, ) -> Result { - let message: Authenticated = + let message: Authenticated> = serde_json::from_slice(&network_message).map_err(|e| Error::from(e))?; let (auth_user, auth_token) = message @@ -230,18 +228,8 @@ impl FromMessage for AuthenticatedUser { #[async_trait::async_trait] impl FromMessage for AuthenticatedInstance { async fn from_message( - message: &NetworkMessage, - state: &ConnectionState, - ) -> Result { - todo!() - } -} - -#[async_trait::async_trait] -impl FromMessage for MessageKind { - async fn from_message( - message: &NetworkMessage, - state: &ConnectionState, + _message: &NetworkMessage, + _state: &ConnectionState, ) -> Result { todo!() }