arks-server 1.3.6

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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
//! Serve operations P1 per `.spec/sot/serve-operations.sot.md`:
//! - O-6: Structured JSON access logs (`ARKS_LOG_FORMAT=json`), `X-Request-Id`, W3C `traceparent`.
//! - O-7: Persistent atomic file-backed job queue (`arks-forge/jobs/`).
//! - O-9: Typed TOML config (`--config arks.toml`), `arks serve config check`, `*_FILE` secret loader.

use crate::http::{HttpRequest, HttpResponse};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};

static TRACE_SEQ: AtomicU64 = AtomicU64::new(1);

fn now_unix_i64() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0)
}

fn now_unix_nanos() -> u128 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0)
}

/// Request correlation context (O-6): `X-Request-Id` and W3C `traceparent`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RequestTrace {
    pub request_id: String,
    pub traceparent: String,
}

impl RequestTrace {
    pub fn from_request(req: &HttpRequest) -> Self {
        let seq = TRACE_SEQ.fetch_add(1, Ordering::Relaxed);
        let nanos = now_unix_nanos();
        let request_id = req
            .header("x-request-id")
            .map(sanitize_header_val)
            .filter(|v| !v.is_empty())
            .unwrap_or_else(|| format!("req_{nanos:016x}_{seq:04x}"));
        let traceparent = req
            .header("traceparent")
            .map(sanitize_header_val)
            .filter(|v| is_valid_traceparent(v))
            .unwrap_or_else(|| {
                let trace_id = format!("{nanos:032x}");
                let span_id = format!("{seq:016x}");
                format!("00-{trace_id}-{span_id}-01")
            });
        Self {
            request_id,
            traceparent,
        }
    }

    pub fn attach_headers(&self, resp: &mut HttpResponse) {
        if !resp
            .extra_headers
            .iter()
            .any(|(k, _)| k.eq_ignore_ascii_case("x-request-id"))
        {
            resp.extra_headers
                .push(("X-Request-Id".into(), self.request_id.clone()));
        }
        if !resp
            .extra_headers
            .iter()
            .any(|(k, _)| k.eq_ignore_ascii_case("traceparent"))
        {
            resp.extra_headers
                .push(("traceparent".into(), self.traceparent.clone()));
        }
    }
}

fn sanitize_header_val(raw: &str) -> String {
    raw.chars()
        .filter(|&c| c.is_ascii_graphic() || c == ' ')
        .take(128)
        .collect::<String>()
        .trim()
        .to_string()
}

fn is_valid_traceparent(s: &str) -> bool {
    let parts: Vec<&str> = s.split('-').collect();
    parts.len() == 4
        && parts[0].len() == 2
        && parts[1].len() == 32
        && parts[2].len() == 16
        && parts[3].len() == 2
        && parts
            .iter()
            .all(|p| p.bytes().all(|b| b.is_ascii_hexdigit()))
}

/// Emit a single-line JSON access log record when `ARKS_LOG_FORMAT=json` (O-6).
pub fn maybe_emit_json_access_log(
    trace: &RequestTrace,
    req: &HttpRequest,
    status: u16,
    duration_ms: u128,
) {
    let fmt = std::env::var("ARKS_LOG_FORMAT").unwrap_or_default();
    if !fmt.eq_ignore_ascii_case("json") {
        return;
    }
    let line = format_json_access_log(trace, req, status, duration_ms);
    eprintln!("{line}");
}

pub fn format_json_access_log(
    trace: &RequestTrace,
    req: &HttpRequest,
    status: u16,
    duration_ms: u128,
) -> String {
    serde_json::json!({
        "ts": now_unix_i64(),
        "level": if status >= 500 { "error" } else if status >= 400 { "warn" } else { "info" },
        "request_id": trace.request_id,
        "traceparent": trace.traceparent,
        "method": req.method,
        "path": req.path,
        "status": status,
        "duration_ms": duration_ms,
        "client_ip": req.client_ip().unwrap_or(""),
    })
    .to_string()
}

