diff --git a/msticpy/context/azure/sentinel_watchlists.py b/msticpy/context/azure/sentinel_watchlists.py index 49082bb08..2db1a639d 100644 --- a/msticpy/context/azure/sentinel_watchlists.py +++ b/msticpy/context/azure/sentinel_watchlists.py @@ -136,7 +136,7 @@ def create_watchlist( # noqa: PLR0913 watchlist_url, headers=get_api_headers(self._token), params=params, - content=str(request_data), + json=request_data, timeout=get_http_timeout(), ) if not response.is_success: @@ -261,9 +261,9 @@ def add_watchlist_item( # noqa: PLR0912 # pylint:disable=too-many-branches copy=False, ) if (current_df == item_series).all(axis=1).any() and overwrite: - watchlist_id: str = current_items[ - current_items.isin(list(new_item.values())).any(axis=1) - ]["properties.watchlistItemId"].iloc[0] + watchlist_id: str = current_items[(current_df == item_series).all(axis=1)][ + "properties.watchlistItemId" + ].iloc[0] # If not in watchlist already generate new ID elif not (current_df == item_series).all(axis=1).any(): watchlist_id = str(uuid4()) @@ -284,7 +284,7 @@ def add_watchlist_item( # noqa: PLR0912 # pylint:disable=too-many-branches watchlist_url, headers=get_api_headers(self._token), params={"api-version": "2021-04-01"}, - content=str({"properties": {"itemsKeyValue": item}}), + json={"properties": {"itemsKeyValue": new_item}}, timeout=get_http_timeout(), ) if not response.is_success: diff --git a/tests/context/azure/test_sentinel_watchlists.py b/tests/context/azure/test_sentinel_watchlists.py index 688867b56..bab7189ee 100644 --- a/tests/context/azure/test_sentinel_watchlists.py +++ b/tests/context/azure/test_sentinel_watchlists.py @@ -4,11 +4,18 @@ # license information. # -------------------------------------------------------------------------- """Azure Sentinel unit tests.""" +import csv +import io +import json import re +from copy import deepcopy import pandas as pd +import pytest import respx +from msticpy.common.exceptions import MsticpyUserError + # pylint: disable=redefined-outer-name, unused-import, no-name-in-module from .sentinel_test_fixtures import sent_loader @@ -109,6 +116,39 @@ def test_sent_watchlists_create(sent_loader): ) +@respx.mock +def test_sent_watchlists_create_json_body(sent_loader): + """Serialize watchlist properties and CSV content as JSON.""" + create = respx.put(re.compile(r"https://management\.azure\.com/.*")).respond( + 200, json=_WATCHLISTS["value"][0] + ) + respx.get(re.compile(r"https://management\.azure\.com/.*/watchlists")).respond( + 200, json=_WATCHLISTS + ) + description = 'Analyst\'s "watchlist"\nwith notes' + data = pd.DataFrame( + [{"IpAddress": "13.67.128.10", "Note": 'Owner\'s "server",\nsecond line'}] + ) + + sent_loader.create_watchlist( + watchlist_name="Test Watchlist", + description=description, + search_key="IpAddress", + data=data, + ) + + request = create.calls[0].request + assert request.headers["Content-Type"] == "application/json" + properties = json.loads(request.content)["properties"] + assert properties["displayName"] == "Test Watchlist" + assert properties["description"] == description + assert properties["itemsSearchKey"] == "IpAddress" + assert properties["contentType"] == "text/csv" + assert list(csv.DictReader(io.StringIO(properties["rawContent"]))) == data.to_dict( + orient="records" + ) + + @respx.mock def test_sent_watchlists_delete(sent_loader): """Test Sentinel Watchlist feature.""" @@ -153,3 +193,88 @@ def test_sent_watchlists_items_add(sent_loader): sent_loader.add_watchlist_item( watchlist_name="watchlist1", item={"Type": "Owned", "IpAddress": "13.67.128.11"} ) + + +@respx.mock +def test_sent_watchlists_item_json_body(sent_loader): + """Serialize a single watchlist item as JSON without changing its values.""" + respx.get(re.compile(r"https://management\.azure\.com/.*/watchlistItems")).respond( + 200, json=_WATCHLIST_ITEM + ) + respx.get(re.compile(r"https://management\.azure\.com/.*/watchlists")).respond( + 200, json=_WATCHLISTS + ) + update = respx.put( + re.compile(r"https://management\.azure\.com/.*/watchlistItems/.*") + ).respond(200) + item = {"Type": 'Owner\'s "server"\nwith notes', "IpAddress": "13.67.128.11"} + + sent_loader.add_watchlist_item("watchlist1", item) + + request = update.calls[0].request + assert request.headers["Content-Type"] == "application/json" + assert json.loads(request.content) == {"properties": {"itemsKeyValue": item}} + + +@pytest.mark.parametrize("input_type", [dict, pd.Series, pd.DataFrame]) +@respx.mock +def test_sent_watchlists_items_normalized_rows(sent_loader, input_type): + """Send one normalized row per PUT for every supported input type.""" + respx.get(re.compile(r"https://management\.azure\.com/.*/watchlistItems")).respond( + 200, json=_WATCHLIST_ITEM + ) + respx.get(re.compile(r"https://management\.azure\.com/.*/watchlists")).respond( + 200, json=_WATCHLISTS + ) + update = respx.put( + re.compile(r"https://management\.azure\.com/.*/watchlistItems/.*") + ).respond(200) + rows = [ + {"Type": "Owned", "IpAddress": "13.67.128.11"}, + {"Type": "External", "IpAddress": "13.67.128.12"}, + ] + if input_type is pd.DataFrame: + item = pd.DataFrame(rows) + expected = rows + else: + item = input_type(rows[0]) + expected = rows[:1] + + sent_loader.add_watchlist_item("watchlist1", item) + + assert update.call_count == len(expected) + payloads = [json.loads(call.request.content) for call in update.calls] + assert payloads == [{"properties": {"itemsKeyValue": row}} for row in expected] + assert len({call.request.url.path for call in update.calls}) == len(expected) + + +@pytest.mark.parametrize("overwrite", [True, False]) +@respx.mock +def test_sent_watchlists_overwrite_exact_match(sent_loader, overwrite): + """Overwrite only the exact row when an earlier row shares a value.""" + items = deepcopy(_WATCHLIST_ITEM) + partial_match = deepcopy(items["value"][0]) + partial_match["properties"]["watchlistItemId"] = "partial-match" + partial_match["properties"]["itemsKeyValue"]["IpAddress"] = "13.67.128.11" + items["value"].insert(0, partial_match) + respx.get(re.compile(r"https://management\.azure\.com/.*/watchlistItems")).respond( + 200, json=items + ) + respx.get(re.compile(r"https://management\.azure\.com/.*/watchlists")).respond( + 200, json=_WATCHLISTS + ) + update = respx.put( + re.compile(r"https://management\.azure\.com/.*/watchlistItems/.*") + ).respond(200) + item = {"Type": "Owned", "IpAddress": "13.67.128.10"} + + if overwrite: + sent_loader.add_watchlist_item("watchlist1", item, overwrite=True) + assert update.call_count == 1 + assert update.calls[0].request.url.path.endswith( + "/watchlistItems/a681a611-8a33-41d2-a6b6-3eeaa88fd87d" + ) + else: + with pytest.raises(MsticpyUserError, match="Item already exists"): + sent_loader.add_watchlist_item("watchlist1", item) + assert not update.called