| 1 | |
| 2 | |
| 3 | use std::path::PathBuf; |
| 4 | use std::time::{SystemTime, UNIX_EPOCH}; |
| 5 | |
| 6 | use forge_core::lfs_token::{self, LfsOp}; |
| 7 | use forge_core::{Repo, User}; |
| 8 | use forge_git::GitService; |
| 9 | use forge_ssh::{GitBackend, LfsOperation}; |
| 10 | |
| 11 | use crate::access::{self, AccessError, Transport}; |
| 12 | use crate::state::AppState; |
| 13 | |
| 14 | pub struct SshBackend { |
| 15 | pub state: AppState, |
| 16 | } |
| 17 | |
| 18 | const MSG_NOT_FOUND: &str = "repository not found"; |
| 19 | const MSG_DENIED: &str = "permission denied"; |
| 20 | const MSG_INTERNAL: &str = "internal error"; |
| 21 | |
| 22 | |
| 23 | const LFS_TOKEN_TTL_SECS: i64 = 3600; |
| 24 | |
| 25 | impl SshBackend { |
| 26 | |
| 27 | async fn authorize( |
| 28 | &self, |
| 29 | user_id: &str, |
| 30 | owner: &str, |
| 31 | name: &str, |
| 32 | service: GitService, |
| 33 | ) -> Result<(User, Repo, PathBuf), String> { |
| 34 | let user = match self.state.store.user_by_id(user_id).await { |
| 35 | Ok(Some(user)) if !user.is_org() => user, |
| 36 | Ok(_) => return Err(MSG_DENIED.to_string()), |
| 37 | Err(e) => { |
| 38 | tracing::error!(error = %e, "ssh: user lookup failed"); |
| 39 | return Err(MSG_INTERNAL.to_string()); |
| 40 | } |
| 41 | }; |
| 42 | |
| 43 | match access::resolve_repo(&self.state, Some(&user), owner, name, service).await { |
| 44 | Ok((repo, path)) => Ok((user, repo, path)), |
| 45 | Err(AccessError::NotFound | AccessError::Unauthorized) => { |
| 46 | Err(MSG_NOT_FOUND.to_string()) |
| 47 | } |
| 48 | Err(AccessError::Forbidden) => Err(MSG_DENIED.to_string()), |
| 49 | Err(AccessError::Internal(detail)) => { |
| 50 | tracing::error!(detail = %detail, "ssh: repo resolution failed"); |
| 51 | Err(MSG_INTERNAL.to_string()) |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | fn now_unix() -> i64 { |
| 58 | SystemTime::now() |
| 59 | .duration_since(UNIX_EPOCH) |
| 60 | .ok() |
| 61 | .and_then(|d| i64::try_from(d.as_secs()).ok()) |
| 62 | .unwrap_or(0) |
| 63 | } |
| 64 | |
| 65 | impl GitBackend for SshBackend { |
| 66 | async fn authenticate_key(&self, _algorithm: &str, key_blob: &[u8]) -> Option<String> { |
| 67 | let key = match self.state.store.ssh_key_by_blob(key_blob).await { |
| 68 | Ok(Some(key)) => key, |
| 69 | Ok(None) => return None, |
| 70 | Err(e) => { |
| 71 | tracing::warn!(error = %e, "ssh key lookup failed"); |
| 72 | return None; |
| 73 | } |
| 74 | }; |
| 75 | if let Err(e) = self.state.store.touch_ssh_key(&key.id).await { |
| 76 | tracing::warn!(error = %e, "could not record ssh key use"); |
| 77 | } |
| 78 | crate::pages::settings_live::bump_account(&self.state, &key.user_id); |
| 79 | |
| 80 | match self.state.store.user_by_id(&key.user_id).await { |
| 81 | Ok(Some(owner)) if !owner.is_org() => Some(key.user_id), |
| 82 | _ => None, |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | async fn prepare( |
| 87 | &self, |
| 88 | user_id: &str, |
| 89 | service: GitService, |
| 90 | repo_path: &str, |
| 91 | git_protocol: Option<&str>, |
| 92 | ) -> Result<tokio::process::Command, String> { |
| 93 | |
| 94 | let (owner, name) = repo_path |
| 95 | .split_once('/') |
| 96 | .ok_or_else(|| MSG_NOT_FOUND.to_string())?; |
| 97 | |
| 98 | let (user, repo, path) = self.authorize(user_id, owner, name, service).await?; |
| 99 | |
| 100 | Ok(access::git_process( |
| 101 | &self.state, |
| 102 | &repo, |
| 103 | &path, |
| 104 | Some(&user), |
| 105 | service, |
| 106 | Transport::Ssh, |
| 107 | false, |
| 108 | git_protocol, |
| 109 | ) |
| 110 | .into_tokio()) |
| 111 | } |
| 112 | |
| 113 | async fn lfs_authenticate( |
| 114 | &self, |
| 115 | user_id: &str, |
| 116 | repo_path: &str, |
| 117 | operation: LfsOperation, |
| 118 | ) -> Result<String, String> { |
| 119 | |
| 120 | let (owner, name) = repo_path |
| 121 | .split_once('/') |
| 122 | .ok_or_else(|| MSG_NOT_FOUND.to_string())?; |
| 123 | |
| 124 | |
| 125 | let service = match operation { |
| 126 | LfsOperation::Download => GitService::UploadPack, |
| 127 | LfsOperation::Upload => GitService::ReceivePack, |
| 128 | }; |
| 129 | let (_user, repo, _path) = self.authorize(user_id, owner, name, service).await?; |
| 130 | |
| 131 | if operation == LfsOperation::Upload { |
| 132 | |
| 133 | match self.state.store.pull_mirror(&repo.id).await { |
| 134 | Ok(None) => {} |
| 135 | Ok(Some(_)) => return Err(MSG_DENIED.to_string()), |
| 136 | Err(e) => { |
| 137 | tracing::error!(error = %e, "ssh: pull mirror lookup failed"); |
| 138 | return Err(MSG_INTERNAL.to_string()); |
| 139 | } |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | let token = lfs_token::issue( |
| 144 | &self.state.key, |
| 145 | &repo.id, |
| 146 | LfsOp::Any, |
| 147 | now_unix() + LFS_TOKEN_TTL_SECS, |
| 148 | ); |
| 149 | let base = self.state.config.base_url.trim_end_matches('/'); |
| 150 | let reply = serde_json::json!({ |
| 151 | "href": format!("{base}/{}/{}.git/info/lfs", repo.owner_name, repo.name), |
| 152 | "header": { "Authorization": format!("RemoteAuth {token}") }, |
| 153 | "expires_in": LFS_TOKEN_TTL_SECS, |
| 154 | }); |
| 155 | Ok(reply.to_string()) |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | #[cfg(test)] |
| 160 | mod org_tests { |
| 161 | use super::*; |
| 162 | |
| 163 | |
| 164 | #[tokio::test] |
| 165 | async fn an_org_key_does_not_authenticate() { |
| 166 | let dir = tempfile::tempdir().unwrap(); |
| 167 | let state = crate::test_support::test_state(dir.path()).await; |
| 168 | let tahinli = state |
| 169 | .store |
| 170 | .create_user("tahinli", None, "h", false) |
| 171 | .await |
| 172 | .unwrap(); |
| 173 | let org = state.store.create_org("acme", &tahinli.id).await.unwrap(); |
| 174 | let org_blob = b"org-key-blob"; |
| 175 | let person_blob = b"person-key-blob"; |
| 176 | state |
| 177 | .store |
| 178 | .add_ssh_key(&org.id, "ci", "ssh-ed25519", org_blob, "SHA256:org") |
| 179 | .await |
| 180 | .unwrap(); |
| 181 | state |
| 182 | .store |
| 183 | .add_ssh_key( |
| 184 | &tahinli.id, |
| 185 | "laptop", |
| 186 | "ssh-ed25519", |
| 187 | person_blob, |
| 188 | "SHA256:me", |
| 189 | ) |
| 190 | .await |
| 191 | .unwrap(); |
| 192 | let backend = SshBackend { state }; |
| 193 | |
| 194 | assert_eq!( |
| 195 | backend.authenticate_key("ssh-ed25519", org_blob).await, |
| 196 | None |
| 197 | ); |
| 198 | assert_eq!( |
| 199 | backend.authenticate_key("ssh-ed25519", person_blob).await, |
| 200 | Some(tahinli.id.clone()) |
| 201 | ); |
| 202 | } |
| 203 | } |