@@ -19,11 +19,13 @@ use crate::ServerState;
1919use crate :: auth:: workspace_authz:: {
2020 AuthorizedWorkspaceScope , MinWorkspaceRole , authorize_list_workspace_selector,
2121} ;
22+ use crate :: compute:: MutationScope ;
2223use crate :: pagination:: Pagination ;
2324use crate :: persistence:: { ObjectListQuery , ObjectType , WriteCondition } ;
2425use crate :: service_routing;
2526
2627const MAX_SERVICE_NAME_LEN : usize = super :: MAX_ROUTABLE_NAME_LEN ;
28+ const MAX_APP_SERVICE_ROUTES : u32 = 1024 ;
2729
2830#[ cfg( test) ]
2931#[ derive( Default ) ]
@@ -92,6 +94,21 @@ pub(super) async fn expose_service_endpoint(
9294 authorization_mode : ServiceAuthorizationMode ,
9395) -> Result < Response < ServiceEndpointResponse > , Status > {
9496 let sandbox_name = sandbox. object_name ( ) ;
97+ // Count and persist under the same fleet-wide sandbox guard, including
98+ // create-time exposure, so concurrent gateways cannot overfill the allowlist.
99+ let _mutation_guard = if state. config . supervisor_app_listener . enabled {
100+ Some (
101+ state
102+ . compute
103+ . mutation_guard ( MutationScope :: sandbox ( workspace, sandbox. object_id ( ) ) )
104+ . await
105+ . map_err ( |error| {
106+ super :: persistence_error_to_status ( error, "acquire sandbox mutation lock" )
107+ } ) ?,
108+ )
109+ } else {
110+ None
111+ } ;
95112
96113 let now = crate :: persistence:: current_time_ms ( ) ;
97114 let key = service_routing:: endpoint_key ( sandbox_name, service) ;
@@ -103,6 +120,15 @@ pub(super) async fn expose_service_endpoint(
103120 . await
104121 . map_err ( |e| Status :: internal ( format ! ( "fetch endpoint failed: {e}" ) ) ) ?;
105122
123+ if state. config . supervisor_app_listener . enabled
124+ && existing. is_none ( )
125+ && app_service_endpoints ( state, sandbox) . await ?. len ( ) >= MAX_APP_SERVICE_ROUTES as usize
126+ {
127+ return Err ( Status :: resource_exhausted (
128+ "too many application service declarations" ,
129+ ) ) ;
130+ }
131+
106132 let ( id, created_at_ms, condition, created) = if let Some ( existing) = existing {
107133 // Update path: preserve id and created_at, use CAS to prevent conflicts
108134 let resource_version = existing
@@ -383,26 +409,8 @@ pub(super) async fn configured_app_routes(
383409 if !state. config . supervisor_app_listener . enabled {
384410 return Ok ( Vec :: new ( ) ) ;
385411 }
386- let selector = format ! ( "sandbox={}" , sandbox. object_name( ) ) ;
387- let page = state
388- . store
389- . list_message_page :: < ServiceEndpoint > (
390- ObjectListQuery :: WorkspaceSelector {
391- workspace : sandbox. object_workspace ( ) ,
392- label_selector : & selector,
393- } ,
394- None ,
395- 1024 ,
396- )
397- . await
398- . map_err ( |_| Status :: unavailable ( "service declarations unavailable" ) ) ?;
399- if page. next_cursor . is_some ( ) {
400- return Err ( Status :: resource_exhausted (
401- "too many application service declarations" ,
402- ) ) ;
403- }
404- let mut service_routes: Vec < _ > = page
405- . messages
412+ let mut service_routes: Vec < _ > = app_service_endpoints ( state, sandbox)
413+ . await ?
406414 . into_iter ( )
407415 . filter ( |ep| {
408416 ep. sandbox_id == sandbox. object_id ( )
@@ -424,6 +432,31 @@ pub(super) async fn configured_app_routes(
424432 Ok ( service_routes)
425433}
426434
435+ async fn app_service_endpoints (
436+ state : & ServerState ,
437+ sandbox : & Sandbox ,
438+ ) -> Result < Vec < ServiceEndpoint > , Status > {
439+ let selector = format ! ( "sandbox={}" , sandbox. object_name( ) ) ;
440+ let page = state
441+ . store
442+ . list_message_page :: < ServiceEndpoint > (
443+ ObjectListQuery :: WorkspaceSelector {
444+ workspace : sandbox. object_workspace ( ) ,
445+ label_selector : & selector,
446+ } ,
447+ None ,
448+ MAX_APP_SERVICE_ROUTES ,
449+ )
450+ . await
451+ . map_err ( |_| Status :: unavailable ( "service declarations unavailable" ) ) ?;
452+ if page. next_cursor . is_some ( ) {
453+ return Err ( Status :: resource_exhausted (
454+ "too many application service declarations" ,
455+ ) ) ;
456+ }
457+ Ok ( page. messages )
458+ }
459+
427460async fn get_service_endpoint (
428461 state : & Arc < ServerState > ,
429462 workspace : & str ,
@@ -536,6 +569,130 @@ mod tests {
536569 state. store . put_message ( & sandbox) . await . unwrap ( ) ;
537570 }
538571
572+ async fn app_listener_state ( ) -> Arc < ServerState > {
573+ let mut state = test_server_state ( ) . await ;
574+ Arc :: get_mut ( & mut state)
575+ . unwrap ( )
576+ . config
577+ . supervisor_app_listener = openshell_core:: app_listener:: AppListenerConfig {
578+ enabled : true ,
579+ port : 9443 ,
580+ domain : "services.example.com" . into ( ) ,
581+ } ;
582+ seed_sandbox ( & state, "limited" ) . await ;
583+ state
584+ }
585+
586+ async fn seed_app_services ( state : & Arc < ServerState > , count : u32 ) {
587+ for index in 0 ..count {
588+ let name = format ! ( "web-{index}" ) ;
589+ state
590+ . store
591+ . put_message ( & ServiceEndpoint {
592+ metadata : Some ( ObjectMeta {
593+ id : format ! ( "endpoint-{index}" ) ,
594+ name : service_routing:: endpoint_key ( "limited" , & name) ,
595+ workspace : "default" . into ( ) ,
596+ labels : HashMap :: from ( [ ( "sandbox" . into ( ) , "limited" . into ( ) ) ] ) ,
597+ ..Default :: default ( )
598+ } ) ,
599+ sandbox_id : "sandbox-limited" . into ( ) ,
600+ sandbox : "limited" . into ( ) ,
601+ name,
602+ target_port : 8080 ,
603+ domain : true ,
604+ authorization_mode : ServiceAuthorizationMode :: Strip as i32 ,
605+ } )
606+ . await
607+ . unwrap ( ) ;
608+ }
609+ }
610+
611+ async fn expose_limited (
612+ state : & Arc < ServerState > ,
613+ name : & str ,
614+ ) -> Result < Response < ServiceEndpointResponse > , Status > {
615+ handle_expose_service (
616+ state,
617+ authed_request ( ExposeServiceRequest {
618+ sandbox : "limited" . into ( ) ,
619+ name : name. into ( ) ,
620+ target_port : 9090 ,
621+ workspace_scope : Some ( openshell_core:: proto:: workspace_selector ( "default" ) ) ,
622+ ..Default :: default ( )
623+ } ) ,
624+ )
625+ . await
626+ }
627+
628+ #[ tokio:: test]
629+ async fn app_listener_rejects_overflow_before_persistence_and_keeps_config_deliverable ( ) {
630+ let state = app_listener_state ( ) . await ;
631+ seed_app_services ( & state, MAX_APP_SERVICE_ROUTES ) . await ;
632+ assert_eq ! (
633+ expose_limited( & state, "overflow" ) . await . unwrap_err( ) . code( ) ,
634+ tonic:: Code :: ResourceExhausted
635+ ) ;
636+ assert ! (
637+ get_service_endpoint( & state, "default" , "limited" , "overflow" )
638+ . await
639+ . unwrap( )
640+ . is_none( )
641+ ) ;
642+ // Editing a route at capacity must remain possible, as must unrelated
643+ // policy changes and the complete configuration that delivers them.
644+ expose_limited ( & state, "web-0" ) . await . unwrap ( ) ;
645+ super :: super :: policy:: handle_update_config (
646+ & state,
647+ authed_request ( openshell_core:: proto:: UpdateConfigRequest {
648+ sandbox : "limited" . into ( ) ,
649+ workspace_scope : Some ( openshell_core:: proto:: workspace_selector ( "default" ) ) ,
650+ policy : Some ( openshell_policy:: restrictive_default_policy ( ) ) ,
651+ ..Default :: default ( )
652+ } ) ,
653+ )
654+ . await
655+ . unwrap ( ) ;
656+ let sandbox = state
657+ . store
658+ . get_message :: < Sandbox > ( "sandbox-limited" )
659+ . await
660+ . unwrap ( )
661+ . unwrap ( ) ;
662+ let config = super :: super :: policy:: load_sandbox_config ( & state, & sandbox)
663+ . await
664+ . unwrap ( ) ;
665+ assert_eq ! ( config. service_routes. len( ) , MAX_APP_SERVICE_ROUTES as usize ) ;
666+ assert ! ( config. policy. is_some( ) ) ;
667+ assert_eq ! ( config. service_routes[ 0 ] . target_port, 9090 ) ;
668+ }
669+
670+ #[ tokio:: test]
671+ async fn app_listener_concurrent_exposures_cannot_exceed_capacity ( ) {
672+ let state = app_listener_state ( ) . await ;
673+ seed_app_services ( & state, MAX_APP_SERVICE_ROUTES - 1 ) . await ;
674+ let barrier = Arc :: new ( tokio:: sync:: Barrier :: new ( 2 ) ) ;
675+ let spawn_exposure = |name : & ' static str | {
676+ let state = state. clone ( ) ;
677+ let barrier = barrier. clone ( ) ;
678+ tokio:: spawn ( async move {
679+ barrier. wait ( ) . await ;
680+ expose_limited ( & state, name) . await
681+ } )
682+ } ;
683+ let ( first, second) = tokio:: join!( spawn_exposure( "first" ) , spawn_exposure( "second" ) ) ;
684+ let results = [ first. unwrap ( ) , second. unwrap ( ) ] ;
685+ assert_eq ! ( results. iter( ) . filter( |result| result. is_ok( ) ) . count( ) , 1 ) ;
686+ assert_eq ! (
687+ results
688+ . iter( )
689+ . find_map( |result| result. as_ref( ) . err( ) )
690+ . unwrap( )
691+ . code( ) ,
692+ tonic:: Code :: ResourceExhausted
693+ ) ;
694+ }
695+
539696 #[ test]
540697 fn validates_good_endpoint_name ( ) {
541698 validate_endpoint_name ( "service" , "web-api" , 28 ) . unwrap ( ) ;
0 commit comments