Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
[FEATURE] : add AWS Backup service (#340) (#473)
Akhil Adiga457c3459587d
diff --git a/README.md b/README.mdindex 954956a5..06fb47ac 100644--- a/README.md+++ b/README.md@@ -360,6 +360,7 @@ subnet = ec2.create_subnet(| **SES** | SendEmail, SendRawEmail, SendTemplatedEmail, SendBulkTemplatedEmail, VerifyEmailIdentity, VerifyEmailAddress, VerifyDomainIdentity, VerifyDomainDkim, ListIdentities, ListVerifiedEmailAddresses, GetIdentityVerificationAttributes, GetIdentityDkimAttributes, DeleteIdentity, GetSendQuota, GetSendStatistics, SetIdentityNotificationTopic, SetIdentityFeedbackForwardingEnabled, CreateConfigurationSet, DeleteConfigurationSet, DescribeConfigurationSet, ListConfigurationSets, CreateTemplate, GetTemplate, UpdateTemplate, DeleteTemplate, ListTemplates | Emails stored in-memory, not sent || **SES v2** | SendEmail, CreateEmailIdentity, GetEmailIdentity, DeleteEmailIdentity, ListEmailIdentities, CreateConfigurationSet, GetConfigurationSet, DeleteConfigurationSet, ListConfigurationSets, GetAccount, PutAccountSuppressionAttributes, ListSuppressedDestinations | REST API (`/v2/email/`); identities auto-verified; emails stored in-memory, not sent || **ACM** | RequestCertificate, DescribeCertificate, ListCertificates, DeleteCertificate, GetCertificate, ImportCertificate, AddTagsToCertificate, RemoveTagsFromCertificate, ListTagsForCertificate, UpdateCertificateOptions, RenewCertificate, ResendValidationEmail | Certificates auto-issued; DNS validation records generated; supports SANs |+| **Backup** | CreateBackupVault, DescribeBackupVault, DeleteBackupVault, ListBackupVaults, CreateBackupPlan, GetBackupPlan, UpdateBackupPlan, DeleteBackupPlan, ListBackupPlans, ListBackupPlanVersions, CreateBackupSelection, GetBackupSelection, DeleteBackupSelection, ListBackupSelections, StartBackupJob, StopBackupJob, DescribeBackupJob, ListBackupJobs, TagResource, UntagResource, ListTags | In-memory; jobs complete immediately; vaults and plans participate in Resource Groups Tagging API || **WAF v2** | CreateWebACL, GetWebACL, UpdateWebACL, DeleteWebACL, ListWebACLs, AssociateWebACL, DisassociateWebACL, GetWebACLForResource, ListResourcesForWebACL, CreateIPSet, GetIPSet, UpdateIPSet, DeleteIPSet, ListIPSets, CreateRuleGroup, GetRuleGroup, UpdateRuleGroup, DeleteRuleGroup, ListRuleGroups, TagResource, UntagResource, ListTagsForResource, CheckCapacity, DescribeManagedRuleGroup | LockToken enforced on Update/Delete; resource associations tracked || **Step Functions** | CreateStateMachine, DeleteStateMachine, DescribeStateMachine, UpdateStateMachine, ListStateMachines, StartExecution, StartSyncExecution, StopExecution, DescribeExecution, DescribeStateMachineForExecution, ListExecutions, GetExecutionHistory, SendTaskSuccess, SendTaskFailure, SendTaskHeartbeat, CreateActivity, DeleteActivity, DescribeActivity, ListActivities, GetActivityTask, TestState, TagResource, UntagResource, ListTagsForResource | Full ASL interpreter; Retry/Catch; waitForTaskToken; Activities (worker pattern); Pass/Task/Choice/Wait/Succeed/Fail/Map/Parallel; TestState API with mock and inspectionLevel support; SFN_MOCK_CONFIG for AWS SFN Local compatible mock testing; intrinsic functions (States.StringToJson, States.JsonToString, States.JsonMerge, States.Format); nested startExecution.sync || **API Gateway v2** | CreateApi, GetApi, GetApis, UpdateApi, DeleteApi, CreateRoute, GetRoute, GetRoutes, UpdateRoute, DeleteRoute, CreateIntegration, GetIntegration, GetIntegrations, UpdateIntegration, DeleteIntegration, CreateRouteResponse, GetRouteResponse, GetRouteResponses, UpdateRouteResponse, DeleteRouteResponse, CreateIntegrationResponse, GetIntegrationResponse, GetIntegrationResponses, UpdateIntegrationResponse, DeleteIntegrationResponse, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateDeployment, GetDeployment, GetDeployments, DeleteDeployment, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, TagResource, UntagResource, GetTags, PostToConnection, GetConnection, DeleteConnection | **HTTP API** and **WebSocket API** (`protocolType=WEBSOCKET`); Lambda proxy (`AWS_PROXY`), HTTP proxy (`HTTP_PROXY`), and MOCK integrations; HTTP data plane via `{apiId}.execute-api.localhost` Host header or path-based `/_aws/execute-api/{apiId}/{stage}/{path}` (no DNS/Host override needed — works from browsers on macOS and strict clients); `$default` stage served from the URL root (no stage segment in the path); per-API `corsConfiguration` applied to preflights + dispatched responses; qualified-alias integration URIs (`arn:...:function:<name>:<alias>`) resolve to the alias's target version; WebSocket data plane on the same two URL forms, with `$connect` / `$disconnect` / `$default` / custom-action routing, `$request.body.*` RouteSelectionExpression, `@connections` management API (PostToConnection / GetConnection / DeleteConnection), per-connection outbox for server-side push; `{param}` / `{proxy+}` matching; JWT/Lambda authorizer CRUD; pin `apiId` across runs with the `ms-custom-id` tag |diff --git a/ministack/app.py b/ministack/app.pyindex 23c9ec75..f692c886 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -137,6 +137,7 @@ logger = logging.getLogger("ministack")# Single source of truth for routable services, their backing modules, and aliases.SERVICE_REGISTRY = {"acm": {"module": "acm"},+ "backup": {"module": "backup"},"apigateway": {"module": "apigateway", "aliases": ("execute-api", "apigatewayv2")},"appconfig": {"module": "appconfig"},"appconfigdata": {"module": "appconfig"},@@ -1111,7 +1112,7 @@ async def _handle_lifespan(scope, receive, send):"servicediscovery": "servicediscovery", "s3files": "s3files","appconfig": "appconfig", "transfer": "transfer","scheduler": "scheduler", "autoscaling": "autoscaling",- "eks": "eks",+ "eks": "eks", "backup": "backup",}save_dict = {}for key, mod_name in _state_map.items():diff --git a/ministack/core/router.py b/ministack/core/router.pyindex b25b9abc..996141da 100644--- a/ministack/core/router.py+++ b/ministack/core/router.py@@ -219,6 +219,11 @@ SERVICE_PATTERNS = {"host_patterns": [r"tagging\."],"credential_scope": "tagging",},+ "backup": {+ "host_patterns": [r"backup\."],+ "path_prefixes": ["/backup-vaults", "/backup/plans", "/backup-jobs", "/untag"],+ "credential_scope": "backup",+ },}diff --git a/ministack/services/backup.py b/ministack/services/backup.pynew file mode 100644index 00000000..a18901ee--- /dev/null+++ b/ministack/services/backup.py@@ -0,0 +1,594 @@+"""+AWS Backup Service Emulator.+REST/JSON protocol — /backup-vaults/*, /backup/plans/*, /backup-jobs/*, /tags/* paths.++Supports:+ Vaults: CreateBackupVault, DescribeBackupVault, DeleteBackupVault, ListBackupVaults+ Plans: CreateBackupPlan, GetBackupPlan, UpdateBackupPlan, DeleteBackupPlan,+ ListBackupPlans, ListBackupPlanVersions+ Selections: CreateBackupSelection, GetBackupSelection, DeleteBackupSelection,+ ListBackupSelections+ Jobs: StartBackupJob, StopBackupJob, DescribeBackupJob, ListBackupJobs+ Tags: TagResource, UntagResource, ListTags+"""++import copy+import json+import logging+import time++from ministack.core.responses import AccountScopedDict, get_account_id, get_region, new_uuid++logger = logging.getLogger("backup")++# ---------------------------------------------------------------------------+# State+# ---------------------------------------------------------------------------++_vaults = AccountScopedDict() # vault_name -> vault record+_plans = AccountScopedDict() # plan_id -> plan record+_selections = AccountScopedDict() # selection_id -> selection record+_jobs = AccountScopedDict() # job_id -> job record+++def reset():+ _vaults.clear()+ _plans.clear()+ _selections.clear()+ _jobs.clear()+++def get_state():+ return copy.deepcopy({+ "vaults": dict(_vaults),+ "plans": dict(_plans),+ "selections": dict(_selections),+ "jobs": dict(_jobs),+ })+++def restore_state(data):+ _vaults.update(data.get("vaults", {}))+ _plans.update(data.get("plans", {}))+ _selections.update(data.get("selections", {}))+ _jobs.update(data.get("jobs", {}))+++def load_persisted_state(data):+ restore_state(data)+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------++def _ts():+ return time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime())+++def _epoch():+ return time.time()+++def _vault_arn(name):+ return f"arn:aws:backup:{get_region()}:{get_account_id()}:backup-vault:{name}"+++def _plan_arn(plan_id):+ return f"arn:aws:backup:{get_region()}:{get_account_id()}:backup-plan:{plan_id}"+++def _selection_arn(plan_id, selection_id):+ return f"arn:aws:backup:{get_region()}:{get_account_id()}:backup-selection:{plan_id}/{selection_id}"+++def _job_arn(job_id):+ return f"arn:aws:backup:{get_region()}:{get_account_id()}:backup-job:{job_id}"+++def _recovery_point_arn(vault_name):+ return (+ f"arn:aws:backup:{get_region()}:{get_account_id()}:"+ f"recovery-point:{vault_name}/{new_uuid()}"+ )+++def _ok(body):+ return 200, {"Content-Type": "application/json"}, json.dumps(body).encode()+++def _no_content():+ return 200, {"Content-Type": "application/json"}, b""+++def _err(code, msg, status=400):+ return (+ status,+ {"Content-Type": "application/json"},+ json.dumps({"__type": code, "Message": msg}).encode(),+ )+++def _paginate(items, query, key):+ """Simple token-based pagination over a list."""+ max_results = int(query.get("maxResults", query.get("MaxResults", 100)))+ next_token = query.get("nextToken", query.get("NextToken", ""))+ start = 0+ if next_token:+ try:+ start = int(next_token)+ except ValueError:+ start = 0+ page = items[start:start + max_results]+ out = {key: page}+ if start + max_results < len(items):+ out["NextToken"] = str(start + max_results)+ return _ok(out)+++# ---------------------------------------------------------------------------+# Vaults+# ---------------------------------------------------------------------------++def _create_vault(name, body):+ if name in _vaults:+ return _err("AlreadyExistsException", f"Vault '{name}' already exists.", 409)+ vault = {+ "BackupVaultName": name,+ "BackupVaultArn": _vault_arn(name),+ "CreationDate": _epoch(),+ "EncryptionKeyArn": body.get("EncryptionKeyArn", ""),+ "BackupVaultTags": body.get("BackupVaultTags", {}),+ "CreatorRequestId": body.get("CreatorRequestId", ""),+ "NumberOfRecoveryPoints": 0,+ "Locked": False,+ }+ _vaults[name] = vault+ logger.info("CreateBackupVault: %s", name)+ return _ok({+ "BackupVaultName": vault["BackupVaultName"],+ "BackupVaultArn": vault["BackupVaultArn"],+ "CreationDate": vault["CreationDate"],+ })+++def _describe_vault(name):+ v = _vaults.get(name)+ if v is None:+ return _err("ResourceNotFoundException", f"Vault '{name}' not found.", 404)+ return _ok(copy.copy(v))+++def _delete_vault(name):+ if name not in _vaults:+ return _err("ResourceNotFoundException", f"Vault '{name}' not found.", 404)+ del _vaults[name]+ logger.info("DeleteBackupVault: %s", name)+ return _no_content()+++def _list_vaults(query):+ items = list(_vaults.values())+ return _paginate(items, query, "BackupVaultList")+++# ---------------------------------------------------------------------------+# Plans+# ---------------------------------------------------------------------------++def _create_plan(body):+ plan_data = body.get("BackupPlan", {})+ if not plan_data:+ return _err("InvalidParameterValueException", "BackupPlan is required.", 400)+ plan_id = new_uuid()+ version_id = new_uuid()+ now = _epoch()+ record = {+ "BackupPlanId": plan_id,+ "BackupPlanArn": _plan_arn(plan_id),+ "BackupPlanName": plan_data.get("BackupPlanName", ""),+ "CreationDate": now,+ "LastExecutionDate": now,+ "VersionId": version_id,+ "BackupPlan": plan_data,+ "Tags": body.get("BackupPlanTags", {}),+ "AdvancedBackupSettings": plan_data.get("AdvancedBackupSettings", []),+ "Versions": [{+ "BackupPlanId": plan_id,+ "BackupPlanArn": _plan_arn(plan_id),+ "BackupPlanName": plan_data.get("BackupPlanName", ""),+ "CreationDate": now,+ "VersionId": version_id,+ "BackupPlan": copy.deepcopy(plan_data),+ }],+ }+ _plans[plan_id] = record+ logger.info("CreateBackupPlan: %s (%s)", plan_data.get("BackupPlanName"), plan_id)+ return _ok({+ "BackupPlanId": plan_id,+ "BackupPlanArn": record["BackupPlanArn"],+ "CreationDate": now,+ "VersionId": version_id,+ })+++def _get_plan(plan_id):+ p = _plans.get(plan_id)+ if p is None:+ return _err("ResourceNotFoundException", f"Plan '{plan_id}' not found.", 404)+ return _ok({+ "BackupPlanId": p["BackupPlanId"],+ "BackupPlanArn": p["BackupPlanArn"],+ "BackupPlanName": p["BackupPlanName"],+ "CreationDate": p["CreationDate"],+ "LastExecutionDate": p["LastExecutionDate"],+ "VersionId": p["VersionId"],+ "BackupPlan": p["BackupPlan"],+ "AdvancedBackupSettings": p["AdvancedBackupSettings"],+ })+++def _update_plan(plan_id, body):+ p = _plans.get(plan_id)+ if p is None:+ return _err("ResourceNotFoundException", f"Plan '{plan_id}' not found.", 404)+ plan_data = body.get("BackupPlan", {})+ if not plan_data:+ return _err("InvalidParameterValueException", "BackupPlan is required.", 400)+ new_version = new_uuid()+ now = _epoch()+ p["BackupPlan"] = plan_data+ p["BackupPlanName"] = plan_data.get("BackupPlanName", p["BackupPlanName"])+ p["AdvancedBackupSettings"] = plan_data.get("AdvancedBackupSettings", [])+ p["VersionId"] = new_version+ p["LastExecutionDate"] = now+ p["Versions"].append({+ "BackupPlanId": plan_id,+ "BackupPlanArn": p["BackupPlanArn"],+ "BackupPlanName": p["BackupPlanName"],+ "CreationDate": now,+ "VersionId": new_version,+ "BackupPlan": copy.deepcopy(plan_data),+ })+ logger.info("UpdateBackupPlan: %s", plan_id)+ return _ok({+ "BackupPlanId": plan_id,+ "BackupPlanArn": p["BackupPlanArn"],+ "CreationDate": p["CreationDate"],+ "VersionId": new_version,+ })+++def _delete_plan(plan_id):+ p = _plans.get(plan_id)+ if p is None:+ return _err("ResourceNotFoundException", f"Plan '{plan_id}' not found.", 404)+ del _plans[plan_id]+ logger.info("DeleteBackupPlan: %s", plan_id)+ return _ok({+ "BackupPlanId": plan_id,+ "BackupPlanArn": p["BackupPlanArn"],+ "DeletionDate": _epoch(),+ "VersionId": p["VersionId"],+ })+++def _list_plans(query):+ items = [+ {+ "BackupPlanId": p["BackupPlanId"],+ "BackupPlanArn": p["BackupPlanArn"],+ "BackupPlanName": p["BackupPlanName"],+ "CreationDate": p["CreationDate"],+ "LastExecutionDate": p["LastExecutionDate"],+ "VersionId": p["VersionId"],+ }+ for p in _plans.values()+ ]+ return _paginate(items, query, "BackupPlansList")+++def _list_plan_versions(plan_id):+ p = _plans.get(plan_id)+ if p is None:+ return _err("ResourceNotFoundException", f"Plan '{plan_id}' not found.", 404)+ return _ok({"BackupPlanVersionsList": p["Versions"]})+++# ---------------------------------------------------------------------------+# Selections+# ---------------------------------------------------------------------------++def _create_selection(plan_id, body):+ if plan_id not in _plans:+ return _err("ResourceNotFoundException", f"Plan '{plan_id}' not found.", 404)+ sel = body.get("BackupSelection", {})+ if not sel:+ return _err("InvalidParameterValueException", "BackupSelection is required.", 400)+ selection_id = new_uuid()+ record = {+ "SelectionId": selection_id,+ "SelectionName": sel.get("SelectionName", ""),+ "BackupPlanId": plan_id,+ "IamRoleArn": sel.get("IamRoleArn", ""),+ "Resources": sel.get("Resources", []),+ "ListOfTags": sel.get("ListOfTags", []),+ "NotResources": sel.get("NotResources", []),+ "Conditions": sel.get("Conditions", {}),+ "CreationDate": _epoch(),+ "CreatorRequestId": body.get("CreatorRequestId", ""),+ }+ _selections[selection_id] = record+ logger.info("CreateBackupSelection: %s under plan %s", selection_id, plan_id)+ return _ok({+ "SelectionId": selection_id,+ "BackupPlanId": plan_id,+ "CreationDate": record["CreationDate"],+ })+++def _get_selection(plan_id, selection_id):+ if plan_id not in _plans:+ return _err("ResourceNotFoundException", f"Plan '{plan_id}' not found.", 404)+ s = _selections.get(selection_id)+ if s is None or s["BackupPlanId"] != plan_id:+ return _err("ResourceNotFoundException", f"Selection '{selection_id}' not found.", 404)+ return _ok({+ "SelectionId": s["SelectionId"],+ "BackupPlanId": s["BackupPlanId"],+ "BackupSelection": {+ "SelectionName": s["SelectionName"],+ "IamRoleArn": s["IamRoleArn"],+ "Resources": s["Resources"],+ "ListOfTags": s["ListOfTags"],+ "NotResources": s["NotResources"],+ "Conditions": s["Conditions"],+ },+ "CreationDate": s["CreationDate"],+ "CreatorRequestId": s["CreatorRequestId"],+ })+++def _delete_selection(plan_id, selection_id):+ if plan_id not in _plans:+ return _err("ResourceNotFoundException", f"Plan '{plan_id}' not found.", 404)+ s = _selections.get(selection_id)+ if s is None or s["BackupPlanId"] != plan_id:+ return _err("ResourceNotFoundException", f"Selection '{selection_id}' not found.", 404)+ del _selections[selection_id]+ logger.info("DeleteBackupSelection: %s", selection_id)+ return _no_content()+++def _list_selections(plan_id):+ if plan_id not in _plans:+ return _err("ResourceNotFoundException", f"Plan '{plan_id}' not found.", 404)+ items = [+ {+ "SelectionId": s["SelectionId"],+ "SelectionName": s["SelectionName"],+ "BackupPlanId": s["BackupPlanId"],+ "IamRoleArn": s["IamRoleArn"],+ "CreationDate": s["CreationDate"],+ }+ for s in _selections.values()+ if s["BackupPlanId"] == plan_id+ ]+ return _ok({"BackupSelectionsList": items})+++# ---------------------------------------------------------------------------+# Jobs+# ---------------------------------------------------------------------------++def _start_job(body):+ vault_name = body.get("BackupVaultName", "")+ if vault_name and vault_name not in _vaults:+ return _err("ResourceNotFoundException", f"Vault '{vault_name}' not found.", 404)+ job_id = new_uuid()+ now = _epoch()+ record = {+ "BackupJobId": job_id,+ "BackupJobArn": _job_arn(job_id),+ "BackupVaultName": vault_name,+ "BackupVaultArn": _vault_arn(vault_name) if vault_name else "",+ "ResourceArn": body.get("ResourceArn", ""),+ "IamRoleArn": body.get("IamRoleArn", ""),+ "StartBy": now,+ "CreationDate": now,+ "CompletionDate": now,+ "State": "COMPLETED",+ "StatusMessage": "",+ "PercentDone": "100.0",+ "BackupSizeInBytes": 0,+ "IsParent": False,+ "RecoveryPointArn": _recovery_point_arn(vault_name) if vault_name else "",+ "RecoveryPointTags": body.get("RecoveryPointTags", {}),+ "IdempotencyToken": body.get("IdempotencyToken", ""),+ }+ _jobs[job_id] = record+ # increment recovery point count on the vault+ if vault_name and vault_name in _vaults:+ _vaults[vault_name]["NumberOfRecoveryPoints"] += 1+ logger.info("StartBackupJob: %s vault=%s", job_id, vault_name)+ return _ok({+ "BackupJobId": job_id,+ "RecoveryPointArn": record["RecoveryPointArn"],+ "CreationDate": now,+ "IsParent": False,+ })+++def _stop_job(job_id):+ j = _jobs.get(job_id)+ if j is None:+ return _err("ResourceNotFoundException", f"Job '{job_id}' not found.", 404)+ if j["State"] in ("COMPLETED", "FAILED", "ABORTED"):+ return _err(+ "InvalidRequestException",+ f"Job '{job_id}' is already in terminal state '{j['State']}'.",+ 400,+ )+ j["State"] = "ABORTED"+ j["CompletionDate"] = _epoch()+ logger.info("StopBackupJob: %s", job_id)+ return _no_content()+++def _describe_job(job_id):+ j = _jobs.get(job_id)+ if j is None:+ return _err("ResourceNotFoundException", f"Job '{job_id}' not found.", 404)+ return _ok(copy.copy(j))+++def _list_jobs(query):+ vault_filter = query.get("backupVaultName", "")+ state_filter = query.get("state", "")+ resource_filter = query.get("resourceArn", "")+ items = list(_jobs.values())+ if vault_filter:+ items = [j for j in items if j["BackupVaultName"] == vault_filter]+ if state_filter:+ items = [j for j in items if j["State"] == state_filter]+ if resource_filter:+ items = [j for j in items if j["ResourceArn"] == resource_filter]+ return _paginate(items, query, "BackupJobs")+++# ---------------------------------------------------------------------------+# Tags+# ---------------------------------------------------------------------------++def _resolve_resource(arn):+ """Return the mutable tag dict for a supported backup ARN, or None."""+ if ":backup-vault:" in arn:+ name = arn.split(":")[-1]+ v = _vaults.get(name)+ return v["BackupVaultTags"] if v is not None else None+ if ":backup-plan:" in arn:+ pid = arn.split(":")[-1]+ p = _plans.get(pid)+ return p["Tags"] if p is not None else None+ return None+++def _tag_resource(arn, body):+ tags = body.get("Tags", {})+ tag_dict = _resolve_resource(arn)+ if tag_dict is None:+ return _err("ResourceNotFoundException", f"Resource '{arn}' not found.", 404)+ tag_dict.update(tags)+ return _no_content()+++def _untag_resource(arn, body):+ keys = body.get("TagKeyList", [])+ tag_dict = _resolve_resource(arn)+ if tag_dict is None:+ return _err("ResourceNotFoundException", f"Resource '{arn}' not found.", 404)+ for k in keys:+ tag_dict.pop(k, None)+ return _no_content()+++def _list_tags(arn):+ tag_dict = _resolve_resource(arn)+ if tag_dict is None:+ return _err("ResourceNotFoundException", f"Resource '{arn}' not found.", 404)+ return _ok({"Tags": dict(tag_dict)})+++# ---------------------------------------------------------------------------+# Request Router+# ---------------------------------------------------------------------------++async def handle_request(method, path, headers, body_bytes, query_params):+ try:+ body = json.loads(body_bytes) if body_bytes else {}+ except json.JSONDecodeError:+ body = {}++ query = {k: (v[0] if isinstance(v, list) else v) for k, v in query_params.items()}+ parts = [p for p in path.strip("/").split("/") if p]++ # /backup-vaults+ if parts and parts[0] == "backup-vaults":+ if len(parts) == 1 and method == "GET":+ return _list_vaults(query)+ if len(parts) == 2:+ name = parts[1]+ if method == "PUT":+ return _create_vault(name, body)+ if method == "GET":+ return _describe_vault(name)+ if method == "DELETE":+ return _delete_vault(name)++ # /backup/plans (and nested selections/versions)+ if len(parts) >= 2 and parts[0] == "backup" and parts[1] == "plans":+ # /backup/plans+ if len(parts) == 2:+ if method == "PUT":+ return _create_plan(body)+ if method == "GET":+ return _list_plans(query)++ # /backup/plans/{planId}+ if len(parts) == 3:+ plan_id = parts[2]+ if method == "GET":+ return _get_plan(plan_id)+ if method == "POST":+ return _update_plan(plan_id, body)+ if method == "DELETE":+ return _delete_plan(plan_id)++ # /backup/plans/{planId}/versions+ if len(parts) == 4 and parts[3] == "versions" and method == "GET":+ return _list_plan_versions(parts[2])++ # /backup/plans/{planId}/selections+ if len(parts) >= 4 and parts[3] == "selections":+ plan_id = parts[2]+ if len(parts) == 4:+ if method == "PUT":+ return _create_selection(plan_id, body)+ if method == "GET":+ return _list_selections(plan_id)+ if len(parts) == 5:+ selection_id = parts[4]+ if method == "GET":+ return _get_selection(plan_id, selection_id)+ if method == "DELETE":+ return _delete_selection(plan_id, selection_id)++ # /backup-jobs+ if parts and parts[0] == "backup-jobs":+ if len(parts) == 1:+ if method == "PUT":+ return _start_job(body)+ if method == "GET":+ return _list_jobs(query)+ if len(parts) == 2:+ job_id = parts[1]+ if method == "POST":+ return _stop_job(job_id)+ if method == "GET":+ return _describe_job(job_id)++ # /tags/{resourceArn} — TagResource (POST) and ListTags (GET)+ if parts and parts[0] == "tags":+ arn = "/".join(parts[1:])+ if method == "GET":+ return _list_tags(arn)+ if method == "POST":+ return _tag_resource(arn, body)++ # /untag/{resourceArn} — UntagResource (POST)+ if parts and parts[0] == "untag":+ arn = "/".join(parts[1:])+ if method == "POST":+ return _untag_resource(arn, body)++ return _err("ValidationException", f"No route for {method} {path}", 400)diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex b29ced41..0747297c 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -44,6 +44,7 @@ import ministack.services.cloudfront as _cfimport ministack.services.rds as _rdsimport ministack.services.autoscaling as _asgimport ministack.services.codebuild as _codebuild+import ministack.services.backup as _backuplogger = logging.getLogger("cloudformation")@@ -2798,6 +2799,40 @@ def _asg_scheduled_delete(physical_id, props):# Resource Handler Registry# ===========================================================================+# --- AWS Backup ---+++def _backup_vault_create(logical_id, props, stack_name):+ name = props.get("BackupVaultName") or _physical_name(stack_name, logical_id, max_len=50)+ tags = {t["Key"]: t["Value"] for t in props.get("BackupVaultTags", [])} if isinstance(props.get("BackupVaultTags"), list) else props.get("BackupVaultTags", {})+ body = {+ "EncryptionKeyArn": props.get("EncryptionKeyArn", ""),+ "BackupVaultTags": tags,+ }+ _backup._create_vault(name, body)+ arn = _backup._vault_arn(name)+ return name, {"BackupVaultArn": arn, "BackupVaultName": name}+++def _backup_vault_delete(physical_id, props):+ _backup._vaults.pop(physical_id, None)+++def _backup_plan_create(logical_id, props, stack_name):+ plan_cfg = props.get("BackupPlan", {})+ tags = {t["Key"]: t["Value"] for t in props.get("BackupPlanTags", [])} if isinstance(props.get("BackupPlanTags"), list) else props.get("BackupPlanTags", {})+ body = {"BackupPlan": plan_cfg, "BackupPlanTags": tags}+ _, _, resp_bytes = _backup._create_plan(body)+ import json as _json+ resp = _json.loads(resp_bytes)+ plan_id = resp["BackupPlanId"]+ return plan_id, {"BackupPlanArn": resp["BackupPlanArn"], "BackupPlanId": plan_id, "VersionId": resp["VersionId"]}+++def _backup_plan_delete(physical_id, props):+ _backup._plans.pop(physical_id, None)++_RESOURCE_HANDLERS = {"AWS::S3::Bucket": {"create": _s3_create, "delete": _s3_delete},"AWS::S3::BucketPolicy": {"create": _s3_bucket_policy_create, "delete": _s3_bucket_policy_delete},@@ -2874,6 +2909,9 @@ _RESOURCE_HANDLERS = {# EKS"AWS::EKS::Cluster": {"create": _eks_cluster_create, "delete": _eks_cluster_delete},"AWS::EKS::Nodegroup": {"create": _eks_nodegroup_create, "delete": _eks_nodegroup_delete},+ # AWS Backup+ "AWS::Backup::BackupVault": {"create": _backup_vault_create, "delete": _backup_vault_delete},+ "AWS::Backup::BackupPlan": {"create": _backup_plan_create, "delete": _backup_plan_delete},# CDK metadata — safe to ignore"AWS::CDK::Metadata": {"create": lambda lid, props, sn: (f"CDKMetadata-{lid}", {}), "delete": lambda pid, props: None},# AutoScalingdiff --git a/ministack/services/tagging.py b/ministack/services/tagging.pyindex 4cbc1380..95f2e7d8 100644--- a/ministack/services/tagging.py+++ b/ministack/services/tagging.py@@ -176,6 +176,16 @@ def _collect_efs():yield arn, _normalise_list(ap.get("Tags", []))+def _collect_backup():+ import ministack.services.backup as svc+ for name, v in svc._vaults.items():+ arn = f"arn:aws:backup:{get_region()}:{_account()}:backup-vault:{name}"+ yield arn, _normalise_flat(v.get("BackupVaultTags", {}))+ for pid, p in svc._plans.items():+ arn = f"arn:aws:backup:{get_region()}:{_account()}:backup-plan:{pid}"+ yield arn, _normalise_flat(p.get("Tags", {}))++# ResourceTypeFilter prefix -> collector_COLLECTORS = {# Phase 1@@ -196,6 +206,7 @@ _COLLECTORS = {"scheduler": _collect_scheduler,"cloudfront": _collect_cloudfront,"elasticfilesystem": _collect_efs,+ "backup": _collect_backup,}@@ -369,6 +380,24 @@ def _write_efs(arn, tags):resource["Tags"] = [{"Key": k, "Value": v} for k, v in existing.items()]+def _write_backup(arn, tags):+ import ministack.services.backup as svc+ if ":backup-vault:" in arn:+ name = arn.split(":")[-1]+ v = svc._vaults.get(name)+ if v is None:+ raise _ResourceNotFound(arn)+ v.setdefault("BackupVaultTags", {}).update(tags)+ elif ":backup-plan:" in arn:+ pid = arn.split(":")[-1]+ p = svc._plans.get(pid)+ if p is None:+ raise _ResourceNotFound(arn)+ p.setdefault("Tags", {}).update(tags)+ else:+ raise _ResourceNotFound(arn)++_WRITERS = {"s3": _write_s3, "lambda": _write_lambda, "sqs": _write_sqs,"sns": _write_sns, "dynamodb": _write_dynamodb, "events": _write_eventbridge,@@ -376,7 +405,7 @@ _WRITERS = {"glue": _write_glue, "cognito-idp": _write_cognito_idp,"cognito-identity": _write_cognito_identity, "appsync": _write_appsync,"scheduler": _write_scheduler, "cloudfront": _write_cloudfront,- "elasticfilesystem": _write_efs,+ "elasticfilesystem": _write_efs, "backup": _write_backup,}@@ -514,6 +543,18 @@ def _remove_efs(arn, keys):resource["Tags"] = [t for t in resource.get("Tags", []) if t["Key"] not in keys]+def _remove_backup(arn, keys):+ import ministack.services.backup as svc+ if ":backup-vault:" in arn:+ tags = svc._vaults.get(arn.split(":")[-1], {}).get("BackupVaultTags", {})+ elif ":backup-plan:" in arn:+ tags = svc._plans.get(arn.split(":")[-1], {}).get("Tags", {})+ else:+ return+ for k in keys:+ tags.pop(k, None)++_REMOVERS = {"s3": _remove_s3, "lambda": _remove_lambda, "sqs": _remove_sqs,"sns": _remove_sns, "dynamodb": _remove_dynamodb, "events": _remove_eventbridge,@@ -521,7 +562,7 @@ _REMOVERS = {"glue": _remove_glue, "cognito-idp": _remove_cognito_idp,"cognito-identity": _remove_cognito_identity, "appsync": _remove_appsync,"scheduler": _remove_scheduler, "cloudfront": _remove_cloudfront,- "elasticfilesystem": _remove_efs,+ "elasticfilesystem": _remove_efs, "backup": _remove_backup,}diff --git a/tests/test_backup.py b/tests/test_backup.pynew file mode 100644index 00000000..4f6f7f22--- /dev/null+++ b/tests/test_backup.py@@ -0,0 +1,454 @@+import pytest+import boto3+from botocore.exceptions import ClientError++ENDPOINT = "http://localhost:4566"+REGION = "us-east-1"++[email protected](scope="module")+def backup():+ return boto3.client(+ "backup",+ endpoint_url=ENDPOINT,+ aws_access_key_id="test",+ aws_secret_access_key="test",+ region_name=REGION,+ )+++def _uid():+ import uuid+ return uuid.uuid4().hex[:8]+++# ---------------------------------------------------------------------------+# Vault tests+# ---------------------------------------------------------------------------++def test_backup_create_vault(backup):+ name = f"test-vault-{_uid()}"+ resp = backup.create_backup_vault(BackupVaultName=name)+ assert resp["BackupVaultName"] == name+ assert f"backup-vault:{name}" in resp["BackupVaultArn"]+ assert "CreationDate" in resp+++def test_backup_describe_vault(backup):+ name = f"desc-vault-{_uid()}"+ backup.create_backup_vault(BackupVaultName=name)+ desc = backup.describe_backup_vault(BackupVaultName=name)+ assert desc["BackupVaultName"] == name+ assert f"backup-vault:{name}" in desc["BackupVaultArn"]+ assert desc["NumberOfRecoveryPoints"] == 0+++def test_backup_describe_vault_not_found(backup):+ with pytest.raises(ClientError) as exc:+ backup.describe_backup_vault(BackupVaultName="no-such-vault-xyz")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_backup_create_vault_duplicate(backup):+ name = f"dup-vault-{_uid()}"+ backup.create_backup_vault(BackupVaultName=name)+ with pytest.raises(ClientError) as exc:+ backup.create_backup_vault(BackupVaultName=name)+ assert exc.value.response["Error"]["Code"] == "AlreadyExistsException"+++def test_backup_list_vaults(backup):+ name = f"list-vault-{_uid()}"+ backup.create_backup_vault(BackupVaultName=name)+ resp = backup.list_backup_vaults()+ names = [v["BackupVaultName"] for v in resp["BackupVaultList"]]+ assert name in names+++def test_backup_delete_vault(backup):+ name = f"del-vault-{_uid()}"+ backup.create_backup_vault(BackupVaultName=name)+ backup.delete_backup_vault(BackupVaultName=name)+ with pytest.raises(ClientError) as exc:+ backup.describe_backup_vault(BackupVaultName=name)+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_backup_delete_vault_not_found(backup):+ with pytest.raises(ClientError) as exc:+ backup.delete_backup_vault(BackupVaultName="no-such-vault-xyz")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++# ---------------------------------------------------------------------------+# Plan tests+# ---------------------------------------------------------------------------++def _plan_body(name):+ return {+ "BackupPlanName": name,+ "Rules": [+ {+ "RuleName": "daily",+ "TargetBackupVaultName": "Default",+ "ScheduleExpression": "cron(0 12 * * ? *)",+ }+ ],+ }+++def test_backup_create_plan(backup):+ resp = backup.create_backup_plan(BackupPlan=_plan_body(f"plan-{_uid()}"))+ assert "BackupPlanId" in resp+ assert "BackupPlanArn" in resp+ assert "VersionId" in resp+++def test_backup_get_plan(backup):+ name = f"plan-get-{_uid()}"+ create = backup.create_backup_plan(BackupPlan=_plan_body(name))+ plan_id = create["BackupPlanId"]+ resp = backup.get_backup_plan(BackupPlanId=plan_id)+ assert resp["BackupPlanId"] == plan_id+ assert resp["BackupPlan"]["BackupPlanName"] == name+++def test_backup_get_plan_not_found(backup):+ with pytest.raises(ClientError) as exc:+ backup.get_backup_plan(BackupPlanId="no-such-plan-id")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_backup_update_plan(backup):+ name = f"plan-upd-{_uid()}"+ plan_id = backup.create_backup_plan(BackupPlan=_plan_body(name))["BackupPlanId"]+ v1 = backup.get_backup_plan(BackupPlanId=plan_id)["VersionId"]+ backup.update_backup_plan(+ BackupPlanId=plan_id,+ BackupPlan=_plan_body(f"{name}-updated"),+ )+ v2 = backup.get_backup_plan(BackupPlanId=plan_id)["VersionId"]+ assert v1 != v2+++def test_backup_list_plan_versions(backup):+ plan_id = backup.create_backup_plan(BackupPlan=_plan_body(f"ver-{_uid()}"))["BackupPlanId"]+ backup.update_backup_plan(BackupPlanId=plan_id, BackupPlan=_plan_body(f"ver-v2-{_uid()}"))+ resp = backup.list_backup_plan_versions(BackupPlanId=plan_id)+ assert len(resp["BackupPlanVersionsList"]) == 2+++def test_backup_list_plan_versions_single_version(backup):+ plan_id = backup.create_backup_plan(BackupPlan=_plan_body(f"ver-single-{_uid()}"))["BackupPlanId"]+ resp = backup.list_backup_plan_versions(BackupPlanId=plan_id)+ assert len(resp["BackupPlanVersionsList"]) == 1+++def test_backup_list_plan_versions_not_found(backup):+ with pytest.raises(ClientError) as exc:+ backup.list_backup_plan_versions(BackupPlanId="no-such-plan-id")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_backup_delete_plan_not_found(backup):+ with pytest.raises(ClientError) as exc:+ backup.delete_backup_plan(BackupPlanId="no-such-plan-id")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_backup_update_plan_not_found(backup):+ with pytest.raises(ClientError) as exc:+ backup.update_backup_plan(+ BackupPlanId="no-such-plan-id",+ BackupPlan=_plan_body(f"upd-missing-{_uid()}"),+ )+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_backup_list_plans(backup):+ plan_id = backup.create_backup_plan(BackupPlan=_plan_body(f"listed-{_uid()}"))["BackupPlanId"]+ resp = backup.list_backup_plans()+ ids = [p["BackupPlanId"] for p in resp["BackupPlansList"]]+ assert plan_id in ids+++def test_backup_delete_plan(backup):+ plan_id = backup.create_backup_plan(BackupPlan=_plan_body(f"del-{_uid()}"))["BackupPlanId"]+ backup.delete_backup_plan(BackupPlanId=plan_id)+ with pytest.raises(ClientError) as exc:+ backup.get_backup_plan(BackupPlanId=plan_id)+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++# ---------------------------------------------------------------------------+# Selection tests+# ---------------------------------------------------------------------------++def _make_plan(backup):+ return backup.create_backup_plan(BackupPlan=_plan_body(f"sel-plan-{_uid()}"))["BackupPlanId"]+++def test_backup_create_selection_plan_not_found(backup):+ with pytest.raises(ClientError) as exc:+ backup.create_backup_selection(+ BackupPlanId="no-such-plan-id",+ BackupSelection={+ "SelectionName": "sel-x",+ "IamRoleArn": "arn:aws:iam::000000000000:role/BackupRole",+ },+ )+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_backup_create_selection(backup):+ plan_id = _make_plan(backup)+ resp = backup.create_backup_selection(+ BackupPlanId=plan_id,+ BackupSelection={+ "SelectionName": "sel-1",+ "IamRoleArn": "arn:aws:iam::000000000000:role/BackupRole",+ "Resources": ["arn:aws:dynamodb:us-east-1:000000000000:table/MyTable"],+ },+ )+ assert "SelectionId" in resp+ assert resp["BackupPlanId"] == plan_id+++def test_backup_get_selection(backup):+ plan_id = _make_plan(backup)+ sel_id = backup.create_backup_selection(+ BackupPlanId=plan_id,+ BackupSelection={+ "SelectionName": "sel-get",+ "IamRoleArn": "arn:aws:iam::000000000000:role/BackupRole",+ },+ )["SelectionId"]+ resp = backup.get_backup_selection(BackupPlanId=plan_id, SelectionId=sel_id)+ assert resp["SelectionId"] == sel_id+ assert resp["BackupSelection"]["SelectionName"] == "sel-get"+++def test_backup_list_selections(backup):+ plan_id = _make_plan(backup)+ sel_id = backup.create_backup_selection(+ BackupPlanId=plan_id,+ BackupSelection={+ "SelectionName": "sel-list",+ "IamRoleArn": "arn:aws:iam::000000000000:role/BackupRole",+ },+ )["SelectionId"]+ resp = backup.list_backup_selections(BackupPlanId=plan_id)+ ids = [s["SelectionId"] for s in resp["BackupSelectionsList"]]+ assert sel_id in ids+++def test_backup_list_selections_plan_not_found(backup):+ with pytest.raises(ClientError) as exc:+ backup.list_backup_selections(BackupPlanId="no-such-plan-id")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_backup_get_selection_not_found(backup):+ plan_id = _make_plan(backup)+ with pytest.raises(ClientError) as exc:+ backup.get_backup_selection(BackupPlanId=plan_id, SelectionId="no-such-sel-id")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_backup_delete_selection(backup):+ plan_id = _make_plan(backup)+ sel_id = backup.create_backup_selection(+ BackupPlanId=plan_id,+ BackupSelection={+ "SelectionName": "sel-del",+ "IamRoleArn": "arn:aws:iam::000000000000:role/BackupRole",+ },+ )["SelectionId"]+ backup.delete_backup_selection(BackupPlanId=plan_id, SelectionId=sel_id)+ with pytest.raises(ClientError) as exc:+ backup.get_backup_selection(BackupPlanId=plan_id, SelectionId=sel_id)+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++# ---------------------------------------------------------------------------+# Job tests+# ---------------------------------------------------------------------------++def test_backup_start_job(backup):+ vault_name = f"job-vault-{_uid()}"+ backup.create_backup_vault(BackupVaultName=vault_name)+ resp = backup.start_backup_job(+ BackupVaultName=vault_name,+ ResourceArn="arn:aws:dynamodb:us-east-1:000000000000:table/MyTable",+ IamRoleArn="arn:aws:iam::000000000000:role/BackupRole",+ )+ assert "BackupJobId" in resp+ assert "RecoveryPointArn" in resp+++def test_backup_describe_job(backup):+ vault_name = f"desc-job-vault-{_uid()}"+ backup.create_backup_vault(BackupVaultName=vault_name)+ job_id = backup.start_backup_job(+ BackupVaultName=vault_name,+ ResourceArn="arn:aws:dynamodb:us-east-1:000000000000:table/MyTable",+ IamRoleArn="arn:aws:iam::000000000000:role/BackupRole",+ )["BackupJobId"]+ resp = backup.describe_backup_job(BackupJobId=job_id)+ assert resp["BackupJobId"] == job_id+ assert resp["State"] == "COMPLETED"+ assert resp["BackupVaultName"] == vault_name+++def test_backup_describe_job_not_found(backup):+ with pytest.raises(ClientError) as exc:+ backup.describe_backup_job(BackupJobId="no-such-job-id")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_backup_list_jobs(backup):+ vault_name = f"list-job-vault-{_uid()}"+ backup.create_backup_vault(BackupVaultName=vault_name)+ job_id = backup.start_backup_job(+ BackupVaultName=vault_name,+ ResourceArn="arn:aws:s3:::my-bucket",+ IamRoleArn="arn:aws:iam::000000000000:role/BackupRole",+ )["BackupJobId"]+ resp = backup.list_backup_jobs(ByBackupVaultName=vault_name)+ ids = [j["BackupJobId"] for j in resp["BackupJobs"]]+ assert job_id in ids+++def test_backup_start_job_vault_not_found(backup):+ with pytest.raises(ClientError) as exc:+ backup.start_backup_job(+ BackupVaultName="no-such-vault-xyz",+ ResourceArn="arn:aws:s3:::my-bucket",+ IamRoleArn="arn:aws:iam::000000000000:role/BackupRole",+ )+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_backup_start_job_increments_recovery_point_count(backup):+ vault_name = f"rp-count-vault-{_uid()}"+ backup.create_backup_vault(BackupVaultName=vault_name)+ before = backup.describe_backup_vault(BackupVaultName=vault_name)["NumberOfRecoveryPoints"]+ backup.start_backup_job(+ BackupVaultName=vault_name,+ ResourceArn="arn:aws:dynamodb:us-east-1:000000000000:table/MyTable",+ IamRoleArn="arn:aws:iam::000000000000:role/BackupRole",+ )+ after = backup.describe_backup_vault(BackupVaultName=vault_name)["NumberOfRecoveryPoints"]+ assert after == before + 1+++def test_backup_stop_job_not_found(backup):+ with pytest.raises(ClientError) as exc:+ backup.stop_backup_job(BackupJobId="no-such-job-id")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"++++def test_backup_list_jobs_by_state(backup):+ vault_name = f"state-filter-vault-{_uid()}"+ backup.create_backup_vault(BackupVaultName=vault_name)+ job_id = backup.start_backup_job(+ BackupVaultName=vault_name,+ ResourceArn="arn:aws:s3:::my-bucket",+ IamRoleArn="arn:aws:iam::000000000000:role/BackupRole",+ )["BackupJobId"]+ resp = backup.list_backup_jobs(ByState="COMPLETED")+ ids = [j["BackupJobId"] for j in resp["BackupJobs"]]+ assert job_id in ids+ resp_fail = backup.list_backup_jobs(ByState="FAILED")+ ids_fail = [j["BackupJobId"] for j in resp_fail["BackupJobs"]]+ assert job_id not in ids_fail+++def test_backup_list_jobs_by_resource_arn(backup):+ vault_name = f"res-filter-vault-{_uid()}"+ resource = f"arn:aws:dynamodb:us-east-1:000000000000:table/table-{_uid()}"+ backup.create_backup_vault(BackupVaultName=vault_name)+ job_id = backup.start_backup_job(+ BackupVaultName=vault_name,+ ResourceArn=resource,+ IamRoleArn="arn:aws:iam::000000000000:role/BackupRole",+ )["BackupJobId"]+ resp = backup.list_backup_jobs(ByResourceArn=resource)+ ids = [j["BackupJobId"] for j in resp["BackupJobs"]]+ assert job_id in ids+++def test_backup_stop_job_already_completed(backup):+ vault_name = f"stop-vault-{_uid()}"+ backup.create_backup_vault(BackupVaultName=vault_name)+ job_id = backup.start_backup_job(+ BackupVaultName=vault_name,+ ResourceArn="arn:aws:s3:::my-bucket",+ IamRoleArn="arn:aws:iam::000000000000:role/BackupRole",+ )["BackupJobId"]+ with pytest.raises(ClientError) as exc:+ backup.stop_backup_job(BackupJobId=job_id)+ assert exc.value.response["Error"]["Code"] == "InvalidRequestException"+++# ---------------------------------------------------------------------------+# Tag tests+# ---------------------------------------------------------------------------++def test_backup_tag_vault(backup):+ name = f"tag-vault-{_uid()}"+ backup.create_backup_vault(BackupVaultName=name)+ arn = f"arn:aws:backup:{REGION}:000000000000:backup-vault:{name}"+ backup.tag_resource(ResourceArn=arn, Tags={"Env": "test", "Team": "platform"})+ resp = backup.list_tags(ResourceArn=arn)+ assert resp["Tags"]["Env"] == "test"+ assert resp["Tags"]["Team"] == "platform"+++def test_backup_untag_vault(backup):+ name = f"untag-vault-{_uid()}"+ backup.create_backup_vault(BackupVaultName=name)+ arn = f"arn:aws:backup:{REGION}:000000000000:backup-vault:{name}"+ backup.tag_resource(ResourceArn=arn, Tags={"Env": "test", "Team": "platform"})+ backup.untag_resource(ResourceArn=arn, TagKeyList=["Team"])+ resp = backup.list_tags(ResourceArn=arn)+ assert "Team" not in resp["Tags"]+ assert resp["Tags"]["Env"] == "test"+++def test_backup_tag_plan(backup):+ plan_id = backup.create_backup_plan(BackupPlan=_plan_body(f"tag-plan-{_uid()}"))["BackupPlanId"]+ arn = f"arn:aws:backup:{REGION}:000000000000:backup-plan:{plan_id}"+ backup.tag_resource(ResourceArn=arn, Tags={"Owner": "data-team"})+ resp = backup.list_tags(ResourceArn=arn)+ assert resp["Tags"]["Owner"] == "data-team"+++def test_backup_tag_not_found(backup):+ arn = "arn:aws:backup:us-east-1:000000000000:backup-vault:no-such-vault"+ with pytest.raises(ClientError) as exc:+ backup.tag_resource(ResourceArn=arn, Tags={"k": "v"})+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_backup_untag_resource_not_found(backup):+ arn = "arn:aws:backup:us-east-1:000000000000:backup-vault:no-such-vault"+ with pytest.raises(ClientError) as exc:+ backup.untag_resource(ResourceArn=arn, TagKeyList=["k"])+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_backup_list_tags_not_found(backup):+ arn = "arn:aws:backup:us-east-1:000000000000:backup-vault:no-such-vault"+ with pytest.raises(ClientError) as exc:+ backup.list_tags(ResourceArn=arn)+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_backup_list_tags_empty(backup):+ name = f"empty-tag-vault-{_uid()}"+ backup.create_backup_vault(BackupVaultName=name)+ arn = f"arn:aws:backup:{REGION}:000000000000:backup-vault:{name}"+ resp = backup.list_tags(ResourceArn=arn)+ assert resp["Tags"] == {}