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
use crate::error::{ApiError, ApiErrorKind, ApiResult};
use crate::headers::crypto_key::CryptoKeyHeader;
use crate::headers::util::{get_header, get_owned_header};
use actix_web::HttpRequest;
use autopush_common::{util::InsertOpt, MAX_NOTIFICATION_TTL};
use lazy_static::lazy_static;
use regex::Regex;
use std::cmp::min;
use std::collections::HashMap;
use validator::Validate;
use validator_derive::Validate;

lazy_static! {
    static ref VALID_BASE64_URL: Regex = Regex::new(r"^[0-9A-Za-z\-_]+=*$").unwrap();
    static ref STRIP_PADDING: Regex =
        Regex::new(r"(?P<head>[0-9A-Za-z\-_]+)=+(?P<tail>[,;]|$)").unwrap();
}

/// Extractor and validator for notification headers
#[derive(Clone, Debug, Eq, PartialEq, Validate)]
pub struct NotificationHeaders {
    // TTL is a signed value so that validation can catch negative inputs
    #[validate(range(min = 0, message = "TTL must be greater than 0", code = "114"))]
    pub ttl: i64,

    #[validate(
        length(
            max = 32,
            message = "Topic must be no greater than 32 characters",
            code = "113"
        ),
        regex(
            path = *VALID_BASE64_URL,
            message = "Topic must be URL and Filename safe Base64 alphabet",
            code = "113"
        )
    )]
    pub topic: Option<String>,

    // These fields are validated separately, because the validation is complex
    // and based upon the content encoding
    pub encoding: Option<String>,
    pub encryption: Option<String>,
    pub encryption_key: Option<String>,
    pub crypto_key: Option<String>,
}

impl From<NotificationHeaders> for HashMap<String, String> {
    fn from(headers: NotificationHeaders) -> Self {
        let mut map = HashMap::new();

        map.insert_opt("encoding", headers.encoding);
        map.insert_opt("encryption", headers.encryption);
        map.insert_opt("encryption_key", headers.encryption_key);
        map.insert_opt("crypto_key", headers.crypto_key);

        map
    }
}

impl NotificationHeaders {
    /// Extract the notification headers from a request.
    /// This can not be implemented as a `FromRequest` impl because we need to
    /// know if the payload has data, without actually advancing the payload
    /// stream.
    pub fn from_request(req: &HttpRequest, has_data: bool) -> ApiResult<Self> {
        // Collect raw headers
        let ttl = get_header(req, "ttl")
            .and_then(|ttl| ttl.parse().ok())
            // Enforce a maximum TTL, but don't error
            // NOTE: In order to trap for negative TTLs, this should be a
            // signed value, otherwise we will error out with NO_TTL.
            .map(|ttl| min(ttl, MAX_NOTIFICATION_TTL as i64))
            .ok_or(ApiErrorKind::NoTTL)?;
        let topic = get_owned_header(req, "topic");

        let headers = if has_data {
            NotificationHeaders {
                ttl,
                topic,
                encoding: get_owned_header(req, "content-encoding"),
                encryption: get_owned_header(req, "encryption").map(Self::strip_header),
                encryption_key: get_owned_header(req, "encryption-key"),
                crypto_key: get_owned_header(req, "crypto-key").map(Self::strip_header),
            }
        } else {
            // Messages without a body shouldn't pass along unnecessary headers
            NotificationHeaders {
                ttl,
                topic,
                encoding: None,
                encryption: None,
                encryption_key: None,
                crypto_key: None,
            }
        };

        // Validate encryption if there is a message body
        if has_data {
            headers.validate_encryption()?;
        }

        // Validate the other headers
        match headers.validate() {
            Ok(_) => Ok(headers),
            Err(e) => Err(ApiError::from(e)),
        }
    }

    /// Remove Base64 padding and double-quotes
    fn strip_header(header: String) -> String {
        let header = header.replace('"', "");
        STRIP_PADDING.replace_all(&header, "$head$tail").to_string()
    }

    /// Validate the encryption headers according to the various WebPush
    /// standard versions
    fn validate_encryption(&self) -> ApiResult<()> {
        let encoding = self.encoding.as_deref().ok_or_else(|| {
            ApiErrorKind::InvalidEncryption("Missing Content-Encoding header".to_string())
        })?;

        match encoding {
            "aesgcm" => self.validate_encryption_04_rules()?,
            "aes128gcm" => self.validate_encryption_06_rules()?,
            _ => {
                return Err(ApiErrorKind::InvalidEncryption(
                    "Unknown Content-Encoding header".to_string(),
                )
                .into());
            }
        }

        Ok(())
    }

