Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 26 additions & 5 deletions attack_range/cloud_providers/azure_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,41 @@
import re
from typing import Optional
import os
from collections.abc import Mapping

from .base_provider import BaseCloudProvider, BackendParams

# Azure imports
try:
from azure.identity import DefaultAzureCredential
from azure.mgmt.storage import StorageManagementClient
from azure.mgmt.resource import ResourceManagementClient
try:
# azure-mgmt-resource >= 24 moved the client into the "resources" subpackage
from azure.mgmt.resource.resources import ResourceManagementClient
except ImportError:
from azure.mgmt.resource import ResourceManagementClient
from azure.core.exceptions import AzureError, ResourceNotFoundError
from azure.storage.blob import BlobServiceClient
from azure.mgmt.storage.models import StorageAccountCreateParameters, Sku, Kind
AZURE_AVAILABLE = True
except ImportError:
AZURE_IMPORT_ERROR = None
except ImportError as e:
AZURE_AVAILABLE = False
AZURE_IMPORT_ERROR = e


def _first_storage_key(list_keys_result) -> str:
"""
Return the first key value from a StorageAccountListKeysResult.

azure-mgmt-storage >= 25 models are MutableMappings, so `.keys` is the dict
method rather than the key list; older (msrest) models only support attributes.
"""
if isinstance(list_keys_result, Mapping):
key_list = list_keys_result["keys"]
else:
key_list = list_keys_result.keys
return key_list[0].value


class AzureProvider(BaseCloudProvider):
Expand All @@ -32,7 +53,7 @@ def __init__(self, config: dict, logger):
"""Initialize Azure provider."""
super().__init__(config, logger)
if not AZURE_AVAILABLE:
self.logger.warning("Azure SDK not available. Some features may not work.")
self.logger.warning(f"Azure SDK not available ({AZURE_IMPORT_ERROR}). Some features may not work.")

def get_region(self, required: bool = True) -> Optional[str]:
"""
Expand Down Expand Up @@ -183,7 +204,7 @@ def check_storage_container(self, account_name: str, container_name: str, resour

# Get storage account keys
keys = storage_client.storage_accounts.list_keys(resource_group_name, account_name)
key = keys.keys[0].value
key = _first_storage_key(keys)

# Use Azure Storage SDK to check container
blob_service_client = BlobServiceClient(
Expand Down Expand Up @@ -221,7 +242,7 @@ def create_storage_container(self, account_name: str, container_name: str, resou

# Get storage account keys
keys = storage_client.storage_accounts.list_keys(resource_group_name, account_name)
key = keys.keys[0].value
key = _first_storage_key(keys)

# Use Azure Storage SDK to create container
blob_service_client = BlobServiceClient(
Expand Down
37 changes: 37 additions & 0 deletions tests/test_azure_provider.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
"""
Regression tests for Azure provider SDK compatibility.

azure-mgmt-resource >= 24 moved ResourceManagementClient into the "resources"
subpackage, and azure-mgmt-storage >= 25 models are MutableMappings (so `.keys`
is the dict method, not the key list). Both broke the Azure backend setup.
"""

import sys
from types import SimpleNamespace
from unittest.mock import MagicMock

sys.modules.setdefault("ansible_runner", MagicMock())
sys.modules.setdefault("python_vagrant", MagicMock())

import pytest

azure_provider = pytest.importorskip("attack_range.cloud_providers.azure_provider")


def test_azure_sdk_imports_succeed():
"""All Azure SDK imports must succeed with the pinned requirements."""
assert azure_provider.AZURE_AVAILABLE, f"Azure SDK import failed: {azure_provider.AZURE_IMPORT_ERROR}"


def test_first_storage_key_with_mapping_model():
"""azure-mgmt-storage >= 25 returns dict-like models."""
from azure.mgmt.storage.models import StorageAccountListKeysResult

result = StorageAccountListKeysResult({"keys": [{"keyName": "key1", "value": "secret1"}]})
assert azure_provider._first_storage_key(result) == "secret1"


def test_first_storage_key_with_attribute_model():
"""Older msrest-based models expose keys only as an attribute."""
result = SimpleNamespace(keys=[SimpleNamespace(value="secret1")])
assert azure_provider._first_storage_key(result) == "secret1"