Add comprehensive documentation and unit tests

Documentation:
- Add detailed README files for all services (auth, character, database, launcher, packet, utils, world)
- Create API documentation for the database service with detailed endpoint specifications
- Document database schema and relationships
- Add service architecture overviews and configuration instructions

Unit Tests:
- Implement comprehensive test suite for database repositories (user, character, session)
- Add gRPC service tests for database interactions
- Create tests for packet service components (bufferpool, connection, packets)
- Add utility service tests (health check, logging, load balancer, redis cache, service discovery)
- Implement auth service user tests
- Add character service tests

Code Structure:
- Reorganize test files into a more consistent structure
- Create a dedicated tests crate for integration testing
- Add test helpers and mock implementations for easier testing
This commit is contained in:
2025-04-09 13:29:38 -04:00
parent d47d5f44b1
commit a8755bd3de
85 changed files with 4218 additions and 764 deletions

94
auth-service/README.md Normal file
View File

@@ -0,0 +1,94 @@
# Authentication Service
The Authentication Service is responsible for user authentication, session validation, and account management in the MMORPG server architecture.
## Overview
The Authentication Service provides gRPC endpoints for:
- User login and logout
- Session validation and refresh
It communicates with the external database service to verify user credentials and manage sessions.
## Architecture
The service is built using the following components:
- **gRPC Server**: Exposes authentication endpoints
- **Database Client**: Communicates with the database service for user data
- **Session Client**: Manages user sessions
- **Password Hashing**: Securely handles password verification
> **Note**: User registration and password reset functionality are handled by an external system.
## Service Endpoints
The Authentication Service exposes the following gRPC endpoints:
### Login
Authenticates a user and creates a new session.
```protobuf
rpc Login(LoginRequest) returns (LoginResponse);
```
### Logout
Terminates a user session.
```protobuf
rpc Logout(LogoutRequest) returns (Empty);
```
### ValidateToken
Validates a JWT token.
```protobuf
rpc ValidateToken(ValidateTokenRequest) returns (ValidateTokenResponse);
```
### ValidateSession
Validates a session ID.
```protobuf
rpc ValidateSession(ValidateSessionRequest) returns (ValidateSessionResponse);
```
### RefreshSession
Refreshes an existing session.
```protobuf
rpc RefreshSession(ValidateSessionRequest) returns (RefreshSessionResponse);
```
## Configuration
The service can be configured using environment variables:
- `LISTEN_ADDR`: The address to listen on (default: "0.0.0.0")
- `SERVICE_PORT`: The port to listen on (default: "50051")
- `LOG_LEVEL`: Logging level (default: "info")
## Running the Service
### Local Development
```bash
cargo run
```
### Docker
```bash
docker build -t auth-service .
docker run -p 50051:50051 auth-service
```
## Integration with External Systems
The Authentication Service integrates with:
- **Database Service**: For user data storage and retrieval
- **Session Service**: For session management
- **External Auth System**: The service is designed to work with an external authentication system (better-auth) that manages the database schema and user accounts

View File

