mssql-auth 0.20.0

Authentication strategies for SQL Server connections
Documentation
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! Azure Identity authentication providers.
//!
//! This module provides Azure authentication using the `azure_identity` crate
//! for token acquisition. It supports:
//!
//! - **Managed Identity**: For Azure VMs, App Service, Container Instances, and AKS
//! - **Service Principal**: For application-based authentication with client credentials
//!
//! ## Example: Managed Identity (System-Assigned)
//!
//! ```rust,ignore
//! use mssql_auth::ManagedIdentityAuth;
//!
//! // System-assigned managed identity (default)
//! let auth = ManagedIdentityAuth::system_assigned();
//! let token = auth.get_token().await?;
//! ```
//!
//! ## Example: Managed Identity (User-Assigned)
//!
//! ```rust,ignore
//! use mssql_auth::ManagedIdentityAuth;
//!
//! // User-assigned managed identity by client ID
//! let auth = ManagedIdentityAuth::user_assigned_client_id("your-client-id");
//! let token = auth.get_token().await?;
//! ```
//!
//! ## Example: Service Principal
//!
//! ```rust,ignore
//! use mssql_auth::ServicePrincipalAuth;
//!
//! let auth = ServicePrincipalAuth::new(
//!     "your-tenant-id",
//!     "your-client-id",
//!     "your-client-secret",
//! );
//! let token = auth.get_token().await?;
//! ```

use std::sync::Arc;
use std::time::Duration;

use azure_core::credentials::TokenCredential;
use azure_identity::{
    ClientSecretCredential, DeveloperToolsCredential, ManagedIdentityCredential,
    ManagedIdentityCredentialOptions, UserAssignedId,
};

use crate::AzureAdAuth;
use crate::error::AuthError;
use crate::provider::{AuthData, AuthMethod};

/// The Azure SQL Database scope for token requests.
const AZURE_SQL_SCOPE: &str = "https://database.windows.net/.default";

/// Default Azure credential chain for `Authentication=ActiveDirectoryDefault`.
///
/// Tries each credential in order and returns the first token acquired:
/// 1. [`ManagedIdentityCredential`] — for code running on Azure compute.
/// 2. [`DeveloperToolsCredential`] — the signed-in `az` / `azd` CLI session,
///    for local development.
///
/// `azure_identity` 1.0 ships no aggregate `DefaultAzureCredential`, so this is
/// a minimal hand-rolled chain over the two credential types that cover the
/// common production and local-development cases. The environment /
/// service-principal case is served by the explicit
/// [`ServicePrincipalAuth`] credential.
#[derive(Clone)]
pub struct DefaultAzureAuth {
    sources: Vec<Arc<dyn TokenCredential>>,
}

impl DefaultAzureAuth {
    /// Create the default credential chain (managed identity → developer tooling).
    ///
    /// # Errors
    ///
    /// Returns an error if either underlying credential cannot be constructed.
    pub fn new() -> Result<Self, AuthError> {
        let managed_identity: Arc<dyn TokenCredential> = ManagedIdentityCredential::new(None)
            .map_err(|e| AuthError::AzureIdentity(e.to_string()))?;
        let developer_tools: Arc<dyn TokenCredential> = DeveloperToolsCredential::new(None)
            .map_err(|e| AuthError::AzureIdentity(e.to_string()))?;
        Ok(Self {
            sources: vec![managed_identity, developer_tools],
        })
    }

    /// Get an access token for Azure SQL Database from the first credential in
    /// the chain that succeeds.
    ///
    /// # Errors
    ///
    /// Returns an error if no credential in the chain can acquire a token.
    pub async fn get_token(&self) -> Result<String, AuthError> {
        let mut last_err: Option<String> = None;
        for source in &self.sources {
            match source.get_token(&[AZURE_SQL_SCOPE], None).await {
                Ok(token) => return Ok(token.token.secret().to_string()),
                Err(e) => last_err = Some(e.to_string()),
            }
        }
        Err(AuthError::AzureIdentity(format!(
            "the default credential chain (managed identity, then developer tooling) \
             could not acquire a token: {}",
            last_err.as_deref().unwrap_or("no credentials in chain")
        )))
    }
}

/// Managed Identity authentication provider.
///
/// Uses Azure Managed Identity to acquire access tokens for Azure SQL Database.
/// This works on Azure VMs, App Service, Container Instances, and AKS.
#[derive(Clone)]
pub struct ManagedIdentityAuth {
    credential: Arc<ManagedIdentityCredential>,
}

impl ManagedIdentityAuth {
    /// Create authentication using system-assigned managed identity.
    ///
    /// This is the simplest form - uses the identity assigned to the Azure resource
    /// (VM, App Service, etc.) that the code is running on.
    ///
    /// # Errors
    ///
    /// Returns an error if the managed identity credential cannot be created.
    pub fn system_assigned() -> Result<Self, AuthError> {
        let credential = ManagedIdentityCredential::new(None)
            .map_err(|e| AuthError::AzureIdentity(e.to_string()))?;
        Ok(Self { credential })
    }

