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
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
561
//! Smart + dumb HTTP request dispatch (info/refs + service POST + static dumb GETs)
//! plus additive WebDAV write for dumb HTTP push (R2).
//!
//! Auth: unauthenticated loopback when Basic unset (G15). Optional in-process HTTP
//! Basic when configured (G36 / ADR 20261109224236). Forge OAuth refused.
//! Ops reverse-proxy / external TLS MAY still front the listener.
//!
//! Cite: gitprotocol-http, gitprotocol-v2, RFC 7617 Basic (summarize),
//! RFC 4918 / git-http-push (dumb push).

use crate::auth::BasicAuthConfig;
use crate::dav::{handle_dav_as, is_dav_method};
use crate::dumb::serve_dumb_path;
use crate::error::ServerError;
use crate::push_policy::Pusher;
use crate::receive::{receive_advertisement, receive_pack_as};
use crate::upload::{upload_advertisement, upload_pack_result};
use crate::v2::{handle_v2_request, v2_capability_advertisement_for};
use arks_repo::Repository;

const UPLOAD_AD: &str = "application/x-git-upload-pack-advertisement";
const UPLOAD_RES: &str = "application/x-git-upload-pack-result";
const RECEIVE_AD: &str = "application/x-git-receive-pack-advertisement";
const RECEIVE_RES: &str = "application/x-git-receive-pack-result";

#[derive(Debug, Clone)]
pub struct HttpRequest {
    pub method: String,
    pub path: String,
    pub query: String,
    pub body: Vec<u8>,
    /// Raw `Git-Protocol` header value (e.g. `version=2`), if present.
    pub git_protocol: Option<String>,
    /// Raw `Authorization` header value (e.g. `Basic …`), if present.
    pub authorization: Option<String>,
    /// WebDAV `Destination` header (MOVE).
    pub destination: Option<String>,
    /// WebDAV lock token from `Lock-Token` or `If` header.
    pub lock_token: Option<String>,
    /// Raw `Host` header (for LFS batch href construction).
    pub host: Option<String>,
    /// Raw `Cookie` header (for self-hosted Web UI session authentication).
    pub cookie: Option<String>,
    /// Raw `Origin` header (for cross-site POST CSRF protection).
    pub origin: Option<String>,
    /// Effective scheme (`https` when served over TLS or `X-Forwarded-Proto: https`).
    pub forwarded_proto: Option<String>,
    /// Raw `Sec-Fetch-Site` header (for cross-site mutation CSRF defense when `Origin` is absent).
    pub sec_fetch_site: Option<String>,
    /// Case-insensitive HTTP request headers (`HX-Request`, `HX-Boosted`, `HX-Target`,
    /// `If-None-Match`, `Accept`, `X-CSRF-Token`, etc.).
    pub headers: Vec<(String, String)>,
}

impl HttpRequest {
    pub fn new(
        method: impl Into<String>,
        path: impl Into<String>,
        query: impl Into<String>,
        body: Vec<u8>,
    ) -> Self {
        Self {
            method: method.into(),
            path: path.into(),
            query: query.into(),
            body,
            git_protocol: None,
            authorization: None,
            destination: None,
            lock_token: None,
            host: None,
            cookie: None,
            origin: None,
            forwarded_proto: None,
            sec_fetch_site: None,
            headers: Vec::new(),
        }
    }

    /// Effective client IP resolved by `arks serve` after trusted-proxy CIDR checks (O-5).
    pub fn client_ip(&self) -> Option<&str> {
        self.header("x-arks-client-ip")
    }

