@@ -29,18 +29,19 @@ use events::events;
2929use std:: {
3030 collections:: HashMap ,
3131 fs,
32- path:: { Component , PathBuf } ,
32+ path:: { Component , Path as FsPath , PathBuf } ,
3333 sync:: { Arc , RwLock } ,
3434 time:: { SystemTime , UNIX_EPOCH } ,
3535} ;
3636
3737use axum:: {
3838 Json , Router ,
39+ body:: Body ,
3940 extract:: {
4041 DefaultBodyLimit , Path , Query , State ,
4142 ws:: { Message , WebSocket , WebSocketUpgrade } ,
4243 } ,
43- http:: { StatusCode , header} ,
44+ http:: { StatusCode , Uri , header} ,
4445 response:: { IntoResponse , Response } ,
4546 routing:: { delete, get, post} ,
4647} ;
@@ -77,6 +78,7 @@ pub struct ApiState {
7778 device_template_instances : Arc < RwLock < HashMap < String , String > > > ,
7879 clock : Arc < dyn SimulatorClock > ,
7980 host_telemetry : Arc < std:: sync:: Mutex < host_telemetry:: HostTelemetrySampler > > ,
81+ web_root : Option < PathBuf > ,
8082}
8183
8284impl ApiState {
@@ -176,6 +178,7 @@ impl ApiState {
176178 host_telemetry : Arc :: new ( std:: sync:: Mutex :: new (
177179 host_telemetry:: HostTelemetrySampler :: new ( ) ,
178180 ) ) ,
181+ web_root : discover_web_root ( ) ,
179182 } )
180183 }
181184}
@@ -228,9 +231,103 @@ pub fn router(state: ApiState) -> Router {
228231 . route ( "/api/v1/faults/{id}/disable" , post ( disable_fault) )
229232 . route ( "/api/v1/telemetry/buses" , get ( telemetry:: bus_telemetry) )
230233 . route ( "/api/v1/events" , get ( events) )
234+ . fallback ( serve_web)
231235 . with_state ( state)
232236}
233237
238+ fn discover_web_root ( ) -> Option < PathBuf > {
239+ if let Some ( path) = std:: env:: var_os ( "VDS4E_WEB_ROOT" ) . map ( PathBuf :: from) {
240+ return path. join ( "index.html" ) . is_file ( ) . then_some ( path) ;
241+ }
242+ [
243+ PathBuf :: from ( "build/web" ) ,
244+ PathBuf :: from ( "/usr/local/share/vds4e/web" ) ,
245+ PathBuf :: from ( "/usr/share/vds4e/web" ) ,
246+ ]
247+ . into_iter ( )
248+ . find ( |path| path. join ( "index.html" ) . is_file ( ) )
249+ }
250+
251+ async fn serve_web ( State ( state) : State < ApiState > , uri : Uri ) -> Response {
252+ if uri. path ( ) == "/api" || uri. path ( ) . starts_with ( "/api/" ) {
253+ return StatusCode :: NOT_FOUND . into_response ( ) ;
254+ }
255+ let Some ( root) = state. web_root . as_ref ( ) else {
256+ return StatusCode :: NOT_FOUND . into_response ( ) ;
257+ } ;
258+ let Some ( relative) = safe_web_path ( uri. path ( ) ) else {
259+ return StatusCode :: NOT_FOUND . into_response ( ) ;
260+ } ;
261+
262+ let requested = root. join ( & relative) ;
263+ let selected = if relative. as_os_str ( ) . is_empty ( ) {
264+ root. join ( "index.html" )
265+ } else if tokio:: fs:: metadata ( & requested)
266+ . await
267+ . is_ok_and ( |metadata| metadata. is_file ( ) )
268+ {
269+ requested
270+ } else if relative. extension ( ) . is_none ( ) {
271+ root. join ( "index.html" )
272+ } else {
273+ return StatusCode :: NOT_FOUND . into_response ( ) ;
274+ } ;
275+
276+ match tokio:: fs:: read ( & selected) . await {
277+ Ok ( bytes) => {
278+ let cache_control = if uri. path ( ) . starts_with ( "/assets/" ) {
279+ "public, max-age=31536000, immutable"
280+ } else {
281+ "no-cache"
282+ } ;
283+ Response :: builder ( )
284+ . status ( StatusCode :: OK )
285+ . header ( header:: CONTENT_TYPE , web_content_type ( & selected) )
286+ . header ( header:: CACHE_CONTROL , cache_control)
287+ . body ( Body :: from ( bytes) )
288+ . unwrap_or_else ( |_| StatusCode :: INTERNAL_SERVER_ERROR . into_response ( ) )
289+ }
290+ Err ( error) if error. kind ( ) == std:: io:: ErrorKind :: NotFound => {
291+ StatusCode :: NOT_FOUND . into_response ( )
292+ }
293+ Err ( _) => StatusCode :: INTERNAL_SERVER_ERROR . into_response ( ) ,
294+ }
295+ }
296+
297+ fn safe_web_path ( path : & str ) -> Option < PathBuf > {
298+ let trimmed = path. trim_start_matches ( '/' ) ;
299+ if trimmed. is_empty ( ) {
300+ return Some ( PathBuf :: new ( ) ) ;
301+ }
302+ let path = PathBuf :: from ( trimmed) ;
303+ path. components ( )
304+ . all ( |component| matches ! ( component, Component :: Normal ( _) ) )
305+ . then_some ( path)
306+ }
307+
308+ fn web_content_type ( path : & FsPath ) -> & ' static str {
309+ match path
310+ . extension ( )
311+ . and_then ( |extension| extension. to_str ( ) )
312+ . map ( str:: to_ascii_lowercase)
313+ . as_deref ( )
314+ {
315+ Some ( "html" ) => "text/html; charset=utf-8" ,
316+ Some ( "css" ) => "text/css; charset=utf-8" ,
317+ Some ( "js" | "mjs" ) => "text/javascript; charset=utf-8" ,
318+ Some ( "json" | "map" ) => "application/json; charset=utf-8" ,
319+ Some ( "svg" ) => "image/svg+xml" ,
320+ Some ( "png" ) => "image/png" ,
321+ Some ( "jpg" | "jpeg" ) => "image/jpeg" ,
322+ Some ( "webp" ) => "image/webp" ,
323+ Some ( "gif" ) => "image/gif" ,
324+ Some ( "ico" ) => "image/x-icon" ,
325+ Some ( "woff" ) => "font/woff" ,
326+ Some ( "woff2" ) => "font/woff2" ,
327+ _ => "application/octet-stream" ,
328+ }
329+ }
330+
234331#[ derive( Serialize ) ]
235332struct Health {
236333 status : & ' static str ,
@@ -365,3 +462,26 @@ impl IntoResponse for ApiError {
365462 . into_response ( )
366463 }
367464}
465+
466+
467+ #[ cfg( test) ]
468+ mod web_asset_tests {
469+ use super :: { safe_web_path, web_content_type} ;
470+ use std:: path:: Path ;
471+
472+ #[ test]
473+ fn web_paths_reject_parent_traversal ( ) {
474+ assert ! ( safe_web_path( "/assets/app.js" ) . is_some( ) ) ;
475+ assert ! ( safe_web_path( "/devices/example" ) . is_some( ) ) ;
476+ assert ! ( safe_web_path( "/../etc/passwd" ) . is_none( ) ) ;
477+ assert ! ( safe_web_path( "/assets/../secret" ) . is_none( ) ) ;
478+ }
479+
480+ #[ test]
481+ fn web_content_types_cover_vite_assets ( ) {
482+ assert_eq ! ( web_content_type( Path :: new( "index.html" ) ) , "text/html; charset=utf-8" ) ;
483+ assert_eq ! ( web_content_type( Path :: new( "assets/app.js" ) ) , "text/javascript; charset=utf-8" ) ;
484+ assert_eq ! ( web_content_type( Path :: new( "assets/app.css" ) ) , "text/css; charset=utf-8" ) ;
485+ assert_eq ! ( web_content_type( Path :: new( "assets/logo.svg" ) ) , "image/svg+xml" ) ;
486+ }
487+ }
0 commit comments