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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
//! # HTTP-API-PROBLEM
//!
//! [![crates.io](https://img.shields.io/crates/v/http-api-problem.svg)](https://crates.io/crates/http-api-problem)
//! [![docs.rs](https://docs.rs/http-api-problem/badge.svg)](https://docs.rs/http-api-problem)
//! [![downloads](https://img.shields.io/crates/d/http-api-problem.svg)](https://crates.io/crates/http-api-problem)
//! ![CI](https://github.com/chridou/http-api-problem/workflows/CI/badge.svg)
//! [![license-mit](http://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/chridou/http-api-problem/blob/master/LICENSE-MIT)
//! [![license-apache](http://img.shields.io/badge/license-APACHE-blue.svg)](https://github.com/chridou/http-api-problem/blob/master/LICENSE-APACHE)
//!
//! A library to create HTTP response content for APIs based on
//! [RFC7807](https://tools.ietf.org/html/rfc7807).
//!
//! ** Breaking changes! This crate now uses `http::StatusCode` instead of the own custom one **
//!
//! ## Usage
//!
//! Get the latest version for your `Cargo.toml` from
//! [crates.io](https://crates.io/crates/http-api-problem).
//!
//! Add this to your crate root:
//!
//! ```rust
//! extern crate http_api_problem;
//! ```
//!
//!  ## serde
//!
//! `HttpApiProblem` implements `Serialize` and `Deserialize` for
//! `HttpApiProblem`.
//!
//! ## Examples
//!
//! ```rust
//! use http_api_problem::*;
//!
//! let p = HttpApiProblem::with_title_and_type_from_status(StatusCode::NOT_FOUND)
//!     .set_detail("detailed explanation")
//!     .set_instance("/on/1234/do/something");
//!
//! assert_eq!(Some("https://httpstatuses.com/404".to_string()), p.type_url);
//! assert_eq!(Some(StatusCode::NOT_FOUND), p.status);
//! assert_eq!("Not Found".to_string(), p.title);
//! assert_eq!(Some("detailed explanation".to_string()), p.detail);
//! assert_eq!(Some("/on/1234/do/something".to_string()), p.instance);
//! ```
//!
//! There is also `From<u16>` implemented for `StatusCode`:
//!
//! ```rust
//! use http_api_problem::*;
//!
//! let p = HttpApiProblem::with_title_and_type_from_status(StatusCode::PRECONDITION_REQUIRED)
//!     .set_detail("detailed explanation")
//!     .set_instance("/on/1234/do/something");
//!
//! assert_eq!(Some("https://httpstatuses.com/428".to_string()), p.type_url);
//! assert_eq!(Some(StatusCode::PRECONDITION_REQUIRED), p.status);
//! assert_eq!("Precondition Required".to_string(), p.title);
//! assert_eq!(Some("detailed explanation".to_string()), p.detail);
//! assert_eq!(Some("/on/1234/do/something".to_string()), p.instance);
//! ```
//!
//! ## License
//!
//! `http-api-problem` is primarily distributed under the terms of both the MIT
//! license and the Apache License (Version 2.0).
//!
//! Copyright (c) 2017 Christian Douven.
#[cfg(feature = "with-hyper")]
extern crate hyper;

use std::error::Error;

use std::fmt;

use serde::{de::DeserializeOwned, Deserialize, Serialize};
use std::collections::HashMap;

#[cfg(feature = "with-api-error")]
mod api_error;
#[cfg(feature = "with-api-error")]
pub use api_error::*;

pub use http::StatusCode;

/// The recommended media type when serialized to JSON
pub static PROBLEM_JSON_MEDIA_TYPE: &str = "application/problem+json";

