girt 0.14.0

An incremental, idiomatic Rust implementation of Git
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
//! Bounded URL validation for configured remote snapshots, not transport admission.

/// A value-free configured URL validation diagnostic.
///
/// The URL in configuration is malformed, except for [`Unsupported`](Self::Unsupported), which
/// marks a form girt does not interpret, such as a Windows UNC path or a value with control bytes.
/// Such a value may or may not be valid for Git; girt has not decided. Report malformed values to
/// the user with the remote and key, and hand unsupported values to whatever else the application
/// uses to interpret configuration, or report them as unsupported by girt.
///
/// # Examples
///
/// ```
/// use girt::remote::{ConfiguredUrlError, parse_configured_url};
///
/// let error = |url: &[u8]| parse_configured_url(url).err();
/// assert_eq!(
///     error(b"https://example.com:0/project.git"),
///     Some(ConfiguredUrlError::Port)
/// );
/// // A Windows UNC path is valid Git syntax that girt does not interpret yet.
/// assert_eq!(
///     error(b"\\\\server\\share\\project.git"),
///     Some(ConfiguredUrlError::Unsupported)
/// );
/// assert_eq!(error(b"https://example.com/project.git"), None);
/// ```
#[derive(Debug, Clone, Copy, Eq, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum ConfiguredUrlError {
    /// The supported URL form requires a repository path.
    #[error("remote URL has no repository path")]
    MissingPath,
    /// A scheme URL cannot be decoded as UTF-8.
    #[error("remote network URL is not UTF-8")]
    Encoding,
    /// The supported URL form has an empty or malformed host or user component.
    #[error("invalid remote URL authority")]
    Authority,
    /// An explicit numeric port must fit a nonzero u16.
    #[error("invalid remote URL port")]
    Port,
    /// A network path has malformed percent escapes or decodes to invalid UTF-8.
    #[error("invalid remote URL path escape")]
    PathEscape,
    /// URL syntax or normalization is outside the characterized subset.
    /// [`super::ConfiguredRemote`] reports this as its distinct unsupported error variant.
    #[error("unsupported configured URL syntax")]
    Unsupported,
}

/// Interpreted presentation components of a configured Git location.
///
/// Construct with [`parse_configured_url`]. Components describe URL syntax and do not authorize a
/// transport. Host and path bytes can contain private data; Debug omits them. No credentials or
/// port are included in the host. This type owns its components independently of the source
/// configuration.
#[derive(Clone, PartialEq, Eq)]
pub struct ConfiguredUrlParts {
    pub(super) protocol: super::Protocol,
    pub(super) host: Option<Vec<u8>>,
    pub(super) path: Vec<u8>,
}

impl std::fmt::Debug for ConfiguredUrlParts {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ConfiguredUrlParts")
            .field("protocol", &self.protocol)
            .finish_non_exhaustive()
    }
}

impl ConfiguredUrlParts {
    /// Returns the recognized protocol family without granting transport permission.
    ///
    /// Lowercase `file` URLs are [`super::Protocol::File`]; local paths are
    /// [`super::Protocol::Local`]. Custom and mixed-case schemes are [`super::Protocol::Helper`].
    pub fn protocol(&self) -> super::Protocol {
        self.protocol
    }

    /// Returns the host without credentials or a port, or None for a hostless location.
    ///
    /// HTTP(S) retains encoded host spelling and IPv6 brackets. Other scheme hosts decode percent
    /// escapes; SSH and scp hosts omit enclosing brackets. File and scp hosts retain literal
    /// percent sequences. Ordinary ASCII names are lowercased; opaque host spelling is
    /// retained.
    pub fn host(&self) -> Option<&[u8]> {
        self.host.as_deref()
    }

