Skip to main content

gcloud_observability/otlp/
auth.rs

1use crate::errors::{GcloudObservabilityError, GcloudObservabilityResult};
2use gcloud_sdk::tonic::metadata::{KeyAndValueRef, MetadataMap};
3use gcloud_sdk::tonic::service::Interceptor;
4use gcloud_sdk::tonic::{Request, Status};
5use gcloud_sdk::{GoogleAuthHeaders, HeaderMap};
6use std::sync::Arc;
7use std::time::Duration;
8use tokio::runtime::Handle;
9use tokio::sync::watch;
10
11// Polling is cheap: the credentials answer from their cache until they hold a new token.
12const AUTH_HEADERS_REFRESH_INTERVAL: Duration = Duration::from_secs(5);
13
14/// A tonic [`Interceptor`] that sets the headers of Google credentials on every request:
15/// `authorization`, and whatever else the credentials add, such as `x-goog-user-project`
16/// for a quota project.
17///
18/// [`super::GcpOtlpExporterBuilder`] authenticates its exporters with one. Pass one to
19/// `with_interceptor` to authenticate an OTLP exporter built elsewhere, such as a
20/// metrics exporter.
21///
22/// An interceptor runs synchronously while Google tokens are refreshed asynchronously, so
23/// a background task polls the credentials and publishes their headers when they change,
24/// and each request copies the latest ones. The task runs on the Tokio runtime the
25/// interceptor is created on, and ends when the last clone is dropped. A failed refresh
26/// keeps the headers published last; a warning is logged when refreshing starts failing
27/// and another when it recovers.
28#[derive(Clone)]
29pub struct GcpAuthInterceptor {
30    headers: watch::Receiver<MetadataMap>,
31}
32
33impl GcpAuthInterceptor {
34    /// Fetches the first headers of `auth_headers` and starts the task that keeps them
35    /// current.
36    ///
37    /// Fails when called outside a Tokio runtime, or when the credentials serve no
38    /// headers.
39    pub async fn new(
40        auth_headers: impl Into<Arc<GoogleAuthHeaders>>,
41    ) -> GcloudObservabilityResult<Self> {
42        let runtime = Handle::try_current().map_err(|error| {
43            GcloudObservabilityError::system_caused_by(
44                "GcpAuthInterceptor refreshes its credentials on a Tokio runtime, and none is running",
45                error,
46            )
47        })?;
48        let auth_headers = auth_headers.into();
49        let served = auth_headers.headers().await?;
50        let (sender, headers) =
51            watch::channel(MetadataMap::from_headers(HeaderMap::clone(&served)));
52        runtime.spawn(keep_current(auth_headers, served, sender));
53        Ok(Self { headers })
54    }
55
56    /// [`Self::new`] with the Application Default Credentials and the `cloud-platform`
57    /// scope.
58    pub async fn from_adc() -> GcloudObservabilityResult<Self> {
59        Self::new(GoogleAuthHeaders::from_adc().await?).await
60    }
61}
62
63impl std::fmt::Debug for GcpAuthInterceptor {
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        f.debug_struct("GcpAuthInterceptor").finish_non_exhaustive()
66    }
67}
68
69impl Interceptor for GcpAuthInterceptor {
70    fn call(&mut self, mut request: Request<()>) -> Result<Request<()>, Status> {
71        let metadata = request.metadata_mut();
72        for entry in self.headers.borrow().iter() {
73            match entry {
74                KeyAndValueRef::Ascii(key, value) => {
75                    metadata.insert(key.clone(), value.clone());
76                }
77                KeyAndValueRef::Binary(key, value) => {
78                    metadata.insert_bin(key.clone(), value.clone());
79                }
80            }
81        }
82        Ok(request)
83    }
84}
85
86async fn keep_current(
87    auth_headers: Arc<GoogleAuthHeaders>,
88    mut served: Arc<HeaderMap>,
89    sender: watch::Sender<MetadataMap>,
90) {
91    let refresh = async {
92        let mut failing = false;
93        loop {
94            tokio::time::sleep(AUTH_HEADERS_REFRESH_INTERVAL).await;
95            match auth_headers.headers().await {
96                Ok(headers) => {
97                    if failing {
98                        failing = false;
99                        tracing::warn!(
100                            "Refreshing the Google credentials of OTLP exports recovered"
101                        );
102                    }
103                    // Unchanged credentials answer with the map they served last.
104                    if !Arc::ptr_eq(&headers, &served) {
105                        sender.send_replace(MetadataMap::from_headers(HeaderMap::clone(&headers)));
106                        served = headers;
107                    }
108                }
109                Err(error) if !failing => {
110                    failing = true;
111                    tracing::warn!(
112                        %error,
113                        "Refreshing the Google credentials of OTLP exports failed; the last headers stay in use until it recovers"
114                    );
115                }
116                Err(_) => {}
117            }
118        }
119    };
120    tokio::select! {
121        () = sender.closed() => {}
122        () = refresh => {}
123    }
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129    use crate::otlp::testing::ScriptedAccessToken;
130
131    #[tokio::test]
132    async fn requests_carry_the_credentials_authorization_as_a_sensitive_header() {
133        let auth_headers = ScriptedAccessToken::new("first-token").auth_headers();
134        let mut interceptor = GcpAuthInterceptor::new(auth_headers).await.unwrap();
135
136        let request = interceptor.call(Request::new(())).unwrap();
137
138        let authorization = request
139            .metadata()
140            .get("authorization")
141            .expect("the credentials' authorization header is set");
142        assert_eq!(authorization, "Bearer first-token");
143        assert!(authorization.is_sensitive());
144    }
145
146    #[tokio::test(start_paused = true)]
147    async fn requests_carry_the_rotated_token_after_a_refresh() {
148        let credentials = ScriptedAccessToken::new("first-token");
149        let mut interceptor = GcpAuthInterceptor::new(credentials.auth_headers())
150            .await
151            .unwrap();
152
153        credentials.rotate("second-token");
154        tokio::time::sleep(AUTH_HEADERS_REFRESH_INTERVAL + Duration::from_secs(1)).await;
155
156        let request = interceptor.call(Request::new(())).unwrap();
157        assert_eq!(
158            request
159                .metadata()
160                .get("authorization")
161                .map(|value| value.to_str().unwrap()),
162            Some("Bearer second-token")
163        );
164    }
165
166    #[tokio::test(start_paused = true)]
167    async fn refresh_task_ends_with_the_last_interceptor_clone() {
168        let auth_headers = ScriptedAccessToken::new("first-token").auth_headers();
169        let interceptor = GcpAuthInterceptor::new(Arc::clone(&auth_headers))
170            .await
171            .unwrap();
172        let clone = interceptor.clone();
173
174        drop(interceptor);
175        drop(clone);
176        tokio::time::sleep(AUTH_HEADERS_REFRESH_INTERVAL * 3).await;
177
178        // The refresh task holds the only other reference to the credentials.
179        assert_eq!(Arc::strong_count(&auth_headers), 1);
180    }
181
182    #[tokio::test]
183    async fn construction_fails_when_the_credentials_serve_no_headers() {
184        let auth_headers = ScriptedAccessToken::default().auth_headers();
185
186        let result = GcpAuthInterceptor::new(auth_headers).await;
187
188        assert!(matches!(
189            result,
190            Err(GcloudObservabilityError::SystemError(_))
191        ));
192    }
193}