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
// -*- coding: utf-8 -*-
// ------------------------------------------------------------------------------------------------
// Copyright © 2019, rs-reporting-api authors.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied.  See the License for the specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------------------------------------

//! This crate provides some useful Rust code for working with the [Reporting API][reporting] and
//! [Network Error Logging][nel] W3C draft specifications.
//!
//! [reporting]: https://w3c.github.io/reporting/
//! [nel]: https://w3c.github.io/network-error-logging/

use std::time::Duration;

use serde::Deserialize;
use serde::Serialize;

/// Represents a single report uploaded via the Reporting API.
#[derive(Deserialize, Serialize)]
pub struct Report {
    /// The amount of time between when the report was generated by the user agent and when it was
    /// uploaded.
    #[serde(with = "parse_milliseconds")]
    pub age: Duration,
    /// The URL of the request that this report describes.
    pub url: String,
    /// The value of the `User-Agent` header of the request that this report describes.
    pub user_agent: String,
    /// The body of the report.
    #[serde(flatten)]
    pub body: Box<dyn ReportBody>,
}

/// Each kind of report that can be delivered via the Reporting API will have its own type, which
/// implements this trait.
#[typetag::serde(tag = "type", content = "body")]
pub trait ReportBody {}

/// A single Network Error Logging report.
#[derive(Deserialize, Serialize)]
pub struct NELReport {
    /// The referrer information for the request, as determined by the referrer policy associated
    /// with its client.
    pub referrer: String,
    /// The sampling rate that was in effect for this request, expressed as a frcation between 0.0
    /// and 1.0 (inclusive).
    pub sampling_fraction: f32,
    /// The IP address of the host to which the user agent sent the request.
    pub server_ip: String,
    /// The ALPN ID of the network protocol used to fetch the resource.
    pub protocol: String,
    /// The method of the HTTP request (e.g., `GET`, `POST`)
    pub method: String,
    /// The status code of the HTTP response, if available.
    pub status_code: Option<u16>,
    /// The elapsed time between the start of the resource fetch and when it was completed or
    /// aborted by the user agent.
    #[serde(with = "parse_opt_milliseconds")]
    pub elapsed_time: Option<Duration>,
    /// The phase of the request in which the failure occurred, if any.  One of `dns`,
    /// `connection`, or `application`.  A successful request always has a phase of `application`.
    pub phase: String,
    /// The code describing the error that occurred, or `ok` if the request was successful.  See
    /// the NEL spec for the [authoritative
    /// list](https://w3c.github.io/network-error-logging/#predefined-network-error-types) of
    /// possible codes.
    #[serde(rename = "type")]
    pub status: String,
}

#[typetag::serde(name = "network-error")]
impl ReportBody for NELReport {}

/// A serde parsing module that can be used to parse durations expressed as an integer number of
/// milliseconds.
pub mod parse_milliseconds {
    use std::time::Duration;

    use serde::Deserialize;
    use serde::Deserializer;
    use serde::Serializer;

    pub fn serialize<S>(value: &Duration, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_u64(value.as_millis() as u64)
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Duration, D::Error>
    where
        D: Deserializer<'de>,
    {
        Ok(Duration::from_millis(u64::deserialize(deserializer)?))
    }
}

/// A serde parsing module that can be used to parse _optional_ durations expressed as an integer
/// number of milliseconds.
pub mod parse_opt_milliseconds {
    use std::time::Duration;

    use serde::Deserialize;
    use serde::Deserializer;
    use serde::Serializer;

    pub fn serialize<S>(value: &Option<Duration>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match value {
            Some(duration) => serializer.serialize_some(&(duration.as_millis() as u64)),
            None => serializer.serialize_none(),
        }
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Duration>, D::Error>
    where
        D: Deserializer<'de>,
    {
        Ok(Option::<u64>::deserialize(deserializer)?.map(|millis| Duration::from_millis(millis)))
    }
}

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

    use serde_json::json;

    #[test]
    fn cannot_parse_unknown_report_type() {
        let report_json = json!({
            "age": 500,
            "type": "unknown",
            "url": "https://example.com/about/",
            "user_agent": "Mozilla/5.0",
            "body": {},
        });
        assert!(serde_json::from_value::<Report>(report_json).is_err());
    }

    #[test]
    fn cannot_parse_missing_report_type() {
        let report_json = json!({
            "age": 500,
            "url": "https://example.com/about/",
            "user_agent": "Mozilla/5.0",
            "body": {},
        });
        assert!(serde_json::from_value::<Report>(report_json).is_err());
    }

    #[test]
    fn can_parse_nel_report() {
        let report_json = json!({
            "age": 500,
            "type": "network-error",
            "url": "https://example.com/about/",
            "user_agent": "Mozilla/5.0",
            "body": {
                "referrer": "https://example.com/",
                "sampling_fraction": 0.5,
                "server_ip": "203.0.113.75",
                "protocol": "h2",
                "method": "POST",
                "status_code": 200,
                "elapsed_time": 45,
                "phase":"application",
                "type": "ok"
            }
        });
        let report: Report =
            serde_json::from_value(report_json).expect("Should be able to parse JSON report");
        assert_eq!(report.age, Duration::from_millis(500));
        assert_eq!(report.url, "https://example.com/about/");
        assert_eq!(report.user_agent, "Mozilla/5.0");
    }
}