Skip to content

Commit

Permalink
basic tests are all running
Browse files Browse the repository at this point in the history
  • Loading branch information
raimond visser committed Jan 17, 2024
1 parent 55097ca commit 916740f
Show file tree
Hide file tree
Showing 25 changed files with 732 additions and 952 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ axum-auth = "0.7.0"
axum-extra = { version = "0.9.1", features = ["typed-header", "query", "async-read-body", "typed-routing"] }
axum-macros = "0.4.0"
axum-server = { version = "0.6.0", features = ["tls-rustls"] }
axum-range = "0.4.0"
axum-range = "0.4"
clap = { version = "4.4.2", features = ["derive"] }
#enum_dispatch = "0.3.12"
futures = "0.3"
Expand Down
32 changes: 15 additions & 17 deletions src/acl.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
use once_cell::sync::OnceCell;
use crate::error::ErrorKind;
use crate::handlers::path_analysis::TPE_LOCKS;
use anyhow::Result;
use once_cell::sync::OnceCell;
use serde_derive::Deserialize;
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use serde_derive::Deserialize;
use crate::error::ErrorKind;
use crate::handlers::path_analysis::TPE_LOCKS;

//Static storage of our credentials
pub static ACL:OnceCell<Acl> = OnceCell::new();
pub static ACL: OnceCell<Acl> = OnceCell::new();

