gitpoulpi_hosting/trust/
origin.rs1use gitpoulpi_config::{ApiFamily, Integration, IntegrationKind};
10use url::{Host, Url};
11
12use crate::{Error, Result};
13
14fn parse(url: &str) -> Option<Url> {
15 let url = url.trim();
16 let url = if url.contains("://") {
17 Url::parse(url).ok()?
18 } else {
19 Url::parse(&format!("https://{url}")).ok()?
20 };
21 matches!(url.scheme(), "http" | "https").then_some(())?;
22 url.host_str()?;
23 Some(url)
24}
25
26fn origin_string(url: &Url) -> String {
27 let mut out = format!("{}://{}", url.scheme(), url.host_str().unwrap_or(""));
28 if let Some(port) = url.port() {
29 out.push_str(&format!(":{port}"));
30 }
31 out
32}
33
34pub fn normalize(url: &str) -> Option<String> {
37 let url = parse(url)?;
38 let mut out = origin_string(&url);
39 let path = url.path().trim_end_matches('/');
40 if !path.is_empty() {
41 out.push_str(path);
42 }
43 Some(out)
44}
45
46pub fn origin_of(url: &str) -> Option<String> {
48 Some(origin_string(&parse(url)?))
49}
50
51pub fn host_of(url: &str) -> Option<String> {
53 parse(url)?.host_str().map(str::to_string)
54}
55
56pub fn integration_origin(integration: &Integration) -> Result<String> {
60 let raw = match integration.url.trim() {
62 "" => integration.kind.default_url().unwrap_or("").to_string(),
63 url => url.to_string(),
64 };
65 let url = if integration.kind == IntegrationKind::AzureDevops {
66 gitpoulpi_config::normalize_azure_url(&raw)
67 } else {
68 raw
69 };
70 normalize(&url).ok_or_else(|| Error::BadUrl(integration.url.clone()))
71}
72
73pub fn is_plain_http_remote(url: &str) -> bool {
75 parse(url).is_some_and(|u| u.scheme() == "http" && !host_is_loopback(&u))
76}
77
78pub fn is_loopback(url: &str) -> bool {
80 parse(url).is_some_and(|u| host_is_loopback(&u))
81}
82
83fn host_is_loopback(url: &Url) -> bool {
84 match url.host() {
85 Some(Host::Domain(d)) => d == "localhost" || d.ends_with(".localhost"),
86 Some(Host::Ipv4(ip)) => ip.is_loopback(),
87 Some(Host::Ipv6(ip)) => ip.is_loopback(),
88 None => false,
89 }
90}
91
92fn dot_com_api_host(kind: IntegrationKind, host: &str) -> Option<&'static str> {
95 let (domain, api): (&str, &'static str) = match kind.family() {
96 ApiFamily::Github => ("github.com", "api.github.com"),
97 ApiFamily::Bitbucket if kind == IntegrationKind::Bitbucket => {
98 ("bitbucket.org", "api.bitbucket.org")
99 }
100 ApiFamily::Trello => ("trello.com", "api.trello.com"),
101 ApiFamily::Linear => ("linear.app", "api.linear.app"),
102 _ => return None,
103 };
104 (host == domain || host == format!("www.{domain}") || host == format!("api.{domain}"))
105 .then_some(api)
106}
107
108pub fn api_origins(kind: IntegrationKind, recorded_origin: &str) -> Vec<String> {
112 let mut out = Vec::new();
113 let Some(own) = origin_of(recorded_origin) else {
114 return out;
115 };
116 if let Some(host) = host_of(recorded_origin) {
117 if let Some(api) = dot_com_api_host(kind, &host) {
118 out.push(format!("https://{api}"));
119 }
120 }
121 out.push(own);
122 out.dedup();
123 out
124}
125
126pub fn is_public_saas_host(host: &str) -> bool {
129 let host = host.to_ascii_lowercase();
130 const EXACT: &[&str] = &[
131 "github.com",
132 "api.github.com",
133 "gitlab.com",
134 "codeberg.org",
135 "bitbucket.org",
136 "api.bitbucket.org",
137 "dev.azure.com",
138 "api.trello.com",
139 "trello.com",
140 "api.linear.app",
141 "linear.app",
142 ];
143 EXACT.contains(&host.as_str())
144 || host.ends_with(".atlassian.net")
145 || host.ends_with(".youtrack.cloud")
146}
147
148#[cfg(test)]
149mod tests {
150 use super::*;
151
152 #[test]
153 fn spellings_of_one_server_compare_equal_and_lookalikes_do_not() {
154 let same = [
155 ("https://GitLab.Example.com/", "https://gitlab.example.com"),
156 (
157 "https://gitlab.example.com:443",
158 "https://gitlab.example.com",
159 ),
160 ("http://gitlab.example.com:80/", "http://gitlab.example.com"),
161 (
162 "https://user:pw@gitlab.example.com/sub/?q=1#f",
163 "https://gitlab.example.com/sub",
164 ),
165 ("gitlab.example.com", "https://gitlab.example.com"),
166 (
167 "https://git.example.com:8443/a/b/",
168 "https://git.example.com:8443/a/b",
169 ),
170 ("https://BÜCHER.example", "https://xn--bcher-kva.example"),
171 ];
172 for (input, want) in same {
173 assert_eq!(normalize(input).as_deref(), Some(want), "{input}");
174 }
175 let a = normalize("https://gitlab.example.com").unwrap();
176 for other in [
177 "https://gitlab.example.com.evil.test",
178 "https://gitlab-example.com",
179 "http://gitlab.example.com",
180 "https://gitlab.example.com:8443",
181 "https://gitlab.example.com/other",
182 ] {
183 assert_ne!(normalize(other).unwrap(), a, "{other}");
184 }
185 assert_eq!(normalize("ftp://x.example"), None);
186 assert_eq!(normalize(""), None);
187 }
188
189 #[test]
190 fn loopback_and_plain_http() {
191 assert!(is_loopback("http://localhost:3000"));
192 assert!(is_loopback("http://127.0.0.1:8080"));
193 assert!(is_loopback("http://[::1]:11434"));
194 assert!(!is_loopback("http://192.168.1.4"));
195 assert!(!is_plain_http_remote("http://localhost:11434"));
196 assert!(is_plain_http_remote("http://nas.local:3000"));
197 assert!(!is_plain_http_remote("https://nas.local"));
198 }
199
200 #[test]
201 fn saas_kinds_may_reach_their_api_host_and_nothing_else() {
202 let gh = api_origins(IntegrationKind::Github, "https://github.com");
203 assert!(gh.contains(&"https://api.github.com".to_string()));
204 assert!(gh.contains(&"https://github.com".to_string()));
205 let ghe = api_origins(
206 IntegrationKind::GithubEnterprise,
207 "https://ghe.corp.example",
208 );
209 assert_eq!(ghe, vec!["https://ghe.corp.example".to_string()]);
210 let gl = api_origins(
211 IntegrationKind::GitlabSelfManaged,
212 "https://git.corp.example/sub",
213 );
214 assert_eq!(gl, vec!["https://git.corp.example".to_string()]);
215 assert!(api_origins(IntegrationKind::Trello, "https://trello.com")
216 .contains(&"https://api.trello.com".to_string()));
217 }
218
219 #[test]
220 fn public_saas_hosts() {
221 assert!(is_public_saas_host("GitHub.com"));
222 assert!(is_public_saas_host("acme.atlassian.net"));
223 assert!(!is_public_saas_host("git.corp.example"));
224 assert!(!is_public_saas_host("evilgithub.com"));
225 }
226}