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

/// [Provides tokens](https://cloud.google.com/compute/docs/instances/verifying-instance-identity)
/// using the metadata server accessible when running from within GCP.
/// Caches tokens internally.
pub type MetadataServerProvider = CachedTokenProvider<MetadataServerProviderInner>;
impl MetadataServerProvider {
    pub fn new(account_name: Option<String>) -> Self {
        CachedTokenProvider::wrap(MetadataServerProviderInner::new(account_name))
    }
}

/// [Provides tokens](https://cloud.google.com/compute/docs/instances/verifying-instance-identity)
/// using the metadata server accessible when running from within GCP
pub struct MetadataServerProviderInner {
    account_name: String,
}

impl MetadataServerProviderInner {
    pub fn new(account_name: Option<String>) -> Self {
        Self {
            account_name: account_name.unwrap_or_else(|| "default".into()),
        }
    }
}

impl TokenProvider for MetadataServerProviderInner {
    fn get_token_with_subject<'a, S, I, T>(
        &self,
        subject: Option<T>,
        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(
                    "Metadata server tokens do not support jwt subjects".to_string(),
                ),
            }));
        }

        // Regardless of GCE or GAE, the token_uri is
        // `computeMetadata/v1/instance/service-accounts/<name or id>/token`.
        let mut url = format!(
            "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/{}/token",
            self.account_name
        );

        // Merge all the scopes into a single string.
        let scopes_str = scopes
            .into_iter()
            .map(|s| s.as_ref())
            .collect::<Vec<_>>()
            .join(",");

        // If we have any scopes, pass them along in the querystring.
        if !scopes_str.is_empty() {
            url.push_str("?scopes=");
            url.push_str(&scopes_str);
        }

        let request = http::Request::builder()
            .method("GET")
            .uri(url)
            // To get responses from GCE, we must pass along the
            // Metadata-Flavor header with a value of "Google".
            .header("Metadata-Flavor", "Google")
            .body(Vec::new())?;

        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())?;

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

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

    #[test]
    fn metadata_noscopes() {
        let provider = MetadataServerProvider::new(None);

        let scopes: &[&str] = &[];

        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 metadata server
                assert_eq!(request.uri().host(), Some("metadata.google.internal"));
                // Since we had no scopes, no querystring.
                assert_eq!(request.uri().query(), None);
            }
        }
    }

    #[test]
    fn metadata_with_scopes() {
        let provider = MetadataServerProvider::new(None);

        let scopes = ["scope1", "scope2"];

        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 metadata server
                assert_eq!(request.uri().host(), Some("metadata.google.internal"));
                // Since we had some scopes, we should have a querystring.
                assert!(request.uri().query().is_some());

                let query_string = request.uri().query().unwrap();
                // We don't care about ordering, but the query_string
                // should be comma-separated and only include the
                // scopes.
                assert!(
                    query_string == "scopes=scope1,scope2"
                        || query_string == "scopes=scope2,scope1"
                );
            }
        }
    }

    #[test]
    fn wrapper_dispatch() {
        // Wrap the metadata server provider.
        let provider =
            crate::gcp::TokenProviderWrapper::Metadata(MetadataServerProvider::new(None));

        // And then have the same test as metadata_with_scopes
        let scopes = ["scope1", "scope2"];

        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 metadata server
                assert_eq!(request.uri().host(), Some("metadata.google.internal"));
                // Since we had some scopes, we should have a querystring.
                assert!(request.uri().query().is_some());

                let query_string = request.uri().query().unwrap();
                // We don't care about ordering, but the query_string
                // should be comma-separated and only include the
                // scopes.
                assert!(
                    query_string == "scopes=scope1,scope2"
                        || query_string == "scopes=scope2,scope1"
                );
            }
        }
    }
}