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, 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};
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}
43
44impl HttpRequest {
45    pub fn new(
46        method: impl Into<String>,
47        path: impl Into<String>,
48        query: impl Into<String>,
49        body: Vec<u8>,
50    ) -> Self {
51        Self {
52            method: method.into(),
53            path: path.into(),
54            query: query.into(),
55            body,
56            git_protocol: None,
57            authorization: None,
58            destination: None,
59            lock_token: None,
60            host: None,
61        }
62    }
63}
64
65#[derive(Debug, Clone)]
66pub struct HttpResponse {
67    pub status: u16,
68    pub content_type: String,
69    pub body: Vec<u8>,
70    /// Set on 401 challenges (`Basic realm="arks"`).
71    pub www_authenticate: Option<String>,
72    /// Extra response headers (e.g. WebDAV `Lock-Token`).
73    pub extra_headers: Vec<(String, String)>,
74}
75
76/// Handle one HTTP request against an open repository (smart + dumb + v2).
77pub fn handle_smart_http(
78    repo: &mut Repository,
79    req: &HttpRequest,
80) -> Result<HttpResponse, ServerError> {
81    handle_smart_http_auth(repo, req, None)
82}
83
84/// Like [`handle_smart_http`], with optional Basic auth gate.
85pub fn handle_smart_http_auth(
86    repo: &mut Repository,
87    req: &HttpRequest,
88    basic: Option<&BasicAuthConfig>,
89) -> Result<HttpResponse, ServerError> {
90    if let Some(cfg) = basic {
91        if !cfg.check_authorization(req.authorization.as_deref()) {
92            return Ok(HttpResponse {
93                status: 401,
94                content_type: "text/plain".into(),
95                body: b"unauthorized\n".to_vec(),
96                www_authenticate: Some(cfg.challenge_header()),
97                extra_headers: Vec::new(),
98            });
99        }
100    }
101    // LFS server productization (`info/lfs`) trimmed — keep plain git HTTP only.
102    if is_dav_method(&req.method) {
103        return handle_dav(repo, req);
104    }
105    let path = req.path.as_str();
106    let wants_v2 = req
107        .git_protocol
108        .as_deref()
109        .map(|v| {
110            v.split(':')
111                .any(|p| p.trim() == "version=2" || p.trim().starts_with("version=2"))
112        })
113        .unwrap_or(false)
114        || req
115            .git_protocol
116            .as_deref()
117            .map(|v| v.contains("version=2"))
118            .unwrap_or(false);
119
120    if path.ends_with("/info/refs") || path == "/info/refs" || path.ends_with("info/refs") {
121        let service = query_param(&req.query, "service").unwrap_or("");
122        if service.is_empty() {
123            // Dumb HTTP discovery (gitprotocol-http dumb clients).
124            return match serve_dumb_path(repo, "info/refs")? {
125                Some((ct, body)) => Ok(typed(200, &ct, body)),
126                None => Ok(text(404, b"not found")),
127            };
128        }
129        if wants_v2 && service == "git-upload-pack" {
130            // HTTP info/refs keeps `# service=` + flush, then v2 capability ad
131            // (gitprotocol-http first-bytes `#` check + gitprotocol-v2).
132            let mut body = arks_protocol::encode_text_line("# service=git-upload-pack")
133                .map_err(|e| ServerError::Protocol(e.to_string()))?;
134            body.extend(
135                arks_protocol::encode_packet(&arks_protocol::Packet::Flush)
136                    .map_err(|e| ServerError::Protocol(e.to_string()))?,
137            );
138            body.extend(v2_capability_advertisement()?);
139            return Ok(typed(200, UPLOAD_AD, body));
140        }
141        // receive-pack stays v1 (push over v2 not claimed).
142        return match service {
143            "git-upload-pack" => Ok(typed(200, UPLOAD_AD, upload_advertisement(repo)?)),
144            "git-receive-pack" => Ok(typed(200, RECEIVE_AD, receive_advertisement(repo)?)),
145            _ => Ok(text(403, b"unknown service")),
146        };
147    }
148    if req.method.eq_ignore_ascii_case("POST")
149        && (path.ends_with("/git-upload-pack") || path.ends_with("git-upload-pack"))
150    {
151        if looks_like_v2_command(&req.body) {
152            return Ok(typed(
153                200,
154                UPLOAD_RES,
155                handle_v2_request(repo, &req.body, true)?,
156            ));
157        }
158        return Ok(typed(200, UPLOAD_RES, upload_pack_result(repo, &req.body)?));
159    }
160    if req.method.eq_ignore_ascii_case("POST")
161        && (path.ends_with("/git-receive-pack") || path.ends_with("git-receive-pack"))
162    {
163        let pusher = Pusher {
164            transport: "http",
165            verified_user: basic.and_then(|cfg| cfg.authorized_user(req.authorization.as_deref())),
166            authorization: req.authorization.clone(),
167        };
168        return Ok(typed(
169            200,
170            RECEIVE_RES,
171            receive_pack_as(repo, &req.body, &pusher)?,
172        ));
173    }
174    // Dumb static GETs: objects/…, objects/info/packs, …
175    if req.method.eq_ignore_ascii_case("GET") || req.method.eq_ignore_ascii_case("HEAD") {
176        let rel = path.trim_start_matches('/');
177        if let Some((ct, body)) = serve_dumb_path(repo, rel)? {
178            return Ok(typed(200, &ct, body));
179        }
180        // Also try stripping a leading repo path segment before objects/info.
181        if let Some(idx) = rel.find("objects/") {
182            if let Some((ct, body)) = serve_dumb_path(repo, &rel[idx..])? {
183                return Ok(typed(200, &ct, body));
184            }
185        }
186        if let Some(idx) = rel.find("info/refs") {
187            if let Some((ct, body)) = serve_dumb_path(repo, &rel[idx..])? {
188                return Ok(typed(200, &ct, body));
189            }
190        }
191    }
192    Ok(text(404, b"not found"))
193}
194
195fn looks_like_v2_command(body: &[u8]) -> bool {
196    // v2 command requests start with pkt-line "command=…"
197    body.len() >= 4 && {
198        let s = String::from_utf8_lossy(body);
199        s.contains("command=")
200    }
201}
202
203fn query_param<'a>(query: &'a str, key: &str) -> Option<&'a str> {
204    for part in query.split('&') {
205        if let Some((k, v)) = part.split_once('=') {
206            if k == key {
207                return Some(v);
208            }
209        }
210    }
211    None
212}
213
214fn typed(status: u16, ct: &str, body: Vec<u8>) -> HttpResponse {
215    HttpResponse {
216        status,
217        content_type: ct.into(),
218        body,
219        www_authenticate: None,
220        extra_headers: Vec::new(),
221    }
222}
223
224fn text(status: u16, body: &[u8]) -> HttpResponse {
225    HttpResponse {
226        status,
227        content_type: "text/plain".into(),
228        body: body.to_vec(),
229        www_authenticate: None,
230        extra_headers: Vec::new(),
231    }
232}