steid

@jamesgill /

steid/src/domain/import.rs
Rust17.0 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::{fmt, net::IpAddr, str::FromStr};
9
10use super::{
11 DomainError,
12 net::{is_public, names_local_network},
13};
14
15/// How far an import has got.
16///
17/// `None` on a repository — not a variant here — is the ordinary case: a repository
18/// that was never imported, or one whose import finished, is simply a repository. A
19/// `Ready` variant would mean every read had to remember that `Ready` and `NULL` are
20/// the same thing.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum ImportState {
23 /// The mirror is running, or the process died while it was.
24 Importing,
25 /// The mirror failed. The reason is on the repository, not in here: a state that
26 /// carried its own message would be a state that differs from itself.
27 Failed,
28}
29
30impl ImportState {
31 pub fn as_str(self) -> &'static str {
32 match self {
33 Self::Importing => "importing",
34 Self::Failed => "failed",
35 }
36 }
37}
38
39impl fmt::Display for ImportState {
40 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41 f.write_str(self.as_str())
42 }
43}
44
45/// `Result`, never `Option`. A silently-defaulted state would either serve a
46/// half-cloned repository as if it were finished, or hide a finished one forever.
47impl FromStr for ImportState {
48 type Err = DomainError;
49
50 fn from_str(value: &str) -> Result<Self, Self::Err> {
51 match value {
52 "importing" => Ok(Self::Importing),
53 "failed" => Ok(Self::Failed),
54 other => Err(DomainError::validation(
55 "import state",
56 format!("unknown import state {other:?}"),
57 )),
58 }
59 }
60}
61
62/// Where a repository is being imported from.
63///
64/// **This value becomes an argument to `git clone`, and the host becomes a connection
65/// the server makes on a visitor's behalf.** That is a server-side request forgery hole
66/// unless it is closed here, in one place: a form that will fetch any URL given to it
67/// can be pointed at a cloud metadata endpoint, an internal admin panel, or a service
68/// on loopback that trusts anything reaching it.
69///
70/// So the rules are deliberately narrow, and each is a refusal rather than a
71/// normalisation:
72///
73/// - **`https://` only.** Not `http://` (a token or a redirect in cleartext), not
74/// `git://` (unauthenticated), not `ssh://` (needs a key Steid does not have), and
75/// above all not `file://`, which would read the server's own disk.
76/// - **No userinfo.** `https://user:token@host/…` would store somebody's credential in
77/// a column that is rendered on a page.
78/// - **No literal address in a range that is not the public internet.** Checked here
79/// for an address typed into the form; the same predicate is applied by the adapter
80/// to whatever DNS resolves the host to, because a hostname can point anywhere.
81/// - **No name that means this machine or its own network** — `localhost`, `.local`,
82/// `.internal` and the rest of [`names_local_network`], the same list a webhook URL
83/// is held to.
84/// - **A port, when one is named, that the adapter can read the same way git does**,
85/// because the adapter pins the address it checked to that port.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct ImportSource(String);
88
89impl ImportSource {
90 /// Longest URL accepted. Far above any real clone address, and a bound on what a
91 /// form can put in a column.
92 pub const MAX_LEN: usize = 512;
93
94 /// The port an `https://` URL that names none is fetched from.
95 pub const DEFAULT_PORT: u16 = 443;
96
97 /// Validates a URL typed by a person.
98 pub fn new(value: impl Into<String>) -> Result<Self, DomainError> {
99 let value = value.into();
100 let trimmed = value.trim();
101
102 let invalid = |reason: &str| DomainError::validation("import source", reason);
103
104 if trimmed.is_empty() {
105 return Err(invalid("must not be empty"));
106 }
107 if trimmed.len() > Self::MAX_LEN {
108 return Err(invalid("is too long"));
109 }
110 // Control characters and spaces would be passed to `git clone` as part of one
111 // argument; nothing legitimate contains them.
112 if trimmed.chars().any(|c| c.is_control() || c == ' ') {
113 return Err(invalid("must not contain spaces or control characters"));
114 }
115
116 let Some(rest) = strip_https(trimmed) else {
117 return Err(invalid("must start with https://"));
118 };
119
120 let authority = rest
121 .split(['/', '?', '#'])
122 .next()
123 .expect("split always yields one part");
124
125 if authority.contains('@') {
126 return Err(invalid(
127 "must not carry a username or password — Steid only imports public repositories",
128 ));
129 }
130
131 let host = host_of(authority).ok_or_else(|| invalid("must name a host"))?;
132
133 if host.is_empty() {
134 return Err(invalid("must name a host"));
135 }
136 if names_local_network(host) {
137 return Err(invalid("must not point at this server or its own network"));
138 }
139 // An empty port (`host:/…`) means the default to git as to everyone else, so
140 // only a port that is written out and unreadable is refused.
141 if let Some(port) = port_text(authority)
142 && !port.is_empty()
143 && parse_port(port).is_none()
144 {
145 return Err(invalid("must name a port between 1 and 65535"));
146 }
147 if let Ok(address) = host.parse::<IpAddr>()
148 && !is_public(address)
149 {
150 return Err(invalid(
151 "must not be a private, loopback or link-local address",
152 ));
153 }
154
155 Ok(Self(trimmed.to_owned()))
156 }
157
158 /// Wraps a value already validated on the way into the database.
159 pub fn from_trusted(value: impl Into<String>) -> Self {
160 Self(value.into())
161 }
162
163 pub fn as_str(&self) -> &str {
164 &self.0
165 }
166
167 /// The host to resolve before connecting. Never empty — [`new`](Self::new) refused
168 /// a URL without one.
169 pub fn host(&self) -> &str {
170 let rest = strip_https(&self.0).unwrap_or(&self.0);
171 let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
172
173 host_of(authority).unwrap_or(authority)
174 }
175
176 /// The port git will connect to: the one the URL names, or
177 /// [`DEFAULT_PORT`](Self::DEFAULT_PORT).
178 ///
179 /// The adapter pins the address it checked to `host:port`, and curl applies a pin
180 /// only to the exact pair it names — so a pin on 443 for a URL on 8443 would leave
181 /// git resolving the name afresh, which is the hole the pin exists to close.
182 ///
183 /// A stored value whose port cannot be read answers the default. [`new`](Self::new)
184 /// refuses one, and git refuses to fetch such a URL before connecting anywhere, so
185 /// there is no connection for the pin to miss.
186 pub fn port(&self) -> u16 {
187 let rest = strip_https(&self.0).unwrap_or(&self.0);
188 let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
189
190 port_text(authority)
191 .and_then(parse_port)
192 .unwrap_or(Self::DEFAULT_PORT)
193 }
194
195 /// The repository name this source suggests — its last path segment without `.git`.
196 ///
197 /// A suggestion, not a decision: it pre-fills the form's name field and is put
198 /// through [`RepoName`](super::RepoName) like anything else typed there. Returns an
199 /// empty string when the URL has no usable segment, which the form renders as an
200 /// empty box rather than guessing.
201 pub fn suggested_name(&self) -> &str {
202 let Some(rest) = strip_https(&self.0) else {
203 return "";
204 };
205
206 let path = rest
207 .split(['?', '#'])
208 .next()
209 .unwrap_or("")
210 .trim_end_matches('/');
211
212 // Split at the authority first: the host is not a repository name, so a URL
213 // with no path at all must suggest nothing rather than suggest its host.
214 let Some((_authority, tail)) = path.split_once('/') else {
215 return "";
216 };
217
218 let segment = tail.split('/').next_back().unwrap_or("");
219
220 segment.strip_suffix(".git").unwrap_or(segment)
221 }
222}
223
224impl fmt::Display for ImportSource {
225 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
226 f.write_str(&self.0)
227 }
228}
229
230/// The part after `https://`, case-insensitively, or `None`.
231fn strip_https(value: &str) -> Option<&str> {
232 const SCHEME: &str = "https://";
233
234 if value.len() >= SCHEME.len() && value[..SCHEME.len()].eq_ignore_ascii_case(SCHEME) {
235 Some(&value[SCHEME.len()..])
236 } else {
237 None
238 }
239}
240
241/// The host out of an authority, with the port and IPv6 brackets removed.
242fn host_of(authority: &str) -> Option<&str> {
243 if let Some(rest) = authority.strip_prefix('[') {
244 // `[::1]:443` — the brackets exist precisely because the address contains colons.
245 return rest.split(']').next();
246 }
247
248 match authority.split_once(':') {
249 Some((host, _port)) => Some(host),
250 None => Some(authority),
251 }
252}
253
254/// The text after the host's `:`, or `None` when the authority names no port.
255fn port_text(authority: &str) -> Option<&str> {
256 match authority.strip_prefix('[') {
257 Some(rest) => rest.split_once(']')?.1.strip_prefix(':'),
258 None => authority.split_once(':').map(|(_host, port)| port),
259 }
260}
261
262/// A port as curl reads one: decimal digits only, from 1 to 65535.
263///
264/// Digits are checked before parsing because Rust's `u16` parser also takes a leading
265/// `+`, which curl refuses — and a port the two read differently is a port the pin
266/// would not name.
267fn parse_port(text: &str) -> Option<u16> {
268 if text.is_empty() || !text.bytes().all(|byte| byte.is_ascii_digit()) {
269 return None;
270 }
271
272 text.parse().ok().filter(|port| *port > 0)
273}
274
275#[cfg(test)]
276mod tests {
277 use super::*;
278
279 #[test]
280 fn import_state_round_trips_through_strings() {
281 for state in [ImportState::Importing, ImportState::Failed] {
282 assert_eq!(
283 state.as_str().parse::<ImportState>().expect("round trip"),
284 state
285 );
286 }
287 }
288
289 #[test]
290 fn unknown_import_state_is_an_error_not_a_default() {
291 assert!("ready".parse::<ImportState>().is_err());
292 assert!("".parse::<ImportState>().is_err());
293 }
294
295 #[test]
296 fn accepts_ordinary_public_clone_urls() {
297 for input in [
298 "https://github.com/rust-lang/mdBook.git",
299 "https://github.com/rust-lang/mdBook",
300 "https://gitlab.com/group/subgroup/project.git",
301 "HTTPS://example.com/thing.git",
302 "https://git.example.com:8443/thing.git",
303 " https://example.com/thing.git ",
304 ] {
305 assert!(
306 ImportSource::new(input).is_ok(),
307 "expected {input:?} to be accepted"
308 );
309 }
310 }
311
312 #[test]
313 fn refuses_every_scheme_but_https() {
314 for input in [
315 "http://example.com/thing.git",
316 "git://example.com/thing.git",
317 "ssh://git@example.com/thing.git",
318 "git@example.com:thing.git",
319 "file:///etc/passwd",
320 "/etc/passwd",
321 "//example.com/thing.git",
322 "httpsx://example.com/thing.git",
323 ] {
324 assert!(
325 ImportSource::new(input).is_err(),
326 "expected {input:?} to be refused"
327 );
328 }
329 }
330
331 /// The server-side request forgery boundary. Each of these, if allowed through,
332 /// becomes a connection Steid makes from inside its own network on a stranger's
333 /// instruction.
334 #[test]
335 fn refuses_addresses_that_are_not_the_public_internet() {
336 for input in [
337 "https://127.0.0.1/thing.git",
338 "https://127.1.2.3/thing.git",
339 "https://localhost/thing.git",
340 "https://LOCALHOST:8443/thing.git",
341 "https://api.localhost/thing.git",
342 "https://0.0.0.0/thing.git",
343 "https://10.0.0.5/thing.git",
344 "https://172.16.4.1/thing.git",
345 "https://192.168.1.1/thing.git",
346 // The AWS/GCP metadata endpoint, the canonical SSRF target.
347 "https://169.254.169.254/latest/meta-data",
348 "https://100.64.0.1/thing.git",
349 "https://[::1]/thing.git",
350 "https://[::]/thing.git",
351 "https://[fd00::1]/thing.git",
352 "https://[fe80::1]/thing.git",
353 "https://[::ffff:127.0.0.1]/thing.git",
354 ] {
355 assert!(
356 ImportSource::new(input).is_err(),
357 "expected {input:?} to be refused: it is not on the public internet"
358 );
359 }
360 }
361
362 /// The names a webhook was already refused, now refused to an import too: an mDNS
363 /// `.local` answers from whichever machine on the LAN claims it, and `.internal` is
364 /// how cloud platforms name their own services, the metadata server included.
365 #[test]
366 fn refuses_names_on_the_local_network() {
367 for input in [
368 "https://steid.local/thing.git",
369 "https://NAS.LOCAL:8443/thing.git",
370 "https://db.internal/thing.git",
371 "https://metadata.google.internal/computeMetadata/v1/",
372 "https://box.localdomain/thing.git",
373 "https://localhost./thing.git",
374 ] {
375 assert!(
376 ImportSource::new(input).is_err(),
377 "expected {input:?} to be refused: it names the local network"
378 );
379 }
380 }
381
382 #[test]
383 fn refuses_a_port_that_cannot_be_read() {
384 for input in [
385 "https://example.com:0/thing.git",
386 "https://example.com:65536/thing.git",
387 "https://example.com:+443/thing.git",
388 "https://example.com:https/thing.git",
389 "https://[2606:4700::1111]:x/thing.git",
390 ] {
391 assert!(
392 ImportSource::new(input).is_err(),
393 "expected {input:?} to be refused"
394 );
395 }
396 }
397
398 #[test]
399 fn the_port_is_the_one_the_url_names_or_443() {
400 let port = |url: &str| ImportSource::new(url).expect("valid").port();
401
402 assert_eq!(port("https://example.com/thing.git"), 443);
403 assert_eq!(port("https://git.example.com:8443/thing.git"), 8443);
404 assert_eq!(port("https://example.com:/thing.git"), 443);
405 assert_eq!(port("https://[2606:4700::1111]/thing.git"), 443);
406 assert_eq!(port("https://[2606:4700::1111]:8443/thing.git"), 8443);
407 assert_eq!(port("https://example.com:8443?x=1"), 8443);
408 }
409
410 #[test]
411 fn refuses_credentials_in_the_url() {
412 // They would be stored in a column the repository page renders.
413 assert!(ImportSource::new("https://user:token@example.com/thing.git").is_err());
414 assert!(ImportSource::new("https://token@example.com/thing.git").is_err());
415 }
416
417 #[test]
418 fn refuses_malformed_urls() {
419 for input in [
420 "",
421 " ",
422 "https://",
423 "https:///no/host.git",
424 "https://exa mple.com/thing.git",
425 "https://example.com/thing\n.git",
426 &format!("https://example.com/{}", "a".repeat(ImportSource::MAX_LEN)),
427 ] {
428 assert!(
429 ImportSource::new(input).is_err(),
430 "expected {input:?} to be refused"
431 );
432 }
433 }
434
435 #[test]
436 fn a_public_address_is_still_allowed() {
437 assert!(ImportSource::new("https://1.1.1.1/thing.git").is_ok());
438 assert!(ImportSource::new("https://[2606:4700::1111]/thing.git").is_ok());
439 }
440
441 #[test]
442 fn the_host_is_read_back_without_its_port_or_brackets() {
443 let host = |url: &str| ImportSource::new(url).expect("valid").host().to_owned();
444
445 assert_eq!(host("https://example.com/thing.git"), "example.com");
446 assert_eq!(
447 host("https://git.example.com:8443/thing.git"),
448 "git.example.com"
449 );
450 assert_eq!(
451 host("https://[2606:4700::1111]:8443/thing.git"),
452 "2606:4700::1111"
453 );
454 assert_eq!(host("https://example.com"), "example.com");
455 }
456
457 #[test]
458 fn the_last_path_segment_suggests_the_name() {
459 let name = |url: &str| {
460 ImportSource::new(url)
461 .expect("valid")
462 .suggested_name()
463 .to_owned()
464 };
465
466 assert_eq!(name("https://github.com/rust-lang/mdBook.git"), "mdBook");
467 assert_eq!(name("https://github.com/rust-lang/mdBook"), "mdBook");
468 assert_eq!(name("https://example.com/a/b/c.git/"), "c");
469 assert_eq!(name("https://example.com/thing.git?ref=main"), "thing");
470 // No path at all: nothing to suggest, and a guess of "example.com" would be
471 // both wrong and an invalid repository name.
472 assert_eq!(name("https://example.com"), "");
473 assert_eq!(name("https://example.com/"), "");
474 }
475}