liburlx 0.2.2

A memory-safe URL transfer library — idiomatic Rust reimplementation of libcurl
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
//! HTTP Digest authentication (RFC 7616).
//!
//! Implements the Digest access authentication scheme with support for
//! MD5 and SHA-256 algorithms, and `qop=auth` quality of protection.

use crate::error::Error;

/// A parsed Digest authentication challenge from a `WWW-Authenticate` header.
#[derive(Debug, Clone)]
pub struct DigestChallenge {
    /// The authentication realm.
    pub realm: String,
    /// The server-generated nonce.
    pub nonce: String,
    /// The quality of protection (typically "auth").
    pub qop: Option<String>,
    /// The hash algorithm ("MD5", "SHA-256", etc.).
    pub algorithm: DigestAlgorithm,
    /// The opaque string to echo back.
    pub opaque: Option<String>,
    /// Whether the nonce is stale (client should retry with new nonce).
    pub stale: bool,
    /// Whether the server explicitly specified an algorithm in the challenge.
    pub algorithm_specified: bool,
}

/// Supported Digest hash algorithms.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DigestAlgorithm {
    /// MD5 (RFC 2617 default).
    Md5,
    /// SHA-256 (RFC 7616).
    Sha256,
}

impl DigestAlgorithm {
    /// Compute the hash of the input bytes, returning a hex string.
    fn hash(self, input: &[u8]) -> String {
        use md5::Digest as _;

        match self {
            Self::Md5 => hex::encode(md5::Md5::digest(input)),
            Self::Sha256 => hex::encode(sha2::Sha256::digest(input)),
        }
    }
}

impl DigestChallenge {
    /// Parse a Digest challenge from a `WWW-Authenticate` header value.
    ///
    /// Expected format: `Digest realm="...", nonce="...", qop="auth", algorithm=MD5`
    ///
    /// # Errors
    ///
    /// Returns [`Error::Http`] if the header cannot be parsed.
    pub fn parse(header_value: &str) -> Result<Self, Error> {
        let stripped = header_value
            .strip_prefix("Digest")
            .or_else(|| header_value.strip_prefix("digest"))
            .ok_or_else(|| Error::Http("not a Digest challenge".to_string()))?
            .trim();

        let mut realm = None;
        let mut nonce = None;
        let mut qop = None;
        let mut algorithm = DigestAlgorithm::Md5; // Default per RFC
        let mut algorithm_specified = false;
        let mut opaque = None;
        let mut stale = false;

        for param in split_params(stripped) {
            let (key, value) = split_kv(param);
            let value = unquote(value);

            match key.to_lowercase().as_str() {
                "realm" => realm = Some(value),
                "nonce" => nonce = Some(value),
                "qop" => {
                    // qop can be a comma-separated list like "auth, auth-int".
                    // Select "auth" if available (test 388).
                    let selected = value
                        .split(',')
                        .map(str::trim)
                        .find(|q| q.eq_ignore_ascii_case("auth"))
                        .map(ToString::to_string)
                        .unwrap_or(value);
                    qop = Some(selected);
                }
                "algorithm" => {
                    algorithm_specified = true;
                    algorithm = match value.to_uppercase().as_str() {
                        "SHA-256" => DigestAlgorithm::Sha256,
                        _ => DigestAlgorithm::Md5,
                    };
                }
                "opaque" => opaque = Some(value),
                "stale" => stale = value.eq_ignore_ascii_case("true"),
                _ => {} // Ignore unknown parameters
            }
        }

        let realm =
            realm.ok_or_else(|| Error::Http("Digest challenge missing realm".to_string()))?;
        let nonce =
            nonce.ok_or_else(|| Error::Http("Digest challenge missing nonce".to_string()))?;

        Ok(Self { realm, nonce, qop, algorithm, opaque, stale, algorithm_specified })
    }

