google_cloud_auth/
token.rs

1// Copyright 2024 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::Result;
16use std::collections::HashMap;
17use std::time::Instant;
18
19/// Represents an auth token.
20#[derive(Clone, PartialEq)]
21pub struct Token {
22    /// The actual token string.
23    ///
24    /// This is the value used in `Authorization:` header.
25    pub token: String,
26
27    /// The type of the token.
28    ///
29    /// The most common type is `"Bearer"` but other types may appear in the
30    /// future.
31    pub token_type: String,
32
33    /// The instant at which the token expires.
34    ///
35    /// If `None`, the token does not expire.
36    ///
37    /// Note that the `Instant` is not valid across processes. It is
38    /// recommended to let the authentication library refresh tokens within a
39    /// process instead of handling expirations yourself. If you do need to
40    /// copy an expiration across processes, consider converting it to a
41    /// `time::OffsetDateTime` first:
42    ///
43    /// ```
44    /// # let expires_at = Some(std::time::Instant::now());
45    /// expires_at.map(|i| time::OffsetDateTime::now_utc() + (i - std::time::Instant::now()));
46    /// ```
47    pub expires_at: Option<Instant>,
48
49    /// Optional metadata associated with the token.
50    ///
51    /// This might include information like granted scopes or other claims.
52    pub metadata: Option<HashMap<String, String>>,
53}
54
55impl std::fmt::Debug for Token {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        f.debug_struct("Token")
58            .field("token", &"[censored]")
59            .field("token_type", &self.token_type)
60            .field("expires_at", &self.expires_at)
61            .field("metadata", &self.metadata)
62            .finish()
63    }
64}
65
66#[async_trait::async_trait]
67pub(crate) trait TokenProvider: std::fmt::Debug + Send + Sync {
68    async fn token(&self) -> Result<Token>;
69}
70
71#[cfg(test)]
72pub(crate) mod test {
73    use super::*;
74    use std::time::Duration;
75
76    // Used by tests in other modules.
77    mockall::mock! {
78        #[derive(Debug)]
79        pub TokenProvider { }
80
81        #[async_trait::async_trait]
82        impl TokenProvider for TokenProvider {
83            async fn token(&self) -> Result<Token>;
84        }
85    }
86
87    #[test]
88    fn debug() {
89        let expires_at = Instant::now() + Duration::from_secs(3600);
90        let metadata =
91            HashMap::from([("a", "test-only")].map(|(k, v)| (k.to_string(), v.to_string())));
92
93        let token = Token {
94            token: "token-test-only".into(),
95            token_type: "token-type-test-only".into(),
96            expires_at: Some(expires_at),
97            metadata: Some(metadata.clone()),
98        };
99        let got = format!("{token:?}");
100        assert!(!got.contains("token-test-only"), "{got}");
101        assert!(got.contains("token: \"[censored]\""), "{got}");
102        assert!(got.contains("token_type: \"token-type-test-only"), "{got}");
103        assert!(
104            got.contains(&format!("expires_at: Some({expires_at:?}")),
105            "{got}"
106        );
107        assert!(
108            got.contains(&format!("metadata: Some({metadata:?}")),
109            "{got}"
110        );
111    }
112}