    /// Builder helper to attach an HTTP header (name normalized to ASCII lowercase).
    pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers
            .push((name.into().to_ascii_lowercase(), value.into()));
        self
    }

    /// Case-insensitive lookup for any HTTP request header (checks `headers` first,
    /// then falls back to dedicated parsed header fields).
    pub fn header(&self, name: &str) -> Option<&str> {
        if let Some((_, v)) = self
            .headers
            .iter()
            .find(|(k, _)| k.eq_ignore_ascii_case(name))
        {
            return Some(v.as_str());
        }
        if name.eq_ignore_ascii_case("host") {
            self.host.as_deref()
        } else if name.eq_ignore_ascii_case("cookie") {
            self.cookie.as_deref()
        } else if name.eq_ignore_ascii_case("origin") {
            self.origin.as_deref()
        } else if name.eq_ignore_ascii_case("authorization") {
            self.authorization.as_deref()
        } else if name.eq_ignore_ascii_case("git-protocol") {
            self.git_protocol.as_deref()
        } else if name.eq_ignore_ascii_case("x-forwarded-proto") {
            self.forwarded_proto.as_deref()
        } else if name.eq_ignore_ascii_case("sec-fetch-site") {
            self.sec_fetch_site.as_deref()
        } else {
            None
        }
    }

    /// Returns true if the request arrived over HTTPS or behind an HTTPS reverse proxy.
    pub fn is_https(&self) -> bool {
        self.forwarded_proto.as_deref().is_some_and(|v| {
            v.split(',')
                .next()
                .unwrap_or("")
                .trim()
                .eq_ignore_ascii_case("https")
        })
    }
}

#[derive(Debug, Clone)]
pub struct HttpResponse {
    pub status: u16,
    pub content_type: String,
    pub body: Vec<u8>,
    /// Set on 401 challenges (`Basic realm="arks"`).
    pub www_authenticate: Option<String>,
    /// Extra response headers (e.g. WebDAV `Lock-Token`).
    pub extra_headers: Vec<(String, String)>,
}

/// Handle one HTTP request against an open repository (smart + dumb + v2).
pub fn handle_smart_http(
    repo: &mut Repository,
    req: &HttpRequest,
) -> Result<HttpResponse, ServerError> {
    handle_smart_http_auth(repo, req, None)
}

/// Like [`handle_smart_http`], with optional Basic auth gate (LFS enabled by default).
pub fn handle_smart_http_auth(
    repo: &mut Repository,
    req: &HttpRequest,
    basic: Option<&BasicAuthConfig>,
) -> Result<HttpResponse, ServerError> {
    handle_smart_http_auth_opts(repo, req, basic, true, "http")
}

