Skip to main content

arks_server/
ops_p2.rs

1//! Wave E4 P2 operations & API/Web extensions per
2//! `.spec/sot/serve-operations.sot.md` and `.spec/sot/rest-api-standards.sot.md`:
3//! - O-11: Native SMTP email notification client from `arks serve` (`ARKS_SMTP_HOST`).
4//! - O-12: Actions external container-runner typed config (default disabled; zero `unsafe`).
5//! - O-13: Mirror records, audit retention pruning, RFC 5424 syslog formatter.
6//! - P-8: `Idempotency-Key` replay cache, CORS allowlist (`ARKS_CORS_ORIGINS`),
7//!   minimal i18n catalog (`en`/`de`) + `<time datetime>` helper, Atom feed builder.
8
9use crate::http::{HttpRequest, HttpResponse};
10use crate::web_ui::store::ForgeStore;
11use serde::{Deserialize, Serialize};
12use std::collections::HashMap;
13use std::io::{BufRead, BufReader, Write};
14use std::net::TcpStream;
15use std::sync::{Mutex, OnceLock};
16use std::time::{Duration, SystemTime, UNIX_EPOCH};
17
18fn now_unix_i64() -> i64 {
19    SystemTime::now()
20        .duration_since(UNIX_EPOCH)
21        .map(|d| d.as_secs() as i64)
22        .unwrap_or(0)
23}
24
25// ---------------------------------------------------------------------------
26// O-11: Minimal SMTP notification client for `arks serve`
27// ---------------------------------------------------------------------------
28
29#[derive(Clone, Debug, PartialEq, Eq)]
30pub struct SmtpConfig {
31    pub host: String,
32    pub port: u16,
33    pub from: String,
34}
35
36impl SmtpConfig {
37    pub fn from_env() -> Option<Self> {
38        let host = std::env::var("ARKS_SMTP_HOST").ok()?.trim().to_string();
39        if host.is_empty() {
40            return None;
41        }
42        let port = std::env::var("ARKS_SMTP_PORT")
43            .ok()
44            .and_then(|v| v.trim().parse::<u16>().ok())
45            .unwrap_or(25);
46        let from = std::env::var("ARKS_SMTP_FROM")
47            .ok()
48            .map(|s| s.trim().to_string())
49            .filter(|s| !s.is_empty())
50            .unwrap_or_else(|| "arks@localhost".into());
51        Some(Self { host, port, from })
52    }
53}
54
55/// Send a plain-text notification email via minimal RFC 5321 SMTP (`HELO/MAIL/RCPT/DATA/QUIT`).
56pub fn send_smtp_email(
57    cfg: &SmtpConfig,
58    to: &str,
59    subject: &str,
60    body: &str,
61) -> Result<(), String> {
62    let addr = format!("{}:{}", cfg.host, cfg.port);
63    let stream = TcpStream::connect(&addr).map_err(|e| format!("smtp connect {addr}: {e}"))?;
64    let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
65    let _ = stream.set_write_timeout(Some(Duration::from_secs(5)));
66    let mut writer = stream.try_clone().map_err(|e| e.to_string())?;
67    let mut reader = BufReader::new(stream);
68
69    let read_code = |r: &mut BufReader<TcpStream>| -> Result<u16, String> {
70        let mut line = String::new();
71        r.read_line(&mut line).map_err(|e| e.to_string())?;
72        line.get(0..3)
73            .and_then(|c| c.parse::<u16>().ok())
74            .ok_or_else(|| format!("unexpected smtp reply: {}", line.trim()))
75    };
76
77    let greet = read_code(&mut reader)?;
78    if greet != 220 {
79        return Err(format!("smtp greeting failed: {greet}"));
80    }
81    for (cmd, ok_codes) in [
82        ("HELO arks.local\r\n".to_string(), &[250u16][..]),
83        (format!("MAIL FROM:<{}>\r\n", cfg.from), &[250][..]),
84        (format!("RCPT TO:<{to}>\r\n"), &[250, 251][..]),
85        ("DATA\r\n".to_string(), &[354][..]),
86    ] {
87        writer
88            .write_all(cmd.as_bytes())
89            .map_err(|e| e.to_string())?;
90        let code = read_code(&mut reader)?;
91        if !ok_codes.contains(&code) {
92            return Err(format!("smtp command rejected ({code})"));
93        }
94    }
95    let clean_subj: String = subject
96        .chars()
97        .filter(|&c| c != '\r' && c != '\n')
98        .collect();
99    let msg = format!(
100        "From: {}\r\nTo: {to}\r\nSubject: {clean_subj}\r\n\r\n{body}\r\n.\r\n",
101        cfg.from
102    );
103    writer
104        .write_all(msg.as_bytes())
105        .map_err(|e| e.to_string())?;
106    let data_code = read_code(&mut reader)?;
107    if data_code != 250 {
108        return Err(format!("smtp DATA rejected ({data_code})"));
109    }
110    let _ = writer.write_all(b"QUIT\r\n");
111    Ok(())
112}
113
114// ---------------------------------------------------------------------------
115// O-12: Actions external container-runner typed config (default disabled)
116// ---------------------------------------------------------------------------
117
118#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
119pub struct ActionsRunnerConfig {
120    /// Disabled by default (fail-closed).
121    pub enabled: bool,
122    /// Only `"external-container"` is permitted when enabled (no in-process unsafe namespaces).
123    pub mode: String,
124    pub container_image: String,
125    pub timeout_secs: u64,
126    pub memory_mb: u64,
127}
128
129impl Default for ActionsRunnerConfig {
130    fn default() -> Self {
131        Self {
132            enabled: false,
133            mode: "external-container".into(),
134            container_image: String::new(),
135            timeout_secs: 600,
136            memory_mb: 1024,
137        }
138    }
139}
140
141impl ActionsRunnerConfig {
142    pub fn validate(&self) -> Result<(), String> {
143        if !self.enabled {
144            return Ok(());
145        }
146        if self.mode != "external-container" {
147            return Err(format!(
148                "unsupported actions runner mode `{}` (only `external-container` is supported)",
149                self.mode
150            ));
151        }
152        if self.container_image.trim().is_empty() {
153            return Err("actions.container_image must be set when actions.enabled = true".into());
154        }
155        if self.timeout_secs == 0 || self.memory_mb == 0 {
156            return Err("actions timeout_secs and memory_mb must be > 0".into());
157        }
158        Ok(())
159    }
160}
161
162// ---------------------------------------------------------------------------
163// O-13: Mirrors, Audit retention pruning, RFC 5424 syslog formatter
164// ---------------------------------------------------------------------------
165
166#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
167pub struct MirrorConfig {
168    pub name: String,
169    pub direction: String, // "pull" | "push"
170    pub remote_url: String,
171    pub interval_secs: u64,
172    #[serde(default)]
173    pub enabled: bool,
174}
175
176/// Prune audit log entries older than `retention_days` (0 = retain forever).
177pub fn prune_audit_log(store: &mut ForgeStore, retention_days: u64, now: i64) -> usize {
178    if retention_days == 0 {
179        return 0;
180    }
181    let cutoff = now.saturating_sub((retention_days as i64).saturating_mul(86_400));
182    let before = store.audit_log.len();
183    store.audit_log.retain(|e| e.created_at >= cutoff);
184    before.saturating_sub(store.audit_log.len())
185}
186
187/// Format an audit event as an RFC 5424 syslog line (`<PRI>1 TS HOST APP PID MSGID - MSG`).
188pub fn format_syslog_rfc5424(
189    hostname: &str,
190    actor: &str,
191    action: &str,
192    detail: &str,
193    ts_unix: i64,
194) -> String {
195    // Facility 10 (security/authpriv) * 8 + Severity 6 (Informational) = 86
196    let clean = |s: &str| {
197        s.chars()
198            .filter(|&c| c != '\r' && c != '\n' && c != '\0')
199            .collect::<String>()
200    };
201    format!(
202        "<86>1 {ts_unix} {} arks-serve - {} - actor={} {}",
203        clean(hostname),
204        clean(action),
205        clean(actor),
206        clean(detail)
207    )
208}
209
210// ---------------------------------------------------------------------------
211// P-8: Idempotency-Key replay cache, CORS allowlist, i18n + <time>, Atom feed
212// ---------------------------------------------------------------------------
213
214#[derive(Clone)]
215struct CachedIdempotency {
216    status: u16,
217    content_type: String,
218    body: Vec<u8>,
219    expires_at: i64,
220}
221
222static IDEMPOTENCY_CACHE: OnceLock<Mutex<HashMap<String, CachedIdempotency>>> = OnceLock::new();
223
224/// Look up a cached response for `Idempotency-Key` on mutating POST requests (24h TTL).
225pub fn lookup_idempotency(key: &str, path: &str) -> Option<HttpResponse> {
226    let now = now_unix_i64();
227    let cache = IDEMPOTENCY_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
228    let mut guard = cache.lock().ok()?;
229    guard.retain(|_, v| v.expires_at > now);
230    let entry = guard.get(&format!("{path}:{key}"))?;
231    Some(HttpResponse {
232        status: entry.status,
233        content_type: entry.content_type.clone(),
234        body: entry.body.clone(),
235        www_authenticate: None,
236        extra_headers: vec![("Idempotency-Replayed".into(), "true".into())],
237    })
238}
239
240/// Store a response for `Idempotency-Key` (24h TTL).
241pub fn store_idempotency(key: &str, path: &str, resp: &HttpResponse) {
242    let now = now_unix_i64();
243    let cache = IDEMPOTENCY_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
244    if let Ok(mut guard) = cache.lock() {
245        guard.insert(
246            format!("{path}:{key}"),
247            CachedIdempotency {
248                status: resp.status,
249                content_type: resp.content_type.clone(),
250                body: resp.body.clone(),
251                expires_at: now + 86_400,
252            },
253        );
254    }
255}
256
257/// Check `Origin` against an exact CORS allowlist (`ARKS_CORS_ORIGINS`, comma-separated).
258/// Never reflects `*` with credentials; always attaches `Vary: Origin`.
259pub fn apply_cors_allowlist(req: &HttpRequest, resp: &mut HttpResponse, allowlist: &[String]) {
260    let Some(origin) = req.origin.as_deref().map(str::trim) else {
261        return;
262    };
263    if allowlist.iter().any(|allowed| allowed.trim() == origin) {
264        resp.extra_headers
265            .push(("Access-Control-Allow-Origin".into(), origin.to_string()));
266        resp.extra_headers.push(("Vary".into(), "Origin".into()));
267        resp.extra_headers.push((
268            "Access-Control-Allow-Methods".into(),
269            "GET, POST, PATCH, PUT, DELETE, OPTIONS".into(),
270        ));
271        resp.extra_headers.push((
272            "Access-Control-Allow-Headers".into(),
273            "Authorization, Content-Type, If-Match, If-None-Match, Idempotency-Key".into(),
274        ));
275    }
276}
277
278/// Minimal i18n UI catalog (`en` default, `de` sample) + semantic `<time datetime="...">` helper.
279pub fn t_label(lang: &str, key: &str) -> &'static str {
280    let is_de = lang.to_ascii_lowercase().starts_with("de");
281    match (is_de, key) {
282        (true, "code") => "Quellcode",
283        (true, "issues") => "Aufgaben",
284        (true, "pulls") => "Pull-Anfragen",
285        (true, "releases") => "Veroeffentlichungen",
286        (true, "settings") => "Einstellungen",
287        (_, "code") => "Code",
288        (_, "issues") => "Issues",
289        (_, "pulls") => "Pull Requests",
290        (_, "releases") => "Releases",
291        (_, "settings") => "Settings",
292        _ => "",
293    }
294}
295
296/// Render a semantic HTML5 `<time datetime="...">` element.
297pub fn render_time_el(iso_utc: &str, display: &str) -> String {
298    format!("<time datetime=\"{iso_utc}\">{display}</time>")
299}
300
301/// Build an RFC 4287 Atom 1.0 XML feed for releases or issues.
302pub fn render_atom_feed(title: &str, feed_id: &str, entries: &[(String, String, i64)]) -> String {
303    let mut xml = format!(
304        "<?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"
305    );
306    for (id, entry_title, ts) in entries {
307        xml.push_str(&format!(
308            "  <entry><id>{id}</id><title>{entry_title}</title><updated>{ts}</updated></entry>\n"
309        ));
310    }
311    xml.push_str("</feed>\n");
312    xml
313}
314
315#[cfg(test)]
316mod tests {
317    use super::*;
318    use crate::web_ui::store::AuditEntry;
319
320    #[test]
321    fn actions_runner_defaults_disabled_and_validates_external_container() {
322        let def = ActionsRunnerConfig::default();
323        assert!(!def.enabled);
324        assert!(def.validate().is_ok());
325
326        let bad = ActionsRunnerConfig {
327            enabled: true,
328            mode: "in-process".into(),
329            container_image: "alpine:3.20".into(),
330            ..Default::default()
331        };
332        assert!(bad.validate().is_err());
333
334        let good = ActionsRunnerConfig {
335            enabled: true,
336            mode: "external-container".into(),
337            container_image: "ghcr.io/modootoday/arks-runner:v1".into(),
338            ..Default::default()
339        };
340        assert!(good.validate().is_ok());
341    }
342
343    #[test]
344    fn audit_retention_prunes_old_entries_and_formats_rfc5424_syslog() {
345        let mut store = ForgeStore::default();
346        store.audit_log.push(AuditEntry {
347            id: 1,
348            created_at: 1000,
349            actor: "alice".into(),
350            action: "old".into(),
351            target: "x".into(),
352        });
353        store.audit_log.push(AuditEntry {
354            id: 2,
355            created_at: 900_000,
356            actor: "alice".into(),
357            action: "recent".into(),
358            target: "y".into(),
359        });
360        let pruned = prune_audit_log(&mut store, 7, 1_000_000);
361        assert_eq!(pruned, 1);
362        assert_eq!(store.audit_log.len(), 1);
363
364        let line = format_syslog_rfc5424("forge01", "alice", "auth.login", "ip=127.0.0.1", 1000);
365        assert!(line.starts_with("<86>1 1000 forge01 arks-serve - auth.login - actor=alice "));
366    }
367
368    #[test]
369    fn idempotency_cache_cors_allowlist_and_atom_feed() {
370        let resp = HttpResponse {
371            status: 201,
372            content_type: "application/json".into(),
373            body: br#"{"id":42}"#.to_vec(),
374            www_authenticate: None,
375            extra_headers: Vec::new(),
376        };
377        store_idempotency("idem-1", "/api/v1/issues", &resp);
378        let hit = lookup_idempotency("idem-1", "/api/v1/issues").unwrap();
379        assert_eq!(hit.status, 201);
380        assert!(
381            hit.extra_headers
382                .iter()
383                .any(|(k, v)| k == "Idempotency-Replayed" && v == "true")
384        );
385
386        let mut req = HttpRequest::new("GET", "/api/v1/issues", "", Vec::new());
387        req.origin = Some("https://app.example.com".into());
388        let mut r2 = resp.clone();
389        apply_cors_allowlist(&req, &mut r2, &["https://app.example.com".into()]);
390        assert!(
391            r2.extra_headers
392                .iter()
393                .any(|(k, v)| k == "Access-Control-Allow-Origin" && v == "https://app.example.com")
394        );
395
396        let feed = render_atom_feed(
397            "Releases",
398            "urn:arks:releases",
399            &[("1".into(), "v1.0.0".into(), 100)],
400        );
401        assert!(feed.contains("http://www.w3.org/2005/Atom"));
402        assert!(feed.contains("v1.0.0"));
403        assert_eq!(t_label("en", "issues"), "Issues");
404        assert!(render_time_el("2026-01-01T00:00:00Z", "Jan 1").contains("<time datetime="));
405    }
406
407    #[test]
408    fn smtp_client_delivers_to_mock_loopback_server() {
409        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
410        let port = listener.local_addr().unwrap().port();
411        let handle = std::thread::spawn(move || {
412            let (mut sock, _) = listener.accept().unwrap();
413            let _ = sock.write_all(b"220 mock.local ESMTP\r\n");
414            let mut r = BufReader::new(sock.try_clone().unwrap());
415            let mut line = String::new();
416            for reply in [
417                b"250 ok\r\n".as_slice(),
418                b"250 ok\r\n",
419                b"250 ok\r\n",
420                b"354 go\r\n",
421            ] {
422                line.clear();
423                let _ = r.read_line(&mut line);
424                let _ = sock.write_all(reply);
425            }
426            loop {
427                line.clear();
428                if r.read_line(&mut line).unwrap_or(0) == 0 || line == ".\r\n" {
429                    break;
430                }
431            }
432            let _ = sock.write_all(b"250 queued\r\n");
433        });
434        let cfg = SmtpConfig {
435            host: "127.0.0.1".into(),
436            port,
437            from: "arks@example.invalid".into(),
438        };
439        send_smtp_email(&cfg, "dev@example.invalid", "Alert", "Hello").unwrap();
440        handle.join().unwrap();
441    }
442}