    /// Create authentication using a user-assigned managed identity by client ID.
    ///
    /// Use this when you have multiple managed identities and need to specify which one to use.
    ///
    /// # Arguments
    ///
    /// * `client_id` - The client ID of the user-assigned managed identity
    ///
    /// # Errors
    ///
    /// Returns an error if the managed identity credential cannot be created.
    pub fn user_assigned_client_id(client_id: impl Into<String>) -> Result<Self, AuthError> {
        let options = ManagedIdentityCredentialOptions {
            user_assigned_id: Some(UserAssignedId::ClientId(client_id.into())),
            ..Default::default()
        };
        let credential = ManagedIdentityCredential::new(Some(options))
            .map_err(|e| AuthError::AzureIdentity(e.to_string()))?;
        Ok(Self { credential })
    }

    /// Create authentication using a user-assigned managed identity by resource ID.
    ///
    /// # Arguments
    ///
    /// * `resource_id` - The Azure resource ID of the user-assigned managed identity
    ///
    /// # Errors
    ///
    /// Returns an error if the managed identity credential cannot be created.
    pub fn user_assigned_resource_id(resource_id: impl Into<String>) -> Result<Self, AuthError> {
        let options = ManagedIdentityCredentialOptions {
            user_assigned_id: Some(UserAssignedId::ResourceId(resource_id.into())),
            ..Default::default()
        };
        let credential = ManagedIdentityCredential::new(Some(options))
            .map_err(|e| AuthError::AzureIdentity(e.to_string()))?;
        Ok(Self { credential })
    }

    /// Create authentication using a user-assigned managed identity by object ID.
    ///
    /// # Arguments
    ///
    /// * `object_id` - The object ID of the user-assigned managed identity
    ///
    /// # Errors
    ///
    /// Returns an error if the managed identity credential cannot be created.
    pub fn user_assigned_object_id(object_id: impl Into<String>) -> Result<Self, AuthError> {
        let options = ManagedIdentityCredentialOptions {
            user_assigned_id: Some(UserAssignedId::ObjectId(object_id.into())),
            ..Default::default()
        };
        let credential = ManagedIdentityCredential::new(Some(options))
            .map_err(|e| AuthError::AzureIdentity(e.to_string()))?;
        Ok(Self { credential })
    }

    /// Get an access token for Azure SQL Database.
    ///
    /// # Errors
    ///
    /// Returns an error if token acquisition fails.
    pub async fn get_token(&self) -> Result<String, AuthError> {
        let token = self
            .credential
            .get_token(&[AZURE_SQL_SCOPE], None)
            .await
            .map_err(|e| AuthError::AzureIdentity(e.to_string()))?;
        Ok(token.token.secret().to_string())
    }

    /// Get an access token with expiration information.
    ///
    /// # Errors
    ///
    /// Returns an error if token acquisition fails.
    pub async fn get_token_with_expiry(&self) -> Result<(String, Option<Duration>), AuthError> {
        let token = self
            .credential
            .get_token(&[AZURE_SQL_SCOPE], None)
            .await
            .map_err(|e| AuthError::AzureIdentity(e.to_string()))?;

        // Calculate time until expiration
        let now = time::OffsetDateTime::now_utc();
        let expires_in = if token.expires_on > now {
            let diff = token.expires_on - now;
            Some(Duration::from_secs(diff.whole_seconds().max(0) as u64))
        } else {
            None
        };

        Ok((token.token.secret().to_string(), expires_in))
    }

    /// Convert to an `AzureAdAuth` provider with an acquired token.
    ///
    /// # Errors
    ///
    /// Returns an error if token acquisition fails.
    pub async fn to_azure_ad_auth(&self) -> Result<AzureAdAuth, AuthError> {
        let (token, expires_in) = self.get_token_with_expiry().await?;
        match expires_in {
            Some(duration) => Ok(AzureAdAuth::with_token_expiring(token, duration)),
            None => Ok(AzureAdAuth::with_token(token)),
        }
    }
}

impl std::fmt::Debug for ManagedIdentityAuth {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ManagedIdentityAuth")
            .finish_non_exhaustive()
    }
}

impl crate::provider::AsyncAuthProvider for ManagedIdentityAuth {
    fn method(&self) -> AuthMethod {
        AuthMethod::AzureAd
    }

    async fn authenticate_async(&self) -> Result<AuthData, AuthError> {
        let token = self.get_token().await?;
        Ok(AuthData::FedAuth { token, nonce: None })
    }

    fn needs_refresh(&self) -> bool {
        // Managed identity tokens are acquired fresh each time
        false
    }
}

/// Service Principal authentication provider.
///
/// Uses Azure Service Principal (application credentials) to acquire access tokens.
/// This is suitable for server-to-server authentication where no user is present.
pub struct ServicePrincipalAuth {
    credential: Arc<ClientSecretCredential>,
}

