Skip to content

Commit

Permalink
passes tests, and restic can backup
Browse files Browse the repository at this point in the history
  • Loading branch information
raimond visser committed Jan 21, 2024
1 parent 0f9859f commit 952b2ee
Show file tree
Hide file tree
Showing 23 changed files with 369 additions and 410 deletions.
4 changes: 2 additions & 2 deletions .cargo/config.toml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# See https://doc.rust-lang.org/cargo/reference/config.html
[env]
RUST_LOG="DEBUG"
TEST_NOCAPTURE="1"
RUST_LOG = "DEBUG"
TEST_NOCAPTURE = "1"
16 changes: 8 additions & 8 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,26 +23,26 @@ algorithm = "minisign"
pubkey = "RWSWSCEJEEacVeCy0va71hlrVtiW8YzMzOyJeso0Bfy/ZXq5OryWi/8T"

[dependencies]
once_cell = "1.17"
anyhow = "1.0.75"
async-trait = "0.1"
# FIXME: Add "headers" feature to Axum?
axum = { version = "0.7.3", features = ["tracing", "multipart", "http2"] }
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"
axum-server = { version = "0.6.0", features = ["tls-rustls"] }
clap = { version = "4.4", features = ["derive"] }
#enum_dispatch = "0.3.12"
# enum_dispatch = "0.3.12"
futures = "0.3"
futures-util = "0.3"
htpasswd-verify = "0.3"
http-range = "0.1"
http-body-util = "0.1.0"
http-range = "0.1"
once_cell = "1.17"
pin-project = "1.1"
rand = "0.8.5"
serde = { version = "1", default-features=false, features = ["derive"] }
serde = { version = "1", default-features = false, features = ["derive"] }
serde_derive = "1"
thiserror = "1.0.48"
tokio = { version = "1", features = ["full"] }
Expand Down Expand Up @@ -94,8 +94,8 @@ debug-assertions = false
codegen-units = 1

