1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
|
"""Directory-related unit tests for Microsoft AD Directory Services.
The logic to check the details of VPCs and Subnets is shared between the
"create directory" APIs, so it will not be repeated here.
"""
from datetime import datetime, timezone
import boto3
import pytest
from botocore.exceptions import ClientError
from moto import mock_aws
from moto.moto_api._internal import mock_random
from .test_ds_simple_ad_directory import TEST_REGION, create_subnets, create_vpc
def create_test_microsoft_ad(ds_client, ec2_client, vpc_settings=None, tags=None):
"""Return ID of a newly created valid directory."""
if not vpc_settings:
good_vpc_id = create_vpc(ec2_client)
good_subnet_ids = create_subnets(ec2_client, good_vpc_id)
vpc_settings = {"VpcId": good_vpc_id, "SubnetIds": good_subnet_ids}
if not tags:
tags = []
result = ds_client.create_microsoft_ad(
Name=f"test-{mock_random.get_random_hex(6)}.test",
Password="4MicrosoftADPassword",
VpcSettings=vpc_settings,
Tags=tags,
Edition="Standard",
)
return result["DirectoryId"]
@mock_aws
def test_ds_create_microsoft_ad_validations():
"""Test validation errs that aren't caught by botocore.
Most of this validation is shared with the Simple AD directory, but
this verifies that it is invoked from create_microsoft_ad().
"""
client = boto3.client("ds", region_name=TEST_REGION)
random_num = mock_random.get_random_hex(6)
# Verify ValidationException error messages are accumulated properly.
bad_name = f"bad_name_{random_num}"
bad_password = "bad_password"
bad_edition = "foo"
ok_vpc_settings = {
"VpcId": f"vpc-{random_num}",
"SubnetIds": [f"subnet-{random_num}01", f"subnet-{random_num}02"],
}
with pytest.raises(ClientError) as exc:
client.create_microsoft_ad(
Name=bad_name,
Password=bad_password,
Edition=bad_edition,
VpcSettings=ok_vpc_settings,
)
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert "3 validation errors detected" in err["Message"]
assert (
r"Value at 'password' failed to satisfy constraint: "
r"Member must satisfy regular expression pattern: "
r"^(?=^.{8,64}$)((?=.*\d)(?=.*[A-Z])(?=.*[a-z])|"
r"(?=.*\d)(?=.*[^A-Za-z0-9\s])(?=.*[a-z])|"
r"(?=.*[^A-Za-z0-9\s])(?=.*[A-Z])(?=.*[a-z])|"
r"(?=.*\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9\s]))^.*$" in err["Message"]
)
assert (
f"Value '{bad_edition}' at 'edition' failed to satisfy constraint: "
f"Member must satisfy enum value set: [Enterprise, Standard]" in err["Message"]
)
assert (
rf"Value '{bad_name}' at 'name' failed to satisfy constraint: "
rf"Member must satisfy regular expression pattern: "
rf"^([a-zA-Z0-9]+[\.-])+([a-zA-Z0-9])+$" in err["Message"]
)
too_long = (
"Test of directory service 0123456789 0123456789 0123456789 "
"0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 "
"0123456789 0123456789"
)
short_name = "a:b.c"
with pytest.raises(ClientError) as exc:
client.create_microsoft_ad(
Name=f"test{random_num}.test",
Password="TESTfoobar1",
VpcSettings=ok_vpc_settings,
Description=too_long,
ShortName=short_name,
)
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert "2 validation errors detected" in err["Message"]
assert (
f"Value '{too_long}' at 'description' failed to satisfy constraint: "
f"Member must have length less than or equal to 128" in err["Message"]
)
pattern = r'^[^\/:*?"<>|.]+[^\/:*?"<>|]*$'
assert (
f"Value '{short_name}' at 'shortName' failed to satisfy constraint: "
f"Member must satisfy regular expression pattern: " + pattern
) in err["Message"]
bad_vpc_settings = {"VpcId": f"vpc-{random_num}", "SubnetIds": ["foo"]}
with pytest.raises(ClientError) as exc:
client.create_microsoft_ad(
Name=f"test{random_num}.test",
Password="TESTfoobar1",
VpcSettings=bad_vpc_settings,
)
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert "1 validation error detected" in err["Message"]
assert (
rf"Value '['{bad_vpc_settings['SubnetIds'][0]}']' at "
rf"'vpcSettings.subnetIds' failed to satisfy constraint: "
rf"Member must satisfy regular expression pattern: "
rf"^(subnet-[0-9a-f]{{8}}|subnet-[0-9a-f]{{17}})$" in err["Message"]
)
@mock_aws
def test_ds_create_microsoft_ad_good_args():
"""Test creation of Microsoft AD directory using good arguments."""
client = boto3.client("ds", region_name=TEST_REGION)
ec2_client = boto3.client("ec2", region_name=TEST_REGION)
# Verify a good call to create_microsoft_ad()
directory_id = create_test_microsoft_ad(client, ec2_client)
assert directory_id.startswith("d-")
# Verify that too many directories can't be created.
limits = client.get_directory_limits()["DirectoryLimits"]
for _ in range(limits["CloudOnlyMicrosoftADLimit"]):
create_test_microsoft_ad(client, ec2_client)
with pytest.raises(ClientError) as exc:
create_test_microsoft_ad(client, ec2_client)
err = exc.value.response["Error"]
assert err["Code"] == "DirectoryLimitExceededException"
assert (
f"Directory limit exceeded. A maximum of "
f"{limits['CloudOnlyMicrosoftADLimit']} "
f"directories may be created" in err["Message"]
)
@mock_aws
def test_ds_create_microsoft_ad_delete():
"""Test deletion of Microsoft AD directory."""
client = boto3.client("ds", region_name=TEST_REGION)
ec2_client = boto3.client("ec2", region_name=TEST_REGION)
# Delete an existing directory.
directory_id = create_test_microsoft_ad(client, ec2_client)
result = client.delete_directory(DirectoryId=directory_id)
assert result["DirectoryId"] == directory_id
@mock_aws
def test_ds_create_microsoft_ad_describe():
"""Test describe_directory() for Microsoft AD directory."""
client = boto3.client("ds", region_name=TEST_REGION)
ec2_client = boto3.client("ec2", region_name=TEST_REGION)
# Test that if no directory IDs are specified, all are returned.
directory_id = create_test_microsoft_ad(client, ec2_client)
result = client.describe_directories()
directory = result["DirectoryDescriptions"][0]
assert len(result["DirectoryDescriptions"]) == 1
assert directory["DesiredNumberOfDomainControllers"] == 0
assert not directory["SsoEnabled"]
assert directory["DirectoryId"] == directory_id
assert directory["Name"].startswith("test-")
assert directory["Alias"] == directory_id
assert directory["AccessUrl"] == f"{directory_id}.awsapps.com"
assert directory["Stage"] == "Active"
assert directory["LaunchTime"] <= datetime.now(timezone.utc)
assert directory["StageLastUpdatedDateTime"] <= datetime.now(timezone.utc)
assert directory["Type"] == "MicrosoftAD"
assert directory["VpcSettings"]["VpcId"].startswith("vpc-")
assert len(directory["VpcSettings"]["SubnetIds"]) == 2
assert directory["Edition"] == "Standard"
assert len(directory["DnsIpAddrs"]) == 2
assert "NextToken" not in result
@mock_aws
def test_ds_create_microsoft_ad_tags():
"""Test that AD directory tags can be added and retrieved."""
client = boto3.client("ds", region_name=TEST_REGION)
ec2_client = boto3.client("ec2", region_name=TEST_REGION)
added_tags = [{"Key": f"{x}", "Value": f"{x}"} for x in range(10)]
directory_id = create_test_microsoft_ad(client, ec2_client, tags=added_tags)
result = client.list_tags_for_resource(ResourceId=directory_id)
assert len(result["Tags"]) == 10
assert result["Tags"] == added_tags
@mock_aws
def test_ds_get_microsoft_ad_directory_limits():
"""Test return value for directory limits."""
client = boto3.client("ds", region_name=TEST_REGION)
ec2_client = boto3.client("ec2", region_name=TEST_REGION)
# Create a bunch of directories and verify the current count has been
# updated.
limits = client.get_directory_limits()["DirectoryLimits"]
for _ in range(limits["CloudOnlyMicrosoftADLimit"]):
create_test_microsoft_ad(client, ec2_client)
limits = client.get_directory_limits()["DirectoryLimits"]
assert (
limits["CloudOnlyMicrosoftADLimit"]
== limits["CloudOnlyMicrosoftADCurrentCount"]
)
assert limits["CloudOnlyMicrosoftADLimitReached"]
assert not limits["ConnectedDirectoriesLimitReached"]
assert not limits["CloudOnlyDirectoriesCurrentCount"]
@mock_aws
def test_enable_describe_disable_ldaps():
"""Test good and bad invocations of describe_directories()."""
client = boto3.client("ds", region_name=TEST_REGION)
ec2_client = boto3.client("ec2", region_name=TEST_REGION)
directory_id = create_test_microsoft_ad(client, ec2_client)
# Describe LDAPS settings for Microsoft AD without LDAPS enabled
ldaps = client.describe_ldaps_settings(DirectoryId=directory_id)[
"LDAPSSettingsInfo"
]
assert ldaps == []
# Enable LDAPS for Microsoft AD and verify it is enabled
client.enable_ldaps(DirectoryId=directory_id, Type="Client")
ldaps = client.describe_ldaps_settings(DirectoryId=directory_id)[
"LDAPSSettingsInfo"
]
assert len(ldaps) == 1
assert ldaps[0]["LDAPSStatus"] == "Enabled"
# Disable LDAPS for Microsoft AD and verify it is disabled
client.disable_ldaps(DirectoryId=directory_id, Type="Client")
ldaps = client.describe_ldaps_settings(DirectoryId=directory_id)[
"LDAPSSettingsInfo"
]
assert len(ldaps) == 1
assert ldaps[0]["LDAPSStatus"] == "Disabled"
@mock_aws
def test_describe_settings():
client = boto3.client("ds", region_name=TEST_REGION)
ec2_client = boto3.client("ec2", region_name=TEST_REGION)
directory_id = create_test_microsoft_ad(client, ec2_client)
# Describe the settings for a Microsoft AD directory
settings = client.describe_settings(DirectoryId=directory_id)["SettingEntries"]
assert len(settings) > 0
assert "TLS_1_0" in [s["Name"] for s in settings]
@mock_aws
def test_update_settings():
client = boto3.client("ds", region_name=TEST_REGION)
ec2_client = boto3.client("ec2", region_name=TEST_REGION)
directory_id = create_test_microsoft_ad(client, ec2_client)
# Check the current setting for TLS 1.0
directory_settings = client.describe_settings(DirectoryId=directory_id)[
"SettingEntries"
]
tls_1_0_setting = next(
(s for s in directory_settings if s["Name"] == "TLS_1_0"), None
)
assert tls_1_0_setting["AppliedValue"] == "Enable"
new_setting = {"Name": "TLS_1_0", "Value": "Disable"}
client.update_settings(DirectoryId=directory_id, Settings=[new_setting])
# Check the updated setting for TLS 1.0
new_directory_settings = client.describe_settings(DirectoryId=directory_id)[
"SettingEntries"
]
new_tls_1_0_setting = next(
(s for s in new_directory_settings if s["Name"] == "TLS_1_0"), None
)
assert new_tls_1_0_setting["AppliedValue"] == "Disable"
|