/// Like [`handle_smart_http_auth`], with explicit LFS toggle and scheme (`http`/`https`).
pub fn handle_smart_http_auth_opts(
    repo: &mut Repository,
    req: &HttpRequest,
    basic: Option<&BasicAuthConfig>,
    enable_lfs: bool,
    scheme: &str,
) -> Result<HttpResponse, ServerError> {
    let verified_basic_user = if let Some(cfg) = basic {
        match cfg.authorized_user(req.authorization.as_deref()) {
            Some(user) => Some(user),
            None => {
                return Ok(HttpResponse {
                    status: 401,
                    content_type: "text/plain".into(),
                    body: b"unauthorized\n".to_vec(),
                    www_authenticate: Some(cfg.challenge_header()),
                    extra_headers: Vec::new(),
                });
            }
        }
    } else {
        None
    };
    if crate::lfs::is_lfs_path(&req.path) {
        if enable_lfs {
            return crate::lfs::handle_lfs(repo, req, scheme);
        }
        return Ok(text(404, b"LFS disabled\n"));
    }
    if is_dav_method(&req.method) {
        if dav_mutation_targets_internal_arks_ref(req) {
            return Ok(text(
                403,
                b"Forbidden: mutations under refs/arks/ are not permitted\n",
            ));
        }
        let pusher = Pusher {
            transport: "http",
            verified_user: verified_basic_user,
            authorization: req.authorization.clone(),
        };
        return handle_dav_as(repo, req, &pusher);
    }
    let path = req.path.as_str();
    let wants_v2 = req
        .git_protocol
        .as_deref()
        .map(|v| {
            v.split(':')
                .any(|p| p.trim() == "version=2" || p.trim().starts_with("version=2"))
        })
        .unwrap_or(false)
        || req
            .git_protocol
            .as_deref()
            .map(|v| v.contains("version=2"))
            .unwrap_or(false);

    if path.ends_with("/info/refs") || path == "/info/refs" || path.ends_with("info/refs") {
        let service = query_param(&req.query, "service").unwrap_or("");
        if service.is_empty() {
            // Dumb HTTP discovery (gitprotocol-http dumb clients).
            return match serve_dumb_path(repo, "info/refs")? {
                Some((ct, body)) => Ok(typed(200, &ct, body)),
                None => Ok(text(404, b"not found")),
            };
        }
        if wants_v2 && service == "git-upload-pack" {
            // HTTP info/refs keeps `# service=` + flush, then v2 capability ad
            // (gitprotocol-http first-bytes `#` check + gitprotocol-v2).
            let mut body = arks_protocol::encode_text_line("# service=git-upload-pack")
                .map_err(|e| ServerError::Protocol(e.to_string()))?;
            body.extend(
                arks_protocol::encode_packet(&arks_protocol::Packet::Flush)
                    .map_err(|e| ServerError::Protocol(e.to_string()))?,
            );
            body.extend(v2_capability_advertisement_for(repo)?);
            return Ok(typed(200, UPLOAD_AD, body));
        }
        // receive-pack stays v1 (push over v2 not claimed).
        return match service {
            "git-upload-pack" => Ok(typed(200, UPLOAD_AD, upload_advertisement(repo)?)),
            "git-receive-pack" => Ok(typed(200, RECEIVE_AD, receive_advertisement(repo)?)),
            _ => Ok(text(403, b"unknown service")),
        };
    }
    if req.method.eq_ignore_ascii_case("POST")
        && (path.ends_with("/git-upload-pack") || path.ends_with("git-upload-pack"))
    {
        if looks_like_v2_command(&req.body) {
            return Ok(typed(
                200,
                UPLOAD_RES,
                handle_v2_request(repo, &req.body, true)?,
            ));
        }
        return Ok(typed(200, UPLOAD_RES, upload_pack_result(repo, &req.body)?));
    }
    if req.method.eq_ignore_ascii_case("POST")
        && (path.ends_with("/git-receive-pack") || path.ends_with("git-receive-pack"))
    {
        let pusher = Pusher {
            transport: "http",
            verified_user: verified_basic_user,
            authorization: req.authorization.clone(),
        };
        return Ok(typed(
            200,
            RECEIVE_RES,
            receive_pack_as(repo, &req.body, &pusher)?,
        ));
    }
    // Dumb static GETs: objects/…, objects/info/packs, …
    if req.method.eq_ignore_ascii_case("GET") || req.method.eq_ignore_ascii_case("HEAD") {
        let rel = path.trim_start_matches('/');
        if let Some((ct, body)) = serve_dumb_path(repo, rel)? {
            return Ok(typed(200, &ct, body));
        }
        // Also try stripping a leading repo path segment before objects/info.
        if let Some(idx) = rel.find("objects/") {
            if let Some((ct, body)) = serve_dumb_path(repo, &rel[idx..])? {
                return Ok(typed(200, &ct, body));
            }
        }
        if let Some(idx) = rel.find("info/refs") {
            if let Some((ct, body)) = serve_dumb_path(repo, &rel[idx..])? {
                return Ok(typed(200, &ct, body));
            }
        }
    }
    Ok(text(404, b"not found"))
}

fn dav_mutation_targets_internal_arks_ref(req: &HttpRequest) -> bool {
    let method = req.method.to_ascii_uppercase();
    if !matches!(
        method.as_str(),
        "PUT" | "MOVE" | "DELETE" | "LOCK" | "UNLOCK" | "MKCOL"
    ) {
        return false;
    }
    if raw_path_targets_internal_arks_ref(&req.path) {
        return true;
    }
    if let Some(dest) = req.destination.as_deref() {
        if raw_path_targets_internal_arks_ref(dest) {
            return true;
        }
    }
    false
}

fn hex_nibble(b: u8) -> Option<u8> {
    match b {
        b'0'..=b'9' => Some(b - b'0'),
        b'a'..=b'f' => Some(b - b'a' + 10),
        b'A'..=b'F' => Some(b - b'A' + 10),
        _ => None,
    }
}

