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
use std::collections::HashMap;
use std::fmt;

use base64::Engine;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;

use crate::headers::util::split_key_value;
use autopush_common::util::{sec_since_epoch, ONE_DAY_IN_SECONDS};

pub const ALLOWED_SCHEMES: [&str; 3] = ["bearer", "webpush", "vapid"];

/*
The Assertion block for the VAPID header.

Please note: We require the `sub` claim in addition to the `exp` and `aud`.
See [HTTP Endpoints for Notficiations::Lexicon::{vapid_key}](https://mozilla-services.github.io/autopush-rs/http.html#lexicon-1)
for details.

 */
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
pub struct VapidClaims {
    pub exp: u64,
    pub aud: String,
    pub sub: String,
}

impl Default for VapidClaims {
    fn default() -> Self {
        Self {
            exp: VapidClaims::default_exp(),
            aud: "No audience".to_owned(),
            sub: "No sub".to_owned(),
        }
    }
}

impl VapidClaims {
    pub fn default_exp() -> u64 {
        sec_since_epoch() + ONE_DAY_IN_SECONDS
    }
}

impl fmt::Display for VapidClaims {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("VapidClaims")
            .field("exp", &self.exp)
            .field("aud", &self.aud)
            .field("sub", &self.sub)
            .finish()
    }
}

impl TryFrom<VapidHeader> for VapidClaims {
    type Error = VapidError;
    fn try_from(header: VapidHeader) -> Result<Self, Self::Error> {
        let b64_str = header
            .token
            .split('.')
            .nth(1)
            .ok_or(VapidError::InvalidVapid(header.token.to_string()))?;
        let value_str = String::from_utf8(
            base64::engine::general_purpose::URL_SAFE_NO_PAD
                .decode(b64_str)
                .map_err(|e| VapidError::InvalidVapid(e.to_string()))?,
        )
        .map_err(|e| VapidError::InvalidVapid(e.to_string()))?;
        serde_json::from_str::<VapidClaims>(&value_str)
            .map_err(|e| VapidError::InvalidVapid(e.to_string()))
    }
}

/// Parses the VAPID authorization header
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct VapidHeader {
    pub scheme: String,
    pub token: String,
    pub version_data: VapidVersionData,
}

/// Combines the VAPID header details with the public key, which may not be from
/// the VAPID header
#[derive(Clone, Debug)]
pub struct VapidHeaderWithKey {
    pub vapid: VapidHeader,
    pub public_key: String,
}

/// Version-specific VAPID data. Also used to identify the VAPID version.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum VapidVersionData {
    Version1,
    Version2 { public_key: String },
}

impl VapidHeader {
    /// Parse the VAPID authorization header. The public key is available if the
    /// version is 2 ("vapid" scheme).
    pub fn parse(header: &str) -> Result<VapidHeader, VapidError> {
        let mut scheme_split = header.splitn(2, ' ');
        let scheme = scheme_split
            .next()
            .ok_or(VapidError::MissingToken)?
            .to_lowercase();
        let data = scheme_split
            .next()
            .ok_or(VapidError::MissingToken)?
            .replace(' ', "");

        if !ALLOWED_SCHEMES.contains(&scheme.as_str()) {
            return Err(VapidError::UnknownScheme);
        }

        let (token, version_data) = if scheme == "vapid" {
            let data: HashMap<&str, &str> = data.split(',').filter_map(split_key_value).collect();

            let public_key = *data.get("k").ok_or(VapidError::MissingKey)?;
            let token = *data.get("t").ok_or(VapidError::MissingToken)?;

            (
                token.to_string(),
                VapidVersionData::Version2 {
                    public_key: public_key.to_string(),
                },
            )
        } else {
            (data, VapidVersionData::Version1)
        };

        Ok(Self {
            scheme,
            token,
            version_data,
        })
    }

    /// Get the VAPID version as a number
    pub fn version(&self) -> usize {
        match self.version_data {
            VapidVersionData::Version1 => 1,
            VapidVersionData::Version2 { .. } => 2,
        }
    }

