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
use std::borrow::Borrow;
use std::fmt;
use std::str::FromStr;

use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::Error;

/// A URI string used in a WebFinger JRD response.
///
/// RFC 7033 defines the JRD `subject`, `aliases`, link `href`, and property identifiers as URI
/// strings. This type keeps those fields distinct from free-form text and rejects relative URI
/// references when values are parsed from JSON or constructed with [`JrdUri::try_new`].
///
/// `JrdUri` serializes as a JSON string, implements [`AsRef<str>`] for borrowed access, and can be
/// converted back into a [`String`] when a caller needs owned text. Builder methods accept strings
/// for ergonomics, then store validated `JrdUri` values internally.
///
/// See [RFC 7033 section 4.4.1] for `subject`, [section 4.4.2] for `aliases`,
/// [section 4.4.3] for response properties, [section 4.4.4.3] for link `href`, and
/// [section 4.4.4.5] for link properties. Those sections rely on URI syntax from RFC 3986,
/// including [section 2.1] percent escapes and [section 4.3] absolute URIs.
///
/// # Examples
///
/// Fallible construction is useful when accepting input from users, configuration, or another
/// service:
///
/// ```rust
/// use webfinger_rs::JrdUri;
///
/// let subject = JrdUri::try_new("acct:carol@example.com")?;
/// assert_eq!(subject.as_ref(), "acct:carol@example.com");
/// # Ok::<(), webfinger_rs::Error>(())
/// ```
///
/// Relative references are rejected:
///
/// ```rust
/// use webfinger_rs::JrdUri;
///
/// assert!(JrdUri::try_new("/users/carol").is_err());
/// ```
///
/// [RFC 7033 section 4.4.1]: https://www.rfc-editor.org/rfc/rfc7033.html#section-4.4.1
/// [section 4.4.2]: https://www.rfc-editor.org/rfc/rfc7033.html#section-4.4.2
/// [section 4.4.3]: https://www.rfc-editor.org/rfc/rfc7033.html#section-4.4.3
/// [section 4.4.4.3]: https://www.rfc-editor.org/rfc/rfc7033.html#section-4.4.4.3
/// [section 4.4.4.5]: https://www.rfc-editor.org/rfc/rfc7033.html#section-4.4.4.5
/// [section 2.1]: https://www.rfc-editor.org/rfc/rfc3986.html#section-2.1
/// [section 4.3]: https://www.rfc-editor.org/rfc/rfc3986.html#section-4.3
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct JrdUri(String);

impl JrdUri {
    /// Creates a JRD URI.
    ///
    /// This constructor is intended for URI strings controlled by the application, such as
    /// constants and values already validated by routing or configuration code. Use
    /// [`JrdUri::try_new`] for fallible construction from external input.
    ///
    /// # Panics
    ///
    /// Panics if `uri` is not an absolute URI string. Use [`JrdUri::try_new`] when handling
    /// untrusted input.
    pub fn new<S: AsRef<str>>(uri: S) -> Self {
        Self::try_new(uri).expect("invalid WebFinger JRD URI")
    }

    /// Tries to create a JRD URI from an absolute URI string.
    ///
    /// The value is stored without normalization. This preserves the string that will be serialized
    /// into the JRD while still checking that callers did not pass relative references or ordinary
    /// labels by mistake.
    pub fn try_new<S: AsRef<str>>(uri: S) -> Result<Self, Error> {
        let uri = uri.as_ref();
        if is_absolute_uri(uri) {
            Ok(Self(uri.to_string()))
        } else {
            Err(Error::InvalidJrdUri(uri.to_string()))
        }
    }
}

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

impl fmt::Debug for JrdUri {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("JrdUri").field(&self.0).finish()
    }
}

impl FromStr for JrdUri {
    type Err = Error;

    fn from_str(uri: &str) -> Result<Self, Self::Err> {
        Self::try_new(uri)
    }
}

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

    fn try_from(uri: &str) -> Result<Self, Self::Error> {
        Self::try_new(uri)
    }
}

impl TryFrom<String> for JrdUri {
    type Error = Error;

    fn try_from(uri: String) -> Result<Self, Self::Error> {
        Self::try_new(uri)
    }
}

impl From<JrdUri> for String {
    fn from(uri: JrdUri) -> Self {
        uri.0
    }
}

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

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

impl Serialize for JrdUri {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.0)
    }
}

impl<'de> Deserialize<'de> for JrdUri {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_str(JrdUriVisitor)
    }
}

struct JrdUriVisitor;

