steid

@jamesgill /

steid/src/domain/import.rs
Rust14.9 KBCode·Blame·History·Raw
1//! Importing a repository from somewhere else.
2//!
3//! Two values live here: where the code is coming from, and how far the copy has got.
4//! Both are domain concerns — the address is a security boundary in the same way
5//! [`RepoName`](super::RepoName) is, and the state is a fact about the repository that
6//! storage and the page have to agree on.
7
8use std::{
9 fmt,
10 net::{IpAddr, Ipv4Addr, Ipv6Addr},
11 str::FromStr,
12};
13
14use super::DomainError;
15
16/// How far an import has got.
17///
18/// `None` on a repository — not a variant here — is the ordinary case: a repository
19/// that was never imported, or one whose import finished, is simply a repository. A
20/// `Ready` variant would mean every read had to remember that `Ready` and `NULL` are
21/// the same thing.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum ImportState {
24 /// The mirror is running, or the process died while it was.
25 Importing,
26 /// The mirror failed. The reason is on the repository, not in here: a state that
27 /// carried its own message would be a state that differs from itself.
28 Failed,
29}
30
31impl ImportState {
32 pub fn as_str(self) -> &'static str {
33 match self {
34 Self::Importing => "importing",
35 Self::Failed => "failed",
36 }
37 }
38}
39
40impl 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/// `Result`, never `Option`. A silently-defaulted state would either serve a
47/// half-cloned repository as if it were finished, or hide a finished one forever.
48impl 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/// Where a repository is being imported from.
64///
65/// **This value becomes an argument to `git clone`, and the host becomes a connection
66/// the server makes on a visitor's behalf.** That is a server-side request forgery hole
67/// unless it is closed here, in one place: a form that will fetch any URL given to it
68/// can be pointed at a cloud metadata endpoint, an internal admin panel, or a service
69/// on loopback that trusts anything reaching it.
70///
71/// So the rules are deliberately narrow, and each is a refusal rather than a
72/// normalisation:
73///
74/// - **`https://` only.** Not `http://` (a token or a redirect in cleartext), not
75/// `git://` (unauthenticated), not `ssh://` (needs a key Steid does not have), and
76/// above all not `file://`, which would read the server's own disk.
77/// - **No userinfo.** `https://user:token@host/…` would store somebody's credential in
78/// a column that is rendered on a page.
79/// - **No literal address in a range that is not the public internet.** Checked here
80/// for an address typed into the form; the same predicate is applied by the adapter
81/// to whatever DNS resolves the host to, because a hostname can point anywhere.
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct ImportSource(String);
84
85impl ImportSource {
86 /// Longest URL accepted. Far above any real clone address, and a bound on what a
87 /// form can put in a column.
88 pub const MAX_LEN: usize = 512;
89
90 /// Validates a URL typed by a person.
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 // Control characters and spaces would be passed to `git clone` as part of one
104 // argument; nothing legitimate contains them.
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 /// Wraps a value already validated on the way into the database.
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 /// The host to resolve before connecting. Never empty — [`new`](Self::new) refused
153 /// a URL without one.
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 /// The repository name this source suggests — its last path segment without `.git`.
162 ///
163 /// A suggestion, not a decision: it pre-fills the form's name field and is put
164 /// through [`RepoName`](super::RepoName) like anything else typed there. Returns an
165 /// empty string when the URL has no usable segment, which the form renders as an
166 /// empty box rather than guessing.
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 // Split at the authority first: the host is not a repository name, so a URL
179 // with no path at all must suggest nothing rather than suggest its host.
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
190impl fmt::Display for ImportSource {
191 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192 f.write_str(&self.0)
193 }
194}
195
196/// The part after `https://`, case-insensitively, or `None`.
197fn 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
207fn 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/// The host out of an authority, with the port and IPv6 brackets removed.
212fn host_of(authority: &str) -> Option<&str> {
213 if let Some(rest) = authority.strip_prefix('[') {
214 // `[::1]:443` — the brackets exist precisely because the address contains colons.
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/// Whether an address is somewhere Steid is willing to connect on a visitor's say-so.
225///
226/// The allowlist is "the public internet", expressed as a denylist of everything that
227/// is not, because the ranges that are not routable are the finite, enumerable half.
228/// Anything unrecognised is therefore *allowed* — which is the right way round only
229/// because the reserved ranges below are fixed by IANA and do not grow quietly.
230pub fn is_public(address: IpAddr) -> bool {
231 match address {
232 // An IPv4-mapped v6 address reaches the same host as the v4 one, so it has to
233 // answer the same way: `::ffff:127.0.0.1` is loopback however it is spelled.
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
242fn 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 // 0.0.0.0/8 — "this network". Reaches the local host on some stacks.
252 || a == 0
253 // 100.64.0.0/10, carrier-grade NAT: a provider's internal space, not the
254 // internet, and `Ipv4Addr` has no predicate for it.
255 || (a == 100 && (64..128).contains(&b))
256 // 198.18.0.0/15, benchmarking. Routed to lab equipment where it is used at all.
257 || (a == 198 && (b == 18 || b == 19)))
258}
259
260fn 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 // fc00::/7, unique local — IPv6's answer to RFC 1918.
267 || (first & 0xfe00) == 0xfc00
268 // fe80::/10, link-local.
269 || (first & 0xffc0) == 0xfe80)
270}
271
272#[cfg(test)]
273mod 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 /// The server-side request forgery boundary. Each of these, if allowed through,
329 /// becomes a connection Steid makes from inside its own network on a stranger's
330 /// instruction.
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 // The AWS/GCP metadata endpoint, the canonical SSRF target.
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 // They would be stored in a column the repository page renders.
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 // No path at all: nothing to suggest, and a guess of "example.com" would be
420 // both wrong and an invalid repository name.
421 assert_eq!(name("https://example.com"), "");
422 assert_eq!(name("https://example.com/"), "");
423 }
424}