/// Description of a problem that can be returned by an HTTP API
/// based on [RFC7807](https://tools.ietf.org/html/rfc7807)
///
/// # Example
///
/// ```javascript
/// {
///    "type": "https://example.com/probs/out-of-credit",
///    "title": "You do not have enough credit.",
///    "detail": "Your current balance is 30, but that costs 50.",
///    "instance": "/account/12345/msgs/abc",
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(test, derive(PartialEq))]
pub struct HttpApiProblem {
    /// A URI reference [RFC3986](https://tools.ietf.org/html/rfc3986) that identifies the
    /// problem type.  This specification encourages that, when
    /// dereferenced, it provide human-readable documentation for the
    /// problem type (e.g., using HTML [W3C.REC-html5-20141028]).  When
    /// this member is not present, its value is assumed to be
    /// "about:blank".
    #[serde(rename = "type")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub type_url: Option<String>,
    /// The HTTP status code [RFC7231, Section 6](https://tools.ietf.org/html/rfc7231#section-6)
    /// generated by the origin server for this occurrence of the problem.
    #[serde(default)]
    #[serde(with = "custom_http_status_serialization")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<StatusCode>,
    /// A short, human-readable summary of the problem
    /// type. It SHOULD NOT change from occurrence to occurrence of the
    /// problem, except for purposes of localization (e.g., using
    /// proactive content negotiation;
    /// see [RFC7231, Section 3.4](https://tools.ietf.org/html/rfc7231#section-3.4).
    ///
    /// This is the only mandatory field.
    #[serde(default)]
    pub title: String,
    /// A human-readable explanation specific to this
    /// occurrence of the problem.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
    /// A URI reference that identifies the specific
    /// occurrence of the problem.  It may or may not yield further
    /// information if dereferenced.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub instance: Option<String>,

    /// Additional fields that must be JSON values
    #[serde(flatten)]
    additional_fields: HashMap<String, serde_json::Value>,
}

impl HttpApiProblem {
    /// Creates a new instance with the given `title`.
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p = HttpApiProblem::new("Internal Error");
    ///
    /// assert_eq!(None, p.type_url);
    /// assert_eq!(None, p.status);
    /// assert_eq!("Internal Error", p.title);
    /// assert_eq!(None, p.detail);
    /// assert_eq!(None, p.instance);
    /// ```
    pub fn new<T: Into<String>>(title: T) -> HttpApiProblem {
        HttpApiProblem {
            type_url: None,
            status: None,
            title: title.into(),
            detail: None,
            instance: None,
            additional_fields: Default::default(),
        }
    }

    /// Creates a new instance with the `title` and `type_url` derived from the
    /// `status`.
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p = HttpApiProblem::with_title_and_type_from_status(StatusCode::SERVICE_UNAVAILABLE);
    ///
    /// assert_eq!(Some("https://httpstatuses.com/503".to_string()), p.type_url);
    /// assert_eq!(Some(StatusCode::SERVICE_UNAVAILABLE), p.status);
    /// assert_eq!("Service Unavailable", &p.title);
    /// assert_eq!(None, p.detail);
    /// assert_eq!(None, p.instance);
    /// ```
    pub fn with_title_and_type_from_status<T: Into<StatusCode>>(status: T) -> HttpApiProblem {
        let status = status.into();
        HttpApiProblem {
            type_url: Some(format!("https://httpstatuses.com/{}", status.as_u16())),
            status: Some(status),
            title: status
                .canonical_reason()
                .unwrap_or("<unknown status code>")
                .to_string(),
            detail: None,
            instance: None,
            additional_fields: Default::default(),
        }
    }

    /// Creates a new instance with `title` derived from `status`.
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p = HttpApiProblem::with_title_from_status(StatusCode::NOT_FOUND);
    ///
    /// assert_eq!(None, p.type_url);
    /// assert_eq!(Some(StatusCode::NOT_FOUND), p.status);
    /// assert_eq!("Not Found", p.title);
    /// assert_eq!(None, p.detail);
    /// assert_eq!(None, p.instance);
    /// ```
    pub fn with_title_from_status<T: Into<StatusCode>>(status: T) -> HttpApiProblem {
        let status = status.into();
        HttpApiProblem {
            type_url: None,
            status: Some(status),
            title: status
                .canonical_reason()
                .unwrap_or("<unknown status code>")
                .to_string(),
            detail: None,
            instance: None,
            additional_fields: Default::default(),
        }
    }

    /// Sets the `type_url`
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p = HttpApiProblem::new("Error").set_type_url("http://example.com/my/real_error");
    ///
    /// assert_eq!(Some("http://example.com/my/real_error".to_string()), p.type_url);
    /// assert_eq!(None, p.status);
    /// assert_eq!("Error", p.title);
    /// assert_eq!(None, p.detail);
    /// assert_eq!(None, p.instance);
    /// ```
    pub fn set_type_url<T: Into<String>>(self, type_url: T) -> HttpApiProblem {
        let mut s = self;
        s.type_url = Some(type_url.into());
        s
    }

