arks-server 1.3.10

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
//! REST API standards helpers per `.spec/sot/rest-api-standards.sot.md`:
//! - P-3: RFC 8288 `Link` pagination (`page`/`per_page` default 30, max 100) + `X-Total-Count`.
//! - P-4: Strong `ETag` (`"sha256-..."`), `If-None-Match` (304), `If-Match` (412/428).
//! - P-5 & O-10: IETF `RateLimit-Policy` / `RateLimit` + `X-RateLimit-*` + global limiter + quotas.

use crate::http::{HttpRequest, HttpResponse};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
use std::time::{SystemTime, UNIX_EPOCH};

pub const DEFAULT_PER_PAGE: usize = 30;
pub const MAX_PER_PAGE: usize = 100;
pub const DEFAULT_API_RATE_LIMIT_PER_MIN: u32 = 10_000;
pub const DEFAULT_MAX_BODY_BYTES: usize = 64 * 1024 * 1024;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PageParams {
    pub page: usize,
    pub per_page: usize,
}

impl PageParams {
    pub fn from_query(query: &str) -> Self {
        let mut page = 1usize;
        let mut per_page = DEFAULT_PER_PAGE;
        for part in query.split('&') {
            if let Some((k, v)) = part.split_once('=') {
                match k {
                    "page" => {
                        if let Ok(p) = v.parse::<usize>() {
                            page = p.max(1);
                        }
                    }
                    "per_page" => {
                        if let Ok(pp) = v.parse::<usize>() {
                            per_page = pp.clamp(1, MAX_PER_PAGE);
                        }
                    }
                    _ => {}
                }
            }
        }
        Self { page, per_page }
    }
}

/// Slice a collection for `(page, per_page)` and return `(items, total, Link header)`.
pub fn paginate_slice<T>(items: &[T], params: PageParams) -> (&[T], usize) {
    let total = items.len();
    let start = params
        .page
        .saturating_sub(1)
        .saturating_mul(params.per_page);
    if start >= total {
        return (&items[total..total], total);
    }
    let end = start.saturating_add(params.per_page).min(total);
    (&items[start..end], total)
}

/// Format an RFC 8288 `Link` header (`rel="next"`, `rel="prev"`, `rel="first"`, `rel="last"`).
pub fn format_link_header(base_path: &str, params: PageParams, total: usize) -> Option<String> {
    let last_page = total.div_ceil(params.per_page).max(1);
    if last_page <= 1 && params.page == 1 {
        return None;
    }
    let mut links = Vec::new();
    let pp = params.per_page;
    if params.page < last_page {
        links.push(format!(
            "<{base_path}?page={}&per_page={pp}>; rel=\"next\"",
            params.page + 1
        ));
    }
    if params.page > 1 {
        let prev = (params.page - 1).min(last_page);
        links.push(format!(
            "<{base_path}?page={prev}&per_page={pp}>; rel=\"prev\""
        ));
    }
    links.push(format!("<{base_path}?page=1&per_page={pp}>; rel=\"first\""));
    links.push(format!(
        "<{base_path}?page={last_page}&per_page={pp}>; rel=\"last\""
    ));
    Some(links.join(", "))
}

/// Attach `X-Total-Count` and optional RFC 8288 `Link` pagination headers to a response.
pub fn attach_pagination_headers(
    resp: &mut HttpResponse,
    base_path: &str,
    params: PageParams,
    total: usize,
) {
    resp.extra_headers
        .push(("X-Total-Count".into(), total.to_string()));
    if let Some(link) = format_link_header(base_path, params, total) {
        resp.extra_headers.push(("Link".into(), link));
    }
}

/// Compute a strong quoted SHA-256 `ETag` (`"sha256-<16-byte-hex>"`).
pub fn compute_etag(body: &[u8]) -> String {
    let digest = Sha256::digest(body);
    let mut hex = String::with_capacity(32);
    for b in &digest[..16] {
        hex.push_str(&format!("{b:02x}"));
    }
    format!("\"sha256-{hex}\"")
}

/// Apply strong `ETag` and `If-None-Match` (304 Not Modified) conditional GET handling.
pub fn apply_etag_and_conditional_get(req: &HttpRequest, resp: &mut HttpResponse) {
    if resp.status != 200 {
        return;
    }
    let etag = compute_etag(&resp.body);
    resp.extra_headers.push(("ETag".into(), etag.clone()));
    if let Some(inm) = req.header("if-none-match") {
        let matches = inm.split(',').map(str::trim).any(|cand| {
            cand == "*" || cand == etag || cand.strip_prefix("W/") == Some(etag.as_str())
        });
        if matches {
            resp.status = 304;
            resp.body.clear();
        }
    }
}

