Skip to main content

port_sdk/
auth.rs

1use crate::error::PortError;
2use async_trait::async_trait;
3use reqwest::Client as HttpClient;
4use serde::Deserialize;
5use std::fmt;
6use std::sync::{Arc, Mutex};
7use std::time::{Duration, Instant};
8use url::Url;
9
10/// Strategy used to authenticate requests made by the SDK.
11#[derive(Clone)]
12pub enum AuthStrategy {
13    /// Static bearer token (API key/service user token).
14    StaticToken(String),
15    /// OAuth 2.0 client credentials flow.
16    ClientCredentials(ClientCredentialsOptions),
17    /// Custom token provider supplied by the caller.
18    Provider(Arc<dyn TokenProvider>),
19}
20
21impl fmt::Debug for AuthStrategy {
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        match self {
24            AuthStrategy::StaticToken(_) => f.debug_tuple("StaticToken").finish(),
25            AuthStrategy::ClientCredentials(options) => {
26                f.debug_tuple("ClientCredentials").field(options).finish()
27            }
28            AuthStrategy::Provider(_) => f.debug_tuple("Provider").field(&"<custom>").finish(),
29        }
30    }
31}
32
33impl AuthStrategy {
34    /// Convert the strategy into a token provider that can be consumed by the client.
35    pub fn into_provider(self) -> Result<Arc<dyn TokenProvider>, PortError> {
36        match self {
37            AuthStrategy::StaticToken(token) => Ok(Arc::new(StaticTokenProvider::new(token))),
38            AuthStrategy::ClientCredentials(options) => {
39                Ok(Arc::new(ClientCredentialsTokenProvider::new(options)?))
40            }
41            AuthStrategy::Provider(provider) => Ok(provider),
42        }
43    }
44}
45
46/// Options for performing the OAuth 2.0 client credentials grant.
47#[derive(Clone, Debug)]
48pub struct ClientCredentialsOptions {
49    pub client_id: String,
50    pub client_secret: String,
51    pub token_url: Url,
52    pub minimum_ttl: Duration,
53}
54
55#[async_trait]
56pub trait TokenProvider: Send + Sync {
57    async fn bearer_token(&self) -> Result<String, PortError>;
58}
59
60/// Simple token provider backed by an in-memory token.
61#[derive(Debug)]
62pub struct StaticTokenProvider {
63    token: String,
64}
65
66impl StaticTokenProvider {
67    pub fn new(token: impl Into<String>) -> Self {
68        Self { token: token.into() }
69    }
70}
71
72#[async_trait]
73impl TokenProvider for StaticTokenProvider {
74    async fn bearer_token(&self) -> Result<String, PortError> {
75        Ok(self.token.clone())
76    }
77}
78
79#[derive(Clone)]
80struct CachedToken {
81    value: String,
82    expires_at: Instant,
83}
84
85struct ClientCredentialsTokenProvider {
86    options: ClientCredentialsOptions,
87    http: HttpClient,
88    cache: Mutex<Option<CachedToken>>,
89}
90
91impl ClientCredentialsTokenProvider {
92    fn new(options: ClientCredentialsOptions) -> Result<Self, PortError> {
93        let http = HttpClient::builder().build().map_err(|err| {
94            PortError::Configuration(format!("failed to build OAuth client: {err}"))
95        })?;
96        Ok(Self { options, http, cache: Mutex::new(None) })
97    }
98
99    fn cached_token(&self) -> Option<CachedToken> {
100        let guard = self.cache.lock().expect("client credentials cache mutex poisoned");
101        guard.clone()
102    }
103
104    fn store_token(&self, token: CachedToken) {
105        let mut guard = self.cache.lock().expect("client credentials cache mutex poisoned");
106        *guard = Some(token);
107    }
108
109    fn should_refresh(&self, expires_at: Instant) -> bool {
110        Instant::now() + self.options.minimum_ttl >= expires_at
111    }
112
113    async fn fetch_token(&self) -> Result<CachedToken, PortError> {
114        let form = vec![
115            ("grant_type".to_string(), "client_credentials".to_string()),
116            ("client_id".to_string(), self.options.client_id.clone()),
117            ("client_secret".to_string(), self.options.client_secret.clone()),
118        ];
119        let response = self
120            .http
121            .post(self.options.token_url.clone())
122            .form(&form)
123            .send()
124            .await?
125            .error_for_status()?;
126
127        let payload: OAuthTokenResponse = response.json().await?;
128        let token = payload.access_token;
129        if token.trim().is_empty() {
130            return Err(PortError::Configuration(
131                "OAuth client credentials flow returned an empty access token".into(),
132            ));
133        }
134
135        let expires_in = payload.expires_in.unwrap_or(3600);
136        let expires_at = Instant::now()
137            + if expires_in <= self.options.minimum_ttl.as_secs() {
138                Duration::from_secs(expires_in)
139            } else {
140                Duration::from_secs(expires_in - self.options.minimum_ttl.as_secs())
141            };
142
143        Ok(CachedToken { value: token, expires_at })
144    }
145}
146
147#[async_trait]
148impl TokenProvider for ClientCredentialsTokenProvider {
149    async fn bearer_token(&self) -> Result<String, PortError> {
150        if let Some(cached) = self.cached_token() {
151            if !self.should_refresh(cached.expires_at) {
152                return Ok(cached.value);
153            }
154        }
155
156        let token = self.fetch_token().await?;
157        let value = token.value.clone();
158        self.store_token(token);
159        Ok(value)
160    }
161}
162
163#[derive(Debug, Deserialize)]
164struct OAuthTokenResponse {
165    access_token: String,
166    #[allow(dead_code)]
167    token_type: Option<String>,
168    expires_in: Option<u64>,
169}