// ---------------------------------------------------------------------------
// O-7: Persistent atomic file-backed job queue (`<git_dir>/arks-forge/jobs/`)
// ---------------------------------------------------------------------------

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum JobStatus {
    Pending,
    Completed,
    DeadLetter,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct JobRecord {
    pub id: String,
    pub kind: String,
    pub payload: serde_json::Value,
    pub status: JobStatus,
    pub attempts: u32,
    pub max_attempts: u32,
    pub next_run_at: i64,
    #[serde(default)]
    pub last_error: Option<String>,
    pub created_at: i64,
}

fn jobs_dir(git_dir: &Path) -> PathBuf {
    git_dir.join("arks-forge").join("jobs")
}

/// Atomically persist a new background job into `<git_dir>/arks-forge/jobs/<id>.json`.
pub fn enqueue_job(
    git_dir: &Path,
    kind: &str,
    payload: serde_json::Value,
    max_attempts: u32,
) -> std::io::Result<JobRecord> {
    let dir = jobs_dir(git_dir);
    fs::create_dir_all(&dir)?;
    let seq = TRACE_SEQ.fetch_add(1, Ordering::Relaxed);
    let now = now_unix_i64();
    let id = format!("job_{}_{:04x}", now_unix_nanos(), seq);
    let rec = JobRecord {
        id: id.clone(),
        kind: kind.to_string(),
        payload,
        status: JobStatus::Pending,
        attempts: 0,
        max_attempts: max_attempts.max(1),
        next_run_at: now,
        last_error: None,
        created_at: now,
    };
    write_job_atomic(&dir, &rec)?;
    Ok(rec)
}

fn write_job_atomic(dir: &Path, rec: &JobRecord) -> std::io::Result<()> {
    let target = dir.join(format!("{}.json", rec.id));
    let tmp = dir.join(format!("{}.json.tmp", rec.id));
    let bytes = serde_json::to_vec_pretty(rec).unwrap_or_else(|_| b"{}".to_vec());
    fs::write(&tmp, bytes)?;
    fs::rename(&tmp, &target)?;
    Ok(())
}

/// List all persisted jobs in `<git_dir>/arks-forge/jobs/`.
pub fn list_jobs(git_dir: &Path) -> Vec<JobRecord> {
    let dir = jobs_dir(git_dir);
    let Ok(rd) = fs::read_dir(&dir) else {
        return Vec::new();
    };
    let mut out = Vec::new();
    for entry in rd.flatten() {
        let p = entry.path();
        if p.extension().and_then(|e| e.to_str()) != Some("json") {
            continue;
        }
        if let Ok(bytes) = fs::read(&p) {
            if let Ok(rec) = serde_json::from_slice::<JobRecord>(&bytes) {
                out.push(rec);
            }
        }
    }
    out.sort_by_key(|j| j.created_at);
    out
}

/// Claim due pending jobs (`next_run_at <= now`) and return them.
pub fn due_jobs(git_dir: &Path, now: i64) -> Vec<JobRecord> {
    list_jobs(git_dir)
        .into_iter()
        .filter(|j| j.status == JobStatus::Pending && j.next_run_at <= now)
        .collect()
}

/// Mark a job completed and persist atomically.
pub fn complete_job(git_dir: &Path, mut rec: JobRecord) -> std::io::Result<JobRecord> {
    rec.status = JobStatus::Completed;
    rec.attempts = rec.attempts.saturating_add(1);
    rec.last_error = None;
    let dir = jobs_dir(git_dir);
    fs::create_dir_all(&dir)?;
    write_job_atomic(&dir, &rec)?;
    Ok(rec)
}

/// Record a failed attempt with capped exponential backoff (`2^attempts * 5s`, max 3600s),
/// transitioning to `DeadLetter` once `attempts >= max_attempts`.
pub fn fail_job_with_backoff(
    git_dir: &Path,
    mut rec: JobRecord,
    err: &str,
    now: i64,
) -> std::io::Result<JobRecord> {
    rec.attempts = rec.attempts.saturating_add(1);
    rec.last_error = Some(err.to_string());
    if rec.attempts >= rec.max_attempts {
        rec.status = JobStatus::DeadLetter;
    } else {
        let backoff = (5i64.saturating_mul(1i64 << rec.attempts.min(10))).min(3600);
        rec.next_run_at = now.saturating_add(backoff);
    }
    let dir = jobs_dir(git_dir);
    fs::create_dir_all(&dir)?;
    write_job_atomic(&dir, &rec)?;
    Ok(rec)
}

// ---------------------------------------------------------------------------
// O-9: Typed config (`--config arks.toml`), `config check`, and `*_FILE` secrets
// ---------------------------------------------------------------------------

/// Resolve a secret from `<VAR>_FILE` (trimmed file contents) first, falling back to `<VAR>`.
pub fn resolve_secret_env(var_name: &str) -> Option<String> {
    let file_var = format!("{var_name}_FILE");
    if let Ok(path) = std::env::var(&file_var) {
        let trimmed_path = path.trim();
        if !trimmed_path.is_empty() {
            if let Ok(contents) = fs::read_to_string(trimmed_path) {
                let secret = contents.trim().to_string();
                if !secret.is_empty() {
                    return Some(secret);
                }
            }
        }
    }
    std::env::var(var_name)
        .ok()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ServeConfig {
    pub bind: String,
    pub shutdown_grace_secs: u64,
    pub trusted_proxies: Vec<String>,
    pub log_format: String,
    pub pwa: bool,
    pub api_rate_limit_per_min: u32,
    pub max_body_bytes: usize,
    pub metrics_token: Option<String>,
    pub security_contact: Option<String>,
    pub security_expires: Option<String>,
}

impl Default for ServeConfig {
    fn default() -> Self {
        Self {
            bind: "127.0.0.1:8080".into(),
            shutdown_grace_secs: 30,
            trusted_proxies: vec!["127.0.0.1/32".into(), "::1/128".into()],
            log_format: "text".into(),
            pwa: true,
            api_rate_limit_per_min: crate::web::api::standards::DEFAULT_API_RATE_LIMIT_PER_MIN,
            max_body_bytes: crate::web::api::standards::DEFAULT_MAX_BODY_BYTES,
            metrics_token: None,
            security_contact: None,
            security_expires: None,
        }
    }
}

impl ServeConfig {
    /// Parse a minimal TOML config file (zero external TOML crate dependency).
    pub fn from_toml_str(src: &str) -> Result<Self, String> {
        let mut cfg = Self::default();
        let mut section = String::new();
        let mut unknown_keys: Vec<String> = Vec::new();
        for (line_no, raw_line) in src.lines().enumerate() {
            let line = raw_line.split('#').next().unwrap_or("").trim();
            if line.is_empty() {
                continue;
            }
            if line.starts_with('[') && line.ends_with(']') {
                section = line[1..line.len() - 1].trim().to_string();
                continue;
            }
            let Some((k, v)) = line.split_once('=') else {
                return Err(format!("line {}: expected `key = value`", line_no + 1));
            };
            let key = k.trim();
            let val = v.trim();
            let full = if section.is_empty() {
                key.to_string()
            } else {
                format!("{section}.{key}")
            };
            match full.as_str() {
                "server.bind" => cfg.bind = parse_toml_string(val)?,
                "server.shutdown_grace_secs" => {
                    cfg.shutdown_grace_secs = val.parse::<u64>().map_err(|e| {
                        format!("line {}: invalid shutdown_grace_secs: {e}", line_no + 1)
                    })?;
                }
                "server.trusted_proxies" => {
                    cfg.trusted_proxies = parse_toml_string_array(val)?;
                }
                "ops.log_format" => cfg.log_format = parse_toml_string(val)?,
                "ops.metrics_token" => cfg.metrics_token = Some(parse_toml_string(val)?),
                "web.pwa" => {
                    cfg.pwa = parse_toml_bool(val)
                        .ok_or_else(|| format!("line {}: invalid bool for web.pwa", line_no + 1))?;
                }
                "web.security_contact" => cfg.security_contact = Some(parse_toml_string(val)?),
                "web.security_expires" => cfg.security_expires = Some(parse_toml_string(val)?),
                "api.rate_limit_per_min" => {
                    cfg.api_rate_limit_per_min = val.parse::<u32>().map_err(|e| {
                        format!("line {}: invalid api.rate_limit_per_min: {e}", line_no + 1)
                    })?;
                }
                "storage.max_body_bytes" => {
                    cfg.max_body_bytes = val.parse::<usize>().map_err(|e| {
                        format!("line {}: invalid storage.max_body_bytes: {e}", line_no + 1)
                    })?;
                }
                other => unknown_keys.push(format!("line {}: unknown key `{other}`", line_no + 1)),
            }
        }
        if !unknown_keys.is_empty() {
            return Err(unknown_keys.join("; "));
        }
        cfg.validate()?;
        Ok(cfg)
    }

    pub fn from_file(path: &Path) -> Result<Self, String> {
        let src = fs::read_to_string(path)
            .map_err(|e| format!("cannot read config {}: {e}", path.display()))?;
        Self::from_toml_str(&src)
    }

    pub fn validate(&self) -> Result<(), String> {
        if self.bind.trim().is_empty() || !self.bind.contains(':') {
            return Err(format!(
                "invalid server.bind `{}` (expected host:port)",
                self.bind
            ));
        }
        if !matches!(self.log_format.as_str(), "text" | "json") {
            return Err(format!(
                "invalid ops.log_format `{}` (expected `text` or `json`)",
                self.log_format
            ));
        }
        for cidr in &self.trusted_proxies {
            let (ip_str, prefix) = match cidr.split_once('/') {
                Some((a, b)) => (a.trim(), Some(b.trim())),
                None => (cidr.trim(), None),
            };
            let ip: std::net::IpAddr = ip_str
                .parse()
                .map_err(|_| format!("invalid IP in server.trusted_proxies: `{cidr}`"))?;
            if let Some(p) = prefix {
                let bits: u8 = p.parse().map_err(|_| {
                    format!("invalid CIDR prefix in server.trusted_proxies: `{cidr}`")
                })?;
                let max_bits = if ip.is_ipv4() { 32 } else { 128 };
                if bits > max_bits {
                    return Err(format!(
                        "CIDR prefix out of range in server.trusted_proxies: `{cidr}`"
                    ));
                }
            }
        }
        Ok(())
    }

    pub fn summary_map(&self) -> BTreeMap<&'static str, String> {
        let mut m = BTreeMap::new();
        m.insert("server.bind", self.bind.clone());
        m.insert(
            "server.shutdown_grace_secs",
            self.shutdown_grace_secs.to_string(),
        );
        m.insert("ops.log_format", self.log_format.clone());
        m.insert("web.pwa", self.pwa.to_string());
        m.insert(
            "api.rate_limit_per_min",
            self.api_rate_limit_per_min.to_string(),
        );
        m.insert("storage.max_body_bytes", self.max_body_bytes.to_string());
        m
    }
}

fn parse_toml_string(val: &str) -> Result<String, String> {
    let trimmed = val.trim();
    if trimmed.len() >= 2
        && ((trimmed.starts_with('"') && trimmed.ends_with('"'))
            || (trimmed.starts_with('\'') && trimmed.ends_with('\'')))
    {
        Ok(trimmed[1..trimmed.len() - 1].to_string())
    } else {
        Err(format!("expected quoted string, got `{trimmed}`"))
    }
}

fn parse_toml_bool(val: &str) -> Option<bool> {
    match val.trim() {
        "true" => Some(true),
        "false" => Some(false),
        _ => None,
    }
}

fn parse_toml_string_array(val: &str) -> Result<Vec<String>, String> {
    let trimmed = val.trim();
    if !trimmed.starts_with('[') || !trimmed.ends_with(']') {
        return Err(format!("expected array [...], got `{trimmed}`"));
    }
    let inner = trimmed[1..trimmed.len() - 1].trim();
    if inner.is_empty() {
        return Ok(Vec::new());
    }
    let mut out = Vec::new();
    for part in inner.split(',') {
        let item = part.trim();
        if !item.is_empty() {
            out.push(parse_toml_string(item)?);
        }
    }
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn request_trace_propagates_or_generates_id_and_traceparent() {
        let req = HttpRequest::new("GET", "/api/v1/issues", "", Vec::new());
        let tr = RequestTrace::from_request(&req);
        assert!(tr.request_id.starts_with("req_"));
        assert!(is_valid_traceparent(&tr.traceparent));

        let custom_tp = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01";
        let req2 = HttpRequest::new("GET", "/api/v1/issues", "", Vec::new())
            .with_header("X-Request-Id", "custom-123")
            .with_header("traceparent", custom_tp);
        let tr2 = RequestTrace::from_request(&req2);
        assert_eq!(tr2.request_id, "custom-123");
        assert_eq!(tr2.traceparent, custom_tp);

        let log_json: serde_json::Value =
            serde_json::from_str(&format_json_access_log(&tr2, &req2, 200, 12)).unwrap();
        assert_eq!(log_json["request_id"], "custom-123");
        assert_eq!(log_json["status"], 200);
    }

    #[test]
    fn persistent_job_queue_enqueue_retry_backoff_and_dead_letter() {
        let dir = tempfile::TempDir::new().unwrap();
        let job = enqueue_job(
            dir.path(),
            "webhook.deliver",
            serde_json::json!({"id": 1}),
            2,
        )
        .unwrap();
        assert_eq!(due_jobs(dir.path(), job.created_at + 1).len(), 1);

        let after_fail = fail_job_with_backoff(dir.path(), job, "502 bad gateway", 1000).unwrap();
        assert_eq!(after_fail.status, JobStatus::Pending);
        assert_eq!(after_fail.attempts, 1);
        assert!(after_fail.next_run_at > 1000);
        assert!(due_jobs(dir.path(), 1001).is_empty());

        let dead = fail_job_with_backoff(dir.path(), after_fail, "timeout", 2000).unwrap();
        assert_eq!(dead.status, JobStatus::DeadLetter);
        assert_eq!(list_jobs(dir.path()).len(), 1);
    }

    #[test]
    fn typed_serve_config_parses_and_rejects_unknown_keys() {
        let cfg = ServeConfig::from_toml_str(
            r#"
            [server]
            bind = "0.0.0.0:8080"
            shutdown_grace_secs = 45
            trusted_proxies = ["10.0.0.0/8", "127.0.0.1/32"]

            [ops]
            log_format = "json"

            [web]
            pwa = false

            [api]
            rate_limit_per_min = 600
            "#,
        )
        .unwrap();
        assert_eq!(cfg.bind, "0.0.0.0:8080");
        assert_eq!(cfg.shutdown_grace_secs, 45);
        assert!(!cfg.pwa);
        assert_eq!(cfg.log_format, "json");
        assert_eq!(cfg.api_rate_limit_per_min, 600);

        assert!(ServeConfig::from_toml_str("[server]\nunknown_opt = 1\n").is_err());
        assert!(ServeConfig::from_toml_str("[ops]\nlog_format = \"xml\"\n").is_err());
    }
}