| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | use std::{ |
| 9 | fmt, |
| 10 | net::{IpAddr, Ipv4Addr, Ipv6Addr}, |
| 11 | str::FromStr, |
| 12 | }; |
| 13 | |
| 14 | use super::DomainError; |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 23 | pub enum ImportState { |
| 24 | |
| 25 | Importing, |
| 26 | |
| 27 | |
| 28 | Failed, |
| 29 | } |
| 30 | |
| 31 | impl ImportState { |
| 32 | pub fn as_str(self) -> &'static str { |
| 33 | match self { |
| 34 | Self::Importing => "importing", |
| 35 | Self::Failed => "failed", |
| 36 | } |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | impl fmt::Display for ImportState { |
| 41 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 42 | f.write_str(self.as_str()) |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | |
| 47 | |
| 48 | impl FromStr for ImportState { |
| 49 | type Err = DomainError; |
| 50 | |
| 51 | fn from_str(value: &str) -> Result<Self, Self::Err> { |
| 52 | match value { |
| 53 | "importing" => Ok(Self::Importing), |
| 54 | "failed" => Ok(Self::Failed), |
| 55 | other => Err(DomainError::validation( |
| 56 | "import state", |
| 57 | format!("unknown import state {other:?}"), |
| 58 | )), |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | |
| 64 | |
| 65 | |
| 66 | |
| 67 | |
| 68 | |
| 69 | |
| 70 | |
| 71 | |
| 72 | |
| 73 | |
| 74 | |
| 75 | |
| 76 | |
| 77 | |
| 78 | |
| 79 | |
| 80 | |
| 81 | |
| 82 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 83 | pub struct ImportSource(String); |
| 84 | |
| 85 | impl ImportSource { |
| 86 | |
| 87 | |
| 88 | pub const MAX_LEN: usize = 512; |
| 89 | |
| 90 | |
| 91 | pub fn new(value: impl Into<String>) -> Result<Self, DomainError> { |
| 92 | let value = value.into(); |
| 93 | let trimmed = value.trim(); |
| 94 | |
| 95 | let invalid = |reason: &str| DomainError::validation("import source", reason); |
| 96 | |
| 97 | if trimmed.is_empty() { |
| 98 | return Err(invalid("must not be empty")); |
| 99 | } |
| 100 | if trimmed.len() > Self::MAX_LEN { |
| 101 | return Err(invalid("is too long")); |
| 102 | } |
| 103 | |
| 104 | |
| 105 | if trimmed.chars().any(|c| c.is_control() || c == ' ') { |
| 106 | return Err(invalid("must not contain spaces or control characters")); |
| 107 | } |
| 108 | |
| 109 | let Some(rest) = strip_https(trimmed) else { |
| 110 | return Err(invalid("must start with https://")); |
| 111 | }; |
| 112 | |
| 113 | let authority = rest |
| 114 | .split(['/', '?', '#']) |
| 115 | .next() |
| 116 | .expect("split always yields one part"); |
| 117 | |
| 118 | if authority.contains('@') { |
| 119 | return Err(invalid( |
| 120 | "must not carry a username or password — Steid only imports public repositories", |
| 121 | )); |
| 122 | } |
| 123 | |
| 124 | let host = host_of(authority).ok_or_else(|| invalid("must name a host"))?; |
| 125 | |
| 126 | if host.is_empty() { |
| 127 | return Err(invalid("must name a host")); |
| 128 | } |
| 129 | if host.eq_ignore_ascii_case("localhost") || ends_with_ignore_case(host, ".localhost") { |
| 130 | return Err(invalid("must not point at this server")); |
| 131 | } |
| 132 | if let Ok(address) = host.parse::<IpAddr>() |
| 133 | && !is_public(address) |
| 134 | { |
| 135 | return Err(invalid( |
| 136 | "must not be a private, loopback or link-local address", |
| 137 | )); |
| 138 | } |
| 139 | |
| 140 | Ok(Self(trimmed.to_owned())) |
| 141 | } |
| 142 | |
| 143 | |
| 144 | pub fn from_trusted(value: impl Into<String>) -> Self { |
| 145 | Self(value.into()) |
| 146 | } |
| 147 | |
| 148 | pub fn as_str(&self) -> &str { |
| 149 | &self.0 |
| 150 | } |
| 151 | |
| 152 | |
| 153 | |
| 154 | pub fn host(&self) -> &str { |
| 155 | let rest = strip_https(&self.0).unwrap_or(&self.0); |
| 156 | let authority = rest.split(['/', '?', '#']).next().unwrap_or(""); |
| 157 | |
| 158 | host_of(authority).unwrap_or(authority) |
| 159 | } |
| 160 | |
| 161 | |
| 162 | |
| 163 | |
| 164 | |
| 165 | |
| 166 | |
| 167 | pub fn suggested_name(&self) -> &str { |
| 168 | let Some(rest) = strip_https(&self.0) else { |
| 169 | return ""; |
| 170 | }; |
| 171 | |
| 172 | let path = rest |
| 173 | .split(['?', '#']) |
| 174 | .next() |
| 175 | .unwrap_or("") |
| 176 | .trim_end_matches('/'); |
| 177 | |
| 178 | |
| 179 | |
| 180 | let Some((_authority, tail)) = path.split_once('/') else { |
| 181 | return ""; |
| 182 | }; |
| 183 | |
| 184 | let segment = tail.split('/').next_back().unwrap_or(""); |
| 185 | |
| 186 | segment.strip_suffix(".git").unwrap_or(segment) |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | impl fmt::Display for ImportSource { |
| 191 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 192 | f.write_str(&self.0) |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | |
| 197 | fn strip_https(value: &str) -> Option<&str> { |
| 198 | const SCHEME: &str = "https://"; |
| 199 | |
| 200 | if value.len() >= SCHEME.len() && value[..SCHEME.len()].eq_ignore_ascii_case(SCHEME) { |
| 201 | Some(&value[SCHEME.len()..]) |
| 202 | } else { |
| 203 | None |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | fn ends_with_ignore_case(value: &str, suffix: &str) -> bool { |
| 208 | value.len() >= suffix.len() && value[value.len() - suffix.len()..].eq_ignore_ascii_case(suffix) |
| 209 | } |
| 210 | |
| 211 | |
| 212 | fn host_of(authority: &str) -> Option<&str> { |
| 213 | if let Some(rest) = authority.strip_prefix('[') { |
| 214 | |
| 215 | return rest.split(']').next(); |
| 216 | } |
| 217 | |
| 218 | match authority.split_once(':') { |
| 219 | Some((host, _port)) => Some(host), |
| 220 | None => Some(authority), |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | |
| 225 | |
| 226 | |
| 227 | |
| 228 | |
| 229 | |
| 230 | pub fn is_public(address: IpAddr) -> bool { |
| 231 | match address { |
| 232 | |
| 233 | |
| 234 | IpAddr::V6(address) => match address.to_ipv4_mapped() { |
| 235 | Some(mapped) => is_public_v4(mapped), |
| 236 | None => is_public_v6(address), |
| 237 | }, |
| 238 | IpAddr::V4(address) => is_public_v4(address), |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | fn is_public_v4(address: Ipv4Addr) -> bool { |
| 243 | let [a, b, ..] = address.octets(); |
| 244 | |
| 245 | !(address.is_unspecified() |
| 246 | || address.is_loopback() |
| 247 | || address.is_private() |
| 248 | || address.is_link_local() |
| 249 | || address.is_multicast() |
| 250 | || address.is_broadcast() |
| 251 | |
| 252 | || a == 0 |
| 253 | |
| 254 | |
| 255 | || (a == 100 && (64..128).contains(&b)) |
| 256 | |
| 257 | || (a == 198 && (b == 18 || b == 19))) |
| 258 | } |
| 259 | |
| 260 | fn is_public_v6(address: Ipv6Addr) -> bool { |
| 261 | let first = address.segments()[0]; |
| 262 | |
| 263 | !(address.is_unspecified() |
| 264 | || address.is_loopback() |
| 265 | || address.is_multicast() |
| 266 | |
| 267 | || (first & 0xfe00) == 0xfc00 |
| 268 | |
| 269 | || (first & 0xffc0) == 0xfe80) |
| 270 | } |
| 271 | |
| 272 | #[cfg(test)] |
| 273 | mod tests { |
| 274 | use super::*; |
| 275 | |
| 276 | #[test] |
| 277 | fn import_state_round_trips_through_strings() { |
| 278 | for state in [ImportState::Importing, ImportState::Failed] { |
| 279 | assert_eq!( |
| 280 | state.as_str().parse::<ImportState>().expect("round trip"), |
| 281 | state |
| 282 | ); |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | #[test] |
| 287 | fn unknown_import_state_is_an_error_not_a_default() { |
| 288 | assert!("ready".parse::<ImportState>().is_err()); |
| 289 | assert!("".parse::<ImportState>().is_err()); |
| 290 | } |
| 291 | |
| 292 | #[test] |
| 293 | fn accepts_ordinary_public_clone_urls() { |
| 294 | for input in [ |
| 295 | "https://github.com/rust-lang/mdBook.git", |
| 296 | "https://github.com/rust-lang/mdBook", |
| 297 | "https://gitlab.com/group/subgroup/project.git", |
| 298 | "HTTPS://example.com/thing.git", |
| 299 | "https://git.example.com:8443/thing.git", |
| 300 | " https://example.com/thing.git ", |
| 301 | ] { |
| 302 | assert!( |
| 303 | ImportSource::new(input).is_ok(), |
| 304 | "expected {input:?} to be accepted" |
| 305 | ); |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | #[test] |
| 310 | fn refuses_every_scheme_but_https() { |
| 311 | for input in [ |
| 312 | "http://example.com/thing.git", |
| 313 | "git://example.com/thing.git", |
| 314 | "ssh://git@example.com/thing.git", |
| 315 | "git@example.com:thing.git", |
| 316 | "file:///etc/passwd", |
| 317 | "/etc/passwd", |
| 318 | "//example.com/thing.git", |
| 319 | "httpsx://example.com/thing.git", |
| 320 | ] { |
| 321 | assert!( |
| 322 | ImportSource::new(input).is_err(), |
| 323 | "expected {input:?} to be refused" |
| 324 | ); |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | |
| 329 | |
| 330 | |
| 331 | #[test] |
| 332 | fn refuses_addresses_that_are_not_the_public_internet() { |
| 333 | for input in [ |
| 334 | "https://127.0.0.1/thing.git", |
| 335 | "https://127.1.2.3/thing.git", |
| 336 | "https://localhost/thing.git", |
| 337 | "https://LOCALHOST:8443/thing.git", |
| 338 | "https://api.localhost/thing.git", |
| 339 | "https://0.0.0.0/thing.git", |
| 340 | "https://10.0.0.5/thing.git", |
| 341 | "https://172.16.4.1/thing.git", |
| 342 | "https://192.168.1.1/thing.git", |
| 343 | |
| 344 | "https://169.254.169.254/latest/meta-data", |
| 345 | "https://100.64.0.1/thing.git", |
| 346 | "https://[::1]/thing.git", |
| 347 | "https://[::]/thing.git", |
| 348 | "https://[fd00::1]/thing.git", |
| 349 | "https://[fe80::1]/thing.git", |
| 350 | "https://[::ffff:127.0.0.1]/thing.git", |
| 351 | ] { |
| 352 | assert!( |
| 353 | ImportSource::new(input).is_err(), |
| 354 | "expected {input:?} to be refused: it is not on the public internet" |
| 355 | ); |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | #[test] |
| 360 | fn refuses_credentials_in_the_url() { |
| 361 | |
| 362 | assert!(ImportSource::new("https://user:token@example.com/thing.git").is_err()); |
| 363 | assert!(ImportSource::new("https://token@example.com/thing.git").is_err()); |
| 364 | } |
| 365 | |
| 366 | #[test] |
| 367 | fn refuses_malformed_urls() { |
| 368 | for input in [ |
| 369 | "", |
| 370 | " ", |
| 371 | "https://", |
| 372 | "https:///no/host.git", |
| 373 | "https://exa mple.com/thing.git", |
| 374 | "https://example.com/thing\n.git", |
| 375 | &format!("https://example.com/{}", "a".repeat(ImportSource::MAX_LEN)), |
| 376 | ] { |
| 377 | assert!( |
| 378 | ImportSource::new(input).is_err(), |
| 379 | "expected {input:?} to be refused" |
| 380 | ); |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | #[test] |
| 385 | fn a_public_address_is_still_allowed() { |
| 386 | assert!(ImportSource::new("https://1.1.1.1/thing.git").is_ok()); |
| 387 | assert!(ImportSource::new("https://[2606:4700::1111]/thing.git").is_ok()); |
| 388 | } |
| 389 | |
| 390 | #[test] |
| 391 | fn the_host_is_read_back_without_its_port_or_brackets() { |
| 392 | let host = |url: &str| ImportSource::new(url).expect("valid").host().to_owned(); |
| 393 | |
| 394 | assert_eq!(host("https://example.com/thing.git"), "example.com"); |
| 395 | assert_eq!( |
| 396 | host("https://git.example.com:8443/thing.git"), |
| 397 | "git.example.com" |
| 398 | ); |
| 399 | assert_eq!( |
| 400 | host("https://[2606:4700::1111]:8443/thing.git"), |
| 401 | "2606:4700::1111" |
| 402 | ); |
| 403 | assert_eq!(host("https://example.com"), "example.com"); |
| 404 | } |
| 405 | |
| 406 | #[test] |
| 407 | fn the_last_path_segment_suggests_the_name() { |
| 408 | let name = |url: &str| { |
| 409 | ImportSource::new(url) |
| 410 | .expect("valid") |
| 411 | .suggested_name() |
| 412 | .to_owned() |
| 413 | }; |
| 414 | |
| 415 | assert_eq!(name("https://github.com/rust-lang/mdBook.git"), "mdBook"); |
| 416 | assert_eq!(name("https://github.com/rust-lang/mdBook"), "mdBook"); |
| 417 | assert_eq!(name("https://example.com/a/b/c.git/"), "c"); |
| 418 | assert_eq!(name("https://example.com/thing.git?ref=main"), "thing"); |
| 419 | |
| 420 | |
| 421 | assert_eq!(name("https://example.com"), ""); |
| 422 | assert_eq!(name("https://example.com/"), ""); |
| 423 | } |
| 424 | } |