forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.7 MiB37e985dTahinli3 hours ago363 commits

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