/// Verify `If-Match` precondition on optimistic-concurrency mutations (RFC 9110 §13.1.1).
/// Returns 412 Precondition Failed on mismatch, or 428 Precondition Required when `required` is true and header is absent.
pub fn check_if_match(
    req: &HttpRequest,
    current_etag: &str,
    required: bool,
) -> Result<(), HttpResponse> {
    match req.header("if-match") {
        Some(hdr) => {
            let ok = hdr
                .split(',')
                .map(str::trim)
                .any(|cand| cand == "*" || cand == current_etag);
            if ok {
                Ok(())
            } else {
                Err(crate::web::api::problem::problem_response(
                    412,
                    "precondition-failed",
                    "Precondition Failed",
                    "If-Match ETag does not match current resource state",
                    &req.path,
                ))
            }
        }
        None if required => Err(crate::web::api::problem::problem_response(
            428,
            "precondition-required",
            "Precondition Required",
            "If-Match header is required for this update",
            &req.path,
        )),
        None => Ok(()),
    }
}

#[derive(Clone, Copy, Debug)]
pub struct RateLimitDecision {
    pub allowed: bool,
    pub limit: u32,
    pub remaining: u32,
    pub reset_secs: u64,
    pub reset_unix: u64,
}

#[derive(Default)]
struct RateWindow {
    window_start: u64,
    count: u32,
}

static GLOBAL_API_LIMITER: OnceLock<Mutex<HashMap<String, RateWindow>>> = OnceLock::new();

fn now_unix_u64() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

pub fn configured_api_rate_limit() -> u32 {
    std::env::var("ARKS_API_RATE_LIMIT_PER_MIN")
        .ok()
        .and_then(|v| v.trim().parse::<u32>().ok())
        .unwrap_or(DEFAULT_API_RATE_LIMIT_PER_MIN)
}

/// Evaluate the per-client-IP 60-second fixed-window API rate limiter (P-5 / O-10).
/// Setting `ARKS_API_RATE_LIMIT_PER_MIN=0` disables enforcement while still reporting unlimited.
pub fn check_api_rate_limit(client_key: &str) -> RateLimitDecision {
    check_api_rate_limit_with_cap(client_key, configured_api_rate_limit())
}

pub fn check_api_rate_limit_with_cap(client_key: &str, limit: u32) -> RateLimitDecision {
    let now = now_unix_u64();
    if limit == 0 {
        return RateLimitDecision {
            allowed: true,
            limit: 0,
            remaining: 0,
            reset_secs: 60,
            reset_unix: now + 60,
        };
    }
    let map = GLOBAL_API_LIMITER.get_or_init(|| Mutex::new(HashMap::new()));
    let Ok(mut guard) = map.lock() else {
        return RateLimitDecision {
            allowed: true,
            limit,
            remaining: limit,
            reset_secs: 60,
            reset_unix: now + 60,
        };
    };
    let win = guard.entry(client_key.to_string()).or_default();
    if now.saturating_sub(win.window_start) >= 60 {
        win.window_start = now;
        win.count = 0;
    }
    let reset_unix = win.window_start + 60;
    let reset_secs = reset_unix.saturating_sub(now).max(1);
    if win.count >= limit {
        RateLimitDecision {
            allowed: false,
            limit,
            remaining: 0,
            reset_secs,
            reset_unix,
        }
    } else {
        win.count += 1;
        RateLimitDecision {
            allowed: true,
            limit,
            remaining: limit.saturating_sub(win.count),
            reset_secs,
            reset_unix,
        }
    }
}

/// Attach both IETF draft `RateLimit-Policy`/`RateLimit` and GitHub-compat `X-RateLimit-*` headers.
pub fn attach_rate_limit_headers(resp: &mut HttpResponse, dec: RateLimitDecision) {
    if dec.limit == 0 {
        return;
    }
    resp.extra_headers
        .push(("RateLimit-Policy".into(), format!("{};w=60", dec.limit)));
    resp.extra_headers.push((
        "RateLimit".into(),
        format!(
            "limit={}, remaining={}, reset={}",
            dec.limit, dec.remaining, dec.reset_secs
        ),
    ));
    resp.extra_headers
        .push(("X-RateLimit-Limit".into(), dec.limit.to_string()));
    resp.extra_headers
        .push(("X-RateLimit-Remaining".into(), dec.remaining.to_string()));
    resp.extra_headers
        .push(("X-RateLimit-Reset".into(), dec.reset_unix.to_string()));
}

/// Build a 429 Too Many Requests RFC 9457 response with `Retry-After` and rate-limit headers.
pub fn rate_limit_exceeded_response(path: &str, dec: RateLimitDecision) -> HttpResponse {
    let mut resp = crate::web::api::problem::problem_response(
        429,
        "rate-limit-exceeded",
        "Too Many Requests",
        "API rate limit exceeded; retry after reset window",
        path,
    );
    resp.extra_headers
        .push(("Retry-After".into(), dec.reset_secs.to_string()));
    attach_rate_limit_headers(&mut resp, dec);
    resp
}