    /// Returns the interpreted repository path, including any query or fragment suffix.
    ///
    /// Scheme URL paths decode percent escapes once, except lowercase file URLs. Local, file and
    /// scp-like paths are literal. No slash trimming, suffix removal, filesystem expansion or
    /// canonicalization occurs. Decoded control bytes may be present: this is not a filesystem or
    /// transport-ready path.
    pub fn path(&self) -> &[u8] {
        &self.path
    }
}

/// Parses configured URL presentation components without filesystem or network access.
///
/// Applies the same syntax boundary as [`normalize_configured_url`], retaining the shared parser's
/// interpreted host and path rather than parsing the serialized URL again. For lossless syntactic
/// components use [`super::ParsedUrl`] instead. This operation does not load remote configuration,
/// apply rewrites or decide how to construct a web link.
///
/// # Errors
///
/// Returns the same value-free validation and unsupported-syntax errors as
/// [`normalize_configured_url`].
///
/// ```
/// use girt::remote::{Protocol, parse_configured_url};
/// let url = parse_configured_url(b"ssh://user@HOST/team/repo%2Egit")?;
/// assert_eq!(url.protocol(), Protocol::Ssh);
/// assert_eq!(url.host(), Some(b"host".as_slice()));
/// assert_eq!(url.path(), b"/team/repo.git");
/// let literal = parse_configured_url(b"user@HOST:team/repo%2Egit")?;
/// assert_eq!(literal.path(), b"team/repo%2Egit");
/// # Ok::<(), girt::remote::ConfiguredUrlError>(())
/// ```
pub fn parse_configured_url(bytes: &[u8]) -> Result<ConfiguredUrlParts, ConfiguredUrlError> {
    parse(bytes).map(|url| url.parts)
}

/// Validates and serializes one configured destination, without applying URL rewrites.
///
/// Supports ordinary local byte paths, file URLs, scp-like SSH, and scheme-based network URLs.
/// Ordinary ASCII hosts are lowercased. HTTP(S) retains percent-encoded host spelling; SSH and
/// custom schemes interpret host escapes before serialization. Numeric ports lose leading zeroes;
/// explicit default ports and ordinary dot path segments are retained. File-host case is preserved.
/// An HTTP(S)
/// URL without a path gains `/`. Local paths can contain non-UTF-8 bytes and spaces.
/// File URL paths also retain literal spaces, without encoding or trimming them.
/// Percent spelling and case in paths are retained. HTTP(S)/SSH path escapes must be complete hex
/// pairs whose decoded bytes form UTF-8; file/scp path percent sequences remain uninterpreted.
///
/// Unlike an empty value in [`super::ConfiguredRemoteRecord`], an empty destination is an error,
/// not a list reset. This function does not read configuration, apply fetch-to-push fallback,
/// authorize a transport, access the network or check whether a repository exists.
/// Returned bytes may contain private paths or credentials; do not log them by default.
///
/// Accepts IPv6, credentials, authority escapes, query/fragment components, custom schemes and
/// retained scheme case using the same pure normalization as [`super::canonicalize_user_url`].
/// Relative local paths and file paths remain unchanged: no filesystem access or canonicalization
/// occurs. On Windows, absolute drive paths (including verbatim drive paths) remain local and
/// retain their spelling. Parsing a custom scheme does not authorize its transport.
///
/// # Errors
///
/// Returns a value-free diagnostic for malformed supported syntax. Helper syntax, control bytes,
/// Windows drive paths on non-Windows hosts, UNC paths, bracketed scp hosts with an explicit user,
/// and uncharacterized file authorities return [`ConfiguredUrlError::Unsupported`]. That result
/// requests compatibility handling; it does not
/// establish that the destination is malformed.
///
/// ```
/// use girt::remote::{ConfiguredUrlError, normalize_configured_url};
/// assert_eq!(
///     normalize_configured_url(b"https://HOST:00443/repo")?,
///     b"https://host:443/repo"
/// );
/// assert_eq!(
///     normalize_configured_url(b"https://HOST/a%2fb")?,
///     b"https://host/a%2fb"
/// );
/// assert_eq!(
///     normalize_configured_url(b"file:///repo name ")?,
///     b"file:///repo name "
/// );
/// assert_eq!(
///     normalize_configured_url(b""),
///     Err(ConfiguredUrlError::MissingPath)
/// );
/// # Ok::<(), ConfiguredUrlError>(())
/// ```
pub fn normalize_configured_url(bytes: &[u8]) -> Result<Vec<u8>, ConfiguredUrlError> {
    normalize(bytes)
}

