@@ -26,6 +26,9 @@ const API_TIMEOUT: Duration = Duration::from_secs(30);
2626/// Maximum allowed size for the event stream line buffer (1 MB).
2727const MAX_EVENT_BUFFER : usize = 1_048_576 ;
2828
29+ /// Image account databases are metadata, not unrestricted archive downloads.
30+ const MAX_IMAGE_ACCOUNT_BYTES : usize = 1_048_576 ;
31+
2932#[ derive( Debug , thiserror:: Error ) ]
3033pub enum PodmanApiError {
3134 #[ error( "podman API not found (404): {0}" ) ]
@@ -281,6 +284,38 @@ pub struct SecurityInfo {
281284
282285// ── Client ───────────────────────────────────────────────────────────────
283286
287+ fn extract_image_account_file ( archive : & [ u8 ] ) -> Result < Vec < u8 > , PodmanApiError > {
288+ use std:: io:: Read as _;
289+
290+ let invalid = |error : std:: io:: Error | {
291+ PodmanApiError :: InvalidInput ( format ! ( "invalid image account archive: {error}" ) )
292+ } ;
293+ let mut archive = tar:: Archive :: new ( archive) ;
294+ let mut entries = archive. entries ( ) . map_err ( invalid) ?;
295+ let entry = entries
296+ . next ( )
297+ . ok_or_else ( || PodmanApiError :: InvalidInput ( "empty image account archive" . into ( ) ) ) ?
298+ . map_err ( invalid) ?;
299+ if !entry. header ( ) . entry_type ( ) . is_file ( ) || entry. size ( ) > MAX_IMAGE_ACCOUNT_BYTES as u64 {
300+ return Err ( PodmanApiError :: InvalidInput ( format ! (
301+ "image account must be a regular file of at most {MAX_IMAGE_ACCOUNT_BYTES} bytes"
302+ ) ) ) ;
303+ }
304+ let mut bytes = Vec :: new ( ) ;
305+ // Bound extraction independently: sparse/PAX tar metadata must not expand
306+ // a small wire archive into an unbounded account database.
307+ entry
308+ . take ( MAX_IMAGE_ACCOUNT_BYTES as u64 + 1 )
309+ . read_to_end ( & mut bytes)
310+ . map_err ( invalid) ?;
311+ if bytes. len ( ) > MAX_IMAGE_ACCOUNT_BYTES {
312+ return Err ( PodmanApiError :: InvalidInput (
313+ "image account payload exceeds size limit" . into ( ) ,
314+ ) ) ;
315+ }
316+ Ok ( bytes)
317+ }
318+
284319/// Async Podman REST API client communicating over a Unix socket.
285320#[ derive( Debug , Clone ) ]
286321pub struct PodmanClient {
@@ -628,6 +663,94 @@ impl PodmanClient {
628663 }
629664 }
630665
666+ /// Fetch archive metadata without reading an image-controlled response body.
667+ pub ( crate ) async fn container_path_exists (
668+ & self ,
669+ name : & str ,
670+ path : & str ,
671+ ) -> Result < bool , PodmanApiError > {
672+ let response = self
673+ . image_metadata_response ( name, path, hyper:: Method :: HEAD )
674+ . await ?;
675+ // Libpod returns 404 for a dangling symlink, but still supplies its
676+ // lstat metadata. Such a path exists and must never pass admission.
677+ if response
678+ . headers ( )
679+ . contains_key ( "x-docker-container-path-stat" )
680+ {
681+ return Ok ( true ) ;
682+ }
683+ match response. status ( ) . as_u16 ( ) {
684+ 200 => Ok ( true ) ,
685+ 404 => Ok ( false ) ,
686+ status => Err ( PodmanApiError :: Api {
687+ status,
688+ message : "container image path metadata probe failed" . into ( ) ,
689+ } ) ,
690+ }
691+ }
692+
693+ /// Bound both the wire archive and its extracted account-file payload.
694+ pub ( crate ) async fn copy_image_account_file (
695+ & self ,
696+ name : & str ,
697+ path : & str ,
698+ ) -> Result < Vec < u8 > , PodmanApiError > {
699+ let response = self
700+ . image_metadata_response ( name, path, hyper:: Method :: GET )
701+ . await ?;
702+ let status = response. status ( ) ;
703+ if status == hyper:: StatusCode :: NOT_FOUND {
704+ return Ok ( Vec :: new ( ) ) ;
705+ }
706+ if !status. is_success ( ) {
707+ return Err ( PodmanApiError :: Api {
708+ status : status. as_u16 ( ) ,
709+ message : "container image account download failed" . into ( ) ,
710+ } ) ;
711+ }
712+ let archive = tokio:: time:: timeout (
713+ API_TIMEOUT ,
714+ http_body_util:: Limited :: new ( response. into_body ( ) , MAX_IMAGE_ACCOUNT_BYTES ) . collect ( ) ,
715+ )
716+ . await
717+ . map_err ( |_| PodmanApiError :: Timeout ( API_TIMEOUT ) ) ?
718+ . map_err ( |error| {
719+ PodmanApiError :: InvalidInput ( format ! (
720+ "image account archive must fit within {MAX_IMAGE_ACCOUNT_BYTES} bytes: {error}"
721+ ) )
722+ } ) ?
723+ . to_bytes ( ) ;
724+ extract_image_account_file ( & archive)
725+ }
726+
727+ async fn image_metadata_response (
728+ & self ,
729+ name : & str ,
730+ path : & str ,
731+ method : hyper:: Method ,
732+ ) -> Result < hyper:: Response < hyper:: body:: Incoming > , PodmanApiError > {
733+ validate_name ( name) ?;
734+ let request = Self :: build_request (
735+ method,
736+ & format ! (
737+ "/{API_VERSION}/libpod/containers/{name}/archive?path={}" ,
738+ url_encode( path)
739+ ) ,
740+ Full :: new ( Bytes :: new ( ) ) ,
741+ None ,
742+ ) ;
743+ tokio:: time:: timeout ( API_TIMEOUT , async {
744+ let mut sender = self . connect ( ) . await ?;
745+ sender
746+ . send_request ( request)
747+ . await
748+ . map_err ( |error| PodmanApiError :: Connection ( error. to_string ( ) ) )
749+ } )
750+ . await
751+ . map_err ( |_| PodmanApiError :: Timeout ( API_TIMEOUT ) ) ?
752+ }
753+
631754 /// Inspect a container by name or ID.
632755 pub async fn inspect_container ( & self , name : & str ) -> Result < ContainerInspect , PodmanApiError > {
633756 validate_name ( name) ?;
@@ -1001,6 +1124,144 @@ mod tests {
10011124 use crate :: test_utils:: { StubResponse , spawn_podman_stub} ;
10021125 use hyper:: StatusCode ;
10031126
1127+ #[ tokio:: test]
1128+ async fn image_path_probe_uses_head_and_fails_closed_on_server_errors ( ) {
1129+ let ( path, requests, server) = spawn_podman_stub (
1130+ "image-path-head" ,
1131+ vec ! [
1132+ StubResponse :: new( StatusCode :: OK , vec![ 0 ; MAX_IMAGE_ACCOUNT_BYTES + 1 ] ) ,
1133+ StubResponse :: new( StatusCode :: NOT_FOUND , "" ) ,
1134+ StubResponse :: new( StatusCode :: INTERNAL_SERVER_ERROR , "" ) ,
1135+ ] ,
1136+ ) ;
1137+ let client = PodmanClient :: new ( path) ;
1138+ assert ! (
1139+ client
1140+ . container_path_exists( "image" , "/.openshell" )
1141+ . await
1142+ . unwrap( )
1143+ ) ;
1144+ assert ! (
1145+ !client
1146+ . container_path_exists( "image" , "/.openshell" )
1147+ . await
1148+ . unwrap( )
1149+ ) ;
1150+ assert ! (
1151+ client
1152+ . container_path_exists( "image" , "/.openshell" )
1153+ . await
1154+ . is_err( )
1155+ ) ;
1156+ server. await . unwrap ( ) ;
1157+ assert ! (
1158+ requests. lock( ) . unwrap( ) . iter( ) . all( |request| request
1159+ == "HEAD /v5.0.0/libpod/containers/image/archive?path=%2F.openshell" )
1160+ ) ;
1161+ }
1162+
1163+ #[ tokio:: test]
1164+ async fn image_path_probe_rejects_dangling_symlink_metadata_on_404 ( ) {
1165+ let path = crate :: test_utils:: unique_socket_path ( "dangling-root-head" ) ;
1166+ let listener = tokio:: net:: UnixListener :: bind ( & path) . unwrap ( ) ;
1167+ let server = tokio:: spawn ( async move {
1168+ let ( stream, _) = listener. accept ( ) . await . unwrap ( ) ;
1169+ let _ = hyper:: server:: conn:: http1:: Builder :: new ( )
1170+ . serve_connection (
1171+ TokioIo :: new ( stream) ,
1172+ hyper:: service:: service_fn ( |request| async move {
1173+ assert_eq ! ( request. method( ) , hyper:: Method :: HEAD ) ;
1174+ Ok :: < _ , std:: convert:: Infallible > (
1175+ hyper:: Response :: builder ( )
1176+ . status ( StatusCode :: NOT_FOUND )
1177+ // Its contents need not be decoded: any stat metadata
1178+ // proves this is not an absent directory entry.
1179+ . header ( "x-docker-container-path-stat" , "present" )
1180+ . body ( Full :: new ( Bytes :: new ( ) ) )
1181+ . unwrap ( ) ,
1182+ )
1183+ } ) ,
1184+ )
1185+ . await ;
1186+ } ) ;
1187+ let client = PodmanClient :: new ( path. clone ( ) ) ;
1188+ assert ! (
1189+ client
1190+ . container_path_exists( "image" , "/.openshell" )
1191+ . await
1192+ . unwrap( )
1193+ ) ;
1194+ server. await . unwrap ( ) ;
1195+ std:: fs:: remove_file ( path) . unwrap ( ) ;
1196+ }
1197+
1198+ #[ tokio:: test]
1199+ async fn image_account_download_rejects_oversized_archive ( ) {
1200+ let ( path, _, server) = spawn_podman_stub (
1201+ "account-wire-limit" ,
1202+ vec ! [ StubResponse :: new(
1203+ StatusCode :: OK ,
1204+ vec![ 0 ; MAX_IMAGE_ACCOUNT_BYTES + 1 ] ,
1205+ ) ] ,
1206+ ) ;
1207+ let client = PodmanClient :: new ( path) ;
1208+ let error = client
1209+ . copy_image_account_file ( "image" , "/etc/passwd" )
1210+ . await
1211+ . unwrap_err ( ) ;
1212+ assert ! ( error. to_string( ) . contains( "archive must fit within" ) ) ;
1213+ server. await . unwrap ( ) ;
1214+ }
1215+
1216+ #[ test]
1217+ fn image_account_extraction_rejects_oversized_header_before_allocating_payload ( ) {
1218+ let mut header = tar:: Header :: new_gnu ( ) ;
1219+ header. set_entry_type ( tar:: EntryType :: Regular ) ;
1220+ header. set_path ( "passwd" ) . unwrap ( ) ;
1221+ header. set_mode ( 0o644 ) ;
1222+ header. set_size ( u64:: MAX / 2 ) ;
1223+ header. set_cksum ( ) ;
1224+ let error = extract_image_account_file ( header. as_bytes ( ) ) . unwrap_err ( ) ;
1225+ assert ! ( error. to_string( ) . contains( "regular file of at most" ) ) ;
1226+ }
1227+
1228+ #[ tokio:: test]
1229+ async fn image_account_download_accepts_regular_file_and_missing_database ( ) {
1230+ let mut archive = tar:: Builder :: new ( Vec :: new ( ) ) ;
1231+ let payload = b"agent:x:1000:1000::/sandbox:/bin/sh\n " ;
1232+ let mut header = tar:: Header :: new_gnu ( ) ;
1233+ header. set_entry_type ( tar:: EntryType :: Regular ) ;
1234+ header. set_mode ( 0o644 ) ;
1235+ header. set_size ( payload. len ( ) as u64 ) ;
1236+ header. set_cksum ( ) ;
1237+ archive
1238+ . append_data ( & mut header, "passwd" , payload. as_slice ( ) )
1239+ . unwrap ( ) ;
1240+ let ( path, _, server) = spawn_podman_stub (
1241+ "account-regular" ,
1242+ vec ! [
1243+ StubResponse :: new( StatusCode :: OK , archive. into_inner( ) . unwrap( ) ) ,
1244+ StubResponse :: new( StatusCode :: NOT_FOUND , "" ) ,
1245+ ] ,
1246+ ) ;
1247+ let client = PodmanClient :: new ( path) ;
1248+ assert_eq ! (
1249+ client
1250+ . copy_image_account_file( "image" , "/etc/passwd" )
1251+ . await
1252+ . unwrap( ) ,
1253+ payload
1254+ ) ;
1255+ assert ! (
1256+ client
1257+ . copy_image_account_file( "image" , "/etc/group" )
1258+ . await
1259+ . unwrap( )
1260+ . is_empty( )
1261+ ) ;
1262+ server. await . unwrap ( ) ;
1263+ }
1264+
10041265 #[ test]
10051266 fn url_encode_encodes_special_characters ( ) {
10061267 assert_eq ! ( url_encode( "hello world" ) , "hello%20world" ) ;
0 commit comments