Преглед изворни кода

Closes #23661: Keep Google unique user ID logins working

Sites which set USE_UNIQUE_USER_ID for a Google backend (directly or
through the global setting) stored Google's sub as each user's uid,
but social-auth-app-django's id_key backfill migration assumes email.
Derive SOCIAL_AUTH_OLD_ID_KEYS for these sites so the migration tags
their associations correctly and users keep their existing accounts.
Configured entries take precedence, and a configured ID_KEY suppresses
the derivation, as it took precedence over USE_UNIQUE_USER_ID in
social-auth-core 5.2.0.
Jason Novinger пре 2 дана
родитељ
комит
7f7321c051
3 измењених фајлова са 117 додато и 1 уклоњено
  1. 5 0
      netbox/netbox/settings.py
  2. 24 0
      netbox/netbox/settings_utils.py
  3. 88 1
      netbox/netbox/tests/test_settings_utils.py

+ 5 - 0
netbox/netbox/settings.py

@@ -26,6 +26,7 @@ from netbox.settings_utils import (
     parse_job_timeout,
     resolve_install_paths,
     secret_key_hint,
+    social_auth_old_id_keys,
     validate_permissions_policy,
     validate_webhook_default_timeout,
 )
@@ -776,6 +777,10 @@ for name in dir(configuration):
     if name.startswith('SOCIAL_AUTH_'):
         globals()[name] = getattr(configuration, name)
 
