use crate::http::{HttpRequest, HttpResponse};
use crate::web_ui::store::ForgeStore;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::{BufRead, BufReader, Write};
use std::net::TcpStream;
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
fn now_unix_i64() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SmtpConfig {
pub host: String,
pub port: u16,
pub from: String,
}
impl SmtpConfig {
pub fn from_env() -> Option<Self> {
let host = std::env::var("ARKS_SMTP_HOST").ok()?.trim().to_string();
if host.is_empty() {
return None;
}
let port = std::env::var("ARKS_SMTP_PORT")
.ok()
.and_then(|v| v.trim().parse::<u16>().ok())
.unwrap_or(25);
let from = std::env::var("ARKS_SMTP_FROM")
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "arks@localhost".into());
Some(Self { host, port, from })
}
}
pub fn send_smtp_email(
cfg: &SmtpConfig,
to: &str,
subject: &str,
body: &str,
) -> Result<(), String> {
let addr = format!("{}:{}", cfg.host, cfg.port);
let stream = TcpStream::connect(&addr).map_err(|e| format!("smtp connect {addr}: {e}"))?;
let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
let _ = stream.set_write_timeout(Some(Duration::from_secs(5)));
let mut writer = stream.try_clone().map_err(|e| e.to_string())?;
let mut reader = BufReader::new(stream);
let read_code = |r: &mut BufReader<TcpStream>| -> Result<u16, String> {
let mut line = String::new();
r.read_line(&mut line).map_err(|e| e.to_string())?;
line.get(0..3)
.and_then(|c| c.parse::<u16>().ok())
.ok_or_else(|| format!("unexpected smtp reply: {}", line.trim()))
};
let greet = read_code(&mut reader)?;
if greet != 220 {
return Err(format!("smtp greeting failed: {greet}"));
}
for (cmd, ok_codes) in [
("HELO arks.local\r\n".to_string(), &[250u16][..]),
(format!("MAIL FROM:<{}>\r\n", cfg.from), &[250][..]),
(format!("RCPT TO:<{to}>\r\n"), &[250, 251][..]),
("DATA\r\n".to_string(), &[354][..]),
] {
writer
.write_all(cmd.as_bytes())
.map_err(|e| e.to_string())?;
let code = read_code(&mut reader)?;
if !ok_codes.contains(&code) {
return Err(format!("smtp command rejected ({code})"));
}
}
let clean_subj: String = subject
.chars()
.filter(|&c| c != '\r' && c != '\n')
.collect();
let msg = format!(
"From: {}\r\nTo: {to}\r\nSubject: {clean_subj}\r\n\r\n{body}\r\n.\r\n",
cfg.from
);
writer
.write_all(msg.as_bytes())
.map_err(|e| e.to_string())?;
let data_code = read_code(&mut reader)?;
if data_code != 250 {
return Err(format!("smtp DATA rejected ({data_code})"));
}
let _ = writer.write_all(b"QUIT\r\n");
Ok(())
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ActionsRunnerConfig {
pub enabled: bool,
pub mode: String,
pub container_image: String,
pub timeout_secs: u64,
pub memory_mb: u64,
}
impl Default for ActionsRunnerConfig {
fn default() -> Self {
Self {
enabled: false,
mode: "external-container".into(),
container_image: String::new(),
timeout_secs: 600,
memory_mb: 1024,
}
}
}
impl ActionsRunnerConfig {
pub fn validate(&self) -> Result<(), String> {
if !self.enabled {
return Ok(());
}
if self.mode != "external-container" {
return Err(format!(
"unsupported actions runner mode `{}` (only `external-container` is supported)",
self.mode
));
}
if self.container_image.trim().is_empty() {
return Err("actions.container_image must be set when actions.enabled = true".into());
}
if self.timeout_secs == 0 || self.memory_mb == 0 {
return Err("actions timeout_secs and memory_mb must be > 0".into());
}
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct MirrorConfig {
pub name: String,
pub direction: String, pub remote_url: String,
pub interval_secs: u64,
#[serde(default)]
pub enabled: bool,
}
pub fn prune_audit_log(store: &mut ForgeStore, retention_days: u64, now: i64) -> usize {
if retention_days == 0 {
return 0;
}
let cutoff = now.saturating_sub((retention_days as i64).saturating_mul(86_400));
let before = store.audit_log.len();
store.audit_log.retain(|e| e.created_at >= cutoff);
before.saturating_sub(store.audit_log.len())
}
pub fn format_syslog_rfc5424(
hostname: &str,
actor: &str,
action: &str,
detail: &str,
ts_unix: i64,
) -> String {
let clean = |s: &str| {
s.chars()
.filter(|&c| c != '\r' && c != '\n' && c != '\0')
.collect::<String>()
};
format!(
"<86>1 {ts_unix} {} arks-serve - {} - actor={} {}",
clean(hostname),
clean(action),
clean(actor),
clean(detail)
)
}
#[derive(Clone)]
struct CachedIdempotency {
status: u16,
content_type: String,
body: Vec<u8>,
expires_at: i64,
}
static IDEMPOTENCY_CACHE: OnceLock<Mutex<HashMap<String, CachedIdempotency>>> = OnceLock::new();
pub fn lookup_idempotency(key: &str, path: &str) -> Option<HttpResponse> {
let now = now_unix_i64();
let cache = IDEMPOTENCY_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
let mut guard = cache.lock().ok()?;
guard.retain(|_, v| v.expires_at > now);
let entry = guard.get(&format!("{path}:{key}"))?;
Some(HttpResponse {
status: entry.status,
content_type: entry.content_type.clone(),
body: entry.body.clone(),
www_authenticate: None,
extra_headers: vec![("Idempotency-Replayed".into(), "true".into())],
})
}
pub fn store_idempotency(key: &str, path: &str, resp: &HttpResponse) {
let now = now_unix_i64();
let cache = IDEMPOTENCY_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
if let Ok(mut guard) = cache.lock() {
guard.insert(
format!("{path}:{key}"),
CachedIdempotency {
status: resp.status,
content_type: resp.content_type.clone(),
body: resp.body.clone(),
expires_at: now + 86_400,
},
);
}
}
pub fn apply_cors_allowlist(req: &HttpRequest, resp: &mut HttpResponse, allowlist: &[String]) {
let Some(origin) = req.origin.as_deref().map(str::trim) else {
return;
};
if allowlist.iter().any(|allowed| allowed.trim() == origin) {
resp.extra_headers
.push(("Access-Control-Allow-Origin".into(), origin.to_string()));
resp.extra_headers.push(("Vary".into(), "Origin".into()));
resp.extra_headers.push((
"Access-Control-Allow-Methods".into(),
"GET, POST, PATCH, PUT, DELETE, OPTIONS".into(),
));
resp.extra_headers.push((
"Access-Control-Allow-Headers".into(),
"Authorization, Content-Type, If-Match, If-None-Match, Idempotency-Key".into(),
));
}
}
pub fn t_label(lang: &str, key: &str) -> &'static str {
let is_de = lang.to_ascii_lowercase().starts_with("de");
match (is_de, key) {
(true, "code") => "Quellcode",
(true, "issues") => "Aufgaben",
(true, "pulls") => "Pull-Anfragen",
(true, "releases") => "Veroeffentlichungen",
(true, "settings") => "Einstellungen",
(_, "code") => "Code",
(_, "issues") => "Issues",
(_, "pulls") => "Pull Requests",
(_, "releases") => "Releases",
(_, "settings") => "Settings",
_ => "",
}
}
pub fn render_time_el(iso_utc: &str, display: &str) -> String {
format!("<time datetime=\"{iso_utc}\">{display}</time>")
}
pub fn render_atom_feed(title: &str, feed_id: &str, entries: &[(String, String, i64)]) -> String {
let mut xml = format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<feed xmlns=\"http://www.w3.org/2005/Atom\">\n <title>{title}</title>\n <id>{feed_id}</id>\n"
);
for (id, entry_title, ts) in entries {
xml.push_str(&format!(
" <entry><id>{id}</id><title>{entry_title}</title><updated>{ts}</updated></entry>\n"
));
}
xml.push_str("</feed>\n");
xml
}
#[cfg(test)]
mod tests {
use super::*;
use crate::web_ui::store::AuditEntry;
#[test]
fn actions_runner_defaults_disabled_and_validates_external_container() {
let def = ActionsRunnerConfig::default();
assert!(!def.enabled);
assert!(def.validate().is_ok());
let bad = ActionsRunnerConfig {
enabled: true,
mode: "in-process".into(),
container_image: "alpine:3.20".into(),
..Default::default()
};
assert!(bad.validate().is_err());
let good = ActionsRunnerConfig {
enabled: true,
mode: "external-container".into(),
container_image: "ghcr.io/modootoday/arks-runner:v1".into(),
..Default::default()
};
assert!(good.validate().is_ok());
}
#[test]
fn audit_retention_prunes_old_entries_and_formats_rfc5424_syslog() {
let mut store = ForgeStore::default();
store.audit_log.push(AuditEntry {
id: 1,
created_at: 1000,
actor: "alice".into(),
action: "old".into(),
target: "x".into(),
});
store.audit_log.push(AuditEntry {
id: 2,
created_at: 900_000,
actor: "alice".into(),
action: "recent".into(),
target: "y".into(),
});
let pruned = prune_audit_log(&mut store, 7, 1_000_000);
assert_eq!(pruned, 1);
assert_eq!(store.audit_log.len(), 1);
let line = format_syslog_rfc5424("forge01", "alice", "auth.login", "ip=127.0.0.1", 1000);
assert!(line.starts_with("<86>1 1000 forge01 arks-serve - auth.login - actor=alice "));
}
#[test]
fn idempotency_cache_cors_allowlist_and_atom_feed() {
let resp = HttpResponse {
status: 201,
content_type: "application/json".into(),
body: br#"{"id":42}"#.to_vec(),
www_authenticate: None,
extra_headers: Vec::new(),
};
store_idempotency("idem-1", "/api/v1/issues", &resp);
let hit = lookup_idempotency("idem-1", "/api/v1/issues").unwrap();
assert_eq!(hit.status, 201);
assert!(
hit.extra_headers
.iter()
.any(|(k, v)| k == "Idempotency-Replayed" && v == "true")
);
let mut req = HttpRequest::new("GET", "/api/v1/issues", "", Vec::new());
req.origin = Some("https://app.example.com".into());
let mut r2 = resp.clone();
apply_cors_allowlist(&req, &mut r2, &["https://app.example.com".into()]);
assert!(
r2.extra_headers
.iter()
.any(|(k, v)| k == "Access-Control-Allow-Origin" && v == "https://app.example.com")
);
let feed = render_atom_feed(
"Releases",
"urn:arks:releases",
&[("1".into(), "v1.0.0".into(), 100)],
);
assert!(feed.contains("http://www.w3.org/2005/Atom"));
assert!(feed.contains("v1.0.0"));
assert_eq!(t_label("en", "issues"), "Issues");
assert!(render_time_el("2026-01-01T00:00:00Z", "Jan 1").contains("<time datetime="));
}
#[test]
fn smtp_client_delivers_to_mock_loopback_server() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let handle = std::thread::spawn(move || {
let (mut sock, _) = listener.accept().unwrap();
let _ = sock.write_all(b"220 mock.local ESMTP\r\n");
let mut r = BufReader::new(sock.try_clone().unwrap());
let mut line = String::new();
for reply in [
b"250 ok\r\n".as_slice(),
b"250 ok\r\n",
b"250 ok\r\n",
b"354 go\r\n",
] {
line.clear();
let _ = r.read_line(&mut line);
let _ = sock.write_all(reply);
}
loop {
line.clear();
if r.read_line(&mut line).unwrap_or(0) == 0 || line == ".\r\n" {
break;
}
}
let _ = sock.write_all(b"250 queued\r\n");
});
let cfg = SmtpConfig {
host: "127.0.0.1".into(),
port,
from: "arks@example.invalid".into(),
};
send_smtp_email(&cfg, "dev@example.invalid", "Alert", "Hello").unwrap();
handle.join().unwrap();
}
}