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
use super::TokenResponse;
use crate::{
    error::{self, Error},
    token::{RequestReason, Token, TokenOrRequest, TokenProvider},
    token_cache::CachedTokenProvider,
};

/// Provides tokens using
/// [default application credentials](https://cloud.google.com/sdk/gcloud/reference/auth/application-default)
/// Caches tokens internally.
pub type EndUserCredentials = CachedTokenProvider<EndUserCredentialsInner>;
impl EndUserCredentials {
    pub fn new(info: EndUserCredentialsInfo) -> Self {
        CachedTokenProvider::wrap(EndUserCredentialsInner::new(info))
    }
}

/// Provides tokens using
/// [default application credentials](https://cloud.google.com/sdk/gcloud/reference/auth/application-default)
#[derive(serde::Deserialize, Debug, Clone)]
pub struct EndUserCredentialsInfo {
    /// The OAuth2 client_id
    pub client_id: String,
    /// The OAuth2 client_secret
    pub client_secret: String,
    /// The OAuth2 refresh_token
    pub refresh_token: String,
    /// The client type (the value must be authorized_user)
    #[serde(rename = "type")]
    pub client_type: String,
}

impl EndUserCredentialsInfo {
    /// Deserializes the `EndUserCredentials` from a byte slice. This
    /// data is typically acquired by reading an
    /// `application_default_credentials.json` file from disk.
    pub fn deserialize<T>(key_data: T) -> Result<Self, Error>
    where
        T: AsRef<[u8]>,
    {
        let slice = key_data.as_ref();

        let account_info: Self = serde_json::from_slice(slice)?;
        Ok(account_info)
    }
}

pub struct EndUserCredentialsInner {
    info: EndUserCredentialsInfo,
}

impl EndUserCredentialsInner {
    pub fn new(info: EndUserCredentialsInfo) -> Self {
        Self { info }
    }
}

impl TokenProvider for EndUserCredentialsInner {
    fn get_token_with_subject<'a, S, I, T>(
        &self,
        subject: Option<T>,
        // EndUserCredentials only have the scopes they were granted
        // via their authorization. So whatever scopes you're asking
        // for, better have been handled when authorized. `gcloud auth
        // application-default login` will get the
        // https://www.googleapis.com/auth/cloud-platform which
        // includes all *GCP* APIs.
        _scopes: I,
    ) -> Result<TokenOrRequest, Error>
    where
        S: AsRef<str> + 'a,
        I: IntoIterator<Item = &'a S>,
        T: Into<String>,
    {
        // We can only support subject being none
        if subject.is_some() {
            return Err(Error::Auth(error::AuthError {
                error: Some("Unsupported".to_string()),
                error_description: Some(
                    "ADC / User tokens do not support jwt subjects".to_string(),
                ),
            }));
        }

        // To get an access token, we need to perform a refresh
        // following the instructions at
        // https://developers.google.com/identity/protocols/oauth2/web-server#offline
        // (i.e., POST our client data as a refresh_token request to
        // the /token endpoint).
        let url = "https://oauth2.googleapis.com/token";

        // Build up the parameters as a form encoded string.
        let body = url::form_urlencoded::Serializer::new(String::new())
            .append_pair("client_id", &self.info.client_id)
            .append_pair("client_secret", &self.info.client_secret)
            .append_pair("grant_type", "refresh_token")
            .append_pair("refresh_token", &self.info.refresh_token)
            .finish();

        let body = Vec::from(body);

        let request = http::Request::builder()
            .method("POST")
            .uri(url)
            .header(
                http::header::CONTENT_TYPE,
                "application/x-www-form-urlencoded",
            )
            .header(http::header::CONTENT_LENGTH, body.len())
            .body(body)?;

        Ok(TokenOrRequest::Request {
            request,
            reason: RequestReason::ScopesChanged,
            scope_hash: 0,
        })
    }

    fn parse_token_response<S>(
        &self,
        _hash: u64,
        response: http::Response<S>,
    ) -> Result<Token, Error>
    where
        S: AsRef<[u8]>,
    {
        let (parts, body) = response.into_parts();

        if !parts.status.is_success() {
            return Err(Error::HttpStatus(parts.status));
        }

        // Deserialize our response, or fail.
        let token_res: TokenResponse = serde_json::from_slice(body.as_ref())?;

        // TODO(boulos): The response also includes the set of scopes
        // (as "scope") that we're granted. We could check that
        // cloud-platform is in it.

        // Convert it into our output.
        let token: Token = token_res.into();
        Ok(token)
    }
}

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

    #[test]
    fn end_user_credentials() {
        let provider = EndUserCredentialsInner::new(EndUserCredentialsInfo {
            client_id: "fake_client@domain.com".into(),
            client_secret: "TOP_SECRET".into(),
            refresh_token: "REFRESH_TOKEN".into(),
            client_type: "authorized_user".into(),
        });

        // End-user credentials don't let you override scopes.
        let scopes = vec!["better_not_be_there"];

        let token_or_req = provider
            .get_token(&scopes)
            .expect("Should have gotten a request");

        match token_or_req {
            TokenOrRequest::Token(_) => panic!("Shouldn't have gotten a token"),
            TokenOrRequest::Request { request, .. } => {
                // Should be the Google oauth2 API
                assert_eq!(request.uri().host(), Some("oauth2.googleapis.com"));
                // Scopes aren't passed for end user credentials
                assert_eq!(request.uri().query(), None);
            }
        }
    }
}