1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
|
//! Git HTTP Protocol Handlers
//!
//! This module implements the HTTP handlers for Git Smart HTTP protocol.
use std::path::PathBuf;
use hyper::{body::Bytes, Response, StatusCode};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tracing::{debug, error, warn};
use super::protocol::{GitService, PktLine};
use super::subprocess::GitSubprocess;
/// Handle GET /info/refs?service=git-{upload,receive}-pack
///
/// This advertises the repository's refs to the client.
pub async fn handle_info_refs(
repo_path: PathBuf,
service: GitService,
) -> Result<Response<String>, GitError> {
debug!("Handling info/refs for {:?} with service {:?}", repo_path, service);
// Check if repository exists
if !repo_path.exists() {
warn!("Repository not found: {:?}", repo_path);
return Err(GitError::RepositoryNotFound);
}
// Spawn git with --advertise-refs
let mut git = GitSubprocess::spawn(service, &repo_path, true)
.map_err(|e| {
error!("Failed to spawn git process: {}", e);
GitError::ProcessSpawnFailed(e)
})?;
// Read the output from git
let mut output = Vec::new();
if let Some(stdout) = git.take_stdout() {
let mut stdout = stdout;
stdout.read_to_end(&mut output).await
.map_err(|e| {
error!("Failed to read git output: {}", e);
GitError::IoError(e)
})?;
}
// Wait for process to complete
let status = git.wait().await
.map_err(|e| {
error!("Failed to wait for git process: {}", e);
GitError::IoError(e)
})?;
if !status.success() {
error!("Git process failed with status: {:?}", status);
return Err(GitError::GitFailed(status.code()));
}
// Build response with pkt-line header
let mut response_body = Vec::new();
// First line: service advertisement
let service_line = format!("# service={}\n", service.as_str());
response_body.extend_from_slice(&PktLine::data(service_line.as_bytes()).encode());
response_body.extend_from_slice(&PktLine::flush().encode());
// Then the git output
response_body.extend_from_slice(&output);
Ok(Response::builder()
.status(StatusCode::OK)
.header("content-type", service.advertisement_content_type())
.header("cache-control", "no-cache")
.body(String::from_utf8_lossy(&response_body).to_string())
.unwrap())
}
/// Handle POST /git-upload-pack (clone/fetch)
pub async fn handle_upload_pack(
repo_path: PathBuf,
request_body: Bytes,
) -> Result<Response<String>, GitError> {
debug!("Handling upload-pack for {:?}", repo_path);
if !repo_path.exists() {
return Err(GitError::RepositoryNotFound);
}
// Spawn git upload-pack
let mut git = GitSubprocess::spawn(GitService::UploadPack, &repo_path, false)
.map_err(GitError::ProcessSpawnFailed)?;
// Write request to git's stdin
if let Some(mut stdin) = git.take_stdin() {
stdin.write_all(&request_body).await
.map_err(GitError::IoError)?;
// Close stdin to signal end of input
drop(stdin);
}
// Read response from git's stdout
let mut output = Vec::new();
if let Some(stdout) = git.take_stdout() {
let mut stdout = stdout;
stdout.read_to_end(&mut output).await
.map_err(GitError::IoError)?;
}
// Wait for process
let status = git.wait().await
.map_err(GitError::IoError)?;
if !status.success() {
return Err(GitError::GitFailed(status.code()));
}
Ok(Response::builder()
.status(StatusCode::OK)
.header("content-type", GitService::UploadPack.result_content_type())
.header("cache-control", "no-cache")
.body(String::from_utf8_lossy(&output).to_string())
.unwrap())
}
/// Handle POST /git-receive-pack (push)
///
/// This includes an authorization hook point where GRASP validation will be added.
pub async fn handle_receive_pack(
repo_path: PathBuf,
request_body: Bytes,
) -> Result<Response<String>, GitError> {
debug!("Handling receive-pack for {:?}", repo_path);
if !repo_path.exists() {
return Err(GitError::RepositoryNotFound);
}
// TODO: Add GRASP authorization here
// For now, we'll accept all pushes to enable testing
debug!("Authorization check would go here (currently accepting all pushes)");
// Spawn git receive-pack
let mut git = GitSubprocess::spawn(GitService::ReceivePack, &repo_path, false)
.map_err(GitError::ProcessSpawnFailed)?;
// Write request to git's stdin
if let Some(mut stdin) = git.take_stdin() {
stdin.write_all(&request_body).await
.map_err(GitError::IoError)?;
drop(stdin);
}
// Read response from git's stdout
let mut output = Vec::new();
if let Some(stdout) = git.take_stdout() {
let mut stdout = stdout;
stdout.read_to_end(&mut output).await
.map_err(GitError::IoError)?;
}
// Wait for process
let status = git.wait().await
.map_err(GitError::IoError)?;
if !status.success() {
return Err(GitError::GitFailed(status.code()));
}
Ok(Response::builder()
.status(StatusCode::OK)
.header("content-type", GitService::ReceivePack.result_content_type())
.header("cache-control", "no-cache")
.body(String::from_utf8_lossy(&output).to_string())
.unwrap())
}
/// Errors that can occur in Git handlers
#[derive(Debug)]
pub enum GitError {
RepositoryNotFound,
ProcessSpawnFailed(std::io::Error),
IoError(std::io::Error),
GitFailed(Option<i32>),
Unauthorized,
}
impl std::fmt::Display for GitError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::RepositoryNotFound => write!(f, "repository not found"),
Self::ProcessSpawnFailed(e) => write!(f, "failed to spawn git process: {}", e),
Self::IoError(e) => write!(f, "IO error: {}", e),
Self::GitFailed(code) => write!(f, "git process failed with code: {:?}", code),
Self::Unauthorized => write!(f, "unauthorized"),
}
}
}
impl std::error::Error for GitError {}
impl GitError {
/// Convert to HTTP status code
pub fn status_code(&self) -> StatusCode {
match self {
Self::RepositoryNotFound => StatusCode::NOT_FOUND,
Self::Unauthorized => StatusCode::FORBIDDEN,
_ => StatusCode::INTERNAL_SERVER_ERROR,
}
}
}
|