feat(misc): fix clippy misc and remove unused auth module

This commit is contained in:
Samuka007 2025-03-28 14:32:04 +08:00
parent 35fb4a8232
commit 21e9f3cbe8
9 changed files with 17 additions and 109 deletions

1
Cargo.lock generated
View File

@ -2041,6 +2041,7 @@ dependencies = [
"futures-util",
"hyper 0.14.32",
"lazy_static",
"log",
"my-workspace-hack",
"prometheus",
"regex",

View File

@ -27,4 +27,5 @@ futures-util = "0.3"
service = { path = "../service" }
async-trait = "0.1"
lazy_static = "1.4.0"
log = "0.4"
my-workspace-hack = { version = "0.1", path = "../my-workspace-hack" }

View File

@ -1,90 +0,0 @@
use actix_web::{Error, HttpMessage, HttpResponse, dev::ServiceRequest};
use std::collections::HashMap;
//写到使用actix-web-httpauth作为中间件还没有解决read_basic_auth函数的实现返回值和之前在bootstrap的调用不一样
pub struct BasicAuthCredentials {
user: String,
password: String,
}
impl BasicAuthCredentials {
pub fn new(username: &str, password: &str) -> Self {
BasicAuthCredentials {
user: username.to_string(),
password: password.to_string(),
}
}
}
pub struct ReadBasicAuthFromDisk {
secret_mount_path: String,
user_filename: String,
password_filename: String,
}
impl ReadBasicAuthFromDisk {
pub fn new(secret_mount_path: &str, user_filename: &str, password_filename: &str) -> Self {
ReadBasicAuthFromDisk {
secret_mount_path: secret_mount_path.to_string(),
user_filename: user_filename.to_string(),
password_filename: password_filename.to_string(),
}
}
//TODO:这里应该加密?
pub async fn read_basic_auth(&self) -> HashMap<String, String> {
let mut user_map = HashMap::new();
let user_file =
std::fs::read_to_string(format!("{}/{}", self.secret_mount_path, self.user_filename))
.unwrap();
let password_file = std::fs::read_to_string(format!(
"{}/{}",
self.secret_mount_path, self.password_filename
))
.unwrap();
let user_vec: Vec<&str> = user_file.split("\n").collect();
let password_vec: Vec<&str> = password_file.split("\n").collect();
for i in 0..user_vec.len() {
user_map.insert(user_vec[i].to_string(), password_vec[i].to_string());
}
user_map
}
pub async fn basic_auth_validator(&self, req: ServiceRequest) -> Result<ServiceRequest, Error> {
let auth_header = req.headers().get("Authorization");
if let Some(auth_header) = auth_header {
//TODO:to_str()转化失败的处理,或者在之前限制用户输入非法字符
let auth_header = auth_header.to_str().unwrap();
let auth_header = auth_header.split(" ").collect::<Vec<&str>>();
if auth_header.len() != 2 {
return Err(actix_web::error::ErrorUnauthorized(
"Invalid Authorization Header",
));
}
let auth_header = auth_header[1];
let auth_header = base64::decode(auth_header).unwrap();
let auth_header = String::from_utf8(auth_header).unwrap();
let auth_header = auth_header.split(":").collect::<Vec<&str>>();
if auth_header.len() != 2 {
return Err(actix_web::error::ErrorUnauthorized(
"Invalid Authorization Header",
));
}
let username = auth_header[0];
let password = auth_header[1];
let user_map = self.read_basic_auth().await;
if let Some(user) = user_map.get(username) {
if user == password {
return Ok(req);
}
}
}
Err(actix_web::error::ErrorUnauthorized(
"Invalid Username or Password",
))
}
}
async fn index() -> HttpResponse {
HttpResponse::Ok().body("欢迎访问受保护的资源!")
}

View File

@ -3,7 +3,6 @@ use prometheus::Registry;
use std::collections::HashMap;
use crate::{
auth,
handlers,
metrics::{self, HttpMetrics},
//httputil,
@ -12,10 +11,12 @@ use crate::{
};
//用于函数/服务名称的表达式
#[allow(dead_code)]
const NAME_EXPRESSION: &str = r"-a-zA-Z_0-9\.";
//应用程序状态,存储共享的数据,如配置、指标、认证信息等,为业务函数提供支持
#[derive(Clone)]
#[allow(dead_code)]
struct AppState {
config: FaaSConfig, //应用程序的配置用于识别是否开启Basic Auth等
metrics: HttpMetrics, //用于监视http请求的持续时间和总数
@ -23,13 +24,14 @@ struct AppState {
}
//serve 把处理程序headlers load到正确路由规范。这个函数是阻塞的。
#[allow(dead_code)]
async fn serve() -> std::io::Result<()> {
let config = FaaSConfig::new(); //加载配置用于识别是否开启Basic Auth等
let registry = Registry::new();
let _registry = Registry::new();
let metrics = metrics::HttpMetrics::new(); //metrics监视http请求的持续时间和总数
// 用于存储应用程序状态的结构体
let mut app_state = AppState {
let app_state = AppState {
config: config.clone(),
metrics: metrics.clone(),
credentials: None,
@ -37,15 +39,7 @@ async fn serve() -> std::io::Result<()> {
// 如果启用了Basic Auth从指定路径读取认证凭证并存储在应用程序状态中
if config.enable_basic_auth {
// 读取Basic Auth凭证
let auth = auth::ReadBasicAuthFromDisk::new(
&config.secret_mount_path,
"users.txt",
"passwords.txt",
);
let credentials = auth.read_basic_auth().await; //这里的credentials是所有的账号密码
app_state.credentials = Some(credentials);
//TODO:handlers decorate with basic auth,尚未清楚是不是需要给所有的函数都加上
todo!("implement authentication");
}
HttpServer::new(move || {

View File

@ -18,7 +18,9 @@ impl super::IAmHandler for FunctionLister {
.await
.unwrap();
for container in containers.iter() {}
for container in containers.iter() {
log::debug!("container: {:?}", container);
}
HttpResponse::Ok().json("函数列表")
}

View File

@ -112,7 +112,7 @@ pub trait IAmHandler {
type Input: DeserializeOwned + Send + 'static;
// type Output: Serialize + Send + 'static;
/// 获取Handler元数据函数名、超时时间等
// /// 获取Handler元数据函数名、超时时间等
// fn metadata(&self) -> HandlerMeta;
/// 执行核心逻辑

View File

@ -1,4 +1,3 @@
pub mod auth;
pub mod bootstrap;
pub mod config;
pub mod handlers;

View File

@ -158,7 +158,6 @@ impl Service {
let request = ListTasksRequest {
filter: format!("container=={}", cid),
..Default::default()
};
let responce = tc
.list(with_namespace!(request, namespace))
@ -183,7 +182,6 @@ impl Service {
let delete_request = DeleteContainerRequest {
id: container.id.clone(),
..Default::default()
};
let _ = cc
@ -444,7 +442,7 @@ impl Service {
todo!()
}
async fn handle_index(&self, data: &Vec<u8>, ns: &str) -> Option<ImageConfiguration> {
async fn handle_index(&self, data: &[u8], ns: &str) -> Option<ImageConfiguration> {
let image_index: ImageIndex = ::serde_json::from_slice(data).unwrap();
let img_manifest_dscr = image_index
.manifests()
@ -486,7 +484,7 @@ impl Service {
self.handle_manifest(&resp, ns).await
}
async fn handle_manifest(&self, data: &Vec<u8>, ns: &str) -> Option<ImageConfiguration> {
async fn handle_manifest(&self, data: &[u8], ns: &str) -> Option<ImageConfiguration> {
let img_manifest: ImageManifest = ::serde_json::from_slice(data).unwrap();
let img_manifest_dscr = img_manifest.config();

View File

@ -131,6 +131,9 @@
apps = {
faas-rs = flake-utils.lib.mkApp {
drv = faas-rs-crate;
meta = {
description = "A containerd base lightweight FaaS platform written in Rust.";
};
};
};