impl ServicePrincipalAuth {
    /// Create a new Service Principal authenticator.
    ///
    /// # Arguments
    ///
    /// * `tenant_id` - The Azure AD tenant ID
    /// * `client_id` - The application (client) ID
    /// * `client_secret` - The client secret
    ///
    /// # Errors
    ///
    /// Returns an error if the credential cannot be created.
    pub fn new(
        tenant_id: impl AsRef<str>,
        client_id: impl Into<String>,
        client_secret: impl Into<String>,
    ) -> Result<Self, AuthError> {
        use azure_core::credentials::Secret;

        let secret = Secret::new(client_secret.into());
        let credential =
            ClientSecretCredential::new(tenant_id.as_ref(), client_id.into(), secret, None)
                .map_err(|e| AuthError::AzureIdentity(e.to_string()))?;
        Ok(Self { credential })
    }

    /// Get an access token for Azure SQL Database.
    ///
    /// # Errors
    ///
    /// Returns an error if token acquisition fails.
    pub async fn get_token(&self) -> Result<String, AuthError> {
        let token = self
            .credential
            .get_token(&[AZURE_SQL_SCOPE], None)
            .await
            .map_err(|e| AuthError::AzureIdentity(e.to_string()))?;
        Ok(token.token.secret().to_string())
    }

    /// Get an access token with expiration information.
    ///
    /// # Errors
    ///
    /// Returns an error if token acquisition fails.
    pub async fn get_token_with_expiry(&self) -> Result<(String, Option<Duration>), AuthError> {
        let token = self
            .credential
            .get_token(&[AZURE_SQL_SCOPE], None)
            .await
            .map_err(|e| AuthError::AzureIdentity(e.to_string()))?;

        // Calculate time until expiration
        let now = time::OffsetDateTime::now_utc();
        let expires_in = if token.expires_on > now {
            let diff = token.expires_on - now;
            Some(Duration::from_secs(diff.whole_seconds().max(0) as u64))
        } else {
            None
        };

        Ok((token.token.secret().to_string(), expires_in))
    }

    /// Convert to an `AzureAdAuth` provider with an acquired token.
    ///
    /// # Errors
    ///
    /// Returns an error if token acquisition fails.
    pub async fn to_azure_ad_auth(&self) -> Result<AzureAdAuth, AuthError> {
        let (token, expires_in) = self.get_token_with_expiry().await?;
        match expires_in {
            Some(duration) => Ok(AzureAdAuth::with_token_expiring(token, duration)),
            None => Ok(AzureAdAuth::with_token(token)),
        }
    }
}

impl Clone for ServicePrincipalAuth {
    fn clone(&self) -> Self {
        Self {
            credential: Arc::clone(&self.credential),
        }
    }
}

impl std::fmt::Debug for ServicePrincipalAuth {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ServicePrincipalAuth")
            .field("credential", &"[REDACTED]")
            .finish()
    }
}

impl crate::provider::AsyncAuthProvider for ServicePrincipalAuth {
    fn method(&self) -> AuthMethod {
        AuthMethod::AzureAd
    }

    async fn authenticate_async(&self) -> Result<AuthData, AuthError> {
        let token = self.get_token().await?;
        Ok(AuthData::FedAuth { token, nonce: None })
    }

    fn needs_refresh(&self) -> bool {
        // Service principal tokens are acquired fresh each time
        false
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    // Note: These tests require Azure credentials to be configured in the environment.
    // They are marked as ignored by default and can be run manually with:
    // cargo test --features azure-identity -- --ignored

    #[tokio::test]
    #[ignore = "Requires Azure Managed Identity environment"]
    async fn test_managed_identity_system_assigned() {
        let auth = ManagedIdentityAuth::system_assigned().expect("Failed to create credential");
        let token = auth.get_token().await.expect("Failed to get token");
        assert!(!token.is_empty());
    }

    #[tokio::test]
    #[ignore = "Requires Azure Service Principal credentials"]
    async fn test_service_principal() {
        let tenant_id = std::env::var("AZURE_TENANT_ID").expect("AZURE_TENANT_ID not set");
        let client_id = std::env::var("AZURE_CLIENT_ID").expect("AZURE_CLIENT_ID not set");
        let client_secret =
            std::env::var("AZURE_CLIENT_SECRET").expect("AZURE_CLIENT_SECRET not set");

        let auth = ServicePrincipalAuth::new(tenant_id, client_id, client_secret)
            .expect("Failed to create credential");
        let token = auth.get_token().await.expect("Failed to get token");
        assert!(!token.is_empty());
    }

    #[test]
    fn test_debug_redacts_credentials() {
        if let Ok(auth) = ManagedIdentityAuth::system_assigned() {
            let debug = format!("{auth:?}");
            assert!(debug.contains("ManagedIdentityAuth"));
        }

        // The client secret must never appear in the Debug output.
        let secret = "client-secret-must-not-appear-in-debug";
        let auth = ServicePrincipalAuth::new(
            "00000000-0000-0000-0000-000000000000",
            "11111111-1111-1111-1111-111111111111",
            secret,
        )
        .expect("constructing a service principal credential should not fail offline");
        let debug = format!("{auth:?}");
        assert!(
            !debug.contains(secret),
            "Debug output must not expose the client secret"
        );
        assert!(debug.contains("[REDACTED]"));
    }
}