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 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
|
"""OpenSearchServiceServerlessBackend class with methods for supported APIs."""
import json
from typing import Any
from moto.core.base_backend import BackendDict, BaseBackend
from moto.core.common_models import BaseModel
from moto.core.utils import unix_time
from moto.moto_api._internal import mock_random
from moto.utilities.tagging_service import TaggingService
from .exceptions import (
ConflictException,
ResourceNotFoundException,
ValidationException,
)
class SecurityPolicy(BaseModel):
def __init__(
self,
client_token: str,
description: str,
name: str,
policy: str,
type: str,
):
self.client_token = client_token
self.description = description
self.name = name
self.type = type
self.created_date = int(unix_time() * 1000)
# update policy # current date default
self.last_modified_date = int(unix_time() * 1000)
self.policy = json.loads(policy)
self.policy_version = mock_random.get_random_string(20)
if type == "encryption":
self.resources = [
res for rule in self.policy["Rules"] for res in rule["Resource"]
]
else:
self.resources = [
res
for p in self.policy
for rule in p["Rules"]
for res in rule["Resource"]
]
def to_dict(self) -> dict[str, Any]:
dct = {
"createdDate": self.created_date,
"description": self.description,
"lastModifiedDate": self.last_modified_date,
"name": self.name,
"policy": self.policy,
"policyVersion": self.policy_version,
"type": self.type,
}
return {k: v for k, v in dct.items() if v}
def to_dict_list(self) -> dict[str, Any]:
dct = self.to_dict()
dct.pop("policy")
return {k: v for k, v in dct.items() if v}
class Collection(BaseModel):
def __init__(
self,
client_token: str,
description: str,
name: str,
standby_replicas: str,
tags: list[dict[str, str]],
type: str,
policy: Any,
region: str,
account_id: str,
):
self.client_token = client_token
self.description = description
self.name = name
self.standby_replicas = standby_replicas
self.tags = tags
self.type = type
self.id = mock_random.get_random_string(length=20, lower_case=True)
self.arn = f"arn:aws:aoss:{region}:{account_id}:collection/{self.id}"
self.created_date = int(unix_time() * 1000)
self.kms_key_arn = policy["KmsARN"]
self.last_modified_date = int(unix_time() * 1000)
self.status = "ACTIVE"
self.collection_endpoint = f"https://{self.id}.{region}.aoss.amazonaws.com"
self.dashboard_endpoint = (
f"https://{self.id}.{region}.aoss.amazonaws.com/_dashboards"
)
def to_dict(self) -> dict[str, Any]:
dct = {
"arn": self.arn,
"createdDate": self.created_date,
"description": self.description,
"id": self.id,
"kmsKeyArn": self.kms_key_arn,
"lastModifiedDate": self.last_modified_date,
"name": self.name,
"standbyReplicas": self.standby_replicas,
"status": self.status,
"type": self.type,
}
return {k: v for k, v in dct.items() if v}
def to_dict_list(self) -> dict[str, Any]:
dct = {"arn": self.arn, "id": self.id, "name": self.name, "status": self.status}
return {k: v for k, v in dct.items() if v}
def to_dict_batch(self) -> dict[str, Any]:
dct = self.to_dict()
dct_options = {
"collectionEndpoint": self.collection_endpoint,
"dashboardEndpoint": self.dashboard_endpoint,
}
for key, value in dct_options.items():
if value is not None:
dct[key] = value
return dct
class OSEndpoint(BaseModel):
def __init__(
self,
client_token: str,
name: str,
security_group_ids: list[str],
subnet_ids: list[str],
vpc_id: str,
):
self.client_token = client_token
self.name = name
self.security_group_ids = security_group_ids
self.subnet_ids = subnet_ids
self.vpc_id = vpc_id
self.id = f"vpce-0{mock_random.get_random_string(length=16, lower_case=True)}"
self.status = "ACTIVE"
def to_dict(self) -> dict[str, Any]:
dct = {"id": self.id, "name": self.name, "status": self.status}
return {k: v for k, v in dct.items() if v}
class OpenSearchServiceServerlessBackend(BaseBackend):
"""Implementation of OpenSearchServiceServerless APIs."""
def __init__(self, region_name: str, account_id: str):
super().__init__(region_name, account_id)
self.collections: dict[str, Collection] = {}
self.security_policies: dict[str, SecurityPolicy] = {}
self.os_endpoints: dict[str, OSEndpoint] = {}
self.tagger = TaggingService(
tag_name="tags", key_name="key", value_name="value"
)
def create_security_policy(
self, client_token: str, description: str, name: str, policy: str, type: str
) -> SecurityPolicy:
if not client_token:
client_token = mock_random.get_random_string(10)
if (name, type) in [
(sp.name, sp.type) for sp in list(self.security_policies.values())
]:
raise ConflictException(
msg=f"Policy with name {name} and type {type} already exists"
)
if type not in ["encryption", "network"]:
raise ValidationException(
msg=f"1 validation error detected: Value '{type}' at 'type' failed to satisfy constraint: Member must satisfy enum value set: [encryption, network]"
)
security_policy = SecurityPolicy(
client_token=client_token,
description=description,
name=name,
policy=policy,
type=type,
)
self.security_policies[security_policy.client_token] = security_policy
return security_policy
def get_security_policy(self, name: str, type: str) -> SecurityPolicy:
for sp in list(self.security_policies.values()):
if sp.name == name and sp.type == type:
return sp
raise ResourceNotFoundException(
msg=f"Policy with name {name} and type {type} is not found"
)
def list_security_policies(
self, resource: list[str], type: str
) -> list[SecurityPolicy]:
"""
Pagination is not yet implemented
"""
security_policy_summaries = []
if resource:
for res in resource:
security_policy_summaries.extend(
[
sp
for sp in list(self.security_policies.values())
if res in sp.resources and type == sp.type
]
)
else:
security_policy_summaries = [
sp for sp in list(self.security_policies.values()) if sp.type == type
]
return security_policy_summaries
def update_security_policy(
self,
client_token: str,
description: str,
name: str,
policy: str,
policy_version: str,
type: str,
) -> SecurityPolicy:
if not client_token:
client_token = mock_random.get_random_string(10)
for sp in list(self.security_policies.values()):
if sp.name == name and sp.type == type:
if sp.policy_version == policy_version:
last_modified_date = sp.last_modified_date
if sp.policy != json.loads(policy):
last_modified_date = int(unix_time() * 1000)
# Updating policy version
policy_version = mock_random.get_random_string(20)
sp.client_token = client_token
sp.description = description
sp.name = name
sp.policy = json.loads(policy)
sp.last_modified_date = last_modified_date
sp.policy_version = policy_version
return sp
else:
raise ValidationException(
msg="Policy version specified in the request refers to an older version and policy has since changed"
)
raise ResourceNotFoundException(
msg=f"Policy with name {name} and type {type} is not found"
)
def create_collection(
self,
client_token: str,
description: str,
name: str,
standby_replicas: str,
tags: list[dict[str, str]],
type: str,
) -> Collection:
policy = ""
if not client_token:
client_token = mock_random.get_random_string(10)
for sp in list(self.security_policies.values()):
if f"collection/{name}" in sp.resources:
policy = sp.policy
if not policy:
raise ValidationException(
msg=f"No matching security policy of encryption type found for collection name: {name}. Please create security policy of encryption type for this collection."
)
collection = Collection(
client_token=client_token,
description=description,
name=name,
standby_replicas=standby_replicas,
tags=tags,
type=type,
policy=policy,
region=self.region_name,
account_id=self.account_id,
)
self.collections[collection.id] = collection
self.tag_resource(collection.arn, tags)
return collection
def list_collections(self, collection_filters: dict[str, str]) -> list[Collection]:
"""
Pagination is not yet implemented
"""
collection_summaries = []
if (collection_filters) and ("name" in collection_filters):
collection_summaries = [
collection
for collection in list(self.collections.values())
if collection.name == collection_filters["name"]
]
else:
collection_summaries = list(self.collections.values())
return collection_summaries
def create_vpc_endpoint(
self,
client_token: str,
name: str,
security_group_ids: list[str],
subnet_ids: list[str],
vpc_id: str,
) -> OSEndpoint:
if not client_token:
client_token = mock_random.get_random_string(10)
# Only 1 endpoint should exists under each VPC
if vpc_id in [ose.vpc_id for ose in list(self.os_endpoints.values())]:
raise ConflictException(
msg=f"Failed to create a VpcEndpoint {name} for AccountId {self.account_id} :: There is already a VpcEndpoint exist under VpcId {vpc_id}"
)
os_endpoint = OSEndpoint(
client_token=client_token,
name=name,
security_group_ids=security_group_ids,
subnet_ids=subnet_ids,
vpc_id=vpc_id,
)
self.os_endpoints[os_endpoint.client_token] = os_endpoint
return os_endpoint
def delete_collection(self, client_token: str, id: str) -> Collection:
if not client_token:
client_token = mock_random.get_random_string(10)
if id in self.collections:
self.collections[id].status = "DELETING"
return self.collections.pop(id)
raise ResourceNotFoundException(f"Collection with ID {id} cannot be found.")
def tag_resource(self, resource_arn: str, tags: list[dict[str, str]]) -> None:
self.tagger.tag_resource(resource_arn, tags)
def untag_resource(self, resource_arn: str, tag_keys: list[str]) -> None:
self.tagger.untag_resource_using_names(resource_arn, tag_keys)
def list_tags_for_resource(self, resource_arn: str) -> list[dict[str, str]]:
return self.tagger.list_tags_for_resource(resource_arn)["tags"]
def batch_get_collection(
self, ids: list[str], names: list[str]
) -> tuple[list[Any], list[dict[str, str]]]:
collection_details = []
collection_error_details = []
collection_error_detail = {
"errorCode": "NOT_FOUND",
"errorMessage": "The specified Collection is not found.",
}
if ids and names:
raise ValidationException(
msg="You need to provide IDs or names. You can't provide both IDs and names in the same request"
)
if ids:
for i in ids:
if i in self.collections:
collection_details.append(self.collections[i].to_dict_batch())
else:
collection_error_detail["id"] = i
collection_error_details.append(collection_error_detail)
if names:
for n in names:
for collection in self.collections.values():
if collection.name == n:
collection_details.append(collection.to_dict_batch())
else:
collection_error_detail["name"] = n
collection_error_details.append(collection_error_detail)
return collection_details, collection_error_details
opensearchserverless_backends = BackendDict(
OpenSearchServiceServerlessBackend, "opensearchserverless"
)
|