Skip to main content

sqlserver_mcp_catalog/auth/
auth_manager.rs

1// SQL Server - master/msdb/sandbox combined catalog MCP server.
2
3use crate::core::config_schema::AuthMethod;
4use crate::core::credential_storage::{load_credential, save_credential};
5
6use super::auth_strategy::{AuthConfig, AuthStrategy, Credentials};
7use super::errors::AuthError;
8use super::strategies::azure_ad::AzureAdAuthStrategy;
9use super::strategies::sql_server::SqlServerAuthStrategy;
10use super::strategies::windows::WindowsAuthStrategy;
11
12const CREDENTIAL_ACCOUNT: &str = "active-credentials";
13const ENV_PREFIX: &str = "SQLSERVER";
14
15/// Builds an `AuthConfig` straight from the `<PREFIX>_USERNAME`/`_PASSWORD`
16/// (SQL Server/Windows auth) or `<PREFIX>_CLIENT_ID`/`_CLIENT_SECRET`/
17/// `_TENANT_ID` (Azure AD) env vars documented in `.env.example`, if the
18/// vars this `auth_method` needs are actually set. Returns `None` when the
19/// required var(s) for this deployment's `auth_method` aren't present, so
20/// callers fall back to the stored-credential lookup unchanged.
21fn credentials_from_env(auth_method: AuthMethod) -> Option<AuthConfig> {
22    let mut config = AuthConfig::new();
23    match auth_method {
24        AuthMethod::SqlServer | AuthMethod::Windows => {
25            let username = std::env::var(format!("{ENV_PREFIX}_USERNAME")).ok()?;
26            let password = std::env::var(format!("{ENV_PREFIX}_PASSWORD")).ok()?;
27            config.insert("username".to_string(), username);
28            config.insert("password".to_string(), password);
29        }
30        AuthMethod::AzureAd => {
31            let client_id = std::env::var(format!("{ENV_PREFIX}_CLIENT_ID")).ok()?;
32            let client_secret = std::env::var(format!("{ENV_PREFIX}_CLIENT_SECRET")).ok()?;
33            config.insert("client_id".to_string(), client_id);
34            config.insert("client_secret".to_string(), client_secret);
35            if let Ok(tenant_id) = std::env::var(format!("{ENV_PREFIX}_TENANT_ID")) {
36                config.insert("tenant_id".to_string(), tenant_id);
37            }
38        }
39    }
40    Some(config)
41}
42
43fn strategy_for(auth_method: AuthMethod) -> Box<dyn AuthStrategy> {
44    match auth_method {
45        AuthMethod::SqlServer => Box::new(SqlServerAuthStrategy),
46        AuthMethod::Windows => Box::new(WindowsAuthStrategy),
47        AuthMethod::AzureAd => Box::new(AzureAdAuthStrategy),
48    }
49}
50
51/// Selects exactly one active auth strategy per deployment, chosen via the
52/// `auth_method` config value — there is no runtime engine for resolving
53/// multiple simultaneously-required schemes. These three methods
54/// (`SqlServer`/`Windows`/`AzureAd`) are the complete set SQL Server's TDS
55/// protocol accepts (see `core::config_schema::AuthMethod`'s doc comment)
56/// — there is no per-request/HTTP-header credential relay concept here:
57/// this server always connects to SQL Server with the one set of
58/// operator-configured credentials resolved via `credentials()`'s config/
59/// env/keychain cascade below, regardless of how a caller reaches *this*
60/// MCP server (stdio or HTTP).
61pub struct AuthManager {
62    auth_method: AuthMethod,
63    strategy: Box<dyn AuthStrategy>,
64    cached_credentials: Option<Credentials>,
65}
66
67impl AuthManager {
68    pub fn new(auth_method: AuthMethod) -> Self {
69        Self {
70            strategy: strategy_for(auth_method),
71            auth_method,
72            cached_credentials: None,
73        }
74    }
75
76    /// Seeds in-memory credentials directly, bypassing OS-keychain/file
77    /// storage entirely — for tests (which must never touch the real OS
78    /// keychain as a side effect of running) and for callers that already
79    /// hold validated credentials from elsewhere.
80    pub fn set_credentials(&mut self, credentials: Credentials) {
81        self.cached_credentials = Some(credentials);
82    }
83
84    pub async fn credentials(&mut self) -> anyhow::Result<Credentials> {
85        if let Some(cached) = &self.cached_credentials
86            && self.strategy.validate_credentials(cached)
87        {
88            return Ok(cached.clone());
89        }
90
91        if let Some(env_config) = credentials_from_env(self.auth_method)
92            && let Ok(from_env) = self.strategy.authenticate(&env_config).await
93            && self.strategy.validate_credentials(&from_env)
94        {
95            self.cached_credentials = Some(from_env.clone());
96            return Ok(from_env);
97        }
98
99        if let Some(stored) = load_credential(CREDENTIAL_ACCOUNT)? {
100            let parsed: Credentials = serde_json::from_str(&stored)?;
101            if self.strategy.validate_credentials(&parsed) {
102                self.cached_credentials = Some(parsed.clone());
103                return Ok(parsed);
104            }
105            if let Ok(refreshed) = self.strategy.refresh_token(&parsed).await {
106                self.cached_credentials = Some(refreshed.clone());
107                save_credential(CREDENTIAL_ACCOUNT, &serde_json::to_string(&refreshed)?)?;
108                return Ok(refreshed);
109            }
110        }
111
112        Err(AuthError::NoActiveCredentials(format!("{:?}", self.auth_method)).into())
113    }
114
115    /// Resolves this deployment's active `tiberius::AuthMethod` from the
116    /// config/env/keychain cascade (`credentials()`).
117    pub async fn resolve_tds_auth(&mut self) -> anyhow::Result<tiberius::AuthMethod> {
118        let credentials = self.credentials().await?;
119        match self.auth_method {
120            AuthMethod::SqlServer => {
121                let username = credentials
122                    .get("username")
123                    .ok_or_else(|| AuthError::MissingCredentials("username".to_string()))?;
124                let password = credentials
125                    .get("password")
126                    .ok_or_else(|| AuthError::MissingCredentials("password".to_string()))?;
127                Ok(tiberius::AuthMethod::sql_server(username, password))
128            }
129            AuthMethod::Windows => {
130                let username = credentials
131                    .get("username")
132                    .ok_or_else(|| AuthError::MissingCredentials("username".to_string()))?;
133                let password = credentials
134                    .get("password")
135                    .ok_or_else(|| AuthError::MissingCredentials("password".to_string()))?;
136                windows_auth_method(username, password)
137            }
138            AuthMethod::AzureAd => {
139                let token = credentials
140                    .get("access_token")
141                    .ok_or_else(|| AuthError::MissingCredentials("access_token".to_string()))?;
142                Ok(tiberius::AuthMethod::AADToken(token.clone()))
143            }
144        }
145    }
146}
147
148/// `tiberius::AuthMethod::windows` only exists (`#[cfg(all(windows, feature
149/// = "winauth"))]`) when actually compiling for Windows — it's a native
150/// SSPI binding, not a portable NTLM implementation. On any other target
151/// (this pipeline's primary one: Linux containers, see
152/// docs/sqlserver-eda-openapi-pipeline/docker-compose.yml) there is no
153/// non-Windows NTLM/SSPI path in this project's current dependencies
154/// (`integrated-auth-gssapi` would add Kerberos via a system `libgssapi`
155/// this project doesn't link), so this surfaces as a clear runtime error
156/// instead of a compile failure or a silent wrong-auth fallback.
157#[cfg(windows)]
158fn windows_auth_method(username: &str, password: &str) -> anyhow::Result<tiberius::AuthMethod> {
159    Ok(tiberius::AuthMethod::windows(username, password))
160}
161
162#[cfg(not(windows))]
163fn windows_auth_method(_username: &str, _password: &str) -> anyhow::Result<tiberius::AuthMethod> {
164    anyhow::bail!(
165        "Windows Authentication requires tiberius's native SSPI binding, which is only compiled \
166         on Windows targets; this server is running on a non-Windows target with no \
167         non-Windows NTLM/Kerberos implementation linked in. Use `sql_server` or `azure_ad` \
168         auth instead, or add Kerberos support (tiberius's `integrated-auth-gssapi` feature, \
169         which requires the system `libgssapi` library) if Windows Authentication against a \
170         non-Windows client is required."
171    )
172}
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177
178    #[tokio::test]
179    async fn seeded_credentials_win_over_stored_ones() {
180        let mut manager = AuthManager::new(AuthMethod::SqlServer);
181        let mut credentials = Credentials::new();
182        credentials.insert("username".to_string(), "sa".to_string());
183        credentials.insert("password".to_string(), "s3cr3t".to_string());
184        manager.set_credentials(credentials.clone());
185
186        let resolved = manager.credentials().await.unwrap();
187        assert_eq!(resolved.get("username").map(String::as_str), Some("sa"));
188    }
189
190    #[tokio::test]
191    async fn resolve_tds_auth_builds_a_sql_server_auth_method() {
192        let mut manager = AuthManager::new(AuthMethod::SqlServer);
193        let mut credentials = Credentials::new();
194        credentials.insert("username".to_string(), "sa".to_string());
195        credentials.insert("password".to_string(), "s3cr3t".to_string());
196        manager.set_credentials(credentials);
197
198        let auth = manager.resolve_tds_auth().await.unwrap();
199        assert!(matches!(auth, tiberius::AuthMethod::SqlServer(_)));
200    }
201
202    #[tokio::test]
203    async fn resolve_tds_auth_builds_an_azure_ad_auth_method() {
204        let mut manager = AuthManager::new(AuthMethod::AzureAd);
205        let mut credentials = Credentials::new();
206        credentials.insert("access_token".to_string(), "eyJ...".to_string());
207        manager.set_credentials(credentials);
208
209        let auth = manager.resolve_tds_auth().await.unwrap();
210        assert!(matches!(auth, tiberius::AuthMethod::AADToken(_)));
211    }
212
213    #[tokio::test]
214    async fn resolve_tds_auth_errors_without_any_credentials() {
215        let mut manager = AuthManager::new(AuthMethod::SqlServer);
216        assert!(manager.resolve_tds_auth().await.is_err());
217    }
218
219    /// `tiberius::AuthMethod::windows` only exists on Windows targets (see
220    /// `windows_auth_method`'s doc comment) -- on every other target
221    /// (including wherever this test suite runs), the Windows arm of
222    /// `resolve_tds_auth` reaches real credentials successfully but then
223    /// hits the `#[cfg(not(windows))]` fallback, which bails with a clear,
224    /// actionable error rather than a panic or a silent wrong-auth
225    /// fallback. This is the behavior every non-Windows deployment of this
226    /// server actually has today.
227    #[tokio::test]
228    #[cfg(not(windows))]
229    async fn resolve_tds_auth_reports_the_missing_sspi_binding_on_non_windows_targets() {
230        let mut manager = AuthManager::new(AuthMethod::Windows);
231        let mut credentials = Credentials::new();
232        credentials.insert("username".to_string(), "CORP\\alice".to_string());
233        credentials.insert("password".to_string(), "s3cr3t".to_string());
234        manager.set_credentials(credentials);
235        let err = manager.resolve_tds_auth().await.unwrap_err();
236        assert!(err.to_string().contains("native SSPI binding"));
237    }
238
239    #[test]
240    fn credentials_from_env_is_none_when_the_required_vars_are_unset() {
241        // Doesn't touch real env vars a developer/CI might have set for
242        // something else -- SQLSERVER_USERNAME/PASSWORD are this project's
243        // own namespaced vars, and this assertion only holds in a process
244        // where neither happens to already be exported (true for a plain
245        // `cargo test` invocation, which is the only context this runs in).
246        assert!(credentials_from_env(AuthMethod::SqlServer).is_none());
247        assert!(credentials_from_env(AuthMethod::AzureAd).is_none());
248    }
249
250    #[tokio::test]
251    async fn credentials_falls_back_past_seeded_credentials_that_fail_validation() {
252        // An empty username/password pair is seeded (fails
253        // `validate_credentials`), so `credentials()` must not just return
254        // it -- it should fall through to the env/stored-credential cascade
255        // and, finding nothing there either in this test environment,
256        // surface `NoActiveCredentials` rather than the invalid seeded pair.
257        let mut manager = AuthManager::new(AuthMethod::SqlServer);
258        let mut credentials = Credentials::new();
259        credentials.insert("username".to_string(), String::new());
260        credentials.insert("password".to_string(), String::new());
261        manager.set_credentials(credentials);
262        assert!(manager.credentials().await.is_err());
263    }
264}