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
use crate::b64;
use crate::error::*;
use crate::mac::Mac;
use base64::Engine;
use std::fmt;
use std::str::FromStr;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

/// Representation of a Hawk `Authorization` header value (the part following "Hawk ").
///
/// Headers can be derived from strings using the `FromStr` trait, and formatted into a
/// string using the `fmt_header` method.
///
/// All fields are optional, although for specific purposes some fields must be present.
#[derive(Clone, PartialEq, Debug)]
pub struct Header {
    pub id: Option<String>,
    pub ts: Option<SystemTime>,
    pub nonce: Option<String>,
    pub mac: Option<Mac>,
    pub ext: Option<String>,
    pub hash: Option<Vec<u8>>,
    pub app: Option<String>,
    pub dlg: Option<String>,
}

impl Header {
    /// Create a new Header with the full set of Hawk fields.
    ///
    /// This is a low-level function. Headers are more often created from Requests or Responses.
    ///
    /// Note that none of the string-formatted header components can contain the character `\"`.
    pub fn new<S>(
        id: Option<S>,
        ts: Option<SystemTime>,
        nonce: Option<S>,
        mac: Option<Mac>,
        ext: Option<S>,
        hash: Option<Vec<u8>>,
        app: Option<S>,
        dlg: Option<S>,
    ) -> Result<Header>
    where
        S: Into<String>,
    {
        Ok(Header {
            id: Header::check_component(id)?,
            ts,
            nonce: Header::check_component(nonce)?,
            mac,
            ext: Header::check_component(ext)?,
            hash,
            app: Header::check_component(app)?,
            dlg: Header::check_component(dlg)?,
        })
    }

    /// Check a header component for validity.
    fn check_component<S>(value: Option<S>) -> Result<Option<String>>
    where
        S: Into<String>,
    {
        if let Some(value) = value {
            let value = value.into();
            if value.contains('\"') {
                return Err(Error::HeaderParseError(
                    "Hawk headers cannot contain `\\`".into(),
                ));
            }
            Ok(Some(value))
        } else {
            Ok(None)
        }
    }

    /// Format the header for transmission in an Authorization header, omitting the `"Hawk "`
    /// prefix.
    pub fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut sep = "";
        if let Some(ref id) = self.id {
            write!(f, "{sep}id=\"{id}\"")?;
            sep = ", ";
        }
        if let Some(ref ts) = self.ts {
            write!(
                f,
                "{}ts=\"{}\"",
                sep,
                ts.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs()
            )?;
            sep = ", ";
        }
        if let Some(ref nonce) = self.nonce {
            write!(f, "{sep}nonce=\"{nonce}\"")?;
            sep = ", ";
        }
        if let Some(ref mac) = self.mac {
            write!(f, "{}mac=\"{}\"", sep, b64::STANDARD_ENGINE.encode(mac))?;
            sep = ", ";
        }
        if let Some(ref ext) = self.ext {
            write!(f, "{sep}ext=\"{ext}\"")?;
            sep = ", ";
        }
        if let Some(ref hash) = self.hash {
            write!(f, "{}hash=\"{}\"", sep, b64::STANDARD_ENGINE.encode(hash))?;
            sep = ", ";
        }
        if let Some(ref app) = self.app {
            write!(f, "{sep}app=\"{app}\"")?;
            sep = ", ";
        }
        if let Some(ref dlg) = self.dlg {
            write!(f, "{sep}dlg=\"{dlg}\"")?;
        }
        Ok(())
    }
}

impl fmt::Display for Header {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.fmt_header(f)
    }
}