pub(super) fn normalize(bytes: &[u8]) -> Result<Vec<u8>, ConfiguredUrlError> {
    parse(bytes).map(|url| url.bytes)
}

pub(super) fn parse(bytes: &[u8]) -> Result<super::user_url::NormalizedUrl, ConfiguredUrlError> {
    validate_input(bytes)?;
    super::user_url::parse(bytes).map_err(configured_error)
}

fn validate_input(bytes: &[u8]) -> Result<(), ConfiguredUrlError> {
    use ConfiguredUrlError as Error;
    if bytes.is_empty() {
        return Err(Error::MissingPath);
    }
    if bytes.iter().any(|b| b.is_ascii_control()) {
        return Err(Error::Unsupported);
    }
    // The shared parser preserves Windows drive paths as local bytes. Keep UNC and device
    // namespaces outside this characterized subset, apart from verbatim absolute drive paths.
    if cfg!(windows) && absolute_windows_drive(bytes.strip_prefix(br"\\?\").unwrap_or(bytes)) {
        return Ok(());
    }
    if bytes.starts_with(b"\\") {
        return Err(Error::Unsupported);
    }
    if absolute_windows_drive(bytes) {
        return Err(Error::Unsupported);
    }
    let colon = bytes.iter().position(|b| *b == b':');
    let slash = bytes.iter().position(|b| *b == b'/');
    if let Some(colon) = colon.filter(|colon| slash.is_none_or(|slash| *colon < slash)) {
        // Only an explicit user in the scp authority triggers this compatibility boundary;
        // the same bytes in a local path or scp repository path remain literal.
        if bytes.get(colon + 1..colon + 3) != Some(b"//")
            && bytes[..colon].windows(2).any(|part| part == b"@[")
        {
            return Err(Error::Unsupported);
        }
        if bytes.get(colon + 1) == Some(&b':')
            && bytes[..colon]
                .iter()
                .all(|b| b.is_ascii_alphanumeric() || b"+.-".contains(b))
        {
            return Err(Error::Unsupported);
        }
        if bytes.starts_with(b"file://") {
            return file_url(bytes, 7);
        }
        if bytes.get(colon + 1..colon + 3) == Some(b"//") {
            std::str::from_utf8(bytes).map_err(|_| Error::Encoding)?;
        }
    }
    Ok(())
}

fn absolute_windows_drive(bytes: &[u8]) -> bool {
    bytes.len() >= 3
        && bytes[0].is_ascii_alphabetic()
        && bytes[1] == b':'
        && matches!(bytes[2], b'/' | b'\\')
}

fn configured_error(error: super::UserUrlParseError) -> ConfiguredUrlError {
    use ConfiguredUrlError as Error;

    use super::UserUrlParseError as Parse;
    match error {
        Parse::EmptyPath | Parse::MissingUrlPath | Parse::MissingScpPath => Error::MissingPath,
        Parse::MissingHost | Parse::InvalidAuthority | Parse::InvalidScp => Error::Authority,
        Parse::InvalidPort => Error::Port,
        Parse::InvalidEscape | Parse::InvalidEncoding => Error::PathEscape,
        Parse::InvalidUrl => Error::Unsupported,
    }
}

fn file_url(bytes: &[u8], start: usize) -> Result<(), ConfiguredUrlError> {
    let rest = &bytes[start..];
    if rest.is_empty() {
        return Err(ConfiguredUrlError::MissingPath);
    }
    let Some(slash) = rest.iter().position(|b| *b == b'/') else {
        return Err(ConfiguredUrlError::Unsupported);
    };
    let host = &rest[..slash];
    if !host
        .iter()
        .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-'))
    {
        return Err(ConfiguredUrlError::Unsupported);
    }
    // Literal file-path spaces are preserved; all other path checks remain shared.
    for part in rest[slash..].split(|byte| *byte == b' ') {
        plain_path(part)?;
    }
    Ok(())
}

fn plain_path(path: &[u8]) -> Result<(), ConfiguredUrlError> {
    if path.contains(&b' ') {
        return Err(ConfiguredUrlError::Unsupported);
    }
    if !path.iter().all(|b| {
        b.is_ascii_alphanumeric() || matches!(b, b'/' | b'.' | b'_' | b'-' | b'~' | b'+' | b'%')
    }) {
        return Err(ConfiguredUrlError::Unsupported);
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use rstest::rstest;

    use super::*;

    // Original observations of the gix 0.87.1 public URL API on macOS; no upstream sources.
    #[rstest]
    #[case::local(b"../repo with spaces", b"../repo with spaces")]
    #[case::local_bytes(b"/repo/\xff", b"/repo/\xff")]
    #[case::local_colon(b"./repo:part", b"./repo:part")]
    #[case::file(b"file:///tmp/repo", b"file:///tmp/repo")]
    #[case::file_host(b"file://HOST/repo", b"file://HOST/repo")]
    #[case::scp(b"user@HOST:repo", b"user@host:repo")]
    #[case::ssh(b"ssh://user@HOST:00022/repo", b"ssh://user@host:22/repo")]
    #[case::default_port_retained(b"https://HOST:443/repo", b"https://host:443/repo")]
    #[case::http_path(b"https://HOST", b"https://host/")]
    #[case::numeric_host(b"https://127.1/repo", b"https://127.1/repo")]
    #[case::dot_segments(b"https://host/a/../repo", b"https://host/a/../repo")]
    #[case::empty_port(b"https://host:/repo", b"https://host:/repo")]
    fn canonical_values(#[case] input: &[u8], #[case] expected: &[u8]) {
        assert_eq!(
            crate::remote::normalize_configured_url(input).unwrap(),
            expected
        );
    }

    #[rstest]
    #[case::empty(b"", ConfiguredUrlError::MissingPath)]
    #[case::scp_empty(b"host:", ConfiguredUrlError::MissingPath)]
    #[case::file_empty(b"file://", ConfiguredUrlError::MissingPath)]
    #[case::ssh_empty(b"ssh://host", ConfiguredUrlError::MissingPath)]
    #[case::bad_port(b"http://host:bad/repo", ConfiguredUrlError::Port)]
    #[case::zero_port(b"http://host:0/repo", ConfiguredUrlError::Port)]
    #[case::large_port(b"http://host:65536/repo", ConfiguredUrlError::Port)]
    #[case::host_space(b"http://bad host/repo", ConfiguredUrlError::Authority)]
    #[case::user_without_host(b"http://user@/repo", ConfiguredUrlError::Authority)]
    #[case::empty_host(b"http:///repo", ConfiguredUrlError::Authority)]
    #[case::network_bytes(b"http://host/\xff", ConfiguredUrlError::Encoding)]
    #[case::helper(b"foo::repo", ConfiguredUrlError::Unsupported)]
    #[case::unc(br"\\server\share\repo", ConfiguredUrlError::Unsupported)]
    #[case::verbatim_unc(br"\\?\UNC\server\share\repo", ConfiguredUrlError::Unsupported)]
    #[case::drive_control(b"C:/repo\n", ConfiguredUrlError::Unsupported)]
    #[case::scp_bracket_user(b"user@[::1]:repo", ConfiguredUrlError::Unsupported)]
    fn failures(#[case] input: &[u8], #[case] error: ConfiguredUrlError) {
        assert_eq!(
            crate::remote::normalize_configured_url(input).unwrap_err(),
            error
        );
    }

    #[cfg(windows)]
    #[rstest]
    #[case::backslash(br"C:\repo with spaces")]
    #[case::slash(b"C:/repo with spaces")]
    #[case::verbatim(br"\\?\C:\repo with spaces")]
    fn absolute_drive_paths_remain_local(#[case] input: &[u8]) {
        let parts = parse_configured_url(input).unwrap();
        assert_eq!(parts.protocol(), crate::remote::Protocol::Local);
        assert_eq!(parts.host(), None);
        assert_eq!(parts.path(), input);
        assert_eq!(normalize_configured_url(input).unwrap(), input);
    }

    #[test]
    fn single_url_error_does_not_disclose_input() {
        let error =
            normalize_configured_url(b"https://user:private-password@host:bad/repo").unwrap_err();
        assert_eq!(error, ConfiguredUrlError::Port);
        assert!(!format!("{error:?}: {error}").contains("private-password"));
    }
    // Original public-gix 0.87.1 percent-path fixtures; serialized bytes remain encoded.
    #[rstest]
    #[case::space(b"https://HOST/a%20b", b"https://host/a%20b")]
    #[case::slash_lower(b"https://HOST/a%2fb", b"https://host/a%2fb")]
    #[case::slash_upper(b"https://HOST/a%2Fb", b"https://host/a%2Fb")]
    #[case::nul(b"https://HOST/a%00b", b"https://host/a%00b")]
    #[case::dot_segments(b"https://HOST/%2e%2e/repo", b"https://host/%2e%2e/repo")]
    #[case::question(b"https://HOST/a%3Fb", b"https://host/a%3Fb")]
    #[case::hash(b"https://HOST/a%23b", b"https://host/a%23b")]
    #[case::percent(b"http://HOST/%25/repo", b"http://host/%25/repo")]
    #[case::ssh_space(b"ssh://HOST/a%20b", b"ssh://host/a%20b")]
    #[case::ssh_slash(b"ssh://HOST/%2Frepo", b"ssh://host/%2Frepo")]
    #[case::file_space(b"file:///tmp/a%20b", b"file:///tmp/a%20b")]
    #[case::file_host(b"file://HOST/a%2Fb", b"file://HOST/a%2Fb")]
    #[case::file_unfinished(b"file:///tmp/a%", b"file:///tmp/a%")]
    #[case::scp_space(b"HOST:a%20b", b"host:a%20b")]
    #[case::scp_user(b"user@HOST:a%2fb", b"user@host:a%2fb")]
    #[case::scp_nonhex(b"HOST:a%GGb", b"host:a%GGb")]
    #[case::local(b"./local%20path", b"./local%20path")]
    #[case::local_invalid_utf8(b"/local/%FF", b"/local/%FF")]
    #[case::unicode(b"https://HOST/%C3%A9", b"https://host/%C3%A9")]
    #[case::newline(b"https://HOST/%0A", b"https://host/%0A")]
    #[case::delete(b"https://HOST/%7F", b"https://host/%7F")]
    #[case::backslash(b"https://HOST/%5C", b"https://host/%5C")]
    #[case::double_percent(b"https://HOST/%2520", b"https://host/%2520")]
    #[case::at(b"https://HOST/%40", b"https://host/%40")]
    #[case::euro(b"https://HOST/%E2%82%AC", b"https://host/%E2%82%AC")]
    fn percent_path_serialization(#[case] input: &[u8], #[case] expected: &[u8]) {
        assert_eq!(
            crate::remote::normalize_configured_url(input).unwrap(),
            expected
        );
    }

    #[rstest]
    #[case::invalid_utf8(b"https://HOST/a%FFb")]
    #[case::one_digit(b"https://HOST/a%b")]
    #[case::missing_pair(b"https://HOST/a%")]
    #[case::missing_digit(b"https://HOST/a%2")]
    #[case::nonhex(b"https://HOST/a%GGb")]
    #[case::ssh_nonhex(b"ssh://HOST/a%GGb")]
    #[case::overlong(b"https://HOST/%C0%AF")]
    #[case::surrogate(b"https://HOST/%ED%A0%80")]
    #[case::truncated_utf8(b"https://HOST/%C3")]
    fn invalid_network_path_escape_is_value_free(#[case] input: &[u8]) {
        let error = crate::remote::normalize_configured_url(input).unwrap_err();
        assert_eq!(error, ConfiguredUrlError::PathEscape);
        assert_eq!(error.to_string(), "invalid remote URL path escape");
        assert_eq!(format!("{error:?}"), "PathEscape");
    }

    #[rstest]
    #[case::host(b"https://HOST%2Eexample/repo", b"https://HOST%2Eexample/repo")]
    #[case::user(b"https://user%20name@HOST/repo", b"https://user%20name@host/repo")]
    #[case::query(b"https://HOST/a%20b?query", b"https://host/a%20b?query")]
    #[case::fragment(b"https://HOST/a%20b#fragment", b"https://host/a%20b#fragment")]
    #[case::credentials(b"https://user:secret@HOST/a%20b", b"https://user:secret@host/a%20b")]
    #[case::ipv6(b"https://[::1]/a%20b", b"https://[::1]/a%20b")]
    #[case::scheme(b"HTTPS://HOST/a%20b", b"HTTPS://host/a%20b")]
    #[case::custom(b"foo://HOST/repo", b"foo://host/repo")]
    #[case::ssh_ipv6(b"ssh://[::1]/repo", b"ssh://[::1]/repo")]
    #[case::authority_escape(b"https://host%20name/repo", b"https://host%20name/repo")]
    #[case::scp_space(b"HOST:repo name", b"host:repo name")]
    fn additional_presentation_syntax(#[case] input: &[u8], #[case] expected: &[u8]) {
        assert_eq!(normalize_configured_url(input).unwrap(), expected);
    }
    // Original gix 0.87.1 public URL oracle: file path spaces serialize byte-for-byte.
    #[rstest]
    #[case::ordinary(b"file:///tmp/repo name")]
    #[case::authority_case(b"file://HOST/repo name")]
    #[case::leading(b"file:/// repo")]
    #[case::trailing(b"file:///repo ")]
    #[case::repeated(b"file:///repo  name")]
    #[case::only_space(b"file:/// ")]
    #[case::components(b"file:///a b/c d")]
    #[case::percent(b"file:///a%20b c")]
    #[case::literal_percent(b"file:///a%GG b")]
    fn file_path_spaces_remain_literal(#[case] input: &[u8]) {
        assert_eq!(
            crate::remote::normalize_configured_url(input).unwrap(),
            input
        );
    }

    #[rstest]
    #[case::authority(b"file://bad host/repo")]
    #[case::tab(b"file:///a\tb")]
    #[case::newline(b"file:///a\nb")]
    #[case::nul(b"file:///a\0b")]
    #[case::encoding(b"file:///a\xff b")]
    #[case::ssh(b"ssh://host/repo name")]
    #[case::http(b"https://host/repo name")]
    fn file_spaces_do_not_change_other_boundaries(#[case] input: &[u8]) {
        assert_eq!(
            crate::remote::normalize_configured_url(input),
            Err(ConfiguredUrlError::Unsupported)
        );
    }
    #[rstest]
    #[case::credentials(
        b"https://user:secret@HOST:00443/repo",
        b"https://user:secret@host:443/repo"
    )]
    #[case::escaped_user(b"https://u%41:p%3a@HOST/repo", b"https://uA:p:@host/repo")]
    #[case::query_fragment(b"https://HOST/repo?token=x#part", b"https://host/repo?token=x#part")]
    #[case::opaque_authority(b"custom://HOST?x/repo", b"custom://HOST%3Fx/repo")]
    #[case::uppercase(b"HTTPS://HOST/repo", b"HTTPS://host/repo")]
    #[case::custom_utf8(b"custom://HOST/\xc3\xa9", b"custom://host/\xc3\xa9")]
    #[case::local_bracket(b"./repo@[backup", b"./repo@[backup")]
    #[case::absolute_bracket(b"/tmp/repo@[backup", b"/tmp/repo@[backup")]
    #[case::scp_path_bracket(b"HOST:repo@[backup", b"host:repo@[backup")]
    #[case::local_bracket_colon(b"./repo@[backup:old", b"./repo@[backup:old")]
    #[case::relative_parent(b"../missing/./repo", b"../missing/./repo")]
    #[case::relative_byte(b"./missing/\xff", b"./missing/\xff")]
    #[case::file_dots(b"file:///missing/a/../repo  ", b"file:///missing/a/../repo  ")]
    #[case::expanded_ipv6(
        b"ssh://[2001:db8:0:0:0:0:0:1]/repo",
        b"ssh://[2001:db8:0:0:0:0:0:1]/repo"
    )]
    fn pure_normalization_retains_config_meaning(#[case] input: &[u8], #[case] expected: &[u8]) {
        assert_eq!(normalize_configured_url(input).unwrap(), expected);
    }

    #[cfg(unix)]
    #[test]
    fn configured_paths_do_not_follow_symlinks_or_resolve_parent_components() {
        let directory = tempfile::tempdir().unwrap();
        let link = directory.path().join("loop");
        std::os::unix::fs::symlink("loop", &link).unwrap();
        let input = format!("file://{}/loop/../repo name ", directory.path().display());
        assert_eq!(
            normalize_configured_url(input.as_bytes()).unwrap(),
            input.as_bytes()
        );
        assert_eq!(
            std::fs::read_link(link).unwrap(),
            std::path::Path::new("loop")
        );
    }

    #[cfg(feature = "http")]
    #[rstest]
    #[case::credentials(b"https://user:secret@HOST/repo")]
    #[case::query(b"https://HOST/repo?secret=value")]
    #[case::fragment(b"https://HOST/repo#secret")]
    #[case::custom(b"custom://HOST/repo")]
    fn config_acceptance_does_not_authorize_http(#[case] input: &[u8]) {
        let normalized = normalize_configured_url(input).unwrap();
        let url = std::str::from_utf8(&normalized).unwrap();
        let error = crate::transport::http::HttpRemote::new(url, &[], &[]).unwrap_err();
        assert!(!format!("{error:?}: {error}").contains("secret"));
    }

    #[cfg(all(feature = "ssh", unix))]
    #[rstest]
    #[case::credentials(b"ssh://user:secret@HOST/repo")]
    #[case::query(b"ssh://HOST/repo?secret=value")]
    #[case::fragment(b"ssh://HOST/repo#secret")]
    #[case::escape(b"ssh://HOST/repo%20name")]
    fn config_acceptance_does_not_authorize_ssh(#[case] input: &[u8]) {
        use crate::remote::{ProtocolEnvironment, Remote};
        use crate::transport::ssh::{OpenSshOptions, SshRemote};
        let normalized = normalize_configured_url(input).unwrap();
        let mut document = crate::config::Document::parse(b"").unwrap();
        document
            .append("remote", Some(b"r"), "url", &normalized)
            .unwrap();
        let config = document.config();
        let destination = Remote::find(config, b"r")
            .unwrap()
            .unwrap()
            .fetch_destination(config, &ProtocolEnvironment::default())
            .unwrap();
        let error = SshRemote::openssh(
            config,
            &destination,
            OpenSshOptions {
                default_executable: "/usr/bin/ssh".into(),
                ..OpenSshOptions::default()
            },
        )
        .unwrap_err();
        assert!(!format!("{error:?}: {error}").contains("secret"));
    }
}

#[cfg(test)]
#[path = "configured_url_parts_tests.rs"]
mod parts_tests;