fn percent_decode_path(input: &str) -> String {
    let bytes = input.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0usize;
    while i < bytes.len() {
        if bytes[i] == b'%'
            && i + 2 < bytes.len()
            && let (Some(hi), Some(lo)) = (hex_nibble(bytes[i + 1]), hex_nibble(bytes[i + 2]))
        {
            out.push((hi << 4) | lo);
            i += 3;
            continue;
        }
        out.push(bytes[i]);
        i += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}

fn raw_path_targets_internal_arks_ref(raw: &str) -> bool {
    let path_only = if let Some(idx) = raw.find("://") {
        let after = &raw[idx + 3..];
        match after.find('/') {
            Some(slash) => &after[slash..],
            None => return false,
        }
    } else {
        raw
    };
    let without_query = path_only.split(['?', '#']).next().unwrap_or("");
    let decoded = percent_decode_path(without_query);
    let normalized = decoded.replace('\\', "/");
    let mut segments: Vec<&str> = Vec::new();
    for seg in normalized.split('/') {
        if seg.is_empty() || seg == "." {
            continue;
        }
        if seg == ".." {
            segments.pop();
            continue;
        }
        segments.push(seg);
    }
    segments
        .windows(2)
        .any(|w| w[0].eq_ignore_ascii_case("refs") && w[1].eq_ignore_ascii_case("arks"))
}

fn looks_like_v2_command(body: &[u8]) -> bool {
    // v2 command requests start with pkt-line "command=…"
    body.len() >= 4 && {
        let s = String::from_utf8_lossy(body);
        s.contains("command=")
    }
}

fn query_param<'a>(query: &'a str, key: &str) -> Option<&'a str> {
    for part in query.split('&') {
        if let Some((k, v)) = part.split_once('=') {
            if k == key {
                return Some(v);
            }
        }
    }
    None
}

fn typed(status: u16, ct: &str, body: Vec<u8>) -> HttpResponse {
    HttpResponse {
        status,
        content_type: ct.into(),
        body,
        www_authenticate: None,
        extra_headers: Vec::new(),
    }
}

