limit path scope

This commit is contained in:
JMARyA 2024-04-16 16:26:18 +02:00
parent 2cc0bfbb09
commit ef14646507
Signed by: jmarya
GPG key ID: 901B2ADDF27C2263
4 changed files with 30 additions and 15 deletions

View file

@ -12,6 +12,7 @@ mirrors = [
cache_dir = "./data"
no_cache = '.*(?:db|db\.sig)$'
only_allow = '^\/archlinux'
```
Add this to your mirrorlist:

View file

@ -14,4 +14,7 @@ cache_dir = "./data"
ttl = "180"
# Regex for paths which will never be served from cache
no_cache = '.*(?:db|db\.sig)$'
no_cache = '.*(?:db|db\.sig)$'
# Redirect only paths matching this regex to the mirrors, return 404 otherwise
only_allow = '^\/archlinux'

View file

@ -2,21 +2,17 @@ use serde::Deserialize;
use crate::proxy::Mirror;
#[derive(Debug, Deserialize)]
#[derive(Debug, Deserialize, Clone)]
pub struct Config {
pub mirrors: Vec<String>,
pub cache_dir: String,
pub no_cache: String,
pub ttl: usize,
pub only_allow: Option<String>,
}
impl Config {
pub fn to_proxy(&self) -> Mirror {
Mirror::new(
self.mirrors.clone(),
&self.cache_dir,
&self.no_cache,
self.ttl,
)
Mirror::new(self)
}
}

View file

@ -5,20 +5,28 @@ use std::{
sync::Arc,
};
use crate::config::Config;
pub struct Mirror {
mirrors: Vec<Arc<String>>,
data_dir: String,
ttl: usize,
no_cache: regex::Regex,
only_allow: Option<regex::Regex>,
config: Config,
}
impl Mirror {
pub fn new(mirrors: Vec<String>, data_dir: &str, no_cache: &str, ttl: usize) -> Self {
pub fn new(config: &Config) -> Self {
let mirrors = config.mirrors.clone();
Self {
mirrors: mirrors.into_iter().map(Arc::new).collect(),
data_dir: data_dir.to_string(),
no_cache: regex::Regex::new(no_cache).unwrap(),
ttl,
data_dir: config.cache_dir.clone(),
no_cache: regex::Regex::new(&config.no_cache).unwrap(),
only_allow: config
.only_allow
.clone()
.map(|x| regex::Regex::new(&x).unwrap()),
config: config.clone(),
}
}
@ -57,13 +65,13 @@ impl Mirror {
let current_time = std::time::SystemTime::now();
let elapsed_time = current_time.duration_since(modified).ok()?;
let threshold_duration =
std::time::Duration::from_secs((self.ttl * 60).try_into().unwrap());
std::time::Duration::from_secs((self.config.ttl * 60).try_into().unwrap());
if elapsed_time > threshold_duration {
log::info!(
"Cached file is {} minutes old. Older than TTL {}.",
(elapsed_time.as_secs() / 60),
self.ttl
self.config.ttl
);
Some(true)
} else {
@ -93,6 +101,13 @@ impl Mirror {
let p = std::path::Path::new(&path[1..]);
let p = std::path::Path::new(&self.data_dir).join(p);
// check if path is in scope
if let Some(only_allow) = &self.only_allow {
if !only_allow.is_match(path) {
return Some(HttpResponse::NotFound().finish());
}
}
// check if cache should be used
if !self.no_cache.is_match(path) || !self.is_cache_invalid(&p) {
Self::create_cache_dir(p.parent().unwrap());