    /// Sets the `status`
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p = HttpApiProblem::new("Error").set_status(StatusCode::NOT_FOUND);
    ///
    /// assert_eq!(None, p.type_url);
    /// assert_eq!(Some(StatusCode::NOT_FOUND), p.status);
    /// assert_eq!("Error", p.title);
    /// assert_eq!(None, p.detail);
    /// assert_eq!(None, p.instance);
    /// ```
    pub fn set_status<T: Into<StatusCode>>(self, status: T) -> HttpApiProblem {
        let status = status.into();
        let mut s = self;
        s.status = Some(status);
        s
    }

    /// Sets the `title`
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p = HttpApiProblem::new("Error").set_title("Another Error");
    ///
    /// assert_eq!(None, p.type_url);
    /// assert_eq!(None, p.status);
    /// assert_eq!("Another Error", p.title);
    /// assert_eq!(None, p.detail);
    /// assert_eq!(None, p.instance);
    /// ```
    pub fn set_title<T: Into<String>>(self, title: T) -> HttpApiProblem {
        let mut s = self;
        s.title = title.into();
        s
    }

    /// Sets the `detail`
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p = HttpApiProblem::new("Error").set_detail("a detailed description");
    ///
    /// assert_eq!(None, p.type_url);
    /// assert_eq!(None, p.status);
    /// assert_eq!("Error", p.title);
    /// assert_eq!(Some("a detailed description".to_string()), p.detail);
    /// assert_eq!(None, p.instance);
    /// ```
    pub fn set_detail<T: Into<String>>(self, detail: T) -> HttpApiProblem {
        let mut s = self;
        s.detail = Some(detail.into());
        s
    }

    /// Add a value that must be serializable. The key must not be one of the
    /// field names of this struct.
    pub fn set_value<K, V>(&mut self, key: K, value: &V) -> Result<(), String>
    where
        V: Serialize,
        K: Into<String>,
    {
        let key: String = key.into();
        match key.as_ref() {
            "type" => return Err("'type' is a reserved field name".into()),
            "status" => return Err("'status' is a reserved field name".into()),
            "title" => return Err("'title' is a reserved field name".into()),
            "detail" => return Err("'detail' is a reserved field name".into()),
            "instance" => return Err("'instance' is a reserved field name".into()),
            "additional_fields" => {
                return Err("'additional_fields' is a reserved field name".into());
            }
            _ => (),
        }
        let serialized = serde_json::to_value(value).map_err(|err| err.to_string())?;
        self.additional_fields.insert(key, serialized);
        Ok(())
    }

    /// Returns the deserialized field for the given key.
    ///
    /// If the key does not exist or the field is not deserializable to
    /// the target type `None` is returned
    pub fn value<K, V>(&self, key: &str) -> Option<V>
    where
        V: DeserializeOwned,
    {
        self.json_value(key)
            .and_then(|v| serde_json::from_value(v.clone()).ok())
    }

    /// Returns the `serde_json::Value` for the given key if the key exists.
    pub fn json_value(&self, key: &str) -> Option<&serde_json::Value> {
        self.additional_fields.get(key)
    }

    pub fn keys<K, V>(&self) -> impl Iterator<Item = &String>
    where
        V: DeserializeOwned,
    {
        self.additional_fields.keys()
    }

    /// Sets the `instance`
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p = HttpApiProblem::new("Error").set_instance("/account/1234/withdraw");
    ///
    /// assert_eq!(None, p.type_url);
    /// assert_eq!(None, p.status);
    /// assert_eq!("Error", p.title);
    /// assert_eq!(None, p.detail);
    /// assert_eq!(Some("/account/1234/withdraw".to_string()), p.instance);
    /// ```
    pub fn set_instance<T: Into<String>>(self, instance: T) -> HttpApiProblem {
        let mut s = self;
        s.instance = Some(instance.into());
        s
    }

    /// Serialize to a JSON `Vec<u8>`
    pub fn json_bytes(&self) -> Vec<u8> {
        serde_json::to_vec(self).unwrap()
    }

    /// Serialize to a JSON `String`
    pub fn json_string(&self) -> String {
        serde_json::to_string(self).unwrap()
    }

