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