impl FromStr for Header {
    type Err = Error;
    fn from_str(s: &str) -> Result<Header> {
        let mut p = s;

        // Required attributes
        let mut id: Option<&str> = None;
        let mut ts: Option<SystemTime> = None;
        let mut nonce: Option<&str> = None;
        let mut mac: Option<Vec<u8>> = None;
        // Optional attributes
        let mut hash: Option<Vec<u8>> = None;
        let mut ext: Option<&str> = None;
        let mut app: Option<&str> = None;
        let mut dlg: Option<&str> = None;

        while !p.is_empty() {
            // Skip whitespace and commas used as separators
            p = p.trim_start_matches(|c| c == ',' || char::is_whitespace(c));
            // Find first '=' which delimits attribute name from value
            let assign_end = p
                .find('=')
                .ok_or_else(|| Error::HeaderParseError("Expected '='".into()))?;
            let attr = &p[..assign_end].trim();
            if p.len() < assign_end + 1 {
                return Err(Error::HeaderParseError(
                    "Missing right hand side of =".into(),
                ));
            }
            p = p[assign_end + 1..].trim_start();
            if !p.starts_with('\"') {
                return Err(Error::HeaderParseError("Expected opening quote".into()));
            }
            p = &p[1..];
            // We have poor RFC 7235 compliance here as we ought to support backslash
            // escaped characters, but hawk doesn't allow this we won't either.  All
            // strings must be surrounded by ".." and contain no such characters.
            let end = p.find('\"');
            let val_end =
                end.ok_or_else(|| Error::HeaderParseError("Expected closing quote".into()))?;
            let val = &p[..val_end];
            match *attr {
                "id" => id = Some(val),
                "ts" => {
                    let epoch = u64::from_str(val)
                        .map_err(|_| Error::HeaderParseError("Error parsing `ts` field".into()))?;
                    ts = Some(UNIX_EPOCH + Duration::new(epoch, 0));
                }
                "mac" => {
                    mac = Some(b64::STANDARD_ENGINE.decode(val).map_err(|_| {
                        Error::HeaderParseError("Error parsing `mac` field".into())
                    })?);
                }
                "nonce" => nonce = Some(val),
                "ext" => ext = Some(val),
                "hash" => {
                    hash = Some(b64::STANDARD_ENGINE.decode(val).map_err(|_| {
                        Error::HeaderParseError("Error parsing `hash` field".into())
                    })?);
                }
                "app" => app = Some(val),
                "dlg" => dlg = Some(val),
                _ => {
                    return Err(Error::HeaderParseError(format!(
                        "Invalid Hawk field {}",
                        *attr
                    )))
                }
            };
            // Break if we are at end of string, otherwise skip separator
            if p.len() < val_end + 1 {
                break;
            }
            p = p[val_end + 1..].trim_start();
        }

        Ok(Header {
            id: id.map(|id| id.to_string()),
            ts,
            nonce: nonce.map(|nonce| nonce.to_string()),
            mac: mac.map(Mac::from),
            ext: ext.map(|ext| ext.to_string()),
            hash,
            app: app.map(|app| app.to_string()),
            dlg: dlg.map(|dlg| dlg.to_string()),
        })
    }
}

#[cfg(test)]
mod test {
    use super::Header;
    use crate::mac::Mac;
    use std::str::FromStr;
    use std::time::{Duration, UNIX_EPOCH};

    #[test]
    fn illegal_id() {
        assert!(Header::new(
            Some("ab\"cdef"),
            Some(UNIX_EPOCH + Duration::new(1234, 0)),
            Some("nonce"),
            Some(Mac::from(vec![])),
            Some("ext"),
            None,
            None,
            None
        )
        .is_err());
    }

    #[test]
    fn illegal_nonce() {
        assert!(Header::new(
            Some("abcdef"),
            Some(UNIX_EPOCH + Duration::new(1234, 0)),
            Some("no\"nce"),
            Some(Mac::from(vec![])),
            Some("ext"),
            None,
            None,
            None
        )
        .is_err());
    }

    #[test]
    fn illegal_ext() {
        assert!(Header::new(
            Some("abcdef"),
            Some(UNIX_EPOCH + Duration::new(1234, 0)),
            Some("nonce"),
            Some(Mac::from(vec![])),
            Some("ex\"t"),
            None,
            None,
            None
        )
        .is_err());
    }

