1use 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 pub git_protocol: Option<String>,
34 pub authorization: Option<String>,
36 pub destination: Option<String>,
38 pub lock_token: Option<String>,
40 pub host: Option<String>,
42 pub cookie: Option<String>,
44 pub origin: Option<String>,
46 pub forwarded_proto: Option<String>,
48 pub sec_fetch_site: Option<String>,
50 pub headers: Vec<(String, String)>,
53}
54
55impl HttpRequest {
56 pub fn new(
57 method: impl Into<String>,
58 path: impl Into<String>,
59 query: impl Into<String>,
60 body: Vec<u8>,
61 ) -> Self {
62 Self {
63 method: method.into(),
64 path: path.into(),
65 query: query.into(),
66 body,
67 git_protocol: None,
68 authorization: None,
69 destination: None,
70 lock_token: None,
71 host: None,
72 cookie: None,
73 origin: None,
74 forwarded_proto: None,
75 sec_fetch_site: None,
76 headers: Vec::new(),
77 }
78 }
79
80 pub fn client_ip(&self) -> Option<&str> {
82 self.header("x-arks-client-ip")
83 }
84
85 pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
87 self.headers
88 .push((name.into().to_ascii_lowercase(), value.into()));
89 self
90 }
91
92 pub fn header(&self, name: &str) -> Option<&str> {
95 if let Some((_, v)) = self
96 .headers
97 .iter()
98 .find(|(k, _)| k.eq_ignore_ascii_case(name))
99 {
100 return Some(v.as_str());
101 }
102 if name.eq_ignore_ascii_case("host") {
103 self.host.as_deref()
104 } else if name.eq_ignore_ascii_case("cookie") {
105 self.cookie.as_deref()
106 } else if name.eq_ignore_ascii_case("origin") {
107 self.origin.as_deref()
108 } else if name.eq_ignore_ascii_case("authorization") {
109 self.authorization.as_deref()
110 } else if name.eq_ignore_ascii_case("git-protocol") {
111 self.git_protocol.as_deref()
112 } else if name.eq_ignore_ascii_case("x-forwarded-proto") {
113 self.forwarded_proto.as_deref()
114 } else if name.eq_ignore_ascii_case("sec-fetch-site") {
115 self.sec_fetch_site.as_deref()
116 } else {
117 None
118 }
119 }
120
121 pub fn is_https(&self) -> bool {
123 self.forwarded_proto.as_deref().is_some_and(|v| {
124 v.split(',')
125 .next()
126 .unwrap_or("")
127 .trim()
128 .eq_ignore_ascii_case("https")
129 })
130 }
131}
132
133#[derive(Debug, Clone)]
134pub struct HttpResponse {
135 pub status: u16,
136 pub content_type: String,
137 pub body: Vec<u8>,
138 pub www_authenticate: Option<String>,
140 pub extra_headers: Vec<(String, String)>,
142}
143
144pub fn handle_smart_http(
146 repo: &mut Repository,
147 req: &HttpRequest,
148) -> Result<HttpResponse, ServerError> {
149 handle_smart_http_auth(repo, req, None)
150}
151
152pub fn handle_smart_http_auth(
154 repo: &mut Repository,
155 req: &HttpRequest,
156 basic: Option<&BasicAuthConfig>,
157) -> Result<HttpResponse, ServerError> {
158 handle_smart_http_auth_opts(repo, req, basic, true, "http")
159}
160
161pub fn handle_smart_http_auth_opts(
163 repo: &mut Repository,
164 req: &HttpRequest,
165 basic: Option<&BasicAuthConfig>,
166 enable_lfs: bool,
167 scheme: &str,
168) -> Result<HttpResponse, ServerError> {
169 let verified_basic_user = if let Some(cfg) = basic {
170 match cfg.authorized_user(req.authorization.as_deref()) {
171 Some(user) => Some(user),
172 None => {
173 return Ok(HttpResponse {
174 status: 401,
175 content_type: "text/plain".into(),
176 body: b"unauthorized\n".to_vec(),
177 www_authenticate: Some(cfg.challenge_header()),
178 extra_headers: Vec::new(),
179 });
180 }
181 }
182 } else {
183 None
184 };
185 if crate::lfs::is_lfs_path(&req.path) {
186 if enable_lfs {
187 return crate::lfs::handle_lfs(repo, req, scheme);
188 }
189 return Ok(text(404, b"LFS disabled\n"));
190 }
191 if is_dav_method(&req.method) {
192 if dav_mutation_targets_internal_arks_ref(req) {
193 return Ok(text(
194 403,
195 b"Forbidden: mutations under refs/arks/ are not permitted\n",
196 ));
197 }
198 let pusher = Pusher {
199 transport: "http",
200 verified_user: verified_basic_user,
201 authorization: req.authorization.clone(),
202 };
203 return handle_dav_as(repo, req, &pusher);
204 }
205 let path = req.path.as_str();
206 let wants_v2 = req
207 .git_protocol
208 .as_deref()
209 .map(|v| {
210 v.split(':')
211 .any(|p| p.trim() == "version=2" || p.trim().starts_with("version=2"))
212 })
213 .unwrap_or(false)
214 || req
215 .git_protocol
216 .as_deref()
217 .map(|v| v.contains("version=2"))
218 .unwrap_or(false);
219
220 if path.ends_with("/info/refs") || path == "/info/refs" || path.ends_with("info/refs") {
221 let service = query_param(&req.query, "service").unwrap_or("");
222 if service.is_empty() {
223 return match serve_dumb_path(repo, "info/refs")? {
225 Some((ct, body)) => Ok(typed(200, &ct, body)),
226 None => Ok(text(404, b"not found")),
227 };
228 }
229 if wants_v2 && service == "git-upload-pack" {
230 let mut body = arks_protocol::encode_text_line("# service=git-upload-pack")
233 .map_err(|e| ServerError::Protocol(e.to_string()))?;
234 body.extend(
235 arks_protocol::encode_packet(&arks_protocol::Packet::Flush)
236 .map_err(|e| ServerError::Protocol(e.to_string()))?,
237 );
238 body.extend(v2_capability_advertisement_for(repo)?);
239 return Ok(typed(200, UPLOAD_AD, body));
240 }
241 return match service {
243 "git-upload-pack" => Ok(typed(200, UPLOAD_AD, upload_advertisement(repo)?)),
244 "git-receive-pack" => Ok(typed(200, RECEIVE_AD, receive_advertisement(repo)?)),
245 _ => Ok(text(403, b"unknown service")),
246 };
247 }
248 if req.method.eq_ignore_ascii_case("POST")
249 && (path.ends_with("/git-upload-pack") || path.ends_with("git-upload-pack"))
250 {
251 if looks_like_v2_command(&req.body) {
252 return Ok(typed(
253 200,
254 UPLOAD_RES,
255 handle_v2_request(repo, &req.body, true)?,
256 ));
257 }
258 return Ok(typed(200, UPLOAD_RES, upload_pack_result(repo, &req.body)?));
259 }
260 if req.method.eq_ignore_ascii_case("POST")
261 && (path.ends_with("/git-receive-pack") || path.ends_with("git-receive-pack"))
262 {
263 let pusher = Pusher {
264 transport: "http",
265 verified_user: verified_basic_user,
266 authorization: req.authorization.clone(),
267 };
268 return Ok(typed(
269 200,
270 RECEIVE_RES,
271 receive_pack_as(repo, &req.body, &pusher)?,
272 ));
273 }
274 if req.method.eq_ignore_ascii_case("GET") || req.method.eq_ignore_ascii_case("HEAD") {
276 let rel = path.trim_start_matches('/');
277 if let Some((ct, body)) = serve_dumb_path(repo, rel)? {
278 return Ok(typed(200, &ct, body));
279 }
280 if let Some(idx) = rel.find("objects/") {
282 if let Some((ct, body)) = serve_dumb_path(repo, &rel[idx..])? {
283 return Ok(typed(200, &ct, body));
284 }
285 }
286 if let Some(idx) = rel.find("info/refs") {
287 if let Some((ct, body)) = serve_dumb_path(repo, &rel[idx..])? {
288 return Ok(typed(200, &ct, body));
289 }
290 }
291 }
292 Ok(text(404, b"not found"))
293}
294
295fn dav_mutation_targets_internal_arks_ref(req: &HttpRequest) -> bool {
296 let method = req.method.to_ascii_uppercase();
297 if !matches!(
298 method.as_str(),
299 "PUT" | "MOVE" | "DELETE" | "LOCK" | "UNLOCK" | "MKCOL"
300 ) {
301 return false;
302 }
303 if raw_path_targets_internal_arks_ref(&req.path) {
304 return true;
305 }
306 if let Some(dest) = req.destination.as_deref() {
307 if raw_path_targets_internal_arks_ref(dest) {
308 return true;
309 }
310 }
311 false
312}
313
314fn hex_nibble(b: u8) -> Option<u8> {
315 match b {
316 b'0'..=b'9' => Some(b - b'0'),
317 b'a'..=b'f' => Some(b - b'a' + 10),
318 b'A'..=b'F' => Some(b - b'A' + 10),
319 _ => None,
320 }
321}
322
323fn percent_decode_path(input: &str) -> String {
324 let bytes = input.as_bytes();
325 let mut out = Vec::with_capacity(bytes.len());
326 let mut i = 0usize;
327 while i < bytes.len() {
328 if bytes[i] == b'%'
329 && i + 2 < bytes.len()
330 && let (Some(hi), Some(lo)) = (hex_nibble(bytes[i + 1]), hex_nibble(bytes[i + 2]))
331 {
332 out.push((hi << 4) | lo);
333 i += 3;
334 continue;
335 }
336 out.push(bytes[i]);
337 i += 1;
338 }
339 String::from_utf8_lossy(&out).into_owned()
340}
341
342fn raw_path_targets_internal_arks_ref(raw: &str) -> bool {
343 let path_only = if let Some(idx) = raw.find("://") {
344 let after = &raw[idx + 3..];
345 match after.find('/') {
346 Some(slash) => &after[slash..],
347 None => return false,
348 }
349 } else {
350 raw
351 };
352 let without_query = path_only.split(['?', '#']).next().unwrap_or("");
353 let decoded = percent_decode_path(without_query);
354 let normalized = decoded.replace('\\', "/");
355 let mut segments: Vec<&str> = Vec::new();
356 for seg in normalized.split('/') {
357 if seg.is_empty() || seg == "." {
358 continue;
359 }
360 if seg == ".." {
361 segments.pop();
362 continue;
363 }
364 segments.push(seg);
365 }
366 segments
367 .windows(2)
368 .any(|w| w[0].eq_ignore_ascii_case("refs") && w[1].eq_ignore_ascii_case("arks"))
369}
370
371fn looks_like_v2_command(body: &[u8]) -> bool {
372 body.len() >= 4 && {
374 let s = String::from_utf8_lossy(body);
375 s.contains("command=")
376 }
377}
378
379fn query_param<'a>(query: &'a str, key: &str) -> Option<&'a str> {
380 for part in query.split('&') {
381 if let Some((k, v)) = part.split_once('=') {
382 if k == key {
383 return Some(v);
384 }
385 }
386 }
387 None
388}
389
390fn typed(status: u16, ct: &str, body: Vec<u8>) -> HttpResponse {
391 HttpResponse {
392 status,
393 content_type: ct.into(),
394 body,
395 www_authenticate: None,
396 extra_headers: Vec::new(),
397 }
398}
399
400fn text(status: u16, body: &[u8]) -> HttpResponse {
401 HttpResponse {
402 status,
403 content_type: "text/plain".into(),
404 body: body.to_vec(),
405 www_authenticate: None,
406 extra_headers: Vec::new(),
407 }
408}
409
410#[cfg(test)]
411mod tests {
412 use super::*;
413 use arks_object::{Commit, ObjectKind, RawObject, Signature, Tree, TreeEntry, TreeMode};
414 use arks_store::{ObjectFormat, ObjectStore};
415 use tempfile::TempDir;
416
417 fn seed_repo(format: ObjectFormat) -> (TempDir, Repository) {
418 let dir = TempDir::new().unwrap();
419 let git = dir.path();
420 std::fs::create_dir_all(git.join("objects")).unwrap();
421 std::fs::create_dir_all(git.join("refs/heads")).unwrap();
422 std::fs::write(git.join("HEAD"), b"ref: refs/heads/main\n").unwrap();
423 if format == ObjectFormat::Sha256 {
424 std::fs::write(
425 git.join("config"),
426 "[core]\n\trepositoryformatversion = 1\n\tbare = true\n[extensions]\n\tobjectformat = sha256\n",
427 )
428 .unwrap();
429 } else {
430 std::fs::write(
431 git.join("config"),
432 "[core]\n\trepositoryformatversion = 0\n\tbare = true\n",
433 )
434 .unwrap();
435 }
436 let mut repo = Repository::open(git).unwrap();
437 let blob = repo
438 .store_mut()
439 .put(format, &RawObject::new(ObjectKind::Blob, b"hi\n".to_vec()))
440 .unwrap();
441 let tree = Tree::new(vec![TreeEntry {
442 mode: TreeMode::File,
443 name: "a.txt".into(),
444 oid: blob,
445 }])
446 .unwrap();
447 let tree_oid = repo
448 .store_mut()
449 .put(
450 format,
451 &RawObject::new(ObjectKind::Tree, tree.encode().unwrap()),
452 )
453 .unwrap();
454 let sig = Signature {
455 name: "arks".into(),
456 email: "arks@example.invalid".into(),
457 timestamp: 1_700_000_000,
458 timezone: "+0000".into(),
459 };
460 let commit = Commit {
461 tree: tree_oid,
462 parents: Vec::new(),
463 author: sig.clone(),
464 committer: sig,
465 gpgsig: None,
466 message: "init\n".into(),
467 };
468 let oid = repo
469 .store_mut()
470 .put(
471 format,
472 &RawObject::new(ObjectKind::Commit, commit.encode().unwrap()),
473 )
474 .unwrap();
475 repo.refs_mut()
476 .update("refs/heads/main", &oid, None)
477 .unwrap();
478 (dir, repo)
479 }
480
481 #[test]
482 fn webdav_mutations_targeting_refs_arks_return_403() {
483 let (_dir, mut repo) = seed_repo(ObjectFormat::Sha1);
484 for method in ["PUT", "DELETE", "LOCK", "MOVE"] {
485 let mut req = HttpRequest::new(
486 method,
487 "/repo.git/refs/arks/v2/keep/pin1",
488 "",
489 b"1111111111111111111111111111111111111111\n".to_vec(),
490 );
491 if method == "MOVE" {
492 req.destination = Some("http://127.0.0.1:8080/repo.git/refs/heads/other".into());
493 }
494 let resp = handle_smart_http(&mut repo, &req).unwrap();
495 assert_eq!(
496 resp.status, 403,
497 "WebDAV {method} targeting refs/arks/ must return 403"
498 );
499 }
500
501 let mut move_into_arks = HttpRequest::new("MOVE", "/refs/heads/main", "", Vec::new());
503 move_into_arks.destination =
504 Some("http://127.0.0.1:8080/repo.git/refs/arks/internal/alice/c1".into());
505 let resp = handle_smart_http(&mut repo, &move_into_arks).unwrap();
506 assert_eq!(resp.status, 403);
507 }
508
509 #[test]
510 fn raw_path_targets_internal_arks_ref_blocks_normalized_and_case_bypasses() {
511 let (_dir, mut repo) = seed_repo(ObjectFormat::Sha1);
512 for bypass_path in [
513 "/refs/./arks/v2/keep/x",
514 "/refs//arks/v2/keep/x",
515 "/refs/ARKS/v2/keep/x",
516 "/REFS/ARKS",
517 "/repo.git/refs/./arks/v2/keep/x",
518 "/repo.git/refs//ARKS/v2/keep/x",
519 "/refs%2farks/v2/keep/x",
520 "/refs%2F%2e%2FARKS/v2/keep/x",
521 "/refs/%2E/arks/v2/keep/x",
522 "/refs/heads/../arks/v2/keep/x",
523 "/refs/heads/%2e%2e/ARKS/v2/keep/x",
524 ] {
525 assert!(
526 raw_path_targets_internal_arks_ref(bypass_path),
527 "must detect internal refs/arks bypass '{bypass_path}'"
528 );
529 let req = HttpRequest::new(
530 "PUT",
531 bypass_path,
532 "",
533 b"1111111111111111111111111111111111111111\n".to_vec(),
534 );
535 let resp = handle_smart_http(&mut repo, &req).unwrap();
536 assert_eq!(
537 resp.status, 403,
538 "PUT {bypass_path} must be rejected with 403"
539 );
540 }
541
542 assert!(!raw_path_targets_internal_arks_ref("/refs/heads/main"));
543 assert!(!raw_path_targets_internal_arks_ref("/refs/heads/arks"));
544 assert!(!raw_path_targets_internal_arks_ref("/refs/arks-other/foo"));
545 assert!(!raw_path_targets_internal_arks_ref(
546 "/repo.git/objects/ab/cdef"
547 ));
548 }
549
550 #[test]
551 fn smart_http_v2_info_refs_advertises_sha256_for_sha256_repo() {
552 let (_dir, mut repo) = seed_repo(ObjectFormat::Sha256);
553 let mut req = HttpRequest::new("GET", "/info/refs", "service=git-upload-pack", Vec::new());
554 req.git_protocol = Some("version=2".into());
555 let resp = handle_smart_http(&mut repo, &req).unwrap();
556 assert_eq!(resp.status, 200);
557 let text = String::from_utf8_lossy(&resp.body);
558 assert!(text.contains("object-format=sha256"), "{text}");
559 assert!(!text.contains("object-format=sha1"), "{text}");
560 }
561}