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
fix(cognito): invoke PreSignUp_ExternalProvider trigger on federation sign-up (#1091)
kjdev571fe23fc2fd
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex 9bc08e92..f542fc73 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -587,7 +587,7 @@ def _apply_pretoken_trigger(pool_id: str, claims: dict, token_type: str,raise RuntimeError(f"PreTokenGeneration error: {result.get('body')}")return claimspayload = result.get("body") if isinstance(result, dict) else result- response = _extract_pretoken_response(payload)+ response = _extract_trigger_response(payload)if not response:return claims@@ -667,12 +667,13 @@ def _build_pretoken_event(pool_id: str, client_id: str, username: str,}-def _extract_pretoken_response(payload) -> dict | None:- """Pull the ``response`` block from a Lambda invocation result.+def _extract_trigger_response(payload) -> dict | None:+ """Pull the ``response`` block from a Lambda trigger invocation result.- Lambdas return the full event echoed back with their overrides written- into ``response.claimsAndScopeOverrideDetails`` (V2/V3) or- ``response.claimsOverrideDetails`` (V1). Accept already-parsed dicts,+ Cognito Lambda triggers return the full event echoed back with their+ overrides written into the ``response`` block (e.g.+ ``response.claimsAndScopeOverrideDetails`` for PreTokenGeneration V2/V3,+ ``response.autoConfirmUser`` for PreSignUp). Accept already-parsed dicts,JSON strings, and bytes."""if payload is None:@@ -692,6 +693,100 @@ def _extract_pretoken_response(payload) -> dict | None:return payload.get("response") if isinstance(payload.get("response"), dict) else payload+class _PreSignUpRejected(Exception):+ """Raised when a PreSignUp Lambda trigger rejects a federated sign-up."""+++def _apply_presignup_trigger(pool_id: str, client_id: str, username: str,+ user_attrs: dict,+ trigger_source: str = "PreSignUp_ExternalProvider") -> dict:+ """Invoke the user pool's PreSignUp Lambda before persisting a federated user.++ Emulates AWS's ``PreSignUp_ExternalProvider`` trigger, which fires+ immediately before Cognito persists a user provisioned through IdP+ federation. Unlike ``_apply_pretoken_trigger``, this is fail-closed: on+ real AWS a Lambda that throws blocks the sign-up outright+ (``UserLambdaValidationException``), so any invocation failure or+ Lambda-reported error raises ``_PreSignUpRejected`` instead of being+ swallowed.++ Returns the trigger's ``autoConfirmUser``/``autoVerifyEmail``/+ ``autoVerifyPhone`` overrides (all ``False`` if the pool has no+ ``LambdaConfig.PreSignUp`` configured, which is a no-op).+ """+ defaults = {"autoConfirmUser": False, "autoVerifyEmail": False, "autoVerifyPhone": False}+ pool = _user_pools.get(pool_id)+ if not pool:+ return defaults+ cfg = pool.get("LambdaConfig") or {}+ arn = cfg.get("PreSignUp")+ if not arn:+ return defaults++ event = _build_presignup_event(+ pool_id=pool_id, client_id=client_id, username=username,+ user_attrs=user_attrs, trigger_source=trigger_source,+ )++ try:+ # Lazy import to avoid a circular dependency between cognito and lambda_svc.+ from ministack.services import lambda_svc+ record, config, _name = lambda_svc._get_func_record_for_ref(arn)+ if record is None or config is None:+ raise RuntimeError(f"PreSignUp Lambda not found: {arn}")+ exec_record = lambda_svc._execution_record_for_config(record, config)+ result = lambda_svc._execute_function_with_config_scope(exec_record, event)+ except Exception as e:+ logger.warning("PreSignUp Lambda invocation failed for pool %s: %s", pool_id, e)+ raise _PreSignUpRejected(str(e)) from e++ if isinstance(result, dict) and result.get("error"):+ reason = result.get("body") or "PreSignUp Lambda rejected the request."+ logger.info("PreSignUp Lambda rejected sign-up for pool %s user %s: %s",+ pool_id, username, reason)+ raise _PreSignUpRejected(str(reason))++ payload = result.get("body") if isinstance(result, dict) else result+ response = _extract_trigger_response(payload) or {}+ return {+ "autoConfirmUser": bool(response.get("autoConfirmUser")),+ "autoVerifyEmail": bool(response.get("autoVerifyEmail")),+ "autoVerifyPhone": bool(response.get("autoVerifyPhone")),+ }+++def _build_presignup_event(pool_id: str, client_id: str, username: str,+ user_attrs: dict, trigger_source: str) -> dict:+ """Construct the event payload AWS sends to a PreSignUp Lambda.++ Shape from the Cognito Developer Guide+ (https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-sign-up.html).+ ``validationData`` is always empty for federated sign-in — it only carries+ data supplied via ``ClientMetadata`` on the native ``SignUp`` API.+ """+ return {+ "version": "1",+ "triggerSource": trigger_source,+ "region": _pool_region(pool_id),+ "userPoolId": pool_id,+ "userName": username or "",+ "callerContext": {+ "awsSdkVersion": "ministack",+ "clientId": client_id or "",+ },+ "request": {+ "userAttributes": {k: v for k, v in (user_attrs or {}).items()+ if isinstance(v, (str, int, float, bool))},+ "validationData": {},+ },+ "response": {+ "autoConfirmUser": False,+ "autoVerifyEmail": False,+ "autoVerifyPhone": False,+ },+ }++def _user_from_token(token: str, pool: dict):"""Decode a stub JWT and return the matching user from pool, or None."""try:@@ -3951,16 +4046,26 @@ def _saml2_idp_response(body: bytes, query_params):sub = existing_dict.get("sub", new_uuid())else:sub = new_uuid()- user_attrs["sub"] = subif "email" not in user_attrs:user_attrs["email"] = name_id if "@" in name_id else ""+ try:+ presignup = _apply_presignup_trigger(pool_id, client_id, username, user_attrs)+ except _PreSignUpRejected as e:+ logger.info("Cognito: PreSignUp Lambda rejected SAML federation sign-up for %s: %s",+ username, e)+ return error_response_json("UserLambdaValidationException", str(e), 400)+ if presignup["autoVerifyEmail"] and "email" in user_attrs:+ user_attrs["email_verified"] = "true"+ if presignup["autoVerifyPhone"] and "phone_number" in user_attrs:+ user_attrs["phone_number_verified"] = "true"+ user_attrs["sub"] = subuser = {"Username": username,"Attributes": _dict_to_attr_list(user_attrs),"UserCreateDate": now,"UserLastModifiedDate": now,"Enabled": True,- "UserStatus": "EXTERNAL_PROVIDER",+ "UserStatus": "CONFIRMED" if presignup["autoConfirmUser"] else "EXTERNAL_PROVIDER","MFAOptions": [],"_password": "","_groups": [],@@ -4170,16 +4275,26 @@ def _oauth2_idp_response(method, body, query_params):sub = existing_dict.get("sub", new_uuid())else:sub = new_uuid()- user_attrs["sub"] = subif "email" not in user_attrs and "@" in name_id:user_attrs["email"] = name_id+ try:+ presignup = _apply_presignup_trigger(pool_id, client_id, username, user_attrs)+ except _PreSignUpRejected as e:+ logger.info("Cognito: PreSignUp Lambda rejected OIDC federation sign-up for %s: %s",+ username, e)+ return error_response_json("UserLambdaValidationException", str(e), 400)+ if presignup["autoVerifyEmail"] and "email" in user_attrs:+ user_attrs["email_verified"] = "true"+ if presignup["autoVerifyPhone"] and "phone_number" in user_attrs:+ user_attrs["phone_number_verified"] = "true"+ user_attrs["sub"] = subuser = {"Username": username,"Attributes": _dict_to_attr_list(user_attrs),"UserCreateDate": now,"UserLastModifiedDate": now,"Enabled": True,- "UserStatus": "EXTERNAL_PROVIDER",+ "UserStatus": "CONFIRMED" if presignup["autoConfirmUser"] else "EXTERNAL_PROVIDER","MFAOptions": [],"_password": "","_groups": [],diff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex 545fbde0..3248dfa3 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -1471,9 +1471,11 @@ class _NoRedirectHandler(urllib.request.HTTPRedirectHandler):_no_redirect_opener = urllib.request.build_opener(_NoRedirectHandler)-def _setup_saml_pool(cognito_idp):+def _setup_saml_pool(cognito_idp, lambda_config=None):"""Helper: create a pool + client + SAML provider for federated tests."""- pid = cognito_idp.create_user_pool(PoolName="FedPool")["UserPool"]["Id"]+ pid = cognito_idp.create_user_pool(+ PoolName="FedPool", **({"LambdaConfig": lambda_config} if lambda_config else {}),+ )["UserPool"]["Id"]client = cognito_idp.create_user_pool_client(UserPoolId=pid,ClientName="FedApp",@@ -1636,6 +1638,106 @@ def test_cognito_saml_full_flow(cognito_idp):assert attrs.get("name") == "John Doe"+def test_cognito_saml_presignup_lambda_rejects_unauthorized_user(cognito_idp, lam):+ """PreSignUp_ExternalProvider trigger fails closed: an uninvited federated+ user is rejected and never persisted."""+ handler = "def handler(event, ctx):\n raise Exception('not invited')\n"+ fn_name = "ministack-presignup-reject"+ lam.create_function(+ FunctionName=fn_name, Runtime="python3.12",+ Role="arn:aws:iam::000000000000:role/test-role",+ Handler="index.handler",+ Code={"ZipFile": _make_pretoken_lambda_zip(handler)},+ )+ fn_arn = lam.get_function(FunctionName=fn_name)["Configuration"]["FunctionArn"]+ pid, cid = _setup_saml_pool(cognito_idp, lambda_config={"PreSignUp": fn_arn})++ url = (+ f"{ENDPOINT}/oauth2/authorize?"+ f"response_type=code&client_id={cid}"+ f"&redirect_uri=http://localhost:3000/callback"+ f"&identity_provider=TestSAML&state=mystate&scope=openid"+ )+ try:+ _no_redirect_opener.open(url)+ assert False, "Expected redirect"+ except urllib.error.HTTPError as e:+ location = e.headers.get("Location", "")+ relay_state = _parse_qs(urlparse(location).query).get("RelayState", [""])[0]++ saml_resp = _build_mock_saml_response(name_id="[email protected]")+ form_data = _urlencode({"SAMLResponse": saml_resp, "RelayState": relay_state}).encode()+ req = urllib.request.Request(+ f"{ENDPOINT}/saml2/idpresponse", data=form_data,+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ )+ try:+ _no_redirect_opener.open(req)+ assert False, "Expected 400"+ except urllib.error.HTTPError as e:+ assert e.code == 400+ body = json.loads(e.read())+ assert "UserLambdaValidationException" in body.get("__type", "")++ with pytest.raises(ClientError):+ cognito_idp.admin_get_user(UserPoolId=pid, Username="[email protected]")+++def test_cognito_saml_presignup_lambda_autoconfirms_invited_user(cognito_idp, lam):+ """PreSignUp_ExternalProvider trigger's `autoConfirmUser`/`autoVerifyEmail`+ overrides are reflected on the persisted federated user."""+ handler = (+ "def handler(event, ctx):\n"+ " event['response']['autoConfirmUser'] = True\n"+ " event['response']['autoVerifyEmail'] = True\n"+ " return event\n"+ )+ fn_name = "ministack-presignup-autoconfirm"+ lam.create_function(+ FunctionName=fn_name, Runtime="python3.12",+ Role="arn:aws:iam::000000000000:role/test-role",+ Handler="index.handler",+ Code={"ZipFile": _make_pretoken_lambda_zip(handler)},+ )+ fn_arn = lam.get_function(FunctionName=fn_name)["Configuration"]["FunctionArn"]+ pid, cid = _setup_saml_pool(cognito_idp, lambda_config={"PreSignUp": fn_arn})++ url = (+ f"{ENDPOINT}/oauth2/authorize?"+ f"response_type=code&client_id={cid}"+ f"&redirect_uri=http://localhost:3000/callback"+ f"&identity_provider=TestSAML&state=mystate&scope=openid"+ )+ try:+ _no_redirect_opener.open(url)+ assert False, "Expected redirect"+ except urllib.error.HTTPError as e:+ location = e.headers.get("Location", "")+ relay_state = _parse_qs(urlparse(location).query).get("RelayState", [""])[0]++ saml_resp = _build_mock_saml_response(+ name_id="[email protected]",+ attributes={+ "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress": "[email protected]",+ },+ )+ form_data = _urlencode({"SAMLResponse": saml_resp, "RelayState": relay_state}).encode()+ req = urllib.request.Request(+ f"{ENDPOINT}/saml2/idpresponse", data=form_data,+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ )+ try:+ _no_redirect_opener.open(req)+ assert False, "Expected redirect"+ except urllib.error.HTTPError:+ pass++ user = cognito_idp.admin_get_user(UserPoolId=pid, Username="[email protected]")+ assert user["UserStatus"] == "CONFIRMED"+ attrs = {a["Name"]: a["Value"] for a in user["UserAttributes"]}+ assert attrs.get("email_verified") == "true"++# ---------------------------------------------------------------------------# OIDC federation (external OIDC IdP — e.g. Keycloak in front of Cognito)# ---------------------------------------------------------------------------@@ -1703,8 +1805,10 @@ def _start_fake_oidc_idp(claims):return token_url, recorded, stop-def _setup_oidc_pool(cognito_idp, token_url):- pid = cognito_idp.create_user_pool(PoolName="OIDCFedPool")["UserPool"]["Id"]+def _setup_oidc_pool(cognito_idp, token_url, lambda_config=None):+ pid = cognito_idp.create_user_pool(+ PoolName="OIDCFedPool", **({"LambdaConfig": lambda_config} if lambda_config else {}),+ )["UserPool"]["Id"]client = cognito_idp.create_user_pool_client(UserPoolId=pid,ClientName="OIDCApp",@@ -1826,6 +1930,52 @@ def test_cognito_oidc_full_flow(cognito_idp):stop()+def test_cognito_oidc_presignup_lambda_rejects_unauthorized_user(cognito_idp, lam):+ """`/oauth2/idpresponse` also honours the PreSignUp_ExternalProvider+ trigger: a rejected federated user is never persisted."""+ handler = "def handler(event, ctx):\n raise Exception('not invited')\n"+ fn_name = "ministack-presignup-oidc-reject"+ lam.create_function(+ FunctionName=fn_name, Runtime="python3.12",+ Role="arn:aws:iam::000000000000:role/test-role",+ Handler="index.handler",+ Code={"ZipFile": _make_pretoken_lambda_zip(handler)},+ )+ fn_arn = lam.get_function(FunctionName=fn_name)["Configuration"]["FunctionArn"]++ claims = {"sub": "user-uninvited", "email": "[email protected]"}+ token_url, _recorded, stop = _start_fake_oidc_idp(claims)+ try:+ pid, cid = _setup_oidc_pool(cognito_idp, token_url, lambda_config={"PreSignUp": fn_arn})++ authorize_url = (+ f"{ENDPOINT}/oauth2/authorize?"+ f"response_type=code&client_id={cid}"+ f"&redirect_uri=http://localhost:3000/callback"+ f"&identity_provider=TestOIDC&state=appstate&scope=openid"+ )+ try:+ _no_redirect_opener.open(authorize_url)+ assert False, "Expected 302"+ except urllib.error.HTTPError as e:+ idp_redirect = e.headers.get("Location", "")+ relay_state = _parse_qs(urlparse(idp_redirect).query)["state"][0]++ cb_url = f"{ENDPOINT}/oauth2/idpresponse?code=idp-issued-code&state={relay_state}"+ try:+ _no_redirect_opener.open(cb_url)+ assert False, "Expected 400"+ except urllib.error.HTTPError as e:+ assert e.code == 400+ body = json.loads(e.read())+ assert "UserLambdaValidationException" in body.get("__type", "")++ with pytest.raises(ClientError):+ cognito_idp.admin_get_user(UserPoolId=pid, Username="TestOIDC_user-uninvited")+ finally:+ stop()++def test_cognito_oidc_callback_invalid_state(cognito_idp):"""`/oauth2/idpresponse` with an unknown state returns 400 — relay codesare single-use, expired, and tied to a prior /oauth2/authorize call."""