fn text(status: u16, body: &[u8]) -> HttpResponse {
    HttpResponse {
        status,
        content_type: "text/plain".into(),
        body: body.to_vec(),
        www_authenticate: None,
        extra_headers: Vec::new(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use arks_object::{Commit, ObjectKind, RawObject, Signature, Tree, TreeEntry, TreeMode};
    use arks_store::{ObjectFormat, ObjectStore};
    use tempfile::TempDir;

    fn seed_repo(format: ObjectFormat) -> (TempDir, Repository) {
        let dir = TempDir::new().unwrap();
        let git = dir.path();
        std::fs::create_dir_all(git.join("objects")).unwrap();
        std::fs::create_dir_all(git.join("refs/heads")).unwrap();
        std::fs::write(git.join("HEAD"), b"ref: refs/heads/main\n").unwrap();
        if format == ObjectFormat::Sha256 {
            std::fs::write(
                git.join("config"),
                "[core]\n\trepositoryformatversion = 1\n\tbare = true\n[extensions]\n\tobjectformat = sha256\n",
            )
            .unwrap();
        } else {
            std::fs::write(
                git.join("config"),
                "[core]\n\trepositoryformatversion = 0\n\tbare = true\n",
            )
            .unwrap();
        }
        let mut repo = Repository::open(git).unwrap();
        let blob = repo
            .store_mut()
            .put(format, &RawObject::new(ObjectKind::Blob, b"hi\n".to_vec()))
            .unwrap();
        let tree = Tree::new(vec![TreeEntry {
            mode: TreeMode::File,
            name: "a.txt".into(),
            oid: blob,
        }])
        .unwrap();
        let tree_oid = repo
            .store_mut()
            .put(
                format,
                &RawObject::new(ObjectKind::Tree, tree.encode().unwrap()),
            )
            .unwrap();
        let sig = Signature {
            name: "arks".into(),
            email: "arks@example.invalid".into(),
            timestamp: 1_700_000_000,
            timezone: "+0000".into(),
        };
        let commit = Commit {
            tree: tree_oid,
            parents: Vec::new(),
            author: sig.clone(),
            committer: sig,
            gpgsig: None,
            message: "init\n".into(),
        };
        let oid = repo
            .store_mut()
            .put(
                format,
                &RawObject::new(ObjectKind::Commit, commit.encode().unwrap()),
            )
            .unwrap();
        repo.refs_mut()
            .update("refs/heads/main", &oid, None)
            .unwrap();
        (dir, repo)
    }

    #[test]
    fn webdav_mutations_targeting_refs_arks_return_403() {
        let (_dir, mut repo) = seed_repo(ObjectFormat::Sha1);
        for method in ["PUT", "DELETE", "LOCK", "MOVE"] {
            let mut req = HttpRequest::new(
                method,
                "/repo.git/refs/arks/v2/keep/pin1",
                "",
                b"1111111111111111111111111111111111111111\n".to_vec(),
            );
            if method == "MOVE" {
                req.destination = Some("http://127.0.0.1:8080/repo.git/refs/heads/other".into());
            }
            let resp = handle_smart_http(&mut repo, &req).unwrap();
            assert_eq!(
                resp.status, 403,
                "WebDAV {method} targeting refs/arks/ must return 403"
            );
        }

        // MOVE with a normal source but a refs/arks/ Destination must also return 403.
        let mut move_into_arks = HttpRequest::new("MOVE", "/refs/heads/main", "", Vec::new());
        move_into_arks.destination =
            Some("http://127.0.0.1:8080/repo.git/refs/arks/internal/alice/c1".into());
        let resp = handle_smart_http(&mut repo, &move_into_arks).unwrap();
        assert_eq!(resp.status, 403);
    }

    #[test]
    fn raw_path_targets_internal_arks_ref_blocks_normalized_and_case_bypasses() {
        let (_dir, mut repo) = seed_repo(ObjectFormat::Sha1);
        for bypass_path in [
            "/refs/./arks/v2/keep/x",
            "/refs//arks/v2/keep/x",
            "/refs/ARKS/v2/keep/x",
            "/REFS/ARKS",
            "/repo.git/refs/./arks/v2/keep/x",
            "/repo.git/refs//ARKS/v2/keep/x",
            "/refs%2farks/v2/keep/x",
            "/refs%2F%2e%2FARKS/v2/keep/x",
            "/refs/%2E/arks/v2/keep/x",
            "/refs/heads/../arks/v2/keep/x",
            "/refs/heads/%2e%2e/ARKS/v2/keep/x",
        ] {
            assert!(
                raw_path_targets_internal_arks_ref(bypass_path),
                "must detect internal refs/arks bypass '{bypass_path}'"
            );
            let req = HttpRequest::new(
                "PUT",
                bypass_path,
                "",
                b"1111111111111111111111111111111111111111\n".to_vec(),
            );
            let resp = handle_smart_http(&mut repo, &req).unwrap();
            assert_eq!(
                resp.status, 403,
                "PUT {bypass_path} must be rejected with 403"
            );
        }

        assert!(!raw_path_targets_internal_arks_ref("/refs/heads/main"));
        assert!(!raw_path_targets_internal_arks_ref("/refs/heads/arks"));
        assert!(!raw_path_targets_internal_arks_ref("/refs/arks-other/foo"));
        assert!(!raw_path_targets_internal_arks_ref(
            "/repo.git/objects/ab/cdef"
        ));
    }

    #[test]
    fn smart_http_v2_info_refs_advertises_sha256_for_sha256_repo() {
        let (_dir, mut repo) = seed_repo(ObjectFormat::Sha256);
        let mut req = HttpRequest::new("GET", "/info/refs", "service=git-upload-pack", Vec::new());
        req.git_protocol = Some("version=2".into());
        let resp = handle_smart_http(&mut repo, &req).unwrap();
        assert_eq!(resp.status, 200);
        let text = String::from_utf8_lossy(&resp.body);
        assert!(text.contains("object-format=sha256"), "{text}");
        assert!(!text.contains("object-format=sha1"), "{text}");
    }
}