    /// Validates encryption headers according to
    /// draft-ietf-webpush-encryption-04
    fn validate_encryption_04_rules(&self) -> ApiResult<()> {
        Self::assert_base64_item_exists("Encryption", self.encryption.as_deref(), "salt")?;

        if self.encryption_key.is_some() {
            return Err(ApiErrorKind::InvalidEncryption(
                "Encryption-Key header is not valid for webpush draft 02 or later".to_string(),
            )
            .into());
        }

        if self.crypto_key.is_some() {
            Self::assert_base64_item_exists("Crypto-Key", self.crypto_key.as_deref(), "dh")?;
        }

        Ok(())
    }

    /// Validates encryption headers according to
    /// draft-ietf-httpbis-encryption-encoding-06
    /// (the encryption values are in the payload, so there shouldn't be any in
    /// the headers)
    fn validate_encryption_06_rules(&self) -> ApiResult<()> {
        Self::assert_not_exists("aes128gcm Encryption", self.encryption.as_deref(), "salt")?;
        Self::assert_not_exists("aes128gcm Crypto-Key", self.crypto_key.as_deref(), "dh")?;

        Ok(())
    }

    /// Assert that the given item exists in the header and is valid base64.
    fn assert_base64_item_exists(
        header_name: &str,
        header: Option<&str>,
        key: &str,
    ) -> ApiResult<()> {
        let header = header.ok_or_else(|| {
            ApiErrorKind::InvalidEncryption(format!("Missing {header_name} header"))
        })?;
        let header_data = CryptoKeyHeader::parse(header).ok_or_else(|| {
            ApiErrorKind::InvalidEncryption(format!("Invalid {header_name} header"))
        })?;
        let value = header_data.get_by_key(key).ok_or_else(|| {
            ApiErrorKind::InvalidEncryption(format!("Missing {key} value in {header_name} header"))
        })?;

        if !VALID_BASE64_URL.is_match(value) {
            return Err(ApiErrorKind::InvalidEncryption(format!(
                "Invalid {key} value in {header_name} header",
            ))
            .into());
        }

        Ok(())
    }

