@@ -859,14 +859,49 @@ function get_ec2_instance_metadata() : array {
859859 }
860860
861861 $ client = new Client ();
862+ $ token = null ;
862863
864+ // Only support IMDSv2: require token, no fallback.
863865 try {
864- $ request = $ client ->request ( 'GET ' , 'http://169.254.169.254/latest/dynamic/instance-identity/document ' , [
865- 'timeout ' => 1 ,
866- 'on_stats ' => __NAMESPACE__ . '\\on_request_stats ' ,
867- ] );
866+ $ token_response = $ client ->request (
867+ 'PUT ' ,
868+ 'http://169.254.169.254/latest/api/token ' ,
869+ [
870+ 'timeout ' => 1 ,
871+ 'headers ' => [
872+ 'X-aws-ec2-metadata-token-ttl-seconds ' => '21600 ' ,
873+ ],
874+ 'on_stats ' => __NAMESPACE__ . '\\on_request_stats ' ,
875+ ]
876+ );
877+ if ( $ token_response ->getStatusCode () === 200 ) {
878+ $ token = (string ) $ token_response ->getBody ();
879+ } else {
880+ trigger_error ( 'IMDSv2 token request failed ' , E_USER_NOTICE );
881+ if ( function_exists ( 'apcu_store ' ) ) {
882+ apcu_store ( $ cache_key , [] );
883+ }
884+ return [];
885+ }
886+ } catch ( Exception $ e ) {
887+ trigger_error ( 'IMDSv2 token required but could not be retrieved: ' . $ e ->getMessage (), E_USER_NOTICE );
888+ if ( function_exists ( 'apcu_store ' ) ) {
889+ apcu_store ( $ cache_key , [] );
890+ }
891+ return [];
892+ }
893+
894+ try {
895+ $ request = $ client ->request (
896+ 'GET ' ,
897+ 'http://169.254.169.254/latest/dynamic/instance-identity/document ' ,
898+ [
899+ 'timeout ' => 1 ,
900+ 'headers ' => [ 'X-aws-ec2-metadata-token ' => $ token ],
901+ 'on_stats ' => __NAMESPACE__ . '\\on_request_stats ' ,
902+ ]
903+ );
868904 } catch ( Exception $ e ) {
869- // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
870905 trigger_error ( sprintf ( 'Unable to get instance metadata. Error: %s ' , $ e ->getMessage () ), E_USER_NOTICE );
871906 if ( function_exists ( 'apcu_store ' ) ) {
872907 apcu_store ( $ cache_key , [] );
@@ -875,7 +910,6 @@ function get_ec2_instance_metadata() : array {
875910 }
876911
877912 if ( $ request ->getStatusCode () !== 200 ) {
878- // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
879913 trigger_error ( sprintf ( 'Unable to get instance metadata. Returned response code: %s ' , $ request ->getStatusCode () ), E_USER_NOTICE );
880914 if ( function_exists ( 'apcu_store ' ) ) {
881915 apcu_store ( $ cache_key , [] );
@@ -884,15 +918,12 @@ function get_ec2_instance_metadata() : array {
884918 }
885919
886920 $ metadata = json_decode ( $ request ->getBody (), true );
887-
888921 if ( ! $ metadata ) {
889922 $ metadata = [];
890923 }
891-
892924 if ( function_exists ( 'apcu_store ' ) ) {
893925 apcu_store ( $ cache_key , $ metadata );
894926 }
895-
896927 return $ metadata ;
897928}
898929
0 commit comments