    pub fn status_or_internal_server_error(&self) -> StatusCode {
        self.status.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)
    }

    pub fn status_code_or_internal_server_error(&self) -> u16 {
        self.status_or_internal_server_error().as_u16()
    }

    /// Creates a `hyper` response.
    ///
    /// If status is `None` `500 - Internal Server Error` is the
    /// default.
    #[cfg(feature = "with-hyper")]
    pub fn to_hyper_response(&self) -> hyper::Response<hyper::Body> {
        use hyper::header::{HeaderValue, CONTENT_LENGTH, CONTENT_TYPE};
        use hyper::*;

        let json = self.json_bytes();
        let length = json.len() as u64;

        let (mut parts, body) = Response::new(json.into()).into_parts();

        parts.headers.insert(
            CONTENT_TYPE,
            HeaderValue::from_static(PROBLEM_JSON_MEDIA_TYPE),
        );
        parts.headers.insert(
            CONTENT_LENGTH,
            HeaderValue::from_str(&length.to_string()).unwrap(),
        );
        parts.status = self.status_or_internal_server_error();

        Response::from_parts(parts, body)
    }

    /// Creates an `actix` response.
    ///
    /// If status is `None` or not convertible
    /// to an actix status `500 - Internal Server Error` is the
    /// default.
    #[cfg(feature = "with-actix-web")]
    pub fn to_actix_response(&self) -> actix_web::HttpResponse {
        let effective_status = self.status_or_internal_server_error();
        let actix_status = actix_web::http::StatusCode::from_u16(effective_status.as_u16())
            .unwrap_or(actix_web::http::StatusCode::INTERNAL_SERVER_ERROR);

        let json = self.json_bytes();

        actix_web::HttpResponse::build(actix_status)
            .header(
                actix_web::http::header::CONTENT_TYPE,
                PROBLEM_JSON_MEDIA_TYPE,
            )
            .body(json)
    }
}

impl fmt::Display for HttpApiProblem {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(status) = self.status {
            write!(f, "{}", status)?;
        } else {
            write!(f, "<no status>")?;
        }

        if let Some(ref detail) = self.detail {
            write!(f, " - {}", detail)?;
        } else {
            write!(f, " - {}", self.title)?;
        }

        Ok(())
    }
}

impl Error for HttpApiProblem {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        None
    }
}

impl From<StatusCode> for HttpApiProblem {
    fn from(status: StatusCode) -> HttpApiProblem {
        HttpApiProblem::with_title_from_status(status)
    }
}

#[cfg(feature = "with-iron")]
impl From<HttpApiProblem> for ::iron::response::Response {
    fn from(problem: HttpApiProblem) -> ::iron::response::Response {
        problem.to_iron_response()
    }
}

/// Creates an `hyper::Response` from something that can become an
/// `HttpApiProblem`.
///
/// If status is `None` `500 - Internal Server Error` is the
/// default.
#[cfg(feature = "with-hyper")]
pub fn into_hyper_response<T: Into<HttpApiProblem>>(what: T) -> hyper::Response<hyper::Body> {
    let problem: HttpApiProblem = what.into();
    problem.to_hyper_response()
}

#[cfg(feature = "with-hyper")]
impl From<HttpApiProblem> for hyper::Response<hyper::Body> {
    fn from(problem: HttpApiProblem) -> hyper::Response<hyper::Body> {
        problem.to_hyper_response()
    }
}

// Creates an `actix::HttpResponse` from something that can become an
/// `HttpApiProblem`.
///
/// If status is `None` `500 - Internal Server Error` is the
/// default.
#[cfg(feature = "with-actix-web")]
pub fn into_actix_response<T: Into<HttpApiProblem>>(what: T) -> actix_web::HttpResponse {
    let problem: HttpApiProblem = what.into();
    problem.to_actix_response()
}

#[cfg(feature = "with-actix-web")]
impl From<HttpApiProblem> for actix_web::HttpResponse {
    fn from(problem: HttpApiProblem) -> actix_web::HttpResponse {
        problem.to_actix_response()
    }
}

#[cfg(feature = "with-warp")]
impl warp::reject::Reject for HttpApiProblem {}

mod custom_http_status_serialization {
    use http::StatusCode;
    use serde::{Deserialize, Deserializer, Serializer};
    use std::convert::TryFrom;

    pub fn serialize<S>(date: &Option<StatusCode>, s: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        if let Some(ref status_code) = *date {
            return s.serialize_u16(status_code.as_u16());
        }
        s.serialize_none()
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<StatusCode>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s: Option<u16> = Option::deserialize(deserializer)?;
        if let Some(numeric_status_code) = s {
            // If the status code numeral is invalid we simply have none...
            let status_code = StatusCode::try_from(numeric_status_code).ok();
            return Ok(status_code);
        }

        Ok(None)
    }
}

#[cfg(test)]
mod test;