    #[test]
    fn illegal_app() {
        assert!(Header::new(
            Some("abcdef"),
            Some(UNIX_EPOCH + Duration::new(1234, 0)),
            Some("nonce"),
            Some(Mac::from(vec![])),
            None,
            None,
            Some("a\"pp"),
            None
        )
        .is_err());
    }

    #[test]
    fn illegal_dlg() {
        assert!(Header::new(
            Some("abcdef"),
            Some(UNIX_EPOCH + Duration::new(1234, 0)),
            Some("nonce"),
            Some(Mac::from(vec![])),
            None,
            None,
            None,
            Some("d\"lg")
        )
        .is_err());
    }

    #[test]
    fn from_str() {
        let s = Header::from_str(
            "id=\"dh37fgj492je\", ts=\"1353832234\", \
             nonce=\"j4h3g2\", ext=\"some-app-ext-data\", \
             mac=\"6R4rV5iE+NPoym+WwjeHzjAGXUtLNIxmo1vpMofpLAE=\", \
             hash=\"6R4rV5iE+NPoym+WwjeHzjAGXUtLNIxmo1vpMofpLAE=\", \
             app=\"my-app\", dlg=\"my-authority\"",
        )
        .unwrap();
        assert!(s.id == Some("dh37fgj492je".to_string()));
        assert!(s.ts == Some(UNIX_EPOCH + Duration::new(1353832234, 0)));
        assert!(s.nonce == Some("j4h3g2".to_string()));
        assert!(
            s.mac
                == Some(Mac::from(vec![
                    233, 30, 43, 87, 152, 132, 248, 211, 232, 202, 111, 150, 194, 55, 135, 206, 48,
                    6, 93, 75, 75, 52, 140, 102, 163, 91, 233, 50, 135, 233, 44, 1
                ]))
        );
        assert!(s.ext == Some("some-app-ext-data".to_string()));
        assert!(s.app == Some("my-app".to_string()));
        assert!(s.dlg == Some("my-authority".to_string()));
    }

    #[test]
    fn from_str_invalid_mac() {
        let r = Header::from_str(
            "id=\"dh37fgj492je\", ts=\"1353832234\", \
             nonce=\"j4h3g2\", ext=\"some-app-ext-data\", \
             mac=\"6!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!AE=\", \
             app=\"my-app\", dlg=\"my-authority\"",
        );
        assert!(r.is_err());
    }

    #[test]
    fn from_str_no_field() {
        let s = Header::from_str("").unwrap();
        assert!(s.id.is_none());
        assert!(s.ts.is_none());
        assert!(s.nonce.is_none());
        assert!(s.mac.is_none());
        assert!(s.ext.is_none());
        assert!(s.app.is_none());
        assert!(s.dlg.is_none());
    }

    #[test]
    fn from_str_few_field() {
        let s = Header::from_str(
            "id=\"xyz\", ts=\"1353832234\", \
             nonce=\"abc\", \
             mac=\"6R4rV5iE+NPoym+WwjeHzjAGXUtLNIxmo1vpMofpLAE=\"",
        )
        .unwrap();
        assert!(s.id == Some("xyz".to_string()));
        assert!(s.ts == Some(UNIX_EPOCH + Duration::new(1353832234, 0)));
        assert!(s.nonce == Some("abc".to_string()));
        assert!(
            s.mac
                == Some(Mac::from(vec![
                    233, 30, 43, 87, 152, 132, 248, 211, 232, 202, 111, 150, 194, 55, 135, 206, 48,
                    6, 93, 75, 75, 52, 140, 102, 163, 91, 233, 50, 135, 233, 44, 1
                ]))
        );
        assert!(s.ext.is_none());
        assert!(s.app.is_none());
        assert!(s.dlg.is_none());
    }

