Skip to main content

shell_tunnel/api/
router.rs

1//! API router configuration.
2
3use std::net::SocketAddr;
4use std::sync::Arc;
5
6use axum::{
7    extract::{
8        connect_info::IntoMakeServiceWithConnectInfo, DefaultBodyLimit, MatchedPath, Request, State,
9    },
10    http::{header::AUTHORIZATION, Method, StatusCode},
11    middleware::{self, Next},
12    response::Response,
13    routing::{any, get, post},
14    Router,
15};
16use tower_http::{
17    cors::{Any, CorsLayer},
18    trace::TraceLayer,
19};
20
21use super::handlers::{
22    api_info, create_session, delete_session, execute_command, execute_oneshot, get_session,
23    health, list_sessions, AppState,
24};
25use super::websocket::{ws_handler, ws_oneshot_handler};
26use crate::security::{
27    rate_limit_middleware, ApiKeyStore, AuthConfig, CapabilitySet, RateLimitConfig, RateLimiter,
28};
29
30/// Cross-Origin Resource Sharing (CORS) configuration.
31///
32/// CORS is a browser-enforced mechanism; non-browser clients (`curl`, SDKs)
33/// ignore it entirely. shell-tunnel therefore emits **no** permissive CORS headers
34/// by default: this blocks a malicious web page from reading responses cross-origin
35/// and, because the JSON execute endpoints require a preflight, from issuing the
36/// request at all — with zero impact on the intended non-browser consumers.
37///
38/// Note: CORS does **not** defend against DNS-rebinding (the attacker's host is
39/// rebound to `127.0.0.1`, making the request same-origin); that requires
40/// Host-header validation and is tracked separately.
41#[derive(Debug, Clone, Default)]
42pub struct CorsConfig {
43    /// Allow any origin/method/header (restores the permissive `Any` behavior).
44    /// Off by default; enable only for trusted browser-based UIs.
45    pub allow_any: bool,
46}
47
48/// Security configuration for the server.
49#[derive(Debug, Clone)]
50pub struct SecurityConfig {
51    /// Authentication configuration.
52    pub auth: AuthConfig,
53    /// Rate limiting configuration.
54    pub rate_limit: RateLimitConfig,
55    /// API keys to pre-register.
56    pub api_keys: Vec<String>,
57    /// Capabilities granted to the pre-registered keys and to the
58    /// auto-generated fallback key.
59    ///
60    /// `None` (the default) means **full-control** (wildcard) — the backward-
61    /// compatible behavior for a bare `--api-key` / `--require-auth` (spec §4).
62    /// `Some(set)` issues fine-grained tokens scoped to that set (spec §9).
63    pub capabilities: Option<CapabilitySet>,
64    /// CORS configuration.
65    pub cors: CorsConfig,
66    /// Host names this server answers to, when it is worth checking.
67    ///
68    /// `None` disables the check. It is meant for a loopback-bound server, where
69    /// DNS rebinding is the one attack CORS cannot stop: the attacker's name is
70    /// rebound to `127.0.0.1`, so the browser considers the request same-origin
71    /// and sends it. The `Host` header still carries the attacker's name, which
72    /// is what this compares. A published server is deliberately reachable under
73    /// a name we may not know, so the check does not apply there.
74    pub allowed_hosts: Option<Vec<String>>,
75}
76
77impl Default for SecurityConfig {
78    fn default() -> Self {
79        Self {
80            auth: AuthConfig::disabled(), // Disabled by default for ease of use
81            rate_limit: RateLimitConfig::default(),
82            api_keys: Vec::new(),
83            capabilities: None, // Full-control by default (legacy-compatible)
84            cors: CorsConfig::default(), // Restrictive by default (no permissive CORS)
85            allowed_hosts: None,
86        }
87    }
88}
89
90/// Build a permissive CORS layer when `allow_any` is set, otherwise `None`.
91///
92/// Returning `None` means no CORS headers are emitted — the secure default.
93fn cors_layer(cfg: &CorsConfig) -> Option<CorsLayer> {
94    cfg.allow_any.then(|| {
95        CorsLayer::new()
96            .allow_origin(Any)
97            .allow_methods(Any)
98            .allow_headers(Any)
99    })
100}
101
102impl SecurityConfig {
103    /// Create a secure configuration.
104    pub fn secure() -> Self {
105        Self {
106            auth: AuthConfig::default(),
107            rate_limit: RateLimitConfig::default(),
108            api_keys: Vec::new(),
109            capabilities: None,
110            cors: CorsConfig::default(),
111            allowed_hosts: None,
112        }
113    }
114
115    /// Create a development configuration (no auth, relaxed limits).
116    pub fn development() -> Self {
117        Self {
118            auth: AuthConfig::disabled(),
119            rate_limit: RateLimitConfig::relaxed(),
120            api_keys: Vec::new(),
121            capabilities: None,
122            cors: CorsConfig::default(),
123            allowed_hosts: None,
124        }
125    }
126
127    /// Add an API key.
128    pub fn with_api_key(mut self, key: impl Into<String>) -> Self {
129        self.api_keys.push(key.into());
130        self
131    }
132
133    /// Scope the issued tokens to a fine-grained capability set (spec §9).
134    ///
135    /// Applies to the pre-registered keys and to the auto-generated fallback
136    /// key. Without this, tokens are full-control (legacy-compatible).
137    pub fn with_capabilities(mut self, capabilities: CapabilitySet) -> Self {
138        self.capabilities = Some(capabilities);
139        self
140    }
141
142    /// Answer only to these host names.
143    pub fn with_allowed_hosts(mut self, hosts: Vec<String>) -> Self {
144        self.allowed_hosts = Some(hosts);
145        self
146    }
147
148    /// Enable permissive (`Any`) CORS. Opt-in; only for trusted browser UIs.
149    pub fn with_cors_allow_any(mut self) -> Self {
150        self.cors.allow_any = true;
151        self
152    }
153}
154
155/// Register `key` into `store` with `capabilities` (fine-grained), or as a
156/// legacy full-control key when `capabilities` is `None` (spec §4/§9).
157fn register_key(store: &ApiKeyStore, key: &str, capabilities: &Option<CapabilitySet>) {
158    match capabilities {
159        Some(caps) => store.add_key_with_capabilities(key, caps.clone(), "configured"),
160        None => store.add_key(key),
161    }
162}
163
164/// Create the API router with all routes configured.
165pub fn create_router() -> Router {
166    create_router_with_state(AppState::new())
167}
168
169/// Create the API router with custom state (no security).
170pub fn create_router_with_state(state: AppState) -> Router {
171    // Session routes
172    let session_routes = Router::new()
173        .route("/", get(list_sessions).post(create_session))
174        .route("/{id}", get(get_session).delete(delete_session))
175        .route("/{id}/execute", post(execute_command))
176        .route("/{id}/ws", any(ws_handler));
177
178    // API v1 routes
179    let api_v1 = Router::new()
180        .route("/", get(api_info))
181        .route("/execute", post(execute_oneshot))
182        .route("/ws", any(ws_oneshot_handler))
183        .nest("/fs", fs_routes())
184        .nest("/sessions", session_routes);
185
186    // Build main router. This "no security" convenience constructor uses the
187    // restrictive CORS default (no permissive CORS headers emitted).
188    Router::new()
189        .route("/health", get(health))
190        .nest("/api/v1", api_v1)
191        .layer(TraceLayer::new_for_http())
192        .with_state(state)
193}
194
195/// The capability a route requires (Phase A spec §3).
196///
197/// Declared here at the router layer — co-located with the route definitions,
198/// which are the single source of truth for the matched-path strings this maps
199/// against. Not a per-handler attribute.
200#[derive(Debug, Clone, Copy, PartialEq, Eq)]
201pub enum RequiredCapability {
202    /// No authentication at all (e.g. `/health`).
203    Public,
204    /// Authenticated only: any valid token passes, no specific capability
205    /// required (spec §3 "인증만" tier, e.g. `GET /api/v1`).
206    Authenticated,
207    /// Requires a specific capability string (set membership, or wildcard).
208    Capability(&'static str),
209}
210
211/// Map a matched route (`method` + axum [`MatchedPath`]) to its required
212/// capability (spec §3 table).
213///
214/// Keyed on the **full nested** `MatchedPath` (confirmed against the real router
215/// structure) plus the HTTP method, because one path can require different
216/// capabilities per method (e.g. `GET /api/v1/sessions` = read, `POST` = manage).
217///
218/// Unknown routes fail **closed** to [`RequiredCapability::Authenticated`]: an
219/// unmapped route still requires a valid token, never less than that.
220pub fn required_capability(method: &Method, matched_path: &str) -> RequiredCapability {
221    use RequiredCapability::{Authenticated, Capability, Public};
222
223    // HEAD is GET without a body, and axum's `get()` serves it automatically, so
224    // its authorization must equal GET's. Keyed separately below, every GET
225    // route would need a twin HEAD arm — and a forgotten twin falls through to
226    // the closed default `Authenticated`, which means any valid token, not the
227    // capability GET requires. Normalising here is the one place it cannot be
228    // forgotten. Matched as `&str` (rather than comparing `Method` values) so
229    // the table below stays exactly as it reads for every other method.
230    let method = match method.as_str() {
231        "HEAD" => "GET",
232        other => other,
233    };
234
235    match (method, matched_path) {
236        (_, "/health") => Public,
237        ("GET", "/api/v1") => Authenticated,
238        ("POST", "/api/v1/execute") => Capability("exec"),
239        (_, "/api/v1/ws") => Capability("exec"),
240        ("GET", "/api/v1/sessions") => Capability("session.read"),
241        ("POST", "/api/v1/sessions") => Capability("session.manage"),
242        ("GET", "/api/v1/sessions/{id}") => Capability("session.read"),
243        ("DELETE", "/api/v1/sessions/{id}") => Capability("session.manage"),
244        ("POST", "/api/v1/sessions/{id}/execute") => Capability("exec"),
245        (_, "/api/v1/sessions/{id}/ws") => Capability("exec"),
246        ("GET", "/api/v1/fs/list") => Capability("fs.read"),
247        ("GET", "/api/v1/fs/stat") => Capability("fs.read"),
248        ("GET", "/api/v1/fs/file") => Capability("fs.read"),
249        ("DELETE", "/api/v1/fs/file") => Capability("fs.write"),
250        ("POST", "/api/v1/fs/uploads") => Capability("fs.write"),
251        ("GET", "/api/v1/fs/uploads/{id}") => Capability("fs.write"),
252        ("PATCH", "/api/v1/fs/uploads/{id}") => Capability("fs.write"),
253        ("POST", "/api/v1/fs/uploads/{id}/complete") => Capability("fs.write"),
254        ("DELETE", "/api/v1/fs/uploads/{id}") => Capability("fs.write"),
255        _ => Authenticated,
256    }
257}
258
259/// Scope-aware authentication + authorization middleware (spec §5).
260///
261/// 1. Resolve the route's required capability from `method` + `MatchedPath`.
262/// 2. `Public` route or auth disabled → pass through.
263/// 3. Extract the bearer token; look up its `TokenRecord` in the store.
264///    Missing/invalid token → **401**.
265/// 4. `Authenticated` route → any valid token passes. `Capability(c)` route →
266///    the token's set must satisfy `c` (membership or wildcard), else **403**.
267async fn capability_auth_middleware(
268    State((store, audit)): State<(
269        std::sync::Arc<ApiKeyStore>,
270        std::sync::Arc<crate::audit::AuditSink>,
271    )>,
272    mut request: Request,
273    next: Next,
274) -> Result<Response, StatusCode> {
275    // Auth disabled → open server (existing behavior).
276    if !store.is_enabled() {
277        return Ok(next.run(request).await);
278    }
279
280    let method = request.method().clone();
281    // Owned so it can be used in the rejection logs after `request` is consumed.
282    let matched = request
283        .extensions()
284        .get::<MatchedPath>()
285        .map(|m| m.as_str().to_owned())
286        .unwrap_or_default();
287    let required = required_capability(&method, &matched);
288
289    // Public routes (e.g. /health) skip auth entirely.
290    if required == RequiredCapability::Public {
291        return Ok(next.run(request).await);
292    }
293
294    // Extract the bearer token and resolve its capabilities.
295    // Missing header, wrong prefix, or unregistered token → 401.
296    let token = request
297        .headers()
298        .get(AUTHORIZATION)
299        .and_then(|v| v.to_str().ok())
300        .and_then(|header| store.extract_key(header));
301
302    let identity = token.as_deref().and_then(|t| store.identity(t));
303
304    let capabilities = match token.as_deref().and_then(|t| store.capabilities(t)) {
305        Some(caps) => caps,
306        None => {
307            // Logged at debug to avoid a log-flood amplifier under probing; the
308            // token value itself is never logged. `missing-token` = no/malformed
309            // Authorization header, `invalid-token` = present but unregistered.
310            let reason = if token.is_none() {
311                "missing-token"
312            } else {
313                "invalid-token"
314            };
315            tracing::debug!(%method, path = %matched, reason, "auth rejected (401)");
316            // Probing is exactly what an audit trail is asked about afterwards,
317            // so refusals are recorded as well as successes.
318            audit.record(
319                crate::audit::AuditEvent::new("denied")
320                    .with_route(format!("{method} {matched}"))
321                    .with_denial(401, reason),
322            );
323            return Err(StatusCode::UNAUTHORIZED);
324        }
325    };
326
327    // Handlers record what actually ran, and need to know who asked.
328    if let Some(identity) = identity.clone() {
329        request.extensions_mut().insert(identity);
330    }
331
332    match required {
333        // Already handled above, but keep the match exhaustive.
334        RequiredCapability::Public => Ok(next.run(request).await),
335        // Any valid token satisfies an authenticated-only route.
336        RequiredCapability::Authenticated => Ok(next.run(request).await),
337        // Specific capability: set membership (or wildcard) required, else 403.
338        RequiredCapability::Capability(cap) => {
339            if capabilities.satisfies(cap) {
340                Ok(next.run(request).await)
341            } else {
342                audit.record(
343                    crate::audit::AuditEvent::new("denied")
344                        .with_identity(identity)
345                        .with_route(format!("{method} {matched}"))
346                        .with_denial(403, format!("missing-capability:{cap}")),
347                );
348                tracing::debug!(
349                    %method,
350                    path = %matched,
351                    required = cap,
352                    "authorization denied (403): insufficient capability"
353                );
354                Err(StatusCode::FORBIDDEN)
355            }
356        }
357    }
358}
359
360/// Whether `header` names a host this server answers to.
361///
362/// Compared without the port, since the port is not what an attacker controls
363/// in a rebinding attack, and a legitimate caller may reach the same server
364/// through different ports.
365fn host_is_allowed(header: Option<&str>, allowed: &[String]) -> bool {
366    let Some(value) = header else {
367        // HTTP/1.1 requires a Host header; its absence is not a shape any
368        // ordinary client produces.
369        return false;
370    };
371
372    let host = value
373        .rsplit_once(':')
374        .map_or(value, |(host, port)| {
375            // Only strip a trailing port, not part of a bare IPv6 address.
376            if port.chars().all(|c| c.is_ascii_digit()) {
377                host
378            } else {
379                value
380            }
381        })
382        .trim_matches(|c| c == '[' || c == ']');
383
384    allowed
385        .iter()
386        .any(|candidate| candidate.eq_ignore_ascii_case(host))
387}
388
389/// Reject requests carrying a `Host` this server does not answer to.
390async fn host_check_middleware(
391    State(allowed): State<Arc<Vec<String>>>,
392    request: Request,
393    next: Next,
394) -> Result<Response, (StatusCode, String)> {
395    let header = request
396        .headers()
397        .get(axum::http::header::HOST)
398        .and_then(|value| value.to_str().ok());
399
400    if host_is_allowed(header, &allowed) {
401        return Ok(next.run(request).await);
402    }
403
404    // Named explicitly: an operator hitting this from a container or behind a
405    // proxy needs to know which name was refused and how to permit it.
406    let seen = header.unwrap_or("(none)").to_string();
407    tracing::debug!(host = %seen, "request refused: host not allowed");
408    Err((
409        StatusCode::FORBIDDEN,
410        format!(
411            "host {seen} is not allowed; pass --allow-host {seen} to permit it
412"
413        ),
414    ))
415}
416
417/// Create the API router with security enabled.
418pub fn create_secure_router(
419    state: AppState,
420    security: SecurityConfig,
421) -> (Router, Arc<ApiKeyStore>, Arc<RateLimiter>) {
422    // Create security components
423    let auth_store = Arc::new(ApiKeyStore::new(security.auth));
424    let rate_limiter = Arc::new(RateLimiter::new(security.rate_limit));
425
426    // Register API keys with their configured capabilities.
427    for key in &security.api_keys {
428        register_key(&auth_store, key, &security.capabilities);
429    }
430
431    // Session routes
432    let session_routes = Router::new()
433        .route("/", get(list_sessions).post(create_session))
434        .route("/{id}", get(get_session).delete(delete_session))
435        .route("/{id}/execute", post(execute_command))
436        .route("/{id}/ws", any(ws_handler));
437
438    // API v1 routes
439    let api_v1 = Router::new()
440        .route("/", get(api_info))
441        .route("/execute", post(execute_oneshot))
442        .route("/ws", any(ws_oneshot_handler))
443        .nest("/fs", fs_routes())
444        .nest("/sessions", session_routes);
445
446    let allowed_hosts = security.allowed_hosts.clone();
447
448    // Build main router with security layers
449    let mut router = Router::new()
450        .route("/health", get(health))
451        .nest("/api/v1", api_v1)
452        .layer(middleware::from_fn_with_state(
453            (Arc::clone(&auth_store), Arc::clone(&state.audit)),
454            capability_auth_middleware,
455        ))
456        .layer(middleware::from_fn_with_state(
457            Arc::clone(&rate_limiter),
458            rate_limit_middleware,
459        ))
460        .layer(TraceLayer::new_for_http());
461
462    // Outermost, so a rebound request is refused before it reaches the token
463    // store or the rate limiter's bookkeeping.
464    if let Some(hosts) = allowed_hosts {
465        router = router.layer(middleware::from_fn_with_state(
466            Arc::new(hosts),
467            host_check_middleware,
468        ));
469    }
470
471    // Permissive CORS only when explicitly opted in (default: restrictive).
472    if let Some(cors) = cors_layer(&security.cors) {
473        router = router.layer(cors);
474    }
475
476    let router = router.with_state(state);
477
478    (router, auth_store, rate_limiter)
479}
480
481/// Server configuration.
482#[derive(Debug, Clone)]
483pub struct ServerConfig {
484    /// Host address to bind to.
485    pub host: String,
486    /// Port to listen on.
487    pub port: u16,
488    /// Security configuration.
489    pub security: SecurityConfig,
490    /// Enable graceful shutdown on SIGTERM/SIGINT.
491    pub graceful_shutdown: bool,
492}
493
494impl ServerConfig {
495    pub fn new(host: impl Into<String>, port: u16) -> Self {
496        Self {
497            host: host.into(),
498            port,
499            security: SecurityConfig::default(),
500            graceful_shutdown: true,
501        }
502    }
503
504    pub fn bind_address(&self) -> String {
505        format!("{}:{}", self.host, self.port)
506    }
507
508    /// Enable security with the given configuration.
509    pub fn with_security(mut self, security: SecurityConfig) -> Self {
510        self.security = security;
511        self
512    }
513
514    /// Disable graceful shutdown.
515    pub fn without_graceful_shutdown(mut self) -> Self {
516        self.graceful_shutdown = false;
517        self
518    }
519}
520
521impl Default for ServerConfig {
522    fn default() -> Self {
523        Self {
524            host: "127.0.0.1".to_string(),
525            port: 3000,
526            security: SecurityConfig::default(),
527            graceful_shutdown: true,
528        }
529    }
530}
531
532/// Start the API server.
533pub async fn serve(config: ServerConfig) -> crate::Result<()> {
534    serve_with_state(config, AppState::new()).await
535}
536
537/// Bind the API server's port without starting to serve.
538///
539/// Callers that need to know the port before traffic flows — anything binding
540/// port 0, where the OS chooses — take the listener from here and hand it to
541/// [`serve_on`]. Splitting bind from serve is what makes an ephemeral port
542/// usable: the alternative is binding twice and racing whoever grabs it in
543/// between.
544pub async fn bind(config: &ServerConfig) -> crate::Result<tokio::net::TcpListener> {
545    tokio::net::TcpListener::bind(config.bind_address())
546        .await
547        .map_err(crate::error::ShellTunnelError::Io)
548}
549
550/// Start the API server with custom state.
551pub async fn serve_with_state(config: ServerConfig, state: AppState) -> crate::Result<()> {
552    let listener = bind(&config).await?;
553    serve_on(listener, config, state).await
554}
555
556/// Serve on an already-bound listener.
557pub async fn serve_on(
558    listener: tokio::net::TcpListener,
559    config: ServerConfig,
560    state: AppState,
561) -> crate::Result<()> {
562    let addr = config.bind_address();
563
564    // Create router with security
565    let (router, auth_store, _rate_limiter) = create_secure_router(state, config.security.clone());
566
567    // Log API key if auth is enabled and keys are registered
568    if auth_store.is_enabled() {
569        if auth_store.count() == 0 {
570            // Generate and register a key if none provided, scoped to the
571            // configured capabilities (full-control when unset).
572            let key = crate::security::generate_api_key();
573            register_key(&auth_store, &key, &config.security.capabilities);
574            tracing::info!("Generated API key: {}", key);
575        }
576        tracing::info!(
577            "Authentication enabled with {} API key(s)",
578            auth_store.count()
579        );
580    } else {
581        tracing::warn!("Authentication is DISABLED - server is open to all requests");
582    }
583
584    let _ = addr;
585    tracing::info!(
586        "Starting shell-tunnel API server on {}",
587        listener
588            .local_addr()
589            .map(|a| a.to_string())
590            .unwrap_or_else(|_| config.bind_address())
591    );
592
593    // Create service with connection info for rate limiting
594    let service: IntoMakeServiceWithConnectInfo<Router, SocketAddr> =
595        router.into_make_service_with_connect_info::<SocketAddr>();
596
597    if config.graceful_shutdown {
598        // Serve with graceful shutdown
599        axum::serve(listener, service)
600            .with_graceful_shutdown(shutdown_signal())
601            .await
602            .map_err(|e| {
603                crate::error::ShellTunnelError::Io(std::io::Error::other(e.to_string()))
604            })?;
605
606        tracing::info!("Server shutdown complete");
607    } else {
608        // Serve without graceful shutdown
609        axum::serve(listener, service).await.map_err(|e| {
610            crate::error::ShellTunnelError::Io(std::io::Error::other(e.to_string()))
611        })?;
612    }
613
614    Ok(())
615}
616
617/// Wait for shutdown signal (Ctrl+C or SIGTERM).
618async fn shutdown_signal() {
619    let ctrl_c = async {
620        tokio::signal::ctrl_c()
621            .await
622            .expect("Failed to install Ctrl+C handler");
623    };
624
625    #[cfg(unix)]
626    let terminate = async {
627        tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
628            .expect("Failed to install SIGTERM handler")
629            .recv()
630            .await;
631    };
632
633    #[cfg(not(unix))]
634    let terminate = std::future::pending::<()>();
635
636    tokio::select! {
637        _ = ctrl_c => {
638            tracing::info!("Received Ctrl+C, initiating graceful shutdown...");
639        }
640        _ = terminate => {
641            tracing::info!("Received SIGTERM, initiating graceful shutdown...");
642        }
643    }
644}
645
646/// Filesystem routes, shared by the plain and the secured router.
647///
648/// Built in one place so the two constructors cannot drift apart — a route
649/// present in only one of them is reachable in only one deployment shape.
650fn fs_routes() -> Router<AppState> {
651    // The chunk-upload route carries request bodies up to `MAX_CHUNK_SIZE` (8
652    // MiB) — well above axum-core's own default body limit (2 MiB, axum-core
653    // 0.5.6's `DEFAULT_LIMIT`), which this app otherwise never overrides. A
654    // client sending a chunk at the server's own advertised `chunk_size` (4
655    // MiB default) would have it rejected before `append_chunk` ever ran.
656    //
657    // Raised only for this one path, via a merged sub-router, rather than
658    // `.layer()` on the whole `fs_routes` router: the latter would also raise
659    // the limit for `/list`, `/stat`, and `/file`, none of which need an 8
660    // MiB body, and a limit set any higher up would reach `/api/v1/execute`
661    // too. Set at the hard ceiling (`MAX_CHUNK_SIZE`) rather than the
662    // *configured* `chunk_size`, so a chunk larger than configured but still
663    // under the ceiling reaches `append_chunk`'s own `TooLarge` check and
664    // gets a 413 with a machine-readable body — if axum's limit cut it off
665    // first, the caller would get a bodyless 413 with no way to tell why.
666    let upload_session_routes = Router::new()
667        .route(
668            "/uploads/{id}",
669            get(super::fs::upload_status)
670                .patch(super::fs::append_chunk)
671                .delete(super::fs::cancel_upload),
672        )
673        .route_layer(DefaultBodyLimit::max(crate::fs::MAX_CHUNK_SIZE));
674
675    Router::new()
676        .route("/list", get(super::fs::list))
677        .route("/stat", get(super::fs::stat))
678        .route(
679            "/file",
680            get(super::fs::download).delete(super::fs::delete_file),
681        )
682        .route("/uploads", post(super::fs::create_upload))
683        .merge(upload_session_routes)
684        .route("/uploads/{id}/complete", post(super::fs::complete_upload))
685}
686
687#[cfg(test)]
688mod tests {
689    use super::*;
690
691    #[test]
692    fn test_server_config_default() {
693        let config = ServerConfig::default();
694        assert_eq!(config.host, "127.0.0.1");
695        assert_eq!(config.port, 3000);
696        assert_eq!(config.bind_address(), "127.0.0.1:3000");
697        assert!(config.graceful_shutdown);
698    }
699
700    #[test]
701    fn test_server_config_custom() {
702        let config = ServerConfig::new("0.0.0.0", 8080);
703        assert_eq!(config.bind_address(), "0.0.0.0:8080");
704    }
705
706    #[test]
707    fn test_server_config_with_security() {
708        let config = ServerConfig::new("0.0.0.0", 8080)
709            .with_security(SecurityConfig::secure().with_api_key("test-key"));
710
711        assert!(config.security.auth.enabled);
712        assert_eq!(config.security.api_keys.len(), 1);
713    }
714
715    #[test]
716    fn test_security_config_default() {
717        let config = SecurityConfig::default();
718        assert!(!config.auth.enabled); // Disabled by default
719        assert!(config.rate_limit.enabled);
720    }
721
722    #[test]
723    fn test_security_config_secure() {
724        let config = SecurityConfig::secure();
725        assert!(config.auth.enabled);
726        assert!(config.rate_limit.enabled);
727    }
728
729    #[test]
730    fn test_cors_restrictive_by_default() {
731        assert!(!SecurityConfig::default().cors.allow_any);
732        assert!(!SecurityConfig::secure().cors.allow_any);
733        assert!(cors_layer(&CorsConfig::default()).is_none());
734    }
735
736    #[test]
737    fn test_cors_allow_any_opt_in() {
738        let config = SecurityConfig::development().with_cors_allow_any();
739        assert!(config.cors.allow_any);
740        assert!(cors_layer(&config.cors).is_some());
741    }
742
743    #[test]
744    fn test_security_config_development() {
745        let config = SecurityConfig::development();
746        assert!(!config.auth.enabled);
747        assert!(config.rate_limit.enabled);
748    }
749
750    #[test]
751    fn test_router_creation() {
752        let _router = create_router();
753        // Router created successfully
754    }
755
756    #[test]
757    fn test_required_capability_mapping() {
758        use RequiredCapability::{Authenticated, Capability, Public};
759
760        // Public + authenticated-only tiers.
761        assert_eq!(required_capability(&Method::GET, "/health"), Public);
762        assert_eq!(required_capability(&Method::GET, "/api/v1"), Authenticated);
763
764        // exec routes (oneshot + session-scoped + WS).
765        assert_eq!(
766            required_capability(&Method::POST, "/api/v1/execute"),
767            Capability("exec")
768        );
769        assert_eq!(
770            required_capability(&Method::GET, "/api/v1/ws"),
771            Capability("exec")
772        );
773        assert_eq!(
774            required_capability(&Method::POST, "/api/v1/sessions/{id}/execute"),
775            Capability("exec")
776        );
777        assert_eq!(
778            required_capability(&Method::GET, "/api/v1/sessions/{id}/ws"),
779            Capability("exec")
780        );
781
782        // read vs manage split on the same path, keyed by method.
783        assert_eq!(
784            required_capability(&Method::GET, "/api/v1/sessions"),
785            Capability("session.read")
786        );
787        assert_eq!(
788            required_capability(&Method::POST, "/api/v1/sessions"),
789            Capability("session.manage")
790        );
791        assert_eq!(
792            required_capability(&Method::GET, "/api/v1/sessions/{id}"),
793            Capability("session.read")
794        );
795        assert_eq!(
796            required_capability(&Method::DELETE, "/api/v1/sessions/{id}"),
797            Capability("session.manage")
798        );
799    }
800
801    #[test]
802    fn test_required_capability_unknown_fails_closed() {
803        // An unmapped route requires at least a valid token (never less).
804        assert_eq!(
805            required_capability(&Method::GET, "/api/v1/unknown"),
806            RequiredCapability::Authenticated
807        );
808    }
809
810    // A direct unit-level check of the `HEAD` normalisation lived here once,
811    // hardcoding three fs paths. It is superseded by
812    // `every_get_fs_route_authorizes_head_identically` in `tests/fs_api.rs`,
813    // which derives the same check from the one authoritative route table
814    // (shared with `every_fs_route_declares_a_capability`) instead of a
815    // second, hand-maintained list that could drift from it.
816
817    #[test]
818    fn test_secure_router_creation() {
819        let state = AppState::new();
820        let security = SecurityConfig::secure().with_api_key("test-key");
821        let (router, auth_store, rate_limiter) = create_secure_router(state, security);
822
823        assert_eq!(auth_store.count(), 1);
824        assert!(auth_store.is_valid("test-key"));
825        assert!(rate_limiter.is_enabled());
826
827        // Router should be created
828        drop(router);
829    }
830}