webfinger-rs 0.0.33

WebFinger request and response types for Rust, with first-party Reqwest, Axum, and Actix Web integrations.
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
553
554
555
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::str::FromStr;

use http::Uri;

/// Errors that can occur while parsing a WebFinger resource URI.
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum ResourceError {
    /// The resource is a relative reference instead of an absolute URI.
    #[error("resource must be an absolute URI")]
    RelativeReference,

    /// The resource contains raw text outside the URI character set.
    ///
    /// Resource URI text must be ASCII and every byte must be allowed by RFC 3986 as an
    /// `unreserved`, `reserved`, or percent-escape marker byte. Characters outside that set, such
    /// as `{`, `|`, `^`, and non-ASCII code points, must be percent-encoded before parsing.
    #[error("resource contains invalid URI characters")]
    InvalidCharacters,

    /// The resource contains a malformed percent escape.
    #[error("resource contains invalid percent encoding")]
    InvalidPercentEncoding,

    /// The resource is an invalid HTTP or HTTPS URI.
    #[error(transparent)]
    InvalidHttpUri(#[from] http::uri::InvalidUri),

    /// The resource is an HTTP or HTTPS URI without an authority.
    #[error("HTTP and HTTPS resources must include an authority")]
    MissingHttpAuthority,
}

// `http::uri::InvalidUri` does not implement `PartialEq` or `Eq`, so this cannot be derived.
// See https://github.com/hyperium/http/issues/849.
impl PartialEq for ResourceError {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::RelativeReference, Self::RelativeReference)
            | (Self::InvalidCharacters, Self::InvalidCharacters)
            | (Self::InvalidPercentEncoding, Self::InvalidPercentEncoding)
            | (Self::MissingHttpAuthority, Self::MissingHttpAuthority) => true,
            (Self::InvalidHttpUri(left), Self::InvalidHttpUri(right)) => {
                left.to_string() == right.to_string()
            }
            _ => false,
        }
    }
}

impl Eq for ResourceError {}

/// A WebFinger resource URI.
///
/// RFC 7033 uses the `resource` query parameter for the query target, which is a URI rather than a
/// relative reference. `Resource` stores that URI text after checking the URI syntax that this crate
/// relies on at request boundaries.
///
/// Validation is intentionally conservative:
///
/// - the value must start with an RFC 3986 URI scheme;
/// - the value must contain only raw RFC 3986 URI characters;
/// - every `%` must start a complete percent escape;
/// - raw non-ASCII text must already be percent-encoded; and
/// - `http` and `https` resources must use the `//authority` form before their host is exposed
///   through [`Resource::host`].
///
/// Common valid resources include `acct:carol@example.com` and
/// `https://example.org/users/carol`.
///
/// # Examples
///
/// Parse a valid `acct:` resource:
///
/// ```rust
/// use webfinger_rs::Resource;
///
/// let resource = "acct:carol@example.com".parse::<Resource>()?;
/// assert_eq!(resource.as_str(), "acct:carol@example.com");
/// # Ok::<(), webfinger_rs::ResourceError>(())
/// ```
///
/// Raw characters outside the URI character set are rejected. Percent-encode them inside the
/// resource URI before putting that URI in the outer WebFinger query string:
///
/// ```rust
/// use webfinger_rs::{Resource, ResourceError};
///
/// let error = "acct:carol{admin}@example.com"
///     .parse::<Resource>()
///     .unwrap_err();
/// assert!(matches!(error, ResourceError::InvalidCharacters));
///
/// let resource = "acct:carol%7Badmin%7D@example.com".parse::<Resource>()?;
/// assert_eq!(resource.as_str(), "acct:carol%7Badmin%7D@example.com");
/// # Ok::<(), webfinger_rs::ResourceError>(())
/// ```
///
/// HTTP(S) resources must include an authority so host inference cannot treat opaque URI text as a
/// host:
///
/// ```rust
/// use webfinger_rs::{Resource, ResourceError};
///
/// let error = "https:example.org/profile"
///     .parse::<Resource>()
///     .unwrap_err();
/// assert!(matches!(error, ResourceError::MissingHttpAuthority));
///
/// let resource = "https://example.org/profile".parse::<Resource>()?;
/// assert_eq!(resource.host(), Some("example.org"));
/// # Ok::<(), webfinger_rs::ResourceError>(())
/// ```
///
/// See [RFC 7033 section 4.1] for the `resource` parameter, [RFC 3986 section 2.1] for percent
/// encoding, [RFC 3986 section 2.2] for reserved characters, [RFC 3986 section 2.3] for
/// unreserved characters, [RFC 3986 section 3.1] for URI schemes, and [RFC 3986 section 3.2] for
/// authority.
///
/// [RFC 7033 section 4.1]: https://www.rfc-editor.org/rfc/rfc7033.html#section-4.1
/// [RFC 3986 section 2.1]: https://www.rfc-editor.org/rfc/rfc3986.html#section-2.1
/// [RFC 3986 section 2.2]: https://www.rfc-editor.org/rfc/rfc3986.html#section-2.2
/// [RFC 3986 section 2.3]: https://www.rfc-editor.org/rfc/rfc3986.html#section-2.3
/// [RFC 3986 section 3.1]: https://www.rfc-editor.org/rfc/rfc3986.html#section-3.1
/// [RFC 3986 section 3.2]: https://www.rfc-editor.org/rfc/rfc3986.html#section-3.2
#[derive(Debug, Clone)]
pub struct Resource {
    text: String,
    host: Option<String>,
}