pub fn init_acl( state: Acl ) -> Result<(), ErrorKind> {
pub fn init_acl(state: Acl) -> Result<(), ErrorKind> {
if ACL.get().is_none() {
match ACL.set(state) {
Ok(_) => {}
Err(_) => {
return Err(ErrorKind::InternalError("Can not create ACL struct".to_string()));
return Err(ErrorKind::InternalError(
"Can not create ACL struct".to_string(),
));
}
}
}
Expand Down Expand Up @@ -134,32 +136,28 @@ impl AclChecker for Acl {

#[cfg(test)]
mod tests {
use std::env;
use super::AccessType::*;
use super::*;
use std::env;

#[test]
fn test_static_acl_access() {
let cwd = env::current_dir().unwrap();
let acl = PathBuf::new()
.join(cwd)
.join("test_data" )
.join("acl.toml" );
let acl = PathBuf::new().join(cwd).join("test_data").join("acl.toml");

dbg!(&acl);

let auth = Acl::from_file(false, true, Some(acl) ).unwrap();
let auth = Acl::from_file(false, true, Some(acl)).unwrap();
init_acl(auth).unwrap();

let acl = ACL.get().unwrap();
assert!( &acl.private_repo);
assert!( ! &acl.append_only );
assert!(&acl.private_repo);
assert!(!&acl.append_only);
let access = acl.repos.get("test_repo").unwrap();
let access_type = access.get("test").unwrap();
assert_eq!( access_type, &Append );
assert_eq!(access_type, &Append);
}


#[test]
fn allowed_flags() {
let mut acl = Acl {
Expand Down
92 changes: 44 additions & 48 deletions src/auth.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
use once_cell::sync::OnceCell;
use crate::error::ErrorKind;
use anyhow::Result;
use axum::extract::FromRequestParts;
use axum::http::request::Parts;
use axum_auth::AuthBasic;
use once_cell::sync::OnceCell;
use serde_derive::Deserialize;
use std::collections::HashMap;
use std::path::PathBuf;
use std::{fs, io};
use axum::extract::FromRequestParts;
use axum::http::request::Parts;
use axum_auth::{AuthBasic};
use crate::error::ErrorKind;
use serde_derive::{Deserialize};

//Static storage of our credentials
pub static AUTH:OnceCell<Auth> = OnceCell::new();
pub static AUTH: OnceCell<Auth> = OnceCell::new();

pub(crate) fn init_auth( state: Auth ) -> Result<(), ErrorKind> {
pub(crate) fn init_auth(state: Auth) -> Result<(), ErrorKind> {
if AUTH.get().is_none() {
match AUTH.set(state) {
Ok(_) => {}
Err(_) => {
return Err(ErrorKind::InternalError("Can not create AUTH struct".to_string()));
return Err(ErrorKind::InternalError(
"Can not create AUTH struct".to_string(),
));
}
}
}
Expand Down Expand Up @@ -99,87 +101,85 @@ pub struct AuthFromRequest {
}

#[async_trait::async_trait]
impl<S:Send+Sync> FromRequestParts<S> for AuthFromRequest {
impl<S: Send + Sync> FromRequestParts<S> for AuthFromRequest {
type Rejection = ErrorKind;

async fn from_request_parts(parts: &mut Parts, state: &S) -> std::result::Result<Self, ErrorKind> {
async fn from_request_parts(
parts: &mut Parts,
state: &S,
) -> std::result::Result<Self, ErrorKind> {
let auth_result = AuthBasic::from_request_parts(parts, state).await;
let checker = AUTH.get().unwrap();
tracing::debug!("Got authentication result ...:{:?}", &auth_result);
return match auth_result {
Ok(auth) => {
let AuthBasic((user, passw)) = auth;
let password = match passw {
None => { "".to_string() }
Some(p) => { p }
None => "".to_string(),
Some(p) => p,
};
if checker.verify(user.as_str(), password.as_str() ) {
Ok( Self{user, password})
if checker.verify(user.as_str(), password.as_str()) {
Ok(Self { user, password })
} else {
Err(ErrorKind::UserAuthenticationError(user))
}
}
Err(_) => {
let user = "".to_string();
if checker.verify("", "") {
return Ok(Self{user, password:"".to_string()})
return Ok(Self {
user,
password: "".to_string(),
});
}
Err(ErrorKind::AuthenticationHeaderError)
}
}
};
}
}

#[cfg(test)]
mod test {
use super::*;
use crate::auth::Auth;
use crate::test_server::{init_mutex, TestServer, WAIT_DELAY, WEB};
use anyhow::Result;
use std::env;
use std::path::PathBuf;
use axum::http::StatusCode;
use axum::Router;
use axum::routing::get;
use axum::Router;
use std::env;
use std::net::SocketAddr;
use std::path::PathBuf;
use tokio::net::TcpListener;
use crate::auth::Auth;
use crate::test_server::{init_mutex, TestServer, WAIT_DELAY, WEB};
use super::*;

#[test]
fn test_htaccess_account() -> Result<()>{
fn test_htaccess_account() -> Result<()> {
let cwd = env::current_dir()?;
let htaccess = PathBuf::new()
.join(cwd)
.join("test_data" )
.join("htaccess" );
let auth = Auth::from_file(false, &htaccess )?;
assert!( auth.verify("test", "test_pw"));
assert!( ! auth.verify("test", "__test_pw"));
let htaccess = PathBuf::new().join(cwd).join("test_data").join("htaccess");
let auth = Auth::from_file(false, &htaccess)?;
assert!(auth.verify("test", "test_pw"));
assert!(!auth.verify("test", "__test_pw"));

Ok(())
}

#[test]
fn test_static_htaccess() {
let cwd = env::current_dir().unwrap();
let htaccess = PathBuf::new()
.join(cwd)
.join("test_data" )
.join("htaccess" );
let htaccess = PathBuf::new().join(cwd).join("test_data").join("htaccess");

dbg!(&htaccess);

let auth = Auth::from_file(false, &htaccess ).unwrap();
let auth = Auth::from_file(false, &htaccess).unwrap();
init_auth(auth).unwrap();

let auth = AUTH.get().unwrap();
assert!( auth.verify("test", "test_pw"));
assert!( ! auth.verify("test", "__test_pw"));
assert!(auth.verify("test", "test_pw"));
assert!(!auth.verify("test", "__test_pw"));
}


#[tokio::test]
async fn server_auth_tester() -> Result<()> {

init_mutex();
let _r = WEB.get().take().unwrap();

Expand All @@ -195,18 +195,17 @@ mod test {
wrong_authentication().await;
nothing().await;

server.stop_server().await;
server.stop_server().await;

Ok(())
}


async fn tester_basic(AuthBasic((id, password)): AuthBasic) -> String {
format!("Got {} and {:?}", id, password)
}

async fn tester_rustic_server( auth:AuthFromRequest ) -> String {
format!("User = {}", auth.user )
async fn tester_rustic_server(auth: AuthFromRequest) -> String {
format!("User = {}", auth.user)
}

/// The requests which should be returned fine
Expand Down Expand Up @@ -234,10 +233,7 @@ mod test {
.await
.unwrap();
assert_eq!(resp.status().as_u16(), StatusCode::OK.as_u16());
assert_eq!(
resp.text().await.unwrap(),
String::from("User = test")
);
assert_eq!(resp.text().await.unwrap(), String::from("User = test"));
}

async fn wrong_authentication() {
Expand Down
12 changes: 7 additions & 5 deletions src/bin/rustic-server.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use std::net::SocketAddr;
use std::str::FromStr;
use clap::Parser;
use anyhow::Result;
use rustic_server::{acl::Acl, auth::Auth, storage::LocalStorage, web, Opts};
use clap::Parser;
use rustic_server::log::init_tracing;
use rustic_server::{acl::Acl, auth::Auth, storage::LocalStorage, web, Opts};
use std::net::SocketAddr;
use std::str::FromStr;

#[tokio::main]
async fn main() -> Result<()> {
Expand All @@ -16,6 +16,8 @@ async fn main() -> Result<()> {
let acl = Acl::from_file(opts.append_only, opts.private_repo, opts.acl)?;

let sa = SocketAddr::from_str(&opts.listen)?;
web::web_browser(acl, auth, storage, sa, opts.tls, opts.cert, opts.key).await.unwrap();
web::web_browser(acl, auth, storage, sa, opts.tls, opts.cert, opts.key)
.await
.unwrap();
Ok(())
}
2 changes: 2 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pub mod auth_file;
pub mod server_config;
File renamed without changes.
2 changes: 1 addition & 1 deletion src/config/auth_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,10 +144,10 @@ impl Display for Credential {
#[cfg(test)]
mod test {
use crate::auth::{Auth, AuthChecker};
use crate::config::auth_file::HtAccess;
use anyhow::Result;
use std::fs;
use std::path::Path;
use crate::config::auth_file::HtAccess;

#[test]
fn test_htaccess() -> Result<()> {
Expand Down
4 changes: 2 additions & 2 deletions src/config/server_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,15 +70,15 @@ impl ServerConfig {
#[cfg(test)]
mod test {
use super::Server;
use crate::config::server_config::{AccessControl, Authorization, Repos, ServerConfig, TLS};
use std::fs;
use std::path::Path;
use crate::config::server_config::{AccessControl, Authorization, Repos, ServerConfig, TLS};

#[test]
fn test_file_read() {
let config_path = Path::new("test_data").join("rustic_server.toml");
let config = ServerConfig::from_file(&config_path);
assert!( config.is_ok());
assert!(config.is_ok());

let config = config.unwrap();
assert_eq!(config.server.host_dns_name, "127.0.0.1");
Expand Down
Loading

0 comments on commit 916740f

Please sign in to comment.