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
Add Docker Registry HTTP API V2 to ECR (issue #606) (#608)
Nahuel Nucera9831a7bd5139
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3dd230ea..31e4c46c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,13 @@ Versioning follows [Semantic Versioning](https://semver.org/).---+## [Unreleased]++### Added+- **ECR Docker Registry HTTP API V2 (`docker push` / `docker pull`)** — the registry V2 wire protocol now coexists with the AWS API on the same gateway, matching real ECR's behaviour. Implements `GET /v2/` (version probe), `GET /v2/_catalog`, chunked blob upload (`POST` / `PATCH` / `PUT /v2/<name>/blobs/uploads/[<uuid>]`), single-shot blob upload (`POST /v2/<name>/blobs/uploads/?digest=...`), cross-repo blob mount (`POST /v2/<name>/blobs/uploads/?mount=<digest>&from=<other>`), `HEAD` / `GET` / `DELETE /v2/<name>/blobs/<digest>`, manifest `PUT` / `GET` / `HEAD` / `DELETE /v2/<name>/manifests/<reference>` (tag or digest), and `GET /v2/<name>/tags/list`. Layer bytes and manifest bytes are persisted across warm-boot under `PERSIST_STATE=1`; in-flight upload sessions are deliberately ephemeral (clients retry on 404, matching real registry semantics). A push via `docker push` becomes immediately visible to `aws ecr describe-images`, and tag mutability is honoured. Routing fix bundled: `/v2/<repo>/...` paths previously fell through to S3 path-style addressing and returned `405 Method Not Allowed` to the Docker daemon; the new pre-empt routes them to ECR before generic detection (the `/v2/email...` SES carve-out is preserved). Reported by @LeTrungNguyen1703.++---+## [1.3.33] — 2026-05-09### Addeddiff --git a/ministack/app.py b/ministack/app.pyindex 735b1dbd..d36a6018 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -906,6 +906,36 @@ async def _handle_ses_v2_request(method: str, path: str, headers: dict, body: byreturn await _get_module("ses_v2").handle_request(method, path, headers, body, query_params)+def _is_ecr_registry_path(path: str) -> bool:+ """Return True iff `path` is a Docker Registry HTTP API V2 endpoint.++ Shares the `/v2/` prefix with API Gateway v2 (`/v2/apis/...`,+ `/v2/tags/{arn}`), AppSync Events (`/v2/apis`), and SES v2 (`/v2/email/...`).+ Registry paths are distinguished by `/blobs/`, `/manifests/`, or the+ `/tags/list` suffix — none appear in any other `/v2/*` consumer.+ """+ if path in ("/v2", "/v2/", "/v2/_catalog"):+ return True+ if not path.startswith("/v2/") or path.startswith(_SES_V2_PREFIX):+ return False+ return "/blobs/" in path or "/manifests/" in path or path.endswith("/tags/list")+++async def _handle_ecr_registry_request(method: str, path: str, headers: dict, body: bytes, query_params: dict):+ """Handle Docker Registry HTTP API V2 requests (`docker push`/`docker pull`).++ Real ECR exposes the V2 protocol on the same endpoint as the AWS API. We+ must run this before the generic router so the path doesn't fall through+ to S3 path-style addressing. The shape check above keeps every other+ `/v2/...` consumer (apigwv2, AppSync Events, SES v2) untouched.+ """+ if not _is_ecr_registry_path(path):+ return None+ return await _get_module("ecr").handle_registry_request(+ method, path, headers, body, query_params+ )++def _parse_execute_api_url(host: str, path: str) -> tuple[str, str, str] | None:"""Resolve an execute-api request into (api_id, stage, execute_path).@@ -1115,6 +1145,8 @@ async def _handle_special_data_plane_request(return responseif response := await _handle_ses_v2_request(method, path, headers, body, query_params):return response+ if response := await _handle_ecr_registry_request(method, path, headers, body, query_params):+ return _with_data_plane_headers(response, request_id)host = headers.get("host", "")if response := await _handle_execute_api_request(host, path, method, headers, body, query_params):diff --git a/ministack/services/ecr.py b/ministack/services/ecr.pyindex 16123afb..16b218c7 100644--- a/ministack/services/ecr.py+++ b/ministack/services/ecr.py@@ -29,6 +29,13 @@ _repositories = AccountScopedDict()_images = AccountScopedDict()_lifecycle_policies = AccountScopedDict()_repo_policies = AccountScopedDict()+# Docker Registry HTTP API V2 backing storage.+# _layer_blobs[repo] = {digest: bytes} — finalised layer + config bytes addressable by digest.+# _manifest_blobs[repo] = {digest: bytes} — raw manifest bytes addressable by digest (for HEAD/GET by digest).+# _uploads[repo] = {upload_uuid: bytearray} — in-flight chunked uploads (cleared on PUT).+_layer_blobs = AccountScopedDict()+_manifest_blobs = AccountScopedDict()+_uploads = AccountScopedDict()# ── Persistence ────────────────────────────────────────────@@ -39,6 +46,11 @@ def get_state():"images": copy.deepcopy(_images),"lifecycle_policies": copy.deepcopy(_lifecycle_policies),"repo_policies": copy.deepcopy(_repo_policies),+ "layer_blobs": copy.deepcopy(_layer_blobs),+ "manifest_blobs": copy.deepcopy(_manifest_blobs),+ # _uploads is intentionally NOT persisted — in-flight upload sessions+ # do not survive a restart, matching real registry behaviour where+ # the client retries the upload from scratch after a 404 on PATCH.}@@ -48,6 +60,8 @@ def restore_state(data):_images.update(data.get("images", {}))_lifecycle_policies.update(data.get("lifecycle_policies", {}))_repo_policies.update(data.get("repo_policies", {}))+ _layer_blobs.update(data.get("layer_blobs", {}))+ _manifest_blobs.update(data.get("manifest_blobs", {}))try:@@ -613,3 +627,648 @@ def reset():_images.clear()_lifecycle_policies.clear()_repo_policies.clear()+ _layer_blobs.clear()+ _manifest_blobs.clear()+ _uploads.clear()+++# ──────────────────────────────────────────────────────────────────────────+# Docker Registry HTTP API V2 (RFC: distribution.github.io/distribution/spec/api/)+# Real AWS ECR exposes both the AWS API (CreateRepository, DescribeImages, etc.)+# and the registry V2 protocol from the same hostname. `docker push` and `docker+# pull` speak only V2. The two paths share `_repositories` and `_images` so a+# `docker push foo:latest` becomes visible to `aws ecr describe-images+# --repository-name foo` and vice-versa.+# ──────────────────────────────────────────────────────────────────────────++_REGISTRY_API_VERSION_HEADER = ("Docker-Distribution-API-Version", "registry/2.0")+_DEFAULT_MANIFEST_MEDIA_TYPE = "application/vnd.docker.distribution.manifest.v2+json"+_UPLOAD_PART_SIZE = 10 * 1024 * 1024 # advisory chunk size; clients ignore for chunked uploads+++def _registry_error(status, code, message, detail=None):+ body = {+ "errors": [+ {"code": code, "message": message, "detail": detail if detail is not None else {}}+ ]+ }+ return (+ status,+ {+ "Content-Type": "application/json",+ _REGISTRY_API_VERSION_HEADER[0]: _REGISTRY_API_VERSION_HEADER[1],+ },+ json.dumps(body).encode(),+ )+++def _registry_ok(status, headers, body):+ out = dict(headers or {})+ out.setdefault(_REGISTRY_API_VERSION_HEADER[0], _REGISTRY_API_VERSION_HEADER[1])+ return (status, out, body if body is not None else b"")+++def _content_digest(data: bytes) -> str:+ return "sha256:" + hashlib.sha256(data).hexdigest()+++def _parse_v2_path(path: str):+ """Split a `/v2/...` path into (verb, name, ref).++ Verbs: ``ping``, ``catalog``, ``blob_uploads``, ``blob_upload_session``,+ ``blob``, ``manifest``, ``tags_list``. Returns ``None`` if the path does+ not match a known V2 endpoint shape.++ Repository names may contain slashes (`my/team/svc`), so we locate the+ first occurrence of a registry keyword (``blobs``, ``manifests``, ``tags``)+ and treat everything before it as the name.+ """+ if path in ("/v2", "/v2/"):+ return ("ping", "", "")+ if path == "/v2/_catalog":+ return ("catalog", "", "")+ if not path.startswith("/v2/"):+ return None++ rest = path[len("/v2/"):]+ parts = rest.split("/")+ keyword_idx = None+ for i, p in enumerate(parts):+ if p in ("blobs", "manifests", "tags"):+ keyword_idx = i+ break+ if keyword_idx is None or keyword_idx == 0:+ return None++ name = "/".join(parts[:keyword_idx])+ keyword = parts[keyword_idx]+ tail = parts[keyword_idx + 1:]++ if keyword == "blobs":+ if tail and tail[0] == "uploads":+ # /v2/<name>/blobs/uploads/ → blob_uploads (start)+ # /v2/<name>/blobs/uploads/<uuid> → blob_upload_session+ uuid = "/".join(tail[1:]).rstrip("/")+ if uuid:+ return ("blob_upload_session", name, uuid)+ return ("blob_uploads", name, "")+ # /v2/<name>/blobs/<digest>+ digest = "/".join(tail).rstrip("/")+ if not digest:+ return None+ return ("blob", name, digest)++ if keyword == "manifests":+ ref = "/".join(tail).rstrip("/")+ if not ref:+ return None+ return ("manifest", name, ref)++ if keyword == "tags":+ if tail and tail[0] == "list":+ return ("tags_list", name, "")+ return None++ return None+++def _ensure_repo_exists(name):+ if name in _repositories:+ return None+ return _registry_error(+ 404,+ "NAME_UNKNOWN",+ f"repository name not known to registry: {name}",+ {"name": name},+ )+++def _query_first(query_params, key):+ val = query_params.get(key)+ if isinstance(val, list):+ return val[0] if val else None+ return val+++def _v2_ping():+ return _registry_ok(200, {"Content-Type": "application/json"}, b"{}")+++def _v2_catalog(query_params):+ n_raw = _query_first(query_params, "n")+ try:+ n = int(n_raw) if n_raw is not None else None+ except (TypeError, ValueError):+ n = None+ repos = sorted(_repositories.keys())+ if n is not None and n >= 0:+ repos = repos[:n]+ return _registry_ok(+ 200,+ {"Content-Type": "application/json"},+ json.dumps({"repositories": repos}).encode(),+ )+++def _v2_start_blob_upload(name, query_params, body):+ err = _ensure_repo_exists(name)+ if err is not None:+ return err++ mount = _query_first(query_params, "mount")+ src = _query_first(query_params, "from")+ # Cross-repo blob mount: if the requested digest already exists in `from`,+ # link it into `name` and return 201 immediately. Otherwise fall through+ # to a normal upload session (per the spec).+ if mount:+ src_blobs = _layer_blobs.get(src, {}) if src else {}+ if mount in src_blobs:+ _layer_blobs.setdefault(name, {})[mount] = src_blobs[mount]+ return _registry_ok(+ 201,+ {+ "Location": f"/v2/{name}/blobs/{mount}",+ "Docker-Content-Digest": mount,+ "Content-Length": "0",+ },+ b"",+ )++ # Single-shot upload: POST /v2/<name>/blobs/uploads/?digest=sha256:... with body.+ digest = _query_first(query_params, "digest")+ if digest and body:+ actual = _content_digest(body if isinstance(body, bytes) else body.encode())+ if actual != digest:+ return _registry_error(+ 400,+ "DIGEST_INVALID",+ "provided digest did not match uploaded content",+ {"expected": digest, "actual": actual},+ )+ _layer_blobs.setdefault(name, {})[digest] = bytes(body)+ return _registry_ok(+ 201,+ {+ "Location": f"/v2/{name}/blobs/{digest}",+ "Docker-Content-Digest": digest,+ "Content-Length": "0",+ },+ b"",+ )++ upload_uuid = new_uuid()+ _uploads.setdefault(name, {})[upload_uuid] = bytearray()+ return _registry_ok(+ 202,+ {+ "Location": f"/v2/{name}/blobs/uploads/{upload_uuid}",+ "Range": "0-0",+ "Content-Length": "0",+ "Docker-Upload-UUID": upload_uuid,+ },+ b"",+ )+++def _v2_get_blob_upload(name, upload_uuid):+ err = _ensure_repo_exists(name)+ if err is not None:+ return err+ buf = _uploads.get(name, {}).get(upload_uuid)+ if buf is None:+ return _registry_error(+ 404,+ "BLOB_UPLOAD_UNKNOWN",+ "blob upload unknown to registry",+ {"name": name, "uuid": upload_uuid},+ )+ end = max(0, len(buf) - 1)+ return _registry_ok(+ 204,+ {+ "Location": f"/v2/{name}/blobs/uploads/{upload_uuid}",+ "Range": f"0-{end}",+ "Docker-Upload-UUID": upload_uuid,+ },+ b"",+ )+++def _v2_patch_blob_upload(name, upload_uuid, body):+ err = _ensure_repo_exists(name)+ if err is not None:+ return err+ buf = _uploads.get(name, {}).get(upload_uuid)+ if buf is None:+ return _registry_error(+ 404,+ "BLOB_UPLOAD_UNKNOWN",+ "blob upload unknown to registry",+ {"name": name, "uuid": upload_uuid},+ )+ if body:+ buf.extend(body if isinstance(body, (bytes, bytearray)) else body.encode())+ end = max(0, len(buf) - 1)+ return _registry_ok(+ 202,+ {+ "Location": f"/v2/{name}/blobs/uploads/{upload_uuid}",+ "Range": f"0-{end}",+ "Content-Length": "0",+ "Docker-Upload-UUID": upload_uuid,+ },+ b"",+ )+++def _v2_complete_blob_upload(name, upload_uuid, query_params, body):+ err = _ensure_repo_exists(name)+ if err is not None:+ return err+ digest = _query_first(query_params, "digest")+ if not digest:+ return _registry_error(+ 400, "DIGEST_INVALID", "digest query parameter is required", {}+ )++ buf = _uploads.get(name, {}).get(upload_uuid)+ if buf is None:+ return _registry_error(+ 404,+ "BLOB_UPLOAD_UNKNOWN",+ "blob upload unknown to registry",+ {"name": name, "uuid": upload_uuid},+ )+ # The PUT may carry a final chunk in its body.+ if body:+ buf.extend(body if isinstance(body, (bytes, bytearray)) else body.encode())++ final = bytes(buf)+ actual = _content_digest(final)+ if actual != digest:+ return _registry_error(+ 400,+ "DIGEST_INVALID",+ "uploaded blob digest did not match provided digest",+ {"expected": digest, "actual": actual},+ )++ _layer_blobs.setdefault(name, {})[digest] = final+ _uploads.get(name, {}).pop(upload_uuid, None)++ return _registry_ok(+ 201,+ {+ "Location": f"/v2/{name}/blobs/{digest}",+ "Docker-Content-Digest": digest,+ "Content-Length": "0",+ },+ b"",+ )+++def _v2_cancel_blob_upload(name, upload_uuid):+ err = _ensure_repo_exists(name)+ if err is not None:+ return err+ sessions = _uploads.get(name, {})+ if upload_uuid not in sessions:+ return _registry_error(+ 404,+ "BLOB_UPLOAD_UNKNOWN",+ "blob upload unknown to registry",+ {"name": name, "uuid": upload_uuid},+ )+ sessions.pop(upload_uuid, None)+ return _registry_ok(204, {}, b"")+++def _v2_head_blob(name, digest):+ err = _ensure_repo_exists(name)+ if err is not None:+ return err+ blob = _layer_blobs.get(name, {}).get(digest)+ if blob is None:+ return _registry_error(+ 404,+ "BLOB_UNKNOWN",+ "blob unknown to registry",+ {"digest": digest},+ )+ return _registry_ok(+ 200,+ {+ "Content-Length": str(len(blob)),+ "Docker-Content-Digest": digest,+ "Content-Type": "application/octet-stream",+ },+ b"",+ )+++def _v2_get_blob(name, digest):+ err = _ensure_repo_exists(name)+ if err is not None:+ return err+ blob = _layer_blobs.get(name, {}).get(digest)+ if blob is None:+ return _registry_error(+ 404,+ "BLOB_UNKNOWN",+ "blob unknown to registry",+ {"digest": digest},+ )+ return _registry_ok(+ 200,+ {+ "Content-Length": str(len(blob)),+ "Docker-Content-Digest": digest,+ "Content-Type": "application/octet-stream",+ },+ blob,+ )+++def _v2_delete_blob(name, digest):+ err = _ensure_repo_exists(name)+ if err is not None:+ return err+ blobs = _layer_blobs.get(name, {})+ if digest not in blobs:+ return _registry_error(+ 404,+ "BLOB_UNKNOWN",+ "blob unknown to registry",+ {"digest": digest},+ )+ blobs.pop(digest, None)+ return _registry_ok(202, {}, b"")+++def _resolve_manifest(name, ref):+ """Return (digest, manifest_bytes, media_type) or (None, None, None)."""+ if ref.startswith("sha256:"):+ blob = _manifest_blobs.get(name, {}).get(ref)+ if blob is None:+ return None, None, None+ # Look up the matching image record for media-type accuracy.+ for img in _images.get(name, []):+ if img.get("imageDigest") == ref:+ return ref, blob, img.get("imageManifestMediaType", _DEFAULT_MANIFEST_MEDIA_TYPE)+ return ref, blob, _DEFAULT_MANIFEST_MEDIA_TYPE+ # Tag lookup.+ for img in _images.get(name, []):+ if ref in img.get("imageTags", []):+ digest = img["imageDigest"]+ blob = _manifest_blobs.get(name, {}).get(digest)+ if blob is None:+ # Pre-V2 PutImage path: the manifest was stored as a string.+ manifest_str = img.get("imageManifest", "")+ blob = manifest_str.encode() if isinstance(manifest_str, str) else manifest_str+ return digest, blob, img.get("imageManifestMediaType", _DEFAULT_MANIFEST_MEDIA_TYPE)+ return None, None, None+++def _v2_put_manifest(name, ref, headers, body):+ err = _ensure_repo_exists(name)+ if err is not None:+ return err+ if not body:+ return _registry_error(400, "MANIFEST_INVALID", "manifest body is empty", {})++ raw = body if isinstance(body, bytes) else body.encode()+ digest = _content_digest(raw)+ media_type = headers.get("content-type") or _DEFAULT_MANIFEST_MEDIA_TYPE++ # If `ref` is a tag, validate against repo immutability.+ repo = _repositories[name]+ is_tag_ref = not ref.startswith("sha256:")+ tag = ref if is_tag_ref else None++ if is_tag_ref and repo.get("imageTagMutability") == "IMMUTABLE":+ for img in _images.get(name, []):+ if tag in img.get("imageTags", []) and img.get("imageDigest") != digest:+ return _registry_error(+ 400,+ "TAG_INVALID",+ f"tag '{tag}' is immutable",+ {"tag": tag},+ )++ _manifest_blobs.setdefault(name, {})[digest] = raw++ # Detach the tag from any other image record currently holding it,+ # then attach it (or upsert a fresh record) for this manifest.+ if tag:+ for img in _images.get(name, []):+ tags = img.get("imageTags", [])+ if tag in tags:+ tags.remove(tag)++ existing = next(+ (img for img in _images.get(name, []) if img.get("imageDigest") == digest),+ None,+ )+ if existing:+ if tag:+ existing.setdefault("imageTags", [])+ if tag not in existing["imageTags"]:+ existing["imageTags"].append(tag)+ existing["imageId"]["imageTag"] = tag+ existing["imageManifest"] = raw.decode("utf-8", errors="replace")+ existing["imageManifestMediaType"] = media_type+ else:+ record = {+ "registryId": _registry_id(),+ "repositoryName": name,+ "imageId": {"imageDigest": digest},+ "imageManifest": raw.decode("utf-8", errors="replace"),+ "imageManifestMediaType": media_type,+ "imageTags": [tag] if tag else [],+ "imagePushedAt": int(time.time()),+ "imageDigest": digest,+ "imageSizeInBytes": len(raw),+ }+ if tag:+ record["imageId"]["imageTag"] = tag+ _images.setdefault(name, []).append(record)++ return _registry_ok(+ 201,+ {+ "Location": f"/v2/{name}/manifests/{digest}",+ "Docker-Content-Digest": digest,+ "Content-Length": "0",+ },+ b"",+ )+++def _v2_get_manifest(name, ref):+ err = _ensure_repo_exists(name)+ if err is not None:+ return err+ digest, blob, media_type = _resolve_manifest(name, ref)+ if blob is None:+ return _registry_error(+ 404,+ "MANIFEST_UNKNOWN",+ "manifest unknown to registry",+ {"name": name, "reference": ref},+ )+ return _registry_ok(+ 200,+ {+ "Content-Length": str(len(blob)),+ "Content-Type": media_type,+ "Docker-Content-Digest": digest,+ },+ blob,+ )+++def _v2_head_manifest(name, ref):+ err = _ensure_repo_exists(name)+ if err is not None:+ return err+ digest, blob, media_type = _resolve_manifest(name, ref)+ if blob is None:+ return _registry_error(+ 404,+ "MANIFEST_UNKNOWN",+ "manifest unknown to registry",+ {"name": name, "reference": ref},+ )+ return _registry_ok(+ 200,+ {+ "Content-Length": str(len(blob)),+ "Content-Type": media_type,+ "Docker-Content-Digest": digest,+ },+ b"",+ )+++def _v2_delete_manifest(name, ref):+ err = _ensure_repo_exists(name)+ if err is not None:+ return err+ if not ref.startswith("sha256:"):+ return _registry_error(+ 400,+ "UNSUPPORTED",+ "manifest delete by tag is not supported; delete by digest",+ {"reference": ref},+ )+ digest = ref+ blobs = _manifest_blobs.get(name, {})+ if digest not in blobs:+ return _registry_error(+ 404,+ "MANIFEST_UNKNOWN",+ "manifest unknown to registry",+ {"name": name, "reference": ref},+ )+ blobs.pop(digest, None)+ images = _images.get(name, [])+ _images[name] = [img for img in images if img.get("imageDigest") != digest]+ return _registry_ok(202, {}, b"")+++def _v2_list_tags(name, query_params):+ err = _ensure_repo_exists(name)+ if err is not None:+ return err+ n_raw = _query_first(query_params, "n")+ last = _query_first(query_params, "last")+ tags = sorted(+ {tag for img in _images.get(name, []) for tag in img.get("imageTags", [])}+ )+ if last:+ tags = [t for t in tags if t > last]+ try:+ n = int(n_raw) if n_raw is not None else None+ except (TypeError, ValueError):+ n = None+ if n is not None and n >= 0:+ tags = tags[:n]+ return _registry_ok(+ 200,+ {"Content-Type": "application/json"},+ json.dumps({"name": name, "tags": tags}).encode(),+ )+++async def handle_registry_request(method, path, headers, body, query_params):+ """Entry point for Docker Registry HTTP API V2 requests (`/v2/...`).++ Real ECR serves this protocol from the same hostname as the AWS API.+ `app.py` routes any path beginning with `/v2/` (excluding the SES v2+ `/v2/email` carve-out) here before generic service detection picks it up.+ """+ parsed = _parse_v2_path(path)+ if parsed is None:+ return _registry_error(+ 404,+ "UNSUPPORTED",+ f"path not handled by registry: {path}",+ {"path": path},+ )++ verb, name, ref = parsed+ method = method.upper()+ headers = {k.lower(): v for k, v in (headers or {}).items()}++ if verb == "ping":+ if method not in ("GET", "HEAD"):+ return _registry_error(405, "UNSUPPORTED", "method not allowed", {})+ return _v2_ping()++ if verb == "catalog":+ if method != "GET":+ return _registry_error(405, "UNSUPPORTED", "method not allowed", {})+ return _v2_catalog(query_params)++ if verb == "blob_uploads":+ if method != "POST":+ return _registry_error(405, "UNSUPPORTED", "method not allowed", {})+ return _v2_start_blob_upload(name, query_params, body)++ if verb == "blob_upload_session":+ if method == "PATCH":+ return _v2_patch_blob_upload(name, ref, body)+ if method == "PUT":+ return _v2_complete_blob_upload(name, ref, query_params, body)+ if method == "GET":+ return _v2_get_blob_upload(name, ref)+ if method == "DELETE":+ return _v2_cancel_blob_upload(name, ref)+ return _registry_error(405, "UNSUPPORTED", "method not allowed", {})++ if verb == "blob":+ if method == "HEAD":+ return _v2_head_blob(name, ref)+ if method == "GET":+ return _v2_get_blob(name, ref)+ if method == "DELETE":+ return _v2_delete_blob(name, ref)+ return _registry_error(405, "UNSUPPORTED", "method not allowed", {})++ if verb == "manifest":+ if method == "PUT":+ return _v2_put_manifest(name, ref, headers, body)+ if method == "GET":+ return _v2_get_manifest(name, ref)+ if method == "HEAD":+ return _v2_head_manifest(name, ref)+ if method == "DELETE":+ return _v2_delete_manifest(name, ref)+ return _registry_error(405, "UNSUPPORTED", "method not allowed", {})++ if verb == "tags_list":+ if method != "GET":+ return _registry_error(405, "UNSUPPORTED", "method not allowed", {})+ return _v2_list_tags(name, query_params)++ return _registry_error(404, "UNSUPPORTED", f"unhandled V2 verb: {verb}", {})diff --git a/tests/test_ecr.py b/tests/test_ecr.pyindex 864794e5..7cbfb937 100644--- a/tests/test_ecr.py+++ b/tests/test_ecr.py@@ -1,3 +1,4 @@+import hashlibimport ioimport jsonimport os@@ -6,9 +7,14 @@ import uuid as _uuid_modimport zipfilefrom urllib.parse import urlparse+import boto3import pytest+import requestsfrom botocore.exceptions import ClientError+ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")+REGION = os.environ.get("MINISTACK_REGION", "us-east-1")+def test_ecr_create_repository(ecr):resp = ecr.create_repository(repositoryName="test-app")@@ -178,3 +184,249 @@ def test_ecr_describe_registry(ecr):resp = ecr.describe_registry()assert "registryId" in respassert "replicationConfiguration" in resp+++# ──────────────────────────────────────────────────────────────────────────+# Docker Registry HTTP API V2 — `docker push` / `docker pull` wire protocol.+# Issue #606: paths starting with /v2/ were routing to S3 (which returned 405).+# ──────────────────────────────────────────────────────────────────────────+++def _digest(data: bytes) -> str:+ return "sha256:" + hashlib.sha256(data).hexdigest()+++def test_v2_version_probe():+ r = requests.get(f"{ENDPOINT}/v2/")+ assert r.status_code == 200+ assert r.headers.get("Docker-Distribution-API-Version") == "registry/2.0"+++def test_v2_unknown_repo_returns_404(ecr):+ r = requests.head(+ f"{ENDPOINT}/v2/no-such-repo-{_uuid_mod.uuid4().hex[:8]}/blobs/sha256:" + "0" * 64+ )+ assert r.status_code == 404+++def test_v2_chunked_blob_upload_then_manifest_then_describe_images(ecr):+ repo = "v2-pushflow-" + _uuid_mod.uuid4().hex[:8]+ ecr.create_repository(repositoryName=repo)++ # Two layers — first chunked, second single-shot.+ layer_a = b"layer-a-bytes" * 100+ layer_b = b"layer-b-bytes" * 50+ digest_a = _digest(layer_a)+ digest_b = _digest(layer_b)++ # Chunked upload of layer A.+ r = requests.post(f"{ENDPOINT}/v2/{repo}/blobs/uploads/")+ assert r.status_code == 202, r.text+ upload_url = r.headers["Location"]+ assert upload_url.startswith("/v2/")++ # PATCH first half.+ half = len(layer_a) // 2+ r = requests.patch(f"{ENDPOINT}{upload_url}", data=layer_a[:half])+ assert r.status_code == 202, r.text+ # PATCH second half.+ upload_url = r.headers["Location"]+ r = requests.patch(f"{ENDPOINT}{upload_url}", data=layer_a[half:])+ assert r.status_code == 202++ # PUT to finalise with digest query.+ upload_url = r.headers["Location"]+ r = requests.put(f"{ENDPOINT}{upload_url}", params={"digest": digest_a})+ assert r.status_code == 201, r.text+ assert r.headers["Docker-Content-Digest"] == digest_a++ # Single-shot upload of layer B.+ r = requests.post(+ f"{ENDPOINT}/v2/{repo}/blobs/uploads/",+ params={"digest": digest_b},+ data=layer_b,+ )+ assert r.status_code == 201+ assert r.headers["Docker-Content-Digest"] == digest_b++ # HEAD + GET round-trip layer A bytes.+ r = requests.head(f"{ENDPOINT}/v2/{repo}/blobs/{digest_a}")+ assert r.status_code == 200+ assert r.headers["Docker-Content-Digest"] == digest_a+ assert int(r.headers["Content-Length"]) == len(layer_a)++ r = requests.get(f"{ENDPOINT}/v2/{repo}/blobs/{digest_a}")+ assert r.status_code == 200+ assert r.content == layer_a++ # PUT manifest by tag.+ manifest = json.dumps({+ "schemaVersion": 2,+ "mediaType": "application/vnd.docker.distribution.manifest.v2+json",+ "config": {+ "mediaType": "application/vnd.docker.container.image.v1+json",+ "size": len(layer_b),+ "digest": digest_b,+ },+ "layers": [{+ "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",+ "size": len(layer_a),+ "digest": digest_a,+ }],+ }).encode()+ manifest_digest = _digest(manifest)++ r = requests.put(+ f"{ENDPOINT}/v2/{repo}/manifests/v1.0.0",+ data=manifest,+ headers={"Content-Type": "application/vnd.docker.distribution.manifest.v2+json"},+ )+ assert r.status_code == 201, r.text+ assert r.headers["Docker-Content-Digest"] == manifest_digest++ # GET manifest by tag.+ r = requests.get(f"{ENDPOINT}/v2/{repo}/manifests/v1.0.0")+ assert r.status_code == 200+ assert r.content == manifest+ assert r.headers["Docker-Content-Digest"] == manifest_digest+ assert r.headers["Content-Type"] == (+ "application/vnd.docker.distribution.manifest.v2+json"+ )++ # GET manifest by digest.+ r = requests.get(f"{ENDPOINT}/v2/{repo}/manifests/{manifest_digest}")+ assert r.status_code == 200+ assert r.content == manifest++ # HEAD manifest by tag.+ r = requests.head(f"{ENDPOINT}/v2/{repo}/manifests/v1.0.0")+ assert r.status_code == 200+ assert r.headers["Docker-Content-Digest"] == manifest_digest++ # /v2/<repo>/tags/list returns the tag.+ r = requests.get(f"{ENDPOINT}/v2/{repo}/tags/list")+ assert r.status_code == 200+ body = r.json()+ assert body["name"] == repo+ assert "v1.0.0" in body["tags"]++ # AWS ECR DescribeImages now sees the pushed image.+ desc = ecr.describe_images(repositoryName=repo)+ digests = [img["imageDigest"] for img in desc["imageDetails"]]+ assert manifest_digest in digests+ pushed = next(img for img in desc["imageDetails"] if img["imageDigest"] == manifest_digest)+ assert "v1.0.0" in pushed.get("imageTags", [])+++def test_v2_digest_mismatch_returns_400(ecr):+ repo = "v2-bad-digest-" + _uuid_mod.uuid4().hex[:8]+ ecr.create_repository(repositoryName=repo)++ payload = b"actual-bytes"+ wrong_digest = "sha256:" + "f" * 64++ r = requests.post(f"{ENDPOINT}/v2/{repo}/blobs/uploads/")+ assert r.status_code == 202+ upload_url = r.headers["Location"]+ r = requests.patch(f"{ENDPOINT}{upload_url}", data=payload)+ assert r.status_code == 202+ upload_url = r.headers["Location"]+ r = requests.put(f"{ENDPOINT}{upload_url}", params={"digest": wrong_digest})+ assert r.status_code == 400+ body = r.json()+ assert body["errors"][0]["code"] == "DIGEST_INVALID"+++def test_v2_cross_repo_blob_mount(ecr):+ src = "v2-mount-src-" + _uuid_mod.uuid4().hex[:8]+ dst = "v2-mount-dst-" + _uuid_mod.uuid4().hex[:8]+ ecr.create_repository(repositoryName=src)+ ecr.create_repository(repositoryName=dst)++ layer = b"shared-layer" * 200+ digest = _digest(layer)++ r = requests.post(+ f"{ENDPOINT}/v2/{src}/blobs/uploads/",+ params={"digest": digest},+ data=layer,+ )+ assert r.status_code == 201++ # Mount into dst without re-uploading.+ r = requests.post(+ f"{ENDPOINT}/v2/{dst}/blobs/uploads/",+ params={"mount": digest, "from": src},+ )+ assert r.status_code == 201, r.text+ assert r.headers["Docker-Content-Digest"] == digest++ r = requests.get(f"{ENDPOINT}/v2/{dst}/blobs/{digest}")+ assert r.status_code == 200+ assert r.content == layer+++def test_v2_repo_named_after_a_path_does_not_route_to_s3(ecr):+ """Regression for #606: /v2/<name>/blobs/uploads/ used to hit S3."""+ repo = "review-service-" + _uuid_mod.uuid4().hex[:8]+ ecr.create_repository(repositoryName=repo)++ # The exact request `docker push` makes first.+ r = requests.post(f"{ENDPOINT}/v2/{repo}/blobs/uploads/")+ # Before the fix this was a 405 from S3. Now it is a 202 from ECR.+ assert r.status_code == 202+ assert "Location" in r.headers+ assert r.headers.get("Docker-Distribution-API-Version") == "registry/2.0"+++def test_v2_catalog_lists_repos(ecr):+ name = "v2-catalog-" + _uuid_mod.uuid4().hex[:8]+ ecr.create_repository(repositoryName=name)+ r = requests.get(f"{ENDPOINT}/v2/_catalog")+ assert r.status_code == 200+ assert name in r.json()["repositories"]+++def test_v2_cancel_upload(ecr):+ repo = "v2-cancel-" + _uuid_mod.uuid4().hex[:8]+ ecr.create_repository(repositoryName=repo)+ r = requests.post(f"{ENDPOINT}/v2/{repo}/blobs/uploads/")+ assert r.status_code == 202+ upload_url = r.headers["Location"]+ r = requests.delete(f"{ENDPOINT}{upload_url}")+ assert r.status_code == 204+ # Subsequent PATCH on a cancelled upload must 404.+ r = requests.patch(f"{ENDPOINT}{upload_url}", data=b"after-cancel")+ assert r.status_code == 404+++def test_v2_apis_path_still_routes_to_apigwv2():+ """Regression: `/v2/apis/...` is the API Gateway v2 management API, not ECR.+ Earlier iteration of the registry routing hijacked every `/v2/*` path and+ broke 60+ apigwv2 tests in CI."""+ apigwv2 = boto3.client(+ "apigatewayv2",+ endpoint_url=ENDPOINT,+ region_name=REGION,+ aws_access_key_id="test",+ aws_secret_access_key="test",+ )+ api = apigwv2.create_api(Name="v2-routing-regression-" + _uuid_mod.uuid4().hex[:8], ProtocolType="HTTP")+ assert "ApiId" in api+ apigwv2.delete_api(ApiId=api["ApiId"])+++def test_v2_email_path_still_routes_to_ses(ses):+ """The SES v2 carve-out (`/v2/email/...`) must NOT be hijacked by ECR."""+ # boto3 SES v2 client uses /v2/email/identities under the hood — verify the+ # client still works after our /v2/ → ECR routing change. We just call it;+ # if the route were broken we'd get a 4xx from the ECR registry handler.+ sesv2 = boto3.client(+ "sesv2",+ endpoint_url=ENDPOINT,+ region_name=REGION,+ aws_access_key_id="test",+ aws_secret_access_key="test",+ )+ resp = sesv2.list_email_identities()+ assert "EmailIdentities" in resp