| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
use git_command::{Operation, Request}; |
| 9 |
use sqlx::PgPool; |
| 10 |
use std::fmt::Write as _; |
| 11 |
|
| 12 |
use crate::db::{self, UserId, Username}; |
| 13 |
use crate::validation::validate_git_repo_name; |
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
pub const MNW_ADMIN_PATH: &str = "/opt/mnw/current/mnw-admin"; |
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
fn git_home() -> std::path::PathBuf { |
| 24 |
std::path::PathBuf::from(std::env::var("GIT_HOME").unwrap_or_else(|_| "/opt/git".to_string())) |
| 25 |
} |
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
pub fn authorized_keys_path() -> std::path::PathBuf { |
| 31 |
git_home().join(".ssh").join("authorized_keys") |
| 32 |
} |
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
pub async fn dispatch(pool: &PgPool, key_id_str: &str) -> anyhow::Result<()> { |
| 47 |
let original_cmd = std::env::var("SSH_ORIGINAL_COMMAND") |
| 48 |
.map_err(|_| anyhow::anyhow!("SSH_ORIGINAL_COMMAND not set"))?; |
| 49 |
|
| 50 |
|
| 51 |
let key_id: db::SshKeyId = key_id_str |
| 52 |
.parse() |
| 53 |
.map_err(|_| anyhow::anyhow!("invalid key ID"))?; |
| 54 |
|
| 55 |
let (_, user_id, ssh_username) = db::ssh_keys::get_key_with_user(pool, key_id) |
| 56 |
.await? |
| 57 |
.ok_or_else(|| anyhow::anyhow!("SSH key not found"))?; |
| 58 |
|
| 59 |
|
| 60 |
let user = db::users::get_user_by_id(pool, user_id) |
| 61 |
.await? |
| 62 |
.ok_or_else(|| anyhow::anyhow!("user not found for SSH key"))?; |
| 63 |
if user.is_suspended() { |
| 64 |
anyhow::bail!("account is suspended"); |
| 65 |
} |
| 66 |
if user.is_deactivated() { |
| 67 |
anyhow::bail!("account is deactivated"); |
| 68 |
} |
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
let _ = &ssh_username; |
| 79 |
if original_cmd.starts_with("git-") { |
| 80 |
exec_git_operation(pool, user_id, &original_cmd).await |
| 81 |
} else { |
| 82 |
anyhow::bail!( |
| 83 |
"management commands have moved; run `ssh cli.makenot.work repo list` (or `help`)" |
| 84 |
) |
| 85 |
} |
| 86 |
} |
| 87 |
|
| 88 |
async fn exec_git_operation( |
| 89 |
pool: &PgPool, |
| 90 |
user_id: UserId, |
| 91 |
original_cmd: &str, |
| 92 |
) -> anyhow::Result<()> { |
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
let request: Request<'_> = |
| 98 |
git_command::parse(original_cmd).map_err(|e| anyhow::anyhow!("{e}"))?; |
| 99 |
let (operation, owner, repo_name) = (request.operation, request.owner, request.repo); |
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
let owner_username = |
| 108 |
Username::new(owner).map_err(|_| anyhow::anyhow!("repository not found"))?; |
| 109 |
validate_git_repo_name(repo_name).map_err(|_| anyhow::anyhow!("repository not found"))?; |
| 110 |
|
| 111 |
let owner_user = db::users::get_user_by_username(pool, &owner_username) |
| 112 |
.await? |
| 113 |
.ok_or_else(|| anyhow::anyhow!("repository not found"))?; |
| 114 |
|
| 115 |
let repo = |
| 116 |
match db::git_repos::get_repo_by_user_and_name(pool, owner_user.id, repo_name).await? { |
| 117 |
Some(repo) => repo, |
| 118 |
None => { |
| 119 |
|
| 120 |
if operation != Operation::ReceivePack || user_id != owner_user.id { |
| 121 |
anyhow::bail!("repository not found"); |
| 122 |
} |
| 123 |
|
| 124 |
tracing::info!(owner = %owner, repo = %repo_name, "registering new repository"); |
| 125 |
db::git_repos::create_repo(pool, owner_user.id, repo_name).await? |
| 126 |
} |
| 127 |
}; |
| 128 |
|
| 129 |
|
| 130 |
let is_owner = user_id == owner_user.id; |
| 131 |
match operation { |
| 132 |
Operation::ReceivePack => { |
| 133 |
if !is_owner { |
| 134 |
let can_push = db::repo_collaborators::can_user_push(pool, repo.id, user_id) |
| 135 |
.await |
| 136 |
.unwrap_or_else(|e| { |
| 137 |
|
| 138 |
|
| 139 |
|
| 140 |
tracing::warn!(repo_id = %repo.id, user_id = %user_id, error = ?e, "can_user_push check failed; denying push"); |
| 141 |
false |
| 142 |
}); |
| 143 |
if !can_push { |
| 144 |
anyhow::bail!( |
| 145 |
"permission denied: you do not have push access to {owner}/{repo_name}" |
| 146 |
); |
| 147 |
} |
| 148 |
} |
| 149 |
|
| 150 |
|
| 151 |
|
| 152 |
|
| 153 |
|
| 154 |
let owner_dir = git_repos_root().join(owner_username.as_ref()); |
| 155 |
crate::git::enforce_disk_quota(owner_dir).await?; |
| 156 |
|
| 157 |
ensure_bare_repo_on_disk(&git_repos_root(), owner_username.as_ref(), repo_name)?; |
| 158 |
} |
| 159 |
Operation::UploadPack | Operation::UploadArchive => { |
| 160 |
if repo.visibility == db::Visibility::Private && !is_owner { |
| 161 |
let is_collab = db::repo_collaborators::is_collaborator(pool, repo.id, user_id) |
| 162 |
.await |
| 163 |
.unwrap_or_else(|e| { |
| 164 |
|
| 165 |
|
| 166 |
|
| 167 |
tracing::warn!(repo_id = %repo.id, user_id = %user_id, error = ?e, "is_collaborator check failed; denying read"); |
| 168 |
false |
| 169 |
}); |
| 170 |
if !is_collab { |
| 171 |
anyhow::bail!("repository not found"); |
| 172 |
} |
| 173 |
} |
| 174 |
} |
| 175 |
} |
| 176 |
|
| 177 |
|
| 178 |
|
| 179 |
|
| 180 |
|
| 181 |
|
| 182 |
|
| 183 |
run_git_shell(&request.shell_command()).await |
| 184 |
} |
| 185 |
|
| 186 |
|
| 187 |
|
| 188 |
|
| 189 |
|
| 190 |
|
| 191 |
|
| 192 |
|
| 193 |
|
| 194 |
|
| 195 |
|
| 196 |
|
| 197 |
|
| 198 |
|
| 199 |
|
| 200 |
|
| 201 |
|
| 202 |
|
| 203 |
fn ensure_bare_repo_on_disk( |
| 204 |
root: &std::path::Path, |
| 205 |
owner: &str, |
| 206 |
repo_name: &str, |
| 207 |
) -> anyhow::Result<()> { |
| 208 |
let owner_dir = root.join(owner); |
| 209 |
let repo_dir = owner_dir.join(format!("{repo_name}.git")); |
| 210 |
if repo_dir.exists() { |
| 211 |
return Ok(()); |
| 212 |
} |
| 213 |
|
| 214 |
tracing::info!(path = %repo_dir.display(), "creating bare repository on disk"); |
| 215 |
std::fs::create_dir_all(&owner_dir)?; |
| 216 |
crate::git::init_bare_repo(&repo_dir)?; |
| 217 |
|
| 218 |
|
| 219 |
|
| 220 |
|
| 221 |
let token = std::env::var("BUILD_TRIGGER_TOKEN").ok(); |
| 222 |
if let Err(error) = install_hooks_for_repo(&repo_dir, token.as_deref(), owner, repo_name) { |
| 223 |
tracing::warn!(error = ?error, path = %repo_dir.display(), "hooks not installed"); |
| 224 |
} |
| 225 |
|
| 226 |
Ok(()) |
| 227 |
} |
| 228 |
|
| 229 |
|
| 230 |
fn git_repos_root() -> std::path::PathBuf { |
| 231 |
std::path::PathBuf::from( |
| 232 |
std::env::var("GIT_REPOS_PATH").unwrap_or_else(|_| "/opt/git".to_string()), |
| 233 |
) |
| 234 |
} |
| 235 |
|
| 236 |
|
| 237 |
|
| 238 |
|
| 239 |
|
| 240 |
|
| 241 |
|
| 242 |
|
| 243 |
|
| 244 |
|
| 245 |
async fn run_git_shell(original_cmd: &str) -> anyhow::Result<()> { |
| 246 |
use tokio::process::Command; |
| 247 |
|
| 248 |
let mut child = Command::new("git-shell") |
| 249 |
.args(["-c", original_cmd]) |
| 250 |
.spawn() |
| 251 |
.map_err(|e| anyhow::anyhow!("failed to spawn git-shell: {e}"))?; |
| 252 |
|
| 253 |
let timeout = std::time::Duration::from_secs(crate::constants::GIT_SSH_OP_TIMEOUT_SECS); |
| 254 |
match tokio::time::timeout(timeout, child.wait()).await { |
| 255 |
Ok(Ok(status)) => std::process::exit(status.code().unwrap_or(0)), |
| 256 |
Ok(Err(e)) => anyhow::bail!("git-shell wait failed: {e}"), |
| 257 |
Err(_elapsed) => { |
| 258 |
let _ = child.start_kill(); |
| 259 |
let _ = child.wait().await; |
| 260 |
eprintln!( |
| 261 |
"git operation timed out after {}s", |
| 262 |
crate::constants::GIT_SSH_OP_TIMEOUT_SECS |
| 263 |
); |
| 264 |
std::process::exit(124); |
| 265 |
} |
| 266 |
} |
| 267 |
} |
| 268 |
|
| 269 |
|
| 270 |
|
| 271 |
|
| 272 |
|
| 273 |
|
| 274 |
|
| 275 |
|
| 276 |
|
| 277 |
|
| 278 |
|
| 279 |
|
| 280 |
|
| 281 |
pub fn install_hooks_for_repo( |
| 282 |
repo_dir: &std::path::Path, |
| 283 |
token: Option<&str>, |
| 284 |
owner: &str, |
| 285 |
repo_name: &str, |
| 286 |
) -> anyhow::Result<()> { |
| 287 |
if let Some(token) = token { |
| 288 |
install_hook( |
| 289 |
repo_dir, |
| 290 |
"post-receive", |
| 291 |
&crate::build_runner::post_receive_hook(token, owner, repo_name), |
| 292 |
)?; |
| 293 |
} |
| 294 |
install_hook(repo_dir, "update", crate::build_runner::UPDATE_HOOK)?; |
| 295 |
Ok(()) |
| 296 |
} |
| 297 |
|
| 298 |
|
| 299 |
fn install_hook( |
| 300 |
repo_dir: &std::path::Path, |
| 301 |
hook_name: &str, |
| 302 |
hook_content: &str, |
| 303 |
) -> anyhow::Result<()> { |
| 304 |
let hooks_dir = repo_dir.join("hooks"); |
| 305 |
std::fs::create_dir_all(&hooks_dir)?; |
| 306 |
let hook_path = hooks_dir.join(hook_name); |
| 307 |
std::fs::write(&hook_path, hook_content)?; |
| 308 |
|
| 309 |
#[cfg(unix)] |
| 310 |
{ |
| 311 |
use std::os::unix::fs::PermissionsExt; |
| 312 |
std::fs::set_permissions(&hook_path, std::fs::Permissions::from_mode(0o755))?; |
| 313 |
} |
| 314 |
|
| 315 |
Ok(()) |
| 316 |
} |
| 317 |
|
| 318 |
|
| 319 |
|
| 320 |
|
| 321 |
|
| 322 |
|
| 323 |
|
| 324 |
|
| 325 |
|
| 326 |
pub async fn write_authorized_keys(pool: &PgPool, set_ownership: bool) -> anyhow::Result<()> { |
| 327 |
let keys = db::ssh_keys::get_all_keys_with_username(pool).await?; |
| 328 |
|
| 329 |
let mut content = String::new(); |
| 330 |
content.push_str("# Managed by mnw-admin rebuild-keys. Do not edit manually.\n"); |
| 331 |
|
| 332 |
for key in &keys { |
| 333 |
writeln!( |
| 334 |
content, |
| 335 |
"command=\"{} git-auth {}\",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty {}", |
| 336 |
MNW_ADMIN_PATH, key.id, key.public_key, |
| 337 |
) |
| 338 |
.unwrap(); |
| 339 |
} |
| 340 |
|
| 341 |
let keys_path = authorized_keys_path(); |
| 342 |
let tmp_path = keys_path.with_extension("tmp"); |
| 343 |
std::fs::write(&tmp_path, &content)?; |
| 344 |
std::fs::rename(&tmp_path, &keys_path)?; |
| 345 |
|
| 346 |
#[cfg(unix)] |
| 347 |
{ |
| 348 |
use std::os::unix::fs::PermissionsExt; |
| 349 |
std::fs::set_permissions(&keys_path, std::fs::Permissions::from_mode(0o600))?; |
| 350 |
|
| 351 |
if set_ownership { |
| 352 |
let status = std::process::Command::new("chown") |
| 353 |
.arg("git:git") |
| 354 |
.arg(&keys_path) |
| 355 |
.status()?; |
| 356 |
if !status.success() { |
| 357 |
anyhow::bail!("chown git:git failed on {}", keys_path.display()); |
| 358 |
} |
| 359 |
} |
| 360 |
} |
| 361 |
|
| 362 |
Ok(()) |
| 363 |
} |
| 364 |
|
| 365 |
#[cfg(test)] |
| 366 |
mod tests { |
| 367 |
use super::*; |
| 368 |
|
| 369 |
|
| 370 |
|
| 371 |
|
| 372 |
|
| 373 |
#[test] |
| 374 |
fn a_first_push_gets_a_bare_repo_on_disk() { |
| 375 |
let root = tempfile::tempdir().unwrap(); |
| 376 |
let repo_dir = root.path().join("max").join("shop.git"); |
| 377 |
|
| 378 |
ensure_bare_repo_on_disk(root.path(), "max", "shop").unwrap(); |
| 379 |
assert!( |
| 380 |
gix::open(&repo_dir).is_ok(), |
| 381 |
"a push to a name with no repo has somewhere to write", |
| 382 |
); |
| 383 |
|
| 384 |
|
| 385 |
|
| 386 |
|
| 387 |
ensure_bare_repo_on_disk(root.path(), "max", "shop").unwrap(); |
| 388 |
assert!(gix::open(&repo_dir).is_ok()); |
| 389 |
} |
| 390 |
|
| 391 |
|
| 392 |
|
| 393 |
|
| 394 |
|
| 395 |
|
| 396 |
#[test] |
| 397 |
fn the_door_parses_what_a_client_sends() { |
| 398 |
let r = git_command::parse("git-receive-pack '/user/repo.git'").unwrap(); |
| 399 |
assert_eq!(r.operation, Operation::ReceivePack); |
| 400 |
assert_eq!((r.owner, r.repo), ("user", "repo")); |
| 401 |
} |
| 402 |
|
| 403 |
#[test] |
| 404 |
fn the_shell_argument_is_rebuilt_from_validated_parts() { |
| 405 |
let r = git_command::parse("git-upload-pack '/user/repo.git'").unwrap(); |
| 406 |
assert_eq!(r.shell_command(), "git-upload-pack '/user/repo.git'"); |
| 407 |
} |
| 408 |
|
| 409 |
#[test] |
| 410 |
fn a_traversing_path_never_reaches_the_db_lookup() { |
| 411 |
for cmd in [ |
| 412 |
"git-upload-pack '/../etc/passwd'", |
| 413 |
"git-upload-pack '/user/../../etc'", |
| 414 |
"git-receive-pack '/user/.hidden.git'", |
| 415 |
"git-upload-pack '/user/a/b.git'", |
| 416 |
] { |
| 417 |
assert!(git_command::parse(cmd).is_err(), "{cmd}"); |
| 418 |
} |
| 419 |
} |
| 420 |
|
| 421 |
#[test] |
| 422 |
fn management_verbs_are_not_this_grammar() { |
| 423 |
assert!(git_command::parse("repo list").is_err()); |
| 424 |
} |
| 425 |
} |
| 426 |
|