arks-server 1.3.4

Git server: upload-pack / receive-pack + smart/dumb HTTP + daemon (M11/M25)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! Wave E4 P2 operations & API/Web extensions per
//! `.spec/sot/serve-operations.sot.md` and `.spec/sot/rest-api-standards.sot.md`:
//! - O-11: Native SMTP email notification client from `arks serve` (`ARKS_SMTP_HOST`).
//! - O-12: Actions external container-runner typed config (default disabled; zero `unsafe`).
//! - O-13: Mirror records, audit retention pruning, RFC 5424 syslog formatter.
//! - P-8: `Idempotency-Key` replay cache, CORS allowlist (`ARKS_CORS_ORIGINS`),
//!   minimal i18n catalog (`en`/`de`) + `<time datetime>` helper, Atom feed builder.

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)
}

// ---------------------------------------------------------------------------
// O-11: Minimal SMTP notification client for `arks serve`
// ---------------------------------------------------------------------------

#[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 })
    }
}

/// Send a plain-text notification email via minimal RFC 5321 SMTP (`HELO/MAIL/RCPT/DATA/QUIT`).
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(())
}

// ---------------------------------------------------------------------------
// O-12: Actions external container-runner typed config (default disabled)
// ---------------------------------------------------------------------------

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ActionsRunnerConfig {
    /// Disabled by default (fail-closed).
    pub enabled: bool,
    /// Only `"external-container"` is permitted when enabled (no in-process unsafe namespaces).
    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(())
    }
}

// ---------------------------------------------------------------------------
// O-13: Mirrors, Audit retention pruning, RFC 5424 syslog formatter
// ---------------------------------------------------------------------------

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct MirrorConfig {
    pub name: String,
    pub direction: String, // "pull" | "push"
    pub remote_url: String,
    pub interval_secs: u64,
    #[serde(default)]
    pub enabled: bool,
}

/// Prune audit log entries older than `retention_days` (0 = retain forever).
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())
}

/// Format an audit event as an RFC 5424 syslog line (`<PRI>1 TS HOST APP PID MSGID - MSG`).
pub fn format_syslog_rfc5424(
    hostname: &str,
    actor: &str,
    action: &str,
    detail: &str,
    ts_unix: i64,
) -> String {
    // Facility 10 (security/authpriv) * 8 + Severity 6 (Informational) = 86
    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)
    )
}

// ---------------------------------------------------------------------------
// P-8: Idempotency-Key replay cache, CORS allowlist, i18n + <time>, Atom feed
// ---------------------------------------------------------------------------

#[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();

/// Look up a cached response for `Idempotency-Key` on mutating POST requests (24h TTL).
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())],
    })
}

/// Store a response for `Idempotency-Key` (24h TTL).
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,
            },
        );
    }
}

/// Check `Origin` against an exact CORS allowlist (`ARKS_CORS_ORIGINS`, comma-separated).
/// Never reflects `*` with credentials; always attaches `Vary: Origin`.
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(),
        ));
    }
}

/// Minimal i18n UI catalog (`en` default, `de` sample) + semantic `<time datetime="...">` helper.
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",
        _ => "",
    }
}

/// Render a semantic HTML5 `<time datetime="...">` element.
pub fn render_time_el(iso_utc: &str, display: &str) -> String {
    format!("<time datetime=\"{iso_utc}\">{display}</time>")
}

/// Build an RFC 4287 Atom 1.0 XML feed for releases or issues.
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();
    }
}