mirror of
https://seed.radicle.dev/rad:z4V1sjrXqjvFdnCUbxPFqd5p4DtH5.git
synced 2026-11-29 02:00:31 +08:00
httpd: End truncated git responses with an error
A killed or failed git process still ended the response body cleanly, so clients saw a complete 200 with a truncated body. Wait for the exit status and end the body with an error when the output was cut short, so hyper aborts the connection. For `git archive` that is any unsuccessful exit. `git http-backend` exits with 1 both after an in-band protocol error and when its `upload-pack` dies, so for it only death by a signal counts. A clone cut short by a dying `upload-pack` still ends cleanly, but the client detects the incomplete pack from its framing. Test the exit statuses, the body errors, the process group and the kill on drop. Co-authored-by: Daniel Norman <daniel@norman.life>
This commit is contained in:
committed by
Daniel Norman
co-authored by
Daniel Norman
parent
0271be8874
commit
ff6c49c064
@@ -17,6 +17,9 @@
|
||||
default `control-group`, systemd signals git directly. The example unit uses
|
||||
`KillMode=mixed`. A git process is now killed when its response is dropped,
|
||||
e.g., when the client disconnects
|
||||
- **Errors for interrupted git responses**: An archive download cut short by a
|
||||
killed or failed `git archive`, or a clone whose `git http-backend` is killed,
|
||||
now ends in a transfer error instead of a complete-looking 200
|
||||
|
||||
## radicle-httpd + radicle-search 0.31.0
|
||||
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
use std::io;
|
||||
use std::process::ExitStatus;
|
||||
|
||||
use axum::body::Body;
|
||||
use futures_util::stream::{self, StreamExt};
|
||||
use tokio::io::AsyncRead;
|
||||
@@ -8,18 +11,151 @@ use tokio_util::io::ReaderStream;
|
||||
/// the daemon's group, e.g., Ctrl-C. The child is killed if it is dropped
|
||||
/// before it is reaped.
|
||||
pub fn git() -> Command {
|
||||
let mut command = Command::new("git");
|
||||
command("git")
|
||||
}
|
||||
|
||||
fn command(program: &str) -> Command {
|
||||
let mut command = Command::new(program);
|
||||
#[cfg(unix)]
|
||||
command.process_group(0);
|
||||
command.kill_on_drop(true);
|
||||
command
|
||||
}
|
||||
|
||||
/// Which exit statuses mean that a process's output is incomplete.
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum Truncated {
|
||||
/// Any unsuccessful exit, e.g., for `git archive`.
|
||||
OnFailure,
|
||||
/// Only termination by a signal, e.g., for `git http-backend`. It exits
|
||||
/// with 1 both after an in-band protocol error and when its `upload-pack`
|
||||
/// dies, so a status of 1 does not tell whether the output is complete.
|
||||
OnSignal,
|
||||
}
|
||||
|
||||
/// Stream `stdout` as a response body that owns `child`, so the child is
|
||||
/// killed if the body is dropped before it ends, e.g., when the client
|
||||
/// disconnects or the daemon exits.
|
||||
pub fn body(mut child: Child, stdout: impl AsyncRead + Send + 'static) -> Body {
|
||||
/// disconnects or the daemon exits. The body ends with an error if the exit
|
||||
/// status means the output is incomplete, so that hyper aborts the response
|
||||
/// instead of completing it.
|
||||
pub fn body(
|
||||
mut child: Child,
|
||||
stdout: impl AsyncRead + Send + 'static,
|
||||
truncated: Truncated,
|
||||
) -> Body {
|
||||
let exit = stream::once(async move { child.wait().await })
|
||||
.filter_map(|_| async { None::<std::io::Result<_>> });
|
||||
.filter_map(move |status| async move { exit_error(status, truncated).map(Err) });
|
||||
Body::from_stream(ReaderStream::new(stdout).chain(exit))
|
||||
}
|
||||
|
||||
/// The error that ends a response body if the output is incomplete.
|
||||
fn exit_error(status: io::Result<ExitStatus>, truncated: Truncated) -> Option<io::Error> {
|
||||
let complete = |status: ExitStatus| match truncated {
|
||||
Truncated::OnFailure => status.success(),
|
||||
Truncated::OnSignal => status.code().is_some(),
|
||||
};
|
||||
match status {
|
||||
Ok(status) if complete(status) => None,
|
||||
Ok(status) => Some(io::Error::other(format!("git exited with {status}"))),
|
||||
Err(e) => Some(e),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use std::os::unix::process::ExitStatusExt as _;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn exited(code: i32) -> io::Result<ExitStatus> {
|
||||
Ok(ExitStatus::from_raw(code << 8))
|
||||
}
|
||||
|
||||
fn killed(signal: i32) -> io::Result<ExitStatus> {
|
||||
Ok(ExitStatus::from_raw(signal))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_exit_error_on_failure() {
|
||||
assert!(exit_error(exited(0), Truncated::OnFailure).is_none());
|
||||
assert!(exit_error(exited(1), Truncated::OnFailure).is_some());
|
||||
assert!(exit_error(killed(9), Truncated::OnFailure).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_exit_error_on_signal() {
|
||||
assert!(exit_error(exited(0), Truncated::OnSignal).is_none());
|
||||
assert!(exit_error(exited(1), Truncated::OnSignal).is_none());
|
||||
assert!(exit_error(killed(9), Truncated::OnSignal).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_exit_error_on_wait_error() {
|
||||
let status = Err(io::Error::other("wait failed"));
|
||||
assert!(exit_error(status, Truncated::OnSignal).is_some());
|
||||
}
|
||||
|
||||
/// Run `script` through `sh` and collect its output as a response body.
|
||||
async fn collect(script: &str, truncated: Truncated) -> Result<Vec<u8>, axum::Error> {
|
||||
let mut child = command("sh")
|
||||
.args(["-c", script])
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let stdout = child.stdout.take().unwrap();
|
||||
axum::body::to_bytes(body(child, stdout, truncated), usize::MAX)
|
||||
.await
|
||||
.map(|bytes| bytes.to_vec())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_body_complete() {
|
||||
let body = collect("printf abc", Truncated::OnFailure).await.unwrap();
|
||||
assert_eq!(body, b"abc");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_body_ends_with_error_when_killed() {
|
||||
let script = "printf abc; kill -9 $$";
|
||||
assert!(collect(script, Truncated::OnFailure).await.is_err());
|
||||
assert!(collect(script, Truncated::OnSignal).await.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_body_exit_code() {
|
||||
let script = "printf abc; exit 1";
|
||||
assert!(collect(script, Truncated::OnFailure).await.is_err());
|
||||
assert!(collect(script, Truncated::OnSignal).await.is_ok());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_child_in_own_process_group() {
|
||||
let body = collect("echo $$ $(ps -o pgid= -p $$)", Truncated::OnFailure)
|
||||
.await
|
||||
.unwrap();
|
||||
let output = String::from_utf8(body).unwrap();
|
||||
let ids: Vec<&str> = output.split_whitespace().collect();
|
||||
assert_eq!(ids.len(), 2, "{output}");
|
||||
assert_eq!(ids[0], ids[1], "the child leads its own process group");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_dropped_body_kills_child() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let marker = tmp.path().join("alive");
|
||||
let script = format!("sleep 0.5 && touch {}", marker.display());
|
||||
let mut child = command("sh")
|
||||
.args(["-c", &script])
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let stdout = child.stdout.take().unwrap();
|
||||
|
||||
drop(body(child, stdout, Truncated::OnFailure));
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
|
||||
assert!(!marker.exists(), "the child outlived its body");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ use tokio::io::{AsyncBufReadExt, BufReader};
|
||||
use tokio_util::io::StreamReader;
|
||||
use tower_http::decompression::RequestDecompressionLayer;
|
||||
|
||||
use crate::children::Truncated;
|
||||
use crate::error::GitError as Error;
|
||||
|
||||
pub fn router(profile: Arc<Profile>, aliases: Arc<HashMap<String, RepoId>>) -> Router {
|
||||
@@ -192,7 +193,7 @@ async fn git_http_backend(
|
||||
.and_then(|values| values.first()?.split_whitespace().next()?.parse().ok())
|
||||
.unwrap_or(StatusCode::OK);
|
||||
|
||||
let body = crate::children::body(child, stdout);
|
||||
let body = crate::children::body(child, stdout, Truncated::OnSignal);
|
||||
|
||||
Ok((status, headers, body))
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ use tokio::io::BufReader;
|
||||
|
||||
use crate::api::query::RawQuery;
|
||||
use crate::axum_extra::Path;
|
||||
use crate::children::Truncated;
|
||||
use crate::error::RawError as Error;
|
||||
|
||||
const MAX_BLOB_SIZE: usize = 10_485_760;
|
||||
@@ -309,7 +310,8 @@ async fn archive_by_committish(
|
||||
|
||||
let stdout = child.stdout.take().expect("stdout was captured");
|
||||
let mut response = response;
|
||||
*response.body_mut() = crate::children::body(child, BufReader::new(stdout));
|
||||
*response.body_mut() =
|
||||
crate::children::body(child, BufReader::new(stdout), Truncated::OnFailure);
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user