impl Resource {
    /// Returns the resource URI as a string slice.
    pub fn as_str(&self) -> &str {
        &self.text
    }

    /// Returns the resource as an [`http::Uri`] when it fits that representation.
    ///
    /// WebFinger resources can use schemes such as `acct:` that are valid URI strings but do not
    /// expose a host through [`http::Uri`]. This accessor is mainly useful for hierarchical
    /// resources such as `https://example.org/users/carol`.
    pub fn uri(&self) -> Option<Uri> {
        Uri::try_from(self.as_str()).ok()
    }

    /// Returns the host from the resource's [`http::Uri`] representation, when present.
    ///
    /// URI schemes such as `acct:` do not have a host in [`http::Uri`], so this returns `None` for
    /// those resources.
    pub fn host(&self) -> Option<&str> {
        self.host.as_deref()
    }
}

impl fmt::Display for Resource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.text)
    }
}

/// Resource identity is the URI text.
///
/// The `host` field is a construction-time cache derived from `text`, so including it here would
/// be redundant for `Resource` comparisons and incompatible with borrowed `str` lookup through
/// [`Borrow`].
impl PartialEq for Resource {
    fn eq(&self, other: &Self) -> bool {
        self.text == other.text
    }
}

/// Equality is complete when URI text matches.
///
/// `host` is derived from `text`, so it cannot distinguish two otherwise equal resources.
impl Eq for Resource {}

/// Partial ordering follows URI text only.
///
/// This keeps ordering consistent with equality and avoids treating the cached `host` as part of
/// resource identity.
impl PartialOrd for Resource {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

/// Ordering follows URI text only.
///
/// The cached `host` value is intentionally excluded so `Resource` sorts the same way as its
/// borrowed string form.
impl Ord for Resource {
    fn cmp(&self, other: &Self) -> Ordering {
        self.text.cmp(&other.text)
    }
}

/// Hashing uses URI text only.
///
/// This matches [`Borrow<str>`] lookup expectations for hash collections; hashing the cached
/// `host` would make `Resource` keys hash differently from their borrowed `str` form.
impl Hash for Resource {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.text.hash(state);
    }
}

impl AsRef<str> for Resource {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl Borrow<str> for Resource {
    fn borrow(&self) -> &str {
        self.as_str()
    }
}

impl FromStr for Resource {
    type Err = ResourceError;

    fn from_str(resource: &str) -> Result<Self, Self::Err> {
        let host = validate_resource(resource)?;
        Ok(Self {
            text: resource.to_string(),
            host,
        })
    }
}

impl TryFrom<String> for Resource {
    type Error = ResourceError;

    fn try_from(resource: String) -> Result<Self, Self::Error> {
        let host = validate_resource(&resource)?;
        Ok(Self {
            text: resource,
            host,
        })
    }
}

impl TryFrom<&str> for Resource {
    type Error = ResourceError;

    fn try_from(resource: &str) -> Result<Self, Self::Error> {
        resource.parse()
    }
}

fn validate_resource(resource: &str) -> Result<Option<String>, ResourceError> {
    let Some(scheme) = scheme(resource) else {
        return Err(ResourceError::RelativeReference);
    };
    if !resource.is_ascii() {
        return Err(ResourceError::InvalidCharacters);
    }
    validate_uri_characters(resource)?;
    validate_percent_escapes(resource)?;
    if scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https") {
        // WebFinger only needs host inference for hierarchical HTTP(S) resources. RFC 3986
        // section 3.2 attaches an authority to URIs that begin their hier-part with `//`; opaque
        // forms like `http:foo` must not produce a synthetic host.
        if !resource[scheme.len()..].starts_with("://") {
            return Err(ResourceError::MissingHttpAuthority);
        }
        let uri = Uri::try_from(resource).map_err(ResourceError::InvalidHttpUri)?;
        let Some(host) = uri.host() else {
            return Err(ResourceError::MissingHttpAuthority);
        };
        return Ok(Some(host.to_string()));
    }
    Ok(None)
}

