Skip to content

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

fix (cognit0, rds, apgw): multi fix (#971)

Nahuel Nucera7e66f55744d5
diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.py
index 83448965..298dc8b3 100644
--- a/ministack/services/apigateway_v1.py
+++ b/ministack/services/apigateway_v1.py
@@ -475,7 +475,20 @@ def _match_recursive(resources, parent_id, segments, params):
segment = segments[0]
remaining = segments[1:]
children = [r for r in resources.values() if r.get("parentId") == parent_id]
- for child in children:
+
+ # AWS resolves by specificity, not resource-creation order: a literal
+ # segment wins over a {param} sibling, which wins over a greedy {proxy+}.
+ # Without this, a {id} resource registered before a literal sibling would
+ # match first and shadow it (405 on the literal path).
+ def _precedence(res):
+ pp = res.get("pathPart", "")
+ if pp.startswith("{") and pp.endswith("+}"):
+ return 2 # greedy {proxy+} — lowest priority
+ if pp.startswith("{") and pp.endswith("}"):
+ return 1 # path parameter
+ return 0 # literal segment — highest priority
+
+ for child in sorted(children, key=_precedence):
pp = child.get("pathPart", "")
if pp.endswith("+}") and pp.startswith("{"):
# greedy {proxy+}
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index 4bbd34a0..b1b6d0eb 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -4263,6 +4263,16 @@ def _oauth2_token(data, query_params, raw_body: bytes = b"", headers: dict | Non
if not _verify_pkce(code_verifier, entry["code_challenge"], method):
return _oauth2_error("invalid_grant", "PKCE verification failed.")
+ # Validate client secret BEFORE consuming the code. AWS rejects bad
+ # client authentication without invalidating the single-use code, so
+ # a client that authenticates in two steps (HTTP Basic, then
+ # client_secret_post fallback — as Go/Vault does) can still succeed
+ # on the retry. Consuming the code first turned that retry into
+ # invalid_grant "Invalid or expired authorization code" (#932).
+ _, _, client = _find_pool_by_client_id(cid)
+ if client and client.get("ClientSecret") and csec != client["ClientSecret"]:
+ return _oauth2_error("invalid_client", "Invalid client credentials.")
+
# Consume code (one-time use)
del _authorization_codes[code]
@@ -4275,11 +4285,6 @@ def _oauth2_token(data, query_params, raw_body: bytes = b"", headers: dict | Non
if not user:
return _oauth2_error("server_error", "User not found.")
- # Validate client secret if client has one
- _, _, client = _find_pool_by_client_id(cid)
- if client and client.get("ClientSecret") and csec != client["ClientSecret"]:
- return _oauth2_error("invalid_client", "Invalid client credentials.")
-
result = _build_auth_result(pool_id, cid, user, nonce=entry.get("nonce", ""))
refresh_val = result["RefreshToken"]
_refresh_tokens[refresh_val] = {
diff --git a/ministack/services/rds_data.py b/ministack/services/rds_data.py
index a7c253e5..29233ae1 100644
--- a/ministack/services/rds_data.py
+++ b/ministack/services/rds_data.py
@@ -391,6 +391,32 @@ def _column_metadata(description, engine):
return metadata
+# A :name placeholder: a colon (not part of a "::" cast) followed by a word
+# token. Greedy \w+ consumes the whole name in one match, so ":1" and ":10"
+# are distinct tokens rather than one being a substring shadow of the other.
+_RE_NAMED_PARAM = re.compile(r"(?<!:):(\w+)")
+
+
+def _substitute_named_params(sql, param_names):
+ """Rewrite :name placeholders to DB-API %(name)s in a single pass.
+
+ AWS treats each :name as a distinct token, so a naive substring replace of
+ ":1" corrupts ":10" (the repro in #957). Matching whole tokens once, left to
+ right, makes them distinct regardless of length or order, leaves a "::type"
+ cast intact, and passes through any ":word" that is not a supplied parameter
+ (so it reaches the engine unchanged instead of becoming a bad placeholder).
+ """
+ if not param_names:
+ return sql
+ names = set(param_names)
+
+ def _repl(match):
+ name = match.group(1)
+ return f"%({name})s" if name in names else match.group(0)
+
+ return _RE_NAMED_PARAM.sub(_repl, sql)
+
+
def _convert_parameters(parameters):
"""Convert RDS Data API parameters to DB-API named params dict."""
if not parameters:
@@ -472,11 +498,7 @@ def _execute_statement(data):
# Convert :name placeholders to %(name)s for DB-API
params = _convert_parameters(parameters)
- exec_sql = sql
- if params:
- # Replace longest names first so ":1" doesn't clobber ":10"/":18" etc.
- for name in sorted(params, key=len, reverse=True):
- exec_sql = exec_sql.replace(f":{name}", f"%({name})s")
+ exec_sql = _substitute_named_params(sql, params)
own_conn = False
conn = None
@@ -652,12 +674,8 @@ def _batch_execute_statement(data):
update_results.append({"generatedFields": []})
else:
# Convert :name placeholders to %(name)s for DB-API
- exec_sql = sql
- if parameter_sets:
- sample = _convert_parameters(parameter_sets[0])
- # Longest names first so ":1" doesn't clobber ":10"/":18" etc.
- for name in sorted(sample, key=len, reverse=True):
- exec_sql = exec_sql.replace(f":{name}", f"%({name})s")
+ sample = _convert_parameters(parameter_sets[0])
+ exec_sql = _substitute_named_params(sql, sample)
for param_set in parameter_sets:
params = _convert_parameters(param_set)
diff --git a/tests/test_apigatewayv1.py b/tests/test_apigatewayv1.py
index f8eca41e..01f2a164 100644
--- a/tests/test_apigatewayv1.py
+++ b/tests/test_apigatewayv1.py
@@ -926,6 +926,74 @@ def test_apigwv1_execute_path_params(apigw_v1, lam):
apigw_v1.delete_rest_api(restApiId=api_id)
lam.delete_function(FunctionName=fname)
+def test_apigwv1_literal_sibling_wins_over_param_registered_first(apigw_v1, lam):
+ """A literal segment must resolve to its own method even when a {param}
+ sibling under the same parent was created first (#970). AWS routes by
+ specificity (literal > {param}), not by resource-creation order, so the
+ literal path must not be shadowed into a 405."""
+ import urllib.request as _urlreq
+ import uuid as _uuid
+
+ def _make_fn(label):
+ fname = f"intg-v1-{label}-{_uuid.uuid4().hex[:8]}"
+ code = (
+ b"def handler(event, context):\n"
+ b" return {'statusCode': 200, 'body': '" + label.encode() + b"'}\n"
+ )
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.py", code)
+ lam.create_function(
+ FunctionName=fname,
+ Runtime="python3.12",
+ Role="arn:aws:iam::000000000000:role/test-role",
+ Handler="index.handler",
+ Code={"ZipFile": buf.getvalue()},
+ )
+ return fname
+
+ get_fn = _make_fn("getuser")
+ verify_fn = _make_fn("verify")
+
+ api_id = apigw_v1.create_rest_api(name=f"v1-precedence-{_uuid.uuid4().hex[:8]}")["id"]
+ root = next(r for r in apigw_v1.get_resources(restApiId=api_id)["items"] if r["path"] == "/")
+ users_id = apigw_v1.create_resource(restApiId=api_id, parentId=root["id"], pathPart="users")["id"]
+
+ def _wire(parent, path_part, http_method, fname):
+ rid = apigw_v1.create_resource(restApiId=api_id, parentId=parent, pathPart=path_part)["id"]
+ apigw_v1.put_method(restApiId=api_id, resourceId=rid, httpMethod=http_method, authorizationType="NONE")
+ apigw_v1.put_integration(
+ restApiId=api_id, resourceId=rid, httpMethod=http_method,
+ type="AWS_PROXY", integrationHttpMethod="POST",
+ uri=f"arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:{fname}/invocations",
+ )
+
+ # {id} registered BEFORE the literal sibling — the order that triggered #970.
+ _wire(users_id, "{id}", "GET", get_fn)
+ _wire(users_id, "verifyUserEmail", "POST", verify_fn)
+
+ dep_id = apigw_v1.create_deployment(restApiId=api_id)["id"]
+ apigw_v1.create_stage(restApiId=api_id, stageName="v1", deploymentId=dep_id)
+
+ url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/v1/users/verifyUserEmail"
+ req = _urlreq.Request(url, method="POST", data=b"{}")
+ req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
+ resp = _urlreq.urlopen(req)
+ assert resp.status == 200
+ assert resp.read() == b"verify"
+
+ # The {param} sibling still resolves for its own path.
+ url2 = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/v1/users/alice123"
+ req2 = _urlreq.Request(url2, method="GET")
+ req2.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
+ resp2 = _urlreq.urlopen(req2)
+ assert resp2.status == 200
+ assert resp2.read() == b"getuser"
+
+ apigw_v1.delete_rest_api(restApiId=api_id)
+ lam.delete_function(FunctionName=get_fn)
+ lam.delete_function(FunctionName=verify_fn)
+
def test_apigwv1_execute_mock_integration(apigw_v1):
"""MOCK integration returns fixed JSON from integration response template."""
import urllib.request as _urlreq
diff --git a/tests/test_cognito.py b/tests/test_cognito.py
index d2b41034..2c826e24 100644
--- a/tests/test_cognito.py
+++ b/tests/test_cognito.py
@@ -2157,6 +2157,43 @@ def test_oauth2_token_authorization_code():
assert resp['expires_in'] == 3600
+def test_oauth2_token_failed_client_auth_does_not_consume_code():
+ """A token request that fails client authentication must NOT consume the
+ single-use authorization code (#932). AWS rejects bad client auth without
+ invalidating the code, so a client that retries — HTTP Basic first, then
+ client_secret_post, as Vault/Go's oauth2 does — succeeds on the retry.
+ Consuming the code on the failed first attempt turned the retry into
+ invalid_grant 'Invalid or expired authorization code'."""
+ cognito_idp = make_client('cognito-idp')
+ pool_id, client = _setup_pool_with_user(cognito_idp)
+ client_id = client['ClientId']
+ client_secret = client['ClientSecret']
+ code = _do_login_and_get_code(cognito_idp, client_id)
+
+ # First exchange fails client auth (wrong secret) -> invalid_client.
+ status, _, body = _post_form(f'{ENDPOINT}/oauth2/token', {
+ 'grant_type': 'authorization_code',
+ 'code': code,
+ 'redirect_uri': 'http://localhost:3000/callback',
+ 'client_id': client_id,
+ 'client_secret': 'wrong-secret',
+ })
+ assert status == 400, body
+ assert json.loads(body)['error'] == 'invalid_client'
+
+ # The code must survive the failed attempt: retry with the correct secret
+ # on the SAME code succeeds (would be invalid_grant before the fix).
+ status, _, body = _post_form(f'{ENDPOINT}/oauth2/token', {
+ 'grant_type': 'authorization_code',
+ 'code': code,
+ 'redirect_uri': 'http://localhost:3000/callback',
+ 'client_id': client_id,
+ 'client_secret': client_secret,
+ })
+ assert status == 200, body
+ assert 'access_token' in json.loads(body)
+
+
def test_oauth2_id_token_echoes_nonce():
"""OIDC requires the id_token to echo the nonce from the authorize request
so clients can mitigate replay. Strict OIDC clients (oidc-client-ts,
diff --git a/tests/test_rds_data.py b/tests/test_rds_data.py
index 9b250cb3..dcec3aae 100644
--- a/tests/test_rds_data.py
+++ b/tests/test_rds_data.py
@@ -252,6 +252,35 @@ def test_convert_parameters_empty_value():
assert result["x"] is None
+def test_substitute_named_params_distinct_numeric_tokens():
+ """:1 and :10 are distinct placeholders, not substring shadows (#957 bug 2).
+
+ A naive substring replace of ":1" first corrupts ":10" into "<val>0". Token
+ matching keeps them distinct regardless of supply order."""
+ from ministack.services.rds_data import _substitute_named_params
+
+ params = {"1": "ONE", "10": "TEN"}
+ assert _substitute_named_params("SELECT :1 AS one, :10 AS ten", params) == \
+ "SELECT %(1)s AS one, %(10)s AS ten"
+ # Order of the names in the dict must not change the result.
+ assert _substitute_named_params("SELECT :10 AS ten, :1 AS one", {"10": "TEN", "1": "ONE"}) == \
+ "SELECT %(10)s AS ten, %(1)s AS one"
+
+
+def test_substitute_named_params_preserves_cast_and_unknowns():
+ """A ::type cast is left intact and a :word that is not a supplied parameter
+ passes through unchanged instead of becoming a bad placeholder."""
+ from ministack.services.rds_data import _substitute_named_params
+
+ assert _substitute_named_params("SELECT :val::jsonb", {"val": "{}"}) == "SELECT %(val)s::jsonb"
+ assert _substitute_named_params("SELECT :foo", {"bar": 1}) == "SELECT :foo"
+ assert _substitute_named_params("SELECT 1", {}) == "SELECT 1"
+ # A longer unrelated :token must not be partially eaten by a shorter param
+ # name. Substring replace of ":id" would corrupt ":identity"; token matching
+ # leaves it whole because it is not a supplied parameter.
+ assert _substitute_named_params("SELECT :id, :identity", {"id": 1}) == "SELECT %(id)s, :identity"
+
+
# ── Stub mode tests ────────────────────────────────────────
def _setup_stub_cluster(rds, sm):