    /// Compute the Digest authorization header value.
    ///
    /// Implements the response computation per RFC 7616:
    /// - HA1 = H(username:realm:password)
    /// - HA2 = H(method:uri)
    /// - If qop=auth: response = H(HA1:nonce:nc:cnonce:qop:HA2)
    /// - Otherwise: response = H(HA1:nonce:HA2)
    #[must_use]
    pub fn respond(
        &self,
        username: &str,
        password: &str,
        method: &str,
        uri: &str,
        nc: u32,
        cnonce: &str,
    ) -> String {
        use std::fmt::Write as _;

        let ha1 = self
            .algorithm
            .hash(format!("{username}:{realm}:{password}", realm = self.realm).as_bytes());

        let ha2 = self.algorithm.hash(format!("{method}:{uri}").as_bytes());

        let response = if self.qop.is_some() {
            let nc_str = format!("{nc:08x}");
            self.algorithm.hash(
                format!("{ha1}:{nonce}:{nc_str}:{cnonce}:auth:{ha2}", nonce = self.nonce)
                    .as_bytes(),
            )
        } else {
            self.algorithm.hash(format!("{ha1}:{nonce}:{ha2}", nonce = self.nonce).as_bytes())
        };

        // Escape `\` and `"` in quoted-string values (RFC 7616 §3.4)
        let username_escaped = username.replace('\\', "\\\\").replace('"', "\\\"");
        let realm_escaped = self.realm.replace('\\', "\\\\").replace('"', "\\\"");
        let uri_escaped = uri.replace('"', "\\\"");
        let mut header = format!(
            "Digest username=\"{username_escaped}\", realm=\"{realm_escaped}\", nonce=\"{nonce}\", uri=\"{uri_escaped}\", response=\"{response}\"",
            nonce = self.nonce,
        );

        if self.qop.is_some() {
            let nc_str = format!("{nc:08x}");
            let _ = write!(header, ", qop=auth, nc={nc_str}, cnonce=\"{cnonce}\"");
        }

        if let Some(ref opaque) = self.opaque {
            let _ = write!(header, ", opaque=\"{opaque}\"");
        }

        if self.algorithm_specified {
            match self.algorithm {
                DigestAlgorithm::Sha256 => header.push_str(", algorithm=SHA-256"),
                DigestAlgorithm::Md5 => header.push_str(", algorithm=MD5"),
            }
        }

        header
    }
}

/// Generate a random client nonce (cnonce) as a hex string.
///
/// Uses a cryptographically secure random number generator to prevent
/// nonce prediction attacks in Digest authentication.
#[must_use]
pub fn generate_cnonce() -> String {
    use rand::Rng as _;
    let mut rng = rand::rng();
    let bytes: [u8; 16] = rng.random();
    hex::encode(bytes)
}

/// Split comma-separated parameters, respecting quoted strings with escaped quotes.
fn split_params(s: &str) -> Vec<&str> {
    let mut params = Vec::new();
    let mut start = 0;
    let mut in_quotes = false;
    let bytes = s.as_bytes();

    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'\\' if in_quotes => {
                i += 2; // Skip escaped character (e.g., \")
                continue;
            }
            b'"' => in_quotes = !in_quotes,
            b',' if !in_quotes => {
                let param = s[start..i].trim();
                if !param.is_empty() {
                    params.push(param);
                }
                start = i + 1;
            }
            _ => {}
        }
        i += 1;
    }

    let last = s[start..].trim();
    if !last.is_empty() {
        params.push(last);
    }

    params
}

/// Split a key=value pair.
fn split_kv(s: &str) -> (&str, &str) {
    if let Some((key, value)) = s.split_once('=') {
        (key.trim(), value.trim())
    } else {
        (s.trim(), "")
    }
}

