diff --git a/src/azure-cli/azure/cli/command_modules/cognitiveservices/_agent_hosting.py b/src/azure-cli/azure/cli/command_modules/cognitiveservices/_agent_hosting.py index ef616324a79..a2613a5c071 100644 --- a/src/azure-cli/azure/cli/command_modules/cognitiveservices/_agent_hosting.py +++ b/src/azure-cli/azure/cli/command_modules/cognitiveservices/_agent_hosting.py @@ -10,7 +10,10 @@ from azure.cli.core.azclierror import ValidationError from knack.log import get_logger -from ._agent_hosting_preflight import build_request, preflight, _missing_identity_fields, _storage_parameters +from ._agent_hosting_preflight import ( + build_request, preflight, _accepted_role_ids, _missing_identity_fields, + _resource_name, _role_guid, _storage_parameters, +) from ._client_factory import get_agent_hosting_clients @@ -28,8 +31,7 @@ def prepare_agent_hosting(cmd, resource_group_name, account_name, location, tags try: return provision(cmd.cli_ctx, checked, tags, request=request) except (AzureError, ValidationError): - logger.warning('BYO AKS dependency preparation failed. Resources and role assignments created before the ' - 'failure were not deleted. Review the preceding messages before retrying.') + logger.warning('BYO AKS dependency preparation failed; resources created before the failure were not deleted.') raise @@ -38,25 +40,15 @@ def provision(cli_ctx, checked, tags, request=None): tags = dict(tags or {}) account = parse_resource_id(resources.account_id) clients = get_agent_hosting_clients(cli_ctx, account['subscription']) - reused_dependencies = tuple( - (name, arm_id) - for name, arm_id, supplied, existing in ( - ('Hosting-management identity', resources.management_identity, - request.management_identity if request else None, checked.management_identity), - ('Workload identity', resources.workload_identity, - request.workload_identity if request else None, checked.workload_identity), - ('Storage account', resources.storage, request.storage if request else None, checked.storage), - ) - if request is not None and supplied is None and existing is not None - ) - if reused_dependencies: - details = '\n'.join(f' {name}: {arm_id}' for name, arm_id in reused_dependencies) - logger.warning('Using existing automatically generated BYO AKS dependencies:\n%s', details) - management = _ensure_identity(clients.identity, resources.management_identity, checked.management_identity, - resources.location, tags) - workload = _ensure_identity(clients.identity, resources.workload_identity, checked.workload_identity, - resources.location, tags, workload=True) - _ensure_storage(clients.storage, resources.storage, checked.storage, resources.location, tags, checked.storage_sku) + management = _ensure_identity( + clients.identity, resources.management_identity, checked.management_identity, + resources.location, tags, warn_reuse=bool(request and request.management_identity is None)) + workload = _ensure_identity( + clients.identity, resources.workload_identity, checked.workload_identity, + resources.location, tags, workload=True, warn_reuse=bool(request and request.workload_identity is None)) + _ensure_storage( + clients.storage, resources.storage, checked.storage, resources.location, tags, checked.storage_sku, + warn_reuse=bool(request and request.storage is None)) principals = { resources.management_identity: management.principal_id, resources.workload_identity: workload.principal_id, } @@ -66,52 +58,51 @@ def provision(cli_ctx, checked, tags, request=None): if subscription.lower() not in authorization_clients: authorization_clients[subscription.lower()] = get_agent_hosting_clients(cli_ctx, subscription).authorization _ensure_grant(authorization_clients[subscription.lower()], grant, principals[grant.identity_id]) - logger.info('BYO AKS dependencies are ready:\n' - ' Hosting-management identity: %s\n' - ' Workload identity: %s\n' - ' Storage account: %s\n' - 'These resources are not automatically deleted if Account creation fails.', - resources.management_identity, resources.workload_identity, resources.storage) return {'storage': resources.storage, 'management_identity': resources.management_identity, 'workload_identity': resources.workload_identity} -def _ensure_identity(client, arm_id, existing, location, tags, workload=False): +def _ensure_identity(client, arm_id, existing, location, tags, workload=False, warn_reuse=False): from azure.mgmt.msi.models import Identity identity_type = 'workload' if workload else 'hosting-management' + name = _resource_name(arm_id) if existing is not None: - logger.info('Using existing %s identity: %s', identity_type, arm_id) + if warn_reuse: + logger.warning("Using existing %s identity '%s'.", identity_type, name) return existing parts = parse_resource_id(arm_id) - logger.warning('Creating %s identity: %s', identity_type, arm_id) + logger.warning("Creating %s identity '%s' ...", identity_type, name) identity = client.user_assigned_identities.create_or_update( parts['resource_group'], parts['name'], Identity(location=location, tags=tags)) missing = _missing_identity_fields(identity, workload) if missing: - raise ValidationError(f'Created identity {arm_id} has missing metadata: {", ".join(missing)}. ' + raise ValidationError(f"Created identity '{name}' has missing metadata: {', '.join(missing)}. " 'Wait for identity provisioning to complete and inspect it before retrying.') return identity -def _ensure_storage(client, arm_id, existing, location, tags, sku): +def _ensure_storage(client, arm_id, existing, location, tags, sku, warn_reuse=False): + name = _resource_name(arm_id) if existing is not None: - logger.info('Using existing Storage account: %s', arm_id) + if warn_reuse: + logger.warning("Using existing storage account '%s'.", name) return existing if sku is None: - raise ValidationError(f'Storage SKU was not resolved for {arm_id}. Run preflight again.') + raise ValidationError(f"Storage SKU was not resolved for '{name}'. Run preflight again.") parts = parse_resource_id(arm_id) - logger.warning('Creating Storage account: %s', arm_id) + logger.warning("Creating storage account '%s' (%s) ...", name, sku) return client.storage_accounts.begin_create( parts['resource_group'], parts['name'], _storage_parameters(location, tags, sku)).result() def _find_grant(client, grant, principal, exact_scope=False): + accepted = {_role_guid(grant.role_id)} if exact_scope else _accepted_role_ids(grant.name) for assignment in client.role_assignments.list_for_scope(grant.scope, filter='atScope()'): properties = assignment.properties if not properties or not properties.principal_id or not properties.role_definition_id: continue if (properties.principal_id.lower() == principal.lower() and - properties.role_definition_id.lower() == grant.role_id.lower() and not properties.condition): + _role_guid(properties.role_definition_id) in accepted and not properties.condition): if not exact_scope or (properties.scope and properties.scope.rstrip('/').lower() == grant.scope.rstrip('/').lower()): return assignment @@ -119,15 +110,12 @@ def _find_grant(client, grant, principal, exact_scope=False): def _ensure_grant(client, grant, principal): - existing = _find_grant(client, grant, principal) - if existing is not None: - logger.info("Using existing role assignment for role '%s': %s", grant.name, existing.id) + if _find_grant(client, grant, principal) is not None: return + identity_name = _resource_name(grant.identity_id) + scope_name = _resource_name(grant.scope) name = str(uuid.uuid5(uuid.NAMESPACE_URL, f'{grant.scope}/{principal}/{grant.role_id}'.lower())) - arm_id = f'{grant.scope}/providers/Microsoft.Authorization/roleAssignments/{name}' - logger.warning("Assigning role '%s':\n Identity: %s\n Scope: %s", - grant.name, grant.identity_id, grant.scope) - logger.info('Role assignment resource ID: %s', arm_id) + logger.info("Assigning role '%s' to '%s' on '%s'", grant.name, identity_name, scope_name) try: client.role_assignments.create(grant.scope, name, {'properties': { 'principalId': principal, 'roleDefinitionId': grant.role_id, 'principalType': 'ServicePrincipal'}}) @@ -136,11 +124,9 @@ def _ensure_grant(client, grant, principal): try: existing = _find_grant(client, grant, principal, exact_scope=True) except AzureError as read_error: - logger.warning('Could not verify a conflicting role assignment:\n' - ' Assignment: %s\n' - ' Error: %s', arm_id, read_error) + logger.info("Could not verify conflicting '%s' role assignment for '%s' on '%s': %s", + grant.name, identity_name, scope_name, read_error) existing = None if existing is not None: - logger.info("Using existing role assignment for role '%s': %s", grant.name, existing.id) return raise diff --git a/src/azure-cli/azure/cli/command_modules/cognitiveservices/_agent_hosting_preflight.py b/src/azure-cli/azure/cli/command_modules/cognitiveservices/_agent_hosting_preflight.py index a2fd1a5feb6..58502392627 100644 --- a/src/azure-cli/azure/cli/command_modules/cognitiveservices/_agent_hosting_preflight.py +++ b/src/azure-cli/azure/cli/command_modules/cognitiveservices/_agent_hosting_preflight.py @@ -7,9 +7,7 @@ import re from contextlib import contextmanager from dataclasses import dataclass, replace -from fnmatch import fnmatchcase from typing import TYPE_CHECKING, Optional -from urllib.parse import urlparse from azure.core.exceptions import AzureError, ResourceNotFoundError from azure.mgmt.core.tools import is_valid_resource_id, parse_resource_id, resource_id @@ -43,6 +41,20 @@ } +_ROLE_IDS = { + 'Reader': 'acdd72a7-3385-48ef-bd42-f606fba81ae7', + 'Kubernetes Extension Contributor': '85cb6faf-e071-4c9b-8136-154b5a04f717', + 'Managed Identity Federated Identity Credential Contributor': '7e559ce2-48d7-4b27-9128-fa1b247f1308', + 'Storage Blob Data Contributor': 'ba92f5b4-2d11-453d-a403-e96b0029c9fe', + 'Storage Blob Data Owner': 'b7e6dc6d-f1e8-4753-8033-0f276bb0955b', + 'Owner': '8e3af657-a8ff-443c-a75c-2fe8c4bcb635', + 'Contributor': 'b24988ac-6180-42a0-ab88-20f7382dd24c', +} + + +_PREFLIGHT_DOC_URL = 'https://aka.ms/byo-aks-onboarding-prerequisites' + + @dataclass(frozen=True) class HostingRequest: account_id: str @@ -102,18 +114,18 @@ def preflight(cli_ctx, request, *, kind=None, custom_domain=None): _check_domain(cognitive_client, existing_account, custom_domain, kind) return PreflightResult(resources, None, None, None, existing_account=True) account_clients = _clients(cli_ctx, request.account_id, clients) + logger.info("Validating BYO AKS prerequisites for cluster '%s' ...", _resource_name(resources.cluster)) if not account_clients.resource.resource_groups.check_existence(account['resource_group']): - raise ValidationError( - f"Resource group '{account['resource_group']}' does not exist. Create it before retrying.") - _report(checks, 'Resource group', request.account_id, True, 'Exists', 'Existing resource group', 'None') + raise ValidationError(f"Resource group '{account['resource_group']}' does not exist.") + _report(checks, 'Resource group', request.account_id, True, 'Exists', 'existing resource group') if custom_domain: _check_domain(cognitive_client, None, custom_domain, kind) with _read_check(checks, 'Tenants', request.account_id): _check_tenants(cli_ctx, clients, resources, checks) _report(checks, 'Distinct identities', request.account_id, resources.management_identity.lower() != resources.workload_identity.lower(), - f'{resources.management_identity}; {resources.workload_identity}', - 'Different management and workload identities', 'Supply distinct identities.') + f'{_resource_name(resources.management_identity)}; {_resource_name(resources.workload_identity)}', + 'distinct management and workload identities') cluster = None with _read_check(checks, 'AKS cluster', resources.cluster): cluster_parts = parse_resource_id(resources.cluster) @@ -131,15 +143,13 @@ def preflight(cli_ctx, request, *, kind=None, custom_domain=None): with _read_check(checks, 'Node pools', resources.cluster): cluster_clients = _clients(cli_ctx, resources.cluster, clients) if cluster is not None: - _check_pools(cluster_clients.aks, cluster_clients.compute, cluster, - resources.cluster, request.location, checks) + _check_pools(cluster_clients.aks, cluster, resources.cluster, checks) checked = PreflightResult(resources, management, workload, storage, storage_sku) grants = () with _read_check(checks, 'Permissions', request.account_id): - grants = _check_permissions(cli_ctx, clients, request, checked, checks) - if any(check['mandatory'] and check['status'] in ('FAIL', 'UNVERIFIED') for check in checks): - raise ValidationError('BYO AKS preflight failed. No Azure resources were written. ' - 'Resolve the reported checks and retry.') + grants = _check_grants(cli_ctx, clients, request, checked, checks) + _raise_if_preflight_failed(checks) + logger.info('BYO AKS preflight validation passed.') return replace(checked, grants=tuple(grants), checks=tuple(checks)) @@ -151,52 +161,35 @@ def _read_account(client, account): def _validate_existing_account(existing, request, resources): + account_name = _resource_name(request.account_id) properties = getattr(existing, 'properties', None) configurations = getattr(properties, 'agent_hosting_configurations', None) if properties else None if not configurations: raise ValidationError( - f'Account {request.account_id} already exists without agent hosting. ' - 'Agent hosting can only be configured when the Account is created.') + f"Account '{account_name}' already exists without agent hosting, " + 'which can only be set during creation.') if _normalize_location(getattr(existing, 'location', None)) != _normalize_location(request.location): raise ValidationError( - f'Account {request.account_id} already exists in location {getattr(existing, "location", None)}. ' + f"Account '{account_name}' already exists in location {getattr(existing, 'location', None)}. " f'Use the existing location instead of {request.location}.') + mismatch_error = ( + f"Account '{account_name}' already exists with a different agent hosting configuration " + 'and cannot be modified.') if not isinstance(configurations, (list, tuple)) or len(configurations) != 1 or configurations[0] is None: - raise ValidationError( - f'Account {request.account_id} has an incompatible agent hosting configuration. ' - 'Updating or removing agentHostingConfigurations is not supported.') - - expected = { - 'name': 'default', - 'hosting_type': 'ManagedCluster', - 'cluster_resource_id': resources.cluster, - 'storage_account_resource_id': resources.storage, - 'hosting_management_identity_resource_id': resources.management_identity, - 'workload_identity_resource_id': resources.workload_identity, - } + raise ValidationError(mismatch_error) configuration = configurations[0] - resource_ids = { - 'cluster_resource_id', - 'storage_account_resource_id', - 'hosting_management_identity_resource_id', - 'workload_identity_resource_id', - } - mismatches = [] - for field, expected_value in expected.items(): - actual = getattr(configuration, field, None) - if field in resource_ids: - matches = ( - isinstance(actual, str) and - _normalize_resource_id(actual) == _normalize_resource_id(expected_value) - ) - else: - matches = actual == expected_value - if not matches: - mismatches.append(field) - if mismatches: - raise ValidationError( - f'Account {request.account_id} has an incompatible agent hosting configuration ' - f'({", ".join(mismatches)}). Updating or removing agentHostingConfigurations is not supported.') + resource_ids = ( + ('cluster_resource_id', resources.cluster), + ('storage_account_resource_id', resources.storage), + ('hosting_management_identity_resource_id', resources.management_identity), + ('workload_identity_resource_id', resources.workload_identity), + ) + if (getattr(configuration, 'name', None) != 'default' or + getattr(configuration, 'hosting_type', None) != 'ManagedCluster' or + any(not isinstance(getattr(configuration, field, None), str) or + _normalize_resource_id(getattr(configuration, field)) != _normalize_resource_id(expected) + for field, expected in resource_ids)): + raise ValidationError(mismatch_error) def _normalize_resource_id(value): @@ -251,7 +244,8 @@ def _names(subscription, group, account): token = hashlib.sha256(account_id.lower().encode('utf-8')).hexdigest()[:10] return { 'storage': re.sub('[^a-z0-9]', '', account.lower())[:14] + token, - 'management_identity': account.lower() + '-hosting-mi', 'workload_identity': account.lower() + '-workload-mi', + 'management_identity': account.lower() + '-hosting-mi-' + token, + 'workload_identity': account.lower() + '-workload-mi-' + token, } @@ -272,30 +266,32 @@ def identity_id(name): else identity_id(names['workload_identity'])) -def _existing_scope(arm_id, exists): - if exists: - return arm_id - parts = parse_resource_id(arm_id) - return f'/subscriptions/{parts["subscription"]}/resourceGroups/{parts["resource_group"]}' +def _resource_name(value): + return value.rstrip('/').rsplit('/', 1)[-1] if value else '' -def _report(checks, name, scope, passed, observed, expected, remediation, mandatory=True): +def _report(checks, name, scope, passed, observed, expected, remediation='None', mandatory=True): status = passed if isinstance(passed, str) else ('PASS' if passed else 'FAIL') + observed = _enum_value(observed) checks.append({'name': name, 'scope': scope, 'status': status, 'mandatory': mandatory, 'observed': observed, 'expected': expected, 'remediation': remediation}) - if isinstance(observed, (list, tuple)): - observed = '\n ' + '\n '.join(str(item) for item in observed) - elif isinstance(observed, dict): - observed = '\n ' + '\n '.join(f'{key}: {value}' for key, value in observed.items()) - if status in ('FAIL', 'UNVERIFIED'): - logger.warning('Preflight check failed: %s\n Scope: %s\n Details: %s\n Requirement: %s\n Action: %s', - name, scope, observed, expected, remediation) - elif status == 'NOT_APPLICABLE': - logger.info('Not applicable: %s [%s]: observed=%s; note=%s', name, scope, observed, remediation) - else: - recommendation = '' if remediation == 'None' else f'; recommendation={remediation}' - logger.info('Validated %s [%s]: observed=%s; expected=%s%s', - name, scope, observed, expected, recommendation) + + +def _raise_if_preflight_failed(checks): + failed = [check for check in checks if check['mandatory'] and check['status'] in ('FAIL', 'UNVERIFIED')] + if not failed: + return + lines = [] + for check in failed: + name, observed = check['name'], check['observed'] + label = f"Role '{name[:-11]}'" if name.endswith(' validation') else name + if isinstance(observed, (list, tuple)): + observed = ', '.join(str(item) for item in observed) or 'None' + lines.append(f" - {label} ('{_resource_name(check['scope'])}'): {observed} (expected {check['expected']})") + raise ValidationError( + 'BYO AKS preflight failed. No Azure resources were written:\n' + '\n'.join(lines), + recommendation=f'See {_PREFLIGHT_DOC_URL} for more details.', + ) @contextmanager @@ -303,11 +299,9 @@ def _read_check(checks, name, scope): try: yield except ResourceNotFoundError: - _report(checks, name, scope, False, 'Resource not found', 'Existing readable resource', - 'Supply an existing resource ID.') + _report(checks, name, scope, False, 'not found', 'existing resource') except AzureError as error: - _report(checks, name, scope, 'UNVERIFIED', str(error), 'Readable prerequisite evidence', - 'Resolve the reported Azure error and retry.') + _report(checks, name, scope, 'UNVERIFIED', str(error), 'accessible resource') def _check_tenants(cli_ctx, clients, resources, checks): @@ -321,7 +315,7 @@ def _check_tenants(cli_ctx, clients, resources, checks): if tenant is None: tenant = current _report(checks, 'Tenant', subscription, bool(current and tenant and current.lower() == tenant.lower()), - current, tenant or 'Readable tenant ID', 'Use subscriptions in the same tenant.') + current, tenant or 'tenant ID') def _missing_identity_fields(identity, workload=False): @@ -337,14 +331,13 @@ def _read_identity(client, arm_id, supplied, checks, workload=False): try: identity = client.user_assigned_identities.get(parts['resource_group'], parts['name']) except ResourceNotFoundError: - _report(checks, 'Identity', arm_id, not supplied, 'Not found', - 'Existing supplied resource' if supplied else 'Planned creation', - 'Supply an existing resource ID.') + _report(checks, 'Identity', arm_id, not supplied, 'not found', + 'existing resource' if supplied else 'planned creation') return None missing = _missing_identity_fields(identity, workload) - _report(checks, 'Identity metadata', arm_id, not missing, f'Missing: {missing}' if missing else 'Available', - 'principalId, clientId and tenantId' if workload else 'principalId', - 'Wait for identity provisioning to complete.') + _report(checks, 'Identity metadata', arm_id, not missing, + f"missing {', '.join(missing)}" if missing else 'available', + 'principalId, clientId, tenantId' if workload else 'principalId') return identity return None @@ -357,8 +350,7 @@ def _read_storage(client, arm_id, supplied, location, checks): storage = client.storage_accounts.get_properties(parts['resource_group'], parts['name']) except ResourceNotFoundError: if supplied: - _report(checks, 'Storage', arm_id, False, 'Not found', 'Existing supplied resource', - 'Supply an existing resource ID.') + _report(checks, 'Storage', arm_id, False, 'not found', 'existing resource') return None, None if storage is not None: _check_storage(storage, arm_id, location, checks) @@ -366,12 +358,10 @@ def _read_storage(client, arm_id, supplied, location, checks): availability = client.storage_accounts.check_name_availability({ 'name': parts['name'], 'type': 'Microsoft.Storage/storageAccounts'}) _report(checks, 'Storage name availability', arm_id, availability.name_available is True, - availability.message or availability.name_available, 'Available deterministic Storage name', - 'Supply an existing Storage account if the generated name is unavailable.') + availability.message or availability.name_available, 'available storage account name') if availability.name_available is True: storage_sku = _select_storage_sku(client, location) - _report(checks, 'Storage configuration', arm_id, True, storage_sku, - 'Planned StorageV2/Hot; prefer ZRS and use LRS when unavailable', 'None') + _report(checks, 'Storage configuration', arm_id, True, storage_sku, 'StorageV2/Hot') return storage, storage_sku @@ -416,171 +406,88 @@ def _image_supported(value): def _check_cluster(cluster, scope, location, checks): if cluster.properties is None: - _report(checks, 'AKS state', scope, 'UNVERIFIED', 'Missing properties', 'Succeeded', - 'Read a fully provisioned cluster.') + _report(checks, 'AKS cluster', scope, 'UNVERIFIED', 'missing properties', 'cluster properties') return properties = cluster.properties network, oidc, security = properties.network_profile, properties.oidc_issuer_profile, properties.security_profile sku, identity = cluster.sku, cluster.identity + kubelet = next((value for key, value in (properties.identity_profile or {}).items() + if isinstance(key, str) and key.lower() == 'kubeletidentity'), None) + kubelet_id = kubelet.object_id if kubelet else None version = properties.current_kubernetes_version or properties.kubernetes_version workload_identity = security.workload_identity if security else None - node_mode = properties.node_provisioning_profile.mode if properties.node_provisioning_profile else None - sku_name = sku.name if sku else None + node_mode = _enum_value(properties.node_provisioning_profile.mode) if properties.node_provisioning_profile else None + sku_name = _enum_value(sku.name) if sku else None requirements = [ ('AKS mode', sku_name == 'Base' and node_mode != 'Auto', - f'{sku_name}/{node_mode}', 'Standard AKS offering, not Automatic; no pricing-tier restriction'), + f'{sku_name}/{node_mode}' if node_mode else sku_name, 'Standard AKS, not Automatic'), ('Kubernetes version', _version_at_least(version, '1.31'), version, '>= 1.31'), - ('AKS state', properties.provisioning_state == 'Succeeded', properties.provisioning_state, 'Succeeded'), ('AKS identity', bool(identity and identity.type in ('SystemAssigned', 'UserAssigned')), - identity.type if identity else None, 'Managed identity'), + identity.type if identity else None, 'managed identity'), + ('Kubelet identity', bool(kubelet_id and str(kubelet_id).strip()), kubelet_id, 'kubelet identity objectId'), ('OIDC', bool(oidc and oidc.enabled is True and oidc.issuer_url), oidc.issuer_url if oidc else None, - 'Enabled with readable issuer URL'), + 'enabled with issuer URL'), ('Workload Identity', bool(workload_identity and workload_identity.enabled is True), - workload_identity.enabled if workload_identity else None, 'Enabled'), + workload_identity.enabled if workload_identity else None, 'enabled'), ('CNI plugin', bool(network and network.network_plugin == 'azure'), - network.network_plugin if network else None, 'Azure CNI'), + network.network_plugin if network else None, 'azure'), ('AKS region', bool(cluster.location and cluster.location.lower() == location.lower()), cluster.location, location), ] for name, passed, observed, expected in requirements: - _report(checks, name, scope, passed, observed, expected, 'Configure a supported AKS cluster and retry.') + _report(checks, name, scope, passed, observed, expected) _check_network_policy(network, scope, checks) def _check_network_policy(network, scope, checks): - policy = network.network_policy if network else None - dataplane = network.network_dataplane if network else None + policy = _enum_value(network.network_policy) if network else None + dataplane = _enum_value(network.network_dataplane) if network else None if dataplane == 'cilium' or policy in ('azure', 'calico'): status = 'PASS' elif policy == 'none' and dataplane in (None, 'azure'): status = 'FAIL' else: status = 'UNVERIFIED' - remediation = 'None' if status == 'PASS' else ( - 'Enable an AKS-supported network policy engine before retrying. ' - 'Missing or custom configurations cannot be verified from AKS resource properties. ' - 'This command does not modify the cluster.') _report(checks, 'Network policy', scope, status, f'networkPolicy={policy}; networkDataplane={dataplane}', - 'AKS-managed network policy enabled: Azure NPM, Calico or the Cilium dataplane', - remediation) - - -def _pool_vm_sizes(properties): - sizes, seen = [], set() - - def add(value): - if value is None or not str(value).strip(): - return - size = str(value).strip() - key = size.lower() - if key not in seen: - seen.add(key) - sizes.append(size) - - add(properties.vm_size) - virtual_machines = properties.virtual_machines_profile - scale = virtual_machines.scale if virtual_machines else None - for profile in scale.manual or [] if scale else []: - add(profile.size) - for node in properties.virtual_machine_nodes_status or []: - add(node.size) - return tuple(sizes) - - -def _pool_capacity_status(sizes, capacity, minimum_cpu, minimum_memory): - if not sizes: - return 'UNVERIFIED', ['No VM size evidence'] - status, evidence = 'PASS', [] - for size in sizes: - key = size.lower() - if key not in capacity: - status = 'UNVERIFIED' if status == 'PASS' else status - evidence.append(f'{size}: SKU not found') - continue - available = capacity[key] - if available is None: - status = 'UNVERIFIED' if status == 'PASS' else status - evidence.append(f'{size}: missing vCPU or MemoryGB capability') - continue - cpu, memory = available - if cpu < minimum_cpu or memory < minimum_memory: - status = 'FAIL' - evidence.append(f'{size}: {cpu:g} vCPU/{memory:g} GiB') - return status, evidence + 'Azure NPM, Calico, or Cilium') -def _vm_size_capacity(compute, location): - capacity = {} - for sku in compute.resource_skus.list(filter=f"location eq '{location}'"): - if sku.resource_type != 'virtualMachines' or not sku.name: - continue - key = sku.name.lower() - capacity.setdefault(key, None) - capabilities = {value.name.lower(): value.value for value in sku.capabilities or [] if value.name} - cores = capabilities.get('vcpusavailable') or capabilities.get('vcpus') - memory = capabilities.get('memorygb') - try: - if cores is not None and memory is not None: - capacity[key] = float(cores), float(memory) - except (TypeError, ValueError): - pass - return capacity - - -def _evaluate_pool(pool, capacity): +def _evaluate_pool(pool): properties = pool.properties if properties is None: - return None, None, f'{pool.name}: missing properties' - sizes = _pool_vm_sizes(properties) - system_capacity, system_evidence = _pool_capacity_status(sizes, capacity, 4, 16) - agent_capacity, agent_evidence = _pool_capacity_status(sizes, capacity, 8, 32) + return False, False, f'{pool.name} (missing properties)' + if properties.mode == 'System': + return True, False, f'{pool.name} (System)' requirements = { 'User': properties.mode == 'User', 'AzureLinux': properties.os_sku in ('AzureLinux', 'AzureLinux3'), 'KataVmIsolation': properties.workload_runtime == 'KataVmIsolation', 'count>=1': (properties.count or 0) >= 1, 'image': _image_supported(properties.node_image_version), 'label': (properties.node_labels or {}).get('agents.ai.azure.com/sandbox-node') == 'true', - 'SSH disabled': bool(properties.security_profile and properties.security_profile.ssh_access == 'Disabled'), - 'Succeeded': properties.provisioning_state == 'Succeeded', } - detail = ( - f'{pool.name}: vmSizes={list(sizes)}; ' - f'systemCapacity={system_capacity} {system_evidence}; ' - f'agentCapacity={agent_capacity} {agent_evidence}; ' - f'missing={[key for key, passed in requirements.items() if not passed]}') - system_status = system_capacity if ( - properties.mode == 'System' and properties.provisioning_state == 'Succeeded') else None - return system_status, agent_capacity if all(requirements.values()) else None, detail + missing = [key for key, passed in requirements.items() if not passed] + detail = f"{pool.name} (missing {', '.join(missing)})" if missing else pool.name + return False, not missing, detail -def _check_pools(aks, compute, cluster, scope, location, checks): +def _check_pools(aks, cluster, scope, checks): parts = parse_resource_id(scope) pools = list(aks.agent_pools.list(parts['resource_group'], parts['name'])) - capacity = _vm_size_capacity(compute, location) - system_statuses, agent_statuses, details = [], [], [] - selected = None + has_system, has_agent, details = False, False, [] for pool in pools: - system_status, agent_status, detail = _evaluate_pool(pool, capacity) + is_system, is_agent, detail = _evaluate_pool(pool) + has_system = has_system or is_system + has_agent = has_agent or is_agent details.append(detail) - if system_status: - system_statuses.append(system_status) - if agent_status: - agent_statuses.append(agent_status) - if agent_status == 'PASS' and selected is None: - selected = pool - system_status = 'PASS' if 'PASS' in system_statuses else ( - 'UNVERIFIED' if 'UNVERIFIED' in system_statuses else 'FAIL') - agent_status = 'PASS' if 'PASS' in agent_statuses else ( - 'UNVERIFIED' if 'UNVERIFIED' in agent_statuses else 'FAIL') - _report(checks, 'System node pool', scope, system_status, details, 'One Succeeded System pool >=4 vCPU/16 GiB', - 'Prepare a qualifying System pool.') - _report(checks, 'Agent node pool', scope, agent_status, details, - 'One User pool satisfying all sandbox requirements', 'Prepare one qualifying User pool.') + _report(checks, 'System node pool', scope, has_system, details, 'at least one System pool') + _report(checks, 'Agent node pool', scope, has_agent, details, 'at least one qualifying sandbox User pool') network = cluster.properties.network_profile if cluster.properties else None - mode = network.network_plugin_mode if network else None - _report(checks, 'CNI mode', scope, mode == 'overlay', mode, 'Azure CNI Overlay', - 'Use Azure CNI Overlay.') - return selected + mode = _enum_value(network.network_plugin_mode) if network else None + pod_subnets = {pool.name: bool(pool.properties and pool.properties.pod_subnet_id and + str(pool.properties.pod_subnet_id).strip()) for pool in pools} + uses_pod_subnets = bool(pools) and all(pod_subnets.values()) + _report(checks, 'CNI mode', scope, mode == 'overlay' or (mode is None and uses_pod_subnets), + f'mode={mode}; podSubnets={pod_subnets}', 'Azure CNI Overlay or Pod Subnet on all pools') def _storage_parameters(location, tags, sku): @@ -598,211 +505,83 @@ def _storage_parameters(location, tags, sku): def _check_storage(storage, scope, location, checks): properties = storage.properties if properties is None: - _report(checks, 'Storage readiness', scope, 'UNVERIFIED', 'Missing properties', 'Succeeded', - 'Read a fully provisioned Storage account.') + _report(checks, 'Storage readiness', scope, 'UNVERIFIED', 'missing properties', 'Succeeded') return - endpoint = properties.primary_endpoints.blob if properties.primary_endpoints else '' - parsed = urlparse(endpoint or '') requirements = [ ('Storage region', _normalize_location(storage.location) == _normalize_location(location), storage.location, location), ('Storage readiness', properties.provisioning_state == 'Succeeded', properties.provisioning_state, 'Succeeded'), ('Storage kind', storage.kind == 'StorageV2', storage.kind, 'StorageV2'), ('Storage tier', properties.access_tier == 'Hot', properties.access_tier, 'Hot'), - ('Storage HNS', properties.is_hns_enabled is not True, properties.is_hns_enabled, - 'Disabled (false or omitted)'), + ('Storage HNS', properties.is_hns_enabled is not True, properties.is_hns_enabled, False), ('Storage HTTPS', properties.enable_https_traffic_only is True, properties.enable_https_traffic_only, True), ('Storage TLS', properties.minimum_tls_version in ('TLS1_2', 'TLS1_3'), properties.minimum_tls_version, '>=TLS1_2'), - ('Storage shared keys', properties.allow_shared_key_access is False, - properties.allow_shared_key_access, False), - ('Storage anonymous Blob', properties.allow_blob_public_access is False, - properties.allow_blob_public_access, False), - ('Storage Blob endpoint', parsed.scheme == 'https' and bool(parsed.hostname) and - not parsed.username and not parsed.password and not parsed.query and not parsed.fragment, - endpoint, 'Valid HTTPS Blob endpoint'), ] for name, passed, observed, expected in requirements: - _report(checks, name, scope, passed, observed, expected, 'Supply Storage with the required configuration.') + _report(checks, name, scope, passed, observed, expected) sku = str(_enum_value(storage.sku.name)) if storage.sku and storage.sku.name else '' zone_redundant = sku.endswith(('ZRS', 'GZRS')) + if sku and not zone_redundant: + logger.warning("Storage account '%s' uses %s; ZRS or GZRS is recommended when available.", + _resource_name(scope), sku) _report(checks, 'Storage redundancy', scope, 'PASS' if sku else 'UNVERIFIED', - sku or 'Missing SKU', 'Readable redundancy; ZRS or GZRS recommended', + sku or 'missing SKU', 'ZRS or GZRS recommended', 'None' if zone_redundant else 'Use ZRS or GZRS when available.', mandatory=False) - public = properties.public_network_access - action = properties.network_rule_set.default_action if properties.network_rule_set else None - restricted = public in ('Disabled', 'SecuredByPerimeter') or action == 'Deny' - status = 'PASS' if public == 'Enabled' and action == 'Allow' else 'NOT_APPLICABLE' if restricted else 'UNVERIFIED' - _report(checks, 'Storage public-network baseline', scope, status, f'{public}/{action}', - 'Enabled/Allow for public baseline', - 'Private/restricted Storage connectivity is unverified; verify routing and DNS.', mandatory=not restricted) -def _permission_allows(permission, action, data=False): - if permission.condition: - return False - if '*' in action: - return _wildcard_action_allowed([permission], action, data) - allowed = permission.data_actions if data else permission.actions - excluded = permission.not_data_actions if data else permission.not_actions - action = action.lower() - return (any(fnmatchcase(action, pattern.lower()) for pattern in allowed or []) and - not any(fnmatchcase(action, pattern.lower()) for pattern in excluded or [])) - - -def _action_pattern_step(pattern, positions, character=None): - if character is not None: - positions = {position if pattern[position] == '*' else position + 1 - for position in positions if position < len(pattern) and pattern[position] in ('*', character)} - expanded = set(positions) - for position in positions: - while position < len(pattern) and pattern[position] == '*': - position += 1 - expanded.add(position) - return frozenset(expanded) - - -def _wildcard_action_allowed(permissions, action, data): - """Find whether any operation in the requested wildcard is left without an effective grant.""" - action = action.lower() - rules = [ - (tuple(pattern.lower() for pattern in (permission.data_actions if data else permission.actions) or []), - tuple(pattern.lower() for pattern in (permission.not_data_actions if data else permission.not_actions) or [])) - for permission in permissions if not permission.condition - ] - if any(not excluded and ('*' in allowed or action in allowed) for allowed, excluded in rules): - return True - grant_patterns = [pattern for allowed, excluded in rules for pattern in allowed + excluded] - patterns = tuple(dict.fromkeys([action] + grant_patterns)) - indexes = {pattern: index for index, pattern in enumerate(patterns)} - rules = [(tuple(indexes[pattern] for pattern in allowed), tuple(indexes[pattern] for pattern in excluded)) - for allowed, excluded in rules] - # All other characters have the same matching behavior, represented by the empty symbol. - alphabet = (set(''.join(patterns)) - {'*'}) | {''} - start = tuple(_action_pattern_step(pattern, {0}) for pattern in patterns) - pending, visited = [start], {start} - while pending: - state = pending.pop() - matches = [len(pattern) in positions for pattern, positions in zip(patterns, state)] - if matches[0] and not any(any(matches[index] for index in allowed) and - not any(matches[index] for index in excluded) for allowed, excluded in rules): - return False - for character in alphabet: - following = tuple(_action_pattern_step(pattern, positions, character) - for pattern, positions in zip(patterns, state)) - if following[0] and following not in visited: - visited.add(following) - pending.append(following) - return True - - -def _permissions(client, scope, principals, definitions): - principals = {principal.lower() for principal in principals} - for assignment in client.role_assignments.list_for_scope(scope, filter='atScope()'): - properties = assignment.properties - if (not properties or not properties.principal_id or properties.principal_id.lower() not in principals or - properties.condition): - continue - role_id = properties.role_definition_id - if role_id not in definitions: - definitions[role_id] = client.role_definitions.get_by_id(role_id) - role = definitions[role_id] - if role.properties: - yield from role.properties.permissions or [] - +def _role_guid(role_definition_id): + return _resource_name(role_definition_id).lower() -def _has_permissions(permissions, actions, data=False): - return all(_wildcard_action_allowed(permissions, action, data) if '*' in action else - any(_permission_allows(permission, action, data) for permission in permissions) for action in actions) - -def _validate_grant(permissions, role): - required = role.properties.permissions if role.properties else None - if not required or not any(item.actions or item.data_actions for item in required): - return False - return all(_has_permissions(permissions, item.actions or []) and - _has_permissions(permissions, item.data_actions or [], data=True) for item in required) +def _accepted_role_ids(role_name): + role_id = _ROLE_IDS[role_name] + if role_name == 'Storage Blob Data Contributor': + return {role_id, _ROLE_IDS['Storage Blob Data Owner']} + return {role_id, _ROLE_IDS['Owner'], _ROLE_IDS['Contributor']} -def _operator_requirements(request, checked): - resources = checked.resources - parent = _existing_scope(resources.account_id, False) - required = [(parent, 'Microsoft.CognitiveServices/accounts/write')] - if request.management_identity is None or request.workload_identity is None: - required.append((parent, 'Microsoft.ManagedIdentity/userAssignedIdentities/write')) - if request.storage is None: - required.append((parent, 'Microsoft.Storage/storageAccounts/write')) - identity_scope = _existing_scope(resources.management_identity, checked.management_identity is not None) - required.append((identity_scope, 'Microsoft.ManagedIdentity/userAssignedIdentities/assign/action')) - required.append((resources.cluster, 'Microsoft.ContainerService/managedClusters/write')) - return required - - -def _operator_permissions(cli_ctx, clients, scope, cache): +def _assigned_role_ids(client, scope, principal, cache): key = scope.lower() if key not in cache: - parts = parse_resource_id(scope) - client = _clients(cli_ctx, scope, clients).authorization - if parts.get('namespace'): - permissions = client.permissions.list_for_resource( - parts['resource_group'], parts['namespace'], '', parts['type'], parts['name']) - else: - permissions = client.permissions.list_for_resource_group(parts['resource_group']) - cache[key] = list(permissions) - return cache[key] - - -def _check_permissions(cli_ctx, clients, request, checked, checks): - required = _operator_requirements(request, checked) - definitions, operator_permissions = {}, {} - for scope, action in required: - permissions = _operator_permissions(cli_ctx, clients, scope, operator_permissions) - allowed = any(_permission_allows(permission, action) for permission in permissions) - _report(checks, 'Operator permission', scope, allowed, action if allowed else f'Missing {action}', - action, 'Have an administrator grant the required unconditional permission.') - return _check_grants(cli_ctx, clients, request, checked, operator_permissions, definitions, checks) - - -def _required_role(client, scope, name): - subscription_scope = f'/subscriptions/{parse_resource_id(scope)["subscription"]}' - roles = [role for role in client.role_definitions.list(subscription_scope, filter=f"roleName eq '{name}'") - if role.properties and role.properties.role_name == name and role.properties.role_type == 'BuiltInRole'] - if len(roles) != 1: - raise ValidationError(f'Cannot resolve the built-in role {name} at {subscription_scope}.') - return roles[0] + cache[key] = list(client.role_assignments.list_for_scope(scope, filter='atScope()')) + principal = principal.lower() + return { + _role_guid(assignment.properties.role_definition_id) + for assignment in cache[key] + if (assignment.properties and assignment.properties.principal_id and + assignment.properties.principal_id.lower() == principal and not assignment.properties.condition and + assignment.properties.role_definition_id) + } -def _check_grants(cli_ctx, clients, request, checked, operator_permissions, definitions, checks): +def _check_grants(cli_ctx, clients, request, checked, checks): resources = checked.resources + assignments_by_scope = {} grants = [ - (resources.management_identity, checked.management_identity, resources.cluster, True, + (resources.management_identity, checked.management_identity, resources.cluster, 'Reader', request.management_identity is not None), - (resources.management_identity, checked.management_identity, resources.cluster, True, + (resources.management_identity, checked.management_identity, resources.cluster, 'Kubernetes Extension Contributor', request.management_identity is not None), (resources.management_identity, checked.management_identity, resources.workload_identity, - checked.workload_identity is not None, 'Managed Identity Federated Identity Credential Contributor', + 'Managed Identity Federated Identity Credential Contributor', request.management_identity is not None and request.workload_identity is not None), (resources.workload_identity, checked.workload_identity, resources.storage, - checked.storage is not None, 'Storage Blob Data Contributor', + 'Storage Blob Data Contributor', request.workload_identity is not None and request.storage is not None), ] assignments = [] - for identity_id, identity, scope, exists, role_name, validation in grants: - client = _clients(cli_ctx, scope, clients).authorization - role = _required_role(client, scope, role_name) + for identity_id, identity, scope, role_name, validation in grants: if validation: + client = _clients(cli_ctx, scope, clients).authorization principal = identity.principal_id if identity else None - permissions = list(_permissions(client, scope, [principal], definitions)) if principal else [] - allowed = bool(principal and _validate_grant(permissions, role)) - _report(checks, f'{role_name} validation', scope, allowed, f'{principal}: {role_name}', - 'Existing effective permission; no grant writes', - 'Have an administrator grant missing permissions.') + assigned = _assigned_role_ids(client, scope, principal, assignments_by_scope) if principal else set() + allowed = bool(assigned & _accepted_role_ids(role_name)) + identity_name = _resource_name(identity_id) + _report(checks, f'{role_name} validation', scope, allowed, + 'assigned' if allowed else f"missing on '{identity_name}'", 'assigned') else: - parent = _existing_scope(scope, exists) - permissions = _operator_permissions(cli_ctx, clients, parent, operator_permissions) - allowed = any(_permission_allows(permission, 'Microsoft.Authorization/roleAssignments/write') - for permission in permissions) - _report(checks, f'{role_name} assignment authority', parent, allowed, role_name, - 'Unconditional roleAssignments/write', 'Have an administrator grant role-assignment authority.') - assignments.append(Grant(role_name, identity_id, scope, role.id)) + role_id = (f'/subscriptions/{parse_resource_id(scope)["subscription"]}' + f'/providers/Microsoft.Authorization/roleDefinitions/{_ROLE_IDS[role_name]}') + assignments.append(Grant(role_name, identity_id, scope, role_id)) return assignments diff --git a/src/azure-cli/azure/cli/command_modules/cognitiveservices/_client_factory.py b/src/azure-cli/azure/cli/command_modules/cognitiveservices/_client_factory.py index 759379ad936..a0753d81b23 100644 --- a/src/azure-cli/azure/cli/command_modules/cognitiveservices/_client_factory.py +++ b/src/azure-cli/azure/cli/command_modules/cognitiveservices/_client_factory.py @@ -38,7 +38,6 @@ def get_agent_hosting_clients(cli_ctx, subscription_id): from types import SimpleNamespace from azure.cli.core.commands.client_factory import get_mgmt_service_client from azure.mgmt.authorization import AuthorizationManagementClient - from azure.mgmt.compute import ComputeManagementClient from azure.mgmt.containerservice import ContainerServiceClient from azure.mgmt.msi import ManagedServiceIdentityClient from azure.mgmt.resource import ResourceManagementClient, SubscriptionClient @@ -46,7 +45,6 @@ def get_agent_hosting_clients(cli_ctx, subscription_id): return SimpleNamespace( aks=get_mgmt_service_client(cli_ctx, ContainerServiceClient, subscription_id=subscription_id), - compute=get_mgmt_service_client(cli_ctx, ComputeManagementClient, subscription_id=subscription_id), identity=get_mgmt_service_client(cli_ctx, ManagedServiceIdentityClient, subscription_id=subscription_id), resource=get_mgmt_service_client(cli_ctx, ResourceManagementClient, subscription_id=subscription_id), storage=get_mgmt_service_client(cli_ctx, StorageManagementClient, subscription_id=subscription_id), diff --git a/src/azure-cli/azure/cli/command_modules/cognitiveservices/tests/latest/test_agent_hosting_preparation.py b/src/azure-cli/azure/cli/command_modules/cognitiveservices/tests/latest/test_agent_hosting_preparation.py index 611d6b46f50..2fd33142383 100644 --- a/src/azure-cli/azure/cli/command_modules/cognitiveservices/tests/latest/test_agent_hosting_preparation.py +++ b/src/azure-cli/azure/cli/command_modules/cognitiveservices/tests/latest/test_agent_hosting_preparation.py @@ -11,8 +11,7 @@ from unittest import mock from azure.core.exceptions import HttpResponseError, ResourceExistsError, ResourceNotFoundError -from azure.mgmt.authorization.models import Permission, RoleAssignment, RoleDefinition -from azure.mgmt.compute.models import ResourceSku +from azure.mgmt.authorization.models import RoleAssignment from azure.mgmt.containerservice.models import AgentPool, ManagedCluster from azure.mgmt.cognitiveservices.models import Account from azure.mgmt.storage.models import SkuInformation, StorageAccount @@ -21,9 +20,8 @@ prepare_agent_hosting, provision, _ensure_grant, ) from azure.cli.command_modules.cognitiveservices._agent_hosting_preflight import ( - Grant, build_request, preflight, _has_permissions, _image_supported, - _names, _operator_requirements, _permission_allows, - _resolve_resources, _select_storage_sku, _storage_parameters, validate_resource_ids, + Grant, _ROLE_IDS, build_request, preflight, _image_supported, + _names, _resolve_resources, _select_storage_sku, _storage_parameters, validate_resource_ids, ) @@ -58,6 +56,7 @@ def setUp(self): 'location': 'westus', 'sku': {'name': 'Base', 'tier': 'Standard'}, 'identity': {'type': 'SystemAssigned'}, 'properties': { 'provisioningState': 'Succeeded', 'kubernetesVersion': '1.31.0', + 'identityProfile': {'kubeletidentity': {'objectId': 'kubelet-principal'}}, 'oidcIssuerProfile': {'enabled': True, 'issuerURL': 'https://issuer.example/'}, 'securityProfile': {'workloadIdentity': {'enabled': True}}, 'networkProfile': { @@ -84,35 +83,17 @@ def setUp(self): 'primaryEndpoints': {'blob': 'https://storage.blob.core.windows.net/'}, }, } - self.roles = {} - role_permissions = { - 'Owner': {'actions': ['*']}, - 'Reader': {'actions': ['*/read']}, - 'Kubernetes Extension Contributor': { - 'actions': ['Microsoft.KubernetesConfiguration/extensions/*']}, - 'Managed Identity Federated Identity Credential Contributor': { - 'actions': ['Microsoft.ManagedIdentity/userAssignedIdentities/federatedIdentityCredentials/*']}, - 'Storage Blob Data Contributor': { - 'actions': ['Microsoft.Storage/storageAccounts/blobServices/containers/*'], - 'dataActions': ['Microsoft.Storage/storageAccounts/blobServices/containers/blobs/*']}, + self.roles = { + name: {'id': f'/subscriptions/{_SUB}/providers/Microsoft.Authorization/roleDefinitions/{guid}'} + for name, guid in _ROLE_IDS.items() } - for index, (name, permission) in enumerate(role_permissions.items()): - self.roles[name] = { - 'id': f'/subscriptions/{_SUB}/providers/Microsoft.Authorization/roleDefinitions/role{index}', - 'roleName': name, 'roleType': 'BuiltInRole', 'permissions': [permission]} - self.assignments = [self._assignment('operator', 'Owner', f'/subscriptions/{_SUB}')] + self.assignments = [] self.clients = {name: mock.Mock() for name in ( - 'aks', 'compute', 'storage', 'identity', 'resource', 'authorization', 'subscription')} + 'aks', 'storage', 'identity', 'resource', 'authorization', 'subscription')} self.clients['subscription'].subscriptions.get.return_value = SimpleNamespace(tenant_id='tenant') self.clients['resource'].resource_groups.check_existence.return_value = True self.clients['aks'].managed_clusters.get.side_effect = lambda *args: ManagedCluster(self.cluster) self.clients['aks'].agent_pools.list.side_effect = lambda *args: [AgentPool(pool) for pool in self.pools] - self.clients['compute'].resource_skus.list.return_value = [ - ResourceSku.deserialize({'name': name, 'resourceType': 'virtualMachines', 'capabilities': [ - {'name': 'vCPUs', 'value': str(cores)}, {'name': 'MemoryGB', 'value': str(memory)}]}) - for name, cores, memory in ( - ('Standard_D2s_v5', 2, 8), ('Standard_D4s_v5', 4, 16), - ('Standard_D8s_v5', 8, 32), ('Standard_D16s_v5', 16, 64))] self.clients['identity'].user_assigned_identities.get.side_effect = self._get_identity self.clients['identity'].user_assigned_identities.create_or_update.side_effect = self._create_identity self.clients['storage'].storage_accounts.get_properties.side_effect = self._get_storage @@ -123,16 +104,12 @@ def setUp(self): self.clients['storage'].storage_accounts.begin_create.return_value.result.side_effect = ( lambda: StorageAccount(self.storage)) auth = self.clients['authorization'] - auth.role_definitions.list.side_effect = lambda scope, filter: [self._sdk_role(self.roles[filter.split("'")[1]])] - auth.role_definitions.get_by_id.side_effect = lambda arm_id: self._sdk_role(next( - role for role in self.roles.values() if role['id'] == arm_id)) auth.role_assignments.list_for_scope.side_effect = lambda scope, **kwargs: [ RoleAssignment({'id': item['id'], 'properties': item}) for item in self.assignments if scope.lower() == item['scope'].lower() or scope.lower().startswith(item['scope'].lower() + '/')] auth.role_assignments.create.side_effect = lambda scope, name, parameters: RoleAssignment({ 'id': f'{scope}/providers/Microsoft.Authorization/roleAssignments/{name}'}) - self._configure_caller_permissions(auth, _SUB) patcher = mock.patch(_PREFIX + 'get_agent_hosting_clients', side_effect=self._subscription_clients) patcher.start() self.addCleanup(patcher.stop) @@ -140,42 +117,14 @@ def setUp(self): self.client_factory = patcher.start() self.addCleanup(patcher.stop) - def _caller_permissions(self, scope): - for assignment in self.assignments: - if assignment['principalId'] not in ('operator', 'operator-group'): - continue - if not (scope.lower() == assignment['scope'].lower() or - scope.lower().startswith(assignment['scope'].lower() + '/')): - continue - role = next(role for role in self.roles.values() if role['id'] == assignment['roleDefinitionId']) - for permission in role['permissions']: - properties = dict(permission) - if assignment.get('condition'): - properties['condition'] = assignment['condition'] - yield Permission(properties) - - def _configure_caller_permissions(self, client, subscription): - client.permissions.list_for_resource_group.side_effect = ( - lambda group: self._caller_permissions(f'/subscriptions/{subscription}/resourceGroups/{group}')) - client.permissions.list_for_resource.side_effect = ( - lambda group, namespace, parent, resource_type, name: self._caller_permissions( - f'/subscriptions/{subscription}/resourceGroups/{group}/providers/{namespace}/{resource_type}/{name}')) - def _subscription_clients(self, cli_ctx, subscription): clients = dict(self.clients) if subscription != _SUB: authorization = mock.Mock() authorization.role_assignments = clients['authorization'].role_assignments - authorization.role_definitions = clients['authorization'].role_definitions - self._configure_caller_permissions(authorization, subscription) clients['authorization'] = authorization return SimpleNamespace(**clients) - @staticmethod - def _sdk_role(role): - return RoleDefinition({'id': role['id'], 'properties': { - 'roleName': role['roleName'], 'type': role['roleType'], 'permissions': role['permissions']}}) - def _assignment(self, principal, role, scope, **kwargs): return {'id': scope + '/providers/Microsoft.Authorization/roleAssignments/' + principal + role, 'principalId': principal, 'scope': scope, 'roleDefinitionId': self.roles[role]['id'], **kwargs} @@ -344,8 +293,10 @@ def test_existing_account_hosting_mismatch_fails_before_dependency_queries(self) self.cognitive.accounts.get.side_effect = None self.cognitive.accounts.get.return_value = self._account_with_hosting(**changes) self.client_factory.reset_mock() - with self.assertRaisesRegex(ValidationError, 'incompatible agent hosting configuration'): + with self.assertRaisesRegex(ValidationError, 'different agent hosting configuration') as caught: preflight(self.cli_ctx, self._prepare()) + self.assertIn("Account 'foundry'", str(caught.exception)) + self.assertNotIn('/subscriptions/', str(caught.exception)) self._assert_no_dependency_queries() def test_unavailable_or_unverified_domain_blocks_dependency_creation(self): @@ -411,36 +362,16 @@ def test_all_eight_dependency_and_grant_branches(self): parameters = self.clients['storage'].storage_accounts.begin_create.call_args.args[2] self.assertEqual(parameters['tags'], self.tags) - def test_supplied_dependencies_need_no_grant_write_permission(self): - self.roles['Owner']['permissions'][0]['notActions'] = ['Microsoft.Authorization/roleAssignments/write'] - preparation = self._prepare() - checked = preflight(self.cli_ctx, preparation) - with mock.patch(_PREFIX + 'logger.warning') as warning: - provision(self.cli_ctx, checked, self.tags, request=preparation) - warning.assert_not_called() + def test_preflight_does_not_query_operator_permissions(self): + for supplied in (True, False): + with self.subTest(supplied=supplied): + checked = preflight(self.cli_ctx, self._prepare(supplied, supplied, supplied)) + self.assertFalse(any('Operator permission' in check['name'] or 'assignment authority' in check['name'] + for check in checked.checks)) + self.clients['authorization'].permissions.list_for_resource_group.assert_not_called() + self.clients['authorization'].permissions.list_for_resource.assert_not_called() self._assert_no_writes() - def test_operator_requirements_follow_request_intent_and_target_scope(self): - request = self._prepare(False, False, False) - checked = SimpleNamespace( - resources=_resolve_resources(request), management_identity=None, workload_identity=None, storage=None) - required = _operator_requirements(request, checked) - self.assertEqual(required.count( - (_RG, 'Microsoft.ManagedIdentity/userAssignedIdentities/write')), 1) - self.assertIn((_CLUSTER, 'Microsoft.ContainerService/managedClusters/write'), required) - - other = '11111111-1111-1111-1111-111111111111' - management = _MANAGEMENT.replace(_SUB, other).replace('/resourceGroups/rg/', '/resourceGroups/identity-rg/') - request = replace(self._prepare(), management_identity=management) - checked = SimpleNamespace( - resources=_resolve_resources(request), management_identity=None, workload_identity=object(), storage=object()) - required = _operator_requirements(request, checked) - self.assertNotIn((_RG, 'Microsoft.ManagedIdentity/userAssignedIdentities/write'), required) - self.assertNotIn((_RG, 'Microsoft.Storage/storageAccounts/write'), required) - self.assertIn(( - f'/subscriptions/{other}/resourceGroups/identity-rg', - 'Microsoft.ManagedIdentity/userAssignedIdentities/assign/action'), required) - def test_account_cluster_and_storage_require_same_subscription(self): request = self._prepare() other = '11111111-1111-1111-1111-111111111111' @@ -456,7 +387,6 @@ def test_cross_subscription_workload_identity_is_allowed_in_same_tenant(self): request = self._prepare(management=False) other = '11111111-1111-1111-1111-111111111111' supplied = replace(request, workload_identity=_WORKLOAD.replace(_SUB, other)) - self.assignments.append(self._assignment('operator', 'Owner', f'/subscriptions/{other}')) checked = preflight(self.cli_ctx, supplied) result = provision(self.cli_ctx, checked, self.tags) self.assertEqual(result['workload_identity'], supplied.workload_identity) @@ -486,7 +416,7 @@ def test_created_workload_identity_requires_all_three_metadata_fields(self): with self.subTest(field=field): def create_identity(group, name, parameters, field=field): identity = original(group, name, parameters) - if name.endswith('-workload-mi'): + if '-workload-mi-' in name: setattr(identity, field, None) return identity self.clients['identity'].user_assigned_identities.create_or_update.side_effect = create_identity @@ -494,18 +424,6 @@ def create_identity(group, name, parameters, field=field): provision(self.cli_ctx, checked, self.tags) self.clients['storage'].storage_accounts.begin_create.assert_not_called() - def test_workload_identity_does_not_require_operator_assign_action(self): - self.roles['Owner']['permissions'][0]['notActions'] = [ - 'Microsoft.ManagedIdentity/userAssignedIdentities/assign/action'] - self.roles['Identity Assigner'] = { - 'id': f'/subscriptions/{_SUB}/providers/Microsoft.Authorization/roleDefinitions/assigner', - 'roleName': 'Identity Assigner', 'roleType': 'CustomRole', - 'permissions': [{'actions': ['Microsoft.ManagedIdentity/userAssignedIdentities/assign/action']}], - } - self.assignments.append(self._assignment('operator', 'Identity Assigner', _MANAGEMENT)) - preflight(self.cli_ctx, self._prepare()) - self._assert_no_writes() - def test_standard_aks_offering_does_not_restrict_pricing_tier(self): self.cluster['sku']['tier'] = 'Free' preflight(self.cli_ctx, self._prepare()) @@ -517,74 +435,29 @@ def test_automatic_cluster_is_rejected(self): preflight(self.cli_ctx, self._prepare()) self._assert_no_writes() - def test_system_pool_must_be_succeeded(self): - self.pools[0]['properties']['provisioningState'] = 'Updating' - with self.assertRaises(ValidationError): - preflight(self.cli_ctx, self._prepare()) - self._assert_no_writes() - - def test_top_level_vm_size_capacity_still_passes(self): + def test_system_pool_requires_only_system_mode(self): + self.pools[0]['properties'].update(provisioningState='Updating', vmSize='Standard_D2s_v5') checked = preflight(self.cli_ctx, self._prepare()) statuses = {check['name']: check['status'] for check in checked.checks} self.assertEqual(statuses['System node pool'], 'PASS') - self.assertEqual(statuses['Agent node pool'], 'PASS') + self.pools[0]['properties']['mode'] = 'User' + with self.assertRaises(ValidationError): + preflight(self.cli_ctx, self._prepare()) self._assert_no_writes() - def test_smaller_manual_or_actual_vm_size_fails_pool_capacity(self): - original = copy.deepcopy(self.pools) - for index, field, value, check in ( - (0, 'virtualMachinesProfile', { - 'scale': {'manual': [{'count': 1, 'size': 'Standard_D2s_v5'}]}}, 'System node pool'), - (1, 'virtualMachinesProfile', { - 'scale': {'manual': [{'count': 1, 'size': 'Standard_D4s_v5'}]}}, 'Agent node pool'), - (1, 'virtualMachineNodesStatus', [{'size': 'Standard_D4s_v5'}], 'Agent node pool')): - with self.subTest(field=field, check=check): - self.pools = copy.deepcopy(original) - self.pools[index]['properties'][field] = value - with self.assertLogs('cli.' + _PREFLIGHT_PREFIX.rstrip('.'), level='WARNING') as logs: - with self.assertRaises(ValidationError): - preflight(self.cli_ctx, self._prepare()) - self.assertTrue(any(f'Preflight check failed: {check}' in line for line in logs.output)) - self._assert_no_writes() - - def test_mixed_vm_sizes_pass_when_every_size_meets_capacity(self): - self.pools[0]['properties']['virtualMachinesProfile'] = { - 'scale': {'manual': [{'count': 1, 'size': 'Standard_D8s_v5'}]}} - self.pools[1]['properties']['virtualMachinesProfile'] = { - 'scale': {'manual': [{'count': 1, 'size': 'Standard_D16s_v5'}]}} - self.pools[1]['properties']['virtualMachineNodesStatus'] = [{'size': 'Standard_D8s_v5'}] + def test_removed_aks_capacity_ssh_and_readiness_checks_do_not_block(self): + self.cluster['properties']['provisioningState'] = 'Updating' + self.pools[0]['properties'].update(vmSize='Standard_B1s', provisioningState='Updating') + self.pools[1]['properties'].update( + vmSize='Standard_B1s', provisioningState='Updating', + securityProfile={'sshAccess': 'LocalUser'}) checked = preflight(self.cli_ctx, self._prepare()) statuses = {check['name']: check['status'] for check in checked.checks} + self.assertNotIn('AKS state', statuses) self.assertEqual(statuses['System node pool'], 'PASS') self.assertEqual(statuses['Agent node pool'], 'PASS') self._assert_no_writes() - def test_missing_vm_size_sku_or_capacity_is_unverified(self): - original_pools = copy.deepcopy(self.pools) - original_skus = self.clients['compute'].resource_skus.list.return_value - incomplete = ResourceSku.deserialize({ - 'name': 'Standard_Incomplete', 'resourceType': 'virtualMachines', - 'capabilities': [{'name': 'vCPUs', 'value': '8'}]}) - for reason, index, check in ( - ('size', 1, 'Agent node pool'), - ('sku', 0, 'System node pool'), - ('capability', 1, 'Agent node pool')): - with self.subTest(reason=reason): - self.pools = copy.deepcopy(original_pools) - self.clients['compute'].resource_skus.list.return_value = original_skus - if reason == 'size': - self.pools[index]['properties'].pop('vmSize') - elif reason == 'sku': - self.pools[index]['properties']['vmSize'] = 'Standard_Missing' - else: - self.pools[index]['properties']['vmSize'] = 'Standard_Incomplete' - self.clients['compute'].resource_skus.list.return_value = original_skus + [incomplete] - with self.assertLogs('cli.' + _PREFLIGHT_PREFIX.rstrip('.'), level='WARNING') as logs: - with self.assertRaises(ValidationError): - preflight(self.cli_ctx, self._prepare()) - self.assertTrue(any(f'Preflight check failed: {check}' in line for line in logs.output)) - self._assert_no_writes() - def test_sandbox_label_requires_exact_lowercase_true(self): for value in ('True', None): with self.subTest(value=value): @@ -601,55 +474,43 @@ def test_missing_validation_permission_blocks_without_repair(self): preflight(self.cli_ctx, preparation) self._assert_no_writes() - def test_partial_custom_grants_must_cover_all_existing_requirements(self): + def test_inherited_built_in_roles_satisfy_mi_validation_without_role_definition_queries(self): request = self._prepare() - self.assignments = [assignment for assignment in self.assignments - if assignment['principalId'] != 'management-principal' or - assignment['scope'] != _CLUSTER] - self.roles['Limited Hosting'] = { - 'id': f'/subscriptions/{_SUB}/providers/Microsoft.Authorization/roleDefinitions/limited', - 'roleName': 'Limited Hosting', 'roleType': 'CustomRole', - 'permissions': [{'actions': ['*'], 'notActions': ['*/write']}], - } - self.assignments.append(self._assignment('management-principal', 'Limited Hosting', _CLUSTER)) - with self.assertRaises(ValidationError): - preflight(self.cli_ctx, request) - self._assert_no_writes() - - self.roles['Extension Writer'] = { - 'id': f'/subscriptions/{_SUB}/providers/Microsoft.Authorization/roleDefinitions/writer', - 'roleName': 'Extension Writer', 'roleType': 'CustomRole', - 'permissions': [{'actions': ['*/write']}], - } - self.assignments.append(self._assignment('management-principal', 'Extension Writer', _CLUSTER)) - checked = preflight(self.cli_ctx, request) - statuses = {check['name']: check['status'] for check in checked.checks} - self.assertEqual(statuses['Reader validation'], 'PASS') - self.assertEqual(statuses['Kubernetes Extension Contributor validation'], 'PASS') - self._assert_no_writes() - - def test_blob_validation_does_not_infer_data_access_from_owner(self): - preparation = self._prepare() - self.assignments = [assignment for assignment in self.assignments - if assignment['principalId'] != 'workload-principal'] - self.assignments.append(self._assignment('workload-principal', 'Owner', _STORAGE)) - with self.assertRaises(ValidationError): - preflight(self.cli_ctx, preparation) - self._assert_no_writes() - - def test_missing_operator_authority_blocks_all_writes(self): - preparation = self._prepare(management=False) - self.roles['Owner']['permissions'][0]['notActions'] = ['Microsoft.Authorization/roleAssignments/write'] - with self.assertRaises(ValidationError): - preflight(self.cli_ctx, preparation) - self._assert_no_writes() + for control_role in ('Owner', 'Contributor'): + for inherited_scope in (f'/subscriptions/{_SUB}', _RG): + with self.subTest(control_role=control_role, inherited_scope=inherited_scope): + self.assignments = [ + self._assignment('management-principal', control_role, inherited_scope), + self._assignment('workload-principal', 'Storage Blob Data Owner', inherited_scope), + ] + checked = preflight(self.cli_ctx, request) + statuses = {check['name']: check['status'] for check in checked.checks} + self.assertEqual(statuses['Reader validation'], 'PASS') + self.assertEqual(statuses['Kubernetes Extension Contributor validation'], 'PASS') + self.assertEqual( + statuses['Managed Identity Federated Identity Credential Contributor validation'], 'PASS') + self.assertEqual(statuses['Storage Blob Data Contributor validation'], 'PASS') + self.clients['authorization'].role_definitions.list.assert_not_called() + self.clients['authorization'].role_definitions.get_by_id.assert_not_called() + self._assert_no_writes() + + def test_blob_validation_does_not_infer_data_access_from_owner_or_contributor(self): + for role in ('Owner', 'Contributor'): + with self.subTest(role=role): + preparation = self._prepare() + self.assignments = [assignment for assignment in self.assignments + if assignment['principalId'] != 'workload-principal'] + self.assignments.append(self._assignment('workload-principal', role, _STORAGE)) + with self.assertRaises(ValidationError): + preflight(self.cli_ctx, preparation) + self._assert_no_writes() def test_qualifying_requirements_cannot_be_combined_across_pools(self): preparation = self._prepare() other = copy.deepcopy(self.pools[1]) other['name'] = 'other' other['properties']['nodeLabels'] = {} - self.pools[1]['properties']['securityProfile']['sshAccess'] = 'LocalUser' + self.pools[1]['properties']['workloadRuntime'] = 'OCIContainer' self.pools.append(other) with self.assertRaises(ValidationError): preflight(self.cli_ctx, preparation) @@ -658,9 +519,8 @@ def test_qualifying_requirements_cannot_be_combined_across_pools(self): def test_agent_pool_requirements_each_block_when_missing(self): original = copy.deepcopy(self.pools[1]) for key, value in ( - ('osSKU', 'Ubuntu'), ('count', 0), ('vmSize', 'Standard_D4s_v5'), - ('workloadRuntime', 'OCIContainer'), ('nodeImageVersion', 'AKSAzureLinux-V3katagen2-202608.13.9'), - ('nodeLabels', {}), ('securityProfile', {'sshAccess': 'LocalUser'}), ('provisioningState', 'Updating')): + ('osSKU', 'Ubuntu'), ('count', 0), ('workloadRuntime', 'OCIContainer'), + ('nodeImageVersion', 'AKSAzureLinux-V3katagen2-202608.13.9'), ('nodeLabels', {})): with self.subTest(key=key): self.pools[1] = copy.deepcopy(original) self.pools[1]['properties'][key] = value @@ -689,11 +549,14 @@ def test_documented_managed_network_policy_configurations_are_accepted(self): def test_disabled_network_policy_fails_before_writes_even_with_overlay(self): self.cluster['properties']['networkProfile'].update(networkPolicy='none', networkDataplane='azure') self.cluster['properties']['addonProfiles'] = {'azurepolicy': {'enabled': True}} - with self.assertLogs('cli.' + _PREFLIGHT_PREFIX.rstrip('.'), level='WARNING') as logs: - with self.assertRaises(ValidationError): + with mock.patch(_PREFLIGHT_PREFIX + 'logger.warning') as warning: + with self.assertRaises(ValidationError) as caught: preflight(self.cli_ctx, self._prepare()) - self.assertTrue(any('Preflight check failed: Network policy' in line for line in logs.output)) - self.assertFalse(any('Validated ' in line for line in logs.output)) + warning.assert_not_called() + self.assertIn("Network policy ('cluster')", str(caught.exception)) + self.assertNotIn('/subscriptions/', str(caught.exception)) + self.assertEqual(caught.exception.recommendations, + ['See https://aka.ms/byo-aks-onboarding-prerequisites for more details.']) self.clients['aks'].managed_clusters.get.assert_called_once() self._assert_no_writes() @@ -703,10 +566,13 @@ def test_missing_or_unrecognized_network_policy_evidence_blocks_preflight(self): with self.subTest(policy=policy, dataplane=dataplane): self.cluster['properties']['networkProfile'].update( networkPolicy=policy, networkDataplane=dataplane) - with self.assertLogs('cli.' + _PREFLIGHT_PREFIX.rstrip('.'), level='WARNING') as logs: - with self.assertRaises(ValidationError): + with mock.patch(_PREFLIGHT_PREFIX + 'logger.warning') as warning: + with self.assertRaises(ValidationError) as caught: preflight(self.cli_ctx, self._prepare()) - self.assertTrue(any('Preflight check failed: Network policy' in line for line in logs.output)) + warning.assert_not_called() + self.assertIn("Network policy ('cluster')", str(caught.exception)) + self.assertEqual(caught.exception.recommendations, + ['See https://aka.ms/byo-aks-onboarding-prerequisites for more details.']) self._assert_no_writes() def test_kubenet_is_rejected_even_with_overlay(self): @@ -719,16 +585,30 @@ def test_explicit_azure_linux_3_os_sku_is_accepted(self): self.pools[1]['properties']['osSKU'] = 'AzureLinux3' preflight(self.cli_ctx, self._prepare()) - def test_non_overlay_networking_is_rejected(self): + def test_cni_pod_subnet_is_accepted_and_other_non_overlay_modes_are_rejected(self): + pod_subnet = _RG + '/providers/Microsoft.Network/virtualNetworks/vnet/subnets/pods' self.cluster['properties']['networkProfile']['networkPluginMode'] = None + with self.assertRaises(ValidationError): + preflight(self.cli_ctx, self._prepare()) + self.pools[0]['properties']['podSubnetID'] = pod_subnet + with self.assertRaises(ValidationError): + preflight(self.cli_ctx, self._prepare()) + self.pools[1]['properties']['podSubnetID'] = pod_subnet + checked = preflight(self.cli_ctx, self._prepare()) + statuses = {check['name']: check['status'] for check in checked.checks} + self.assertEqual(statuses['CNI mode'], 'PASS') + self.cluster['properties']['networkProfile']['networkPluginMode'] = 'custom' with self.assertRaises(ValidationError): preflight(self.cli_ctx, self._prepare()) self._assert_no_writes() def test_cluster_requirement_failures(self): - for key, value in (('kubernetesVersion', '1.30.9'), ('provisioningState', 'Updating'), + self.cluster['properties']['identityProfile'] = {'KubeletIdentity': {'objectId': 'kubelet-principal'}} + preflight(self.cli_ctx, self._prepare()) + for key, value in (('kubernetesVersion', '1.30.9'), ('identityProfile', {}), + ('identityProfile', {'kubeletidentity': {'objectId': ' '}}), ('oidcIssuerProfile', {}), ('securityProfile', {})): - with self.subTest(key=key): + with self.subTest(key=key, value=value): preparation = self._prepare() original = self.cluster['properties'][key] self.cluster['properties'][key] = value @@ -737,24 +617,33 @@ def test_cluster_requirement_failures(self): self.cluster['properties'][key] = original self._assert_no_writes() - def test_restricted_storage_and_lrs_do_not_warn_or_block(self): - self.storage['properties']['publicNetworkAccess'] = 'Disabled' - self.storage['sku']['name'] = 'Standard_LRS' + def test_removed_storage_access_and_public_baseline_checks_do_not_warn_or_block(self): + self.storage['properties'].update( + allowSharedKeyAccess=True, allowBlobPublicAccess=True, + publicNetworkAccess=None, networkAcls=None, primaryEndpoints=None) preparation = self._prepare() with mock.patch(_PREFLIGHT_PREFIX + 'logger.warning') as warning: - checked = preflight(self.cli_ctx, preparation) + preflight(self.cli_ctx, preparation) warning.assert_not_called() + + self.storage['sku']['name'] = 'Standard_LRS' + with mock.patch(_PREFLIGHT_PREFIX + 'logger.warning') as warning: + checked = preflight(self.cli_ctx, preparation) + warning.assert_called_once_with( + "Storage account '%s' uses %s; ZRS or GZRS is recommended when available.", + 'storage', 'Standard_LRS') checks = {check['name']: check for check in checked.checks} - self.assertEqual(checks['Storage public-network baseline']['status'], 'NOT_APPLICABLE') + for removed in ('Storage shared keys', 'Storage anonymous Blob', + 'Storage Blob endpoint', 'Storage public-network baseline'): + self.assertNotIn(removed, checks) self.assertEqual(checks['Storage redundancy']['status'], 'PASS') self.assertEqual(checks['Storage redundancy']['observed'], 'Standard_LRS') self.assertEqual( checks['Storage redundancy']['remediation'], 'Use ZRS or GZRS when available.') def test_invalid_storage_configuration_blocks(self): - for key, value in (('isHnsEnabled', True), ('allowSharedKeyAccess', True), - ('allowBlobPublicAccess', True), ('supportsHttpsTrafficOnly', False), - ('minimumTlsVersion', 'TLS1_0'), ('primaryEndpoints', {'blob': 'http://invalid'})): + for key, value in (('isHnsEnabled', True), ('supportsHttpsTrafficOnly', False), + ('minimumTlsVersion', 'TLS1_0'), ('accessTier', 'Cool')): with self.subTest(key=key): original = self.storage['properties'][key] self.storage['properties'][key] = value @@ -762,6 +651,10 @@ def test_invalid_storage_configuration_blocks(self): preflight(self.cli_ctx, self._prepare()) self.storage['properties'][key] = original self._assert_no_writes() + self.storage['kind'] = 'Storage' + with self.assertRaises(ValidationError): + preflight(self.cli_ctx, self._prepare()) + self._assert_no_writes() def test_supplied_storage_must_match_account_region(self): self.storage['location'] = 'eastus' @@ -776,13 +669,6 @@ def test_unavailable_generated_storage_name_blocks_before_writes(self): preflight(self.cli_ctx, self._prepare(storage=False)) self._assert_no_writes() - def test_unknown_storage_public_network_state_blocks(self): - self.storage['properties']['publicNetworkAccess'] = None - self.storage['properties']['networkAcls'] = None - with self.assertRaises(ValidationError): - preflight(self.cli_ctx, self._prepare()) - self._assert_no_writes() - def test_resolved_management_and_workload_identity_cannot_be_same(self): preparation = self._prepare(workload=False) preparation = replace(preparation, management_identity=_resolve_resources(preparation).workload_identity) @@ -793,10 +679,13 @@ def test_resolved_management_and_workload_identity_cannot_be_same(self): def test_unreadable_resources_are_unverified_not_absent(self): self.clients['identity'].user_assigned_identities.get.side_effect = HttpResponseError('Forbidden') preparation = self._prepare() - with self.assertLogs('cli.' + _PREFLIGHT_PREFIX.rstrip('.'), level='WARNING') as logs: - with self.assertRaises(ValidationError): + with mock.patch(_PREFLIGHT_PREFIX + 'logger.warning') as warning: + with self.assertRaises(ValidationError) as caught: preflight(self.cli_ctx, preparation) - self.assertTrue(any('Preflight check failed: Identity' in line for line in logs.output)) + warning.assert_not_called() + self.assertIn("Identity ('management'): Forbidden", str(caught.exception)) + self.assertEqual(caught.exception.recommendations, + ['See https://aka.ms/byo-aks-onboarding-prerequisites for more details.']) self._assert_no_writes() def test_preflight_returns_results_without_mutating_request(self): @@ -831,20 +720,6 @@ def test_cross_tenant_reference_blocks(self): preflight(self.cli_ctx, preparation) self._assert_no_writes() - def test_unreadable_caller_permissions_block_preflight(self): - self.clients['authorization'].permissions.list_for_resource_group.side_effect = HttpResponseError('Forbidden') - with self.assertRaises(ValidationError): - preflight(self.cli_ctx, self._prepare()) - self._assert_no_writes() - self.profile.get_raw_token.assert_not_called() - - def test_unreadable_assignment_authority_is_not_silently_skipped(self): - self.clients['authorization'].permissions.list_for_resource.side_effect = HttpResponseError('Forbidden') - with self.assertRaises(ValidationError): - preflight(self.cli_ctx, self._prepare(management=False)) - self._assert_no_writes() - self.profile.get_raw_token.assert_not_called() - def test_conditional_grants_are_not_unconditional_evidence(self): preparation = self._prepare() self.assignments[0]['condition'] = 'unverified condition' @@ -901,18 +776,44 @@ def test_existing_generated_dependencies_are_reused_without_updates(self): lambda group, name: self._create_identity(group, name, None)) self.clients['storage'].storage_accounts.get_properties.side_effect = lambda *args: StorageAccount(self.storage) checked = preflight(self.cli_ctx, preparation) - with self.assertLogs('cli.' + _PREFIX.rstrip('.'), level='WARNING') as logs: + self.assignments = [ + self._assignment(f"{checked.resources.management_identity.rsplit('/', 1)[-1]}-principal", + 'Owner', _CLUSTER), + self._assignment(f"{checked.resources.management_identity.rsplit('/', 1)[-1]}-principal", + 'Managed Identity Federated Identity Credential Contributor', + checked.resources.workload_identity), + self._assignment(f"{checked.resources.workload_identity.rsplit('/', 1)[-1]}-principal", + 'Storage Blob Data Contributor', checked.resources.storage), + ] + with self.assertLogs('cli.' + _PREFIX.rstrip('.'), level='INFO') as logs: provision(self.cli_ctx, checked, self.tags, request=preparation) - output = '\n'.join(logs.output) - self.assertIn('Using existing automatically generated BYO AKS dependencies:', output) - for name, arm_id in ( - ('Hosting-management identity', checked.resources.management_identity), - ('Workload identity', checked.resources.workload_identity), - ('Storage account', checked.resources.storage)): - self.assertIn(f' {name}: {arm_id}', output) + warnings = '\n'.join(line for line in logs.output if line.startswith('WARNING:')) + infos = [line for line in logs.output if line.startswith('INFO:')] + mgmt_name = checked.resources.management_identity.rsplit('/', 1)[-1] + workload_name = checked.resources.workload_identity.rsplit('/', 1)[-1] + storage_name = checked.resources.storage.rsplit('/', 1)[-1] + self.assertIn(f"Using existing hosting-management identity '{mgmt_name}'.", warnings) + self.assertIn(f"Using existing workload identity '{workload_name}'.", warnings) + self.assertIn(f"Using existing storage account '{storage_name}'.", warnings) + self.assertEqual(infos, []) + self.assertNotIn('/subscriptions/', '\n'.join(logs.output)) self.clients['identity'].user_assigned_identities.create_or_update.assert_not_called() self.clients['storage'].storage_accounts.begin_create.assert_not_called() + self.assignments = [ + self._assignment('management-principal', 'Reader', _CLUSTER), + self._assignment('management-principal', 'Kubernetes Extension Contributor', _CLUSTER), + self._assignment('management-principal', 'Managed Identity Federated Identity Credential Contributor', + _WORKLOAD), + self._assignment('workload-principal', 'Storage Blob Data Contributor', _STORAGE), + ] + supplied = self._prepare() + checked_supplied = preflight(self.cli_ctx, supplied) + with mock.patch(_PREFIX + 'logger') as provision_logger: + provision(self.cli_ctx, checked_supplied, self.tags, request=supplied) + provision_logger.warning.assert_not_called() + provision_logger.info.assert_not_called() + def test_assignment_names_are_stable_across_retries(self): preparation = self._prepare(False, False, False) checked = preflight(self.cli_ctx, preparation) @@ -926,26 +827,58 @@ def test_assignment_names_are_stable_across_retries(self): self.assertEqual(first, second) def test_dependency_creation_logs_are_descriptive(self): - checked = preflight(self.cli_ctx, self._prepare(False, False, False)) - with self.assertLogs('cli.' + _PREFIX.rstrip('.'), level='WARNING') as logs: + with self.assertLogs('cli.' + _PREFLIGHT_PREFIX.rstrip('.'), level='INFO') as preflight_logs: + checked = preflight(self.cli_ctx, self._prepare(False, False, False)) + preflight_output = '\n'.join(preflight_logs.output) + self.assertIn("Validating BYO AKS prerequisites for cluster 'cluster' ...", preflight_output) + self.assertIn('BYO AKS preflight validation passed.', preflight_output) + self.assertNotIn('observed=', preflight_output) + with self.assertLogs('cli.' + _PREFIX.rstrip('.'), level='INFO') as logs: provision(self.cli_ctx, checked, self.tags) - output = '\n'.join(logs.output) - self.assertIn('Creating hosting-management identity:', output) - self.assertIn('Creating workload identity:', output) - self.assertIn('Creating Storage account:', output) + warnings = '\n'.join(line for line in logs.output if line.startswith('WARNING:')) + infos = '\n'.join(line for line in logs.output if line.startswith('INFO:')) + mgmt_name = checked.resources.management_identity.rsplit('/', 1)[-1] + workload_name = checked.resources.workload_identity.rsplit('/', 1)[-1] + storage_name = checked.resources.storage.rsplit('/', 1)[-1] + self.assertIn(f"Creating hosting-management identity '{mgmt_name}' ...", warnings) + self.assertIn(f"Creating workload identity '{workload_name}' ...", warnings) + self.assertIn(f"Creating storage account '{storage_name}' ({checked.storage_sku}) ...", warnings) + self.assertNotIn('Assigning role', warnings) + self.assertNotIn('/subscriptions/', '\n'.join(logs.output)) for role_name in ( 'Reader', 'Kubernetes Extension Contributor', 'Managed Identity Federated Identity Credential Contributor', 'Storage Blob Data Contributor'): - self.assertIn(f"Assigning role '{role_name}'", output) - self.assertNotRegex(output, r'\bG0[123]\b') + self.assertIn(f"Assigning role '{role_name}' to '", infos) + self.assertNotRegex('\n'.join(logs.output), r'\bG0[123]\b') def test_compatible_existing_grant_is_not_recreated(self): self._prepare() - role = self._sdk_role(self.roles['Reader']) - _ensure_grant(self.clients['authorization'], Grant('Reader', _MANAGEMENT, _CLUSTER, role.id), + _ensure_grant(self.clients['authorization'], + Grant('Reader', _MANAGEMENT, _CLUSTER, self.roles['Reader']['id']), 'management-principal') self.clients['authorization'].role_assignments.create.assert_not_called() + def test_provision_reuses_inherited_higher_built_in_roles_without_recreating_grants(self): + preparation = self._prepare(management=False, workload=True, storage=False) + self.assignments = [ + { + 'id': f'/subscriptions/{_SUB}/providers/Microsoft.Authorization/roleAssignments/mgmt-contrib', + 'principalId': f"{_names(_SUB, 'rg', 'foundry')['management_identity']}-principal", + 'scope': f'/subscriptions/{_SUB}', + 'roleDefinitionId': f'/providers/Microsoft.Authorization/roleDefinitions/{_ROLE_IDS["Contributor"]}', + }, + self._assignment('workload-principal', 'Storage Blob Data Owner', _RG), + ] + checked = preflight(self.cli_ctx, preparation) + provision(self.cli_ctx, checked, self.tags) + self.clients['authorization'].role_assignments.create.assert_not_called() + + self.assignments[-1] = self._assignment('workload-principal', 'Owner', _RG) + provision(self.cli_ctx, checked, self.tags) + self.clients['authorization'].role_assignments.create.assert_called_once() + self.assertEqual(self.clients['authorization'].role_assignments.create.call_args.args[0], + checked.resources.storage) + @staticmethod def _conflict(code='RoleAssignmentExists', status=409): error = ResourceExistsError('Role assignment conflict') @@ -972,7 +905,8 @@ def test_role_assignment_conflict_must_match_principal_role_scope_and_condition( grant = Grant('Reader', _MANAGEMENT, _CLUSTER, self.roles['Reader']['id']) base = {'principalId': 'management-principal', 'roleDefinitionId': grant.role_id, 'scope': _CLUSTER} cases = [ - {'principalId': 'another-principal'}, {'roleDefinitionId': 'another-role'}, {'scope': _RG}, + {'principalId': 'another-principal'}, {'roleDefinitionId': 'another-role'}, + {'roleDefinitionId': self.roles['Owner']['id']}, {'scope': _RG}, {'scope': None}, {'condition': 'unverified condition'}, ] client = self.clients['authorization'] @@ -1021,9 +955,10 @@ def test_service_errors_are_preserved_with_visible_resource_context(self): prepare_agent_hosting(SimpleNamespace(cli_ctx=self.cli_ctx), 'rg', 'foundry', 'westus', self.tags, cluster=_CLUSTER) self.assertIs(caught.exception, error) - for arm_id in (_resolve_resources(preparation).management_identity, - _resolve_resources(preparation).workload_identity, _resolve_resources(preparation).storage): - self.assertTrue(any(arm_id in line for line in logs.output)) + resolved = _resolve_resources(preparation) + for arm_id in (resolved.management_identity, resolved.workload_identity, resolved.storage): + self.assertTrue(any(arm_id.rsplit('/', 1)[-1] in line for line in logs.output)) + self.assertNotIn('/subscriptions/', '\n'.join(logs.output)) self.assertTrue(any('were not deleted' in line for line in logs.output)) self.assertEqual(self.clients['identity'].user_assigned_identities.create_or_update.call_count, 2) @@ -1042,9 +977,12 @@ def test_deterministic_account_based_names(self): names = _names(_SUB, 'rg', 'team-ai-prod') self.assertTrue(names['storage'].startswith('teamaiprod')) self.assertLessEqual(len(names['storage']), 24) - self.assertEqual(names['management_identity'], 'team-ai-prod-hosting-mi') + self.assertEqual(names['management_identity'], 'team-ai-prod-hosting-mi-4c0efe9e92') + self.assertEqual(names['workload_identity'], 'team-ai-prod-workload-mi-4c0efe9e92') self.assertEqual(names, _names(_SUB.upper(), 'RG', 'TEAM-AI-PROD')) - self.assertNotEqual(names['storage'], _names(_SUB, 'other-rg', 'team-ai-prod')['storage']) + other_group_names = _names(_SUB, 'other-rg', 'team-ai-prod') + for resource in ('storage', 'management_identity', 'workload_identity'): + self.assertNotEqual(names[resource], other_group_names[resource]) def test_image_baseline_accepts_only_same_series_at_or_above_minimum(self): for image in ('AKSAzureLinux-V3katagen2-202608.14.0', 'AKSAzureLinux-V3katagen2-202609.1.0'): @@ -1052,45 +990,3 @@ def test_image_baseline_accepts_only_same_series_at_or_above_minimum(self): for image in (None, '', 'AKSAzureLinux-V3katagen2-202608.13.9', 'AKSUbuntu-202610.1.0', 'AKSAzureLinux-V3katagen2-invalid'): self.assertFalse(_image_supported(image)) - - def test_wildcard_requirements_do_not_bypass_write_or_delete_exclusions(self): - action = 'Microsoft.KubernetesConfiguration/extensions/*' - for operation in ('read', 'write', 'delete'): - with self.subTest(operation=operation): - permission = Permission({'actions': ['*'], 'notActions': [f'*/{operation}']}) - self.assertFalse(_permission_allows(permission, action)) - - def test_another_role_can_fill_only_the_missing_wildcard_actions(self): - requirement = 'Microsoft.KubernetesConfiguration/extensions/*' - incomplete = Permission({'actions': ['*'], 'notActions': ['*/write']}) - writer = Permission({'actions': ['*/write']}) - self.assertFalse(_has_permissions([incomplete], [requirement])) - self.assertTrue(_has_permissions([incomplete, writer], [requirement])) - self.assertTrue(_has_permissions([writer, incomplete], [requirement])) - specific_writer = Permission({'actions': ['Microsoft.KubernetesConfiguration/extensions/write']}) - self.assertTrue(_has_permissions([incomplete, specific_writer], [ - 'Microsoft.KubernetesConfiguration/extensions/read', - 'Microsoft.KubernetesConfiguration/extensions/write', - ])) - self.assertFalse(_has_permissions([incomplete, specific_writer], [requirement])) - - def test_excluded_or_conditional_grants_cannot_take_fast_path(self): - required = 'Microsoft.Storage/storageAccounts/*' - for properties in ( - {'actions': ['*'], 'notActions': ['*/write']}, - {'actions': [required], 'notActions': ['*/write']}, - {'actions': ['*'], 'condition': 'unverified'}, - {'actions': [required + 'read']}, - {'dataActions': ['*']}): - with self.subTest(properties=properties): - self.assertFalse(_has_permissions([Permission(properties)], [required])) - - def test_wildcard_data_permissions_use_their_own_exclusions_and_grants(self): - required = 'Microsoft.Storage/storageAccounts/blobServices/containers/blobs/*' - incomplete = Permission({'dataActions': ['*'], 'notDataActions': ['*/delete']}) - delete = Permission({'dataActions': ['*/delete']}) - self.assertFalse(_has_permissions([incomplete], [required], data=True)) - self.assertTrue(_has_permissions([incomplete, delete], [required], data=True)) - self.assertFalse(_has_permissions([Permission({'actions': ['*']}), delete], [required], data=True)) - management_exclusions = Permission({'dataActions': ['*'], 'notActions': ['*']}) - self.assertTrue(_has_permissions([management_exclusions], [required], data=True))