    pub fn sub(&self) -> Result<String, VapidError> {
        let data: HashMap<String, Value> = serde_json::from_str(&self.token).map_err(|e| {
            warn!("🔐 Vapid: {:?}", e);
            VapidError::SubInvalid
        })?;

        if let Some(sub_candiate) = data.get("sub") {
            if let Some(sub) = sub_candiate.as_str() {
                if !sub.starts_with("mailto:") || !sub.starts_with("https://") {
                    info!("🔐 Vapid: Bad Format {:?}", sub);
                    return Err(VapidError::SubBadFormat);
                }
                if sub.is_empty() {
                    info!("🔐 Empty Vapid sub");
                    return Err(VapidError::SubEmpty);
                }
                info!("🔐 Vapid: sub: {:?}", sub);
                return Ok(sub.to_owned());
            }
        }
        Err(VapidError::SubMissing)
    }

    pub fn claims(&self) -> Result<VapidClaims, VapidError> {
        VapidClaims::try_from(self.clone())
    }
}

#[derive(Debug, Error, Eq, PartialEq)]
pub enum VapidError {
    #[error("Missing VAPID token")]
    MissingToken,
    #[error("Invalid VAPID token: {0}")]
    InvalidVapid(String),
    #[error("Missing VAPID public key")]
    MissingKey,
    #[error("Invalid VAPID public key: {0}")]
    InvalidKey(String),
    #[error("Invalid VAPID audience")]
    InvalidAudience,
    #[error("Invalid VAPID expiry")]
    InvalidExpiry,
    #[error("VAPID public key mismatch")]
    KeyMismatch,
    #[error("The VAPID token expiration is too long")]
    FutureExpirationToken,
    #[error("Unknown auth scheme")]
    UnknownScheme,
    #[error("Unparsable sub string")]
    SubInvalid,
    #[error("Improperly formatted sub string")]
    SubBadFormat,
    #[error("Empty sub string")]
    SubEmpty,
    #[error("Missing sub")]
    SubMissing,
}

impl VapidError {
    pub fn as_metric(&self) -> &str {
        match self {
            Self::MissingToken => "missing_token",
            Self::InvalidVapid(_) => "invalid_vapid",
            Self::MissingKey => "missing_key",
            Self::InvalidKey(_) => "invalid_key",
            Self::InvalidAudience => "invalid_audience",
            Self::InvalidExpiry => "invalid_expiry",
            Self::KeyMismatch => "key_mismatch",
            Self::FutureExpirationToken => "future_expiration_token",
            Self::UnknownScheme => "unknown_scheme",
            Self::SubInvalid => "invalid_sub",
            Self::SubBadFormat => "bad_format_sub",
            Self::SubEmpty => "empty_sub",
            Self::SubMissing => "missing_sub",
        }
    }
}

#[cfg(test)]
mod tests {

    use super::{VapidClaims, VapidHeader, VapidVersionData};

    // This was generated externally using the py_vapid package.
    const VALID_HEADER: &str = "vapid t=eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.ey\
        JhdWQiOiJodHRwczovL3B1c2guc2VydmljZXMubW96aWxsYS5jb20iLCJleHAiOjE3MTM1N\
        jQ4NzIsInN1YiI6Im1haWx0bzphZG1pbkBleGFtcGxlLmNvbSJ9.t7uOYm8nbqFkuNpDeln\
        -UeqSC58xu96Mc9tUVifQu1zAAndHYwvMd3-u--PuUo3S_VrqYXEaIlNIOOrGd3iUBA,k=B\
        LMymkOqvT6OZ1o9etCqV4jGPkvOXNz5FdBjsAR9zR5oeCV1x5CBKuSLTlHon-H_boHTzMtM\
        oNHsAGDlDB6X7vI";

    #[test]
    fn parse_succeeds() {
        // brain dead header parser.
        let mut parts = VALID_HEADER.split(' ').nth(1).unwrap().split(',');
        let token = parts.next().unwrap().split('=').nth(1).unwrap().to_string();
        let public_key = parts.next().unwrap().split('=').nth(1).unwrap().to_string();

        let expected_header = VapidHeader {
            scheme: "vapid".to_string(),
            token,
            version_data: VapidVersionData::Version2 { public_key },
        };

        let returned_header = VapidHeader::parse(VALID_HEADER);
        assert_eq!(returned_header, Ok(expected_header.clone()));

        assert_eq!(
            returned_header.unwrap().claims(),
            Ok(VapidClaims {
                exp: 1713564872,
                aud: "https://push.services.mozilla.com".to_string(),
                sub: "mailto:admin@example.com".to_string()
            })
        )
    }
}