1use anyhow::Result;
18use async_trait::async_trait;
19use std::collections::HashMap;
20
21#[derive(Debug, Clone, Default)]
35pub struct CredentialContext {
36 pub properties: HashMap<String, String>,
38}
39
40impl CredentialContext {
41 pub fn new() -> Self {
43 Self::default()
44 }
45
46 pub fn with_property(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
48 self.properties.insert(key.into(), value.into());
49 self
50 }
51
52 pub fn get(&self, key: &str) -> Option<&str> {
54 self.properties.get(key).map(|s| s.as_str())
55 }
56}
57
58#[async_trait]
64pub trait IdentityProvider: Send + Sync {
65 async fn get_credentials(&self, context: &CredentialContext) -> Result<Credentials>;
72
73 fn clone_box(&self) -> Box<dyn IdentityProvider>;
75}
76
77impl Clone for Box<dyn IdentityProvider> {
78 fn clone(&self) -> Self {
79 self.clone_box()
80 }
81}
82
83#[derive(Clone, PartialEq, Eq)]
85pub enum Credentials {
86 UsernamePassword { username: String, password: String },
88 Token { username: String, token: String },
90 Certificate {
95 cert_pem: String,
97 key_pem: String,
99 username: Option<String>,
101 },
102}
103
104impl std::fmt::Debug for Credentials {
106 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107 match self {
108 Credentials::UsernamePassword { username, .. } => f
109 .debug_struct("UsernamePassword")
110 .field("username", username)
111 .field("password", &"[REDACTED]")
112 .finish(),
113 Credentials::Token { username, .. } => f
114 .debug_struct("Token")
115 .field("username", username)
116 .field("token", &"[REDACTED]")
117 .finish(),
118 Credentials::Certificate { username, .. } => f
119 .debug_struct("Certificate")
120 .field("cert_pem", &"[REDACTED]")
121 .field("key_pem", &"[REDACTED]")
122 .field("username", username)
123 .finish(),
124 }
125 }
126}
127
128impl Credentials {
129 pub fn try_into_auth_pair(self) -> std::result::Result<(String, String), Self> {
133 match self {
134 Credentials::UsernamePassword { username, password } => Ok((username, password)),
135 Credentials::Token { username, token } => Ok((username, token)),
136 other => Err(other),
137 }
138 }
139
140 pub fn try_into_certificate(
145 self,
146 ) -> std::result::Result<(String, String, Option<String>), Self> {
147 match self {
148 Credentials::Certificate {
149 cert_pem,
150 key_pem,
151 username,
152 } => Ok((cert_pem, key_pem, username)),
153 other => Err(other),
154 }
155 }
156
157 #[deprecated(note = "Use try_into_auth_pair() which returns Result instead of panicking")]
165 pub(crate) fn into_auth_pair(self) -> (String, String) {
166 self.try_into_auth_pair()
167 .unwrap_or_else(|_| panic!("Certificate credentials cannot be converted to an auth pair. Use try_into_auth_pair() or try_into_certificate() instead."))
168 }
169
170 #[deprecated(note = "Use try_into_certificate() which returns Result instead of panicking")]
178 pub(crate) fn into_certificate(self) -> (String, String, Option<String>) {
179 self.try_into_certificate()
180 .unwrap_or_else(|_| panic!("Not certificate credentials. Use try_into_certificate() or try_into_auth_pair() instead."))
181 }
182
183 pub fn is_certificate(&self) -> bool {
185 matches!(self, Credentials::Certificate { .. })
186 }
187}
188
189mod password;
190pub use password::PasswordIdentityProvider;
191
192#[cfg(test)]
193mod tests {
194 use super::*;
195
196 #[tokio::test]
197 async fn test_password_provider() {
198 let provider = PasswordIdentityProvider::new("testuser", "testpass");
199 let credentials = provider
200 .get_credentials(&CredentialContext::default())
201 .await
202 .unwrap();
203
204 match credentials {
205 Credentials::UsernamePassword { username, password } => {
206 assert_eq!(username, "testuser");
207 assert_eq!(password, "testpass");
208 }
209 _ => panic!("Expected UsernamePassword credentials"),
210 }
211 }
212
213 #[tokio::test]
214 async fn test_provider_clone() {
215 let provider: Box<dyn IdentityProvider> =
216 Box::new(PasswordIdentityProvider::new("user", "pass"));
217 let cloned = provider.clone();
218
219 let credentials = cloned
220 .get_credentials(&CredentialContext::default())
221 .await
222 .unwrap();
223 assert!(matches!(credentials, Credentials::UsernamePassword { .. }));
224 }
225
226 #[test]
227 fn test_try_into_auth_pair_username_password() {
228 let creds = Credentials::UsernamePassword {
229 username: "user".into(),
230 password: "pass".into(),
231 };
232 let (u, p) = creds.try_into_auth_pair().unwrap();
233 assert_eq!(u, "user");
234 assert_eq!(p, "pass");
235 }
236
237 #[test]
238 fn test_try_into_auth_pair_token() {
239 let creds = Credentials::Token {
240 username: "user".into(),
241 token: "tok".into(),
242 };
243 let (u, t) = creds.try_into_auth_pair().unwrap();
244 assert_eq!(u, "user");
245 assert_eq!(t, "tok");
246 }
247
248 #[test]
249 fn test_try_into_auth_pair_rejects_certificate() {
250 let creds = Credentials::Certificate {
251 cert_pem: "cert".into(),
252 key_pem: "key".into(),
253 username: None,
254 };
255 let result = creds.try_into_auth_pair();
256 assert!(result.is_err());
257 let returned = result.unwrap_err();
259 assert!(returned.is_certificate());
260 }
261
262 #[test]
263 fn test_try_into_certificate_success() {
264 let creds = Credentials::Certificate {
265 cert_pem: "cert".into(),
266 key_pem: "key".into(),
267 username: Some("user".into()),
268 };
269 let (c, k, u) = creds.try_into_certificate().unwrap();
270 assert_eq!(c, "cert");
271 assert_eq!(k, "key");
272 assert_eq!(u, Some("user".into()));
273 }
274
275 #[test]
276 fn test_try_into_certificate_rejects_password() {
277 let creds = Credentials::UsernamePassword {
278 username: "user".into(),
279 password: "pass".into(),
280 };
281 let result = creds.try_into_certificate();
282 assert!(result.is_err());
283 }
284}