[dev-dependencies]
reqwest = "0.11.18"
#serial_test = "*"
base64 = "0.21.2"
#reqwest = "0.11.18"
# serial_test = "*"
serde_json = "*"
tower = "*"
base64 = "0.21.2"
8 changes: 3 additions & 5 deletions src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,12 +84,14 @@ pub struct AuthFromRequest {
impl<S: Send + Sync> FromRequestParts<S> for AuthFromRequest {
type Rejection = ErrorKind;

// FIXME: We also have a configuration flag do run without authentication
// This must be handled here too ... otherwise we get an Auth header missing error.
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();
let auth_result = AuthBasic::from_request_parts(parts, state).await;
tracing::debug!("Got authentication result ...:{:?}", &auth_result);
return match auth_result {
Ok(auth) => {
Expand Down Expand Up @@ -253,10 +255,6 @@ mod test {
let request = Request::builder()
.uri("/rustic_server")
.method(Method::GET)
.header(
"Authorization",
basic_auth_header_value("test", Some("__test_pw")),
)
.body(Body::empty())
.unwrap();

Expand Down
1 change: 0 additions & 1 deletion src/bin/rustic-server.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use anyhow::Result;
use clap::{Parser, Subcommand};
use rustic_server::commands::serve::{serve, Opts};
use std::str::FromStr;

#[tokio::main]
async fn main() -> Result<()> {
Expand Down
23 changes: 16 additions & 7 deletions src/commands/serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,28 @@ use crate::acl::Acl;
use crate::auth::Auth;
use crate::config::server_config::ServerConfig;
use crate::error::{ErrorKind, Result};
use crate::log::init_tracing;
use crate::log::{init_trace_from, init_tracing};
use crate::storage::LocalStorage;
use crate::web::start_web_server;
use clap::Parser;
use std::net::SocketAddr;
use std::net::{SocketAddr, ToSocketAddrs};
use std::path::PathBuf;
use std::str::FromStr;

// FIXME: we should not return crate::error::Result here; maybe anyhow::Result,

pub async fn serve(opts: Opts) -> Result<()> {
init_tracing();

match &opts.config {
Some(config) => {
let config_path = PathBuf::new().join(&config);
let server_config = ServerConfig::from_file(&config_path)
.unwrap_or_else(|_| panic!("Can not load server configuration file: {}", &config));
let server_config =
ServerConfig::from_file(&config_path).unwrap_or_else(|e| panic!("{}", e));

if let Some(level) = server_config.log_level {
init_trace_from(&level);
} else {
init_tracing();
}

// Repository storage
let storage_path = PathBuf::new().join(server_config.repos.storage_path);
Expand Down Expand Up @@ -49,10 +53,15 @@ pub async fn serve(opts: Opts) -> Result<()> {
};

// Server definition
let socket = SocketAddr::from_str(&opts.listen).unwrap();
let s_addr = server_config.server;
let s_str = format!("{}:{}", s_addr.host_dns_name, s_addr.port);
tracing::debug!("[serve] Serving address: {}", &s_str);
let socket = s_str.to_socket_addrs().unwrap().next().unwrap();
start_web_server(acl, auth, storage, socket, false, None, opts.key).await
}
None => {
init_trace_from(&opts.log);

let storage = match LocalStorage::try_new(&opts.path) {
Ok(s) => s,
Err(e) => return Err(ErrorKind::InternalError(e.to_string())),
Expand Down
11 changes: 5 additions & 6 deletions src/config/auth_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,19 +31,18 @@ impl HtAccess {
}
})
}
return Ok(HtAccess {
Ok(HtAccess {
path: pth.clone(),
credentials: c,
});
})
}

pub fn get(&self, name: &str) -> Option<&Credential> {
self.credentials.get(name)
}

pub fn users(&self) -> Vec<String> {
let ret: Vec<String> = self.credentials.keys().cloned().collect();
return ret;
self.credentials.keys().cloned().collect()
}

/// Update can be used for both new, and existing credentials
Expand All @@ -62,15 +61,15 @@ impl HtAccess {
}

/// FIXME: Nicer error logging for when we can not write file ...
pub fn to_file(&mut self) -> Result<()> {
pub fn to_file(&self) -> Result<()> {
let mut file = fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(&self.path)?;

for (_n, c) in self.credentials.iter() {
file.write(c.to_line().as_bytes()).unwrap();
let _ = file.write(c.to_line().as_bytes()).unwrap();
}
Ok(())
}
Expand Down
8 changes: 4 additions & 4 deletions src/config/auth_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,20 +154,20 @@ mod test {
let htaccess_pth = Path::new("tmp_test_data").join("rustic");
fs::create_dir_all(&htaccess_pth).unwrap();

let ht_file = htaccess_pth.join(".htaccess");
let ht_file = htaccess_pth.join("htaccess");

let mut ht = HtAccess::from_file(&ht_file)?;
ht.update("Administrator", "stuff");
ht.update("backup-user", "itsme");
ht.to_file()?;

let ht = HtAccess::from_file(&ht_file)?;
assert!(ht.get(&"Administrator").is_some());
assert!(ht.get(&"backup-user").is_some());
assert!(ht.get("Administrator").is_some());
assert!(ht.get("backup-user").is_some());

let auth = Auth::from_file(false, &ht_file).unwrap();
assert!(auth.verify("Administrator", "stuff"));
assert!(auth.verify(&"backup-user", "itsme"));
assert!(auth.verify("backup-user", "itsme"));

Ok(())
}
Expand Down
13 changes: 9 additions & 4 deletions src/config/server_config.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use anyhow::{Context, Result};
use serde_derive::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;
use std::path::Path;

#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct ServerConfig {
Expand All @@ -10,6 +10,7 @@ pub struct ServerConfig {
pub tls: Option<TLS>,
pub authorization: Authorization,
pub accesscontrol: AccessControl,
pub log_level: Option<String>,
}

#[derive(Clone, Serialize, Deserialize, Debug)]
Expand Down Expand Up @@ -52,14 +53,14 @@ pub struct TLS {
}

impl ServerConfig {
pub fn from_file(pth: &PathBuf) -> Result<Self> {
let s = fs::read_to_string(&pth).context("Can not read server configuration file")?;
pub fn from_file(pth: &Path) -> Result<Self> {
let s = fs::read_to_string(pth).context("Can not read server configuration file")?;
let config: ServerConfig =
toml::from_str(&s).context("Can not convert file to server configuration")?;
Ok(config)
}

pub fn to_file(&self, pth: &PathBuf) -> Result<()> {
pub fn to_file(&self, pth: &Path) -> Result<()> {
let toml_string =
toml::to_string(&self).context("Could not serialize SeverConfig to TOML value")?;
fs::write(&pth, toml_string).context("Could not write ServerConfig to file!")?;
Expand All @@ -77,6 +78,7 @@ mod test {
#[test]
fn test_file_read() {
let config_path = Path::new("test_data").join("rustic_server.toml");
//let config_path = Path::new("/data/rustic/rustic_server.toml");
let config = ServerConfig::from_file(&config_path);
assert!(config.is_ok());

Expand Down Expand Up @@ -116,8 +118,11 @@ mod test {
append_only: true,
};

let log = "debug".to_string();

// Try to write
let config = ServerConfig {
log_level: Some(log),
server,
repos,
tls,
Expand Down
Loading

0 comments on commit 952b2ee

Please sign in to comment.