-
Notifications
You must be signed in to change notification settings - Fork 1
Implement JWT authentication, RBAC, and audit logging for admin console #104
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,204 @@ | ||
| //! Authentication API endpoints | ||
|
|
||
| use axum::{ | ||
| extract::State, | ||
| http::StatusCode, | ||
| Json, | ||
| }; | ||
| use serde::{Deserialize, Serialize}; | ||
| use std::sync::Arc; | ||
|
|
||
| use crate::{AppState, auth::{AuthUser, LoginRequest, RefreshRequest, Role}}; | ||
|
|
||
| /// Login endpoint | ||
| pub async fn login( | ||
| State(state): State<Arc<AppState>>, | ||
| Json(req): Json<LoginRequest>, | ||
| ) -> Result<Json<crate::auth::AuthResponse>, crate::auth::AuthError> { | ||
| let result = state.auth.login(req.clone()); | ||
|
|
||
| // Log authentication attempt | ||
| match &result { | ||
| Ok(response) => { | ||
| state.audit.log_success( | ||
| response.user.id.clone(), | ||
| response.user.username.clone(), | ||
| "login".to_string(), | ||
| "auth".to_string(), | ||
| None, | ||
| ); | ||
| } | ||
| Err(_) => { | ||
| state.audit.log_failure( | ||
| "unknown".to_string(), | ||
| req.username.clone(), | ||
| "login".to_string(), | ||
| "auth".to_string(), | ||
| "Invalid credentials".to_string(), | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| result.map(Json) | ||
| } | ||
|
|
||
| /// Refresh token endpoint | ||
| pub async fn refresh( | ||
| State(state): State<Arc<AppState>>, | ||
| Json(req): Json<RefreshRequest>, | ||
| ) -> Result<Json<crate::auth::AuthResponse>, crate::auth::AuthError> { | ||
| let result = state.auth.refresh(req); | ||
|
|
||
| // Log token refresh | ||
| if let Ok(response) = &result { | ||
| state.audit.log_success( | ||
| response.user.id.clone(), | ||
| response.user.username.clone(), | ||
| "refresh_token".to_string(), | ||
| "auth".to_string(), | ||
| None, | ||
| ); | ||
| } | ||
|
|
||
| result.map(Json) | ||
| } | ||
|
|
||
| /// Logout endpoint (revokes token) | ||
| pub async fn logout( | ||
| user: AuthUser, | ||
| State(state): State<Arc<AppState>>, | ||
| req: axum::extract::Request, | ||
| ) -> Result<Json<LogoutResponse>, StatusCode> { | ||
| // Extract token from header | ||
| if let Some(auth_header) = req.headers().get(axum::http::header::AUTHORIZATION) { | ||
| if let Ok(auth_str) = auth_header.to_str() { | ||
| if let Some(token) = auth_str.strip_prefix("Bearer ") { | ||
| state.auth.revoke_token(token.to_string()); | ||
|
|
||
| state.audit.log_success( | ||
| user.claims.sub.clone(), | ||
| user.claims.username.clone(), | ||
| "logout".to_string(), | ||
| "auth".to_string(), | ||
| None, | ||
| ); | ||
|
|
||
| return Ok(Json(LogoutResponse { | ||
| message: "Logged out successfully".to_string(), | ||
| })); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| Err(StatusCode::BAD_REQUEST) | ||
| } | ||
|
|
||
| #[derive(Serialize)] | ||
| pub struct LogoutResponse { | ||
| pub message: String, | ||
| } | ||
|
|
||
| /// Create user endpoint (admin only) | ||
| #[derive(Deserialize)] | ||
| pub struct CreateUserRequest { | ||
| pub username: String, | ||
| pub password: String, | ||
| pub role: Role, | ||
| } | ||
|
|
||
| #[derive(Serialize)] | ||
| pub struct CreateUserResponse { | ||
| pub id: String, | ||
| pub username: String, | ||
| pub role: Role, | ||
| } | ||
|
|
||
| pub async fn create_user( | ||
| user: AuthUser, | ||
| State(state): State<Arc<AppState>>, | ||
| Json(req): Json<CreateUserRequest>, | ||
| ) -> Result<Json<CreateUserResponse>, crate::auth::AuthError> { | ||
| // Only admin can create users | ||
| if user.claims.role != Role::Admin { | ||
| state.audit.log_failure( | ||
| user.claims.sub.clone(), | ||
| user.claims.username.clone(), | ||
| "create_user".to_string(), | ||
| req.username.clone(), | ||
| "Insufficient permissions".to_string(), | ||
| ); | ||
| return Err(crate::auth::AuthError::InsufficientPermissions); | ||
| } | ||
|
|
||
| let result = state.auth.add_user(req.username.clone(), req.password, req.role); | ||
|
|
||
| match &result { | ||
| Ok(new_user) => { | ||
| state.audit.log_success( | ||
| user.claims.sub.clone(), | ||
| user.claims.username.clone(), | ||
| "create_user".to_string(), | ||
| new_user.username.clone(), | ||
| Some(format!("Created user with role: {:?}", new_user.role)), | ||
| ); | ||
|
|
||
| Ok(Json(CreateUserResponse { | ||
| id: new_user.id.clone(), | ||
| username: new_user.username.clone(), | ||
| role: new_user.role, | ||
| })) | ||
| } | ||
| Err(e) => { | ||
| state.audit.log_failure( | ||
| user.claims.sub.clone(), | ||
| user.claims.username.clone(), | ||
| "create_user".to_string(), | ||
| req.username, | ||
| e.to_string(), | ||
| ); | ||
| Err(e.clone()) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// Get audit logs endpoint (admin and operator can view) | ||
| #[derive(Deserialize)] | ||
| pub struct AuditLogsQuery { | ||
| #[serde(default = "default_limit")] | ||
| pub limit: usize, | ||
| } | ||
|
|
||
| fn default_limit() -> usize { | ||
| 100 | ||
| } | ||
|
|
||
| #[derive(Serialize)] | ||
| pub struct AuditLogsResponse { | ||
| pub logs: Vec<crate::audit::AuditLogEntry>, | ||
| pub total: usize, | ||
| } | ||
|
|
||
| pub async fn get_audit_logs( | ||
| user: AuthUser, | ||
| State(state): State<Arc<AppState>>, | ||
| axum::extract::Query(query): axum::extract::Query<AuditLogsQuery>, | ||
| ) -> Result<Json<AuditLogsResponse>, StatusCode> { | ||
| // Only admin and operator can view audit logs | ||
| if !matches!(user.claims.role, Role::Admin | Role::Operator) { | ||
| return Err(StatusCode::FORBIDDEN); | ||
| } | ||
|
|
||
| let all_logs = state.audit.get_logs(); | ||
| let total = all_logs.len(); | ||
| let logs = state.audit.get_recent_logs(query.limit); | ||
|
|
||
| state.audit.log_success( | ||
| user.claims.sub.clone(), | ||
| user.claims.username.clone(), | ||
| "view_audit_logs".to_string(), | ||
| "audit".to_string(), | ||
| Some(format!("Retrieved {} logs", logs.len())), | ||
| ); | ||
|
|
||
| Ok(Json(AuditLogsResponse { logs, total })) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Security: Unnecessary Password Clone: The login request is cloned on line 18 (
req.clone()), which creates an unnecessary copy of the plaintext password in memory. This increases the attack surface for memory scraping attacks.The clone is only needed to access
req.usernamelater (line 34) for error logging. Instead, clone only the username:This prevents the password from being duplicated in memory.