@@ -12,10 +12,7 @@ fn main() {
.build_server(false) // Generate gRPC client code
.compile_well_known_types(true)
.compile_protos(
&[
"../proto/user_db_api.proto",
"../proto/session_db_api.proto",
],
&["../proto/user_db_api.proto", "../proto/session_db_api.proto"],
&["../proto"],
)
.unwrap_or_else(|e| panic!("Failed to compile protos {:?}", e));

View File

@@ -1,56 +1,23 @@
use crate::database::{user_service_client::UserServiceClient, GetUserByEmailRequest, GetUserByUsernameRequest, GetUserRequest, GetUserResponse};
use crate::database::{
user_service_client::UserServiceClient, GetUserByEmailRequest, GetUserByUsernameRequest, GetUserRequest,
GetUserResponse,
};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use std::error::Error;
use tonic::transport::Channel;
#[async_trait]
pub trait DatabaseClientTrait: Sized {
async fn connect(endpoint: &str) -> Result<Self, Box<dyn std::error::Error>>;
async fn get_user_by_userid(
&mut self,
user_id: i32,
) -> Result<GetUserResponse, Box<dyn std::error::Error>>;
async fn get_user_by_username(
&mut self,
user_id: &str,
) -> Result<GetUserResponse, Box<dyn std::error::Error>>;
async fn get_user_by_email(
&mut self,
email: &str,
) -> Result<GetUserResponse, Box<dyn std::error::Error>>;
async fn store_password_reset(
&mut self,
email: &str,
reset_token: &str,
expires_at: DateTime<Utc>,
) -> Result<(), Box<dyn std::error::Error>>;
async fn get_password_reset(
&self,
reset_token: &str,
) -> Result<Option<PasswordReset>, Box<dyn std::error::Error>>;
async fn delete_password_reset(
&self,
reset_token: &str,
) -> Result<(), Box<dyn std::error::Error>>;
async fn update_user_password(
&self,
email: &str,
hashed_password: &str,
) -> Result<(), Box<dyn std::error::Error>>;
async fn get_user_by_userid(&mut self, user_id: i32) -> Result<GetUserResponse, Box<dyn std::error::Error>>;
async fn get_user_by_username(&mut self, user_id: &str) -> Result<GetUserResponse, Box<dyn std::error::Error>>;
async fn get_user_by_email(&mut self, email: &str) -> Result<GetUserResponse, Box<dyn std::error::Error>>;
}
#[derive(Clone)]
pub struct DatabaseClient {
client: UserServiceClient<Channel>,
}
#[derive(Debug)]
pub struct PasswordReset {
pub email: String,
pub reset_token: String,
pub expires_at: DateTime<Utc>,
}
#[async_trait]
impl DatabaseClientTrait for DatabaseClient {
async fn connect(endpoint: &str) -> Result<Self, Box<dyn std::error::Error>> {
@@ -58,19 +25,13 @@ impl DatabaseClientTrait for DatabaseClient {
Ok(Self { client })
}
async fn get_user_by_userid(
&mut self,
user_id: i32,
) -> Result<GetUserResponse, Box<dyn std::error::Error>> {
async fn get_user_by_userid(&mut self, user_id: i32) -> Result<GetUserResponse, Box<dyn std::error::Error>> {
let request = tonic::Request::new(GetUserRequest { user_id });
let response = self.client.get_user(request).await?;
Ok(response.into_inner())
}
async fn get_user_by_username(
&mut self,
username: &str,
) -> Result<GetUserResponse, Box<dyn std::error::Error>> {
async fn get_user_by_username(&mut self, username: &str) -> Result<GetUserResponse, Box<dyn std::error::Error>> {
let request = tonic::Request::new(GetUserByUsernameRequest {
username: username.to_string(),
});
@@ -85,35 +46,4 @@ impl DatabaseClientTrait for DatabaseClient {
let response = self.client.get_user_by_email(request).await?;
Ok(response.into_inner())
}
async fn store_password_reset(
&mut self,
_email: &str,
_reset_token: &str,
_expires_at: DateTime<Utc>,
) -> Result<(), Box<dyn Error>> {
Ok(())
}
async fn get_password_reset(
&self,
_reset_token: &str,
) -> Result<Option<PasswordReset>, Box<dyn std::error::Error>> {
todo!()
}
async fn delete_password_reset(
&self,
_reset_token: &str,
) -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
async fn update_user_password(
&self,
_email: &str,
_hashed_password: &str,
) -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
}

View File

@@ -1,16 +1,12 @@
use crate::auth::auth_service_server::AuthService;
use crate::auth::{
LoginRequest, LoginResponse, LogoutRequest, PasswordResetRequest, PasswordResetResponse,
RefreshSessionResponse, RegisterRequest, RegisterResponse, ResetPasswordRequest,
ResetPasswordResponse, ValidateSessionRequest, ValidateSessionResponse, ValidateTokenRequest, ValidateTokenResponse,
LoginRequest, LoginResponse, LogoutRequest, RefreshSessionResponse, ValidateSessionRequest,
ValidateSessionResponse, ValidateTokenRequest, ValidateTokenResponse,
};
use crate::common::Empty;
use crate::database_client::{DatabaseClient, DatabaseClientTrait};
use crate::database_client::{DatabaseClient};
use crate::session::session_service_client::SessionServiceClient;
use crate::session::{GetSessionRequest, RefreshSessionRequest};
use crate::users::{hash_password, verify_user};
use chrono::{Duration, Utc};
use rand::Rng;
use std::sync::Arc;
use tonic::{Request, Response, Status};
use tracing::{debug, error, info, warn};
@@ -22,22 +18,19 @@ pub struct MyAuthService {
#[tonic::async_trait]
impl AuthService for MyAuthService {
async fn login(
&self,
request: Request<LoginRequest>,
) -> Result<Response<LoginResponse>, Status> {
async fn login(&self, _request: Request<LoginRequest>) -> Result<Response<LoginResponse>, Status> {
Err(Status::unimplemented("login not implemented due to changes"))
}
async fn logout(&self, request: Request<LogoutRequest>) -> Result<Response<Empty>, Status> {
let req = request.into_inner();
let _req = request.into_inner();
Ok(Response::new(Empty {}))
}
async fn validate_token(
&self,
request: Request<ValidateTokenRequest>,
_request: Request<ValidateTokenRequest>,
) -> Result<Response<ValidateTokenResponse>, Status> {
Ok(Response::new(ValidateTokenResponse {
valid: false,
@@ -51,20 +44,32 @@ impl AuthService for MyAuthService {
request: Request<ValidateSessionRequest>,
) -> Result<Response<ValidateSessionResponse>, Status> {
let req = request.into_inner();
let response = self.session_client.as_ref().clone()
let response = self
.session_client
.as_ref()
.clone()
.get_session(GetSessionRequest {
session_id: req.session_id,
}).await;
})
.await;
match response {
Ok(res) => {
let res = res.into_inner();
debug!("Session valid: {:?}", res);
Ok(Response::new(ValidateSessionResponse { valid: true, session_id: res.session_id.to_string(), user_id: res.user_id.to_string() }))
Ok(Response::new(ValidateSessionResponse {
valid: true,
session_id: res.session_id.to_string(),
user_id: res.user_id.to_string(),
}))
}
Err(error) => {
debug!("Session invalid or not found: {error}");
Ok(Response::new(ValidateSessionResponse { valid: false, session_id: "".to_string(), user_id: "".to_string() }))
Ok(Response::new(ValidateSessionResponse {
valid: false,
session_id: "".to_string(),
user_id: "".to_string(),
}))
}
}
}
@@ -95,126 +100,4 @@ impl AuthService for MyAuthService {
}
}
}
async fn register(
&self,
request: Request<RegisterRequest>,
) -> Result<Response<RegisterResponse>, Status> {
// let req = request.into_inner();
//
// // Hash the password
// let hashed_password = hash_password(&req.password);
//
// // Create user in the database
// let result = self
// .db_client
// .as_ref()
// .clone()
// .create_user(&req.username, &req.email, &hashed_password)
// .await;
//
// match result {
// Ok(user) => Ok(Response::new(RegisterResponse {
// user_id: user.user_id,
// message: "User registered successfully".into(),
// })),
// Err(e) => {
// error!("Failed to register user: {:?}", e);
// Err(Status::internal("Failed to register user"))
// }
// }
Err(Status::unimplemented("register not implemented"))
}
async fn request_password_reset(
&self,
request: Request<PasswordResetRequest>,
) -> Result<Response<PasswordResetResponse>, Status> {
let email = request.into_inner().email;
let user = self
.db_client
.as_ref()
.clone()
.get_user_by_email(&email)
.await;
// Check if the email exists
if user.ok().is_some() {
// Generate a reset token
let reset_token: String = rand::thread_rng()
.sample_iter(&rand::distributions::Alphanumeric)
.take(32)
.map(char::from)
.collect();
// Set token expiration (e.g., 1 hour)
let expires_at = Utc::now() + Duration::hours(1);
// Store the reset token in the database
self.db_client
.as_ref()
.clone()
.store_password_reset(&email, &reset_token, expires_at)
.await
.map_err(|e| Status::internal(format!("Database error: {}", e)))?;
// Send the reset email
// send_email(&email, "Password Reset Request", &format!(
// "Click the link to reset your password: https://azgstudio.com/reset?token={}",
// reset_token
// ))
// .map_err(|e| Status::internal(format!("Email error: {}", e)))?;
Ok(Response::new(PasswordResetResponse {
message: "Password reset email sent".to_string(),
}))
} else {
// Respond with a generic message to avoid information leaks
Ok(Response::new(PasswordResetResponse {
message: "If the email exists, a reset link has been sent.".to_string(),
}))
}
}
async fn reset_password(
&self,
request: Request<ResetPasswordRequest>,
) -> Result<Response<ResetPasswordResponse>, Status> {
let req = request.into_inner();
// Validate the reset token
if let Some(password_reset) = self
.db_client
.clone()
.get_password_reset(&req.reset_token)
.await
.map_err(|e| Status::internal(format!("Database error: {}", e)))?
{
if password_reset.expires_at < Utc::now() {
return Err(Status::unauthenticated("Token expired"));
}
// Hash the new password
let hashed_password = hash_password(&req.new_password);
// Update the user's password
self.db_client
.update_user_password(&password_reset.email, &hashed_password)
.await
.map_err(|e| Status::internal(format!("Database error: {}", e)))?;
// Delete the reset token
self.db_client
.delete_password_reset(&req.reset_token)
.await
.map_err(|e| Status::internal(format!("Database error: {}", e)))?;
Ok(Response::new(ResetPasswordResponse {
message: "Password successfully reset".to_string(),
}))
} else {
Err(Status::unauthenticated("Invalid reset token"))
}
}
}

View File

@@ -8,9 +8,8 @@ use std::env;
use std::sync::Arc;
use tonic::transport::Server;
use tracing::info;
use tracing_subscriber::{fmt, EnvFilter};
use utils::logging;
use utils::service_discovery::{get_kube_service_endpoints_by_dns};
use utils::service_discovery::get_kube_service_endpoints_by_dns;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
@@ -19,11 +18,17 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let app_name = env!("CARGO_PKG_NAME");
logging::setup_logging(app_name, &["auth_service"]);
// Set the gRPC server address
let addr = env::var("LISTEN_ADDR").unwrap_or_else(|_| "0.0.0.0".to_string());
let port = env::var("SERVICE_PORT").unwrap_or_else(|_| "50051".to_string());
let db_url = format!("http://{}",get_kube_service_endpoints_by_dns("database-service","tcp","database-service").await?.get(0).unwrap());
let db_url = format!(
"http://{}",
get_kube_service_endpoints_by_dns("database-service", "tcp", "database-service")
.await?
.get(0)
.unwrap()
);
let db_client = Arc::new(DatabaseClient::connect(&db_url).await?);
let session_client = Arc::new(SessionServiceClient::connect(db_url).await?);
@@ -32,7 +37,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let address = full_addr.parse().expect("Invalid address");
let auth_service = MyAuthService {
db_client,
session_client
session_client,
};
let (mut health_reporter, health_service) = tonic_health::server::health_reporter();

View File

@@ -1,7 +1,6 @@
use crate::database::GetUserResponse;
use crate::database_client::{DatabaseClientTrait, PasswordReset};
use crate::database_client::DatabaseClientTrait;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use mockall::{mock, predicate::*};
use std::error::Error;
@@ -15,10 +14,6 @@ mock! {
async fn get_user_by_userid(&mut self, user_id: i32) -> Result<GetUserResponse, Box<dyn std::error::Error>>;
async fn get_user_by_username(&mut self, user_id: &str) -> Result<GetUserResponse, Box<dyn std::error::Error>>;
async fn get_user_by_email(&mut self, email: &str) -> Result<GetUserResponse, Box<dyn Error>>;
async fn store_password_reset(&mut self, email: &str, reset_token: &str, expires_at: DateTime<Utc>) -> Result<(), Box<dyn Error>>;
async fn get_password_reset(&self, reset_token: &str) -> Result<Option<PasswordReset>, Box<dyn Error>>;
async fn delete_password_reset(&self, reset_token: &str) -> Result<(), Box<dyn Error>>;
async fn update_user_password(&self, email: &str, hashed_password: &str) -> Result<(), Box<dyn Error>>;
}
}

View File

@@ -1,16 +1,15 @@
use crate::session::{session_service_client::SessionServiceClient, GetSessionRequest, GetSessionResponse, RefreshSessionRequest, RefreshSessionResponse};
use crate::session::{
session_service_client::SessionServiceClient, GetSessionRequest, GetSessionResponse, RefreshSessionRequest,
RefreshSessionResponse,
};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use std::error::Error;
use tonic::transport::Channel;
#[async_trait]
pub trait SessionClientTrait: Sized {
async fn connect(endpoint: &str) -> Result<Self, Box<dyn std::error::Error>>;
async fn get_session(
&mut self,
session_id: String,
) -> Result<GetSessionResponse, Box<dyn std::error::Error>>;
async fn get_session(&mut self, session_id: String) -> Result<GetSessionResponse, Box<dyn std::error::Error>>;
async fn refresh_session(
&mut self,
session_id: String,
@@ -27,18 +26,14 @@ impl SessionClientTrait for SessionClient {
let client = SessionServiceClient::connect(endpoint.to_string()).await?;
Ok(Self { client })
}
async fn get_session(&mut self, session_id: String) -> Result<GetSessionResponse, Box<dyn Error>> {
let request = tonic::Request::new(GetSessionRequest {
session_id,
});
let request = tonic::Request::new(GetSessionRequest { session_id });
let response = self.client.get_session(request).await?;
Ok(response.into_inner())
}
async fn refresh_session(&mut self, session_id: String) -> Result<RefreshSessionResponse, Box<dyn Error>> {
let request = tonic::Request::new(RefreshSessionRequest {
session_id,
});
let request = tonic::Request::new(RefreshSessionRequest { session_id });
let response = self.client.refresh_session(request).await?;
Ok(response.into_inner())
}

View File

@@ -9,10 +9,7 @@ use argon2::{
pub fn hash_password(password: &str) -> String {
let salt = SaltString::generate(&mut OsRng);
let argon2 = Argon2::default();
argon2
.hash_password(password.as_ref(), &salt)
.unwrap()
.to_string()
argon2.hash_password(password.as_ref(), &salt).unwrap().to_string()
}
pub fn verify_password(password: &str, hash: &str) -> bool {

View File

@@ -1,65 +0,0 @@
#[cfg(test)]
mod tests {
use dotenv::dotenv;
// use auth_service::mocks::database_client_mock::MockDatabaseClient;
#[tokio::test]
async fn test_login() {
// dotenv().ok();
// let mut db_client = MockDatabaseClient::new();
//
// db_client
// .expect_get_user_by_username()
// .with(mockall::predicate::eq("test"))
// .returning(|user_id| {
// Ok(GetUserResponse {
// user_id: 1,
// username: "test".to_string(),
// email: "test@test.com".to_string(),
// hashed_password: "test".to_string(),
// })
// });
//
//
// let auth_service = MyAuthService {
// db_client,
// };
//
// // Create a test LoginRequest
// let request = Request::new(LoginRequest {
// username: "test".into(),
// password: "test".into(),
// });
//
// // Call the login method
// let response = auth_service.login(request).await.unwrap().into_inner();
//
// // Verify the response
// assert!(!response.token.is_empty());
// assert_eq!(response.user_id, "1"); // Replace with the expected user ID
}
#[tokio::test]
async fn test_validate_token() {
dotenv().ok();
// let addr = std::env::var("DATABASE_SERVICE_ADDR").unwrap_or_else(|_| "127.0.0.1:50052".to_string());
// let db_client = DatabaseClient::connect(&addr).await.unwrap();
//
// let auth_service = MyAuthService {
// db_client,
// };
//
// // Generate a token for testing
// let token = jwt::generate_token("123", Vec::from(["".to_string()])).unwrap();
//
// // Create a ValidateTokenRequest
// let request = Request::new(ValidateTokenRequest { token });
//
// // Call the validate_token method
// let response = auth_service.validate_token(request).await.unwrap().into_inner();
//
// // Verify the response
// assert!(response.valid);
// assert_eq!(response.user_id, "123");
}
}