impl Visitor<'_> for JrdUriVisitor {
    type Value = JrdUri;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("an absolute URI string")
    }

    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
    where
        E: de::Error,
    {
        JrdUri::try_new(value).map_err(E::custom)
    }
}

/// Returns whether `value` is an absolute URI string under the crate's JRD URI policy.
///
/// RFC 7033's JRD members call these values URI strings, not arbitrary text. This helper enforces
/// the pieces the crate relies on before storing a [`JrdUri`] or accepting a URI-valued [`Rel`]:
/// a valid RFC 3986 scheme, syntactically valid percent escapes, and successful parsing by
/// [`http::Uri`]. The explicit percent-escape check is necessary because `http::Uri` accepts
/// malformed escapes such as `%GG`, while RFC 3986 section 2.1 constrains percent encoding to `%`
/// followed by two hexadecimal digits.
///
/// [`Rel`]: crate::Rel
///
/// See [RFC 3986 section 2.1] for percent encoding, [section 3.1] for scheme syntax, and
/// [section 4.3] for absolute URI syntax.
///
/// [RFC 3986 section 2.1]: https://www.rfc-editor.org/rfc/rfc3986.html#section-2.1
/// [section 3.1]: https://www.rfc-editor.org/rfc/rfc3986.html#section-3.1
/// [section 4.3]: https://www.rfc-editor.org/rfc/rfc3986.html#section-4.3
pub(crate) fn is_absolute_uri(value: &str) -> bool {
    let Some((scheme, _rest)) = value.split_once(':') else {
        return false;
    };
    let has_scheme = is_uri_scheme(scheme);
    let has_valid_percent_encoding = has_valid_percent_escapes(value);
    let parses_as_uri = value.parse::<http::Uri>().is_ok();

    has_scheme && has_valid_percent_encoding && parses_as_uri
}

/// Returns whether every `%` starts a complete RFC 3986 percent escape.
///
/// RFC 3986 section 2.1 defines `pct-encoded` as `%` followed by exactly two hexadecimal digits.
/// Some URI parsers preserve malformed escapes as ordinary path text, so URI-valued WebFinger
/// fields need this check before accepting user or JSON input as validated URI text.
///
/// See [RFC 3986 section 2.1].
///
/// [RFC 3986 section 2.1]: https://www.rfc-editor.org/rfc/rfc3986.html#section-2.1
fn has_valid_percent_escapes(value: &str) -> bool {
    let mut bytes = value.as_bytes().iter();
    while let Some(byte) = bytes.next() {
        if *byte != b'%' {
            continue;
        }
        let Some(high) = bytes.next() else {
            return false;
        };
        let Some(low) = bytes.next() else {
            return false;
        };
        if !high.is_ascii_hexdigit() || !low.is_ascii_hexdigit() {
            return false;
        }
    }
    true
}

