forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

remote.rs182 lines, 6.7 KiBHistoryRawDownload
1//! Turning what the user typed into a remote reference, and building the API clients.
2
3use std::time::Duration;
4
5use super::Source;
6use super::api::{self, Auth, Forgejo, GitHub, GitLab, Http, Notice};
7use crate::mirrors::policy;
8use crate::state::AppState;
9use crate::webhooks::client::{policy_client, validate_url};
10
11/// A GitHub client under the outbound policy.
12pub fn make_github(
13 state: &AppState,
14 token: Option<String>,
15 notice: Notice,
16) -> Result<GitHub, String> {
17 let client = policy_client(policy(state), Duration::from_secs(60), "forge-import/1")
18 .map_err(|e| format!("could not build the HTTP client: {e}"))?;
19 Ok(GitHub::new(Http::new(
20 client,
21 policy(state),
22 token,
23 Auth::GitHub,
24 "api.github.com".into(),
25 notice,
26 )))
27}
28
29/// A GitLab client for `instance`, which must pass the outbound policy.
30pub fn make_gitlab(
31 state: &AppState,
32 instance: &str,
33 token: Option<String>,
34 notice: Notice,
35) -> Result<GitLab, String> {
36 let instance = instance.trim_end_matches('/');
37 let host = validate_url(instance, &policy(state))
38 .map_err(|e| format!("instance address refused: {e}"))?
39 .host_str()
40 .unwrap_or_default()
41 .to_ascii_lowercase();
42 let client = policy_client(policy(state), Duration::from_secs(60), "forge-import/1")
43 .map_err(|e| format!("could not build the HTTP client: {e}"))?;
44 Ok(GitLab::new(
45 Http::new(client, policy(state), token, Auth::GitLab, host, notice),
46 instance,
47 ))
48}
49
50/// A Forgejo or Gitea client for `instance`, which must pass the outbound policy.
51pub fn make_forgejo(
52 state: &AppState,
53 instance: &str,
54 token: Option<String>,
55 notice: Notice,
56) -> Result<Forgejo, String> {
57 let instance = instance.trim_end_matches('/');
58 let host = validate_url(instance, &policy(state))
59 .map_err(|e| format!("instance address refused: {e}"))?
60 .host_str()
61 .unwrap_or_default()
62 .to_ascii_lowercase();
63 let client = policy_client(policy(state), Duration::from_secs(60), "forge-import/1")
64 .map_err(|e| format!("could not build the HTTP client: {e}"))?;
65 Ok(Forgejo::new(
66 Http::new(client, policy(state), token, Auth::Forgejo, host, notice),
67 instance,
68 ))
69}
70
71/// Splits what the user typed into `(remote, instance)` for a source. `None` when it is not a
72/// usable reference. GitHub takes `owner/name` or a github.com URL; GitLab and Forgejo take a project URL
73/// (`https://host/group/project`) or, with `instance` given, a bare path.
74pub fn parse_remote(source: Source, text: &str, instance: &str) -> Option<(String, String)> {
75 let text = text.trim();
76 match source {
77 Source::Git => (text.starts_with("https://") || text.starts_with("http://"))
78 .then(|| (text.to_owned(), String::new())),
79 Source::GitHub => {
80 let path = text
81 .strip_prefix("https://github.com/")
82 .unwrap_or(text)
83 .trim_end_matches('/');
84 let path = path.strip_suffix(".git").unwrap_or(path);
85 api::valid_path(path, 2, 2).then(|| (path.to_owned(), String::new()))
86 }
87 Source::GitLab | Source::Forgejo => {
88 let max = if source == Source::GitLab { 20 } else { 2 };
89 if let Some((scheme, rest)) = text
90 .strip_prefix("https://")
91 .map(|r| ("https", r))
92 .or_else(|| text.strip_prefix("http://").map(|r| ("http", r)))
93 {
94 let (host, path) = rest.split_once('/')?;
95 let path = path.trim_end_matches('/');
96 let path = path.strip_suffix(".git").unwrap_or(path);
97 if host.is_empty() || host.contains('@') || !api::valid_path(path, 2, max) {
98 return None;
99 }
100 return Some((path.to_owned(), format!("{scheme}://{host}")));
101 }
102 let instance = instance.trim().trim_end_matches('/');
103 let path = text.trim_matches('/');
104 let path = path.strip_suffix(".git").unwrap_or(path);
105 let host = instance
106 .strip_prefix("https://")
107 .or_else(|| instance.strip_prefix("http://"))?;
108 let ok = !host.is_empty()
109 && !host.contains('@')
110 && !host.contains('/')
111 && api::valid_path(path, 2, max);
112 ok.then(|| (path.to_owned(), instance.to_owned()))
113 }
114 }
115}
116
117/// The reference stored on a job and shown to the user: no credential in it.
118pub fn source_ref(source: Source, remote: &str, instance: &str) -> String {
119 match source {
120 Source::GitLab | Source::Forgejo => {
121 format!("{}/{}", instance.trim_end_matches('/'), remote)
122 }
123 _ => remote.to_owned(),
124 }
125}
126
127/// The repository name a remote would get by default: its last path segment without `.git`.
128pub fn default_name(remote: &str) -> String {
129 remote
130 .trim_end_matches('/')
131 .rsplit('/')
132 .next()
133 .unwrap_or_default()
134 .trim_end_matches(".git")
135 .to_owned()
136}
137
138#[cfg(test)]
139mod tests {
140 use super::*;
141
142 #[test]
143 fn github_accepts_owner_name_or_url() {
144 let ok = |t: &str| parse_remote(Source::GitHub, t, "").map(|r| r.0);
145 assert_eq!(ok("tahinli/forge").as_deref(), Some("tahinli/forge"));
146 assert_eq!(
147 ok("https://github.com/tahinli/forge.git").as_deref(),
148 Some("tahinli/forge")
149 );
150 assert_eq!(ok("tahinli").as_deref(), None);
151 assert_eq!(ok("a/b/c").as_deref(), None);
152 assert_eq!(ok("../etc").as_deref(), None);
153 }
154
155 #[test]
156 fn gitlab_takes_a_url_or_a_path_with_an_instance() {
157 let url = parse_remote(Source::GitLab, "https://gl.example.org/grp/sub/proj", "");
158 assert_eq!(
159 url,
160 Some(("grp/sub/proj".into(), "https://gl.example.org".into()))
161 );
162 let bare = parse_remote(Source::GitLab, "grp/proj", "https://gitlab.com/");
163 assert_eq!(bare, Some(("grp/proj".into(), "https://gitlab.com".into())));
164 assert_eq!(parse_remote(Source::GitLab, "grp/proj", ""), None);
165 assert_eq!(
166 parse_remote(Source::GitLab, "https://u:p@host/a/b", ""),
167 None
168 );
169 }
170
171 #[test]
172 fn git_needs_http_scheme_and_names_default_from_the_path() {
173 assert!(parse_remote(Source::Git, "file:///etc", "").is_none());
174 assert!(parse_remote(Source::Git, "https://example.org/x/y.git", "").is_some());
175 assert_eq!(default_name("https://example.org/x/y.git"), "y");
176 assert_eq!(default_name("grp/proj"), "proj");
177 assert_eq!(
178 source_ref(Source::GitLab, "g/p", "https://gitlab.com"),
179 "https://gitlab.com/g/p"
180 );
181 }
182}