gcp_sa/
error.rs

1#![warn(missing_docs)]
2
3//! Error struct for Google's authentication API JWT error messages
4
5use serde::Deserialize;
6use std::fmt;
7
8/// Variants of different error messages types that the API can return. These are [documented] at Google's API descriptions.
9///
10/// [documented]: https://developers.google.com/identity/protocols/oauth2/service-account#error-codes
11#[derive(PartialEq, Debug, Deserialize)]
12#[serde(rename_all = "snake_case")]
13pub enum GoogleJWTErrorType {
14    /// Client was unauthorized to perform the request
15    UnauthorizedClient,
16    /// Credentials provided do not have approriate permissions
17    AccessDenied,
18    /// Non valid grant was provided
19    InvalidGrant,
20    /// Invalid scope was provided
21    InvalidScope,
22    /// The OAuth client was disabled.
23    DisabledClient,
24}
25
26/// Google's authentication API error response
27#[derive(Debug, Deserialize)]
28pub struct GoogleJWTError {
29    error: GoogleJWTErrorType,
30    error_description: String,
31}
32
33impl fmt::Display for GoogleJWTError {
34    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
35        write!(f, "{}", self.error_description)
36    }
37}
38
39#[cfg(test)]
40mod tests {
41    use crate::error::{GoogleJWTError, GoogleJWTErrorType};
42
43    const ACCESSDENIED_MSG: &str = "This is a test error that simulates access denied condition.";
44
45    const ACCESSDENIED_JSON: &str = r#"
46        {
47            "error": "access_denied",
48            "error_description": "This is a test error that simulates access denied condition."
49        }
50    "#;
51
52    #[test]
53    fn test_accessdenied() {
54        let raised: Result<(), GoogleJWTError> = Err(GoogleJWTError {
55            error: GoogleJWTErrorType::AccessDenied,
56            error_description: ACCESSDENIED_MSG.to_string(),
57        });
58        assert_eq!(raised.is_err(), true);
59        match raised {
60            Ok(_) => {}
61            Err(error) => {
62                assert_eq!(error.error, GoogleJWTErrorType::AccessDenied);
63                assert_eq!(error.error_description, ACCESSDENIED_MSG);
64            }
65        };
66    }
67
68    #[test]
69    fn test_accessdenied_from_json() {
70        use serde_json::from_str;
71
72        let raised: Result<(), GoogleJWTError> = Err(from_str(&ACCESSDENIED_JSON).unwrap());
73        assert_eq!(raised.is_err(), true);
74        match raised {
75            Ok(_) => {}
76            Err(error) => {
77                assert_eq!(error.error, GoogleJWTErrorType::AccessDenied);
78                assert_eq!(error.error_description, ACCESSDENIED_MSG);
79            }
80        };
81    }
82}
83
84// eof