+# SOCIAL_AUTH_OLD_ID_KEYS tells social-auth-app-django's id_key backfill migration which Google associations were
+# created with USE_UNIQUE_USER_ID (#23661). Can be removed once that need has passed.
+SOCIAL_AUTH_OLD_ID_KEYS = social_auth_old_id_keys(configuration)
+
 # Warn if a custom pipeline omits the step which enforces allowlists
 if 'social_core.pipeline.social_auth.auth_allowed' not in SOCIAL_AUTH_PIPELINE:
     warnings.warn(

+ 24 - 0
netbox/netbox/settings_utils.py

@@ -24,6 +24,7 @@ __all__ = (
     'parse_job_timeout',
     'resolve_install_paths',
     'secret_key_hint',
+    'social_auth_old_id_keys',
     'validate_permissions_policy',
     'validate_webhook_default_timeout',
 )
@@ -106,6 +107,29 @@ def parse_job_timeout(value):
     return timeout
 
 
+def social_auth_old_id_keys(configuration):
+    """Return the SOCIAL_AUTH_OLD_ID_KEYS value for social-auth-app-django's id_key backfill migration.
+
+    Under social-auth-core 5.2.0, the Google backends stored `sub` as each user's uid when USE_UNIQUE_USER_ID was
+    set and ID_KEY was not, but the migration assumes email. Each setting is resolved as social-auth-core does: the
+    backend's own setting, else the global one. Configured entries take precedence. A configured value which is not
+    a dict is returned untouched, for the migration to reject.
+    """
+    configured = getattr(configuration, 'SOCIAL_AUTH_OLD_ID_KEYS', {})
+    if not isinstance(configured, dict):
+        return configured
+
+    def backend_setting(backend, name):
+        default = getattr(configuration, f'SOCIAL_AUTH_{name}', None)
+        return getattr(configuration, f"SOCIAL_AUTH_{backend.upper().replace('-', '_')}_{name}", default)
+
+    derived = {}
+    for backend in ('google-oauth2', 'google-onetap', 'google-openidconnect'):
+        if backend_setting(backend, 'USE_UNIQUE_USER_ID') and not backend_setting(backend, 'ID_KEY'):
+            derived[backend] = 'sub'
+    return {**derived, **configured}
+
+
 def validate_webhook_default_timeout(timeout, job_timeout):
     """Validate WEBHOOK_DEFAULT_TIMEOUT, including against the background job timeout.
 

+ 88 - 1
netbox/netbox/tests/test_settings_utils.py

@@ -1,7 +1,7 @@
 import os
 import sys
 import tempfile
-from types import ModuleType
+from types import MappingProxyType, ModuleType, SimpleNamespace
 from unittest.mock import patch
 
 from django.conf import settings as django_settings
@@ -542,3 +542,90 @@ class LoadLdapConfigTest(SimpleTestCase):
             django_settings.CONFIGURATION_DIR,
             os.path.dirname(os.path.abspath(configuration_testing.__file__)),
         )
+
+
+class SocialAuthOldIdKeysTest(SimpleTestCase):
+    """
+    social-auth-core 5.2.0 stored Google's `sub` as the uid when USE_UNIQUE_USER_ID was set, which
+    social-auth-app-django's id_key backfill migration cannot detect (#23661).
+    """
+    @staticmethod
+    def old_id_keys(**params):
+        return settings_utils.social_auth_old_id_keys(SimpleNamespace(**params))
+
+    def test_nothing_configured(self):
+        self.assertEqual(self.old_id_keys(), {})
+
+    def test_google_oauth2_flag(self):
+        self.assertEqual(
+            self.old_id_keys(SOCIAL_AUTH_GOOGLE_OAUTH2_USE_UNIQUE_USER_ID=True),
+            {'google-oauth2': 'sub'},
+        )
+
+    def test_google_openidconnect_flag(self):
+        self.assertEqual(
+            self.old_id_keys(SOCIAL_AUTH_GOOGLE_OPENIDCONNECT_USE_UNIQUE_USER_ID=True),
+            {'google-openidconnect': 'sub'},
+        )
+
+    def test_global_flag_covers_google_sub_backends(self):
+        # google-oauth (OAuth1) is left out: its current ID_KEY is `id`, not `sub`.
+        self.assertEqual(
+            self.old_id_keys(SOCIAL_AUTH_USE_UNIQUE_USER_ID=True),
+            {'google-oauth2': 'sub', 'google-onetap': 'sub', 'google-openidconnect': 'sub'},
+        )
+
+    def test_backend_flag_overrides_global_flag(self):
+        self.assertEqual(
+            self.old_id_keys(
+                SOCIAL_AUTH_USE_UNIQUE_USER_ID=True,
+                SOCIAL_AUTH_GOOGLE_OAUTH2_USE_UNIQUE_USER_ID=False,
+            ),
+            {'google-onetap': 'sub', 'google-openidconnect': 'sub'},
+        )
+
+    def test_id_key_overrides_flag(self):
+        # 5.2.0 used a configured ID_KEY ahead of USE_UNIQUE_USER_ID, so the uid is not `sub`.
+        self.assertEqual(
+            self.old_id_keys(
+                SOCIAL_AUTH_USE_UNIQUE_USER_ID=True,
+                SOCIAL_AUTH_GOOGLE_OAUTH2_ID_KEY='email',
+            ),
+            {'google-onetap': 'sub', 'google-openidconnect': 'sub'},
+        )
+        self.assertEqual(
+            self.old_id_keys(SOCIAL_AUTH_USE_UNIQUE_USER_ID=True, SOCIAL_AUTH_ID_KEY='email'),
+            {},
+        )
+
+    def test_configured_google_entry_wins(self):
+        self.assertEqual(
+            self.old_id_keys(
+                SOCIAL_AUTH_GOOGLE_OAUTH2_USE_UNIQUE_USER_ID=True,
+                SOCIAL_AUTH_OLD_ID_KEYS={'google-oauth2': 'email'},
+            ),
+            {'google-oauth2': 'email'},
+        )
+
+    def test_configured_entries_are_kept(self):
+        self.assertEqual(
+            self.old_id_keys(
+                SOCIAL_AUTH_GOOGLE_OAUTH2_USE_UNIQUE_USER_ID=True,
+                SOCIAL_AUTH_OLD_ID_KEYS={'okta-oauth2': 'email'},
+            ),
+            {'google-oauth2': 'sub', 'okta-oauth2': 'email'},
+        )
+        self.assertEqual(
+            self.old_id_keys(SOCIAL_AUTH_OLD_ID_KEYS={'okta-oauth2': 'email'}),
+            {'okta-oauth2': 'email'},
+        )
+
+    def test_invalid_configured_value_passed_through(self):
+        # The migration rejects anything but a dict with its own error. Settings must still load.
+        for value in (None, [('google-oauth2', 'sub')], 'google-oauth2', 1, MappingProxyType({'a': 'b'})):
+            with self.subTest(value=value):
+                result = self.old_id_keys(
+                    SOCIAL_AUTH_GOOGLE_OAUTH2_USE_UNIQUE_USER_ID=True,
+                    SOCIAL_AUTH_OLD_ID_KEYS=value,
+                )
+                self.assertIs(result, value)