fn validate_percent_escapes(resource: &str) -> Result<(), ResourceError> {
    let mut bytes = resource.as_bytes().iter();
    while let Some(byte) = bytes.next() {
        if *byte != b'%' {
            continue;
        }
        let Some(high) = bytes.next() else {
            return Err(ResourceError::InvalidPercentEncoding);
        };
        let Some(low) = bytes.next() else {
            return Err(ResourceError::InvalidPercentEncoding);
        };
        if !high.is_ascii_hexdigit() || !low.is_ascii_hexdigit() {
            return Err(ResourceError::InvalidPercentEncoding);
        }
    }
    Ok(())
}

fn validate_uri_characters(resource: &str) -> Result<(), ResourceError> {
    if resource.bytes().all(is_uri_character) {
        Ok(())
    } else {
        Err(ResourceError::InvalidCharacters)
    }
}

fn is_uri_character(byte: u8) -> bool {
    matches!(
        byte,
        b'A'..=b'Z'
            | b'a'..=b'z'
            | b'0'..=b'9'
            | b'-'
            | b'.'
            | b'_'
            | b'~'
            | b':'
            | b'/'
            | b'?'
            | b'#'
            | b'['
            | b']'
            | b'@'
            | b'!'
            | b'$'
            | b'&'
            | b'\''
            | b'('
            | b')'
            | b'*'
            | b'+'
            | b','
            | b';'
            | b'='
            | b'%'
    )
}