fn is_uri_scheme(scheme: &str) -> bool {
    let mut chars = scheme.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    first.is_ascii_alphabetic()
        && chars.all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '+' | '-' | '.'))
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;
    use std::fmt::{Debug, Display};
    use std::hash::Hash;

    use serde::{Deserialize, Serialize};

    use super::*;

    fn assert_common_traits<T>()
    where
        T: Clone
            + Debug
            + Display
            + Eq
            + Ord
            + Hash
            + Send
            + Sync
            + Serialize
            + for<'de> Deserialize<'de>,
    {
    }

    /// Locks the expected trait surface for a URI value type.
    ///
    /// `JrdUri` appears in maps, serialized JRDs, debug output, and public builders, so missing
    /// common traits would make otherwise ordinary caller code awkward.
    #[test]
    fn implements_applicable_common_traits() {
        assert_common_traits::<JrdUri>();
    }

    /// Accepts absolute URI strings, including non-hierarchical URI schemes.
    ///
    /// JRD fields may use `acct:` and other absolute URI schemes, not only URLs with hosts.
    #[test]
    fn accepts_absolute_uri_strings() {
        let uri = JrdUri::try_new("acct:carol@example.com").unwrap();

        assert_eq!(uri.as_ref(), "acct:carol@example.com");
    }

    /// Accepts borrowed URI text through the standard fallible conversion trait.
    ///
    /// Builder-like APIs can use `TryFrom<&str>` without depending on the inherent constructor.
    #[test]
    fn try_from_parses_valid_uri_strings() {
        let uri = JrdUri::try_from("acct:carol@example.com").unwrap();

        assert_eq!(uri.as_ref(), "acct:carol@example.com");
    }

    /// Accepts owned URI text through the same validation path as borrowed URI text.
    ///
    /// Builders often receive owned configuration strings, so `TryFrom<String>` should not drift
    /// from the `&str` implementation.
    #[test]
    fn try_from_string_parses_valid_uri_strings() {
        let uri = JrdUri::try_from("acct:carol@example.com".to_string()).unwrap();

        assert_eq!(uri.as_ref(), "acct:carol@example.com");
    }

    /// Parses and displays JRD URI values through the standard string traits.
    ///
    /// These impls are what callers get from `"..." .parse()` and `{uri}` formatting, so they
    /// should stay aligned with the explicit constructors.
    #[test]
    fn standard_string_traits_use_inner_uri_text() {
        let uri = "acct:carol@example.com".parse::<JrdUri>().unwrap();

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

    /// Converts back into owned text without normalizing the URI string.
    ///
    /// Serialized JRD values should preserve caller-provided URI text after validation.
    #[test]
    fn converts_back_into_owned_string() {
        let uri = JrdUri::new("acct:carol@example.com");

        assert_eq!(String::from(uri), "acct:carol@example.com");
    }

    /// Supports borrowed lookup in maps keyed by `JrdUri`.
    ///
    /// Property maps are keyed by URI values, and callers should not need to allocate a `JrdUri`
    /// just to look up a known property identifier.
    #[test]
    fn supports_borrowed_string_map_lookup() {
        let mut values = BTreeMap::new();
        values.insert(JrdUri::new("acct:carol@example.com"), "Carol");

        assert_eq!(values.get("acct:carol@example.com"), Some(&"Carol"));
    }

    /// Orders URI values by their serialized string form.
    ///
    /// This keeps map/set ordering deterministic and aligned with the text that appears in JSON.
    #[test]
    fn orders_by_uri_string() {
        let first = JrdUri::new("acct:alice@example.com");
        let second = JrdUri::new("acct:carol@example.com");

        assert!(first < second);
    }

    /// Rejects relative references before they can enter JRD URI-valued fields.
    ///
    /// RFC 7033's JRD URI members are absolute URI strings, so relative paths should fail at the
    /// value boundary rather than during later serialization.
    #[test]
    fn rejects_relative_uri_references() {
        let error = JrdUri::try_new("/profile/carol").expect_err("relative URI");

        assert!(error.to_string().contains("invalid JRD URI"));
    }

    /// Rejects text that does not start with an absolute URI scheme.
    ///
    /// RFC 7033 defines JRD URI-valued members as URI strings. RFC 3986 section 4.3 says an
    /// absolute URI begins with a scheme followed by `:`, so account-like display text must not be
    /// accepted as a JRD URI.
    ///
    /// See <https://www.rfc-editor.org/rfc/rfc7033.html#section-4.4>.
    /// See <https://www.rfc-editor.org/rfc/rfc3986.html#section-4.3>.
    #[test]
    fn rejects_non_uri_strings() {
        let error = JrdUri::try_new("carol@example.com").expect_err("non-URI string");

        assert!(error.to_string().contains("invalid JRD URI"));
    }

    /// Rejects malformed percent escapes in URI-valued fields.
    ///
    /// RFC 3986 percent escapes must be complete hexadecimal byte escapes; accepting malformed
    /// values would serialize invalid JRD URI strings.
    #[test]
    fn rejects_malformed_percent_escapes() {
        for uri in [
            "https://example.org/a%GG",
            "acct:carol%GG@example.com",
            "https://example.org/a%",
            "https://example.org/a%4",
        ] {
            let error = JrdUri::try_new(uri).expect_err("malformed percent escape");

            assert!(
                error.to_string().contains("invalid JRD URI"),
                "expected invalid JRD URI error for {uri:?}, got {error:?}",
            );
        }
    }

    /// Applies the same absolute-URI validation when deserializing JSON.
    ///
    /// This prevents inbound JRD documents from bypassing `JrdUri::try_new` by using Serde.
    #[test]
    fn deserialization_rejects_relative_uri_references() {
        let error =
            serde_json::from_str::<JrdUri>(r#""/profile/carol""#).expect_err("relative URI");

        assert!(error.to_string().contains("invalid JRD URI"));
    }

    /// Rejects non-string JSON before URI syntax validation.
    ///
    /// JRD URI fields are JSON strings, so this guards the Serde visitor's type expectation rather
    /// than the URI parser itself.
    #[test]
    fn deserialization_rejects_non_string_values() {
        let error = serde_json::from_str::<JrdUri>("42").expect_err("number");

        assert!(error.to_string().contains("absolute URI string"));
    }
}