    #[test]
    fn from_str_messy() {
        let s = Header::from_str(
            ", id  =  \"dh37fgj492je\", ts=\"1353832234\", \
             nonce=\"j4h3g2\"  , , ext=\"some-app-ext-data\", \
             mac=\"6R4rV5iE+NPoym+WwjeHzjAGXUtLNIxmo1vpMofpLAE=\"",
        )
        .unwrap();
        assert!(s.id == Some("dh37fgj492je".to_string()));
        assert!(s.ts == Some(UNIX_EPOCH + Duration::new(1353832234, 0)));
        assert!(s.nonce == Some("j4h3g2".to_string()));
        assert!(
            s.mac
                == Some(Mac::from(vec![
                    233, 30, 43, 87, 152, 132, 248, 211, 232, 202, 111, 150, 194, 55, 135, 206, 48,
                    6, 93, 75, 75, 52, 140, 102, 163, 91, 233, 50, 135, 233, 44, 1
                ]))
        );
        assert!(s.ext == Some("some-app-ext-data".to_string()));
        assert!(s.app.is_none());
        assert!(s.dlg.is_none());
    }

    #[test]
    fn to_str_no_fields() {
        // must supply a type for S, since it is otherwise unused
        let s = Header::new::<String>(None, None, None, None, None, None, None, None).unwrap();
        let formatted = format!("{s}");
        println!("got: {formatted}");
        assert!(formatted.is_empty())
    }

    #[test]
    fn to_str_few_fields() {
        let s = Header::new(
            Some("dh37fgj492je"),
            Some(UNIX_EPOCH + Duration::new(1353832234, 0)),
            Some("j4h3g2"),
            Some(Mac::from(vec![
                8, 35, 182, 149, 42, 111, 33, 192, 19, 22, 94, 43, 118, 176, 65, 69, 86, 4, 156,
                184, 85, 107, 249, 242, 172, 200, 66, 209, 57, 63, 38, 83,
            ])),
            None,
            None,
            None,
            None,
        )
        .unwrap();
        let formatted = format!("{s}");
        println!("got: {formatted}");
        assert!(
            formatted
                == "id=\"dh37fgj492je\", ts=\"1353832234\", nonce=\"j4h3g2\", \
                    mac=\"CCO2lSpvIcATFl4rdrBBRVYEnLhVa/nyrMhC0Tk/JlM=\""
        )
    }

    #[test]
    fn to_str_maximal() {
        let s = Header::new(
            Some("dh37fgj492je"),
            Some(UNIX_EPOCH + Duration::new(1353832234, 0)),
            Some("j4h3g2"),
            Some(Mac::from(vec![
                8, 35, 182, 149, 42, 111, 33, 192, 19, 22, 94, 43, 118, 176, 65, 69, 86, 4, 156,
                184, 85, 107, 249, 242, 172, 200, 66, 209, 57, 63, 38, 83,
            ])),
            Some("my-ext-value"),
            Some(vec![1, 2, 3, 4]),
            Some("my-app"),
            Some("my-dlg"),
        )
        .unwrap();
        let formatted = format!("{s}");
        println!("got: {formatted}");
        assert!(
            formatted
                == "id=\"dh37fgj492je\", ts=\"1353832234\", nonce=\"j4h3g2\", \
                    mac=\"CCO2lSpvIcATFl4rdrBBRVYEnLhVa/nyrMhC0Tk/JlM=\", ext=\"my-ext-value\", \
                    hash=\"AQIDBA==\", app=\"my-app\", dlg=\"my-dlg\""
        )
    }

    #[test]
    fn round_trip() {
        let s = Header::new(
            Some("dh37fgj492je"),
            Some(UNIX_EPOCH + Duration::new(1353832234, 0)),
            Some("j4h3g2"),
            Some(Mac::from(vec![
                8, 35, 182, 149, 42, 111, 33, 192, 19, 22, 94, 43, 118, 176, 65, 69, 86, 4, 156,
                184, 85, 107, 249, 242, 172, 200, 66, 209, 57, 63, 38, 83,
            ])),
            Some("my-ext-value"),
            Some(vec![1, 2, 3, 4]),
            Some("my-app"),
            Some("my-dlg"),
        )
        .unwrap();
        let formatted = format!("{s}");
        println!("got: {s}");
        let s2 = Header::from_str(&formatted).unwrap();
        assert!(s2 == s);
    }
}