Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

feat(iceberg-rest): Apache Iceberg REST Catalog endpoint (Glue-backed) (#854)

Jonathan Meerson7fce0037193d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ef500f92..adb20501 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,14 @@ All notable changes to MiniStack will be documented here.
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
Versioning follows [Semantic Versioning](https://semver.org/).
+Unreleased
+
+- **Glue — Iceberg REST catalog data plane** — read-path subset of the Apache Iceberg REST OpenAPI spec at `/iceberg/v1/...`, mirroring AWS Glue's `glue.<region>.amazonaws.com/iceberg` endpoint (prefix shape `catalogs/{catalog}`). `GET /v1/config`, ListNamespaces, GetNamespace, ListTables, LoadTable, HEAD TableExists; writes return 501. Glue tables participate when `Parameters["metadata_location"]` points at an Iceberg metadata.json on MiniStack S3 (written by an external engine such as Trino/Spark); the metadata.json is passed through verbatim. Routed by the `glue` SigV4 credential scope — distinct from the S3 Tables Iceberg surface, exactly as on real AWS. Lets DuckDB's `iceberg` extension `ATTACH '<account_id>' (TYPE iceberg, ENDPOINT 'localhost:4566/iceberg', AUTHORIZATION_TYPE 'sigv4')` (requires `USE_SSL=1`; DuckDB hardcodes HTTPS).
+
+---
+- **IAM — `GenerateServiceLastAccessedDetails`, `GetServiceLastAccessedDetails`** — Access Advisor generate→get job handshake. Returns a UUID `JobId`. `GetServiceLastAccessedDetails` returns `JobStatus=COMPLETED` and an empty `ServicesLastAccessed` list (no CloudTrail data).
+
+
---
## [1.3.61] — 2026-06-10
diff --git a/README.md b/README.md
index b14dec51..7eb45298 100644
--- a/README.md
+++ b/README.md
@@ -499,7 +499,7 @@ Unsupported resource types fail with `CREATE_FAILED` (or `ROLLBACK_COMPLETE` if
| **ECS** | CreateCluster, DeleteCluster, DescribeClusters, ListClusters, UpdateCluster, UpdateClusterSettings, PutClusterCapacityProviders, RegisterTaskDefinition, DeregisterTaskDefinition, DescribeTaskDefinition, ListTaskDefinitions, ListTaskDefinitionFamilies, DeleteTaskDefinitions, CreateService, DeleteService, DescribeServices, UpdateService, ListServices, ListServicesByNamespace, RunTask, StopTask, DescribeTasks, ListTasks, ExecuteCommand, UpdateTaskProtection, GetTaskProtection, CreateCapacityProvider, UpdateCapacityProvider, DeleteCapacityProvider, DescribeCapacityProviders, TagResource, UntagResource, ListTagsForResource, ListAccountSettings, PutAccountSetting, PutAccountSettingDefault, DeleteAccountSetting, PutAttributes, DeleteAttributes, ListAttributes, DescribeServiceDeployments, ListServiceDeployments, DescribeServiceRevisions, SubmitTaskStateChange, SubmitContainerStateChange, SubmitAttachmentStateChanges, DiscoverPollEndpoint | 47 actions; `RunTask` starts real Docker containers via Docker socket; full Terraform ECS coverage |
| **RDS** | CreateDBInstance, DeleteDBInstance, DescribeDBInstances, ModifyDBInstance, StartDBInstance, StopDBInstance, RebootDBInstance, CreateDBInstanceReadReplica, RestoreDBInstanceFromDBSnapshot, CreateDBCluster, DeleteDBCluster, DescribeDBClusters, ModifyDBCluster, StartDBCluster, StopDBCluster, CreateDBSnapshot, DeleteDBSnapshot, DescribeDBSnapshots, CreateDBClusterSnapshot, DescribeDBClusterSnapshots, DeleteDBClusterSnapshot, CreateDBSubnetGroup, DeleteDBSubnetGroup, DescribeDBSubnetGroups, ModifyDBSubnetGroup, CreateDBParameterGroup, DeleteDBParameterGroup, DescribeDBParameterGroups, DescribeDBParameters, ModifyDBParameterGroup, CreateDBClusterParameterGroup, DescribeDBClusterParameterGroups, DeleteDBClusterParameterGroup, DescribeDBClusterParameters, ModifyDBClusterParameterGroup, CreateOptionGroup, DeleteOptionGroup, DescribeOptionGroups, DescribeOptionGroupOptions, ListTagsForResource, AddTagsToResource, RemoveTagsFromResource, DescribeDBEngineVersions, DescribeOrderableDBInstanceOptions, CreateGlobalCluster, DescribeGlobalClusters, DeleteGlobalCluster, RemoveFromGlobalCluster, ModifyGlobalCluster | `CreateDBInstance` spins up real Postgres/MySQL Docker container, returns actual `host:port` endpoint |
| **ElastiCache** | CreateCacheCluster, DeleteCacheCluster, DescribeCacheClusters, ModifyCacheCluster, RebootCacheCluster, CreateReplicationGroup, DeleteReplicationGroup, DescribeReplicationGroups, ModifyReplicationGroup, IncreaseReplicaCount, DecreaseReplicaCount, CreateCacheSubnetGroup, DescribeCacheSubnetGroups, ModifyCacheSubnetGroup, DeleteCacheSubnetGroup, CreateCacheParameterGroup, DescribeCacheParameterGroups, ModifyCacheParameterGroup, ResetCacheParameterGroup, DeleteCacheParameterGroup, DescribeCacheParameters, DescribeCacheEngineVersions, CreateUser, DescribeUsers, DeleteUser, ModifyUser, CreateUserGroup, DescribeUserGroups, DeleteUserGroup, ModifyUserGroup, ListTagsForResource, AddTagsToResource, RemoveTagsFromResource, CreateSnapshot, DeleteSnapshot, DescribeSnapshots, DescribeEvents | `CreateCacheCluster` spins up real Redis/Memcached Docker container |
-| **Glue** | CreateDatabase, DeleteDatabase, GetDatabase, GetDatabases, UpdateDatabase, CreateTable, DeleteTable, GetTable, GetTables, UpdateTable, BatchDeleteTable, CreatePartition, DeletePartition, GetPartition, GetPartitions, BatchCreatePartition, BatchGetPartition, CreatePartitionIndex, GetPartitionIndexes, CreateConnection, DeleteConnection, GetConnection, GetConnections, CreateCrawler, DeleteCrawler, GetCrawler, GetCrawlers, UpdateCrawler, StartCrawler, StopCrawler, GetCrawlerMetrics, CreateJob, DeleteJob, GetJob, GetJobs, UpdateJob, StartJobRun, GetJobRun, GetJobRuns, BatchStopJobRun, CreateTrigger, GetTrigger, DeleteTrigger, UpdateTrigger, StartTrigger, StopTrigger, ListTriggers, BatchGetTriggers, GetTriggers, CreateWorkflow, GetWorkflow, DeleteWorkflow, UpdateWorkflow, StartWorkflowRun, CreateUserDefinedFunction, UpdateUserDefinedFunction, DeleteUserDefinedFunction, GetUserDefinedFunction, GetUserDefinedFunctions, CreateSecurityConfiguration, DeleteSecurityConfiguration, GetSecurityConfiguration, GetSecurityConfigurations, CreateClassifier, GetClassifier, GetClassifiers, DeleteClassifier, TagResource, UntagResource, GetTags | Python shell jobs actually execute via subprocess; Spark jobs run on the official `amazon/aws-glue-libs` PySpark image (`GlueVersion: 4.0` / `3.0`) on MiniStack's Docker network |
+| **Glue** | CreateDatabase, DeleteDatabase, GetDatabase, GetDatabases, UpdateDatabase, CreateTable, DeleteTable, GetTable, GetTables, UpdateTable, BatchDeleteTable, CreatePartition, DeletePartition, GetPartition, GetPartitions, BatchCreatePartition, BatchGetPartition, CreatePartitionIndex, GetPartitionIndexes, CreateConnection, DeleteConnection, GetConnection, GetConnections, CreateCrawler, DeleteCrawler, GetCrawler, GetCrawlers, UpdateCrawler, StartCrawler, StopCrawler, GetCrawlerMetrics, CreateJob, DeleteJob, GetJob, GetJobs, UpdateJob, StartJobRun, GetJobRun, GetJobRuns, BatchStopJobRun, CreateTrigger, GetTrigger, DeleteTrigger, UpdateTrigger, StartTrigger, StopTrigger, ListTriggers, BatchGetTriggers, GetTriggers, CreateWorkflow, GetWorkflow, DeleteWorkflow, UpdateWorkflow, StartWorkflowRun, CreateUserDefinedFunction, UpdateUserDefinedFunction, DeleteUserDefinedFunction, GetUserDefinedFunction, GetUserDefinedFunctions, CreateSecurityConfiguration, DeleteSecurityConfiguration, GetSecurityConfiguration, GetSecurityConfigurations, CreateClassifier, GetClassifier, GetClassifiers, DeleteClassifier, TagResource, UntagResource, GetTags | Python shell jobs actually execute via subprocess; Spark jobs run on the official `amazon/aws-glue-libs` PySpark image (`GlueVersion: 4.0` / `3.0`) on MiniStack's Docker network; Glue-backed Iceberg REST catalog at `/iceberg` (signed with the `glue` credential scope, prefix `catalogs/{catalog}`) — read path for tables whose `metadata_location` parameter points at a metadata.json on MiniStack S3, e.g. DuckDB `ATTACH ... (TYPE iceberg, ENDPOINT 'localhost:4566/iceberg', AUTHORIZATION_TYPE 'sigv4')` with `USE_SSL=1` |
| **S3 Tables** | CreateTableBucket, ListTableBuckets, GetTableBucket, DeleteTableBucket, CreateNamespace, ListNamespaces, GetNamespace, DeleteNamespace, CreateTable, ListTables, GetTable, DeleteTable, GetTableMetadataLocation, UpdateTableMetadataLocation | Iceberg-format tables; embedded Iceberg REST catalog at `/iceberg` so Spark jobs (`spark.sql.catalog.*.type=rest`) can create / load / commit without an external catalog; data files in S3, metadata in memory |
| **Athena** | StartQueryExecution, GetQueryExecution, GetQueryResults, StopQueryExecution, ListQueryExecutions, BatchGetQueryExecution, CreateWorkGroup, DeleteWorkGroup, GetWorkGroup, ListWorkGroups, UpdateWorkGroup, CreateNamedQuery, DeleteNamedQuery, GetNamedQuery, ListNamedQueries, BatchGetNamedQuery, CreateDataCatalog, GetDataCatalog, ListDataCatalogs, DeleteDataCatalog, UpdateDataCatalog, CreatePreparedStatement, GetPreparedStatement, DeletePreparedStatement, ListPreparedStatements, GetTableMetadata, ListTableMetadata, TagResource, UntagResource, ListTagsForResource | Real SQL via **DuckDB** when installed (`pip install duckdb`), otherwise returns mock results; result pagination; column type metadata |
| **Firehose** | CreateDeliveryStream, DeleteDeliveryStream, DescribeDeliveryStream, ListDeliveryStreams, PutRecord, PutRecordBatch, UpdateDestination, TagDeliveryStream, UntagDeliveryStream, ListTagsForDeliveryStream, StartDeliveryStreamEncryption, StopDeliveryStreamEncryption | S3 destinations write records to the local S3 emulator; all other destination types buffer in-memory; concurrency-safe `UpdateDestination` via `VersionId`; `DeliveryStreamType=KinesisStreamAsSource` consumes records from the source Kinesis stream on `PutRecord` / `PutRecords` and forwards them to the configured S3 destination, honoring `Prefix` and `DeliveryStartTimestamp`; `ProcessingConfiguration.Processors[].Type=Lambda` invoked per-batch with the AWS-shape event (`{invocationId, deliveryStreamArn, region, records:[{recordId, approximateArrivalTimestamp, data}]}`) — `Ok` records ship the transformed data downstream, `Dropped`/`ProcessingFailed` are omitted, Lambda failures pass records through unchanged (best-effort per AWS) |
diff --git a/ministack/services/glue.py b/ministack/services/glue.py
index 8f70ccf3..b5ad2a8b 100644
--- a/ministack/services/glue.py
+++ b/ministack/services/glue.py
@@ -21,6 +21,7 @@ import subprocess
import tempfile
import threading
import time
+from urllib.parse import unquote
from ministack.core.persistence import PERSIST_STATE, load_state
from ministack.core.responses import (
@@ -157,6 +158,15 @@ def _arn(resource_type, name):
async def handle_request(method, path, headers, body, query_params):
+ # Glue's Iceberg REST catalog data plane. On real AWS this is
+ # `glue.<region>.amazonaws.com/iceberg` — same service, same SigV4
+ # signing name (`glue`), different protocol (Iceberg REST OpenAPI
+ # instead of X-Amz-Target JSON RPC). The router's credential-scope
+ # dispatch already lands `glue`-signed requests here, so a plain
+ # path check is all that's needed to tell the two protocols apart.
+ if path.startswith("/iceberg"):
+ return _handle_iceberg_rest(method, path, query_params)
+
target = headers.get("x-amz-target", "")
action = target.split(".")[-1] if "." in target else ""
@@ -258,6 +268,208 @@ async def handle_request(method, path, headers, body, query_params):
return handler(data)
+# ---- Iceberg REST catalog (Glue data plane) ----
+#
+# Read-path subset of the Apache Iceberg REST Catalog OpenAPI spec, mirroring
+# AWS Glue's `glue.<region>.amazonaws.com/iceberg` endpoint so that clients
+# like DuckDB's `iceberg` extension can ATTACH:
+#
+# ATTACH '000000000000' AS glue_catalog (
+# TYPE iceberg,
+# ENDPOINT 'localhost:4566/iceberg',
+# AUTHORIZATION_TYPE 'sigv4'
+# );
+#
+# Glue's prefix shape is `/v1/catalogs/{catalog}/...` (returned to the client
+# as `defaults.prefix` from /v1/config). This is distinct from the S3 Tables
+# Iceberg REST endpoint served by `services/s3tables.py`, whose prefix is a
+# URL-encoded table-bucket ARN — on AWS those are two separate services told
+# apart by SigV4 signing name, and MiniStack routes them the same way.
+#
+# A table participates in this surface iff its `Parameters["metadata_location"]`
+# points at an Iceberg metadata.json on MiniStack's S3 (written there by an
+# external engine such as Trino/Spark, then registered in Glue). The
+# metadata.json is passed through verbatim — format versions change and we
+# don't want to be in the parsing business. Write paths return 501.
+#
+# Responses use plain `application/json` and the spec's
+# `{"error": {"message", "type", "code"}}` envelope — NOT the AWS
+# x-amz-json-1.0 flavor the rest of this module speaks.
+
+_iceberg_tls_hint_logged = False
+
+
+def _iceberg_json(data, status=200):
+ body = json.dumps(data, ensure_ascii=False).encode("utf-8")
+ return status, {"Content-Type": "application/json"}, body
+
+
+def _iceberg_error(message, error_type, status):
+ return _iceberg_json(
+ {"error": {"message": message, "type": error_type, "code": status}},
+ status=status,
+ )
+
+
+def _iceberg_s3_overrides():
+ """S3 client config handed to Iceberg REST clients.
+
+ Real AWS Glue returns no overrides (clients use ambient AWS creds);
+ MiniStack must return them or the client tries real S3 for the data
+ files referenced by the catalog and fails.
+
+ Credentials are the fixed `test`/`test` pair (same as the s3tables
+ Iceberg surface) — MiniStack's S3 doesn't verify signatures, and
+ echoing ambient AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY into an HTTP
+ response would leak real credentials from the host environment."""
+ host = os.environ.get("MINISTACK_HOST", "localhost")
+ port = os.environ.get("GATEWAY_PORT", "4566")
+ return {
+ "s3.endpoint": f"http://{host}:{port}",
+ "s3.access-key-id": "test",
+ "s3.secret-access-key": "test",
+ "s3.path-style-access": "true",
+ "s3.region": os.environ.get("MINISTACK_REGION", "us-east-1"),
+ }
+
+
+def _iceberg_fetch_metadata(metadata_location):
+ """Read the metadata.json at an ``s3://bucket/key`` URI from MiniStack's
+ S3 and return it parsed, or None if the URI is malformed, the object is
+ missing, or the body isn't valid JSON."""
+ if not metadata_location or not metadata_location.startswith("s3://"):
+ return None
+ rest = metadata_location[len("s3://"):]
+ if "/" not in rest:
+ return None
+ bucket, key = rest.split("/", 1)
+ if not bucket or not key:
+ return None
+ from ministack.services import s3 as _s3
+ data = _s3._get_object_data(bucket, key)
+ if data is None:
+ return None
+ try:
+ return json.loads(data.decode("utf-8"))
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
+ logger.warning("Iceberg metadata.json at %s did not parse: %s",
+ metadata_location, exc)
+ return None
+
+
+def _iceberg_table_entry(db_name, table_name):
+ """Return the Glue table dict if it exists AND is an Iceberg table
+ (has a `metadata_location` parameter), else None."""
+ table = _tables.get(f"{db_name}/{table_name}")
+ if table is None:
+ return None
+ if not (table.get("Parameters") or {}).get("metadata_location"):
+ return None
+ return table
+
+
+def _iceberg_load_table(db_name, table_name):
+ table = _iceberg_table_entry(db_name, table_name)
+ if table is None:
+ return _iceberg_error(
+ f"Table does not exist: {db_name}.{table_name}",
+ "NoSuchTableException", 404)
+ metadata_location = table["Parameters"]["metadata_location"]
+ # Missing/unparseable metadata.json is a 404, not a 200 with empty
+ # metadata — DuckDB would treat the latter as a real-but-empty table
+ # and silently return wrong query results.
+ metadata = _iceberg_fetch_metadata(metadata_location)
+ if metadata is None:
+ return _iceberg_error(
+ f"Table metadata not readable: {db_name}.{table_name} "
+ f"(metadata_location={metadata_location})",
+ "NoSuchTableException", 404)
+ return _iceberg_json({
+ "metadata-location": metadata_location,
+ "metadata": metadata,
+ "config": _iceberg_s3_overrides(),
+ })
+
+
+def _iceberg_maybe_log_tls_hint():
+ """Warn once if USE_SSL isn't on — DuckDB hardcodes https:// on the
+ Iceberg endpoint and fails at connect time with no useful message."""
+ global _iceberg_tls_hint_logged
+ if _iceberg_tls_hint_logged:
+ return
+ _iceberg_tls_hint_logged = True
+ if os.environ.get("USE_SSL", "").strip().lower() not in ("1", "true", "yes"):
+ logger.warning(
+ "Glue Iceberg REST endpoint hit while USE_SSL is not enabled. "
+ "DuckDB's iceberg extension hardcodes https:// and will fail to "
+ "connect. Set USE_SSL=1 and trust MiniStack's self-signed cert "
+ "(SSL_CERT_FILE / DuckDB ca_cert_file) for ATTACH to work."
+ )
+
+
+def _handle_iceberg_rest(method, path, query_params):
+ _iceberg_maybe_log_tls_hint()
+ parts = [unquote(p) for p in path.strip("/").split("/") if p]
+ # parts: ["iceberg", "v1", ...]
+ if len(parts) < 3 or parts[0] != "iceberg" or parts[1] != "v1":
+ return _iceberg_error(f"Unknown Iceberg REST path: {path}",
+ "NotFoundException", 404)
+
+ # GET /iceberg/v1/config?warehouse=<id> — called once on ATTACH. The
+ # prefix tells the client to build subsequent URLs as
+ # /v1/catalogs/{warehouse}/... — Glue's prefix shape.
+ if parts[2] == "config" and len(parts) == 3 and method == "GET":
+ warehouse = query_params.get("warehouse", "")
+ if isinstance(warehouse, list):
+ warehouse = warehouse[0] if warehouse else ""
+ defaults = {"prefix": f"catalogs/{warehouse}"} if warehouse else {}
+ return _iceberg_json({"defaults": defaults,
+ "overrides": _iceberg_s3_overrides()})
+
+ # Everything else: /v1/catalogs/{catalog}/namespaces[/{ns}[/tables[/{tbl}]]]
+ # The catalog id is accepted but not validated — MiniStack is
+ # single-catalog per account, scoping happens via the SigV4 account id.
+ if len(parts) < 5 or parts[2] != "catalogs" or parts[4] != "namespaces":
+ return _iceberg_error(
+ f"Operation not supported: {method} {path}",
+ "UnsupportedOperationException", 501)
+
+ if len(parts) == 5 and method == "GET": # ListNamespaces
+ return _iceberg_json(
+ {"namespaces": [[name] for name in sorted(_databases.keys())]})
+
+ if len(parts) == 6 and method == "GET": # GetNamespace
+ ns = parts[5]
+ if ns not in _databases:
+ return _iceberg_error(f"Namespace does not exist: {ns}",
+ "NoSuchNamespaceException", 404)
+ return _iceberg_json({"namespace": [ns], "properties": {}})
+
+ if len(parts) >= 7 and parts[6] == "tables":
+ ns = parts[5]
+ if len(parts) == 7 and method == "GET": # ListTables
+ if ns not in _databases:
+ return _iceberg_error(f"Namespace does not exist: {ns}",
+ "NoSuchNamespaceException", 404)
+ prefix = f"{ns}/"
+ names = sorted(
+ t["Name"] for k, t in _tables.items()
+ if k.startswith(prefix)
+ and (t.get("Parameters") or {}).get("metadata_location"))
+ return _iceberg_json(
+ {"identifiers": [{"namespace": [ns], "name": n} for n in names]})
+ if len(parts) == 8:
+ if method == "GET": # LoadTable — the hot path
+ return _iceberg_load_table(ns, parts[7])
+ if method == "HEAD": # TableExists
+ exists = _iceberg_table_entry(ns, parts[7]) is not None
+ return (200 if exists else 404), {}, b""
+
+ return _iceberg_error(
+ f"Operation not supported: {method} {path}",
+ "UnsupportedOperationException", 501)
+
+
# ---- Databases ----
def _create_database(data):
diff --git a/tests/test_glue_iceberg_rest.py b/tests/test_glue_iceberg_rest.py
new file mode 100644
index 00000000..3403d318
--- /dev/null
+++ b/tests/test_glue_iceberg_rest.py
@@ -0,0 +1,321 @@
+"""Unit tests for Glue's Iceberg REST catalog data plane (services/glue.py).
+
+Mirrors AWS Glue's `glue.<region>.amazonaws.com/iceberg` endpoint: prefix
+shape `/v1/catalogs/{catalog}/...`, told apart from the S3 Tables Iceberg
+REST endpoint (services/s3tables.py) by SigV4 signing name — exactly how
+the two separate services are distinguished on real AWS.
+
+These exercise `glue.handle_request` directly with seeded state, without a
+running server — the same direct-handler pattern as test_ecs_metadata.py.
+"""
+
+import asyncio
+import importlib
+import json
+
+import pytest
+
+import ministack.core.responses as _responses
+from ministack.core.router import detect_service
+
+
+def _svc(name):
+ """Resolve a service module through sys.modules at call time.
+
+ NOT a module-level `from ministack.services import glue, s3` — the
+ persistence regression tests cold-reimport service modules
+ (`sys.modules.pop` + fresh import), so an import-time binding here can
+ end up pointing at a stale module object while glue.py's own lazy
+ `from ministack.services import s3` resolves the fresh one. State
+ seeded on the stale object is then invisible to production code (the
+ exact failure mode this replaced: 404 where 200 was expected, only
+ when test_persistence.py ran first in the same worker)."""
+ return importlib.import_module(f"ministack.services.{name}")
+
+
+def _call(method, path, query_params=None):
+ status, headers, body = asyncio.run(
+ _svc("glue").handle_request(method, path, {}, b"", query_params or {})
+ )
+ payload = json.loads(body) if body else None
+ return status, headers, payload
+
+
[email protected](autouse=True)
+def _reset():
+ # Pin the per-request account so AccountScopedDict lookups land in the
+ # same bucket whether the caller is the test or production code.
+ _responses._request_account_id.set("000000000000")
+ _responses._request_region.set("us-east-1")
+ _svc("glue").reset()
+ _svc("s3")._buckets.clear()
+ yield
+ _svc("glue").reset()
+ _svc("s3")._buckets.clear()
+
+
+# ── Routing ──────────────────────────────────────────────────
+
+
+def test_glue_signed_iceberg_request_routes_to_glue_service():
+ """DuckDB signs Iceberg REST requests with the `glue` credential scope.
+ The router's existing scope dispatch must land them on the glue module —
+ no path-based special case required."""
+ headers = {
+ "authorization": (
+ "AWS4-HMAC-SHA256 Credential=test/20260610/us-east-1/glue/aws4_request, "
+ "SignedHeaders=host, Signature=abc"
+ )
+ }
+ assert detect_service("GET", "/iceberg/v1/config", headers, {}) == "glue"
+
+
+def test_s3tables_signed_iceberg_request_still_routes_to_s3tables():
+ """The S3 Tables Iceberg REST surface is a distinct AWS service; signing
+ as `s3tables` must keep landing on services/s3tables.py."""
+ headers = {
+ "authorization": (
+ "AWS4-HMAC-SHA256 Credential=test/20260610/us-east-1/s3tables/aws4_request, "
+ "SignedHeaders=host, Signature=abc"
+ )
+ }
+ assert detect_service("GET", "/iceberg/v1/config", headers, {}) == "s3tables"
+
+
+# ── /iceberg/v1/config ───────────────────────────────────────
+
+
+def test_config_returns_glue_catalogs_prefix_and_s3_overrides():
+ status, headers, payload = _call(
+ "GET", "/iceberg/v1/config", {"warehouse": ["000000000000"]}
+ )
+ assert status == 200
+ assert headers["Content-Type"] == "application/json"
+ # Glue's prefix shape — subsequent client URLs become
+ # /iceberg/v1/catalogs/000000000000/namespaces/...
+ assert payload["defaults"]["prefix"] == "catalogs/000000000000"
+ overrides = payload["overrides"]
+ assert overrides["s3.endpoint"].startswith("http://")
+ assert overrides["s3.path-style-access"] == "true"
+ assert "s3.region" in overrides
+ # Fixed creds, never echoed from the host env — emitting ambient
+ # AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY into a response body would
+ # leak real credentials from a developer's shell.
+ assert overrides["s3.access-key-id"] == "test"
+ assert overrides["s3.secret-access-key"] == "test"
+
+
+def test_config_without_warehouse_returns_empty_defaults():
+ _, _, payload = _call("GET", "/iceberg/v1/config")
+ assert payload["defaults"] == {}
+ assert "overrides" in payload
+
+
+# ── Namespaces ───────────────────────────────────────────────
+
+
+def test_list_namespaces_returns_glue_databases():
+ _svc("glue")._databases["db_a"] = {"Name": "db_a"}
+ _svc("glue")._databases["db_b"] = {"Name": "db_b"}
+ _, _, payload = _call("GET", "/iceberg/v1/catalogs/000000000000/namespaces")
+ assert payload["namespaces"] == [["db_a"], ["db_b"]]
+
+
+def test_get_namespace_404s_when_database_missing():
+ status, _, payload = _call(
+ "GET", "/iceberg/v1/catalogs/000000000000/namespaces/nope"
+ )
+ assert status == 404
+ assert payload["error"]["type"] == "NoSuchNamespaceException"
+
+
+def test_get_namespace_returns_shape_when_database_exists():
+ _svc("glue")._databases["db"] = {"Name": "db"}
+ status, _, payload = _call(
+ "GET", "/iceberg/v1/catalogs/000000000000/namespaces/db"
+ )
+ assert status == 200
+ assert payload == {"namespace": ["db"], "properties": {}}
+
+
+# ── ListTables ───────────────────────────────────────────────
+
+
+def test_list_tables_404s_when_namespace_missing():
+ """Real Iceberg REST returns NoSuchNamespaceException for ListTables on
+ an unknown namespace — not an empty 200 list."""
+ status, _, payload = _call(
+ "GET", "/iceberg/v1/catalogs/000000000000/namespaces/nope/tables"
+ )
+ assert status == 404
+ assert payload["error"]["type"] == "NoSuchNamespaceException"
+
+
+def test_list_tables_hides_non_iceberg_glue_tables():
+ """A Glue table without `Parameters['metadata_location']` is a plain
+ Hive/CSV/Parquet table and must not appear on the Iceberg surface."""
+ _svc("glue")._databases["db"] = {"Name": "db"}
+ _svc("glue")._tables["db/iceberg_table"] = {
+ "Name": "iceberg_table",
+ "DatabaseName": "db",
+ "Parameters": {"metadata_location": "s3://lake/t/metadata/v0.metadata.json"},
+ }
+ _svc("glue")._tables["db/csv_table"] = {
+ "Name": "csv_table", "DatabaseName": "db", "Parameters": {},
+ }
+ _, _, payload = _call(
+ "GET", "/iceberg/v1/catalogs/000000000000/namespaces/db/tables"
+ )
+ assert [t["name"] for t in payload["identifiers"]] == ["iceberg_table"]
+ assert payload["identifiers"][0]["namespace"] == ["db"]
+
+
+# ── LoadTable hot path ───────────────────────────────────────
+
+
+_META_JSON = {
+ "format-version": 2,
+ "table-uuid": "11111111-2222-3333-4444-555555555555",
+ "location": "s3://lake/dim_application",
+ "schemas": [{"schema-id": 0, "type": "struct", "fields": []}],
+ "current-schema-id": 0,
+ "current-snapshot-id": 42,
+ "properties": {},
+}
+
+
+def _seed_glue_table_with_metadata():
+ key = "dim_application/metadata/00003-deadbeef.metadata.json"
+ _svc("s3")._buckets["lake"] = {"objects": {key: {"body": json.dumps(_META_JSON).encode()}}}
+ _svc("glue")._databases["db"] = {"Name": "db"}
+ _svc("glue")._tables["db/dim_application"] = {
+ "Name": "dim_application",
+ "DatabaseName": "db",
+ "Parameters": {"metadata_location": f"s3://lake/{key}"},
+ }
+
+
+def test_load_table_inlines_metadata_json_verbatim():
+ _seed_glue_table_with_metadata()
+ status, _, payload = _call(
+ "GET",
+ "/iceberg/v1/catalogs/000000000000/namespaces/db/tables/dim_application",
+ )
+ assert status == 200
+ assert payload["metadata-location"].endswith("/00003-deadbeef.metadata.json")
+ assert payload["metadata"] == _META_JSON # passthrough — no transformation
+ assert "s3.endpoint" in payload["config"]
+
+
+def test_load_table_404s_when_metadata_object_missing():
+ """Glue table exists and points at an S3 URI, but the metadata.json
+ object isn't there. 200-with-empty-metadata would make DuckDB treat it
+ as a real-but-empty table and silently return wrong results."""
+ _svc("glue")._databases["db"] = {"Name": "db"}
+ _svc("glue")._tables["db/orphan"] = {
+ "Name": "orphan",
+ "DatabaseName": "db",
+ "Parameters": {"metadata_location": "s3://lake/orphan/metadata/v0.metadata.json"},
+ }
+ status, _, payload = _call(
+ "GET", "/iceberg/v1/catalogs/000000000000/namespaces/db/tables/orphan"
+ )
+ assert status == 404
+ assert payload["error"]["type"] == "NoSuchTableException"
+ assert payload["error"]["code"] == 404
+
+
+def test_load_table_404s_when_metadata_json_unparseable():
+ key = "broken/metadata/v0.metadata.json"
+ _svc("s3")._buckets["lake"] = {"objects": {key: {"body": b"<<not json>>"}}}
+ _svc("glue")._databases["db"] = {"Name": "db"}
+ _svc("glue")._tables["db/broken"] = {
+ "Name": "broken",
+ "DatabaseName": "db",
+ "Parameters": {"metadata_location": f"s3://lake/{key}"},
+ }
+ status, _, payload = _call(
+ "GET", "/iceberg/v1/catalogs/000000000000/namespaces/db/tables/broken"
+ )
+ assert status == 404
+ assert payload["error"]["type"] == "NoSuchTableException"
+
+
+def test_load_table_404s_on_unknown_table():
+ status, _, payload = _call(
+ "GET", "/iceberg/v1/catalogs/000000000000/namespaces/db/tables/missing"
+ )
+ assert status == 404
+ assert payload["error"]["type"] == "NoSuchTableException"
+
+
+def test_load_table_404s_on_non_iceberg_table():
+ _svc("glue")._databases["db"] = {"Name": "db"}
+ _svc("glue")._tables["db/csv"] = {"Name": "csv", "DatabaseName": "db", "Parameters": {}}
+ status, _, payload = _call(
+ "GET", "/iceberg/v1/catalogs/000000000000/namespaces/db/tables/csv"
+ )
+ assert status == 404
+
+
+# ── HEAD / TableExists ───────────────────────────────────────
+
+
+def test_head_returns_200_for_iceberg_table():
+ _seed_glue_table_with_metadata()
+ status, _, _ = _call(
+ "HEAD",
+ "/iceberg/v1/catalogs/000000000000/namespaces/db/tables/dim_application",
+ )
+ assert status == 200
+
+
+def test_head_returns_404_for_non_iceberg_table():
+ _svc("glue")._databases["db"] = {"Name": "db"}
+ _svc("glue")._tables["db/csv"] = {"Name": "csv", "DatabaseName": "db", "Parameters": {}}
+ status, _, _ = _call(
+ "HEAD", "/iceberg/v1/catalogs/000000000000/namespaces/db/tables/csv"
+ )
+ assert status == 404
+
+
+# ── Fall-throughs ────────────────────────────────────────────
+
+
+def test_post_to_table_returns_501_unsupported():
+ """Read-only surface: writes get an explicit 501 envelope instead of a
+ silent success that never persisted anything."""
+ status, _, payload = _call(
+ "POST", "/iceberg/v1/catalogs/000000000000/namespaces/db/tables/t"
+ )
+ assert status == 501
+ assert payload["error"]["type"] == "UnsupportedOperationException"
+
+
+def test_non_catalogs_prefix_returns_501():
+ """Bare-warehouse prefixes (`/v1/{warehouse}/namespaces`) are the
+ S3 Tables shape, not Glue's — reject rather than guess."""
+ status, _, payload = _call(
+ "GET", "/iceberg/v1/000000000000/namespaces"
+ )
+ assert status == 501
+
+
+def test_unknown_version_prefix_404s():
+ status, _, _ = _call("GET", "/iceberg/v2/config")
+ assert status == 404
+
+
+def test_glue_json_rpc_surface_unaffected():
+ """The X-Amz-Target JSON RPC surface must keep working alongside the
+ Iceberg branch — same module, two protocols."""
+ status, _, body = asyncio.run(
+ _svc("glue").handle_request(
+ "POST", "/",
+ {"x-amz-target": "AWSGlue.CreateDatabase"},
+ json.dumps({"DatabaseInput": {"Name": "rpc_db"}}).encode(),
+ {},
+ )
+ )
+ assert status == 200
+ assert "rpc_db" in _svc("glue")._databases