Skip to content

Commit ed5f422

Browse files
Harden IMDS region parsing against malformed responses
Treat a non-string resp.text (json.loads raising TypeError) and a non-string location field as malformed IMDS responses and fall back to None, so region auto-detection cannot raise during client setup. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 1153288 commit ed5f422

2 files changed

Lines changed: 19 additions & 1 deletion

File tree

msal/region.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,14 @@ def _detect_region_of_azure_vm(http_client):
5555
else:
5656
try:
5757
location = json.loads(resp.text).get("location")
58-
except (ValueError, AttributeError):
58+
except (ValueError, AttributeError, TypeError):
59+
# ValueError: body is not valid JSON;
60+
# AttributeError: body is valid JSON but not a JSON object;
61+
# TypeError: resp.text is not a string (e.g. a custom http_client).
5962
logger.info("IMDS {} returned a malformed response.".format(url))
6063
return None
64+
if location is not None and not isinstance(location, str):
65+
logger.info("IMDS {} returned a non-string location.".format(url))
66+
return None
6167
return _validate_region(location, source="IMDS endpoint")
6268

tests/test_region.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import os
22
import unittest
3+
from types import SimpleNamespace
34
from unittest.mock import patch
45

56
from msal.region import (
@@ -116,6 +117,17 @@ def test_invalid_location_value_returns_none(self):
116117
MinimalResponse(status_code=200, text='{"location": "evil.com/hijack"}'))
117118
self.assertIsNone(_detect_region_of_azure_vm(client))
118119

120+
def test_non_string_location_returns_none(self):
121+
client = _StubHttpClient(
122+
MinimalResponse(status_code=200, text='{"location": 123}'))
123+
self.assertIsNone(_detect_region_of_azure_vm(client))
124+
125+
def test_non_string_response_text_returns_none(self):
126+
# A custom http_client could yield a non-string resp.text; json.loads
127+
# would raise TypeError, which must be treated as a malformed response.
128+
client = _StubHttpClient(SimpleNamespace(status_code=200, text=None))
129+
self.assertIsNone(_detect_region_of_azure_vm(client))
130+
119131
def test_network_failure_returns_none(self):
120132
client = _StubHttpClient(IOError("IMDS unreachable"))
121133
self.assertIsNone(_detect_region_of_azure_vm(client))

0 commit comments

Comments
 (0)