Skip to main content

gcloud_sdk/
error.rs

1use std::{convert::From, fmt};
2
3/// Represents the details of the [`Error`](struct.Error.html)
4#[derive(Debug)]
5#[non_exhaustive]
6pub enum ErrorKind {
7    /// Errors that can possibly occur while accessing an HTTP server.
8    Http(reqwest::Error),
9    /// An HTTP status other than 2xx.
10    HttpStatus(reqwest::StatusCode),
11    /// Credentials could not be built: no Application Default Credentials were found, or a
12    /// credentials file is malformed or of a type the token cannot be minted from.
13    CredentialsBuild(google_cloud_auth::build_errors::Error),
14    /// Credentials failed to produce a token: a token endpoint refused them or could not be
15    /// reached. [`CredentialsError::is_transient`](google_cloud_auth::errors::CredentialsError::is_transient)
16    /// says whether a retry may succeed.
17    Credentials(google_cloud_auth::errors::CredentialsError),
18    TonicMetadata(tonic::metadata::errors::InvalidMetadataValue),
19    GrpcStatus(tonic::transport::Error),
20    UrlError(hyper::http::uri::InvalidUri),
21    /// An API URL that parses but cannot be connected to: no scheme, a scheme
22    /// other than `http` or `https`, or no host.
23    InvalidApiUrl(String),
24    /// A header value built from user input (user agent, headers, the token itself)
25    /// failed HTTP header validation (e.g. contained a control character).
26    HeaderValue(hyper::header::InvalidHeaderValue),
27    /// The Application Default Credentials hold no service account to mint an ID token
28    /// as. An ID token needs a service account to impersonate, given to
29    /// [`GoogleAuthHeaders::id_token_impersonating`](crate::GoogleAuthHeaders::id_token_impersonating).
30    IdTokenNeedsImpersonation(IdTokenUnsupportedCredentials),
31    /// A `service_account_impersonation_url` in a credentials file that names no
32    /// service account.
33    InvalidImpersonationUrl(String),
34    /// The credentials sign with a private key of their own, such as a service account key
35    /// file as the Application Default Credentials or the key given to
36    /// [`GoogleAuthHeaders::from_service_account_key`](crate::GoogleAuthHeaders::from_service_account_key),
37    /// and no rustls
38    /// [`CryptoProvider`](rustls::crypto::CryptoProvider) is installed to sign with.
39    ///
40    /// Only reported when the `auth-default-crypto` feature is off. Install a provider
41    /// with `CryptoProvider::install_default` before building a client, or enable that
42    /// feature.
43    CryptoProviderMissing,
44}
45
46/// Credentials that cannot mint an ID token without impersonating a service account
47/// (see [`ErrorKind::IdTokenNeedsImpersonation`]).
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49#[non_exhaustive]
50pub enum IdTokenUnsupportedCredentials {
51    /// `authorized_user` credentials, such as those `gcloud auth application-default login`
52    /// writes.
53    AuthorizedUser,
54    /// `external_account` credentials without a `service_account_impersonation_url`.
55    ExternalAccount,
56    /// `external_account_authorized_user` credentials, such as
57    /// `gcloud auth application-default login` writes for a workforce identity
58    /// federation user.
59    ExternalAccountAuthorizedUser,
60    /// `gdch_service_account` credentials of Google Distributed Cloud Hosted.
61    GdchServiceAccount,
62}
63
64impl fmt::Display for IdTokenUnsupportedCredentials {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        match self {
67            Self::AuthorizedUser => write!(f, "authorized_user credentials"),
68            Self::ExternalAccount => write!(
69                f,
70                "external_account credentials without service_account_impersonation_url"
71            ),
72            Self::ExternalAccountAuthorizedUser => {
73                write!(f, "external_account_authorized_user credentials")
74            }
75            Self::GdchServiceAccount => write!(f, "gdch_service_account credentials"),
76        }
77    }
78}
79
80/// Represents errors that can occur during getting token.
81#[derive(Debug)]
82pub struct Error(Box<ErrorKind>);
83
84impl Error {
85    /// Borrow [`ErrorKind`](enum.ErrorKind.html).
86    pub fn kind(&self) -> &ErrorKind {
87        &self.0
88    }
89
90    /// To own [`ErrorKind`](enum.ErrorKind.html).
91    pub fn into_kind(self) -> ErrorKind {
92        *self.0
93    }
94}
95
96impl fmt::Display for Error {
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        use ErrorKind::*;
99        match *self.0 {
100            Http(ref e) => write!(f, "http error: {}", e),
101            HttpStatus(ref s) => write!(f, "http status error: {}", s),
102            CredentialsBuild(ref e) => write!(f, "credentials build error: {}", e),
103            Credentials(ref e) => write!(f, "credentials error: {}", e),
104            GrpcStatus(ref e) => write!(f, "Tonic/gRPC error: {}", e),
105            TonicMetadata(ref e) => write!(f, "Tonic metadata error: {}", e),
106            UrlError(ref e) => write!(f, "Url error: {}", e),
107            InvalidApiUrl(ref e) => write!(f, "Invalid API URL: {}", e),
108            HeaderValue(ref e) => write!(f, "invalid header value: {}", e),
109            IdTokenNeedsImpersonation(ref credentials) => write!(
110                f,
111                "{} cannot mint an ID token; give a service account to impersonate",
112                credentials
113            ),
114            InvalidImpersonationUrl(ref url) => write!(
115                f,
116                "service_account_impersonation_url names no service account: {}",
117                url
118            ),
119            CryptoProviderMissing => write!(
120                f,
121                "the credentials sign with a private key and no rustls CryptoProvider is installed; \
122                 install one with CryptoProvider::install_default or enable the auth-default-crypto feature"
123            ),
124        }
125    }
126}
127
128impl std::error::Error for Error {}
129
130impl From<reqwest::Error> for Error {
131    fn from(e: reqwest::Error) -> Self {
132        ErrorKind::Http(e).into()
133    }
134}
135
136impl From<google_cloud_auth::build_errors::Error> for Error {
137    fn from(e: google_cloud_auth::build_errors::Error) -> Self {
138        ErrorKind::CredentialsBuild(e).into()
139    }
140}
141
142impl From<google_cloud_auth::errors::CredentialsError> for Error {
143    fn from(e: google_cloud_auth::errors::CredentialsError) -> Self {
144        ErrorKind::Credentials(e).into()
145    }
146}
147
148impl From<ErrorKind> for Error {
149    fn from(k: ErrorKind) -> Self {
150        Error(Box::new(k))
151    }
152}
153
154impl From<tonic::transport::Error> for Error {
155    fn from(e: tonic::transport::Error) -> Self {
156        ErrorKind::GrpcStatus(e).into()
157    }
158}
159
160impl From<tonic::metadata::errors::InvalidMetadataValue> for Error {
161    fn from(e: tonic::metadata::errors::InvalidMetadataValue) -> Self {
162        ErrorKind::TonicMetadata(e).into()
163    }
164}
165
166impl From<hyper::http::uri::InvalidUri> for Error {
167    fn from(e: hyper::http::uri::InvalidUri) -> Self {
168        ErrorKind::UrlError(e).into()
169    }
170}
171
172impl From<hyper::header::InvalidHeaderValue> for Error {
173    fn from(e: hyper::header::InvalidHeaderValue) -> Self {
174        ErrorKind::HeaderValue(e).into()
175    }
176}
177
178/// Wrapper for the `Result` type with an [`Error`](struct.Error.html).
179pub type Result<T> = std::result::Result<T, Error>;