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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
mod actor;
mod api;
mod auth;
mod backup;
mod cli;
mod config;
mod db;
mod error;
mod export;
mod mcp;
mod oauth;
mod ratelimit;
use std::sync::Arc;
use axum::{
Router,
body::Body,
extract::Request,
http::{HeaderName, HeaderValue, Method, StatusCode, header},
middleware,
response::IntoResponse,
routing::{any, get},
};
use tower_http::compression::CompressionLayer;
use tower_http::cors::{Any, CorsLayer};
use clap::Parser;
use cli::{Cli, Command, KeyAction, UserAction};
use config::Config;
// Commands that operate directly on the database (no server required)
fn is_crud_command(cmd: &Command) -> bool {
matches!(cmd,
Command::Issue { .. } | Command::Project { .. } | Command::Page { .. } |
Command::Export { .. } |
Command::Search { .. } | Command::Comment { .. } | Command::Module { .. } |
Command::Label { .. } | Command::Folder { .. }
)
}
use rmcp::{
ServiceExt,
transport::streamable_http_server::{
session::local::LocalSessionManager,
tower::{StreamableHttpServerConfig, StreamableHttpService},
},
};
use rust_embed::Embed;
use tracing::info;
/// Embedded frontend assets compiled from web/dist/.
/// Falls back gracefully if dist/ doesn't exist (e.g. dev builds without frontend).
#[derive(Embed)]
#[folder = "web/dist/"]
#[allow(dead_code)]
struct WebAssets;
/// Serve an embedded static file, or fall back to index.html for SPA routing.
async fn serve_frontend(uri: axum::http::Uri) -> impl IntoResponse {
let path = uri.path().trim_start_matches('/');
// Try the exact path first (e.g. assets/index-abc.js)
if let Some(file) = WebAssets::get(path) {
let mime = mime_guess::from_path(path)
.first_or_octet_stream()
.to_string();
// Vite emits content-hashed filenames under assets/ (e.g.
// index-xkSiPCqs.js), so those are safe to cache forever — a new
// build changes the hash and thus the URL. Everything else
// (index.html, favicon) stays uncached so a redeploy is picked up
// immediately.
let cache_control = if path.starts_with("assets/") {
"public, max-age=31536000, immutable"
} else {
"no-cache"
};
return (
StatusCode::OK,
[
(header::CONTENT_TYPE, mime),
(header::CACHE_CONTROL, cache_control.to_string()),
],
file.data.to_vec(),
)
.into_response();
}
// SPA fallback: serve index.html for all unmatched routes
match WebAssets::get("index.html") {
Some(file) => (
StatusCode::OK,
[(header::CONTENT_TYPE, "text/html".to_string())],
file.data.to_vec(),
)
.into_response(),
None => (
StatusCode::NOT_FOUND,
"Frontend not built. Run: cd web && bun run build",
)
.into_response(),
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let cli = Cli::parse();
// Load config (CLI flags override config values)
let mut cfg = Config::load(cli.config.as_deref());
// CLI overrides
if let Some(ref db) = cli.db {
cfg.database.path = db.clone();
}
// Handle CRUD commands (direct database access, no server needed)
if is_crud_command(&cli.command) {
// LIF-155: CLI mutations run outside any request task — audit
// them via the process-default transport.
actor::set_default_transport(actor::Transport::Cli);
let pool = db::open(&cfg.database.path)?;
return cli::exec::run(&pool, &cli.command, cli.json);
}
match cli.command {
Command::Init => {
let config_path = std::path::Path::new("lific.toml");
if config_path.exists() {
eprintln!("lific.toml already exists in current directory");
std::process::exit(1);
}
std::fs::write(config_path, Config::default_toml())?;
println!("Created lific.toml with default settings");
return Ok(());
}
Command::Key { action } => {
let pool = db::open(&cfg.database.path)?;
let manager =
auth::create_key_manager().map_err(|e| format!("key manager init failed: {e}"))?;
match action {
KeyAction::Create { name, user } => {
let key = auth::create_api_key(&pool, &manager, &name)?;
// If --user was provided, assign the key to that user
if let Some(ref username) = user {
let conn = pool.read()?;
let u = db::queries::users::get_user_by_username(&conn, username)?;
drop(conn);
let conn = pool.write()?;
db::queries::users::assign_key_to_user(&conn, &name, u.id)?;
println!();
println!(" API Key created: {name} (assigned to {username})");
} else {
println!();
println!(" API Key created: {name}");
}
println!();
println!(" {key}");
println!();
println!(" Save this key now. It will never be shown again.");
println!(" Use as: Authorization: Bearer {key}");
println!();
}
KeyAction::List => {
let keys = auth::list_api_keys(&pool)?;
if keys.is_empty() {
println!("No API keys configured.");
} else {
println!("{} API key(s):", keys.len());
for k in &keys {
let status = if k.revoked { "REVOKED" } else { "active" };
let expiry = k.expires_at.as_deref().unwrap_or("never");
println!(
" {} | {} | created {} | expires {}",
k.name, status, k.created_at, expiry
);
}
}
}
KeyAction::Revoke { name } => {
auth::revoke_api_key(&pool, &name)?;
println!("Revoked key: {name}");
}
KeyAction::Rotate { name } => {
let key = auth::rotate_api_key(&pool, &manager, &name)?;
println!();
println!(" Key rotated: {name}");
println!();
println!(" {key}");
println!();
println!(" Save this key now. It will never be shown again.");
println!();
}
KeyAction::Assign { name, user } => {
let conn = pool.read()?;
let u = db::queries::users::get_user_by_username(&conn, &user)?;
drop(conn);
let conn = pool.write()?;
db::queries::users::assign_key_to_user(&conn, &name, u.id)?;
println!("Assigned key '{name}' to user '{user}'");
}
}
return Ok(());
}
Command::User { action } => {
let pool = db::open(&cfg.database.path)?;
match action {
UserAction::Create {
username,
email,
password,
admin,
bot,
} => {
// Prompt for password if not provided
let pw = match password {
Some(p) => p,
None => {
eprint!("Password: ");
let mut buf = String::new();
std::io::stdin().read_line(&mut buf)?;
buf.trim().to_string()
}
};
let conn = pool.write()?;
let user = db::queries::users::create_user(
&conn,
&db::models::CreateUser {
username: username.clone(),
email: email.clone(),
password: pw,
display_name: None,
is_admin: admin,
is_bot: bot,
},
)?;
let role = if user.is_admin { " (admin)" } else { "" };
println!("User created: {}{role}", user.username);
println!(" email: {}", user.email);
println!(" display_name: {}", user.display_name);
}
UserAction::List => {
let conn = pool.read()?;
let users = db::queries::users::list_users(&conn)?;
if users.is_empty() {
println!("No users.");
} else {
println!("{} user(s):", users.len());
for u in &users {
let flags = match (u.is_admin, u.is_bot) {
(true, true) => " [admin, bot]",
(true, false) => " [admin]",
(false, true) => " [bot]",
(false, false) => "",
};
println!(
" {} | {} | {}{} | created {}",
u.id, u.username, u.email, flags, u.created_at
);
}
}
}
UserAction::Promote { username } => {
let conn = pool.write()?;
db::queries::users::set_admin(&conn, &username, true)?;
println!("Promoted '{username}' to admin.");
}
UserAction::Demote { username } => {
let conn = pool.write()?;
db::queries::users::set_admin(&conn, &username, false)?;
println!("Demoted '{username}' from admin.");
}
}
return Ok(());
}
Command::Start { port, host } => {
if let Some(p) = port {
cfg.server.port = p;
}
if let Some(h) = host {
cfg.server.host = h;
}
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| format!("lific={}", cfg.log.level).into()),
)
.init();
let pool = db::open(&cfg.database.path)?;
info!(path = %cfg.database.path.display(), "database ready");
// Key manager for auth
let manager =
auth::create_key_manager().map_err(|e| format!("key manager init failed: {e}"))?;
// Auto-generate a key if none exist
if !auth::has_any_keys(&pool) {
let key = auth::create_api_key(&pool, &manager, "default")?;
info!("no API keys found, auto-generated initial key");
println!();
println!(" ┌─────────────────────────────────────────────────────┐");
println!(" │ No API keys found. Generated initial key: │");
println!(" │ │");
println!(" │ {key}");
println!(" │ │");
println!(" │ Save this key now. It will never be shown again. │");
println!(" │ Use as: Authorization: Bearer <key> │");
println!(" └─────────────────────────────────────────────────────┘");
println!();
} else {
let count = auth::list_api_keys(&pool)?
.iter()
.filter(|k| !k.revoked)
.count();
info!(active_keys = count, "API key auth enabled");
}
// Auth state for middleware
let issuer = cfg
.server
.public_url
.clone()
.unwrap_or_else(|| format!("http://{}:{}", cfg.server.host, cfg.server.port));
let manager_ext = Arc::new(manager.clone());
let auth_state = auth::AuthState {
db: pool.clone(),
manager,
public_url: issuer.clone(),
};
// Start backup task
if cfg.backup.enabled {
let pool_arc = Arc::new(pool.clone());
backup::start_backup_task(pool_arc, cfg.database.path.clone(), cfg.backup.clone());
info!(
dir = %cfg.backup_dir().display(),
interval = %format!("{}m", cfg.backup.interval_minutes),
retain = cfg.backup.retain,
"automatic backups enabled"
);
}
// MCP StreamableHTTP service
let db_for_mcp = pool.clone();
let mut mcp_allowed_hosts: Vec<String> =
vec!["localhost".into(), "127.0.0.1".into(), "::1".into()];
// If public_url is set, allow its hostname through the DNS rebinding check
// so reverse proxies (Tailscale funnel, nginx, etc.) can forward requests.
if let Some(ref url) = cfg.server.public_url
&& let Ok(parsed) = url.parse::<axum::http::Uri>()
&& let Some(authority) = parsed.authority() {
let host: String = authority.host().to_string();
mcp_allowed_hosts.push(host);
}
let mcp_config = StreamableHttpServerConfig::default()
.with_stateful_mode(false)
.with_json_response(true)
.with_allowed_hosts(mcp_allowed_hosts.clone());
let mcp_service = StreamableHttpService::new(
move || Ok(mcp::LificMcp::new(db_for_mcp.clone())),
Arc::new(LocalSessionManager::default()),
mcp_config,
);
// Login rate limiter: 5 attempts per 15 minutes per identity
let login_limiter = Arc::new(ratelimit::RateLimiter::new(
5,
std::time::Duration::from_secs(15 * 60),
));
// Routes behind auth: REST API + MCP
let authed_routes = api::router(pool.clone(), &cfg.server.cors_origins)
.route(
"/mcp",
any(move |request: Request<Body>| async move {
// Extract the authenticated user (set by auth middleware)
// and store it for MCP tools to read. Serialized to prevent
// concurrent requests from overwriting each other's identity.
let auth_user = request
.extensions()
.get::<Option<db::models::AuthUser>>()
.cloned()
.flatten();
mcp::with_request_user(auth_user, || async {
mcp_service.handle(request).await.into_response()
})
.await
}),
)
.layer(axum::Extension(login_limiter))
.layer(axum::Extension(cfg.auth.clone()))
.layer(axum::Extension(manager_ext))
.layer(middleware::from_fn_with_state(
auth_state,
auth_middleware_wrapper,
));
// OAuth client registration rate limiter: 10 clients per IP per hour.
// /oauth/register is unauthenticated per RFC 7591; without this anyone
// can flood the server with throwaway clients (LIF-64).
let oauth_register_limiter = Arc::new(ratelimit::RateLimiter::new(
10,
std::time::Duration::from_secs(60 * 60),
));
let oauth_state = oauth::OAuthState {
db: pool.clone(),
issuer,
register_limiter: oauth_register_limiter,
};
// Optional authless MCP escape hatch at /mcp/<token> (see the
// mcp_path_token config docs). Resolved identity for attribution:
// the configured username, else the first admin, else anonymous.
let authless_mcp_router: Option<Router> = cfg
.server
.mcp_path_token
.clone()
.map(|t| t.trim().to_string())
.filter(|t| !t.is_empty())
.map(|token| {
let authless_user: Option<db::models::AuthUser> = {
match pool.read() {
Ok(conn) => match cfg.server.mcp_path_user.as_deref() {
Some(uname) => db::queries::users::get_user_by_username(&conn, uname)
.ok()
.map(|u| db::models::AuthUser {
id: u.id,
username: u.username,
display_name: u.display_name,
is_admin: u.is_admin,
}),
None => db::queries::users::first_admin(&conn)
.ok()
.flatten(),
},
Err(_) => None,
}
};
info!(
acting_as = authless_user
.as_ref()
.map(|u| u.username.as_str())
.unwrap_or("<anonymous>"),
"authless MCP endpoint enabled at /mcp/<token>"
);
build_authless_mcp_router(
pool.clone(),
&token,
authless_user,
mcp_allowed_hosts.clone(),
)
});
let app = authed_routes.merge(oauth::router(oauth_state));
let app = match authless_mcp_router {
Some(r) => app.merge(r),
None => app,
};
let app = app
.fallback(get(serve_frontend))
// Top-level CORS layer.
//
// This wraps EVERYTHING (REST API, /mcp, OAuth, frontend). Two
// things matter here:
//
// 1. `CorsLayer` intercepts OPTIONS preflight requests and
// short-circuits them with a 204 — they never reach the auth
// middleware. Without this, browser MCP clients like Claude
// Web get their preflight rejected with 401 and the actual
// POST is never sent.
//
// 2. We expose MCP-specific headers (`mcp-session-id`,
// `www-authenticate`) and accept the request headers MCP
// clients send (`mcp-protocol-version`, `mcp-session-id`,
// `last-event-id` for SSE resumption).
//
// The internal CORS layer inside `api::router()` still runs for
// /api/* but is effectively shadowed by this outer one.
.layer(build_global_cors(&cfg.server.cors_origins))
.layer(axum::extract::DefaultBodyLimit::max(2 * 1024 * 1024)) // 2 MB
// Gzip/brotli compression for text responses. The embedded
// frontend ships a ~1 MB JS bundle that was previously served
// raw — uncompressed it took ~6-9s to transfer over the
// tailnet, blocking first paint (and everything behind it).
// CompressionLayer's DefaultPredicate already skips SSE
// (text/event-stream — so MCP streaming is untouched), gRPC,
// already-compressed images, and bodies under 32 bytes.
.layer(CompressionLayer::new());
let addr = format!("{}:{}", cfg.server.host, cfg.server.port);
let listener = tokio::net::TcpListener::bind(&addr).await?;
info!(addr = %addr, "lific server started (REST + MCP + OAuth at /mcp)");
let shutdown_pool = pool.clone();
let server =
axum::serve(listener, app).with_graceful_shutdown(shutdown_signal(shutdown_pool));
server.await?;
}
Command::Mcp => {
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| format!("lific={}", cfg.log.level).into()),
)
.with_writer(std::io::stderr)
.init();
let pool = db::open(&cfg.database.path)?;
info!(path = %cfg.database.path.display(), "database ready");
let server = mcp::LificMcp::new(pool);
let transport = rmcp::transport::io::stdio();
info!("lific MCP server started (stdio)");
let handle = server.serve(transport).await?;
handle.waiting().await?;
}
// CRUD commands are handled before this match
Command::Issue { .. } | Command::Project { .. } | Command::Page { .. } |
Command::Export { .. } |
Command::Search { .. } | Command::Comment { .. } | Command::Module { .. } |
Command::Label { .. } | Command::Folder { .. } => unreachable!(),
}
Ok(())
}
/// Build the top-level CORS layer applied to the entire app.
///
/// When `cors_origins` is empty, allows any origin (suitable for a local-first
/// tool exposed via Tailscale Funnel where the auth layer is the real gate).
/// Otherwise, allows only the listed origins.
///
/// Methods, request headers, and exposed response headers are all configured
/// for the union of REST + MCP needs. Notably we accept the MCP transport
/// headers (`mcp-protocol-version`, `mcp-session-id`, `last-event-id`) and
/// expose `mcp-session-id` and `www-authenticate` so MCP clients can read
/// the session id back and so 401 responses surface the resource metadata.
fn build_global_cors(cors_origins: &[String]) -> CorsLayer {
let layer = CorsLayer::new()
.allow_methods([
Method::GET,
Method::POST,
Method::PUT,
Method::DELETE,
Method::OPTIONS,
])
.allow_headers([
header::AUTHORIZATION,
header::CONTENT_TYPE,
header::ACCEPT,
HeaderName::from_static("mcp-protocol-version"),
HeaderName::from_static("mcp-session-id"),
HeaderName::from_static("last-event-id"),
])
.expose_headers([
header::WWW_AUTHENTICATE,
HeaderName::from_static("mcp-session-id"),
])
.max_age(std::time::Duration::from_secs(86400));
if cors_origins.is_empty() {
layer.allow_origin(Any)
} else {
let origins: Vec<HeaderValue> = cors_origins
.iter()
.filter_map(|o| o.parse().ok())
.collect();
layer.allow_origin(origins)
}
}
/// Build the authless MCP router mounted at `/mcp/<token>`.
///
/// This endpoint deliberately bypasses the OAuth/API-key auth middleware: the
/// secret path segment IS the credential. It exists because claude.ai web's
/// OAuth connector flow is currently broken (it finishes the OAuth dance, gets
/// a token, then never sends the authenticated MCP request). An authless server
/// sidesteps that path entirely. Every request is run as a fixed identity
/// (`user`) so MCP tools that attribute actions to a user still work.
///
/// Security: anyone who learns the URL has full MCP access. The token must be
/// long and random, and only served over HTTPS.
fn build_authless_mcp_router(
pool: db::DbPool,
token: &str,
user: Option<db::models::AuthUser>,
allowed_hosts: Vec<String>,
) -> Router {
let config = StreamableHttpServerConfig::default()
.with_stateful_mode(false)
.with_json_response(true)
.with_allowed_hosts(allowed_hosts);
let service = StreamableHttpService::new(
move || Ok(mcp::LificMcp::new(pool.clone())),
Arc::new(LocalSessionManager::default()),
config,
);
Router::new().route(
&format!("/mcp/{token}"),
any(move |request: Request<Body>| async move {
mcp::with_request_user(user, || async {
service.handle(request).await.into_response()
})
.await
}),
)
}
/// Wrapper that skips auth for /api/health
async fn auth_middleware_wrapper(
state: axum::extract::State<auth::AuthState>,
request: Request<Body>,
next: middleware::Next,
) -> axum::response::Response {
let path = request.uri().path();
if path == "/api/health"
|| path == "/api/auth/signup"
|| path == "/api/auth/login"
|| path.starts_with("/.well-known/")
|| path.starts_with("/oauth/")
|| path == "/register"
|| path == "/authorize"
|| path == "/token"
|| path == "/revoke"
{
return next.run(request).await;
}
auth::require_api_key(state, request, next).await
}
/// Wait for SIGINT/SIGTERM, then checkpoint WAL before shutting down.
async fn shutdown_signal(pool: db::DbPool) {
let ctrl_c = async {
tokio::signal::ctrl_c()
.await
.expect("failed to install Ctrl+C handler");
};
#[cfg(unix)]
let terminate = async {
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
.expect("failed to install SIGTERM handler")
.recv()
.await;
};
#[cfg(not(unix))]
let terminate = std::future::pending::<()>();
tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
}
info!("shutdown signal received, checkpointing WAL...");
backup::checkpoint_wal(&pool);
info!("shutdown complete");
}
#[cfg(test)]
mod cors_tests {
use super::*;
use axum::routing::post;
use http_body_util::BodyExt;
use tower::ServiceExt;
/// Build a minimal /mcp router behind an auth gate identical in spirit to
/// the real one (returns 401 if Authorization is missing), wrapped with
/// our global CORS layer.
fn app_with_cors(origins: &[String]) -> Router {
let inner = Router::new().route(
"/mcp",
post(|headers: axum::http::HeaderMap| async move {
if headers.get(header::AUTHORIZATION).is_none() {
return (StatusCode::UNAUTHORIZED, "missing auth").into_response();
}
(StatusCode::OK, "ok").into_response()
}),
);
inner.layer(build_global_cors(origins))
}
/// A browser MCP client (Claude Web) issues a CORS preflight before the
/// authenticated POST. That preflight must succeed WITHOUT any
/// Authorization header — otherwise the browser blocks the real request
/// and the user sees "Authorization with the MCP server failed".
#[tokio::test]
async fn cors_preflight_to_mcp_bypasses_auth() {
let app = app_with_cors(&[]);
let req = Request::builder()
.method(Method::OPTIONS)
.uri("/mcp")
.header("origin", "https://claude.ai")
.header("access-control-request-method", "POST")
.header("access-control-request-headers", "authorization,content-type")
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
// tower-http returns 200 OK for valid preflights (not 204, but either
// is RFC-compliant). The critical thing is NOT 401.
assert!(
res.status().is_success(),
"preflight should succeed without auth, got {}",
res.status()
);
let headers = res.headers();
assert_eq!(
headers
.get("access-control-allow-origin")
.and_then(|v| v.to_str().ok()),
Some("*"),
"empty cors_origins should allow any origin"
);
let allow_methods = headers
.get("access-control-allow-methods")
.and_then(|v| v.to_str().ok())
.unwrap_or("");
assert!(
allow_methods.contains("POST"),
"POST must be in allowed methods, got: {allow_methods}"
);
let allow_headers = headers
.get("access-control-allow-headers")
.and_then(|v| v.to_str().ok())
.unwrap_or("")
.to_ascii_lowercase();
assert!(
allow_headers.contains("authorization"),
"authorization must be allowed, got: {allow_headers}"
);
assert!(
allow_headers.contains("mcp-session-id"),
"mcp-session-id must be allowed, got: {allow_headers}"
);
}
/// Real (post-preflight) requests still go through normal auth — CORS
/// doesn't bypass the auth middleware for the actual call.
#[tokio::test]
async fn cors_does_not_bypass_auth_on_real_request() {
let app = app_with_cors(&[]);
let req = Request::builder()
.method(Method::POST)
.uri("/mcp")
.header("origin", "https://claude.ai")
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
}
/// When configured with an explicit origin list, only those origins
/// receive an Access-Control-Allow-Origin header echoing them back.
#[tokio::test]
async fn explicit_origins_are_allowlisted() {
let app = app_with_cors(&["https://claude.ai".to_string()]);
let req = Request::builder()
.method(Method::OPTIONS)
.uri("/mcp")
.header("origin", "https://claude.ai")
.header("access-control-request-method", "POST")
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert!(res.status().is_success());
assert_eq!(
res.headers()
.get("access-control-allow-origin")
.and_then(|v| v.to_str().ok()),
Some("https://claude.ai")
);
}
/// MCP responses must expose the session id header so the client can
/// read it back — without `Access-Control-Expose-Headers`, browser
/// JS can't see custom response headers cross-origin.
#[tokio::test]
async fn mcp_session_id_is_exposed() {
// We make a synthetic GET that returns 200 with a header. The
// preflight response also carries the expose-headers field, so we
// check it there for simplicity.
let app = app_with_cors(&[]);
let req = Request::builder()
.method(Method::OPTIONS)
.uri("/mcp")
.header("origin", "https://claude.ai")
.header("access-control-request-method", "POST")
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
// Expose-Headers is sent on actual responses, not preflight, in tower-http.
// So instead, fire a real (failing) request and check exposed headers.
let _ = res.into_body().collect().await;
let app = app_with_cors(&[]);
let req = Request::builder()
.method(Method::POST)
.uri("/mcp")
.header("origin", "https://claude.ai")
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
let expose = res
.headers()
.get("access-control-expose-headers")
.and_then(|v| v.to_str().ok())
.unwrap_or("")
.to_ascii_lowercase();
assert!(
expose.contains("mcp-session-id"),
"mcp-session-id must be exposed, got: {expose}"
);
assert!(
expose.contains("www-authenticate"),
"www-authenticate must be exposed, got: {expose}"
);
}
}
#[cfg(test)]
mod authless_mcp_tests {
use super::*;
use http_body_util::BodyExt;
use tower::ServiceExt;
fn initialize_body() -> Body {
let body = serde_json::json!({
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-06-18",
"capabilities": {},
"clientInfo": {"name": "test", "version": "1"}
}
});
Body::from(serde_json::to_vec(&body).unwrap())
}
/// The whole point: a request to /mcp/<token> with NO Authorization header
/// drives a full MCP `initialize` and returns 200. This is the path that
/// works around claude.ai web's broken OAuth connector flow.
#[tokio::test]
async fn authless_path_serves_mcp_without_auth() {
let pool = db::open_memory().unwrap();
let token = "s3cret-authless-token-abcdef";
let router =
build_authless_mcp_router(pool, token, None, vec!["localhost".into()]);
let req = Request::builder()
.method(Method::POST)
.uri(format!("/mcp/{token}"))
.header("host", "localhost")
.header("content-type", "application/json")
.header("accept", "application/json, text/event-stream")
.body(initialize_body())
.unwrap();
let res = router.oneshot(req).await.unwrap();
assert_eq!(
res.status(),
StatusCode::OK,
"authless MCP initialize must succeed without any auth header"
);
let bytes = res.into_body().collect().await.unwrap().to_bytes();
let val: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(
val["result"]["serverInfo"].is_object(),
"expected an initialize result, got: {val}"
);
}
/// A wrong path token does not match the route at all (no secret leak,
/// no MCP access) — it falls through to 404 in this isolated router.
#[tokio::test]
async fn wrong_path_token_does_not_match() {
let pool = db::open_memory().unwrap();
let router =
build_authless_mcp_router(pool, "the-right-token", None, vec!["localhost".into()]);
let req = Request::builder()
.method(Method::POST)
.uri("/mcp/the-wrong-token")
.header("host", "localhost")
.header("content-type", "application/json")
.header("accept", "application/json, text/event-stream")
.body(initialize_body())
.unwrap();
let res = router.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::NOT_FOUND);
}
}