From 2fdf89b94916c87d817494b863f46235ed210c35 Mon Sep 17 00:00:00 2001 From: "benjamin.747" Date: Tue, 12 Aug 2025 15:07:38 +0800 Subject: [PATCH] fix(UI): update user_id to username in ssh/token table --- ceres/Cargo.toml | 2 + ceres/src/model/mr.rs | 4 +- ceres/src/pack/monorepo.rs | 41 ++++++++--- ceres/src/protocol/mod.rs | 49 ++++++++++++- common/src/config.rs | 4 ++ config/config.toml | 2 +- jupiter/callisto/src/access_token.rs | 2 +- jupiter/callisto/src/builds.rs | 2 +- jupiter/callisto/src/entity_ext/mega_mr.rs | 2 + jupiter/callisto/src/mega_mr.rs | 1 + jupiter/callisto/src/ssh_keys.rs | 2 +- .../m20250812_022434_alter_mega_mr.rs | 68 +++++++++++++++++++ jupiter/src/migration/mod.rs | 2 + jupiter/src/storage/mr_storage.rs | 4 ++ jupiter/src/storage/user_storage.rs | 31 +++++---- mono/Cargo.toml | 1 - mono/src/api/label/label_router.rs | 2 +- mono/src/api/mr/mr_router.rs | 31 ++++----- mono/src/api/user/user_router.rs | 46 ++++++------- mono/src/git_protocol/http.rs | 57 +--------------- .../bellatrix/src/orion_client/mod.rs | 2 +- 21 files changed, 223 insertions(+), 132 deletions(-) create mode 100644 jupiter/src/migration/m20250812_022434_alter_mega_mr.rs diff --git a/ceres/Cargo.toml b/ceres/Cargo.toml index 8fc2490cc..a6845499a 100644 --- a/ceres/Cargo.toml +++ b/ceres/Cargo.toml @@ -34,3 +34,5 @@ ring = { workspace = true } hex = { workspace = true } sysinfo = { workspace = true } utoipa = { workspace = true } +base64 = { workspace = true } +http = { workspace = true } diff --git a/ceres/src/model/mr.rs b/ceres/src/model/mr.rs index 23f6d6c6e..5b6814572 100644 --- a/ceres/src/model/mr.rs +++ b/ceres/src/model/mr.rs @@ -1,6 +1,8 @@ -use serde::{Deserialize, Serialize}; use std::path::PathBuf; + +use serde::{Deserialize, Serialize}; use utoipa::ToSchema; + use mercury::hash::SHA1; #[derive(PartialEq, Eq, Debug, Clone, Serialize, Deserialize)] diff --git a/ceres/src/pack/monorepo.rs b/ceres/src/pack/monorepo.rs index bc79664ff..3189ee039 100644 --- a/ceres/src/pack/monorepo.rs +++ b/ceres/src/pack/monorepo.rs @@ -46,10 +46,11 @@ pub struct MonoRepo { pub from_hash: String, pub to_hash: String, // current_commit only exists when an unpack operation occurs. - // When only a branch is updated and the pack file is empty, this value will be null. + // When only a branch is updated and the pack file is empty, this value will be None. pub current_commit: Arc>>, pub mr_link: Arc>>, pub bellatrix: Arc, + pub username: Option, } #[async_trait] @@ -311,8 +312,9 @@ impl RepoHandler for MonoRepo { async fn save_or_update_mr(&self) -> Result<(), MegaError> { let storage = self.storage.mr_storage(); let path_str = self.path.to_str().unwrap(); + let username = self.username(); - match storage.get_open_mr_by_path(path_str).await? { + match storage.get_open_mr_by_path(path_str, &username).await? { Some(mr) => { self.update_existing_mr(mr).await?; } @@ -320,9 +322,20 @@ impl RepoHandler for MonoRepo { let link_guard = self.mr_link.read().await; let mr_link = link_guard.as_ref().unwrap(); let commit_guard = self.current_commit.read().await; - let title = commit_guard.as_ref().unwrap().format_message(); + let title = if let Some(commit) = commit_guard.as_ref() { + commit.format_message() + } else { + String::new() + }; storage - .new_mr(path_str, mr_link, &title, &self.from_hash, &self.to_hash) + .new_mr( + path_str, + mr_link, + &title, + &self.from_hash, + &self.to_hash, + &username, + ) .await?; } }; @@ -377,7 +390,11 @@ impl MonoRepo { async fn fetch_or_new_mr_link(&self) -> Result { let storage = self.storage.mr_storage(); let path_str = self.path.to_str().unwrap(); - let mr_link = match storage.get_open_mr_by_path(path_str).await.unwrap() { + let mr_link = match storage + .get_open_mr_by_path(path_str, &self.username()) + .await + .unwrap() + { Some(mr) => mr.link.clone(), None => { if self.from_hash == "0".repeat(40) { @@ -401,9 +418,10 @@ impl MonoRepo { comment_stg .add_conversation( &mr.link, - "", + &self.username(), Some(format!( - "Mega updated the mr automatic from {} to {}", + "{} updated the mr automatic from {} to {}", + self.username(), &mr.to_hash[..6], &self.to_hash[..6] )), @@ -415,11 +433,12 @@ impl MonoRepo { tracing::info!("repeat commit with mr: {}, do nothing", mr.id); } } else { + // TODO 直接覆盖? comment_stg .add_conversation( &mr.link, - "", - Some("Mega closed MR due to conflict".to_string()), + &self.username(), + Some(format!("{} closed MR due to conflict", self.username(),)), ConvTypeEnum::Closed, ) .await @@ -510,6 +529,10 @@ impl MonoRepo { let to_tree: Tree = mono_stg.get_tree_by_hash(&to_c.tree).await?.unwrap().into(); diff_trees(&to_tree, &from_tree) } + + pub fn username(&self) -> String { + self.username.clone().unwrap_or(String::from("Admin")) + } } type DiffResult = Vec<(PathBuf, Option, Option)>; diff --git a/ceres/src/protocol/mod.rs b/ceres/src/protocol/mod.rs index 7cd30952e..be54be014 100644 --- a/ceres/src/protocol/mod.rs +++ b/ceres/src/protocol/mod.rs @@ -1,6 +1,11 @@ use core::fmt; use std::{path::PathBuf, str::FromStr, sync::Arc}; +use base64::engine::general_purpose; +use base64::prelude::*; +use http::{HeaderMap, HeaderValue}; +use tokio::sync::RwLock; + use bellatrix::Bellatrix; use callisto::sea_orm_active_enums::RefTypeEnum; use common::{ @@ -10,7 +15,6 @@ use common::{ use import_refs::RefCommand; use jupiter::storage::Storage; use repo::Repo; -use tokio::sync::RwLock; use crate::pack::{import_repo::ImportRepo, monorepo::MonoRepo, RepoHandler}; @@ -26,6 +30,7 @@ pub struct SmartProtocol { pub command_list: Vec, pub service_type: Option, pub storage: Storage, + pub username: Option, } #[derive(Debug, PartialEq, Clone, Copy, Default)] @@ -134,6 +139,7 @@ impl SmartProtocol { command_list: Vec::new(), service_type: None, storage, + username: None, } } @@ -146,6 +152,7 @@ impl SmartProtocol { command_list: Vec::new(), service_type: None, storage, + username: None, } } @@ -183,6 +190,7 @@ impl SmartProtocol { current_commit: Arc::new(RwLock::new(None)), mr_link: Arc::new(RwLock::new(None)), bellatrix: Arc::new(Bellatrix::new(self.storage.config().build.clone())), + username: self.username.clone(), }; if let Some(command) = self .command_list @@ -195,6 +203,45 @@ impl SmartProtocol { Ok(Arc::new(res)) } } + + pub fn enable_http_auth(&self) -> bool { + self.storage.config().enable_http_auth() + } + + pub async fn http_auth(&mut self, header: &HeaderMap) -> bool { + for (k, v) in header { + if k == http::header::AUTHORIZATION { + let decoded = general_purpose::STANDARD + .decode( + v.to_str() + .unwrap() + .strip_prefix("Basic ") + .unwrap() + .as_bytes(), + ) + .unwrap(); + let credentials = String::from_utf8(decoded).unwrap_or_default(); + let mut parts = credentials.splitn(2, ':'); + let username = parts.next().unwrap_or(""); + self.username = Some(username.to_owned()); + let token = parts.next().unwrap_or(""); + let auth_config = self.storage.config().authentication.clone(); + if auth_config.enable_test_user + && username == auth_config.test_user_name + && token == auth_config.test_user_token + { + return true; + } + return self + .storage + .user_storage() + .check_token(username, token) + .await + .unwrap(); + } + } + false + } } #[cfg(test)] diff --git a/common/src/config.rs b/common/src/config.rs index 4737f3fb4..3490f9866 100644 --- a/common/src/config.rs +++ b/common/src/config.rs @@ -156,6 +156,10 @@ impl Config { pub fn from_config(config: c::Config) -> Result { config.try_deserialize::() } + + pub fn enable_http_auth(&self) -> bool { + self.authentication.enable_http_auth + } } impl Default for Config { diff --git a/config/config.toml b/config/config.toml index 38d592770..6e6692e6f 100644 --- a/config/config.toml +++ b/config/config.toml @@ -66,7 +66,7 @@ root_dirs = ["third-party", "project", "doc", "release", "model"] [build] # enable build system trigger -enable_build = true +enable_build = false # build system url orion_server = "https://orion.gitmega.com" diff --git a/jupiter/callisto/src/access_token.rs b/jupiter/callisto/src/access_token.rs index 922f99e4a..d97cf24ed 100644 --- a/jupiter/callisto/src/access_token.rs +++ b/jupiter/callisto/src/access_token.rs @@ -8,7 +8,7 @@ use serde::{Deserialize, Serialize}; pub struct Model { #[sea_orm(primary_key, auto_increment = false)] pub id: i64, - pub user_id: String, + pub username: String, #[sea_orm(column_type = "Text")] pub token: String, pub created_at: DateTime, diff --git a/jupiter/callisto/src/builds.rs b/jupiter/callisto/src/builds.rs index faddeb196..1709def69 100644 --- a/jupiter/callisto/src/builds.rs +++ b/jupiter/callisto/src/builds.rs @@ -11,7 +11,7 @@ pub struct Model { pub output: String, pub exit_code: Option, pub start_at: DateTime, - pub end_at: DateTime, + pub end_at: Option, pub repo_name: String, pub target: String, } diff --git a/jupiter/callisto/src/entity_ext/mega_mr.rs b/jupiter/callisto/src/entity_ext/mega_mr.rs index bf93f7123..64eceb466 100644 --- a/jupiter/callisto/src/entity_ext/mega_mr.rs +++ b/jupiter/callisto/src/entity_ext/mega_mr.rs @@ -58,6 +58,7 @@ impl mega_mr::Model { link: String, from_hash: String, to_hash: String, + username: String, ) -> Self { let now = chrono::Utc::now().naive_utc(); Self { @@ -71,6 +72,7 @@ impl mega_mr::Model { path, from_hash, to_hash, + username, } } } diff --git a/jupiter/callisto/src/mega_mr.rs b/jupiter/callisto/src/mega_mr.rs index 3d884ca73..bb4bd5580 100644 --- a/jupiter/callisto/src/mega_mr.rs +++ b/jupiter/callisto/src/mega_mr.rs @@ -20,6 +20,7 @@ pub struct Model { pub to_hash: String, pub created_at: DateTime, pub updated_at: DateTime, + pub username: String, } #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] diff --git a/jupiter/callisto/src/ssh_keys.rs b/jupiter/callisto/src/ssh_keys.rs index e957e249b..c4d75bc9c 100644 --- a/jupiter/callisto/src/ssh_keys.rs +++ b/jupiter/callisto/src/ssh_keys.rs @@ -8,7 +8,7 @@ use serde::{Deserialize, Serialize}; pub struct Model { #[sea_orm(primary_key, auto_increment = false)] pub id: i64, - pub user_id: String, + pub username: String, #[sea_orm(column_type = "Text")] pub title: String, #[sea_orm(column_type = "Text")] diff --git a/jupiter/src/migration/m20250812_022434_alter_mega_mr.rs b/jupiter/src/migration/m20250812_022434_alter_mega_mr.rs new file mode 100644 index 000000000..a9c6fe5bc --- /dev/null +++ b/jupiter/src/migration/m20250812_022434_alter_mega_mr.rs @@ -0,0 +1,68 @@ +use sea_orm::{DatabaseBackend, Statement}; +use sea_orm_migration::prelude::*; + +#[derive(DeriveMigrationName)] +pub struct Migration; + +#[async_trait::async_trait] +impl MigrationTrait for Migration { + async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> { + let backend = manager.get_database_backend(); + + match backend { + DatabaseBackend::Postgres | DatabaseBackend::MySql => { + manager + .alter_table( + Table::alter() + .table(MegaMr::Table) + .add_column_if_not_exists( + ColumnDef::new(Alias::new("username")) + .string() + .not_null() + .default(""), + ) + .to_owned(), + ) + .await?; + + manager + .get_connection() + .execute(Statement::from_string( + manager.get_database_backend(), + "ALTER TABLE access_token RENAME COLUMN user_id TO username".to_owned(), + )) + .await?; + + manager + .get_connection() + .execute(Statement::from_string( + manager.get_database_backend(), + "ALTER TABLE ssh_keys RENAME COLUMN user_id TO username".to_owned(), + )) + .await?; + } + DatabaseBackend::Sqlite => {} + } + + Ok(()) + } + + async fn down(&self, _: &SchemaManager) -> Result<(), DbErr> { + Ok(()) + } +} + +#[derive(DeriveIden)] +enum MegaMr { + Table, +} + +// #[derive(DeriveIden)] +// enum AccessToken { +// Table, +// } + +// #[derive(DeriveIden)] +// enum SshKeys { +// Table, +// } diff --git a/jupiter/src/migration/mod.rs b/jupiter/src/migration/mod.rs index 7bd5ea4d6..2f6ee66d6 100644 --- a/jupiter/src/migration/mod.rs +++ b/jupiter/src/migration/mod.rs @@ -46,6 +46,7 @@ mod m20250702_072055_add_item_assignees; mod m20250710_073119_create_reactions; mod m20250725_103004_add_note; mod m20250804_151214_alter_builds_end_at; +mod m20250812_022434_alter_mega_mr; /// Creates a primary key column definition with big integer type. /// /// # Arguments @@ -79,6 +80,7 @@ impl MigratorTrait for Migrator { Box::new(m20250710_073119_create_reactions::Migration), Box::new(m20250725_103004_add_note::Migration), Box::new(m20250804_151214_alter_builds_end_at::Migration), + Box::new(m20250812_022434_alter_mega_mr::Migration), ] } } diff --git a/jupiter/src/storage/mr_storage.rs b/jupiter/src/storage/mr_storage.rs index b445600f7..820510f91 100644 --- a/jupiter/src/storage/mr_storage.rs +++ b/jupiter/src/storage/mr_storage.rs @@ -33,9 +33,11 @@ impl MrStorage { pub async fn get_open_mr_by_path( &self, path: &str, + username: &str, ) -> Result, MegaError> { let model = mega_mr::Entity::find() .filter(mega_mr::Column::Path.eq(path)) + .filter(mega_mr::Column::Username.eq(username)) .filter(mega_mr::Column::Status.eq(MergeStatusEnum::Open)) .one(self.get_connection()) .await @@ -178,6 +180,7 @@ impl MrStorage { title: &str, from_hash: &str, to_hash: &str, + username: &str, ) -> Result { let model = mega_mr::Model::new( path.to_owned(), @@ -185,6 +188,7 @@ impl MrStorage { link.to_owned(), from_hash.to_owned(), to_hash.to_owned(), + username.to_owned(), ); let res = model .into_active_model() diff --git a/jupiter/src/storage/user_storage.rs b/jupiter/src/storage/user_storage.rs index 1cd224db6..675c7e91b 100644 --- a/jupiter/src/storage/user_storage.rs +++ b/jupiter/src/storage/user_storage.rs @@ -47,14 +47,14 @@ impl UserStorage { pub async fn save_ssh_key( &self, - user_id: String, + username: String, title: &str, ssh_key: &str, finger: &str, ) -> Result<(), MegaError> { let model = ssh_keys::Model { id: generate_id(), - user_id, + username, title: title.to_owned(), ssh_key: ssh_key.to_owned(), finger: finger.to_owned(), @@ -65,18 +65,18 @@ impl UserStorage { Ok(()) } - pub async fn list_user_ssh(&self, user_id: String) -> Result, MegaError> { + pub async fn list_user_ssh(&self, username: String) -> Result, MegaError> { let res: Vec = ssh_keys::Entity::find() - .filter(ssh_keys::Column::UserId.eq(user_id)) + .filter(ssh_keys::Column::Username.eq(username)) .all(self.get_connection()) .await?; Ok(res) } - pub async fn delete_ssh_key(&self, user_id: String, id: i64) -> Result<(), MegaError> { + pub async fn delete_ssh_key(&self, username: String, id: i64) -> Result<(), MegaError> { let res = ssh_keys::Entity::find() .filter(ssh_keys::Column::Id.eq(id)) - .filter(ssh_keys::Column::UserId.eq(user_id)) + .filter(ssh_keys::Column::Username.eq(username)) .one(self.get_connection()) .await?; if let Some(model) = res { @@ -96,11 +96,11 @@ impl UserStorage { Ok(res) } - pub async fn generate_token(&self, user_id: String) -> Result { + pub async fn generate_token(&self, username: String) -> Result { let token_str = Uuid::new_v4().to_string(); let model = access_token::Model { id: generate_id(), - user_id, + username, token: token_str.clone(), created_at: chrono::Utc::now().naive_utc(), }; @@ -109,10 +109,10 @@ impl UserStorage { Ok(token_str.to_owned()) } - pub async fn delete_token(&self, user_id: String, id: i64) -> Result<(), MegaError> { + pub async fn delete_token(&self, username: String, id: i64) -> Result<(), MegaError> { let res = access_token::Entity::find() .filter(access_token::Column::Id.eq(id)) - .filter(access_token::Column::UserId.eq(user_id)) + .filter(access_token::Column::Username.eq(username)) .one(self.get_connection()) .await?; if let Some(model) = res { @@ -121,17 +121,20 @@ impl UserStorage { Ok(()) } - pub async fn list_token(&self, user_id: String) -> Result, MegaError> { + pub async fn list_token( + &self, + username: String, + ) -> Result, MegaError> { let res = access_token::Entity::find() - .filter(access_token::Column::UserId.eq(user_id)) + .filter(access_token::Column::Username.eq(username)) .all(self.get_connection()) .await?; Ok(res) } - pub async fn check_token(&self, user_id: String, token: &str) -> Result { + pub async fn check_token(&self, username: &str, token: &str) -> Result { let res = access_token::Entity::find() - .filter(access_token::Column::UserId.eq(user_id)) + .filter(access_token::Column::Username.eq(username)) .filter(access_token::Column::Token.eq(token)) .one(self.get_connection()) .await?; diff --git a/mono/Cargo.toml b/mono/Cargo.toml index 0f452cb9f..9623fbb84 100644 --- a/mono/Cargo.toml +++ b/mono/Cargo.toml @@ -52,7 +52,6 @@ ed25519-dalek = { workspace = true, features = ["pkcs8"] } lazy_static = { workspace = true } ctrlc = { workspace = true } oauth2 = { workspace = true } -base64 = { workspace = true } async-session = { workspace = true } http = { workspace = true } cedar-policy = { workspace = true } diff --git a/mono/src/api/label/label_router.rs b/mono/src/api/label/label_router.rs index b7e57340c..6bd75aa3c 100644 --- a/mono/src/api/label/label_router.rs +++ b/mono/src/api/label/label_router.rs @@ -73,7 +73,7 @@ async fn new_label( ), path = "/{id}", responses( - (status = 200, body = CommonResult>, content_type = "application/json") + (status = 200, body = CommonResult, content_type = "application/json") ), tag = LABEL_TAG )] diff --git a/mono/src/api/mr/mr_router.rs b/mono/src/api/mr/mr_router.rs index d5455bde0..93b04c18d 100644 --- a/mono/src/api/mr/mr_router.rs +++ b/mono/src/api/mr/mr_router.rs @@ -468,10 +468,10 @@ fn build_forest(paths: Vec) -> Vec { #[cfg(test)] mod test { - use std::collections::HashMap; - use ceres::model::mr::MrDiff; use crate::api::mr::mr_router::{build_forest, extract_files_with_status}; use crate::api::mr::FilesChangedList; + use ceres::model::mr::MrDiff; + use std::collections::HashMap; #[test] fn test_parse_diff_result_to_filelist() { @@ -525,7 +525,7 @@ mod test { fn test_mr_files_changed_logic() { // Test the core logic of mr_files_changed function // This tests the data transformation logic without needing the full state - + let sample_diff_output = r#"diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..abc1234 @@ -550,7 +550,7 @@ mod test { // Test extract_files_with_status let diff_files = extract_files_with_status(sample_diff_output); - + assert_eq!(diff_files.len(), 3); assert_eq!(diff_files.get("src/main.rs"), Some(&"new".to_string())); assert_eq!(diff_files.get("src/lib.rs"), Some(&"modified".to_string())); @@ -561,28 +561,25 @@ mod test { for (path, _) in diff_files { paths.push(path); } - + let mui_trees = build_forest(paths); - + // Verify the tree structure assert!(!mui_trees.is_empty()); - + // Check that we have the expected root nodes let root_labels: Vec<&str> = mui_trees.iter().map(|tree| tree.label.as_str()).collect(); assert!(root_labels.contains(&"src")); assert!(root_labels.contains(&"README.md")); - + let content = MrDiff { data: sample_diff_output.to_string(), - page_info: None + page_info: None, }; // Test the complete response structure - let files_changed_list = FilesChangedList { - mui_trees, - content, - }; - + let files_changed_list = FilesChangedList { mui_trees, content }; + assert!(!files_changed_list.mui_trees.is_empty()); assert_eq!(files_changed_list.content.data, sample_diff_output); } @@ -605,7 +602,7 @@ new file mode 100644 index 0000000..1234567 --- /dev/null +++ b/new_file.txt"#; - + let result = extract_files_with_status(additions_only); assert_eq!(result.len(), 1); assert_eq!(result.get("new_file.txt"), Some(&"new".to_string())); @@ -614,7 +611,7 @@ index 0000000..1234567 let deletions_only = r#"diff --git a/old_file.txt b/old_file.txt deleted file mode 100644 index 1234567..0000000"#; - + let result = extract_files_with_status(deletions_only); assert_eq!(result.len(), 1); assert_eq!(result.get("old_file.txt"), Some(&"deleted".to_string())); @@ -642,7 +639,7 @@ index 1234567..0000000"#; let result = build_forest(nested_paths); assert_eq!(result.len(), 1); // Should have one root "a" assert_eq!(result[0].label, "a"); - + // The tree should have nested structure let root = &result[0]; assert!(root.children.is_some()); diff --git a/mono/src/api/user/user_router.rs b/mono/src/api/user/user_router.rs index 4b84246c3..5b70da690 100644 --- a/mono/src/api/user/user_router.rs +++ b/mono/src/api/user/user_router.rs @@ -8,7 +8,7 @@ use axum::{ use russh::keys::{parse_public_key_base64, HashAlg}; use utoipa_axum::{router::OpenApiRouter, routes}; -use common::model::CommonResult; +use common::{errors::MegaError, model::CommonResult}; use crate::api::user::model::ListSSHKey; use crate::api::user::model::ListToken; @@ -53,23 +53,24 @@ async fn add_key( state: State, Json(json): Json, ) -> Result>, ApiError> { - let ssh_key: Vec<&str> = json.ssh_key.split_whitespace().collect(); - let key = parse_public_key_base64(ssh_key.get(1).ok_or("Invalid key format").unwrap())?; - let title = if !json.title.is_empty() { - json.title - } else { - ssh_key + let ssh_parts: Vec<&str> = json.ssh_key.split_whitespace().collect(); + let key = parse_public_key_base64( + ssh_parts + .get(1) + .ok_or_else(|| MegaError::with_message("Invalid key format"))?, + )?; + let title = if json.title.is_empty() { + ssh_parts .get(2) - .ok_or("Invalid key format") - .unwrap() - .to_owned() - .to_owned() + .ok_or_else(|| MegaError::with_message("Invalid key format"))? + .to_string() + } else { + json.title }; - state .user_stg() .save_ssh_key( - user.campsite_user_id, + user.username, &title, &json.ssh_key, &key.fingerprint(HashAlg::Sha256).to_string(), @@ -97,7 +98,7 @@ async fn remove_key( ) -> Result>, ApiError> { state .user_stg() - .delete_ssh_key(user.campsite_user_id, key_id) + .delete_ssh_key(user.username, key_id) .await?; Ok(Json(CommonResult::success(None))) } @@ -115,10 +116,7 @@ async fn list_key( user: LoginUser, state: State, ) -> Result>>, ApiError> { - let res = state - .user_stg() - .list_user_ssh(user.campsite_user_id) - .await?; + let res = state.user_stg().list_user_ssh(user.username).await?; Ok(Json(CommonResult::success(Some( res.into_iter().map(|x| x.into()).collect(), )))) @@ -137,10 +135,7 @@ async fn generate_token( user: LoginUser, state: State, ) -> Result>, ApiError> { - let res = state - .user_stg() - .generate_token(user.campsite_user_id) - .await?; + let res = state.user_stg().generate_token(user.username).await?; Ok(Json(CommonResult::success(Some(res)))) } @@ -161,10 +156,7 @@ async fn remove_token( state: State, Path(key_id): Path, ) -> Result>, ApiError> { - state - .user_stg() - .delete_token(user.campsite_user_id, key_id) - .await?; + state.user_stg().delete_token(user.username, key_id).await?; Ok(Json(CommonResult::success(None))) } @@ -181,7 +173,7 @@ async fn list_token( user: LoginUser, state: State, ) -> Result>>, ApiError> { - let data = state.user_stg().list_token(user.campsite_user_id).await?; + let data = state.user_stg().list_token(user.username).await?; let res = data.into_iter().map(|x| x.into()).collect(); Ok(Json(CommonResult::success(Some(res)))) } diff --git a/mono/src/git_protocol/http.rs b/mono/src/git_protocol/http.rs index 86a799c54..dc9725caa 100644 --- a/mono/src/git_protocol/http.rs +++ b/mono/src/git_protocol/http.rs @@ -3,12 +3,8 @@ use std::convert::Infallible; use anyhow::Result; use axum::body::Body; use axum::http::{HeaderValue, Request, Response}; -use base64::engine::general_purpose; -use base64::prelude::*; use bytes::{Bytes, BytesMut}; use futures::{stream, TryStreamExt}; -use http::HeaderMap; -use jupiter::storage::Storage; use tokio::io::AsyncReadExt; use tokio_stream::StreamExt; @@ -41,51 +37,6 @@ pub async fn git_info_refs( Ok(response) } -async fn http_auth(header: &HeaderMap, storage: &Storage) -> bool { - for (k, v) in header { - if k == http::header::AUTHORIZATION { - let decoded = general_purpose::STANDARD - .decode( - v.to_str() - .unwrap() - .strip_prefix("Basic ") - .unwrap() - .as_bytes(), - ) - .unwrap(); - let credentials = String::from_utf8(decoded).unwrap_or_default(); - let mut parts = credentials.splitn(2, ':'); - let username = parts.next().unwrap_or(""); - let token = parts.next().unwrap_or(""); - tracing::debug!("{}, {}", username, token); - let auth_config = storage.config().authentication.clone(); - if auth_config.enable_test_user - && username == auth_config.test_user_name - && token == auth_config.test_user_token - { - return true; - } - match storage - .user_storage() - .find_user_by_name(username) - .await - .unwrap() - { - // TODO refactor later - Some(_) => { - return storage - .user_storage() - .check_token(String::new(), token) - .await - .unwrap(); - } - None => return false, - } - } - } - false -} - fn auth_failed() -> Result, ProtocolError> { let resp = Response::builder() .status(401) @@ -186,13 +137,7 @@ pub async fn git_receive_pack( req: Request, mut pack_protocol: SmartProtocol, ) -> Result, ProtocolError> { - if pack_protocol - .storage - .config() - .authentication - .enable_http_auth - && !http_auth(req.headers(), &pack_protocol.storage).await - { + if pack_protocol.enable_http_auth() && !pack_protocol.http_auth(req.headers()).await { return auth_failed(); } // Convert the request body into a data stream. diff --git a/orion-server/bellatrix/src/orion_client/mod.rs b/orion-server/bellatrix/src/orion_client/mod.rs index 874ab6b59..272bc23db 100644 --- a/orion-server/bellatrix/src/orion_client/mod.rs +++ b/orion-server/bellatrix/src/orion_client/mod.rs @@ -10,7 +10,7 @@ pub struct OrionBuildRequest { } #[derive(Clone)] -pub struct OrionClient { +pub(crate) struct OrionClient { base_url: String, client: reqwest::Client, }