agentmux_srv_core/identity/
key_validator.rs1use std::sync::OnceLock;
16use std::time::Duration;
17
18use serde_json::json;
19
20#[derive(Debug, Clone)]
24pub struct ValidationOutcome {
25 pub valid: bool,
26 pub metadata: serde_json::Value,
27 pub masked_tail: String,
28 pub error: Option<String>,
29}
30
31impl ValidationOutcome {
32 fn invalid(masked_tail: String, error: impl Into<String>) -> Self {
33 Self {
34 valid: false,
35 metadata: json!({}),
36 masked_tail,
37 error: Some(error.into()),
38 }
39 }
40}
41
42pub fn masked_tail(secret: &str) -> String {
46 let n = secret.chars().count();
47 if n <= 4 {
48 return "•".repeat(n.max(4));
49 }
50 let tail: String = secret.chars().skip(n - 4).collect();
51 format!("••••••••{tail}")
52}
53
54pub(crate) fn client() -> &'static reqwest::Client {
58 static C: OnceLock<reqwest::Client> = OnceLock::new();
59 C.get_or_init(|| {
60 crate::http_client::client_with(|b| b.timeout(Duration::from_secs(15)).user_agent("AgentMux"))
61 })
62}
63
64pub async fn validate(provider: &str, key: &str) -> ValidationOutcome {
70 let token = zeroize::Zeroizing::new(crate::identity::oauth_tokens::bearer_value(key.to_string()));
71 let key = token.as_str();
72 let tail = masked_tail(key);
73 match provider {
74 "github" => github(key, tail).await,
75 "google" => google(key, tail).await,
76 "openai" => openai(key, tail).await,
77 "anthropic" => anthropic(key, tail).await,
78 "slack" => slack(key, tail).await,
79 other => ValidationOutcome::invalid(
80 tail,
81 format!("no validator for provider '{other}' — save without validating"),
82 ),
83 }
84}
85
86async fn github(key: &str, tail: String) -> ValidationOutcome {
87 let resp = match client()
88 .get("https://api.github.com/user")
89 .header("Authorization", format!("Bearer {key}"))
90 .header("Accept", "application/vnd.github+json")
91 .send()
92 .await
93 {
94 Ok(r) => r,
95 Err(e) => return ValidationOutcome::invalid(tail, format!("network error: {e}")),
96 };
97 if !resp.status().is_success() {
98 return ValidationOutcome::invalid(tail, format!("GitHub rejected the token ({})", resp.status()));
99 }
100 let scopes = resp
102 .headers()
103 .get("x-oauth-scopes")
104 .and_then(|v| v.to_str().ok())
105 .map(|s| {
106 s.split(',')
107 .map(|p| p.trim().to_string())
108 .filter(|p| !p.is_empty())
109 .collect::<Vec<_>>()
110 })
111 .unwrap_or_default();
112 let body: serde_json::Value = resp.json().await.unwrap_or_else(|_| json!({}));
113 let login = body.get("login").and_then(|v| v.as_str()).unwrap_or("");
114 ValidationOutcome {
115 valid: true,
116 metadata: json!({ "github_username": login, "github_scopes": scopes }),
117 masked_tail: tail,
118 error: None,
119 }
120}
121
122pub const GOOGLE_USERINFO_URL: &str = "https://openidconnect.googleapis.com/v1/userinfo";
125
126async fn google(key: &str, tail: String) -> ValidationOutcome {
127 use crate::identity::oauth_tokens::OAuthHttp as _;
128 match crate::identity::oauth_tokens::LiveHttp.get_bearer(GOOGLE_USERINFO_URL, key).await {
129 Ok(reply) => google_outcome(reply.status, &reply.body, tail),
130 Err(e) => ValidationOutcome::invalid(tail, format!("network error: {e}")),
131 }
132}
133
134fn google_outcome(status: u16, body: &serde_json::Value, tail: String) -> ValidationOutcome {
137 if status == 401 {
138 return ValidationOutcome::invalid(tail, "Google rejected the token (401): it expired or was revoked");
139 }
140 if !(200..300).contains(&status) {
141 return ValidationOutcome::invalid(tail, format!("Google rejected the token ({status})"));
142 }
143 let email = body.get("email").and_then(|v| v.as_str()).unwrap_or("");
144 let verified = body.get("email_verified").and_then(|v| v.as_bool()).unwrap_or(false);
145 ValidationOutcome {
146 valid: true,
147 metadata: json!({ "email": email, "google_email": email, "email_verified": verified }),
148 masked_tail: tail,
149 error: None,
150 }
151}
152
153async fn openai(key: &str, tail: String) -> ValidationOutcome {
154 let resp = match client()
155 .get("https://api.openai.com/v1/models")
156 .header("Authorization", format!("Bearer {key}"))
157 .send()
158 .await
159 {
160 Ok(r) => r,
161 Err(e) => return ValidationOutcome::invalid(tail, format!("network error: {e}")),
162 };
163 if !resp.status().is_success() {
164 return ValidationOutcome::invalid(tail, format!("OpenAI rejected the key ({})", resp.status()));
165 }
166 let body: serde_json::Value = resp.json().await.unwrap_or_else(|_| json!({}));
167 let model_count = body.get("data").and_then(|v| v.as_array()).map(|a| a.len()).unwrap_or(0);
168 ValidationOutcome {
169 valid: true,
170 metadata: json!({ "openai_model_count": model_count }),
171 masked_tail: tail,
172 error: None,
173 }
174}
175
176async fn anthropic(key: &str, tail: String) -> ValidationOutcome {
177 let resp = match client()
178 .get("https://api.anthropic.com/v1/models")
179 .header("x-api-key", key)
180 .header("anthropic-version", "2023-06-01")
181 .send()
182 .await
183 {
184 Ok(r) => r,
185 Err(e) => return ValidationOutcome::invalid(tail, format!("network error: {e}")),
186 };
187 if !resp.status().is_success() {
188 return ValidationOutcome::invalid(tail, format!("Anthropic rejected the key ({})", resp.status()));
189 }
190 let body: serde_json::Value = resp.json().await.unwrap_or_else(|_| json!({}));
191 let model_count = body.get("data").and_then(|v| v.as_array()).map(|a| a.len()).unwrap_or(0);
192 ValidationOutcome {
193 valid: true,
194 metadata: json!({ "anthropic_model_count": model_count }),
195 masked_tail: tail,
196 error: None,
197 }
198}
199
200async fn slack(key: &str, tail: String) -> ValidationOutcome {
201 let resp = match client()
202 .post("https://slack.com/api/auth.test")
203 .header("Authorization", format!("Bearer {key}"))
204 .send()
205 .await
206 {
207 Ok(r) => r,
208 Err(e) => return ValidationOutcome::invalid(tail, format!("network error: {e}")),
209 };
210 let body: serde_json::Value = match resp.json().await {
211 Ok(v) => v,
212 Err(e) => return ValidationOutcome::invalid(tail, format!("bad response: {e}")),
213 };
214 if !body.get("ok").and_then(|v| v.as_bool()).unwrap_or(false) {
216 let err = body.get("error").and_then(|v| v.as_str()).unwrap_or("invalid token");
217 return ValidationOutcome::invalid(tail, format!("Slack rejected the token: {err}"));
218 }
219 let team = body.get("team").and_then(|v| v.as_str()).unwrap_or("");
220 let user = body.get("user").and_then(|v| v.as_str()).unwrap_or("");
221 ValidationOutcome {
222 valid: true,
223 metadata: json!({ "slack_team": team, "slack_user": user }),
224 masked_tail: tail,
225 error: None,
226 }
227}
228
229#[cfg(test)]
230mod tests {
231 use super::*;
232
233 #[test]
234 fn masks_all_but_last_four() {
235 assert_eq!(masked_tail("ghp_abcdef123456"), "••••••••3456");
236 }
237
238 #[test]
239 fn short_keys_fully_masked_no_tail_leak() {
240 assert_eq!(masked_tail("ab"), "••••");
241 assert_eq!(masked_tail("abcd"), "••••");
242 }
243
244 #[test]
245 fn google_userinfo_gives_the_email() {
246 let body = json!({ "sub": "1", "email": "me@example.com", "email_verified": true });
247 let ok = google_outcome(200, &body, "t".into());
248 assert!(ok.valid);
249 assert_eq!(ok.metadata["email"], "me@example.com");
250 assert_eq!(ok.metadata["google_email"], "me@example.com");
251 assert_eq!(ok.metadata["email_verified"], true);
252 let expired = google_outcome(401, &json!({ "error": "invalid_token" }), "t".into());
253 assert!(!expired.valid && expired.error.unwrap().contains("401"));
254 assert!(!google_outcome(503, &json!({}), "t".into()).valid);
255 }
256}