forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

ssh_backend.rs213 lines, 7.2 KiBHistoryRawDownload
1//! `impl forge_ssh::GitBackend` for forge: key lookup, authz and git process construction.
2
3use std::path::PathBuf;
4use std::time::{SystemTime, UNIX_EPOCH};
5
6use forge_core::lfs_token::{self, LfsOp};
7use forge_core::{Repo, User};
8use forge_git::GitService;
9use forge_ssh::{GitBackend, LfsOperation};
10
11use crate::access::{self, AccessError, Transport};
12use crate::state::AppState;
13
14pub struct SshBackend {
15 pub state: AppState,
16}
17
18const MSG_NOT_FOUND: &str = "repository not found";
19const MSG_DENIED: &str = "permission denied";
20const MSG_INTERNAL: &str = "internal error";
21
22/// Lifetime of the LFS transfer token handed out by `git-lfs-authenticate`.
23const LFS_TOKEN_TTL_SECS: i64 = 3600;
24
25impl SshBackend {
26 /// Looks up the user and applies the same repository authorization git uses for `service`.
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 // Checked on every command, not only at key authentication: a connection opened before the
43 // account was suspended stays up and can still ask for new channels.
44 match self.state.store.suspension(&user.id).await {
45 Ok(None) => {}
46 Ok(Some(_)) => return Err(MSG_DENIED.to_string()),
47 Err(e) => {
48 tracing::error!(error = %e, "ssh: suspension lookup failed");
49 return Err(MSG_INTERNAL.to_string());
50 }
51 }
52
53 match access::resolve_repo(&self.state, Some(&user), owner, name, service).await {
54 Ok((repo, path)) => Ok((user, repo, path)),
55 Err(AccessError::NotFound | AccessError::Unauthorized) => {
56 Err(MSG_NOT_FOUND.to_string())
57 }
58 Err(AccessError::Forbidden) => Err(MSG_DENIED.to_string()),
59 Err(AccessError::Internal(detail)) => {
60 tracing::error!(detail = %detail, "ssh: repo resolution failed");
61 Err(MSG_INTERNAL.to_string())
62 }
63 }
64 }
65}
66
67fn now_unix() -> i64 {
68 SystemTime::now()
69 .duration_since(UNIX_EPOCH)
70 .ok()
71 .and_then(|d| i64::try_from(d.as_secs()).ok())
72 .unwrap_or(0)
73}
74
75impl GitBackend for SshBackend {
76 async fn authenticate_key(&self, _algorithm: &str, key_blob: &[u8]) -> Option<String> {
77 let key = match self.state.store.ssh_key_by_blob(key_blob).await {
78 Ok(Some(key)) => key,
79 Ok(None) => return None,
80 Err(e) => {
81 tracing::warn!(error = %e, "ssh key lookup failed");
82 return None;
83 }
84 };
85 if let Err(e) = self.state.store.touch_ssh_key(&key.id).await {
86 tracing::warn!(error = %e, "could not record ssh key use");
87 }
88 crate::live::bump_account(&self.state, &key.user_id);
89 // A key that belongs to an organization is refused here, not only in `authorize`.
90 match self.state.store.user_by_id(&key.user_id).await {
91 Ok(Some(owner)) if !owner.is_org() => Some(key.user_id),
92 _ => None,
93 }
94 }
95
96 async fn prepare(
97 &self,
98 user_id: &str,
99 service: GitService,
100 repo_path: &str,
101 git_protocol: Option<&str>,
102 ) -> Result<tokio::process::Command, String> {
103 // parse_exec has already stripped the leading '/' and the trailing ".git".
104 let (owner, name) = repo_path
105 .split_once('/')
106 .ok_or_else(|| MSG_NOT_FOUND.to_string())?;
107
108 let (user, repo, path) = self.authorize(user_id, owner, name, service).await?;
109
110 Ok(access::git_process(
111 &self.state,
112 &repo,
113 &path,
114 Some(&user),
115 service,
116 Transport::Ssh,
117 false,
118 git_protocol,
119 )
120 .into_tokio())
121 }
122
123 async fn lfs_authenticate(
124 &self,
125 user_id: &str,
126 repo_path: &str,
127 operation: LfsOperation,
128 ) -> Result<String, String> {
129 // parse_lfs_authenticate has already stripped the leading '/' and the trailing ".git".
130 let (owner, name) = repo_path
131 .split_once('/')
132 .ok_or_else(|| MSG_NOT_FOUND.to_string())?;
133
134 // Download is a read and upload is a write, checked exactly as git does.
135 let service = match operation {
136 LfsOperation::Download => GitService::UploadPack,
137 LfsOperation::Upload => GitService::ReceivePack,
138 };
139 let (_user, repo, _path) = self.authorize(user_id, owner, name, service).await?;
140
141 if operation == LfsOperation::Upload {
142 // Archived repos are refused by the Write check. Pull mirrors are read-only.
143 match self.state.store.pull_mirror(&repo.id).await {
144 Ok(None) => {}
145 Ok(Some(_)) => return Err(MSG_DENIED.to_string()),
146 Err(e) => {
147 tracing::error!(error = %e, "ssh: pull mirror lookup failed");
148 return Err(MSG_INTERNAL.to_string());
149 }
150 }
151 }
152
153 let token = lfs_token::issue(
154 &self.state.key,
155 &repo.id,
156 LfsOp::Any,
157 now_unix() + LFS_TOKEN_TTL_SECS,
158 );
159 let base = self.state.config.base_url.trim_end_matches('/');
160 let reply = serde_json::json!({
161 "href": format!("{base}/{}/{}.git/info/lfs", repo.owner_name, repo.name),
162 "header": { "Authorization": format!("RemoteAuth {token}") },
163 "expires_in": LFS_TOKEN_TTL_SECS,
164 });
165 Ok(reply.to_string())
166 }
167}
168
169#[cfg(test)]
170mod org_tests {
171 use super::*;
172
173 /// A key that belongs to an organization does not authenticate; a person's key does.
174 #[tokio::test]
175 async fn an_org_key_does_not_authenticate() {
176 let dir = tempfile::tempdir().unwrap();
177 let state = crate::test_support::test_state(dir.path()).await;
178 let tahinli = state
179 .store
180 .create_user("tahinli", None, "h", false)
181 .await
182 .unwrap();
183 let org = state.store.create_org("acme", &tahinli.id).await.unwrap();
184 let org_blob = b"org-key-blob";
185 let person_blob = b"person-key-blob";
186 state
187 .store
188 .add_ssh_key(&org.id, "ci", "ssh-ed25519", org_blob, "SHA256:org")
189 .await
190 .unwrap();
191 state
192 .store
193 .add_ssh_key(
194 &tahinli.id,
195 "laptop",
196 "ssh-ed25519",
197 person_blob,
198 "SHA256:me",
199 )
200 .await
201 .unwrap();
202 let backend = SshBackend { state };
203
204 assert_eq!(
205 backend.authenticate_key("ssh-ed25519", org_blob).await,
206 None
207 );
208 assert_eq!(
209 backend.authenticate_key("ssh-ed25519", person_blob).await,
210 Some(tahinli.id.clone())
211 );
212 }
213}