/// Remove surrounding quotes from a value and unescape backslash-escaped chars.
fn unquote(s: &str) -> String {
    let inner = s.strip_prefix('"').and_then(|s| s.strip_suffix('"')).unwrap_or(s);
    // Unescape \" and \\ sequences (RFC 7616 §3.3)
    let mut result = String::with_capacity(inner.len());
    let mut chars = inner.chars();
    while let Some(c) = chars.next() {
        if c == '\\' {
            if let Some(next) = chars.next() {
                result.push(next);
            } else {
                result.push(c);
            }
        } else {
            result.push(c);
        }
    }
    result
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;

    #[test]
    fn parse_basic_digest_challenge() {
        let header = r#"Digest realm="test@example.com", nonce="abc123", qop="auth""#;
        let challenge = DigestChallenge::parse(header).unwrap();
        assert_eq!(challenge.realm, "test@example.com");
        assert_eq!(challenge.nonce, "abc123");
        assert_eq!(challenge.qop.as_deref(), Some("auth"));
        assert_eq!(challenge.algorithm, DigestAlgorithm::Md5);
        assert!(challenge.opaque.is_none());
        assert!(!challenge.stale);
    }

    #[test]
    fn parse_digest_challenge_with_sha256() {
        let header =
            r#"Digest realm="example", nonce="xyz", algorithm=SHA-256, opaque="opq", stale=true"#;
        let challenge = DigestChallenge::parse(header).unwrap();
        assert_eq!(challenge.realm, "example");
        assert_eq!(challenge.algorithm, DigestAlgorithm::Sha256);
        assert_eq!(challenge.opaque.as_deref(), Some("opq"));
        assert!(challenge.stale);
    }

    #[test]
    fn parse_digest_challenge_missing_realm() {
        let header = r#"Digest nonce="abc""#;
        assert!(DigestChallenge::parse(header).is_err());
    }

    #[test]
    fn parse_digest_challenge_missing_nonce() {
        let header = r#"Digest realm="test""#;
        assert!(DigestChallenge::parse(header).is_err());
    }

    #[test]
    fn parse_not_digest() {
        let header = "Basic realm=\"test\"";
        assert!(DigestChallenge::parse(header).is_err());
    }

    #[test]
    fn digest_response_md5_with_qop() {
        // RFC 2617 example values (adapted)
        let challenge = DigestChallenge {
            realm: "testrealm@host.com".to_string(),
            nonce: "dcd98b7102dd2f0e8b11d0f600bfb0c093".to_string(),
            qop: Some("auth".to_string()),
            algorithm: DigestAlgorithm::Md5,
            opaque: Some("5ccc069c403ebaf9f0171e9517f40e41".to_string()),
            stale: false,
            algorithm_specified: true,
        };

        let response =
            challenge.respond("Mufasa", "Circle Of Life", "GET", "/dir/index.html", 1, "0a4f113b");

        assert!(response.starts_with("Digest username=\"Mufasa\""));
        assert!(response.contains("realm=\"testrealm@host.com\""));
        assert!(response.contains("qop=auth"));
        assert!(response.contains("nc=00000001"));
        assert!(response.contains("cnonce=\"0a4f113b\""));
        assert!(response.contains("algorithm=MD5"));
        assert!(response.contains("opaque=\"5ccc069c403ebaf9f0171e9517f40e41\""));
        // Verify the response hash is computed correctly
        assert!(response.contains("response=\""));
    }

    #[test]
    fn digest_response_md5_rfc2617_example() {
        // Test against the well-known RFC 2617 example
        let challenge = DigestChallenge {
            realm: "testrealm@host.com".to_string(),
            nonce: "dcd98b7102dd2f0e8b11d0f600bfb0c093".to_string(),
            qop: Some("auth".to_string()),
            algorithm: DigestAlgorithm::Md5,
            opaque: None,
            stale: false,
            algorithm_specified: false,
        };

        let response =
            challenge.respond("Mufasa", "Circle Of Life", "GET", "/dir/index.html", 1, "0a4f113b");

        // HA1 = MD5("Mufasa:testrealm@host.com:Circle Of Life")
        //      = 939e7578ed9e3c518a452acee763bce9
        // HA2 = MD5("GET:/dir/index.html")
        //      = 39aff3a2bab6126f332b942af5e6afc3
        // response = MD5("939e7578ed9e3c518a452acee763bce9:dcd98b7102dd2f0e8b11d0f600bfb0c093:00000001:0a4f113b:auth:39aff3a2bab6126f332b942af5e6afc3")
        //          = 6629fae49393a05397450978507c4ef1
        assert!(response.contains("response=\"6629fae49393a05397450978507c4ef1\""));
    }

    #[test]
    fn digest_response_without_qop() {
        let challenge = DigestChallenge {
            realm: "test".to_string(),
            nonce: "nonce123".to_string(),
            qop: None,
            algorithm: DigestAlgorithm::Md5,
            opaque: None,
            stale: false,
            algorithm_specified: false,
        };

        let response = challenge.respond("user", "pass", "GET", "/", 1, "cnonce");

        assert!(!response.contains("qop="));
        assert!(!response.contains("nc="));
        assert!(!response.contains("cnonce="));
        assert!(response.contains("response=\""));
    }

    #[test]
    fn digest_response_sha256() {
        let challenge = DigestChallenge {
            realm: "test".to_string(),
            nonce: "nonce".to_string(),
            qop: Some("auth".to_string()),
            algorithm: DigestAlgorithm::Sha256,
            opaque: None,
            stale: false,
            algorithm_specified: true,
        };

        let response = challenge.respond("user", "pass", "GET", "/", 1, "cnonce");
        assert!(response.contains("algorithm=SHA-256"));
    }

    #[test]
    fn generate_cnonce_not_empty() {
        let cnonce = generate_cnonce();
        assert!(!cnonce.is_empty());
        assert!(cnonce.len() >= 16);
    }

    #[test]
    fn split_params_basic() {
        let params = split_params(r#"realm="test", nonce="abc""#);
        assert_eq!(params.len(), 2);
        assert_eq!(params[0], r#"realm="test""#);
        assert_eq!(params[1], r#"nonce="abc""#);
    }

    #[test]
    fn split_params_with_commas_in_quotes() {
        let params = split_params(r#"realm="a,b", nonce="c""#);
        assert_eq!(params.len(), 2);
        assert_eq!(params[0], r#"realm="a,b""#);
    }

    #[test]
    fn unquote_removes_quotes() {
        assert_eq!(unquote(r#""hello""#), "hello");
        assert_eq!(unquote("hello"), "hello");
        assert_eq!(unquote("\""), "\"");
    }

    #[test]
    fn unquote_escaped_quotes() {
        assert_eq!(unquote(r#""test \"this\" realm!!""#), r#"test "this" realm!!"#);
    }

    #[test]
    fn parse_multiple_qop_values() {
        let header = r#"Digest realm="test", nonce="abc", qop=" crazy, auth""#;
        let challenge = DigestChallenge::parse(header).unwrap();
        assert_eq!(challenge.qop.as_deref(), Some("auth"));
    }
}