fn scheme(resource: &str) -> Option<&str> {
    let mut bytes = resource.bytes();
    let first = bytes.next()?;
    if !first.is_ascii_alphabetic() {
        return None;
    }

    for (index, byte) in bytes.enumerate() {
        match byte {
            b':' => return Some(&resource[..index + 1]),
            b'/' | b'?' | b'#' => return None,
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'+' | b'-' | b'.' => {}
            _ => return None,
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use std::collections::{HashMap, HashSet};

    use super::*;

    /// Accepts `acct:` resources because they are absolute URIs with a scheme.
    #[test]
    fn accepts_acct_resource() {
        let resource = "acct:carol@example.com".parse::<Resource>().unwrap();

        assert_eq!(resource.as_str(), "acct:carol@example.com");
    }

    /// Accepts hierarchical HTTPS resources with an authority.
    ///
    /// Host extraction is used by the CLI fallback path, so this test covers both the original
    /// resource text and the derived host/URI accessors.
    #[test]
    fn accepts_https_resource() {
        let resource = "https://example.org/users/carol"
            .parse::<Resource>()
            .unwrap();

        assert_eq!(resource.as_str(), "https://example.org/users/carol");
        assert_eq!(resource.host(), Some("example.org"));
        assert_eq!(
            resource.uri().map(|uri| uri.to_string()),
            Some("https://example.org/users/carol".to_string()),
        );
    }

    /// Resource identity is the resource URI text.
    ///
    /// Borrowed `str` lookup in hash collections must use the same equality and hash inputs as
    /// owned `Resource` values. This keeps `Borrow<str>` compatible with `Eq` and `Hash` even for
    /// hierarchical resources whose host is cached during construction.
    #[test]
    fn borrowed_str_lookup_uses_resource_text_identity() {
        let resource = "https://example.org/users/carol"
            .parse::<Resource>()
            .unwrap();
        let mut set = HashSet::new();
        set.insert(resource.clone());

        let mut map = HashMap::new();
        map.insert(resource, "profile");

        assert!(set.contains("https://example.org/users/carol"));
        assert_eq!(map.get("https://example.org/users/carol"), Some(&"profile"));
        assert!(!set.contains("https://example.org"));
        assert_eq!(map.get("https://example.org"), None);
    }

    /// Caches host text during construction without making host part of identity.
    #[test]
    fn caches_http_resource_host_at_construction() {
        for (resource, host) in [
            ("https://example.org/users/carol", "example.org"),
            ("https://example.org:8443/users/carol", "example.org"),
            ("https://user:pass@example.org/users/carol", "example.org"),
            ("https://[::1]:8443/users/carol", "[::1]"),
        ] {
            let resource = resource.parse::<Resource>().unwrap();

            assert_eq!(resource.host(), Some(host));
        }
    }

    /// Accepts owned resource text through the same validation path as parsed `&str` input.
    ///
    /// The owned conversion preserves the original text because downstream request encoding should
    /// not normalize or otherwise rewrite caller-provided resource URIs.
    #[test]
    fn try_from_string_preserves_resource_text() {
        let resource = Resource::try_from("acct:carol@example.com".to_string()).unwrap();

        assert_eq!(resource.as_str(), "acct:carol@example.com");
        assert_eq!(resource.to_string(), "acct:carol@example.com");
    }

    /// Accepts scheme-specific opaque-looking URIs.
    ///
    /// RFC 3986's `URI` production requires a scheme but allows a scheme-specific path without an
    /// authority. WebFinger commonly uses this shape for `acct:` resources.
    #[test]
    fn accepts_scheme_specific_resource() {
        let resource = "urn:example:animal:ferret:nose"
            .parse::<Resource>()
            .unwrap();

        assert_eq!(resource.as_str(), "urn:example:animal:ferret:nose");
    }

    /// Rejects relative references that `http::Uri` can otherwise parse.
    ///
    /// RFC 7033 section 4.1 defines `resource` as a URI identifying the target resource. RFC 3986
    /// section 4.2 relative references are not enough because they have no standalone scheme.
    ///
    /// See <https://www.rfc-editor.org/rfc/rfc7033.html#section-4.1>.
    /// See <https://www.rfc-editor.org/rfc/rfc3986.html#section-4.2>.
    #[test]
    fn rejects_relative_resource_references() {
        for resource in [
            "carol",
            "/relative",
            "?resource=acct:carol@example.com",
            "#fragment",
            "../x",
            "",
            "1acct:carol@example.com",
            "ac_ct:carol@example.org",
        ] {
            let error = resource.parse::<Resource>().unwrap_err();

            assert_eq!(error, ResourceError::RelativeReference);
        }
    }

    /// Rejects raw non-ASCII resource text.
    ///
    /// RFC 3986 URI syntax is ASCII. Non-ASCII data must be percent-encoded inside the resource URI
    /// itself before it is put into the WebFinger query parameter.
    #[test]
    fn rejects_non_ascii_resource_text() {
        let error = "acct:carolé@example.org".parse::<Resource>().unwrap_err();

        assert_eq!(error, ResourceError::InvalidCharacters);
    }

    /// Rejects raw ASCII characters outside the RFC 3986 URI character set.
    #[test]
    fn rejects_invalid_raw_uri_characters() {
        for resource in [
            "acct:carol{bad}@example.org",
            "acct:carol|bad@example.org",
            "acct:carol^bad@example.org",
            "acct:carol`bad@example.org",
        ] {
            let error = resource.parse::<Resource>().unwrap_err();

            assert_eq!(error, ResourceError::InvalidCharacters);
        }
    }

    /// Accepts characters outside the raw URI character set when they are percent-encoded.
    #[test]
    fn accepts_percent_encoded_invalid_raw_characters() {
        let resource = "acct:carol%7Bbad%7D@example.org"
            .parse::<Resource>()
            .unwrap();

        assert_eq!(resource.as_str(), "acct:carol%7Bbad%7D@example.org");
    }

    /// Rejects malformed percent escape syntax inside resource URIs.
    ///
    /// Percent escapes belong to the resource URI itself after the outer WebFinger query has been
    /// decoded, so malformed escapes must be rejected at the resource boundary too.
    #[test]
    fn rejects_malformed_resource_percent_escape() {
        for resource in [
            "acct:carol%GG@example.org",
            "acct:carol%@example.org",
            "acct:carol%4@example.org",
        ] {
            let error = resource.parse::<Resource>().unwrap_err();

            assert_eq!(error, ResourceError::InvalidPercentEncoding);
        }
    }

    /// Rejects HTTP and HTTPS resources that omit the required authority.
    #[test]
    fn rejects_http_resources_without_authority() {
        for resource in ["http:foo", "https:foo", "http:/example.org/path"] {
            let error = resource.parse::<Resource>().unwrap_err();

            assert_eq!(error, ResourceError::MissingHttpAuthority);
        }
    }

    /// Validates HTTP and HTTPS resource authorities regardless of scheme case.
    ///
    /// URI schemes are case-insensitive, so uppercase `HTTPS` should not bypass the stricter
    /// hierarchical URI validation used for HTTP resources.
    #[test]
    fn rejects_invalid_https_authority_with_uppercase_scheme() {
        for resource in ["HTTPS://[::1", "https:///profile"] {
            let error = resource.parse::<Resource>().unwrap_err();

            assert!(
                matches!(error, ResourceError::InvalidHttpUri(_)),
                "expected invalid-authority error for {resource:?}, got {error:?}",
            );
        }
    }
}