1use crate::*;
2use base64::{
3 Engine,
4 engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD},
5};
6use rusqlite::{Connection, OpenFlags, OptionalExtension};
7use sha2::{Digest, Sha256};
8use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
9
10const CATALOGS: &[(&str, &str, &[&str])] = &[
11 ("computer", "Computers", &["computer:read", "computer:control", "computer:create", "offline_access"]),
12 (
13 "observability",
14 "Logs and traces",
15 &["observability:read", "offline_access"],
16 ),
17 (
18 "shale",
19 "Shale",
20 &["shale:read", "shale:write", "offline_access"],
21 ),
22];
23
24/// Agents keep the access token their session started with, so it lives while used rather
25/// than for the hour clients are told to renew within.
26const ACCESS_IDLE: i64 = 7 * 86400;
27
28pub struct Store {
29 pub(crate) db: Mutex<Connection>,
30 pub origin: url::Url,
31}
32pub(crate) fn secret() -> String {
33 URL_SAFE_NO_PAD.encode(rand::random::<[u8; 32]>())
34}
35pub(crate) fn hash(value: &str) -> String {
36 format!("{:x}", Sha256::digest(value.as_bytes()))
37}
38pub(crate) fn get(db: &Connection, key: &str) -> Result<Value> {
39 let row: Option<String> = db
40 .query_row(
41 "SELECT value FROM records WHERE key=? AND (expires=0 OR expires>?)",
42 rusqlite::params![key, now() as i64],
43 |r| r.get(0),
44 )
45 .optional()?;
46 Ok(row
47 .map(|s| serde_json::from_str(&s))
48 .transpose()?
49 .unwrap_or(Value::Null))
50}
51pub(crate) fn put(db: &Connection, key: &str, value: &Value, ttl: i64) -> Result<()> {
52 db.execute(
53 "DELETE FROM records WHERE expires>0 AND expires<=?",
54 [now() as i64],
55 )?;
56 let count: i64 = db.query_row("SELECT count(*) FROM records", [], |r| r.get(0))?;
57 if count >= 16384 && get(db, key)?.is_null() {
58 return Err(Error::new(
59 503,
60 "The connection store is full. Remove an unused connection and retry.",
61 ));
62 }
63 db.execute(
64 "INSERT OR REPLACE INTO records VALUES (?,?,?)",
65 rusqlite::params![
66 key,
67 value.to_string(),
68 if ttl == 0 { 0 } else { now() as i64 + ttl }
69 ],
70 )?;
71 Ok(())
72}
73pub(crate) fn delete(db: &Connection, key: &str) -> Result<()> {
74 db.execute("DELETE FROM records WHERE key=?", [key])?;
75 Ok(())
76}
77pub(crate) fn revoke(db: &Connection, grant: &str) -> Result<()> {
78 db.execute(
79 "DELETE FROM records WHERE key=? OR json_extract(value,'$.grant')=?",
80 rusqlite::params![format!("grant:{grant}"), grant],
81 )?;
82 Ok(())
83}
84pub(crate) fn list(db: &Connection, prefix: &str) -> Result<Vec<Value>> {
85 let mut query = db.prepare(
86 "SELECT value FROM records WHERE substr(key,1,?)=? AND (expires=0 OR expires>?)",
87 )?;
88 let rows = query.query_map(rusqlite::params![prefix.len(), prefix, now() as i64], |r| {
89 r.get::<_, String>(0)
90 })?;
91 rows.map(|r| Ok(serde_json::from_str(&r?)?)).collect()
92}
93fn fail(code: &str) -> Error {
94 Error::new(400, code)
95}
96fn redirect(value: &str) -> Result<url::Url> {
97 let url = url::Url::parse(value).map_err(|_| fail("invalid_redirect_uri"))?;
98 let loopback = matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "[::1]"));
99 if value.len() > 4096
100 || !url.username().is_empty()
101 || url.password().is_some()
102 || url.fragment().is_some()
103 || url.host_str().is_none()
104 || !(url.scheme() == "https" || url.scheme() == "http" && loopback)
105 {
106 return Err(fail("invalid_redirect_uri"));
107 }
108 Ok(url)
109}
110impl Store {
111 pub fn new(data: &std::path::Path, origin: &str) -> Result<Self> {
112 let origin = url::Url::parse(origin)?;
113 if origin.path() != "/"
114 || origin.query().is_some()
115 || origin.fragment().is_some()
116 || !origin.username().is_empty()
117 || origin.password().is_some()
118 || origin.scheme() != "https"
119 && !(origin.scheme() == "http"
120 && matches!(origin.host_str(), Some("localhost" | "127.0.0.1" | "[::1]")))
121 {
122 return Err(fail("Set an HTTPS origin for MCP connections."));
123 }
124 std::fs::DirBuilder::new()
125 .recursive(true)
126 .mode(0o700)
127 .create(data)?;
128 let path = data.join("connections.sqlite");
129 let db = Connection::open_with_flags(
130 &path,
131 OpenFlags::SQLITE_OPEN_READ_WRITE
132 | OpenFlags::SQLITE_OPEN_CREATE
133 | OpenFlags::SQLITE_OPEN_NOFOLLOW,
134 )?;
135 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
136 db.execute_batch("PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; CREATE TABLE IF NOT EXISTS records (key TEXT PRIMARY KEY, value TEXT NOT NULL, expires INTEGER NOT NULL);")?;
137 Ok(Self {
138 db: Mutex::new(db),
139 origin,
140 })
141 }
142 pub fn resource(&self, catalog: &str) -> String {
143 self.origin
144 .join(&format!("mcp/{catalog}"))
145 .unwrap()
146 .to_string()
147 }
148 fn client(
149 &self,
150 db: &Connection,
151 input: &HashMap<String, String>,
152 headers: &HeaderMap,
153 ) -> Result<Value> {
154 let basic = headers.get("authorization").and_then(|v| v.to_str().ok());
155 let (id, credential) = if let Some(basic) = basic {
156 if input.contains_key("client_secret") {
157 return Err(fail("invalid_client"));
158 }
159 let bytes = STANDARD
160 .decode(
161 basic
162 .strip_prefix("Basic ")
163 .ok_or_else(|| fail("invalid_client"))?,
164 )
165 .map_err(|_| fail("invalid_client"))?;
166 let value = String::from_utf8(bytes).map_err(|_| fail("invalid_client"))?;
167 let (id, credential) = value
168 .split_once(':')
169 .ok_or_else(|| fail("invalid_client"))?;
170 (id.to_owned(), Some(credential.to_owned()))
171 } else {
172 (
173 input.get("client_id").cloned().unwrap_or_default(),
174 input.get("client_secret").cloned(),
175 )
176 };
177 if input.get("client_id").is_some_and(|v| v != &id) {
178 return Err(fail("invalid_client"));
179 }
180 let client = get(db, &format!("client:{id}"))?;
181 let method = string(&client["token_endpoint_auth_method"]);
182 let valid = match method {
183 "none" => basic.is_none() && credential.is_none(),
184 "client_secret_basic" => {
185 basic.is_some()
186 && credential.as_ref().is_some_and(|v| {
187 hash(v)
188 .as_bytes()
189 .ct_eq(string(&client["secret_hash"]).as_bytes())
190 .unwrap_u8()
191 == 1
192 })
193 }
194 "client_secret_post" => {
195 basic.is_none()
196 && credential.as_ref().is_some_and(|v| {
197 hash(v)
198 .as_bytes()
199 .ct_eq(string(&client["secret_hash"]).as_bytes())
200 .unwrap_u8()
201 == 1
202 })
203 }
204 _ => false,
205 };
206 if valid {
207 Ok(client)
208 } else {
209 Err(fail("invalid_client"))
210 }
211 }
212 fn issue(&self, db: &Connection, grant: &Value) -> Result<Value> {
213 let access = secret();
214 put(
215 db,
216 &format!("access:{}", hash(&access)),
217 &json!({"grant":grant["id"],"resource":grant["resource"]}),
218 ACCESS_IDLE,
219 )?;
220 let mut response = json!({"access_token":access,"token_type":"Bearer","expires_in":3600,"scope":array(&grant["scopes"]).iter().map(string).collect::<Vec<_>>().join(" ")});
221 if array(&grant["scopes"])
222 .iter()
223 .any(|s| s == "offline_access")
224 {
225 let refresh = secret();
226 put(
227 db,
228 &format!("refresh:{}", hash(&refresh)),
229 &json!({"grant":grant["id"]}),
230 30 * 86400,
231 )?;
232 response["refresh_token"] = json!(refresh);
233 }
234 Ok(response)
235 }
236 pub fn authenticate(&self, headers: &HeaderMap, resource: &str) -> Result<Value> {
237 let token = headers
238 .get("authorization")
239 .and_then(|v| v.to_str().ok())
240 .and_then(|s| s.strip_prefix("Bearer "))
241 .filter(|s| !s.is_empty() && s.len() <= 256)
242 .ok_or_else(|| Error::new(401, "invalid_token"))?;
243 let db = self.db.lock().unwrap();
244 let key = format!("access:{}", hash(token));
245 let access = get(&db, &key)?;
246 let grant = get(&db, &format!("grant:{}", string(&access["grant"])))?;
247 if grant.is_null() || access["resource"] != resource || grant["resource"] != resource {
248 return Err(Error::new(401, "invalid_token"));
249 }
250 let expires = now() as i64 + ACCESS_IDLE;
251 db.execute(
252 "UPDATE records SET expires=? WHERE key=? AND expires<?",
253 rusqlite::params![expires, key, expires - 3600],
254 )?;
255 Ok(grant)
256 }
257 fn exchange(
258 &self,
259 db: &Connection,
260 input: &HashMap<String, String>,
261 headers: &HeaderMap,
262 ) -> Result<(String, Value)> {
263 let client = self.client(db, input, headers)?;
264 let (key, grant) = match input.get("grant_type").map(String::as_str) {
265 Some("authorization_code") => {
266 let key = format!(
267 "code:{}",
268 hash(input.get("code").map(String::as_str).unwrap_or_default())
269 );
270 let code = get(db, &key)?;
271 let verifier = input
272 .get("code_verifier")
273 .map(String::as_str)
274 .unwrap_or_default();
275 if code.is_null()
276 || code["client"] != client["client_id"]
277 || input.get("redirect_uri").map(String::as_str) != code["redirect"].as_str()
278 || !(43..=128).contains(&verifier.len())
279 || !verifier
280 .bytes()
281 .all(|b| b.is_ascii_alphanumeric() || b"-._~".contains(&b))
282 || URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()))
283 != string(&code["challenge"])
284 {
285 return Err(fail("invalid_grant"));
286 }
287 if input
288 .get("resource")
289 .is_some_and(|r| code["resource"] != r.as_str())
290 {
291 return Err(fail("invalid_target"));
292 }
293 let grant = get(db, &format!("grant:{}", string(&code["grant"])))?;
294 if grant.is_null() {
295 return Err(fail("invalid_grant"));
296 }
297 (key, grant)
298 }
299 Some("refresh_token") => {
300 let fingerprint = hash(
301 input
302 .get("refresh_token")
303 .map(String::as_str)
304 .unwrap_or_default(),
305 );
306 let key = format!("refresh:{fingerprint}");
307 let token = get(db, &key)?;
308 let used = get(db, &format!("used:{fingerprint}"))?;
309 if !used.is_null() {
310 let grant = get(db, &format!("grant:{}", string(&used["grant"])))?;
311 if grant["client"] == client["client_id"] {
312 revoke(db, string(&used["grant"]))?;
313 }
314 return Err(fail("invalid_grant"));
315 }
316 let grant = get(db, &format!("grant:{}", string(&token["grant"])))?;
317 if grant.is_null() || grant["client"] != client["client_id"] {
318 return Err(fail("invalid_grant"));
319 }
320 if input
321 .get("resource")
322 .is_some_and(|r| grant["resource"] != r.as_str())
323 {
324 return Err(fail("invalid_target"));
325 }
326 if input.get("scope").is_some_and(|s| {
327 s.split_whitespace()
328 .collect::<std::collections::HashSet<_>>()
329 != array(&grant["scopes"]).iter().map(string).collect()
330 }) {
331 return Err(fail("invalid_scope"));
332 }
333 (key, grant)
334 }
335 _ => return Err(fail("unsupported_grant_type")),
336 };
337 if !CATALOGS
338 .iter()
339 .any(|(id, _, _)| grant["resource"] == self.resource(id))
340 {
341 return Err(fail("invalid_grant"));
342 }
343 Ok((key, grant))
344 }
345 fn oauth(
346 &self,
347 path: &str,
348 method: &Method,
349 input: &HashMap<String, String>,
350 headers: &HeaderMap,
351 body: Value,
352 ) -> Result<Response> {
353 let mut db = self.db.lock().unwrap();
354 let tx = db.transaction()?;
355 let value = match (path, method) {
356 ("register", &Method::POST) => {
357 let name = body["client_name"]
358 .as_str()
359 .filter(|s| !s.is_empty() && s.len() <= 128)
360 .ok_or_else(|| fail("invalid_client_metadata"))?;
361 let uris = body["redirect_uris"]
362 .as_array()
363 .filter(|a| !a.is_empty() && a.len() <= 8)
364 .ok_or_else(|| fail("invalid_client_metadata"))?;
365 for uri in uris {
366 redirect(uri.as_str().ok_or_else(|| fail("invalid_redirect_uri"))?)?;
367 }
368 let auth = body["token_endpoint_auth_method"]
369 .as_str()
370 .unwrap_or("none");
371 if !["none", "client_secret_post", "client_secret_basic"].contains(&auth)
372 || body.get("grant_types").is_some_and(|v| {
373 v.as_array().is_none_or(|types| {
374 types.is_empty()
375 || types
376 .iter()
377 .any(|s| s != "authorization_code" && s != "refresh_token")
378 })
379 })
380 || body
381 .get("response_types")
382 .is_some_and(|v| v != &json!(["code"]))
383 {
384 return Err(fail("invalid_client_metadata"));
385 }
386 if list(&tx, "client:")?.len() >= 4096 {
387 return Err(Error::new(429, "too_many_clients"));
388 }
389 let id = uuid::Uuid::new_v4().to_string();
390 let credential = secret();
391 let mut client = json!({"client_id":id,"client_name":name,"redirect_uris":uris,"token_endpoint_auth_method":auth,"grant_types":["authorization_code","refresh_token"],"response_types":["code"],"client_id_issued_at":now() as i64});
392 if auth != "none" {
393 client["secret_hash"] = json!(hash(&credential));
394 }
395 put(&tx, &format!("client:{id}"), &client, 0)?;
396 client.as_object_mut().unwrap().remove("secret_hash");
397 if auth != "none" {
398 client["client_secret"] = json!(credential);
399 client["client_secret_expires_at"] = json!(0);
400 }
401 tx.commit()?;
402 return Ok((StatusCode::CREATED, axum::Json(client)).into_response());
403 }
404 ("authorize", &Method::GET) => {
405 let id = input
406 .get("client_id")
407 .map(String::as_str)
408 .unwrap_or_default();
409 let client = get(&tx, &format!("client:{id}"))?;
410 let uri = input
411 .get("redirect_uri")
412 .map(String::as_str)
413 .unwrap_or_default();
414 let challenge = input
415 .get("code_challenge")
416 .map(String::as_str)
417 .unwrap_or_default();
418 let resource = input
419 .get("resource")
420 .map(String::as_str)
421 .unwrap_or_default();
422 let scopes_allowed = CATALOGS
423 .iter()
424 .find(|(id, _, _)| resource == self.resource(id))
425 .map(|(_, _, scopes)| *scopes)
426 .ok_or_else(|| fail("invalid_target"))?;
427 let scopes: Vec<_> = input
428 .get("scope")
429 .map(String::as_str)
430 .unwrap_or(scopes_allowed[0])
431 .split_whitespace()
432 .collect();
433 if client.is_null() || !array(&client["redirect_uris"]).iter().any(|v| v == uri) {
434 return Err(fail("invalid_redirect_uri"));
435 }
436 if input.get("response_type").map(String::as_str) != Some("code")
437 || input.get("code_challenge_method").map(String::as_str) != Some("S256")
438 || challenge.len() != 43
439 || !challenge
440 .bytes()
441 .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
442 {
443 return Err(fail("invalid_request"));
444 }
445 if !scopes.contains(&scopes_allowed[0])
446 || scopes.iter().any(|scope| !CATALOGS.iter().any(|(_, _, allowed)| allowed.contains(scope)))
447 {
448 return Err(fail("invalid_scope"));
449 }
450 let scopes: Vec<_> = scopes.into_iter().filter(|scope| scopes_allowed.contains(scope)).collect();
451 let pending = secret();
452 put(
453 &tx,
454 &format!("pending:{}", hash(&pending)),
455 &json!({"client":id,"redirect":uri,"challenge":challenge,"resource":resource,"scopes":scopes,"state":input.get("state"),"owner":null}),
456 600,
457 )?;
458 tx.commit()?;
459 return Ok((
460 StatusCode::FOUND,
461 [("location", format!("/connect/{}", encoded(&pending)))],
462 )
463 .into_response());
464 }
465 ("token", &Method::POST) => {
466 let (key, grant) = match self.exchange(&tx, input, headers) {
467 Ok(exchange) => exchange,
468 Err(error) => {
469 tx.commit()?;
470 return Err(error);
471 }
472 };
473 delete(&tx, &key)?;
474 if let Some(fingerprint) = key.strip_prefix("refresh:") {
475 put(
476 &tx,
477 &format!("used:{fingerprint}"),
478 &json!({"grant":grant["id"]}),
479 30 * 86400,
480 )?;
481 }
482 self.issue(&tx, &grant)?
483 }
484 ("revoke", &Method::POST) => {
485 let client = self.client(&tx, input, headers)?;
486 let fingerprint = hash(input.get("token").map(String::as_str).unwrap_or_default());
487 for kind in ["access", "refresh", "used"] {
488 let token = get(&tx, &format!("{kind}:{fingerprint}"))?;
489 let grant = get(&tx, &format!("grant:{}", string(&token["grant"])))?;
490 if !grant.is_null() && grant["client"] == client["client_id"] {
491 revoke(&tx, string(&grant["id"]))?;
492 }
493 }
494 tx.commit()?;
495 return Ok(StatusCode::OK.into_response());
496 }
497 _ => return Err(Error::new(404, "No endpoint here.")),
498 };
499 tx.commit()?;
500 Ok(axum::Json(value).into_response())
501 }
502}
503
504#[derive(Clone)]
505pub(crate) struct Grant(pub Value);
506pub(crate) fn active_owner(app: &App, grant: &Value) -> Result<bool> {
507 let profile = match auth::user(&app.auth.db.lock().unwrap(), string(&grant["user"])) {
508 Ok(profile) => profile,
509 Err(error) if error.status == 404 => return Ok(false),
510 Err(error) => return Err(error),
511 };
512 Ok(profile["enabled"] == true
513 && !guest::is_guest(&profile)
514 && (grant["resource"] != app.mcp.resource("computer")
515 || array(&profile["groups"]).iter().any(|role| matches!(role["name"].as_str(), Some("vm" | "infra-admin"))))
516 && (grant["resource"] != app.mcp.resource("observability")
517 || array(&profile["groups"])
518 .iter()
519 .any(|role| role["name"] == "infra-admin")))
520}
521pub fn router<H: rmcp::ServerHandler>(
522 app: Arc<App>,
523 catalog: &str,
524 handler: impl Fn() -> std::result::Result<H, std::io::Error> + Send + Sync + 'static,
525) -> Router {
526 use rmcp::transport::streamable_http_server::{
527 StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager,
528 };
529 let resource = app.mcp.resource(catalog);
530 let metadata = format!(
531 "{}.well-known/oauth-protected-resource/mcp/{catalog}",
532 app.mcp.origin.as_str()
533 );
534 let mut config = StreamableHttpServerConfig::default();
535 config.legacy_session_mode = false;
536 config.json_response = true;
537 config.allowed_hosts =
538 vec![app.mcp.origin[url::Position::BeforeHost..url::Position::AfterPort].to_owned()];
539 config.allowed_origins = vec![format!(
540 "{}://{}:{}",
541 app.mcp.origin.scheme(),
542 app.mcp.origin.host_str().unwrap(),
543 app.mcp.origin.port_or_known_default().unwrap()
544 )];
545 let service =
546 StreamableHttpService::new(handler, Arc::new(LocalSessionManager::default()), config);
547 Router::new()
548 .nest_service(&format!("/mcp/{catalog}"), service)
549 .layer(axum::middleware::from_fn(
550 move |mut request: Request, next: axum::middleware::Next| {
551 let (app, resource, metadata) = (app.clone(), resource.clone(), metadata.clone());
552 async move {
553 if request.headers().get("origin").is_some_and(|origin| {
554 origin.to_str().ok()
555 != Some(app.mcp.origin.origin().ascii_serialization().as_str())
556 }) {
557 return Error::new(403, "This origin cannot use the connector.")
558 .into_response();
559 }
560 match app
561 .mcp
562 .authenticate(request.headers(), &resource)
563 .and_then(|grant| {
564 if active_owner(&app, &grant)? {
565 Ok(grant)
566 } else {
567 Err(Error::new(401, "invalid_token"))
568 }
569 }) {
570 Ok(grant) => {
571 request.extensions_mut().insert(Grant(grant));
572 if let Some(value) = request.headers_mut().get_mut("authorization") {
573 value.set_sensitive(true);
574 }
575 next.run(request).await
576 }
577 Err(error) if error.status != 401 => error.into_response(),
578 Err(_) => (
579 StatusCode::UNAUTHORIZED,
580 [(
581 "www-authenticate",
582 format!("Bearer resource_metadata=\"{metadata}\""),
583 )],
584 "This connection expired. Connect again.",
585 )
586 .into_response(),
587 }
588 }
589 },
590 ))
591}
592
593pub async fn discovery(State(app): State<Arc<App>>) -> axum::Json<Value> {
594 axum::Json(json!({
595 "version": "1.0",
596 "servers": CATALOGS.iter().map(|(id, name, scopes)| json!({
597 "name": id,
598 "description": name,
599 "url": app.mcp.resource(id),
600 "transport": "streamable-http",
601 "authentication": {
602 "type": "oauth2",
603 "required": true,
604 "authorization_url": app.mcp.origin.join("oauth/authorize").unwrap().as_str(),
605 "scopes": scopes,
606 },
607 "capabilities": ["tools"],
608 })).collect::<Vec<_>>(),
609 "registry": {"name": "Snow Globe", "version": env!("CARGO_PKG_VERSION")},
610 }))
611}
612
613pub fn public(path: &str) -> bool {
614 path == "/.well-known/openid-configuration"
615 || path == "/.well-known/mcp-servers"
616 || path.starts_with("/oauth/")
617 || CATALOGS.iter().any(|(id, _, _)| {
618 path == format!("/mcp/{id}") || path.starts_with(&format!("/mcp/{id}/"))
619 })
620 || path.starts_with("/.well-known/oauth-")
621}
622pub async fn oauth(State(app): State<Arc<App>>, request: Request) -> Response {
623 if request.uri().path().starts_with("/oauth/shale/") {
624 return shale::oauth(app, request).await;
625 }
626 let result = async {
627 let path = request.uri().path().to_owned();
628 if path=="/.well-known/oauth-authorization-server" && request.method()==Method::GET {
629 let base = app.mcp.origin.as_str();
630 let scopes: std::collections::BTreeSet<_> = CATALOGS.iter().flat_map(|(_, _, scopes)| scopes.iter()).collect();
631 return Ok(axum::Json(json!({"issuer":base,"authorization_endpoint":format!("{base}oauth/authorize"),"token_endpoint":format!("{base}oauth/token"),"registration_endpoint":format!("{base}oauth/register"),"revocation_endpoint":format!("{base}oauth/revoke"),"response_types_supported":["code"],"grant_types_supported":["authorization_code","refresh_token"],"token_endpoint_auth_methods_supported":["none","client_secret_post","client_secret_basic"],"code_challenge_methods_supported":["S256"],"scopes_supported":scopes})).into_response());
632 }
633 if request.method() == Method::GET {
634 for (catalog, _, scopes) in CATALOGS {
635 if path == format!("/.well-known/oauth-protected-resource/mcp/{catalog}") {
636 return Ok(axum::Json(json!({"resource":app.mcp.resource(catalog),"authorization_servers":[app.mcp.origin.as_str()],"scopes_supported":scopes,"bearer_methods_supported":["header"]})).into_response());
637 }
638 }
639 }
640 let method = request.method().clone();
641 let headers = request.headers().clone();
642 let query = request.uri().query().unwrap_or_default().to_owned();
643 let bytes = axum::body::to_bytes(request.into_body(),65536).await.map_err(|_| fail("invalid_request"))?;
644 let registration = path=="/oauth/register";
645 let encoded = if method==Method::GET {query.as_bytes()} else {&bytes};
646 if method==Method::POST && !headers.get("content-type").and_then(|v|v.to_str().ok()).is_some_and(|s| s.split(';').next()==Some(if registration {"application/json"} else {"application/x-www-form-urlencoded"})) { return Err(fail("invalid_request")); }
647 let mut input = HashMap::new();
648 if !registration { for (key,value) in url::form_urlencoded::parse(encoded) { if input.insert(key.into_owned(),value.into_owned()).is_some() {return Err(fail("invalid_request"));} } }
649 let body = if registration {serde_json::from_slice(&bytes).map_err(|_| fail("invalid_client_metadata"))?} else {Value::Null};
650 if path == "/oauth/token" && method == Method::POST {
651 let (_, grant) = app.mcp.exchange(&app.mcp.db.lock().unwrap(), &input, &headers)?;
652 if !active_owner(&app, &grant)? {
653 revoke(&app.mcp.db.lock().unwrap(), string(&grant["id"]))?;
654 return Err(fail("invalid_grant"));
655 }
656 }
657 app.mcp.oauth(path.trim_start_matches("/oauth/"),&method,&input,&headers,body)
658 }.await;
659 let mut response = match result {
660 Ok(response) => response,
661 Err(error) => (
662 StatusCode::from_u16(if error.message == "invalid_client" {
663 401
664 } else {
665 error.status
666 })
667 .unwrap_or(StatusCode::BAD_REQUEST),
668 axum::Json(
669 json!({"error":if error.status >= 500 {"server_error"} else {&error.message}}),
670 ),
671 )
672 .into_response(),
673 };
674 response
675 .headers_mut()
676 .insert("cache-control", "no-store".parse().unwrap());
677 response
678 .headers_mut()
679 .insert("pragma", "no-cache".parse().unwrap());
680 response
681}
682
683fn chosen_resources(body: &Value, resources: &[Value], shale: bool, allow_empty: bool) -> Result<Value> {
684 if shale && body["resources"] == "all" {
685 return Ok(json!("all"));
686 }
687 let chosen = body["resources"]
688 .as_array()
689 .filter(|items| (allow_empty || !items.is_empty()) && items.len() <= resources.len())
690 .ok_or_else(|| Error::new(400, "Choose each available resource once."))?;
691 if chosen.iter().enumerate().any(|(index, item)| {
692 !resources.iter().any(|resource| item == &resource["id"]) || chosen[..index].contains(item)
693 }) {
694 return Err(Error::new(
695 403,
696 "Choose resources available to your account.",
697 ));
698 }
699 Ok(json!(chosen))
700}
701
702pub async fn manage(
703 app: Arc<App>,
704 method: &Method,
705 parts: &[&str],
706 me: &Value,
707 body: Value,
708 headers: &HeaderMap,
709) -> Result<Response> {
710 if method != Method::GET
711 && (me["viewing"] == true
712 || headers.get("origin").and_then(|h| h.to_str().ok())
713 != Some(app.mcp.origin.origin().ascii_serialization().as_str()))
714 {
715 return Err(Error::new(
716 403,
717 "Open MCP settings from your own signed-in account.",
718 ));
719 }
720 let owner = users::self_user(&app, me).await?;
721 if owner["enabled"] != true {
722 return Err(Error::new(403, "This account is disabled."));
723 }
724 let owner_id = string(&owner["id"]);
725 if parts == ["shale"] {
726 return shale::manage(app, method, &owner, &body).await;
727 }
728 let consent_resource = if let ["connections", id] = parts
729 && method != Method::DELETE
730 {
731 let grant = get(&app.mcp.db.lock().unwrap(), &format!("grant:{id}"))?;
732 if grant["user"] != owner_id {
733 return Err(Error::new(404, "No connection with that ID."));
734 }
735 string(&grant["resource"]).to_owned()
736 } else if let ["consent", id] = parts {
737 let pending = get(
738 &app.mcp.db.lock().unwrap(),
739 &format!("pending:{}", hash(id)),
740 )?;
741 if pending.is_null() {
742 return Err(Error::new(
743 404,
744 "This connection request expired. Start it again.",
745 ));
746 }
747 if !pending["owner"].is_null() && pending["owner"] != owner_id {
748 return Err(Error::new(
749 403,
750 "This connection request belongs to another account.",
751 ));
752 }
753 string(&pending["resource"]).to_owned()
754 } else {
755 String::new()
756 };
757 let shale_consent = consent_resource == app.mcp.resource("shale");
758 let catalog = CATALOGS
759 .iter()
760 .find(|(id, _, _)| consent_resource == app.mcp.resource(id))
761 .map(|(id, _, _)| *id);
762 if !consent_resource.is_empty() && catalog.is_none() {
763 return Err(Error::new(404, "No connector here."));
764 }
765 let mut linked = true;
766 let mut resource_error = None;
767 let resources: Vec<Value> = if body["deny"] == true {
768 Vec::new()
769 } else if shale_consent {
770 let available = if body["resources"] == "all" {
771 shale::verified_session(&app, owner_id)
772 .await
773 .map(|_| Vec::new())
774 } else {
775 shale::repositories(&app, owner_id).await
776 };
777 match available {
778 Ok(repositories) => repositories,
779 Err(error) if error.status == 401 => {
780 linked = false;
781 Vec::new()
782 }
783 Err(error) if method == Method::GET => {
784 resource_error = Some(error.message);
785 Vec::new()
786 }
787 Err(error) => return Err(error),
788 }
789 } else if consent_resource == app.mcp.resource("computer")
790 && array(&me["sections"]).iter().any(|s| s == "vms")
791 {
792 computer::resources(&owner).await?
793 } else if consent_resource == app.mcp.resource("observability")
794 && array(&me["sections"]).iter().any(|s| s == "admin")
795 && array(&owner["groups"])
796 .iter()
797 .any(|g| g["name"] == "infra-admin")
798 {
799 core::scan(app.clone())
800 .await?
801 .value
802 .as_object()
803 .unwrap()
804 .keys()
805 .map(|id| json!({"id":id,"name":id}))
806 .collect()
807 } else {
808 Vec::new()
809 };
810 let mut db = app.mcp.db.lock().unwrap();
811 let tx = db.transaction()?;
812 let value = match parts {
813 [] if method == Method::GET => {
814 let mut grants = list(&tx, "grant:")?;
815 grants.retain(|g| g["user"] == owner_id);
816 let connections = grants.iter().filter_map(|grant| {
817 let (catalog, _, _) = CATALOGS.iter().find(|(id, _, _)| grant["resource"] == app.mcp.resource(id))?;
818 Some(get(&tx, &format!("client:{}", string(&grant["client"]))).map(|client| {
819 json!({"id":grant["id"],"name":client["client_name"],"catalog":catalog,"resources":grant["resources"],"scopes":grant["scopes"],"createdAt":grant["createdAt"]})
820 }))
821 }).collect::<Result<Vec<_>>>()?;
822 let shale = get(&tx, &format!("shale-session:{owner_id}"))?;
823 let catalogs: Vec<_> = CATALOGS
824 .iter()
825 .map(|(id, name, _)| json!({"id":id,"name":name,"endpoint":app.mcp.resource(id)}))
826 .collect();
827 json!({"catalogs":catalogs,"connections":connections,"shale":if shale["origin"] != app.shale.origin.as_str() {Value::Null} else {json!({"linkedAt":shale["linkedAt"]})}})
828 }
829 ["consent", id] if method == Method::GET || method == Method::POST => {
830 let key = format!("pending:{}", hash(id));
831 let mut pending = get(&tx, &key)?;
832 if pending.is_null() {
833 return Err(Error::new(
834 404,
835 "This connection request expired. Start it again.",
836 ));
837 }
838 if !pending["owner"].is_null() && pending["owner"] != owner_id {
839 return Err(Error::new(
840 403,
841 "This connection request belongs to another account.",
842 ));
843 }
844 pending["owner"] = json!(owner_id);
845 if method == Method::POST && body["deny"] == true {
846 delete(&tx, &key)?;
847 let mut target = redirect(string(&pending["redirect"]))?;
848 target
849 .query_pairs_mut()
850 .append_pair("error", "access_denied")
851 .append_pair("iss", app.mcp.origin.as_str());
852 if let Some(state) = pending["state"].as_str() {
853 target.query_pairs_mut().append_pair("state", state);
854 }
855 tx.commit()?;
856 return Ok(axum::Json(json!({"redirect":target.as_str()})).into_response());
857 }
858 if method == Method::GET {
859 tx.execute(
860 "UPDATE records SET value=? WHERE key=?",
861 rusqlite::params![pending.to_string(), key],
862 )?;
863 json!({"client":get(&tx,&format!("client:{}",string(&pending["client"])))?["client_name"],"catalog":catalog,"account":owner["username"],"redirectHost":redirect(string(&pending["redirect"]))?.host_str(),"scopes":pending["scopes"],"resources":resources,"linked":linked,"resourceError":resource_error})
864 } else {
865 if shale_consent
866 && (!linked
867 || get(&tx, &format!("shale-session:{owner_id}"))?["origin"]
868 != app.shale.origin.as_str())
869 {
870 return Err(Error::new(
871 401,
872 "Link your Shale account before allowing repository access.",
873 ));
874 }
875 let chosen = chosen_resources(&body, &resources, shale_consent, array(&pending["scopes"]).iter().any(|s| s == "computer:create"))?;
876 if list(&tx, "grant:")?
877 .iter()
878 .filter(|g| g["user"] == owner_id)
879 .count()
880 >= 256
881 {
882 return Err(Error::new(
883 409,
884 "Remove an unused connection before adding another.",
885 ));
886 }
887 let grant_id = uuid::Uuid::new_v4().to_string();
888 let grant = json!({"id":grant_id,"user":owner_id,"client":pending["client"],"resource":pending["resource"],"scopes":pending["scopes"],"resources":chosen,"createdAt":now()});
889 put(&tx, &format!("grant:{grant_id}"), &grant, 0)?;
890 let code = secret();
891 pending["grant"] = json!(grant_id);
892 put(&tx, &format!("code:{}", hash(&code)), &pending, 300)?;
893 delete(&tx, &key)?;
894 let mut target = redirect(string(&pending["redirect"]))?;
895 target
896 .query_pairs_mut()
897 .append_pair("code", &code)
898 .append_pair("iss", app.mcp.origin.as_str());
899 if let Some(state) = pending["state"].as_str() {
900 target.query_pairs_mut().append_pair("state", state);
901 }
902 json!({"redirect":target.as_str()})
903 }
904 }
905 ["connections", id]
906 if method == Method::GET || method == Method::POST || method == Method::DELETE =>
907 {
908 let key = format!("grant:{id}");
909 let mut grant = get(&tx, &key)?;
910 if grant["user"] != owner_id {
911 return Err(Error::new(404, "No connection with that ID."));
912 }
913 if method == Method::DELETE {
914 revoke(&tx, id)?;
915 Value::Null
916 } else if method == Method::GET {
917 json!({"resources": resources, "selected": grant["resources"], "linked": linked,"resourceError":resource_error})
918 } else {
919 if shale_consent && !linked {
920 return Err(Error::new(
921 401,
922 "Link your Shale account before allowing repository access.",
923 ));
924 }
925 let chosen = chosen_resources(&body, &resources, shale_consent, array(&grant["scopes"]).iter().any(|s| s == "computer:create"))?;
926 grant["resources"] = json!(chosen);
927 tx.execute(
928 "UPDATE records SET value=? WHERE key=?",
929 rusqlite::params![grant.to_string(), key],
930 )?;
931 Value::Null
932 }
933 }
934 _ => return Err(Error::new(404, "No endpoint here.")),
935 };
936 tx.commit()?;
937 Ok(if value.is_null() {
938 StatusCode::NO_CONTENT.into_response()
939 } else {
940 axum::Json(value).into_response()
941 })
942}
943
944#[cfg(test)]
945mod tests {
946 #[test]
947 fn resource_updates_reject_empty_duplicates_and_foreign_choices() {
948 let resources = vec![json!({"id":"alpha"}), json!({"id":"beta"})];
949 assert_eq!(
950 chosen_resources(&json!({"resources":["beta"]}), &resources, false, false).unwrap(),
951 json!(["beta"])
952 );
953 for selected in [
954 json!([]),
955 json!(["alpha", "alpha"]),
956 json!(["foreign"]),
957 json!([null]),
958 ] {
959 assert!(chosen_resources(&json!({"resources":selected}), &resources, false, false).is_err());
960 }
961 assert_eq!(
962 chosen_resources(&json!({"resources":"all"}), &[], true, false).unwrap(),
963 json!("all")
964 );
965 assert!(chosen_resources(&json!({"resources":"all"}), &resources, false, false).is_err());
966 assert_eq!(chosen_resources(&json!({"resources":[]}), &resources, false, true).unwrap(), json!([]));
967 assert!(chosen_resources(&json!({"resources":["foreign"]}), &resources, false, true).is_err());
968 }
969
970 use super::*;
971 struct Fixture {
972 store: Arc<Store>,
973 path: std::path::PathBuf,
974 }
975 impl Fixture {
976 fn new() -> Self {
977 let path = std::env::temp_dir()
978 .canonicalize()
979 .unwrap()
980 .join(format!("snowglobe-mcp-test-{}", uuid::Uuid::new_v4()));
981 let store = Arc::new(Store::new(&path, "https://globe.snowglobe.test").unwrap());
982 Self { store, path }
983 }
984 fn code(&self, client: &str, code: &str) -> HashMap<String, String> {
985 let grant = uuid::Uuid::new_v4().to_string();
986 let db = self.store.db.lock().unwrap();
987 put(&db, &format!("client:{client}"), &json!({"client_id":client,"token_endpoint_auth_method":"none","redirect_uris":["http://127.0.0.1:20001/callback"]}),0).unwrap();
988 put(&db, &format!("grant:{grant}"), &json!({"id":grant,"user":"one","client":client,"resource":self.store.resource("observability"),"scopes":["observability:read","offline_access"],"resources":["allowed"]}),0).unwrap();
989 let verifier = "v".repeat(43);
990 put(&db, &format!("code:{}",hash(code)), &json!({"client":client,"redirect":"http://127.0.0.1:20001/callback","challenge":URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())),"resource":self.store.resource("observability"),"grant":grant}),300).unwrap();
991 fields(
992 json!({"grant_type":"authorization_code","client_id":client,"code":code,"code_verifier":verifier,"redirect_uri":"http://127.0.0.1:20001/callback","resource":self.store.resource("observability")}),
993 )
994 }
995 }
996 impl Drop for Fixture {
997 fn drop(&mut self) {
998 std::fs::remove_dir_all(&self.path).unwrap();
999 }
1000 }
1001 fn fields(value: Value) -> HashMap<String, String> {
1002 value
1003 .as_object()
1004 .unwrap()
1005 .iter()
1006 .map(|(k, v)| (k.clone(), string(v).to_owned()))
1007 .collect()
1008 }
1009 async fn value(response: Response) -> Value {
1010 serde_json::from_slice(
1011 &axum::body::to_bytes(response.into_body(), 65536)
1012 .await
1013 .unwrap(),
1014 )
1015 .unwrap()
1016 }
1017 fn bearer(token: &str) -> HeaderMap {
1018 let mut headers = HeaderMap::new();
1019 headers.insert("authorization", format!("Bearer {token}").parse().unwrap());
1020 headers
1021 }
1022 #[test]
1023 fn revocation_removes_durable_keys_and_family_records() {
1024 let fixture = Fixture::new();
1025 let db = fixture.store.db.lock().unwrap();
1026 put(&db, "grant:revoked", &json!({"id":"revoked"}), 0).unwrap();
1027 for kind in ["access", "refresh", "used", "code"] {
1028 put(&db, &format!("{kind}:one"), &json!({"grant":"revoked"}), 0).unwrap();
1029 put(
1030 &db,
1031 &format!("{kind}:other"),
1032 &json!({"grant":"retained"}),
1033 0,
1034 )
1035 .unwrap();
1036 }
1037 revoke(&db, "revoked").unwrap();
1038 assert!(get(&db, "grant:revoked").unwrap().is_null());
1039 for kind in ["access", "refresh", "used", "code"] {
1040 assert!(get(&db, &format!("{kind}:one")).unwrap().is_null());
1041 assert!(!get(&db, &format!("{kind}:other")).unwrap().is_null());
1042 }
1043 }
1044 #[test]
1045 fn access_tokens_live_while_used_and_lapse_when_idle() {
1046 let fixture = Fixture::new();
1047 let resource = fixture.store.resource("computer");
1048 let grant = json!({"id":"live","resource":resource,"scopes":["computer:read"]});
1049 let db = fixture.store.db.lock().unwrap();
1050 put(&db, "grant:live", &grant, 0).unwrap();
1051 let tokens = fixture.store.issue(&db, &grant).unwrap();
1052 assert_eq!(tokens["expires_in"], 3600);
1053 let key = format!("access:{}", hash(string(&tokens["access_token"])));
1054 let expires = |db: &Connection| -> i64 {
1055 db.query_row("SELECT expires FROM records WHERE key=?", [&key], |r| r.get(0)).unwrap()
1056 };
1057 let set = |db: &Connection, at: i64| {
1058 db.execute("UPDATE records SET expires=? WHERE key=?", rusqlite::params![at, key]).unwrap();
1059 };
1060 set(&db, now() as i64 + 60);
1061 drop(db);
1062 let headers = bearer(string(&tokens["access_token"]));
1063 assert!(fixture.store.authenticate(&headers, &resource).is_ok());
1064 assert!(expires(&fixture.store.db.lock().unwrap()) >= now() as i64 + ACCESS_IDLE - 5);
1065 set(&fixture.store.db.lock().unwrap(), now() as i64 - 1);
1066 assert!(fixture.store.authenticate(&headers, &resource).is_err());
1067 }
1068 #[tokio::test]
1069 async fn authorization_restricts_issuer_scopes_to_the_requested_resource() {
1070 let fixture = Fixture::new();
1071 let uri = "http://127.0.0.1:57072/callback/H9rAWI-8eQbv";
1072 let client = value(fixture.store.oauth("register", &Method::POST, &HashMap::new(), &HeaderMap::new(),
1073 json!({"client_name":"Codex","redirect_uris":[uri]})).unwrap()).await;
1074 let mut request = fields(json!({"response_type":"code","client_id":client["client_id"],"state":"fixture-state",
1075 "code_challenge":"AdJpfUsRa6XMg54f2khmgo2onMwePN3vmU9DOOoaTzo","code_challenge_method":"S256",
1076 "redirect_uri":uri,"scope":"observability:read offline_access shale:read shale:write computer:read computer:control"}));
1077 for (catalog, _, allowed) in CATALOGS {
1078 request.insert("resource".into(), fixture.store.resource(catalog));
1079 let response = fixture.store.oauth("authorize", &Method::GET, &request, &HeaderMap::new(), Value::Null).unwrap();
1080 assert_eq!(response.status(), StatusCode::FOUND);
1081 let pending_id = response.headers()["location"].to_str().unwrap().strip_prefix("/connect/").unwrap();
1082 let db = fixture.store.db.lock().unwrap();
1083 let mut pending = get(&db, &format!("pending:{}", hash(pending_id))).unwrap();
1084 let expected: Vec<_> = request["scope"].split_whitespace().filter(|scope| allowed.contains(scope)).collect();
1085 assert_eq!(pending["scopes"], json!(expected));
1086 assert_eq!(pending["redirect"], uri);
1087 assert_eq!(pending["state"], "fixture-state");
1088 pending["id"] = json!(format!("fixture-{catalog}"));
1089 put(&db, &format!("grant:fixture-{catalog}"), &pending, 0).unwrap();
1090 let tokens = fixture.store.issue(&db, &pending).unwrap();
1091 assert_eq!(tokens["scope"], expected.join(" "));
1092 assert!(tokens["refresh_token"].is_string());
1093 drop(db);
1094 let headers = bearer(string(&tokens["access_token"]));
1095 assert!(fixture.store.authenticate(&headers, &fixture.store.resource(catalog)).is_ok());
1096 for (other, _, _) in CATALOGS.iter().filter(|(other, _, _)| other != catalog) {
1097 assert!(fixture.store.authenticate(&headers, &fixture.store.resource(other)).is_err());
1098 }
1099 }
1100 for scopes in ["shale:read unknown:scope", "observability:read offline_access", "offline_access", ""] {
1101 request.insert("resource".into(), fixture.store.resource("shale"));
1102 request.insert("scope".into(), scopes.into());
1103 assert_eq!(fixture.store.oauth("authorize", &Method::GET, &request, &HeaderMap::new(), Value::Null).unwrap_err().message, "invalid_scope");
1104 }
1105 request.insert("scope".into(), "shale:read".into());
1106 request.insert("redirect_uri".into(), uri.replace("H9rAWI-8eQbv", "different"));
1107 assert_eq!(fixture.store.oauth("authorize", &Method::GET, &request, &HeaderMap::new(), Value::Null).unwrap_err().message, "invalid_redirect_uri");
1108 }
1109 #[test]
1110 fn removed_catalogs_cannot_authorize_or_exchange_tokens() {
1111 let fixture = Fixture::new();
1112 let mut input = fixture.code("one", "owned-code");
1113 let resource = fixture.store.resource("agents");
1114 let tokens = {
1115 let db = fixture.store.db.lock().unwrap();
1116 let key = format!("code:{}", hash("owned-code"));
1117 let mut code = get(&db, &key).unwrap();
1118 let mut grant = get(&db, &format!("grant:{}", string(&code["grant"]))).unwrap();
1119 code["resource"] = json!(resource);
1120 grant["resource"] = json!(resource);
1121 put(&db, &key, &code, 300).unwrap();
1122 put(&db, &format!("grant:{}", string(&grant["id"])), &grant, 0).unwrap();
1123 fixture.store.issue(&db, &grant).unwrap()
1124 };
1125 input.insert("resource".into(), resource.clone());
1126 let refresh = fields(json!({"grant_type":"refresh_token","client_id":"one","refresh_token":tokens["refresh_token"]}));
1127 for request in [&input, &refresh] {
1128 assert_eq!(fixture.store.oauth("token", &Method::POST, request, &HeaderMap::new(), Value::Null).unwrap_err().message, "invalid_grant");
1129 }
1130 assert_eq!(fixture.store.oauth("authorize", &Method::GET, &fields(json!({"resource":resource})), &HeaderMap::new(), Value::Null).unwrap_err().message, "invalid_target");
1131 }
1132 #[tokio::test]
1133 async fn code_binds_pkce_client_redirect_and_audience_without_consuming_on_failure() {
1134 let fixture = Fixture::new();
1135 let input = fixture.code("one", "owned-code");
1136 fixture.code("two", "other-code");
1137 for (key, wrong) in [
1138 ("client_id", "two"),
1139 ("code_verifier", "wrong"),
1140 ("redirect_uri", "http://127.0.0.1:20002/callback"),
1141 ("resource", "https://other.invalid/mcp/observability"),
1142 ] {
1143 let mut attempt = input.clone();
1144 attempt.insert(key.into(), wrong.into());
1145 assert!(
1146 fixture
1147 .store
1148 .oauth(
1149 "token",
1150 &Method::POST,
1151 &attempt,
1152 &HeaderMap::new(),
1153 Value::Null
1154 )
1155 .is_err()
1156 );
1157 }
1158 let tokens = value(
1159 fixture
1160 .store
1161 .oauth(
1162 "token",
1163 &Method::POST,
1164 &input,
1165 &HeaderMap::new(),
1166 Value::Null,
1167 )
1168 .unwrap(),
1169 )
1170 .await;
1171 assert!(
1172 fixture
1173 .store
1174 .oauth(
1175 "token",
1176 &Method::POST,
1177 &input,
1178 &HeaderMap::new(),
1179 Value::Null
1180 )
1181 .is_err()
1182 );
1183 assert!(
1184 fixture
1185 .store
1186 .authenticate(
1187 &bearer(string(&tokens["access_token"])),
1188 &fixture.store.resource("observability")
1189 )
1190 .is_ok()
1191 );
1192 assert!(
1193 fixture
1194 .store
1195 .authenticate(
1196 &bearer(string(&tokens["access_token"])),
1197 "https://other.invalid/mcp/observability"
1198 )
1199 .is_err()
1200 );
1201 assert_eq!(
1202 std::fs::metadata(fixture.path.join("connections.sqlite"))
1203 .unwrap()
1204 .permissions()
1205 .mode()
1206 & 0o777,
1207 0o600
1208 );
1209 let rows = fixture
1210 .store
1211 .db
1212 .lock()
1213 .unwrap()
1214 .prepare("SELECT key,value FROM records")
1215 .unwrap()
1216 .query_map([], |row| {
1217 Ok(format!(
1218 "{} {}",
1219 row.get::<_, String>(0)?,
1220 row.get::<_, String>(1)?
1221 ))
1222 })
1223 .unwrap()
1224 .collect::<std::result::Result<Vec<_>, _>>()
1225 .unwrap()
1226 .join("\n");
1227 for token in [
1228 "owned-code",
1229 string(&tokens["access_token"]),
1230 string(&tokens["refresh_token"]),
1231 ] {
1232 assert!(!rows.contains(token));
1233 }
1234 }
1235 #[tokio::test]
1236 async fn refresh_replay_revokes_family_but_another_client_cannot_revoke_it() {
1237 let fixture = Fixture::new();
1238 let input = fixture.code("one", "owned-code");
1239 fixture.code("two", "other-code");
1240 let tokens = value(
1241 fixture
1242 .store
1243 .oauth(
1244 "token",
1245 &Method::POST,
1246 &input,
1247 &HeaderMap::new(),
1248 Value::Null,
1249 )
1250 .unwrap(),
1251 )
1252 .await;
1253 let refresh = fields(
1254 json!({"grant_type":"refresh_token","client_id":"one","refresh_token":tokens["refresh_token"]}),
1255 );
1256 let mut wrong = refresh.clone();
1257 wrong.insert("client_id".into(), "two".into());
1258 assert!(
1259 fixture
1260 .store
1261 .oauth(
1262 "token",
1263 &Method::POST,
1264 &wrong,
1265 &HeaderMap::new(),
1266 Value::Null
1267 )
1268 .is_err()
1269 );
1270 fixture
1271 .store
1272 .oauth(
1273 "revoke",
1274 &Method::POST,
1275 &fields(json!({"client_id":"two","token":tokens["access_token"]})),
1276 &HeaderMap::new(),
1277 Value::Null,
1278 )
1279 .unwrap();
1280 let access = bearer(string(&tokens["access_token"]));
1281 assert!(
1282 fixture
1283 .store
1284 .authenticate(&access, &fixture.store.resource("observability"))
1285 .is_ok()
1286 );
1287 let rotated = value(
1288 fixture
1289 .store
1290 .oauth(
1291 "token",
1292 &Method::POST,
1293 &refresh,
1294 &HeaderMap::new(),
1295 Value::Null,
1296 )
1297 .unwrap(),
1298 )
1299 .await;
1300 assert_ne!(rotated["refresh_token"], tokens["refresh_token"]);
1301 assert!(
1302 fixture
1303 .store
1304 .oauth(
1305 "token",
1306 &Method::POST,
1307 &wrong,
1308 &HeaderMap::new(),
1309 Value::Null
1310 )
1311 .is_err()
1312 );
1313 assert!(
1314 fixture
1315 .store
1316 .authenticate(&access, &fixture.store.resource("observability"))
1317 .is_ok()
1318 );
1319 assert!(
1320 fixture
1321 .store
1322 .oauth(
1323 "token",
1324 &Method::POST,
1325 &refresh,
1326 &HeaderMap::new(),
1327 Value::Null
1328 )
1329 .is_err()
1330 );
1331 assert!(
1332 fixture
1333 .store
1334 .authenticate(&access, &fixture.store.resource("observability"))
1335 .is_err()
1336 );
1337 assert!(
1338 fixture
1339 .store
1340 .authenticate(
1341 &bearer(string(&rotated["access_token"])),
1342 &fixture.store.resource("observability")
1343 )
1344 .is_err()
1345 );
1346 assert!(fixture.store.oauth("token",&Method::POST,&fields(json!({"grant_type":"refresh_token","client_id":"one","refresh_token":rotated["refresh_token"]})),&HeaderMap::new(),Value::Null).is_err());
1347 }
1348 #[test]
1349 fn concurrent_code_exchange_has_one_winner() {
1350 let fixture = Fixture::new();
1351 let input = fixture.code("one", "concurrent-code");
1352 let start = Arc::new(std::sync::Barrier::new(9));
1353 let workers = (0..8)
1354 .map(|_| {
1355 let store = fixture.store.clone();
1356 let input = input.clone();
1357 let start = start.clone();
1358 std::thread::spawn(move || {
1359 start.wait();
1360 store
1361 .oauth(
1362 "token",
1363 &Method::POST,
1364 &input,
1365 &HeaderMap::new(),
1366 Value::Null,
1367 )
1368 .is_ok()
1369 })
1370 })
1371 .collect::<Vec<_>>();
1372 start.wait();
1373 assert_eq!(
1374 workers
1375 .into_iter()
1376 .map(|w| w.join().unwrap() as u32)
1377 .sum::<u32>(),
1378 1
1379 );
1380 }
1381 #[tokio::test]
1382 async fn confidential_client_secret_is_required_and_hashed() {
1383 let fixture = Fixture::new();
1384 let client=value(fixture.store.oauth("register",&Method::POST,&HashMap::new(),&HeaderMap::new(),json!({"client_name":"Confidential","redirect_uris":["https://client.invalid/callback"],"token_endpoint_auth_method":"client_secret_basic"})).unwrap()).await;
1385 let id = string(&client["client_id"]);
1386 let stored = get(&fixture.store.db.lock().unwrap(), &format!("client:{id}")).unwrap();
1387 assert!(stored.get("client_secret").is_none());
1388 assert_ne!(stored["secret_hash"], client["client_secret"]);
1389 let input = fields(json!({"client_id":id,"token":"unknown"}));
1390 assert!(
1391 fixture
1392 .store
1393 .oauth(
1394 "revoke",
1395 &Method::POST,
1396 &input,
1397 &HeaderMap::new(),
1398 Value::Null
1399 )
1400 .is_err()
1401 );
1402 let mut headers = HeaderMap::new();
1403 headers.insert(
1404 "authorization",
1405 format!(
1406 "Basic {}",
1407 STANDARD.encode(format!("{id}:{}", string(&client["client_secret"])))
1408 )
1409 .parse()
1410 .unwrap(),
1411 );
1412 assert!(
1413 fixture
1414 .store
1415 .oauth("revoke", &Method::POST, &input, &headers, Value::Null)
1416 .is_ok()
1417 );
1418 let mut duplicate = input.clone();
1419 duplicate.insert(
1420 "client_secret".into(),
1421 string(&client["client_secret"]).into(),
1422 );
1423 assert!(
1424 fixture
1425 .store
1426 .oauth("revoke", &Method::POST, &duplicate, &headers, Value::Null)
1427 .is_err()
1428 );
1429 }
1430}