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
#250: Add support for AWS CodeBuild (#253)
Nikhil Adiga853e7cccfdc4
diff --git a/ministack/app.py b/ministack/app.pyindex 5e6ee10e..bdb22771 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -80,6 +80,7 @@ from ministack.services import (cloudfront,servicediscovery,s3files,+ codebuild,)from ministack.services import iam_stsfrom ministack.services.iam_sts import handle_iam_request, handle_sts_request@@ -128,6 +129,7 @@ SERVICE_HANDLERS = {"elasticfilesystem": efs.handle_request,"kms": kms.handle_request,"cloudfront": cloudfront.handle_request,+ "codebuild": codebuild.handle_request,"appsync": appsync.handle_request,"servicediscovery": servicediscovery.handle_request,"s3files": s3files.handle_request,@@ -188,7 +190,7 @@ BANNER = r"""SSM, EventBridge, Kinesis, CloudWatch, SES, SES v2, ACM, WAF v2, Step Functions,ECS, RDS, ElastiCache, Glue, Athena, API Gateway, Firehose, Route53,Cognito, EC2, EMR, EBS, EFS, ALB/ELBv2, CloudFormation, KMS, ECR, CloudFront,- AppSync, Cloud Map, S3 Files, RDS Data API+ AppSync, Cloud Map, S3 Files, RDS Data API, CodeBuild"""@@ -492,7 +494,7 @@ async def app(scope, receive, send):_non_s3_hosts = {"s3", "s3-control", "sqs", "sns", "dynamodb", "lambda", "iam", "sts","secretsmanager", "logs", "ssm", "events", "kinesis","monitoring", "ses", "states", "ecs", "rds", "rds-data", "elasticache",- "glue", "athena", "apigateway", "cloudformation", "autoscaling"}+ "glue", "athena", "apigateway", "cloudformation", "autoscaling", "codebuild"}if bucket not in _non_s3_hosts:vhost_path = "/" + bucket + path if path != "/" else "/" + bucket + "/"try:@@ -624,6 +626,7 @@ async def _handle_lifespan(scope, receive, send):"athena": athena.get_state,"emr": emr.get_state,"cloudfront": cloudfront.get_state,+ "codebuild": codebuild.get_state,"acm": acm.get_state,"firehose": firehose.get_state,"ses": ses.get_state,@@ -784,6 +787,7 @@ def _reset_all_state():(cloudformation, cloudformation.reset),(kms, kms.reset),(cloudfront, cloudfront.reset),+ (codebuild, codebuild.reset),(ecr, ecr.reset),(appsync, appsync.reset),(servicediscovery, servicediscovery.reset),diff --git a/ministack/core/router.py b/ministack/core/router.pyindex 71e8c5f6..d31570c6 100644--- a/ministack/core/router.py+++ b/ministack/core/router.py@@ -162,6 +162,11 @@ SERVICE_PATTERNS = {"host_patterns": [r"cloudfront\."],"credential_scope": "cloudfront",},+ "codebuild": {+ "target_prefixes": ["CodeBuild_20161006"],+ "host_patterns": [r"codebuild\."],+ "credential_scope": "codebuild",+ },"appsync": {"host_patterns": [r"appsync\."],"path_prefixes": ["/v1/apis", "/v1/tags"],@@ -236,6 +241,7 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->"cloudformation": "cloudformation","kms": "kms","cloudfront": "cloudfront",+ "codebuild": "codebuild","appsync": "appsync","servicediscovery": "servicediscovery","s3files": "s3files",diff --git a/ministack/services/codebuild.py b/ministack/services/codebuild.pynew file mode 100644index 00000000..9db3d4c2--- /dev/null+++ b/ministack/services/codebuild.py@@ -0,0 +1,327 @@+"""+CodeBuild Service Emulator.+JSON-based API via X-Amz-Target: CodeBuild_20161006.<Operation>.++Supports:+ Projects: CreateProject, BatchGetProjects, ListProjects,+ UpdateProject, DeleteProject+ Builds: StartBuild, BatchGetBuilds, StopBuild,+ ListBuilds, ListBuildsForProject, BatchDeleteBuilds+"""++import copy+import json+import logging+import os+import time++from ministack.core.persistence import PERSIST_STATE, load_state+from ministack.core.responses import error_response_json, json_response, new_uuid, now_iso++logger = logging.getLogger("codebuild")++ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")+REGION = os.environ.get("MINISTACK_REGION", "us-east-1")++# ---------------------------------------------------------------------------+# In-memory state+# ---------------------------------------------------------------------------+_projects: dict = {} # project_name -> project record+_builds: dict = {} # build_id -> build record+++def reset():+ _projects.clear()+ _builds.clear()+++def get_state():+ return copy.deepcopy({+ "projects": _projects,+ "builds": _builds,+ })+++def restore_state(data):+ _projects.update(data.get("projects", {}))+ _builds.update(data.get("builds", {}))+++_restored = load_state("codebuild")+if _restored:+ restore_state(_restored)+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------++def _project_arn(name):+ return f"arn:aws:codebuild:{REGION}:{ACCOUNT_ID}:project/{name}"+++def _build_arn(build_id):+ return f"arn:aws:codebuild:{REGION}:{ACCOUNT_ID}:build/{build_id}"+++def _build_id(project_name):+ """Generate a build ID like 'project-name:build-uuid'."""+ return f"{project_name}:{new_uuid()}"+++def _make_build_record(project, build_id, source_version=None):+ """Create a build record that immediately shows SUCCEEDED."""+ now = now_iso()+ return {+ "id": build_id,+ "arn": _build_arn(build_id),+ "buildNumber": len([b for b in _builds.values() if b["projectName"] == project["name"]]) + 1,+ "startTime": now,+ "endTime": now,+ "currentPhase": "COMPLETED",+ "buildStatus": "SUCCEEDED",+ "sourceVersion": source_version or project.get("sourceVersion", "refs/heads/main"),+ "projectName": project["name"],+ "phases": [+ {"phaseType": "SUBMITTED", "phaseStatus": "SUCCEEDED", "startTime": now, "endTime": now},+ {"phaseType": "PROVISIONING", "phaseStatus": "SUCCEEDED", "startTime": now, "endTime": now},+ {"phaseType": "DOWNLOAD_SOURCE", "phaseStatus": "SUCCEEDED", "startTime": now, "endTime": now},+ {"phaseType": "INSTALL", "phaseStatus": "SUCCEEDED", "startTime": now, "endTime": now},+ {"phaseType": "PRE_BUILD", "phaseStatus": "SUCCEEDED", "startTime": now, "endTime": now},+ {"phaseType": "BUILD", "phaseStatus": "SUCCEEDED", "startTime": now, "endTime": now},+ {"phaseType": "POST_BUILD", "phaseStatus": "SUCCEEDED", "startTime": now, "endTime": now},+ {"phaseType": "UPLOAD_ARTIFACTS", "phaseStatus": "SUCCEEDED", "startTime": now, "endTime": now},+ {"phaseType": "FINALIZING", "phaseStatus": "SUCCEEDED", "startTime": now, "endTime": now},+ {"phaseType": "COMPLETED", "phaseStatus": "SUCCEEDED", "startTime": now, "endTime": now},+ ],+ "source": project.get("source", {}),+ "artifacts": project.get("artifacts", {"type": "NO_ARTIFACTS"}),+ "environment": project.get("environment", {}),+ "logs": {+ "groupName": f"/aws/codebuild/{project['name']}",+ "streamName": build_id.replace(":", "/"),+ },+ "timeoutInMinutes": project.get("timeoutInMinutes", 60),+ "initiator": f"{ACCOUNT_ID}/user",+ "encryptionKey": f"arn:aws:kms:{REGION}:{ACCOUNT_ID}:alias/aws/codebuild",+ }+++# ---------------------------------------------------------------------------+# Request dispatcher+# ---------------------------------------------------------------------------++async def handle_request(method, path, headers, body, query_params):+ target = headers.get("x-amz-target", "")+ action = target.split(".")[-1] if "." in target else ""++ try:+ data = json.loads(body) if body else {}+ except json.JSONDecodeError:+ return error_response_json("SerializationException", "Invalid JSON", 400)++ handlers = {+ "CreateProject": _create_project,+ "BatchGetProjects": _batch_get_projects,+ "ListProjects": _list_projects,+ "UpdateProject": _update_project,+ "DeleteProject": _delete_project,+ "StartBuild": _start_build,+ "BatchGetBuilds": _batch_get_builds,+ "StopBuild": _stop_build,+ "ListBuilds": _list_builds,+ "ListBuildsForProject": _list_builds_for_project,+ "BatchDeleteBuilds": _batch_delete_builds,+ }++ handler = handlers.get(action)+ if not handler:+ return error_response_json("InvalidAction", f"Unknown action: {action}", 400)+ return handler(data)+++# ---------------------------------------------------------------------------+# Project handlers+# ---------------------------------------------------------------------------++def _create_project(data):+ name = data.get("name", "")+ if not name:+ return error_response_json("InvalidInputException", "Project name is required", 400)+ if name in _projects:+ return error_response_json("ResourceAlreadyExistsException",+ f"Project already exists: {name}", 400)++ now = now_iso()+ project = {+ "name": name,+ "arn": _project_arn(name),+ "description": data.get("description", ""),+ "source": data.get("source", {"type": "NO_SOURCE"}),+ "sourceVersion": data.get("sourceVersion", ""),+ "artifacts": data.get("artifacts", {"type": "NO_ARTIFACTS"}),+ "environment": data.get("environment", {+ "type": "LINUX_CONTAINER",+ "image": "aws/codebuild/standard:7.0",+ "computeType": "BUILD_GENERAL1_SMALL",+ }),+ "serviceRole": data.get("serviceRole",+ f"arn:aws:iam::{ACCOUNT_ID}:role/codebuild-role"),+ "timeoutInMinutes": data.get("timeoutInMinutes", 60),+ "tags": data.get("tags", []),+ "created": now,+ "lastModified": now,+ "encryptionKey": data.get("encryptionKey",+ f"arn:aws:kms:{REGION}:{ACCOUNT_ID}:alias/aws/codebuild"),+ "badge": {"badgeEnabled": False},+ }+ _projects[name] = project+ logger.info("CreateProject: %s", name)+ return json_response({"project": _project_shape(project)})+++def _project_shape(project):+ """Return the project dict in the shape boto3 expects."""+ return {+ "name": project["name"],+ "arn": project["arn"],+ "description": project.get("description", ""),+ "source": project.get("source", {}),+ "sourceVersion": project.get("sourceVersion", ""),+ "artifacts": project.get("artifacts", {}),+ "environment": project.get("environment", {}),+ "serviceRole": project.get("serviceRole", ""),+ "timeoutInMinutes": project.get("timeoutInMinutes", 60),+ "tags": project.get("tags", []),+ "created": project["created"],+ "lastModified": project["lastModified"],+ "encryptionKey": project.get("encryptionKey", ""),+ "badge": project.get("badge", {}),+ }+++def _batch_get_projects(data):+ names = data.get("names", [])+ found = []+ not_found = []+ for name in names:+ project = _projects.get(name)+ if project:+ found.append(_project_shape(project))+ else:+ not_found.append(name)+ return json_response({"projects": found, "projectsNotFound": not_found})+++def _list_projects(data):+ sort_by = data.get("sortBy", "NAME")+ sort_order = data.get("sortOrder", "ASCENDING")+ names = list(_projects.keys())+ if sort_by == "NAME":+ names.sort(reverse=(sort_order == "DESCENDING"))+ elif sort_by == "LAST_MODIFIED_TIME":+ names.sort(key=lambda n: _projects[n].get("lastModified", ""),+ reverse=(sort_order == "DESCENDING"))+ return json_response({"projects": names})+++def _update_project(data):+ name = data.get("name", "")+ if not name or name not in _projects:+ return error_response_json("ResourceNotFoundException",+ f"Project not found: {name}", 400)+ project = _projects[name]+ for key in ("description", "source", "sourceVersion", "artifacts",+ "environment", "serviceRole", "timeoutInMinutes", "tags",+ "encryptionKey"):+ if key in data:+ project[key] = data[key]+ project["lastModified"] = now_iso()+ logger.info("UpdateProject: %s", name)+ return json_response({"project": _project_shape(project)})+++def _delete_project(data):+ name = data.get("name", "")+ if not name or name not in _projects:+ return error_response_json("ResourceNotFoundException",+ f"Project not found: {name}", 400)+ del _projects[name]+ logger.info("DeleteProject: %s", name)+ return json_response({})+++# ---------------------------------------------------------------------------+# Build handlers+# ---------------------------------------------------------------------------++def _start_build(data):+ project_name = data.get("projectName", "")+ if not project_name or project_name not in _projects:+ return error_response_json("ResourceNotFoundException",+ f"Project not found: {project_name}", 400)+ project = _projects[project_name]+ bid = _build_id(project_name)+ build = _make_build_record(project, bid, data.get("sourceVersion"))+ _builds[bid] = build+ logger.info("StartBuild: %s -> %s", project_name, bid)+ return json_response({"build": build})+++def _batch_get_builds(data):+ ids = data.get("ids", [])+ found = []+ not_found = []+ for bid in ids:+ build = _builds.get(bid)+ if build:+ found.append(build)+ else:+ not_found.append(bid)+ return json_response({"builds": found, "buildsNotFound": not_found})+++def _stop_build(data):+ bid = data.get("id", "")+ build = _builds.get(bid)+ if not build:+ return error_response_json("ResourceNotFoundException",+ f"Build not found: {bid}", 400)+ build["buildStatus"] = "STOPPED"+ build["endTime"] = now_iso()+ build["currentPhase"] = "COMPLETED"+ logger.info("StopBuild: %s", bid)+ return json_response({"build": build})+++def _list_builds(data):+ sort_order = data.get("sortOrder", "DESCENDING")+ ids = list(_builds.keys())+ ids.sort(key=lambda bid: _builds[bid].get("startTime", ""),+ reverse=(sort_order == "DESCENDING"))+ return json_response({"ids": ids})+++def _list_builds_for_project(data):+ project_name = data.get("projectName", "")+ if not project_name or project_name not in _projects:+ return error_response_json("ResourceNotFoundException",+ f"Project not found: {project_name}", 400)+ sort_order = data.get("sortOrder", "DESCENDING")+ ids = [bid for bid, b in _builds.items() if b["projectName"] == project_name]+ ids.sort(key=lambda bid: _builds[bid].get("startTime", ""),+ reverse=(sort_order == "DESCENDING"))+ return json_response({"ids": ids})+++def _batch_delete_builds(data):+ ids = data.get("ids", [])+ deleted = []+ not_deleted = []+ for bid in ids:+ if bid in _builds:+ del _builds[bid]+ deleted.append(bid)+ else:+ not_deleted.append(bid)+ return json_response({"buildsDeleted": deleted, "buildsNotDeleted": not_deleted})diff --git a/tests/conftest.py b/tests/conftest.pyindex e7991473..897c5e62 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -270,3 +270,7 @@ def sd():inject_host_prefix=False,),)+[email protected](scope="session")+def codebuild():+ return make_client("codebuild")diff --git a/tests/test_codebuild.py b/tests/test_codebuild.pynew file mode 100644index 00000000..cdaee012--- /dev/null+++ b/tests/test_codebuild.py@@ -0,0 +1,107 @@+import pytest+from botocore.exceptions import ClientError++# ========== CodeBuild ==========++def test_codebuild_create_project(codebuild):+ resp = codebuild.create_project(+ name="test-project",+ source={"type": "NO_SOURCE", "buildspec": "version: 0.2\nphases:\n build:\n commands:\n - echo Hello"},+ artifacts={"type": "NO_ARTIFACTS"},+ environment={+ "type": "LINUX_CONTAINER",+ "image": "aws/codebuild/standard:7.0",+ "computeType": "BUILD_GENERAL1_SMALL",+ },+ serviceRole="arn:aws:iam::000000000000:role/codebuild-role",+ )+ project = resp["project"]+ assert project["name"] == "test-project"+ assert project["arn"].startswith("arn:aws:codebuild:")+ assert "created" in project+++def test_codebuild_create_duplicate_project(codebuild):+ with pytest.raises(ClientError) as exc:+ codebuild.create_project(+ name="test-project",+ source={"type": "NO_SOURCE"},+ artifacts={"type": "NO_ARTIFACTS"},+ environment={"type": "LINUX_CONTAINER", "image": "aws/codebuild/standard:7.0", "computeType": "BUILD_GENERAL1_SMALL"},+ serviceRole="arn:aws:iam::000000000000:role/codebuild-role",+ )+ assert "ResourceAlreadyExistsException" in str(exc.value)+++def test_codebuild_batch_get_projects(codebuild):+ resp = codebuild.batch_get_projects(names=["test-project", "nonexistent"])+ assert len(resp["projects"]) == 1+ assert resp["projects"][0]["name"] == "test-project"+ assert "nonexistent" in resp["projectsNotFound"]+++def test_codebuild_list_projects(codebuild):+ resp = codebuild.list_projects()+ assert "test-project" in resp["projects"]+++def test_codebuild_update_project(codebuild):+ resp = codebuild.update_project(+ name="test-project",+ description="updated description",+ )+ assert resp["project"]["description"] == "updated description"+++def test_codebuild_start_build(codebuild):+ resp = codebuild.start_build(projectName="test-project")+ build = resp["build"]+ assert build["projectName"] == "test-project"+ assert build["buildStatus"] == "SUCCEEDED"+ assert build["arn"].startswith("arn:aws:codebuild:")+ assert "phases" in build+++def test_codebuild_batch_get_builds(codebuild):+ start_resp = codebuild.start_build(projectName="test-project")+ build_id = start_resp["build"]["id"]+ resp = codebuild.batch_get_builds(ids=[build_id, "nonexistent:fake"])+ assert len(resp["builds"]) == 1+ assert resp["builds"][0]["id"] == build_id+ assert "nonexistent:fake" in resp["buildsNotFound"]+++def test_codebuild_list_builds_for_project(codebuild):+ resp = codebuild.list_builds_for_project(projectName="test-project")+ assert len(resp["ids"]) >= 1+++def test_codebuild_list_builds(codebuild):+ resp = codebuild.list_builds()+ assert len(resp["ids"]) >= 1+++def test_codebuild_stop_build(codebuild):+ start_resp = codebuild.start_build(projectName="test-project")+ build_id = start_resp["build"]["id"]+ resp = codebuild.stop_build(id=build_id)+ assert resp["build"]["buildStatus"] == "STOPPED"+++def test_codebuild_batch_delete_builds(codebuild):+ start_resp = codebuild.start_build(projectName="test-project")+ build_id = start_resp["build"]["id"]+ resp = codebuild.batch_delete_builds(ids=[build_id])+ assert build_id in resp["buildsDeleted"]+++def test_codebuild_delete_project(codebuild):+ codebuild.delete_project(name="test-project")+ resp = codebuild.list_projects()+ assert "test-project" not in resp["projects"]+++def test_codebuild_delete_nonexistent_project(codebuild):+ with pytest.raises(ClientError) as exc:+ codebuild.delete_project(name="nonexistent")+ assert "ResourceNotFoundException" in str(exc.value)