Skip to main content

arks_server/daemon/
session.rs

1//! One `git://` connection: request checks in `git daemon` order, then the
2//! service itself.
3//!
4//! Primary: <https://git-scm.com/docs/git-daemon> (SERVICES, `--informative-errors`,
5//! `--access-hook`, per-repository `daemon.<service>` overrides). Check order and
6//! error wording follow observed stock `git daemon`.
7
8use super::access_hook::{HookRequest, run_access_hook};
9use super::archive::{drain_upload_archive_args, serve_upload_archive_partial};
10use super::options::{DaemonOptions, DaemonService};
11use super::path::{HostContext, ResolvedRepo, resolve_request};
12use super::request::ServiceRequest;
13use crate::error::ServerError;
14use crate::stdio::{receive_pack_stream, upload_pack_stream};
15use arks_config::ConfigSet;
16use arks_protocol::{Packet, encode_packet};
17use arks_repo::Repository;
18use std::io::{Read, Write};
19use std::net::SocketAddr;
20
21/// Generic refusal sent without `--informative-errors`.
22const ACCESS_DENIED: &str = "access denied or repository not exported";
23
24/// What happened to one request.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum Outcome {
27    /// The service ran to completion.
28    Served,
29    /// The request was refused (or the service failed).
30    Refused,
31}
32
33/// Run every check, then the service, on `stream`.
34pub(super) fn handle_request<S: Read + Write>(
35    stream: &mut S,
36    req: &ServiceRequest,
37    opts: &DaemonOptions,
38    peer: Option<SocketAddr>,
39) -> Result<Outcome, ServerError> {
40    let log = &opts.log;
41    let Some(service) = DaemonService::from_request(&req.command).filter(|_| !req.path.is_empty())
42    else {
43        log.error(&format!("Protocol error: '{}'", req.line));
44        return Ok(Outcome::Refused);
45    };
46    let dir = req.path.as_str();
47    log.info(&format!("Request {} for '{dir}'", service.name()));
48    let policy = opts.services.get(service);
49    if !policy.enabled && !policy.overridable {
50        log.error(&format!("'{}': service not enabled.", service.name()));
51        return refuse(stream, opts, dir, "service not enabled");
52    }
53    let host = host_context(req, opts);
54    let Some(repo) = resolve_request(opts, dir, host.as_ref()) else {
55        return refuse(stream, opts, dir, "no such repository");
56    };
57    if !opts.export_all && !repo.git_dir.join("git-daemon-export-ok").exists() {
58        log.error(&format!("'{}': repository not exported.", repo.validated));
59        return refuse(stream, opts, dir, "repository not exported");
60    }
61    let mut enabled = policy.enabled;
62    if policy.overridable {
63        if let Some(v) = ConfigSet::load(Some(&repo.git_dir)).get_bool(service.config_key()) {
64            enabled = v;
65        }
66    }
67    if !enabled {
68        log.error(&format!(
69            "'{}': service not enabled for '{}'",
70            service.name(),
71            repo.validated
72        ));
73        return refuse(stream, opts, dir, "service not enabled");
74    }
75    if let Some(hook) = opts.access_hook.as_deref() {
76        let hook_req = HookRequest {
77            service: service.name(),
78            validated: &repo.validated,
79            git_dir: &repo.git_dir,
80            host: host.as_ref(),
81            peer,
82        };
83        if let Err(msg) = run_access_hook(hook, &hook_req) {
84            let msg = msg.unwrap_or_else(|| "service rejected".to_string());
85            return refuse(stream, opts, dir, &msg);
86        }
87    }
88    let forge_store = crate::web_ui::store::ForgeStore::load_shared(&repo.git_dir);
89    if forge_store.corrupt || forge_store.is_private() {
90        log.error(&format!(
91            "'{}': access denied (private or corrupted forge metadata).",
92            repo.validated
93        ));
94        return refuse(stream, opts, dir, "access denied");
95    }
96    if service == DaemonService::ReceivePack && forge_store.archived {
97        log.error(&format!("'{}': repository is archived.", repo.validated));
98        return refuse(stream, opts, dir, "repository is archived");
99    }
100    run_service(stream, service, &repo, opts)
101}
102
103fn host_context(req: &ServiceRequest, opts: &DaemonOptions) -> Option<HostContext> {
104    let attr = req.host.as_ref()?;
105    let info = opts
106        .platform
107        .lookup_host(&attr.hostname)
108        .unwrap_or_default();
109    Some(HostContext {
110        hostname: attr.hostname.clone(),
111        canonical: info.canonical,
112        ip: info.ip,
113        port: attr.port.clone(),
114    })
115}
116
117fn run_service<S: Read + Write>(
118    stream: &mut S,
119    service: DaemonService,
120    repo: &ResolvedRepo,
121    opts: &DaemonOptions,
122) -> Result<Outcome, ServerError> {
123    let mut repository = match Repository::open(&repo.git_dir) {
124        Ok(r) => r,
125        Err(e) => {
126            opts.log.error(&format!("fatal: {e}"));
127            return refuse(stream, opts, &repo.validated, "no such repository");
128        }
129    };
130    let result = match service {
131        DaemonService::UploadPack => upload_pack_stream(&repository, stream),
132        DaemonService::ReceivePack => receive_pack_stream(&mut repository, stream),
133        DaemonService::UploadArchive => drain_upload_archive_args(stream)
134            .and_then(|args| serve_upload_archive_partial(&repository, &args, stream, false)),
135    };
136    match result {
137        Ok(()) => Ok(Outcome::Served),
138        Err(e) => {
139            opts.log.error(&format!("fatal: {e}"));
140            Ok(Outcome::Refused)
141        }
142    }
143}
144
145/// Send `ERR <msg>: <dir>` (generic message unless `--informative-errors`).
146fn refuse<W: Write>(
147    stream: &mut W,
148    opts: &DaemonOptions,
149    dir: &str,
150    msg: &str,
151) -> Result<Outcome, ServerError> {
152    let msg = if opts.informative_errors {
153        msg
154    } else {
155        ACCESS_DENIED
156    };
157    let pkt = encode_packet(&Packet::Data(format!("ERR {msg}: {dir}").into_bytes()))
158        .map_err(|e| ServerError::Protocol(e.to_string()))?;
159    stream.write_all(&pkt)?;
160    stream.flush()?;
161    Ok(Outcome::Refused)
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167    use crate::daemon::log::DaemonLog;
168    use crate::daemon::request::parse_service_payload;
169    use std::io::Cursor;
170    use std::path::Path;
171    use tempfile::TempDir;
172
173    /// In-memory duplex: reads `input`, collects writes.
174    struct Duplex {
175        input: Cursor<Vec<u8>>,
176        output: Vec<u8>,
177    }
178    impl Read for Duplex {
179        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
180            self.input.read(buf)
181        }
182    }
183    impl Write for Duplex {
184        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
185            self.output.extend_from_slice(buf);
186            Ok(buf.len())
187        }
188        fn flush(&mut self) -> std::io::Result<()> {
189            Ok(())
190        }
191    }
192
193    fn bare(at: &Path, exported: bool) {
194        std::fs::create_dir_all(at.join("objects")).unwrap();
195        std::fs::create_dir_all(at.join("refs/heads")).unwrap();
196        std::fs::write(at.join("HEAD"), b"ref: refs/heads/main\n").unwrap();
197        std::fs::write(at.join("config"), b"[core]\n\tbare = true\n").unwrap();
198        if exported {
199            std::fs::write(at.join("git-daemon-export-ok"), b"").unwrap();
200        }
201    }
202
203    fn ask(opts: &DaemonOptions, payload: &[u8]) -> (Outcome, String) {
204        let req = parse_service_payload(payload, &opts.log).unwrap();
205        let mut io = Duplex {
206            input: Cursor::new(b"0000".to_vec()),
207            output: Vec::new(),
208        };
209        let out = handle_request(&mut io, &req, opts, None).unwrap();
210        (out, String::from_utf8_lossy(&io.output).to_string())
211    }
212
213    fn setup() -> (TempDir, DaemonOptions) {
214        let root = TempDir::new().unwrap();
215        bare(&root.path().join("pub.git"), true);
216        bare(&root.path().join("hidden.git"), false);
217        let noup = root.path().join("noup.git");
218        bare(&noup, true);
219        std::fs::write(
220            noup.join("config"),
221            b"[core]\n\tbare = true\n[daemon]\n\tuploadpack = false\n",
222        )
223        .unwrap();
224        let arch = root.path().join("arch.git");
225        bare(&arch, true);
226        std::fs::write(arch.join("config"), b"[daemon]\n\tuploadarch\n").unwrap();
227        let opts = DaemonOptions {
228            base_path: Some(root.path().to_path_buf()),
229            log: DaemonLog::memory(true),
230            ..DaemonOptions::default()
231        };
232        (root, opts)
233    }
234
235    #[test]
236    fn default_errors_are_generic() {
237        let (_root, opts) = setup();
238        for (payload, dir) in [
239            (&b"git-upload-pack /nope.git\0"[..], "/nope.git"),
240            (b"git-upload-pack /hidden.git\0", "/hidden.git"),
241            (b"git-receive-pack /pub.git\0", "/pub.git"),
242            (b"git-upload-pack /noup.git\0", "/noup.git"),
243        ] {
244            let (out, text) = ask(&opts, payload);
245            assert_eq!(out, Outcome::Refused);
246            let want = format!("ERR access denied or repository not exported: {dir}");
247            assert_eq!(text, format!("{:04x}{want}", want.len() + 4));
248        }
249        let lines = opts.log.lines();
250        assert!(
251            lines
252                .iter()
253                .any(|l| l.ends_with("/hidden.git': repository not exported."))
254        );
255        assert!(
256            lines
257                .iter()
258                .any(|l| l.starts_with("'receive-pack': service not enabled for '"))
259        );
260        assert!(
261            lines
262                .iter()
263                .any(|l| l.starts_with("'upload-pack': service not enabled for '"))
264        );
265    }
266
267    #[test]
268    fn informative_errors_name_the_reason() {
269        let (_root, mut opts) = setup();
270        opts.informative_errors = true;
271        let cases: [(&[u8], &str); 4] = [
272            (
273                b"git-upload-pack /nope.git\0",
274                "no such repository: /nope.git",
275            ),
276            (
277                b"git-upload-pack /hidden.git\0",
278                "repository not exported: /hidden.git",
279            ),
280            (
281                b"git-receive-pack /pub.git\0",
282                "service not enabled: /pub.git",
283            ),
284            (b"git-upload-pack pub.git\0", "no such repository: pub.git"),
285        ];
286        for (payload, want) in cases {
287            let (_, text) = ask(&opts, payload);
288            assert!(text.ends_with(&format!("ERR {want}")), "{text}");
289        }
290    }
291
292    #[test]
293    fn per_repo_override_and_forbid_override() {
294        let (_root, mut opts) = setup();
295        opts.informative_errors = true;
296        // daemon.uploadarch (bare key = true) enables upload-archive for arch.git.
297        let (out, text) = ask(&opts, b"git-upload-archive /arch.git\0");
298        assert_eq!(out, Outcome::Served, "{text}");
299        assert!(!text.contains("service not enabled"), "{text}");
300        let (_, text) = ask(&opts, b"git-upload-archive /pub.git\0");
301        assert!(text.ends_with("ERR service not enabled: /pub.git"));
302        // --forbid-override=upload-pack ignores daemon.uploadpack=false.
303        opts.services.upload_pack.overridable = false;
304        let (out, _) = ask(&opts, b"git-upload-pack /noup.git\0");
305        assert_eq!(out, Outcome::Served);
306        // --forbid-override=receive-pack with receive-pack disabled refuses early.
307        opts.services.receive_pack.overridable = false;
308        let (_, text) = ask(&opts, b"git-receive-pack /nope.git\0");
309        assert!(text.ends_with("ERR service not enabled: /nope.git"));
310        assert!(
311            opts.log
312                .lines()
313                .contains(&"'receive-pack': service not enabled.".to_string())
314        );
315    }
316
317    #[test]
318    fn unknown_service_is_a_protocol_error_without_reply() {
319        let (_root, opts) = setup();
320        let (out, text) = ask(&opts, b"git-foo /pub.git\0");
321        assert_eq!(out, Outcome::Refused);
322        assert!(text.is_empty());
323        assert!(
324            opts.log
325                .lines()
326                .contains(&"Protocol error: 'git-foo /pub.git'".to_string())
327        );
328    }
329
330    #[test]
331    fn export_all_serves_unmarked_repository() {
332        let (_root, mut opts) = setup();
333        opts.export_all = true;
334        let (out, text) = ask(&opts, b"git-upload-pack /hidden.git\0");
335        assert_eq!(out, Outcome::Served, "{text}");
336    }
337
338    #[cfg(unix)]
339    #[test]
340    fn access_hook_decline_message_needs_informative_errors() {
341        use std::os::unix::fs::PermissionsExt;
342        let (root, mut opts) = setup();
343        let hook = root.path().join("hook.sh");
344        std::fs::write(&hook, "#!/bin/sh\necho 'nope from hook'\nexit 1\n").unwrap();
345        std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();
346        opts.access_hook = Some(hook.clone());
347        let (_, text) = ask(&opts, b"git-upload-pack /pub.git\0");
348        assert!(text.ends_with("ERR access denied or repository not exported: /pub.git"));
349        opts.informative_errors = true;
350        let (_, text) = ask(&opts, b"git-upload-pack /pub.git\0");
351        assert!(text.ends_with("ERR nope from hook: /pub.git"), "{text}");
352        std::fs::write(&hook, "#!/bin/sh\nexit 2\n").unwrap();
353        let (_, text) = ask(&opts, b"git-upload-pack /pub.git\0");
354        assert!(text.ends_with("ERR service rejected: /pub.git"), "{text}");
355        std::fs::write(&hook, "#!/bin/sh\nexit 0\n").unwrap();
356        let (out, _) = ask(&opts, b"git-upload-pack /pub.git\0");
357        assert_eq!(out, Outcome::Served);
358    }
359
360    #[test]
361    fn daemon_refuses_private_repo_and_blocks_receive_pack_on_archived_repo() {
362        let (root, mut opts) = setup();
363        opts.informative_errors = true;
364        opts.services.receive_pack.enabled = true;
365
366        // Private repository refuses both upload-pack and receive-pack with "access denied".
367        let priv_dir = root.path().join("priv.git");
368        bare(&priv_dir, true);
369        {
370            let mut st = crate::web_ui::store::ForgeStore::lock_mut(&priv_dir);
371            st.visibility = "private".into();
372            st.commit().unwrap();
373        }
374        let (out_up, text_up) = ask(&opts, b"git-upload-pack /priv.git\0");
375        assert_eq!(out_up, Outcome::Refused);
376        assert!(
377            text_up.ends_with("ERR access denied: /priv.git"),
378            "{text_up}"
379        );
380        let (out_rp, text_rp) = ask(&opts, b"git-receive-pack /priv.git\0");
381        assert_eq!(out_rp, Outcome::Refused);
382        assert!(
383            text_rp.ends_with("ERR access denied: /priv.git"),
384            "{text_rp}"
385        );
386
387        // Archived repository allows upload-pack but refuses receive-pack.
388        let archived_dir = root.path().join("archived.git");
389        bare(&archived_dir, true);
390        {
391            let mut st = crate::web_ui::store::ForgeStore::lock_mut(&archived_dir);
392            st.archived = true;
393            st.commit().unwrap();
394        }
395        let (out_a_up, text_a_up) = ask(&opts, b"git-upload-pack /archived.git\0");
396        assert_eq!(out_a_up, Outcome::Served, "{text_a_up}");
397        let (out_a_rp, text_a_rp) = ask(&opts, b"git-receive-pack /archived.git\0");
398        assert_eq!(out_a_rp, Outcome::Refused);
399        assert!(
400            text_a_rp.ends_with("ERR repository is archived: /archived.git"),
401            "{text_a_rp}"
402        );
403
404        // Corrupt store.json fails closed for both services.
405        let corrupt_dir = root.path().join("corrupt.git");
406        bare(&corrupt_dir, true);
407        std::fs::create_dir_all(corrupt_dir.join("arks-forge")).unwrap();
408        std::fs::write(corrupt_dir.join("arks-forge").join("store.json"), b"{bad").unwrap();
409        let (out_c_up, text_c_up) = ask(&opts, b"git-upload-pack /corrupt.git\0");
410        assert_eq!(out_c_up, Outcome::Refused);
411        assert!(
412            text_c_up.ends_with("ERR access denied: /corrupt.git"),
413            "{text_c_up}"
414        );
415    }
416}