Просмотр исходного кода

Closes #23661: Clear stale SSO login data in housekeeping

social-auth-core 7 records a nonce in the database for each SSO login
started, which only a completed login removes. Run
social-auth-app-django's clearsocial command from the system
housekeeping job so abandoned logins don't accumulate.
Jason Novinger 2 дней назад
Родитель
Сommit
73b54e79aa
2 измененных файлов с 38 добавлено и 0 удалено
  1. 16 0
      netbox/core/jobs.py
  2. 22 0
      netbox/core/tests/test_jobs.py

+ 16 - 0
netbox/core/jobs.py

@@ -5,6 +5,7 @@ from importlib import import_module
 import requests
 from django.conf import settings
 from django.core.cache import cache
+from django.core.management import call_command
 from django.db import router, transaction
 from django.db.models import Exists, OuterRef, Subquery
 from django.utils import timezone
@@ -119,6 +120,7 @@ class SystemHousekeepingJob(JobRunner):
 
         self.send_census_report()
         self.clear_expired_sessions()
+        self.clear_social_auth_data()
         self.prune_changelog()
         self.delete_expired_jobs()
         self.check_for_new_releases()
@@ -165,6 +167,20 @@ class SystemHousekeepingJob(JobRunner):
                 f"clearing sessions; skipping."
             )
 
+    def clear_social_auth_data(self):
+        """
+        Clear stale SSO login data, such as the nonce left behind by each login which is started but never
+        completed, using social-auth-app-django's own cleanup command.
+        """
+        self.logger.info("Clearing stale social auth data...")
+        try:
+            call_command('clearsocial')
+        except Exception:
+            # clearsocial depends on social auth settings, so a failure must not stop other housekeeping.
+            self.logger.exception("Failed to clear stale social auth data; skipping.")
+            return
+        self.logger.info("Social auth data cleared.")
+
     def prune_changelog(self):
         """
         Delete any ObjectChange records older than the configured changelog retention time (if any).

+ 22 - 0
netbox/core/tests/test_jobs.py

@@ -8,6 +8,7 @@ from django.db import connection
 from django.test import TestCase, override_settings, tag
 from django.test.utils import CaptureQueriesContext
 from django.utils import timezone
+from social_django.models import Nonce
 
 from core.choices import DataSourceStatusChoices, JobIntervalChoices, JobStatusChoices
 from core.events import JOB_COMPLETED
@@ -173,6 +174,7 @@ class SystemHousekeepingRunTestCase(HousekeepingRunnerMixin, TestCase):
     SUBMETHODS = (
         'send_census_report',
         'clear_expired_sessions',
+        'clear_social_auth_data',
         'prune_changelog',
         'delete_expired_jobs',
         'check_for_new_releases',
@@ -291,6 +293,26 @@ class ClearExpiredSessionsTestCase(HousekeepingRunnerMixin, TestCase):
         )
 
 
+class ClearSocialAuthDataTestCase(HousekeepingRunnerMixin, TestCase):
+    def test_clear_social_auth_data_deletes_only_stale_nonces(self):
+        # Each SSO login started leaves a nonce, which only a completed login removes (#23661).
+        now = int(timezone.now().timestamp())
+        Nonce.objects.create(server_url='social_core.oauth2.google-oauth2', timestamp=now - 86400 * 15, salt='old')
+        Nonce.objects.create(server_url='social_core.oauth2.google-oauth2', timestamp=now, salt='recent')
+
+        self._runner().clear_social_auth_data()
+
+        self.assertEqual(list(Nonce.objects.values_list('salt', flat=True)), ['recent'])
+
+    def test_clear_social_auth_data_failure_does_not_stop_housekeeping(self):
+        # e.g. a non-numeric PARTIAL_PIPELINE_EXPIRED_THRESHOLD raises TypeError inside clearsocial.
+        runner = self._runner()
+        with patch('core.jobs.call_command', side_effect=TypeError('bad threshold')):
+            runner.clear_social_auth_data()  # must not raise
+
+        runner.logger.exception.assert_called_once()
+
+
 class DeleteExpiredJobsTestCase(HousekeepingRunnerMixin, TestCase):
     def test_delete_expired_jobs_skips_when_retention_unset(self):
         old_job = Job.objects.create(name='old', job_id=uuid.uuid4())