Skip to content

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

feat(eventbridge): invoke API destination targets over HTTP on PutEvents (#1319)

t-rechfe1557fb3b72
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 79c826ea..b557bdd8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
+### Added
+- **EventBridge — API destination targets are now invoked over HTTP on `PutEvents`** — API destinations and connections were control-plane stubs: a matching rule with an api-destination target logged "unsupported event target ARN" and dropped the event, so webhook-style pipelines (EventBridge → HTTPS endpoint) could not be tested locally. Matching events now POST (or the destination's configured method) to the `InvocationEndpoint` with the input-selected payload (`Input` / `InputPath` / `InputTransformer` apply as for other targets). Connection authorization is honored: `BASIC` populates `Authorization: Basic …`, `API_KEY` sends the configured header, and `OAUTH_CLIENT_CREDENTIALS` exchanges the client ID/secret at the authorization endpoint (`OAuthHttpParameters` merged in, `grant_type=client_credentials` defaulted), caches the token per connection and invalidates it when the connection is deleted, re-authorized, or deauthorized (a connection recreated under a reused name never inherits its predecessor's token), refreshes proactively when it expires within 60 seconds, and refreshes + retries once on a `401`/`407` response — matching documented AWS behavior. Connection `InvocationHttpParameters` and target `HttpParameters` are merged with connection values taking precedence (per the `HttpParameters` API reference), `PathParameterValues` populate `*` path wildcards, and body parameters fold into JSON-object bodies. Requests carry the AWS default headers (`User-Agent: Amazon/EventBridge/ApiDestinations` and `Range` non-overridable, `Content-Type` defaulting to `application/json; charset=utf-8`), strip the headers real EventBridge removes, and time out after 5 seconds (the documented maximum client execution timeout). Delivery runs on a background thread mirroring the SNS HTTP(S) path. Not modeled, mirroring the cross-region FailedInvocations policy: the 24h/185-attempt retry pipeline, `Retry-After`, DLQs, and `InvocationRateLimitPerSecond` — retryable statuses (`401`, `407`, `409`, `429`, `5xx`) are logged and dropped.
### Fixed
- **CloudWatch Logs — ARN-based tag operations resolve vended-delivery resources** — `TagResource`, `UntagResource`, and `ListTagsForResource` only resolved log-group ARNs, so the AWS provider's read-after-create on `aws_cloudwatch_log_delivery_source` / `aws_cloudwatch_log_delivery_destination` / `aws_cloudwatch_log_delivery` failed with `ResourceNotFoundException` and broke `terraform apply` of any stack using EventBridge bus logging (the community EventBridge module ≥ v4.1 provisions the trio). All three operations now resolve the delivery records' tags.
- **Route 53 — `ChangeResourceRecordSets` `DELETE` now requires the values provided to match the current values** — a `DELETE` matched only on name, type, and set identifier, so a delete carrying a stale TTL or stale record values silently removed the live record. Real Route 53 requires the values in a `DELETE` to match the current record exactly and rejects the whole batch with `InvalidChangeBatch` otherwise — the compare-and-swap semantics that guarded-delete workflows (delete only if the record still holds the values I last observed) rely on to detect concurrent modification, which the emulator's silent success defeated. A mismatched `DELETE` now fails the batch atomically with the AWS-shaped message (`Tried to delete resource record set [name='…', type='…'] but the values provided do not match the current values`); record values are compared as an unordered set, so the same values in a different order still match. Contributed by @jayjanssen.
diff --git a/README.md b/README.md
index 4a76da4c..b919e167 100644
--- a/README.md
+++ b/README.md
@@ -415,7 +415,7 @@ subnet = ec2.create_subnet(
| Service | Operations | Notes |
|---------|-----------|-------|
| **SSM Parameter Store** | PutParameter, GetParameter, GetParameters, GetParametersByPath, DeleteParameter, DeleteParameters, DescribeParameters, GetParameterHistory, LabelParameterVersion, AddTagsToResource, RemoveTagsFromResource, ListTagsForResource | Supports String, SecureString, StringList |
-| **EventBridge** | CreateEventBus, UpdateEventBus, DeleteEventBus, ListEventBuses, DescribeEventBus, PutRule, DeleteRule, ListRules, DescribeRule, EnableRule, DisableRule, PutTargets, RemoveTargets, ListTargetsByRule, ListRuleNamesByTarget, PutEvents, TestEventPattern, TagResource, UntagResource, ListTagsForResource, CreateArchive, DeleteArchive, DescribeArchive, UpdateArchive, ListArchives, PutPermission, RemovePermission, CreateConnection, DescribeConnection, DeleteConnection, UpdateConnection, DeauthorizeConnection, ListConnections, CreateApiDestination, DescribeApiDestination, DeleteApiDestination, UpdateApiDestination, ListApiDestinations, StartReplay, DescribeReplay, ListReplays, CancelReplay, CreateEndpoint, DeleteEndpoint, DescribeEndpoint, ListEndpoints, UpdateEndpoint, ActivateEventSource, DeactivateEventSource, DescribeEventSource, CreatePartnerEventSource, DeletePartnerEventSource, DescribePartnerEventSource, ListPartnerEventSources, ListPartnerEventSourceAccounts, ListEventSources, PutPartnerEvents | Lambda target dispatch on PutEvents; S3 EventBridge notifications; archives capture matching events and `StartReplay` re-dispatches them to the destination bus in a background thread; SaaS/partner APIs are control-plane stubs |
+| **EventBridge** | CreateEventBus, UpdateEventBus, DeleteEventBus, ListEventBuses, DescribeEventBus, PutRule, DeleteRule, ListRules, DescribeRule, EnableRule, DisableRule, PutTargets, RemoveTargets, ListTargetsByRule, ListRuleNamesByTarget, PutEvents, TestEventPattern, TagResource, UntagResource, ListTagsForResource, CreateArchive, DeleteArchive, DescribeArchive, UpdateArchive, ListArchives, PutPermission, RemovePermission, CreateConnection, DescribeConnection, DeleteConnection, UpdateConnection, DeauthorizeConnection, ListConnections, CreateApiDestination, DescribeApiDestination, DeleteApiDestination, UpdateApiDestination, ListApiDestinations, StartReplay, DescribeReplay, ListReplays, CancelReplay, CreateEndpoint, DeleteEndpoint, DescribeEndpoint, ListEndpoints, UpdateEndpoint, ActivateEventSource, DeactivateEventSource, DescribeEventSource, CreatePartnerEventSource, DeletePartnerEventSource, DescribePartnerEventSource, ListPartnerEventSources, ListPartnerEventSourceAccounts, ListEventSources, PutPartnerEvents | Lambda target dispatch on PutEvents; S3 EventBridge notifications; archives capture matching events and `StartReplay` re-dispatches them to the destination bus in a background thread; API destination targets are **invoked over HTTP** on PutEvents — connection auth (Basic, API Key, OAuth client-credentials with token caching and 401/407 refresh), connection/target header/query/body parameter merging with connection precedence, `*` path parameters, and the AWS default headers (`User-Agent: Amazon/EventBridge/ApiDestinations`, default `Content-Type: application/json; charset=utf-8`) — the 24h retry pipeline, rate limiting, and DLQs are not modeled; SaaS/partner APIs are otherwise control-plane stubs |
| **Kinesis** | CreateStream, DeleteStream, DescribeStream, DescribeStreamSummary, ListStreams, ListShards, PutRecord, PutRecords, GetShardIterator, GetRecords, IncreaseStreamRetentionPeriod, DecreaseStreamRetentionPeriod, MergeShards, SplitShard, UpdateShardCount, StartStreamEncryption, StopStreamEncryption, EnableEnhancedMonitoring, DisableEnhancedMonitoring, RegisterStreamConsumer, DeregisterStreamConsumer, ListStreamConsumers, DescribeStreamConsumer, AddTagsToStream, RemoveTagsFromStream, ListTagsForStream | Partition key → shard routing; AWS limits enforced (1 MB/record, 500 records/batch, 5 MB payload, 256-char partition key) |
| **CloudWatch Metrics** | PutMetricData, GetMetricStatistics, GetMetricData, ListMetrics, PutMetricAlarm, PutCompositeAlarm, DescribeAlarms, DescribeAlarmsForMetric, DescribeAlarmHistory, DeleteAlarms, SetAlarmState, EnableAlarmActions, DisableAlarmActions, TagResource, UntagResource, ListTagsForResource, PutDashboard, GetDashboard, DeleteDashboards, ListDashboards | CBOR and JSON protocol |
| **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 |
diff --git a/ministack/services/eventbridge.py b/ministack/services/eventbridge.py
index 7a994f17..a7505ee6 100644
--- a/ministack/services/eventbridge.py
+++ b/ministack/services/eventbridge.py
@@ -1190,7 +1190,9 @@ def _invoke_target(target, event, rule):
logger.warning("EventBridge: invalid target ARN %s", arn)
return
- if spec.service == "events":
+ if spec.service == "events" and spec.resource.startswith("api-destination/"):
+ _dispatch_to_api_destination(spec, event_payload, target)
+ elif spec.service == "events":
_dispatch_to_event_bus(spec, event, rule, event_path, target_input_payload)
elif spec.service == "states":
_dispatch_to_stepfunctions(arn, event_payload)
@@ -1426,6 +1428,322 @@ def _dispatch_to_stepfunctions(arn, payload):
logger.info("EventBridge → Step Functions %s: dispatched", sm_name)
+# ---------------------------------------------------------------------------
+# API destination dispatch
+# ---------------------------------------------------------------------------
+
+# OAuth access tokens per connection: {(account, region, connection_name): entry}.
+# Plain dict (not AccountRegionScopedDict) because delivery worker threads read
+# it outside a request scope; guarded by _oauth_tokens_lock.
+_oauth_tokens: dict = {}
+_oauth_tokens_lock = threading.Lock()
+
+# Stamped on every API destination request. Real EventBridge documents
+# User-Agent and Range as non-overridable and sends Accept-Encoding /
+# Connection itself; Content-Type defaults below only when no custom value is
+# configured on the connection or target.
+_API_DEST_FIXED_HEADERS = {
+ "User-Agent": "Amazon/EventBridge/ApiDestinations",
+ "Range": "bytes=0-1048575",
+ "Accept-Encoding": "gzip,deflate",
+ "Connection": "close",
+}
+_API_DEST_DEFAULT_CONTENT_TYPE = "application/json; charset=utf-8"
+
+# Real EventBridge removes these headers from API destination requests, so
+# connection/target parameters cannot smuggle them in (transport-owned headers
+# such as Host and Content-Length are set by the HTTP client itself).
+_API_DEST_REMOVED_HEADERS = {
+ "a-im", "accept-charset", "accept-datetime", "accept-encoding",
+ "cache-control", "connection", "content-encoding", "content-length",
+ "content-md5", "date", "expect", "forwarded", "from", "host",
+ "http2-settings", "if-match", "if-modified-since", "if-none-match",
+ "if-range", "if-unmodified-since", "max-forwards", "origin", "pragma",
+ "proxy-authorization", "range", "referer", "te", "trailer",
+ "transfer-encoding", "user-agent", "upgrade", "via", "warning",
+}
+
+
+def _connection_params_map(params) -> dict:
+ """Flatten a ConnectionHttpParameters list (``[{Key, Value, IsValueSecret}]``)
+ into a plain map. Connection-side parameters use the list-of-objects shape,
+ unlike the string maps on target HttpParameters."""
+ out = {}
+ for item in params or []:
+ key = item.get("Key")
+ if key:
+ out[key] = item.get("Value", "")
+ return out
+
+
+def _apply_path_parameters(url: str, values) -> str:
+ """Populate ``*`` path wildcards in the invocation endpoint from the
+ target's PathParameterValues, in order — the same contract as real
+ EventBridge."""
+ if not values:
+ return url
+ import urllib.parse
+
+ parsed = urllib.parse.urlsplit(url)
+ path = parsed.path
+ for value in values:
+ if "*" not in path:
+ break
+ path = path.replace("*", urllib.parse.quote(str(value), safe=""), 1)
+ return urllib.parse.urlunsplit((parsed.scheme, parsed.netloc, path, parsed.query, parsed.fragment))
+
+
+def _merge_query(url: str, params: dict) -> str:
+ if not params:
+ return url
+ import urllib.parse
+
+ parsed = urllib.parse.urlsplit(url)
+ query = dict(urllib.parse.parse_qsl(parsed.query, keep_blank_values=True))
+ query.update(params)
+ encoded = urllib.parse.urlencode(query)
+ return urllib.parse.urlunsplit((parsed.scheme, parsed.netloc, parsed.path, encoded, parsed.fragment))
+
+
+def _merge_body_parameters(payload: str, body_params: dict) -> str:
+ """Fold connection BodyParameters into a JSON-object body. Real EventBridge
+ documents body parameters as included in every invocation; how they combine
+ with a non-object body is undocumented there, so those bodies are left
+ untouched."""
+ if not body_params:
+ return payload
+ try:
+ parsed = json.loads(payload)
+ except (TypeError, ValueError):
+ return payload
+ if not isinstance(parsed, dict):
+ return payload
+ parsed.update(body_params)
+ return json.dumps(parsed)
+
+
+def _fetch_oauth_token(oauth: dict) -> dict:
+ """client_credentials exchange against the connection's authorization
+ endpoint: ClientID/ClientSecret ride the request body (query for GET),
+ OAuthHttpParameters contribute extra header/query/body parameters, and
+ ``access_token`` / ``token_type`` / ``expires_in`` are read from the JSON
+ response. ``grant_type`` defaults to ``client_credentials`` when
+ OAuthHttpParameters does not set one — AWS's own examples pass it
+ explicitly through body parameters."""
+ import urllib.parse
+ import urllib.request
+
+ method = (oauth.get("HttpMethod") or "POST").upper()
+ client = oauth.get("ClientParameters") or {}
+ http_params = oauth.get("OAuthHttpParameters") or {}
+ headers = _connection_params_map(http_params.get("HeaderParameters"))
+ form = {
+ "grant_type": "client_credentials",
+ "client_id": client.get("ClientID", ""),
+ "client_secret": client.get("ClientSecret", ""),
+ }
+ form.update(_connection_params_map(http_params.get("BodyParameters")))
+ url = _merge_query(
+ oauth.get("AuthorizationEndpoint", ""),
+ _connection_params_map(http_params.get("QueryStringParameters")),
+ )
+ data = None
+ if method == "GET":
+ url = _merge_query(url, form)
+ else:
+ data = urllib.parse.urlencode(form).encode("utf-8")
+ headers.setdefault("Content-Type", "application/x-www-form-urlencoded")
+ req = urllib.request.Request(url, data=data, headers=headers, method=method)
+ with urllib.request.urlopen(req, timeout=5) as resp:
+ token = json.loads(resp.read().decode("utf-8"))
+ token_type = token.get("token_type") or "Bearer"
+ if token_type.lower() == "bearer":
+ token_type = "Bearer"
+ expires_in = token.get("expires_in")
+ return {
+ "token": token.get("access_token", ""),
+ "type": token_type,
+ "expires_at": time.time() + float(expires_in) if expires_in else None,
+ }
+
+
+def _oauth_authorization_header(conn: dict, token_key, force_refresh: bool = False) -> str:
+ oauth = (conn.get("AuthParameters") or {}).get("OAuthParameters") or {}
+ with _oauth_tokens_lock:
+ cached = _oauth_tokens.get(token_key)
+ # Real EventBridge refreshes proactively when the token expires within 60
+ # seconds of an invocation — synchronously, on the event path.
+ fresh = cached and (cached["expires_at"] is None or cached["expires_at"] - time.time() > 60)
+ if force_refresh or not fresh:
+ cached = _fetch_oauth_token(oauth)
+ with _oauth_tokens_lock:
+ _oauth_tokens[token_key] = cached
+ return f"{cached['type']} {cached['token']}"
+
+
+def _evict_oauth_token(name: str):
+ """Drop a connection's cached access token.
+
+ The cache is keyed by connection NAME, and names are reusable: on real
+ EventBridge the token lives and dies with the connection, so a connection
+ that is deleted (and possibly recreated under the same name), has its auth
+ parameters replaced, or is deauthorized must perform a fresh
+ client_credentials exchange rather than keep serving a token minted from
+ credentials that no longer apply.
+ """
+ with _oauth_tokens_lock:
+ _oauth_tokens.pop((get_account_id(), get_region(), name), None)
+
+
+def _connection_auth_headers(conn: dict, token_key, force_refresh: bool = False) -> dict:
+ """Authorization header(s) for one delivery, mirroring how real EventBridge
+ populates them from the connection secret: BASIC → ``Authorization:
+ Basic``, API_KEY → the configured header, OAUTH_CLIENT_CREDENTIALS → a
+ managed Bearer token."""
+ import base64 as _b64
+
+ auth_type = conn.get("AuthorizationType", "")
+ params = conn.get("AuthParameters") or {}
+ if auth_type == "BASIC":
+ basic = params.get("BasicAuthParameters") or {}
+ raw = f"{basic.get('Username', '')}:{basic.get('Password', '')}".encode("utf-8")
+ return {"Authorization": "Basic " + _b64.b64encode(raw).decode("ascii")}
+ if auth_type == "API_KEY":
+ api_key = params.get("ApiKeyAuthParameters") or {}
+ name = api_key.get("ApiKeyName")
+ return {name: api_key.get("ApiKeyValue", "")} if name else {}
+ if auth_type == "OAUTH_CLIENT_CREDENTIALS":
+ return {"Authorization": _oauth_authorization_header(conn, token_key, force_refresh)}
+ return {}
+
+
+def _build_api_destination_request(dest: dict, conn: dict, target_http_params: dict, payload: str) -> dict:
+ invocation = (conn.get("AuthParameters") or {}).get("InvocationHttpParameters") or {}
+ conn_headers = _connection_params_map(invocation.get("HeaderParameters"))
+ conn_query = _connection_params_map(invocation.get("QueryStringParameters"))
+ conn_body = _connection_params_map(invocation.get("BodyParameters"))
+
+ # Target HttpParameters are merged with the connection's invocation
+ # parameters, "with any values from the Connection taking precedence"
+ # (EventBridge API reference, HttpParameters).
+ headers = {**(target_http_params.get("HeaderParameters") or {}), **conn_headers}
+ query = {**(target_http_params.get("QueryStringParameters") or {}), **conn_query}
+
+ url = _apply_path_parameters(
+ dest.get("InvocationEndpoint", ""), target_http_params.get("PathParameterValues")
+ )
+ url = _merge_query(url, query)
+ body = _merge_body_parameters(payload, conn_body)
+
+ headers = {k: v for k, v in headers.items() if k.lower() not in _API_DEST_REMOVED_HEADERS}
+ if not any(k.lower() == "content-type" for k in headers):
+ headers["Content-Type"] = _API_DEST_DEFAULT_CONTENT_TYPE
+ headers.update(_API_DEST_FIXED_HEADERS)
+
+ return {
+ "url": url,
+ "method": (dest.get("HttpMethod") or "POST").upper(),
+ "headers": headers,
+ "body": body,
+ }
+
+
+def _api_destination_send_sync(request: dict, auth_headers: dict) -> int:
+ """Blocking HTTP send for one API destination delivery. Runs on a worker
+ thread so the event loop stays unblocked; stdlib only (see the SNS HTTP
+ delivery note — aiohttp is not a declared dependency). The 5-second timeout
+ is AWS parity: API destination requests have a maximum client execution
+ timeout of 5 seconds."""
+ import urllib.error
+ import urllib.request
+
+ headers = {**request["headers"], **auth_headers}
+ body = request["body"]
+ req = urllib.request.Request(
+ request["url"],
+ data=body.encode("utf-8") if body is not None else None,
+ headers=headers,
+ method=request["method"],
+ )
+ try:
+ with urllib.request.urlopen(req, timeout=5) as resp:
+ return resp.status
+ except urllib.error.HTTPError as exc:
+ return exc.code
+
+
+def _deliver_to_api_destination(name: str, request: dict, conn: dict, token_key):
+ is_oauth = conn.get("AuthorizationType") == "OAUTH_CLIENT_CREDENTIALS"
+ try:
+ status = _api_destination_send_sync(request, _connection_auth_headers(conn, token_key))
+ if status in (401, 407) and is_oauth:
+ # Real EventBridge refreshes the OAuth token when a 401/407 comes
+ # back and retries the delivery.
+ status = _api_destination_send_sync(
+ request, _connection_auth_headers(conn, token_key, force_refresh=True)
+ )
+ except Exception as exc:
+ logger.warning("EventBridge → API destination %s delivery failed: %s", name, exc)
+ return
+ if 200 <= status < 300:
+ logger.info("EventBridge → API destination %s: HTTP %s", name, status)
+ elif status in (401, 407, 409, 429) or status >= 500:
+ # AWS parity: these statuses re-enter the 24h/185-attempt retry pipeline
+ # (DLQ on exhaustion, Retry-After honored). MiniStack does not model
+ # that queue — the same policy as cross-region FailedInvocations — so
+ # the outcome is logged and the event dropped.
+ logger.warning(
+ "EventBridge → API destination %s: retryable HTTP %s (retry pipeline not modeled; dropped)",
+ name,
+ status,
+ )
+ else:
+ logger.warning("EventBridge → API destination %s: HTTP %s (not retryable; dropped)", name, status)
+
+
+def _dispatch_to_api_destination(spec, payload, target):
+ if spec.account_id != get_account_id() or spec.region != get_region():
+ logger.warning(
+ "EventBridge → API destination: %s is outside the current account/region scope", spec
+ )
+ return
+ # Resource is "api-destination/<name>" (real AWS appends "/<uuid>"; tolerate both).
+ name = spec.resource.split("/", 2)[1]
+ dest = _api_destinations.get(name)
+ if not dest:
+ logger.warning("EventBridge → API destination: %s not found", name)
+ return
+ if dest.get("ApiDestinationState") != "ACTIVE":
+ # Real EventBridge does not invoke INACTIVE destinations; the delivery
+ # fails into the retry pipeline instead. Log-and-drop, as above.
+ logger.warning(
+ "EventBridge → API destination %s: state %s; not invoked",
+ name,
+ dest.get("ApiDestinationState"),
+ )
+ return
+ conn_name = (dest.get("ConnectionArn") or "").rsplit("/", 1)[-1]
+ conn = _connections.get(conn_name) if conn_name else None
+ if conn is None:
+ logger.warning(
+ "EventBridge → API destination %s: connection %s not found", name, conn_name or "<unset>"
+ )
+ return
+ # InvocationRateLimitPerSecond is accepted at CreateApiDestination but not
+ # enforced here — MiniStack delivers immediately and does not model the
+ # delivery queue that rate limiting implies.
+ request = _build_api_destination_request(dest, conn, target.get("HttpParameters") or {}, payload)
+ token_key = (get_account_id(), get_region(), conn_name)
+ # Deliver on a background daemon thread, mirroring the SNS HTTP(S) path:
+ # PutEvents returns as soon as the event is accepted and must not block on
+ # the destination endpoint.
+ threading.Thread(
+ target=_deliver_to_api_destination,
+ args=(name, request, copy.deepcopy(conn), token_key),
+ daemon=True,
+ ).start()
+
+
# ---------------------------------------------------------------------------
# Tags
# ---------------------------------------------------------------------------
@@ -2009,6 +2327,7 @@ def _delete_connection(data):
if not conn:
return error_response_json("ResourceNotFoundException",
f"Connection {name} does not exist.", 400)
+ _evict_oauth_token(name)
return json_response({
"ConnectionArn": conn["ConnectionArn"],
"ConnectionState": "DELETING",
@@ -2048,6 +2367,11 @@ def _update_connection(data):
for key in ("AuthorizationType", "AuthParameters", "Description"):
if key in data:
conn[key] = data[key]
+ if "AuthParameters" in data or "AuthorizationType" in data:
+ # Re-authorization: the new credentials, not the cached token, decide
+ # what the next invocation carries. A description-only update does not
+ # re-authorize, so it keeps the token.
+ _evict_oauth_token(name)
conn["LastModifiedTime"] = now
conn["ConnectionState"] = "AUTHORIZED"
conn["LastAuthorizedTime"] = now
@@ -2071,6 +2395,7 @@ def _deauthorize_connection(data):
conn["ConnectionState"] = "DEAUTHORIZED"
conn["LastModifiedTime"] = now
conn.pop("LastAuthorizedTime", None)
+ _evict_oauth_token(name)
return json_response({
"ConnectionArn": conn["ConnectionArn"],
"ConnectionState": conn["ConnectionState"],
@@ -2585,5 +2910,7 @@ def reset():
_partner_event_sources.clear()
_event_buses.clear()
_rule_last_fired.clear()
+ with _oauth_tokens_lock:
+ _oauth_tokens.clear()
# The "default" bus is lazily recreated per-account on next access via
# _ensure_default_bus(), so nothing to re-seed here.
diff --git a/tests/test_eventbridge.py b/tests/test_eventbridge.py
index 56b774a3..1aba6cf2 100644
--- a/tests/test_eventbridge.py
+++ b/tests/test_eventbridge.py
@@ -2851,3 +2851,456 @@ def test_eventbridge_input_transformer_ingestion_time(eb, sqs):
# substituted (not the literal placeholder) and non-empty; time is the event's stored value
assert body["it"] != "<aws.events.event.ingestion-time>"
assert body["it"] != ""
+
+
+# ---------------------------------------------------------------------------
+# API destination dispatch
+# ---------------------------------------------------------------------------
+
+def _start_api_dest_capture_server(status_plan=None):
+ """Local HTTPS-endpoint stand-in for an API destination. Captures every
+ request and answers with the next status in ``status_plan`` (the last one
+ repeats). Returns (server, captured)."""
+ import threading as _threading
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+ captured = []
+ plan = list(status_plan or [200])
+
+ class _Handler(BaseHTTPRequestHandler):
+ def _handle(self):
+ length = int(self.headers.get("Content-Length") or 0)
+ body = self.rfile.read(length).decode("utf-8") if length else ""
+ captured.append({
+ "method": self.command,
+ "path": self.path,
+ "headers": {k.lower(): v for k, v in self.headers.items()},
+ "body": body,
+ })
+ status = plan.pop(0) if len(plan) > 1 else plan[0]
+ payload = b"{}"
+ self.send_response(status)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload)
+
+ do_POST = _handle
+ do_PUT = _handle
+ do_GET = _handle
+ do_DELETE = _handle
+
+ def log_message(self, _format, *_args):
+ return
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
+ _threading.Thread(target=server.serve_forever, daemon=True).start()
+ return server, captured
+
+
+def _start_oauth_issuer(tokens=("tok-1",), expires_in=3600):
+ """Minimal client-credentials issuer: captures every token request and
+ hands out tokens from ``tokens`` in order (the last one repeats)."""
+ import threading as _threading
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+ from urllib.parse import parse_qs
+
+ token_requests = []
+ remaining = list(tokens)
+
+ class _Handler(BaseHTTPRequestHandler):
+ def do_POST(self):
+ length = int(self.headers.get("Content-Length") or 0)
+ body = self.rfile.read(length).decode("utf-8") if length else ""
+ token_requests.append({
+ "path": self.path,
+ "headers": {k.lower(): v for k, v in self.headers.items()},
+ "form": {k: v[0] for k, v in parse_qs(body, keep_blank_values=True).items()},
+ })
+ token = remaining.pop(0) if len(remaining) > 1 else remaining[0]
+ payload = json.dumps(
+ {"access_token": token, "token_type": "bearer", "expires_in": expires_in}
+ ).encode("utf-8")
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload)
+
+ def log_message(self, _format, *_args):
+ return
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
+ _threading.Thread(target=server.serve_forever, daemon=True).start()
+ return server, token_requests
+
+
+def _wait_until(predicate, timeout=5.0):
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ if predicate():
+ return True
+ time.sleep(0.05)
+ return predicate()
+
+
+def _api_dest_pipeline(eb, slug, endpoint, auth_type, auth_params, target_extras=None, http_method="POST"):
+ """Create bus → rule → connection → API destination → target for one test."""
+ bus_name = f"qa-eb-apidest-{slug}-bus"
+ source = f"myapp.apidest.{slug}"
+ eb.create_event_bus(Name=bus_name)
+ conn = eb.create_connection(
+ Name=f"qa-eb-apidest-{slug}-conn",
+ AuthorizationType=auth_type,
+ AuthParameters=auth_params,
+ )
+ dest = eb.create_api_destination(
+ Name=f"qa-eb-apidest-{slug}-dest",
+ ConnectionArn=conn["ConnectionArn"],
+ InvocationEndpoint=endpoint,
+ HttpMethod=http_method,
+ )
+ eb.put_rule(
+ Name=f"qa-eb-apidest-{slug}-rule",
+ EventBusName=bus_name,
+ EventPattern=json.dumps({"source": [source]}),
+ State="ENABLED",
+ )
+ target = {"Id": "t1", "Arn": dest["ApiDestinationArn"]}
+ target.update(target_extras or {})
+ eb.put_targets(Rule=f"qa-eb-apidest-{slug}-rule", EventBusName=bus_name, Targets=[target])
+ return bus_name, source
+
+
+def test_eventbridge_api_destination_basic_auth_full_envelope(eb):
+ server, captured = _start_api_dest_capture_server()
+ try:
+ port = server.server_address[1]
+ bus_name, source = _api_dest_pipeline(
+ eb,
+ "basic",
+ f"http://127.0.0.1:{port}/hooks/ingest",
+ "BASIC",
+ {"BasicAuthParameters": {"Username": "u", "Password": "p"}},
+ )
+ resp = eb.put_events(Entries=[{
+ "Source": source,
+ "DetailType": "UserSignup",
+ "Detail": json.dumps({"userId": "u-1"}),
+ "EventBusName": bus_name,
+ }])
+ assert resp["FailedEntryCount"] == 0
+
+ assert _wait_until(lambda: len(captured) >= 1)
+ req = captured[0]
+ assert req["method"] == "POST"
+ assert req["path"] == "/hooks/ingest"
+ # base64("u:p")
+ assert req["headers"]["authorization"] == "Basic dTpw"
+ assert req["headers"]["content-type"] == "application/json; charset=utf-8"
+ assert req["headers"]["user-agent"] == "Amazon/EventBridge/ApiDestinations"
+ assert req["headers"]["range"] == "bytes=0-1048575"
+ body = json.loads(req["body"])
+ assert body["version"] == "0"
+ assert body["source"] == source
+ assert body["detail-type"] == "UserSignup"
+ assert body["detail"] == {"userId": "u-1"}
+ finally:
+ server.shutdown()
+
+
+def test_eventbridge_api_destination_input_path_detail(eb):
+ """InputPath $.detail delivers exactly the event payload — the webhook body shape."""
+ server, captured = _start_api_dest_capture_server()
+ try:
+ port = server.server_address[1]
+ bus_name, source = _api_dest_pipeline(
+ eb,
+ "inputpath",
+ f"http://127.0.0.1:{port}/webhook",
+ "API_KEY",
+ {"ApiKeyAuthParameters": {"ApiKeyName": "X-Api-Key", "ApiKeyValue": "k-123"}},
+ target_extras={"InputPath": "$.detail"},
+ )
+ detail = {"orderId": "o-1", "amount": 42}
+ eb.put_events(Entries=[{
+ "Source": source,
+ "DetailType": "OrderPlaced",
+ "Detail": json.dumps(detail),
+ "EventBusName": bus_name,
+ }])
+
+ assert _wait_until(lambda: len(captured) >= 1)
+ req = captured[0]
+ assert req["headers"]["x-api-key"] == "k-123"
+ assert json.loads(req["body"]) == detail
+ finally:
+ server.shutdown()
+
+
+def test_eventbridge_api_destination_parameter_merging_connection_precedence(eb):
+ server, captured = _start_api_dest_capture_server()
+ try:
+ port = server.server_address[1]
+ bus_name, source = _api_dest_pipeline(
+ eb,
+ "params",
+ f"http://127.0.0.1:{port}/hooks/*/notify",
+ "API_KEY",
+ {
+ "ApiKeyAuthParameters": {"ApiKeyName": "X-Api-Key", "ApiKeyValue": "k-9"},
+ "InvocationHttpParameters": {
+ "HeaderParameters": [
+ {"Key": "X-Env", "Value": "conn"},
+ # Non-overridable in real AWS — must be dropped, not honored.
+ {"Key": "User-Agent", "Value": "evil"},
+ ],
+ "QueryStringParameters": [{"Key": "tenant", "Value": "conn-t"}],
+ "BodyParameters": [{"Key": "injected", "Value": "yes"}],
+ },
+ },
+ target_extras={
+ "HttpParameters": {
+ "HeaderParameters": {"X-Env": "target", "X-Target-Only": "t"},
+ "QueryStringParameters": {"tenant": "target-t", "extra": "1"},
+ "PathParameterValues": ["partner-1"],
+ }
+ },
+ )
+ eb.put_events(Entries=[{
+ "Source": source,
+ "DetailType": "Ping",
+ "Detail": json.dumps({"k": "v"}),
+ "EventBusName": bus_name,
+ }])
+
+ assert _wait_until(lambda: len(captured) >= 1)
+ req = captured[0]
+ path, _, query = req["path"].partition("?")
+ assert path == "/hooks/partner-1/notify"
+ from urllib.parse import parse_qs
+ params = {k: v[0] for k, v in parse_qs(query).items()}
+ # Connection values win over target values; target-only keys survive.
+ assert params == {"tenant": "conn-t", "extra": "1"}
+ assert req["headers"]["x-env"] == "conn"
+ assert req["headers"]["x-target-only"] == "t"
+ assert req["headers"]["user-agent"] == "Amazon/EventBridge/ApiDestinations"
+ body = json.loads(req["body"])
+ assert body["injected"] == "yes"
+ assert body["detail"] == {"k": "v"}
+ finally:
+ server.shutdown()
+
+
+def test_eventbridge_api_destination_oauth_client_credentials(eb):
+ issuer, token_requests = _start_oauth_issuer(tokens=("tok-1",))
+ server, captured = _start_api_dest_capture_server()
+ try:
+ issuer_port = issuer.server_address[1]
+ port = server.server_address[1]
+ bus_name, source = _api_dest_pipeline(
+ eb,
+ "oauth",
+ f"http://127.0.0.1:{port}/secured",
+ "OAUTH_CLIENT_CREDENTIALS",
+ {
+ "OAuthParameters": {
+ "AuthorizationEndpoint": f"http://127.0.0.1:{issuer_port}/oauth/token",
+ "HttpMethod": "POST",
+ "ClientParameters": {"ClientID": "cid", "ClientSecret": "csec"},
+ "OAuthHttpParameters": {
+ "BodyParameters": [{"Key": "audience", "Value": "https://api.example.test"}]
+ },
+ }
+ },
+ )
+ entry = {
+ "Source": source,
+ "DetailType": "Ping",
+ "Detail": json.dumps({"n": 1}),
+ "EventBusName": bus_name,
+ }
+ eb.put_events(Entries=[entry])
+ assert _wait_until(lambda: len(captured) >= 1)
+ # Second event rides the cached token — the issuer is not called again.
+ eb.put_events(Entries=[entry])
+ assert _wait_until(lambda: len(captured) >= 2)
+
+ assert len(token_requests) == 1
+ token_req = token_requests[0]
+ assert token_req["path"] == "/oauth/token"
+ assert token_req["headers"]["content-type"] == "application/x-www-form-urlencoded"
+ assert token_req["form"]["grant_type"] == "client_credentials"
+ assert token_req["form"]["client_id"] == "cid"
+ assert token_req["form"]["client_secret"] == "csec"
+ assert token_req["form"]["audience"] == "https://api.example.test"
+ assert captured[0]["headers"]["authorization"] == "Bearer tok-1"
+ assert captured[1]["headers"]["authorization"] == "Bearer tok-1"
+ finally:
+ issuer.shutdown()
+ server.shutdown()
+
+
+def _oauth_params(issuer_port, client_secret="csec"):
+ return {
+ "OAuthParameters": {
+ "AuthorizationEndpoint": f"http://127.0.0.1:{issuer_port}/oauth/token",
+ "HttpMethod": "POST",
+ "ClientParameters": {"ClientID": "cid", "ClientSecret": client_secret},
+ "OAuthHttpParameters": {
+ "BodyParameters": [{"Key": "grant_type", "Value": "client_credentials"}]
+ },
+ }
+ }
+
+
+def _oauth_entry(bus_name, source):
+ return {
+ "Source": source,
+ "DetailType": "Ping",
+ "Detail": json.dumps({"n": 1}),
+ "EventBusName": bus_name,
+ }
+
+
+def test_eventbridge_api_destination_oauth_token_dies_with_the_connection(eb):
+ """A recreated connection re-authorizes: the token cache is keyed by name,
+ and names are reusable, so a delete must not leave a token behind for the
+ next connection to inherit. Terraform replacing a connection in place is
+ the everyday way to hit this."""
+ issuer, token_requests = _start_oauth_issuer(tokens=("tok-1", "tok-2"))
+ server, captured = _start_api_dest_capture_server()
+ try:
+ issuer_port = issuer.server_address[1]
+ port = server.server_address[1]
+ bus_name, source = _api_dest_pipeline(
+ eb,
+ "oauthrecreate",
+ f"http://127.0.0.1:{port}/secured",
+ "OAUTH_CLIENT_CREDENTIALS",
+ _oauth_params(issuer_port),
+ )
+ entry = _oauth_entry(bus_name, source)
+ eb.put_events(Entries=[entry])
+ assert _wait_until(lambda: len(captured) >= 1)
+ assert len(token_requests) == 1
+
+ # Same name, so the API destination's ConnectionArn still resolves.
+ conn_name = "qa-eb-apidest-oauthrecreate-conn"
+ eb.delete_connection(Name=conn_name)
+ eb.create_connection(
+ Name=conn_name,
+ AuthorizationType="OAUTH_CLIENT_CREDENTIALS",
+ AuthParameters=_oauth_params(issuer_port, client_secret="rotated"),
+ )
+
+ eb.put_events(Entries=[entry])
+ assert _wait_until(lambda: len(captured) >= 2)
+ assert len(token_requests) == 2
+ assert token_requests[1]["form"]["client_secret"] == "rotated"
+ assert captured[1]["headers"]["authorization"] == "Bearer tok-2"
+ finally:
+ issuer.shutdown()
+ server.shutdown()
+
+
+def test_eventbridge_api_destination_oauth_token_evicted_on_reauthorization(eb):
+ """Rotating the client secret must take effect on the next invocation, not
+ whenever the old token happens to expire."""
+ issuer, token_requests = _start_oauth_issuer(tokens=("tok-1", "tok-2"))
+ server, captured = _start_api_dest_capture_server()
+ try:
+ issuer_port = issuer.server_address[1]
+ port = server.server_address[1]
+ bus_name, source = _api_dest_pipeline(
+ eb,
+ "oauthrotate",
+ f"http://127.0.0.1:{port}/secured",
+ "OAUTH_CLIENT_CREDENTIALS",
+ _oauth_params(issuer_port),
+ )
+ entry = _oauth_entry(bus_name, source)
+ eb.put_events(Entries=[entry])
+ assert _wait_until(lambda: len(captured) >= 1)
+ assert len(token_requests) == 1
+
+ eb.update_connection(
+ Name="qa-eb-apidest-oauthrotate-conn",
+ AuthorizationType="OAUTH_CLIENT_CREDENTIALS",
+ AuthParameters=_oauth_params(issuer_port, client_secret="rotated"),
+ )
+
+ eb.put_events(Entries=[entry])
+ assert _wait_until(lambda: len(captured) >= 2)
+ assert len(token_requests) == 2
+ assert token_requests[1]["form"]["client_secret"] == "rotated"
+ assert captured[1]["headers"]["authorization"] == "Bearer tok-2"
+ finally:
+ issuer.shutdown()
+ server.shutdown()
+
+
+def test_eventbridge_api_destination_oauth_token_survives_metadata_update(eb):
+ """The mirror image: a description-only update does not re-authorize, so
+ the cached token stays and no needless exchange is made."""
+ issuer, token_requests = _start_oauth_issuer(tokens=("tok-1", "tok-2"))
+ server, captured = _start_api_dest_capture_server()
+ try:
+ issuer_port = issuer.server_address[1]
+ port = server.server_address[1]
+ bus_name, source = _api_dest_pipeline(
+ eb,
+ "oauthdescr",
+ f"http://127.0.0.1:{port}/secured",
+ "OAUTH_CLIENT_CREDENTIALS",
+ _oauth_params(issuer_port),
+ )
+ entry = _oauth_entry(bus_name, source)
+ eb.put_events(Entries=[entry])
+ assert _wait_until(lambda: len(captured) >= 1)
+
+ eb.update_connection(Name="qa-eb-apidest-oauthdescr-conn", Description="renamed")
+
+ eb.put_events(Entries=[entry])
+ assert _wait_until(lambda: len(captured) >= 2)
+ assert len(token_requests) == 1
+ assert captured[1]["headers"]["authorization"] == "Bearer tok-1"
+ finally:
+ issuer.shutdown()
+ server.shutdown()
+
+
+def test_eventbridge_api_destination_oauth_refresh_on_401(eb):
+ issuer, token_requests = _start_oauth_issuer(tokens=("tok-old", "tok-new"))
+ server, captured = _start_api_dest_capture_server(status_plan=[401, 200])
+ try:
+ issuer_port = issuer.server_address[1]
+ port = server.server_address[1]
+ bus_name, source = _api_dest_pipeline(
+ eb,
+ "oauth401",
+ f"http://127.0.0.1:{port}/secured",
+ "OAUTH_CLIENT_CREDENTIALS",
+ {
+ "OAuthParameters": {
+ "AuthorizationEndpoint": f"http://127.0.0.1:{issuer_port}/oauth/token",
+ "HttpMethod": "POST",
+ "ClientParameters": {"ClientID": "cid", "ClientSecret": "csec"},
+ }
+ },
+ )
+ eb.put_events(Entries=[{
+ "Source": source,
+ "DetailType": "Ping",
+ "Detail": json.dumps({"n": 1}),
+ "EventBusName": bus_name,
+ }])
+
+ # 401 → token refresh → one retry with the new token.
+ assert _wait_until(lambda: len(captured) >= 2)
+ assert captured[0]["headers"]["authorization"] == "Bearer tok-old"
+ assert captured[1]["headers"]["authorization"] == "Bearer tok-new"
+ assert len(token_requests) == 2
+ finally:
+ issuer.shutdown()
+ server.shutdown()