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
feat(cognito): invoke InboundFederation trigger on SAML and OIDC federated sign-in (#2169)
kjdev73c3d6f8e387
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex 7d7be2b6..bb899d8b 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -1098,6 +1098,89 @@ def _apply_presignup_trigger(pool_id: str, client_id: str, username: str,}+# Token claims Cognito owns; an IdP claim of the same name only becomes a user+# attribute when AttributeMapping maps it explicitly.+_FEDERATION_RESERVED_CLAIMS = frozenset(+ ("iss", "aud", "exp", "iat", "nbf", "jti", "azp", "auth_time"))+++def _drop_unmapped_reserved_claims(claims: dict, attr_mapping: dict) -> dict:+ """Drop registered token claims from InboundFederation output unless mapped.++ A Lambda that echoes the whole ``idToken`` back would otherwise land+ ``iss`` / ``exp`` / ``iat`` in ``user_attrs``, and ``_fake_token`` copies+ those over Cognito's own claims. Real Cognito only keeps mapped claims.+ """+ mapped = set(attr_mapping.values())+ return {k: v for k, v in claims.items()+ if k not in _FEDERATION_RESERVED_CLAIMS or k in mapped}+++class _InboundFederationRejected(Exception):+ """Raised when an InboundFederation Lambda trigger fails the federated sign-in."""+++def _apply_inbound_federation_trigger(pool_id: str, client_id: str, username: str,+ provider_name: str, provider_type: str,+ attributes: dict) -> dict:+ """Invoke the pool's InboundFederation Lambda before AttributeMapping.++ Emulates ``InboundFederation_ExternalProvider``: the Lambda receives the+ raw IdP data (``samlResponse`` as a SAML Attribute name -> value map, or+ ``idToken`` / ``userInfo`` claims) and returns+ ``response.userAttributesToMap`` keyed by IdP claim name, which replaces+ the IdP's own value for that claim as the AttributeMapping input.+ Fail-closed like PreSignUp: a Lambda failure aborts the sign-in.++ Returns ``{}`` when the pool has no ``LambdaConfig.InboundFederation``.+ """+ pool = _user_pools.get(pool_id)+ cfg = ((pool or {}).get("LambdaConfig") or {}).get("InboundFederation")+ arn = cfg.get("LambdaArn") if isinstance(cfg, dict) else None+ if not arn:+ return {}++ event = {+ "version": "1",+ "triggerSource": "InboundFederation_ExternalProvider",+ "region": _pool_region(pool_id),+ "userPoolId": pool_id,+ "userName": username or "",+ "callerContext": {"awsSdkVersion": "ministack", "clientId": client_id or ""},+ "request": {+ "providerName": provider_name,+ "providerType": provider_type,+ "attributes": attributes,+ },+ "response": {"userAttributesToMap": {}},+ }++ 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"InboundFederation 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("InboundFederation Lambda invocation failed for pool %s: %s", pool_id, e)+ raise _InboundFederationRejected(str(e)) from e++ if isinstance(result, dict) and result.get("error"):+ reason = result.get("body") or "InboundFederation Lambda rejected the request."+ logger.info("InboundFederation Lambda rejected sign-in for pool %s user %s: %s",+ pool_id, username, reason)+ raise _InboundFederationRejected(str(reason))++ payload = result.get("body") if isinstance(result, dict) else result+ to_map = (_extract_trigger_response(payload) or {}).get("userAttributesToMap")+ if not isinstance(to_map, dict):+ return {}+ return {str(k): str(v) for k, v in to_map.items()+ if isinstance(v, (str, int, float, bool))}++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.@@ -6144,8 +6227,19 @@ def _saml2_idp_response(body: bytes, query_params):# Apply attribute mapping: IdP claim name → Cognito attribute nameattr_mapping = provider.get("AttributeMapping", {})reverse_mapping = {v: k for k, v in attr_mapping.items()} # IdP claim → Cognito attr+ idp_attrs = dict(saml_data.get("attributes", {}))+ try:+ idp_attrs.update(_drop_unmapped_reserved_claims(+ _apply_inbound_federation_trigger(+ pool_id, client_id, name_id, provider_name, "SAML",+ {"samlResponse": saml_data["attributes"]}),+ attr_mapping))+ except _InboundFederationRejected as e:+ logger.info("Cognito: InboundFederation Lambda rejected SAML sign-in for %s: %s",+ name_id, e)+ return error_response_json("UserLambdaValidationException", str(e), 400)user_attrs = {}- for idp_claim, value in saml_data.get("attributes", {}).items():+ for idp_claim, value in idp_attrs.items():cognito_attr = reverse_mapping.get(idp_claim, idp_claim)user_attrs[cognito_attr] = value@@ -6368,14 +6462,22 @@ def _oauth2_idp_response(method, body, query_params):# as the SAML branch.attr_mapping = provider.get("AttributeMapping", {})reverse_mapping = {v: k for k, v in attr_mapping.items()}+ idp_claims = {k: str(v) for k, v in claims.items()+ if k not in _FEDERATION_RESERVED_CLAIMS+ and isinstance(v, (str, int, float, bool))}+ try:+ idp_claims.update(_drop_unmapped_reserved_claims(+ _apply_inbound_federation_trigger(+ pool_id, client_id, str(claims.get("sub") or ""), provider_name, "OIDC",+ {"idToken": claims}),+ attr_mapping))+ except _InboundFederationRejected as e:+ logger.info("Cognito: InboundFederation Lambda rejected OIDC sign-in for %s: %s",+ claims.get("sub"), e)+ return error_response_json("UserLambdaValidationException", str(e), 400)user_attrs = {}- for idp_claim, value in claims.items():- if idp_claim in ("iss", "aud", "exp", "iat", "nbf", "jti", "azp", "auth_time"):- continue- if not isinstance(value, (str, int, float, bool)):- continue- cognito_attr = reverse_mapping.get(idp_claim, idp_claim)- user_attrs[cognito_attr] = str(value)+ for idp_claim, value in idp_claims.items():+ user_attrs[reverse_mapping.get(idp_claim, idp_claim)] = value# Stable identifier: prefer `sub` from id_token, fall back to `email` or# a generated UUID so users can be re-found on subsequent logins.diff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex 58bf565c..dc2da7ec 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -2891,7 +2891,7 @@ def _start_fake_oidc_idp(claims):return token_url, recorded, stop-def _setup_oidc_pool(cognito_idp, token_url, lambda_config=None):+def _setup_oidc_pool(cognito_idp, token_url, lambda_config=None, attribute_mapping=None):pid = cognito_idp.create_user_pool(PoolName="OIDCFedPool", **({"LambdaConfig": lambda_config} if lambda_config else {}),)["UserPool"]["Id"]@@ -2915,7 +2915,7 @@ def _setup_oidc_pool(cognito_idp, token_url, lambda_config=None):"client_secret": "oidc-client-secret","authorize_scopes": "openid email profile",},- AttributeMapping={"email": "email", "name": "name"},+ AttributeMapping=attribute_mapping or {"email": "email", "name": "name"},)return pid, client["ClientId"]@@ -10649,3 +10649,185 @@ def test_cognito_secret_hash_no_secret_refresh_ignores_supplied_hash(cognito_idpinitiate = cognito_idp.admin_initiate_auth if admin else cognito_idp.initiate_authresult = initiate(**kwargs)["AuthenticationResult"]assert cognito_idp.get_user(AccessToken=result["AccessToken"])["Username"] == "canonical-user"+++_INBOUND_EMAIL_CLAIM = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"+++def _create_inbound_federation_lambda(lam, fn_name, handler):+ 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)},+ )+ return lam.get_function(FunctionName=fn_name)["Configuration"]["FunctionArn"]+++def _saml_idpresponse(cid, saml_resp):+ """Run the SAML authorize + idpresponse legs; return (status, Location or body)."""+ try:+ _no_redirect_opener.open(+ f"{ENDPOINT}/oauth2/authorize?response_type=code&client_id={cid}"+ f"&redirect_uri=http://localhost:3000/callback"+ f"&identity_provider=TestSAML&state=s&scope=openid")+ assert False, "Expected redirect"+ except urllib.error.HTTPError as e:+ relay_state = _parse_qs(urlparse(e.headers.get("Location", "")).query)["RelayState"][0]+ req = urllib.request.Request(+ f"{ENDPOINT}/saml2/idpresponse",+ data=_urlencode({"SAMLResponse": saml_resp, "RelayState": relay_state}).encode(),+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ )+ try:+ _no_redirect_opener.open(req)+ assert False, "Expected redirect or 400"+ except urllib.error.HTTPError as e:+ return e.code, (e.headers.get("Location", "") if e.code == 302 else e.read())+++def test_cognito_inbound_federation_trigger_feeds_attribute_mapping(cognito_idp, lam):+ """userAttributesToMap supplies the AttributeMapping input the IdP did not send under that name."""+ handler = (+ "def handler(event, ctx):\n"+ " assert event['triggerSource'] == 'InboundFederation_ExternalProvider'\n"+ " assert event['request']['providerType'] == 'SAML'\n"+ " assert event['request']['providerName'] == 'TestSAML'\n"+ f" assert event['request']['attributes']['samlResponse'] == {{'{_INBOUND_EMAIL_CLAIM}': '[email protected]'}}\n"+ f" event['response']['userAttributesToMap'] = {{'{_INBOUND_EMAIL_CLAIM}': '[email protected]'}}\n"+ " return event\n"+ )+ fn_arn = _create_inbound_federation_lambda(lam, "ministack-inbound-fed-map", handler)+ pid, cid = _setup_saml_pool(cognito_idp, lambda_config={"InboundFederation": {"LambdaVersion": "V1_0", "LambdaArn": fn_arn}})+ assert cognito_idp.describe_user_pool(UserPoolId=pid)["UserPool"]["LambdaConfig"]["InboundFederation"]["LambdaArn"] == fn_arn++ status, _ = _saml_idpresponse(+ cid, _build_mock_saml_response(name_id="opaque-name-id", attributes={_INBOUND_EMAIL_CLAIM: "[email protected]"}))+ assert status == 302++ user = cognito_idp.admin_get_user(UserPoolId=pid, Username="TestSAML_opaque-name-id")+ attrs = {a["Name"]: a["Value"] for a in user["UserAttributes"]}+ assert attrs["email"] == "[email protected]"+++def test_cognito_inbound_federation_trigger_failure_fails_saml_sign_in(cognito_idp, lam):+ handler = "def handler(event, ctx):\n raise Exception('bad claims')\n"+ fn_arn = _create_inbound_federation_lambda(lam, "ministack-inbound-fed-reject", handler)+ pid, cid = _setup_saml_pool(cognito_idp, lambda_config={"InboundFederation": {"LambdaVersion": "V1_0", "LambdaArn": fn_arn}})++ status, body = _saml_idpresponse(cid, _build_mock_saml_response(name_id="[email protected]"))+ assert status == 400+ assert "UserLambdaValidationException" in json.loads(body).get("__type", "")+ with pytest.raises(ClientError):+ cognito_idp.admin_get_user(UserPoolId=pid, Username="[email protected]")+++def test_cognito_inbound_federation_trigger_feeds_oidc_attribute_mapping(cognito_idp, lam):+ handler = (+ "def handler(event, ctx):\n"+ " assert event['request']['providerType'] == 'OIDC'\n"+ " assert event['request']['attributes']['idToken']['sub'] == 'oidc-sub'\n"+ " event['response']['userAttributesToMap'] = {'auth_time': '1700000000', 'email': '[email protected]'}\n"+ " return event\n"+ )+ fn_arn = _create_inbound_federation_lambda(lam, "ministack-inbound-fed-oidc", handler)+ token_url, _recorded, stop = _start_fake_oidc_idp({"sub": "oidc-sub"})+ try:+ pid, cid = _setup_oidc_pool(cognito_idp, token_url, lambda_config={"InboundFederation": {"LambdaVersion": "V1_0", "LambdaArn": fn_arn}},+ attribute_mapping={"email": "email", "updated_at": "auth_time"})+ status, _ = _oidc_idpresponse(cid)+ assert status == 302+ user = cognito_idp.admin_get_user(UserPoolId=pid, Username="TestOIDC_oidc-sub")+ attrs = {a["Name"]: a["Value"] for a in user["UserAttributes"]}+ assert attrs["email"] == "[email protected]"+ assert attrs["updated_at"] == "1700000000"+ assert "auth_time" not in attrs+ finally:+ stop()+++def test_cognito_inbound_federation_trigger_registered_claims_do_not_override_id_token(cognito_idp, lam):+ handler = (+ "def handler(event, ctx):\n"+ " event['response']['userAttributesToMap'] = {\n"+ " k: str(v) for k, v in event['request']['attributes']['idToken'].items()}\n"+ " return event\n"+ )+ fn_arn = _create_inbound_federation_lambda(lam, "ministack-inbound-fed-oidc-reserved", handler)+ token_url, _recorded, stop = _start_fake_oidc_idp({+ "sub": "oidc-sub", "email": "[email protected]", "iss": "https://idp.example.com",+ "aud": "oidc-client-id", "exp": 1791852598, "iat": 1791852298, "jti": "idp-jti"})+ try:+ pid, cid = _setup_oidc_pool(cognito_idp, token_url, lambda_config={"InboundFederation": {"LambdaVersion": "V1_0", "LambdaArn": fn_arn}})+ status, location = _oidc_idpresponse(cid)+ assert status == 302+ code = _parse_qs(urlparse(location).query)["code"][0]+ req = urllib.request.Request(+ f"{ENDPOINT}/oauth2/token",+ data=(f"grant_type=authorization_code&code={code}&client_id={cid}"+ f"&redirect_uri=http://localhost:3000/callback").encode(),+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ )+ with urllib.request.urlopen(req) as resp:+ claims = _decode_jwt_claims(json.loads(resp.read())["id_token"])+ assert isinstance(claims["exp"], int) and isinstance(claims["iat"], int)+ assert claims["iss"].startswith("https://cognito-idp.")+ assert claims["aud"] == cid+ assert claims["jti"] != "idp-jti"+ assert claims["email"] == "[email protected]"+ finally:+ stop()+++def _oidc_idpresponse(cid):+ """Run the OIDC authorize + idpresponse legs; return (status, Location or body)."""+ try:+ _no_redirect_opener.open(+ f"{ENDPOINT}/oauth2/authorize?response_type=code&client_id={cid}"+ f"&redirect_uri=http://localhost:3000/callback"+ f"&identity_provider=TestOIDC&state=s&scope=openid")+ assert False, "Expected 302"+ except urllib.error.HTTPError as e:+ relay_state = _parse_qs(urlparse(e.headers.get("Location", "")).query)["state"][0]+ try:+ _no_redirect_opener.open(f"{ENDPOINT}/oauth2/idpresponse?code=idp-code&state={relay_state}")+ assert False, "Expected redirect or 400"+ except urllib.error.HTTPError as e:+ return e.code, (e.headers.get("Location", "") if e.code == 302 else e.read())+++def test_cognito_inbound_federation_trigger_failure_fails_oidc_sign_in(cognito_idp, lam):+ handler = "def handler(event, ctx):\n raise Exception('bad claims')\n"+ fn_arn = _create_inbound_federation_lambda(lam, "ministack-inbound-fed-oidc-reject", handler)+ token_url, _recorded, stop = _start_fake_oidc_idp({"sub": "oidc-blocked"})+ try:+ pid, cid = _setup_oidc_pool(cognito_idp, token_url, lambda_config={"InboundFederation": {"LambdaVersion": "V1_0", "LambdaArn": fn_arn}})+ status, body = _oidc_idpresponse(cid)+ assert status == 400+ assert "UserLambdaValidationException" in json.loads(body).get("__type", "")+ with pytest.raises(ClientError):+ cognito_idp.admin_get_user(UserPoolId=pid, Username="TestOIDC_oidc-blocked")+ finally:+ stop()+++def test_cognito_inbound_federation_trigger_missing_function_fails_sign_in(cognito_idp):+ missing_arn = "arn:aws:lambda:us-east-1:000000000000:function:ministack-inbound-fed-missing"+ pid, cid = _setup_saml_pool(cognito_idp, lambda_config={"InboundFederation": {"LambdaVersion": "V1_0", "LambdaArn": missing_arn}})++ status, body = _saml_idpresponse(cid, _build_mock_saml_response(name_id="[email protected]"))+ assert status == 400+ assert "UserLambdaValidationException" in json.loads(body).get("__type", "")+ with pytest.raises(ClientError):+ cognito_idp.admin_get_user(UserPoolId=pid, Username="[email protected]")+++def test_cognito_inbound_federation_trigger_unconfigured_pool_keeps_idp_attributes(cognito_idp):+ pid, cid = _setup_saml_pool(cognito_idp)++ status, _ = _saml_idpresponse(+ cid, _build_mock_saml_response(name_id="plain-name-id", attributes={_INBOUND_EMAIL_CLAIM: "[email protected]"}))+ assert status == 302+ user = cognito_idp.admin_get_user(UserPoolId=pid, Username="TestSAML_plain-name-id")+ attrs = {a["Name"]: a["Value"] for a in user["UserAttributes"]}+ assert attrs["email"] == "[email protected]"