    /// Assert that the given key does not exist in the header.
    fn assert_not_exists(header_name: &str, header: Option<&str>, key: &str) -> ApiResult<()> {
        let header = match header {
            Some(header) => header,
            None => return Ok(()),
        };

        let header_data = CryptoKeyHeader::parse(header).ok_or_else(|| {
            ApiErrorKind::InvalidEncryption(format!("Invalid {header_name} header"))
        })?;

        if header_data.get_by_key(key).is_some() {
            return Err(ApiErrorKind::InvalidEncryption(format!(
                "Do not include '{key}' header in {header_name} header"
            ))
            .into());
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::NotificationHeaders;
    use crate::error::{ApiErrorKind, ApiResult};
    use actix_web::test::TestRequest;
    use autopush_common::MAX_NOTIFICATION_TTL;

    /// Assert that a result is a validation error and check its serialization
    /// against the JSON value.
    fn assert_validation_error(
        result: ApiResult<NotificationHeaders>,
        expected_json: serde_json::Value,
    ) {
        assert!(result.is_err());
        let errors = match result.unwrap_err().kind {
            ApiErrorKind::Validation(errors) => errors,
            _ => panic!("Expected a validation error"),
        };

        assert_eq!(serde_json::to_value(errors).unwrap(), expected_json);
    }

    /// Assert that a result is a specific encryption error
    fn assert_encryption_error(result: ApiResult<NotificationHeaders>, expected_error: &str) {
        assert!(result.is_err());
        let error = match result.unwrap_err().kind {
            ApiErrorKind::InvalidEncryption(error) => error,
            _ => panic!("Expected an encryption error"),
        };

        assert_eq!(error, expected_error);
    }

    /// A valid TTL results in no errors or adjustment
    #[test]
    fn valid_ttl() {
        let req = TestRequest::post()
            .insert_header(("TTL", "10"))
            .to_http_request();
        let result = NotificationHeaders::from_request(&req, false);

        assert!(result.is_ok());
        assert_eq!(result.unwrap().ttl, 10);
    }

    /// Negative TTL values are not allowed
    #[test]
    fn negative_ttl() {
        let req = TestRequest::post()
            .insert_header(("TTL", "-1"))
            .to_http_request();
        let result = NotificationHeaders::from_request(&req, false);
        assert_validation_error(
            result,
            serde_json::json!({
                "ttl": [{
                    "code": "114",
                    "message": "TTL must be greater than 0",
                    "params": {
                        "min": 0,
                        "value": -1
                    }
                }]
            }),
        );
    }

    /// TTL values above the max are silently reduced to the max
    #[test]
    fn maximum_ttl() {
        let req = TestRequest::post()
            .insert_header(("TTL", (MAX_NOTIFICATION_TTL + 1).to_string()))
            .to_http_request();
        let result = NotificationHeaders::from_request(&req, false);

        assert!(result.is_ok());
        assert_eq!(result.unwrap().ttl, MAX_NOTIFICATION_TTL as i64);
    }

    /// A valid topic results in no errors
    #[test]
    fn valid_topic() {
        let req = TestRequest::post()
            .insert_header(("TTL", "10"))
            .insert_header(("TOPIC", "a-test-topic-which-is-just-right"))
            .to_http_request();
        let result = NotificationHeaders::from_request(&req, false);

        assert!(result.is_ok());
        assert_eq!(
            result.unwrap().topic,
            Some("a-test-topic-which-is-just-right".to_string())
        );
    }

    /// Topic names which are too long return an error
    #[test]
    fn too_long_topic() {
        let req = TestRequest::post()
            .insert_header(("TTL", "10"))
            .insert_header(("TOPIC", "test-topic-which-is-too-long-1234"))
            .to_http_request();
        let result = NotificationHeaders::from_request(&req, false);

        assert_validation_error(
            result,
            serde_json::json!({
                "topic": [{
                    "code": "113",
                    "message": "Topic must be no greater than 32 characters",
                    "params": {
                        "max": 32,
                        "value": "test-topic-which-is-too-long-1234"
                    }
                }]
            }),
        );
    }

    /// If there is a payload, there must be a content encoding header
    #[test]
    fn payload_without_content_encoding() {
        let req = TestRequest::post()
            .insert_header(("TTL", "10"))
            .to_http_request();
        let result = NotificationHeaders::from_request(&req, true);

        assert_encryption_error(result, "Missing Content-Encoding header");
    }

    /// Valid 04 draft encryption passes validation
    #[test]
    fn valid_04_encryption() {
        let req = TestRequest::post()
            .insert_header(("TTL", "10"))
            .insert_header(("Content-Encoding", "aesgcm"))
            .insert_header(("Encryption", "salt=foo"))
            .insert_header(("Crypto-Key", "dh=bar"))
            .to_http_request();
        let result = NotificationHeaders::from_request(&req, true);

        assert!(result.is_ok());
        assert_eq!(
            result.unwrap(),
            NotificationHeaders {
                ttl: 10,
                topic: None,
                encoding: Some("aesgcm".to_string()),
                encryption: Some("salt=foo".to_string()),
                encryption_key: None,
                crypto_key: Some("dh=bar".to_string())
            }
        );
    }

    /// Valid 06 draft encryption passes validation
    #[test]
    fn valid_06_encryption() {
        let req = TestRequest::post()
            .insert_header(("TTL", "10"))
            .insert_header(("Content-Encoding", "aes128gcm"))
            .insert_header(("Encryption", "notsalt=foo"))
            .insert_header(("Crypto-Key", "notdh=bar"))
            .to_http_request();
        let result = NotificationHeaders::from_request(&req, true);

        assert!(result.is_ok());
        assert_eq!(
            result.unwrap(),
            NotificationHeaders {
                ttl: 10,
                topic: None,
                encoding: Some("aes128gcm".to_string()),
                encryption: Some("notsalt=foo".to_string()),
                encryption_key: None,
                crypto_key: Some("notdh=bar".to_string())
            }
        );
    }

    /// The encryption and crypto-key headers are stripped of Base64 padding and
    /// double-quotes.
    #[test]
    fn strip_headers() {
        let req = TestRequest::post()
            .insert_header(("TTL", "10"))
            .insert_header(("Content-Encoding", "aesgcm"))
            .insert_header(("Encryption", "salt=\"foo\""))
            .insert_header(("Crypto-Key", "keyid=\"p256dh\";dh=\"deadbeef==\""))
            .to_http_request();
        let result = NotificationHeaders::from_request(&req, true);

        assert!(result.is_ok());
        assert_eq!(
            result.unwrap(),
            NotificationHeaders {
                ttl: 10,
                topic: None,
                encoding: Some("aesgcm".to_string()),
                encryption: Some("salt=foo".to_string()),
                encryption_key: None,
                crypto_key: Some("keyid=p256dh;dh=deadbeef".to_string())
            }
        );
    }

    // TODO: Add negative test cases for encryption validation?
}