@@ -27,6 +27,12 @@ final class GcpMetadataConfig {
2727 static final GcpMetadataConfig DEFAULT_INSTANCE = new GcpMetadataConfig ();
2828
2929 private static final String DEFAULT_URL = "http://metadata.google.internal/computeMetadata/v1/" ;
30+ // google-auth-library-java uses 500 ms connect timeout (with up to 3 retries) for its metadata
31+ // ping and sets no read timeout; 1 s is generous for an attribute fetch on the link-local
32+ // metadata server.
33+ private static final int CONNECT_TIMEOUT_MS = 1_000 ;
34+ private static final int READ_TIMEOUT_MS = 1_000 ;
35+ private static final int MAX_METADATA_VALUE_CHARS = 4096 ;
3036 private final String url ;
3137 private final Map <String , String > cachedAttributes = new ConcurrentHashMap <>();
3238
@@ -146,13 +152,17 @@ private String fetchAttribute(String attributeName) {
146152 try {
147153 URL url = URI .create (this .url + attributeName ).toURL ();
148154 HttpURLConnection connection = (HttpURLConnection ) url .openConnection ();
155+ connection .setConnectTimeout (CONNECT_TIMEOUT_MS );
156+ connection .setReadTimeout (READ_TIMEOUT_MS );
149157 connection .setRequestProperty ("Metadata-Flavor" , "Google" );
150158 if (connection .getResponseCode () == 200
151159 && "Google" .equals (connection .getHeaderField ("Metadata-Flavor" ))) {
152160 InputStream input = connection .getInputStream ();
153161 try (BufferedReader reader =
154162 new BufferedReader (new InputStreamReader (input , StandardCharsets .UTF_8 ))) {
155- return reader .readLine ();
163+ char [] buffer = new char [MAX_METADATA_VALUE_CHARS ];
164+ int n = reader .read (buffer , 0 , buffer .length );
165+ return n > 0 ? new String (buffer , 0 , n ) : null ;
156166 }
157167 }
158168 } catch (IOException ignore ) {
0 commit comments