|
| 1 | +# Copyright 2026 Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +"""Claims extraction in the login-profile customization hook. |
| 4 | +
|
| 5 | +``customAuthProfileLoginWriteOverride`` reads the caller's claims to populate the stored |
| 6 | +user profile. The REST API (v1) REQUEST authorizer delivers claims as a flat map of string |
| 7 | +values under ``requestContext.authorizer``, not nested under ``authorizer.jwt.claims`` or |
| 8 | +``authorizer.lambda`` as the HTTP API (v2) did. These tests pin that the hook reads the |
| 9 | +deployed REST shape (so the default email override is not silently inert), still reads the |
| 10 | +nested shapes for a customized copy carried across the migration, and does not raise on |
| 11 | +event shapes that carry no authorizer context. |
| 12 | +
|
| 13 | +The module is loaded directly from its file path because it imports VAMS handler packages |
| 14 | +that the shared ``conftest.py`` replaces with mocks. |
| 15 | +""" |
| 16 | +import importlib.util |
| 17 | +import os |
| 18 | +import sys |
| 19 | +from unittest.mock import MagicMock |
| 20 | + |
| 21 | +import pytest |
| 22 | + |
| 23 | +_HOOK_PATH = os.path.join( |
| 24 | + os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), |
| 25 | + "backend", "customConfigCommon", "customAuthLoginProfile.py", |
| 26 | +) |
| 27 | + |
| 28 | + |
| 29 | +_STUBS = { |
| 30 | + "customLogging": {}, |
| 31 | + "customLogging.logger": {"safeLogger": MagicMock(return_value=MagicMock())}, |
| 32 | + "handlers": {}, |
| 33 | + "handlers.auth": {"request_to_claims": MagicMock(return_value={})}, |
| 34 | + "handlers.authz": {"CasbinEnforcer": MagicMock()}, |
| 35 | + "common": {}, |
| 36 | + "common.constants": {"STANDARD_JSON_RESPONSE": {}}, |
| 37 | + "requests": {"get": MagicMock()}, |
| 38 | +} |
| 39 | + |
| 40 | + |
| 41 | +def _load_hook(): |
| 42 | + """Load the hook module with its VAMS imports stubbed out. |
| 43 | +
|
| 44 | + Other test modules (and the shared conftest) may already have registered partial mocks |
| 45 | + for these package names, so the required attributes are ensured on whatever object is |
| 46 | + present rather than only when the name is absent from sys.modules. Prior module state is |
| 47 | + restored afterwards so this does not perturb tests that run later in the session. |
| 48 | + """ |
| 49 | + saved = {} |
| 50 | + for name, attrs in _STUBS.items(): |
| 51 | + existing = sys.modules.get(name) |
| 52 | + if existing is None: |
| 53 | + sys.modules[name] = MagicMock() |
| 54 | + saved[name] = (False, None) |
| 55 | + else: |
| 56 | + saved[name] = (True, {a: getattr(existing, a, None) for a in attrs}) |
| 57 | + for attr, value in attrs.items(): |
| 58 | + if not hasattr(sys.modules[name], attr) or getattr(sys.modules[name], attr) is None: |
| 59 | + setattr(sys.modules[name], attr, value) |
| 60 | + |
| 61 | + try: |
| 62 | + spec = importlib.util.spec_from_file_location("_real_customAuthLoginProfile", _HOOK_PATH) |
| 63 | + module = importlib.util.module_from_spec(spec) |
| 64 | + spec.loader.exec_module(module) |
| 65 | + return module |
| 66 | + finally: |
| 67 | + for name, (existed, attrs) in saved.items(): |
| 68 | + if not existed: |
| 69 | + sys.modules.pop(name, None) |
| 70 | + elif attrs: |
| 71 | + for attr, value in attrs.items(): |
| 72 | + if value is None: |
| 73 | + try: |
| 74 | + delattr(sys.modules[name], attr) |
| 75 | + except AttributeError: |
| 76 | + pass |
| 77 | + else: |
| 78 | + setattr(sys.modules[name], attr, value) |
| 79 | + |
| 80 | + |
| 81 | +@pytest.fixture(scope="module") |
| 82 | +def hook(): |
| 83 | + return _load_hook().customAuthProfileLoginWriteOverride |
| 84 | + |
| 85 | + |
| 86 | +def _profile(): |
| 87 | + return {"userId": "u1", "email": "stored@example.com"} |
| 88 | + |
| 89 | + |
| 90 | +@pytest.mark.unit |
| 91 | +class TestClaimsEmailOverride: |
| 92 | + def test_rest_flat_authorizer_context_overrides_email(self, hook): |
| 93 | + """The deployed REST shape: claims are a flat string map under 'authorizer'.""" |
| 94 | + event = { |
| 95 | + "requestContext": { |
| 96 | + "authorizer": { |
| 97 | + "principalId": "u1", |
| 98 | + "sub": "u1", |
| 99 | + "email": "rest@example.com", |
| 100 | + "vams:tokens": '["u1"]', |
| 101 | + } |
| 102 | + } |
| 103 | + } |
| 104 | + assert hook(_profile(), event)["email"] == "rest@example.com" |
| 105 | + |
| 106 | + def test_v2_nested_jwt_claims_overrides_email(self, hook): |
| 107 | + event = {"requestContext": {"authorizer": {"jwt": {"claims": {"email": "jwt@example.com"}}}}} |
| 108 | + assert hook(_profile(), event)["email"] == "jwt@example.com" |
| 109 | + |
| 110 | + def test_v2_nested_lambda_claims_overrides_email(self, hook): |
| 111 | + event = {"requestContext": {"authorizer": {"lambda": {"email": "lam@example.com"}}}} |
| 112 | + assert hook(_profile(), event)["email"] == "lam@example.com" |
| 113 | + |
| 114 | + def test_user_id_is_never_altered(self, hook): |
| 115 | + """userId is the profile lookup key and must survive the override untouched.""" |
| 116 | + event = {"requestContext": {"authorizer": {"sub": "someone-else", "email": "x@example.com"}}} |
| 117 | + assert hook(_profile(), event)["userId"] == "u1" |
| 118 | + |
| 119 | + |
| 120 | +@pytest.mark.unit |
| 121 | +class TestNoClaimsAvailable: |
| 122 | + def test_cross_call_event_keeps_stored_email(self, hook): |
| 123 | + """A cross-call carries no email claim, so the stored value must be preserved.""" |
| 124 | + event = {"lambdaCrossCall": {"userName": "SYSTEM_USER"}} |
| 125 | + assert hook(_profile(), event)["email"] == "stored@example.com" |
| 126 | + |
| 127 | + def test_missing_request_context_does_not_raise(self, hook): |
| 128 | + assert hook(_profile(), {})["email"] == "stored@example.com" |
| 129 | + |
| 130 | + def test_null_authorizer_does_not_raise(self, hook): |
| 131 | + assert hook(_profile(), {"requestContext": {"authorizer": None}})["email"] == "stored@example.com" |
| 132 | + |
| 133 | + def test_empty_authorizer_keeps_stored_email(self, hook): |
| 134 | + assert hook(_profile(), {"requestContext": {"authorizer": {}}})["email"] == "stored@example.com" |
| 135 | + |
| 136 | + def test_blank_email_claim_does_not_overwrite_stored_email(self, hook): |
| 137 | + event = {"requestContext": {"authorizer": {"sub": "u1", "email": ""}}} |
| 138 | + assert hook(_profile(), event)["email"] == "stored@example.com" |
| 139 | + |
| 140 | + def test_principal_id_alone_is_not_treated_as_an_email_claim(self, hook): |
| 141 | + """principalId is authorizer metadata, not a claim; it must be stripped.""" |
| 142 | + event = {"requestContext": {"authorizer": {"principalId": "u1"}}} |
| 143 | + assert hook(_profile(), event)["email"] == "stored@example.com" |
0 commit comments