Skip to main content

arks_server/
http.rs

1//! Smart + dumb HTTP request dispatch (info/refs + service POST + static dumb GETs)
2//! plus additive WebDAV write for dumb HTTP push (R2).
3//!
4//! Auth: unauthenticated loopback when Basic unset (G15). Optional in-process HTTP
5//! Basic when configured (G36 / ADR 20261109224236). Forge OAuth refused.
6//! Ops reverse-proxy / external TLS MAY still front the listener.
7//!
8//! Cite: gitprotocol-http, gitprotocol-v2, RFC 7617 Basic (summarize),
9//! RFC 4918 / git-http-push (dumb push).
10
11use crate::auth::BasicAuthConfig;
12use crate::dav::{handle_dav_as, is_dav_method};
13use crate::dumb::serve_dumb_path;
14use crate::error::ServerError;
15use crate::push_policy::Pusher;
16use crate::receive::{receive_advertisement, receive_pack_as};
17use crate::upload::{upload_advertisement, upload_pack_result};
18use crate::v2::{handle_v2_request, v2_capability_advertisement_for};
19use arks_repo::Repository;
20
21const UPLOAD_AD: &str = "application/x-git-upload-pack-advertisement";
22const UPLOAD_RES: &str = "application/x-git-upload-pack-result";
23const RECEIVE_AD: &str = "application/x-git-receive-pack-advertisement";
24const RECEIVE_RES: &str = "application/x-git-receive-pack-result";
25
26#[derive(Debug, Clone)]
27pub struct HttpRequest {
28    pub method: String,
29    pub path: String,
30    pub query: String,
31    pub body: Vec<u8>,
32    /// Raw `Git-Protocol` header value (e.g. `version=2`), if present.
33    pub git_protocol: Option<String>,
34    /// Raw `Authorization` header value (e.g. `Basic …`), if present.
35    pub authorization: Option<String>,
36    /// WebDAV `Destination` header (MOVE).
37    pub destination: Option<String>,
38    /// WebDAV lock token from `Lock-Token` or `If` header.
39    pub lock_token: Option<String>,
40    /// Raw `Host` header (for LFS batch href construction).
41    pub host: Option<String>,
42    /// Raw `Cookie` header (for self-hosted Web UI session authentication).
43    pub cookie: Option<String>,
44    /// Raw `Origin` header (for cross-site POST CSRF protection).
45    pub origin: Option<String>,
46    /// Effective scheme (`https` when served over TLS or `X-Forwarded-Proto: https`).
47    pub forwarded_proto: Option<String>,
48    /// Raw `Sec-Fetch-Site` header (for cross-site mutation CSRF defense when `Origin` is absent).
49    pub sec_fetch_site: Option<String>,
50}
51
52impl HttpRequest {
53    pub fn new(
54        method: impl Into<String>,
55        path: impl Into<String>,
56        query: impl Into<String>,
57        body: Vec<u8>,
58    ) -> Self {
59        Self {
60            method: method.into(),
61            path: path.into(),
62            query: query.into(),
63            body,
64            git_protocol: None,
65            authorization: None,
66            destination: None,
67            lock_token: None,
68            host: None,
69            cookie: None,
70            origin: None,
71            forwarded_proto: None,
72            sec_fetch_site: None,
73        }
74    }
75
76    /// Returns true if the request arrived over HTTPS or behind an HTTPS reverse proxy.
77    pub fn is_https(&self) -> bool {
78        self.forwarded_proto.as_deref().is_some_and(|v| {
79            v.split(',')
80                .next()
81                .unwrap_or("")
82                .trim()
83                .eq_ignore_ascii_case("https")
84        })
85    }
86}
87
88#[derive(Debug, Clone)]
89pub struct HttpResponse {
90    pub status: u16,
91    pub content_type: String,
92    pub body: Vec<u8>,
93    /// Set on 401 challenges (`Basic realm="arks"`).
94    pub www_authenticate: Option<String>,
95    /// Extra response headers (e.g. WebDAV `Lock-Token`).
96    pub extra_headers: Vec<(String, String)>,
97}
98
99/// Handle one HTTP request against an open repository (smart + dumb + v2).
100pub fn handle_smart_http(
101    repo: &mut Repository,
102    req: &HttpRequest,
103) -> Result<HttpResponse, ServerError> {
104    handle_smart_http_auth(repo, req, None)
105}
106
107/// Like [`handle_smart_http`], with optional Basic auth gate (LFS enabled by default).
108pub fn handle_smart_http_auth(
109    repo: &mut Repository,
110    req: &HttpRequest,
111    basic: Option<&BasicAuthConfig>,
112) -> Result<HttpResponse, ServerError> {
113    handle_smart_http_auth_opts(repo, req, basic, true, "http")
114}
115
116/// Like [`handle_smart_http_auth`], with explicit LFS toggle and scheme (`http`/`https`).
117pub fn handle_smart_http_auth_opts(
118    repo: &mut Repository,
119    req: &HttpRequest,
120    basic: Option<&BasicAuthConfig>,
121    enable_lfs: bool,
122    scheme: &str,
123) -> Result<HttpResponse, ServerError> {
124    let verified_basic_user = if let Some(cfg) = basic {
125        match cfg.authorized_user(req.authorization.as_deref()) {
126            Some(user) => Some(user),
127            None => {
128                return Ok(HttpResponse {
129                    status: 401,
130                    content_type: "text/plain".into(),
131                    body: b"unauthorized\n".to_vec(),
132                    www_authenticate: Some(cfg.challenge_header()),
133                    extra_headers: Vec::new(),
134                });
135            }
136        }
137    } else {
138        None
139    };
140    if crate::lfs::is_lfs_path(&req.path) {
141        if enable_lfs {
142            return crate::lfs::handle_lfs(repo, req, scheme);
143        }
144        return Ok(text(404, b"LFS disabled\n"));
145    }
146    if is_dav_method(&req.method) {
147        if dav_mutation_targets_internal_arks_ref(req) {
148            return Ok(text(
149                403,
150                b"Forbidden: mutations under refs/arks/ are not permitted\n",
151            ));
152        }
153        let pusher = Pusher {
154            transport: "http",
155            verified_user: verified_basic_user,
156            authorization: req.authorization.clone(),
157        };
158        return handle_dav_as(repo, req, &pusher);
159    }
160    let path = req.path.as_str();
161    let wants_v2 = req
162        .git_protocol
163        .as_deref()
164        .map(|v| {
165            v.split(':')
166                .any(|p| p.trim() == "version=2" || p.trim().starts_with("version=2"))
167        })
168        .unwrap_or(false)
169        || req
170            .git_protocol
171            .as_deref()
172            .map(|v| v.contains("version=2"))
173            .unwrap_or(false);
174
175    if path.ends_with("/info/refs") || path == "/info/refs" || path.ends_with("info/refs") {
176        let service = query_param(&req.query, "service").unwrap_or("");
177        if service.is_empty() {
178            // Dumb HTTP discovery (gitprotocol-http dumb clients).
179            return match serve_dumb_path(repo, "info/refs")? {
180                Some((ct, body)) => Ok(typed(200, &ct, body)),
181                None => Ok(text(404, b"not found")),
182            };
183        }
184        if wants_v2 && service == "git-upload-pack" {
185            // HTTP info/refs keeps `# service=` + flush, then v2 capability ad
186            // (gitprotocol-http first-bytes `#` check + gitprotocol-v2).
187            let mut body = arks_protocol::encode_text_line("# service=git-upload-pack")
188                .map_err(|e| ServerError::Protocol(e.to_string()))?;
189            body.extend(
190                arks_protocol::encode_packet(&arks_protocol::Packet::Flush)
191                    .map_err(|e| ServerError::Protocol(e.to_string()))?,
192            );
193            body.extend(v2_capability_advertisement_for(repo)?);
194            return Ok(typed(200, UPLOAD_AD, body));
195        }
196        // receive-pack stays v1 (push over v2 not claimed).
197        return match service {
198            "git-upload-pack" => Ok(typed(200, UPLOAD_AD, upload_advertisement(repo)?)),
199            "git-receive-pack" => Ok(typed(200, RECEIVE_AD, receive_advertisement(repo)?)),
200            _ => Ok(text(403, b"unknown service")),
201        };
202    }
203    if req.method.eq_ignore_ascii_case("POST")
204        && (path.ends_with("/git-upload-pack") || path.ends_with("git-upload-pack"))
205    {
206        if looks_like_v2_command(&req.body) {
207            return Ok(typed(
208                200,
209                UPLOAD_RES,
210                handle_v2_request(repo, &req.body, true)?,
211            ));
212        }
213        return Ok(typed(200, UPLOAD_RES, upload_pack_result(repo, &req.body)?));
214    }
215    if req.method.eq_ignore_ascii_case("POST")
216        && (path.ends_with("/git-receive-pack") || path.ends_with("git-receive-pack"))
217    {
218        let pusher = Pusher {
219            transport: "http",
220            verified_user: verified_basic_user,
221            authorization: req.authorization.clone(),
222        };
223        return Ok(typed(
224            200,
225            RECEIVE_RES,
226            receive_pack_as(repo, &req.body, &pusher)?,
227        ));
228    }
229    // Dumb static GETs: objects/…, objects/info/packs, …
230    if req.method.eq_ignore_ascii_case("GET") || req.method.eq_ignore_ascii_case("HEAD") {
231        let rel = path.trim_start_matches('/');
232        if let Some((ct, body)) = serve_dumb_path(repo, rel)? {
233            return Ok(typed(200, &ct, body));
234        }
235        // Also try stripping a leading repo path segment before objects/info.
236        if let Some(idx) = rel.find("objects/") {
237            if let Some((ct, body)) = serve_dumb_path(repo, &rel[idx..])? {
238                return Ok(typed(200, &ct, body));
239            }
240        }
241        if let Some(idx) = rel.find("info/refs") {
242            if let Some((ct, body)) = serve_dumb_path(repo, &rel[idx..])? {
243                return Ok(typed(200, &ct, body));
244            }
245        }
246    }
247    Ok(text(404, b"not found"))
248}
249
250fn dav_mutation_targets_internal_arks_ref(req: &HttpRequest) -> bool {
251    let method = req.method.to_ascii_uppercase();
252    if !matches!(
253        method.as_str(),
254        "PUT" | "MOVE" | "DELETE" | "LOCK" | "UNLOCK" | "MKCOL"
255    ) {
256        return false;
257    }
258    if raw_path_targets_internal_arks_ref(&req.path) {
259        return true;
260    }
261    if let Some(dest) = req.destination.as_deref() {
262        if raw_path_targets_internal_arks_ref(dest) {
263            return true;
264        }
265    }
266    false
267}
268
269fn hex_nibble(b: u8) -> Option<u8> {
270    match b {
271        b'0'..=b'9' => Some(b - b'0'),
272        b'a'..=b'f' => Some(b - b'a' + 10),
273        b'A'..=b'F' => Some(b - b'A' + 10),
274        _ => None,
275    }
276}
277
278fn percent_decode_path(input: &str) -> String {
279    let bytes = input.as_bytes();
280    let mut out = Vec::with_capacity(bytes.len());
281    let mut i = 0usize;
282    while i < bytes.len() {
283        if bytes[i] == b'%'
284            && i + 2 < bytes.len()
285            && let (Some(hi), Some(lo)) = (hex_nibble(bytes[i + 1]), hex_nibble(bytes[i + 2]))
286        {
287            out.push((hi << 4) | lo);
288            i += 3;
289            continue;
290        }
291        out.push(bytes[i]);
292        i += 1;
293    }
294    String::from_utf8_lossy(&out).into_owned()
295}
296
297fn raw_path_targets_internal_arks_ref(raw: &str) -> bool {
298    let path_only = if let Some(idx) = raw.find("://") {
299        let after = &raw[idx + 3..];
300        match after.find('/') {
301            Some(slash) => &after[slash..],
302            None => return false,
303        }
304    } else {
305        raw
306    };
307    let without_query = path_only.split(['?', '#']).next().unwrap_or("");
308    let decoded = percent_decode_path(without_query);
309    let normalized = decoded.replace('\\', "/");
310    let mut segments: Vec<&str> = Vec::new();
311    for seg in normalized.split('/') {
312        if seg.is_empty() || seg == "." {
313            continue;
314        }
315        if seg == ".." {
316            segments.pop();
317            continue;
318        }
319        segments.push(seg);
320    }
321    segments
322        .windows(2)
323        .any(|w| w[0].eq_ignore_ascii_case("refs") && w[1].eq_ignore_ascii_case("arks"))
324}
325
326fn looks_like_v2_command(body: &[u8]) -> bool {
327    // v2 command requests start with pkt-line "command=…"
328    body.len() >= 4 && {
329        let s = String::from_utf8_lossy(body);
330        s.contains("command=")
331    }
332}
333
334fn query_param<'a>(query: &'a str, key: &str) -> Option<&'a str> {
335    for part in query.split('&') {
336        if let Some((k, v)) = part.split_once('=') {
337            if k == key {
338                return Some(v);
339            }
340        }
341    }
342    None
343}
344
345fn typed(status: u16, ct: &str, body: Vec<u8>) -> HttpResponse {
346    HttpResponse {
347        status,
348        content_type: ct.into(),
349        body,
350        www_authenticate: None,
351        extra_headers: Vec::new(),
352    }
353}
354
355fn text(status: u16, body: &[u8]) -> HttpResponse {
356    HttpResponse {
357        status,
358        content_type: "text/plain".into(),
359        body: body.to_vec(),
360        www_authenticate: None,
361        extra_headers: Vec::new(),
362    }
363}
364
365#[cfg(test)]
366mod tests {
367    use super::*;
368    use arks_object::{Commit, ObjectKind, RawObject, Signature, Tree, TreeEntry, TreeMode};
369    use arks_store::{ObjectFormat, ObjectStore};
370    use tempfile::TempDir;
371
372    fn seed_repo(format: ObjectFormat) -> (TempDir, Repository) {
373        let dir = TempDir::new().unwrap();
374        let git = dir.path();
375        std::fs::create_dir_all(git.join("objects")).unwrap();
376        std::fs::create_dir_all(git.join("refs/heads")).unwrap();
377        std::fs::write(git.join("HEAD"), b"ref: refs/heads/main\n").unwrap();
378        if format == ObjectFormat::Sha256 {
379            std::fs::write(
380                git.join("config"),
381                "[core]\n\trepositoryformatversion = 1\n\tbare = true\n[extensions]\n\tobjectformat = sha256\n",
382            )
383            .unwrap();
384        } else {
385            std::fs::write(
386                git.join("config"),
387                "[core]\n\trepositoryformatversion = 0\n\tbare = true\n",
388            )
389            .unwrap();
390        }
391        let mut repo = Repository::open(git).unwrap();
392        let blob = repo
393            .store_mut()
394            .put(format, &RawObject::new(ObjectKind::Blob, b"hi\n".to_vec()))
395            .unwrap();
396        let tree = Tree::new(vec![TreeEntry {
397            mode: TreeMode::File,
398            name: "a.txt".into(),
399            oid: blob,
400        }])
401        .unwrap();
402        let tree_oid = repo
403            .store_mut()
404            .put(
405                format,
406                &RawObject::new(ObjectKind::Tree, tree.encode().unwrap()),
407            )
408            .unwrap();
409        let sig = Signature {
410            name: "arks".into(),
411            email: "arks@example.invalid".into(),
412            timestamp: 1_700_000_000,
413            timezone: "+0000".into(),
414        };
415        let commit = Commit {
416            tree: tree_oid,
417            parents: Vec::new(),
418            author: sig.clone(),
419            committer: sig,
420            gpgsig: None,
421            message: "init\n".into(),
422        };
423        let oid = repo
424            .store_mut()
425            .put(
426                format,
427                &RawObject::new(ObjectKind::Commit, commit.encode().unwrap()),
428            )
429            .unwrap();
430        repo.refs_mut()
431            .update("refs/heads/main", &oid, None)
432            .unwrap();
433        (dir, repo)
434    }
435
436    #[test]
437    fn webdav_mutations_targeting_refs_arks_return_403() {
438        let (_dir, mut repo) = seed_repo(ObjectFormat::Sha1);
439        for method in ["PUT", "DELETE", "LOCK", "MOVE"] {
440            let mut req = HttpRequest::new(
441                method,
442                "/repo.git/refs/arks/v2/keep/pin1",
443                "",
444                b"1111111111111111111111111111111111111111\n".to_vec(),
445            );
446            if method == "MOVE" {
447                req.destination = Some("http://127.0.0.1:8080/repo.git/refs/heads/other".into());
448            }
449            let resp = handle_smart_http(&mut repo, &req).unwrap();
450            assert_eq!(
451                resp.status, 403,
452                "WebDAV {method} targeting refs/arks/ must return 403"
453            );
454        }
455
456        // MOVE with a normal source but a refs/arks/ Destination must also return 403.
457        let mut move_into_arks = HttpRequest::new("MOVE", "/refs/heads/main", "", Vec::new());
458        move_into_arks.destination =
459            Some("http://127.0.0.1:8080/repo.git/refs/arks/internal/alice/c1".into());
460        let resp = handle_smart_http(&mut repo, &move_into_arks).unwrap();
461        assert_eq!(resp.status, 403);
462    }
463
464    #[test]
465    fn raw_path_targets_internal_arks_ref_blocks_normalized_and_case_bypasses() {
466        let (_dir, mut repo) = seed_repo(ObjectFormat::Sha1);
467        for bypass_path in [
468            "/refs/./arks/v2/keep/x",
469            "/refs//arks/v2/keep/x",
470            "/refs/ARKS/v2/keep/x",
471            "/REFS/ARKS",
472            "/repo.git/refs/./arks/v2/keep/x",
473            "/repo.git/refs//ARKS/v2/keep/x",
474            "/refs%2farks/v2/keep/x",
475            "/refs%2F%2e%2FARKS/v2/keep/x",
476            "/refs/%2E/arks/v2/keep/x",
477            "/refs/heads/../arks/v2/keep/x",
478            "/refs/heads/%2e%2e/ARKS/v2/keep/x",
479        ] {
480            assert!(
481                raw_path_targets_internal_arks_ref(bypass_path),
482                "must detect internal refs/arks bypass '{bypass_path}'"
483            );
484            let req = HttpRequest::new(
485                "PUT",
486                bypass_path,
487                "",
488                b"1111111111111111111111111111111111111111\n".to_vec(),
489            );
490            let resp = handle_smart_http(&mut repo, &req).unwrap();
491            assert_eq!(
492                resp.status, 403,
493                "PUT {bypass_path} must be rejected with 403"
494            );
495        }
496
497        assert!(!raw_path_targets_internal_arks_ref("/refs/heads/main"));
498        assert!(!raw_path_targets_internal_arks_ref("/refs/heads/arks"));
499        assert!(!raw_path_targets_internal_arks_ref("/refs/arks-other/foo"));
500        assert!(!raw_path_targets_internal_arks_ref(
501            "/repo.git/objects/ab/cdef"
502        ));
503    }
504
505    #[test]
506    fn smart_http_v2_info_refs_advertises_sha256_for_sha256_repo() {
507        let (_dir, mut repo) = seed_repo(ObjectFormat::Sha256);
508        let mut req = HttpRequest::new("GET", "/info/refs", "service=git-upload-pack", Vec::new());
509        req.git_protocol = Some("version=2".into());
510        let resp = handle_smart_http(&mut repo, &req).unwrap();
511        assert_eq!(resp.status, 200);
512        let text = String::from_utf8_lossy(&resp.body);
513        assert!(text.contains("object-format=sha256"), "{text}");
514        assert!(!text.contains("object-format=sha1"), "{text}");
515    }
516}