/// Check request body size against `ARKS_MAX_BODY_BYTES` (default 64 MiB -> 413 Payload Too Large).
pub fn check_body_quota(req: &HttpRequest) -> Result<(), HttpResponse> {
    let max_bytes = std::env::var("ARKS_MAX_BODY_BYTES")
        .ok()
        .and_then(|v| v.trim().parse::<usize>().ok())
        .unwrap_or(DEFAULT_MAX_BODY_BYTES);
    if max_bytes > 0 && req.body.len() > max_bytes {
        return Err(crate::web::api::problem::problem_response(
            413,
            "payload-too-large",
            "Payload Too Large",
            format!("Request body exceeds maximum allowed size ({max_bytes} bytes)"),
            &req.path,
        ));
    }
    Ok(())
}

/// Check directory byte usage against an optional quota (507 Insufficient Storage).
pub fn check_storage_quota(
    path: &str,
    used_bytes: u64,
    incoming_bytes: u64,
    max_bytes: u64,
) -> Result<(), HttpResponse> {
    if max_bytes > 0 && used_bytes.saturating_add(incoming_bytes) > max_bytes {
        return Err(crate::web::api::problem::problem_response(
            507,
            "insufficient-storage",
            "Insufficient Storage",
            format!("Storage quota exceeded (limit {max_bytes} bytes)"),
            path,
        ));
    }
    Ok(())
}

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

    #[test]
    fn pagination_clamps_per_page_and_formats_rfc8288_links() {
        let p = PageParams::from_query("page=2&per_page=999");
        assert_eq!(p.page, 2);
        assert_eq!(p.per_page, MAX_PER_PAGE);

        let items: Vec<usize> = (0..75).collect();
        let p2 = PageParams::from_query("page=2&per_page=30");
        let (slice, total) = paginate_slice(&items, p2);
        assert_eq!(total, 75);
        assert_eq!(slice.len(), 30);
        assert_eq!(slice[0], 30);

        let link = format_link_header("/repos/a/b/issues", p2, total).unwrap();
        assert!(link.contains("page=3&per_page=30>; rel=\"next\""));
        assert!(link.contains("page=1&per_page=30>; rel=\"prev\""));
        assert!(link.contains("page=1&per_page=30>; rel=\"first\""));
        assert!(link.contains("page=3&per_page=30>; rel=\"last\""));
    }

    #[test]
    fn etag_conditional_get_and_if_match_preconditions() {
        let mut resp = HttpResponse {
            status: 200,
            content_type: "application/json".into(),
            body: br#"{"id":1}"#.to_vec(),
            www_authenticate: None,
            extra_headers: Vec::new(),
        };
        let req0 = HttpRequest::new("GET", "/api/v1/issues", "", Vec::new());
        apply_etag_and_conditional_get(&req0, &mut resp);
        let etag = resp
            .extra_headers
            .iter()
            .find(|(k, _)| k == "ETag")
            .unwrap()
            .1
            .clone();
        assert!(etag.starts_with("\"sha256-"));

        let mut resp2 = HttpResponse {
            status: 200,
            content_type: "application/json".into(),
            body: br#"{"id":1}"#.to_vec(),
            www_authenticate: None,
            extra_headers: Vec::new(),
        };
        let req_inm = HttpRequest::new("GET", "/api/v1/issues", "", Vec::new())
            .with_header("If-None-Match", &etag);
        apply_etag_and_conditional_get(&req_inm, &mut resp2);
        assert_eq!(resp2.status, 304);
        assert!(resp2.body.is_empty());

        let req_bad = HttpRequest::new("PATCH", "/api/v1/issues/1", "", Vec::new())
            .with_header("If-Match", "\"sha256-stale\"");
        assert_eq!(
            check_if_match(&req_bad, &etag, false).unwrap_err().status,
            412
        );

        let req_missing = HttpRequest::new("PATCH", "/api/v1/issues/1", "", Vec::new());
        assert_eq!(
            check_if_match(&req_missing, &etag, true)
                .unwrap_err()
                .status,
            428
        );
    }

    #[test]
    fn rate_limiter_emits_ietf_and_compat_headers_and_429() {
        let key = "test-rate-limit-client-1";
        let d1 = check_api_rate_limit_with_cap(key, 2);
        assert!(d1.allowed && d1.remaining == 1);
        let d2 = check_api_rate_limit_with_cap(key, 2);
        assert!(d2.allowed && d2.remaining == 0);
        let d3 = check_api_rate_limit_with_cap(key, 2);
        assert!(!d3.allowed && d3.remaining == 0);

        let resp = rate_limit_exceeded_response("/api/v1/issues", d3);
        assert_eq!(resp.status, 429);
        assert!(
            resp.extra_headers
                .iter()
                .any(|(k, _)| k == "RateLimit-Policy")
        );
        assert!(resp.extra_headers.iter().any(|(k, _)| k == "RateLimit"));
        assert!(
            resp.extra_headers
                .iter()
                .any(|(k, _)| k == "X-RateLimit-Limit")
        );
        assert!(resp.extra_headers.iter().any(|(k, _)| k == "Retry-After"));
    }

    #[test]
    fn storage_quota_returns_507() {
        let err = check_storage_quota("/info/lfs/objects", 900, 200, 1000).unwrap_err();
        assert_eq!(err.status, 507);
    }
}