diff --git a/tests/unit/utils/cache/users/test_module.py b/tests/unit/utils/cache/users/test_module.py index 9ca2e17e06..3a90e7e129 100644 --- a/tests/unit/utils/cache/users/test_module.py +++ b/tests/unit/utils/cache/users/test_module.py @@ -90,6 +90,44 @@ class TestLoadUserDefs(unittest.TestCase): with self.assertRaisesRegex(ValueError, "Conflict for user 'shared'"): cache_users._load_user_defs(roles) + def test_two_roles_register_a_token_for_the_same_user(self): + with tempfile.TemporaryDirectory() as tmp: + roles = Path(tmp) / "roles" + _write( + roles / "web-app-a" / ROLE_FILE_META_USERS, + """ + administrator: {tokens: {web-app-a: ""}} + """, + ) + _write( + roles / "web-app-b" / ROLE_FILE_META_USERS, + """ + administrator: {tokens: {web-app-b: ""}} + """, + ) + defs = cache_users._load_user_defs(roles) + self.assertEqual( + sorted(defs["administrator"]["tokens"]), ["web-app-a", "web-app-b"] + ) + + def test_the_same_token_key_with_two_values_still_conflicts(self): + with tempfile.TemporaryDirectory() as tmp: + roles = Path(tmp) / "roles" + _write( + roles / "web-app-a" / ROLE_FILE_META_USERS, + """ + administrator: {tokens: {shared-app: from-a}} + """, + ) + _write( + roles / "web-app-b" / ROLE_FILE_META_USERS, + """ + administrator: {tokens: {shared-app: from-b}} + """, + ) + with self.assertRaisesRegex(ValueError, "tokens.shared-app"): + cache_users._load_user_defs(roles) + class TestBuildUsers(unittest.TestCase): def test_allocates_distinct_uids_for_users_without_explicit_uid(self): diff --git a/utils/cache/users/__init__.py b/utils/cache/users/__init__.py index da97804f2c..d750543d8c 100644 --- a/utils/cache/users/__init__.py +++ b/utils/cache/users/__init__.py @@ -102,12 +102,25 @@ def _load_user_defs(roles_dir: Path) -> OrderedDict[str, dict[str, Any]]: existing = merged[key] for field, value in overrides.items(): - if field in existing and existing[field] != value: + if field not in existing: + existing[field] = copy.deepcopy(value) + continue + current = existing[field] + if isinstance(current, dict) and isinstance(value, dict): + for sub_key, sub_value in value.items(): + if sub_key in current and current[sub_key] != sub_value: + raise ValueError( + f"Conflict for user '{key}': field '{field}.{sub_key}' has " + f"existing value '{current[sub_key]}', tried to set " + f"'{sub_value}' in {filepath}" + ) + current[sub_key] = copy.deepcopy(sub_value) + continue + if current != value: raise ValueError( f"Conflict for user '{key}': field '{field}' has existing value " - f"'{existing[field]}', tried to set '{value}' in {filepath}" + f"'{current}', tried to set '{value}' in {filepath}" ) - existing.update(copy.deepcopy(overrides)) return merged