c7d3ec57c3
Commitd2217531(google-labs-jules SSRF fix) catastrophically deleted 11,500+ lines across 100+ files while fixing an unrelated IMAP issue. Restored from d2217531^ (pre-bad-commit state): Deleted files (fully restored): - app/api/{automation,classification_rules,comments,sharing}.py - app/middleware/upload_rate_limit.py - app/tasks/{automation_tasks,classify_document}.py - app/utils/{automation_hooks,classification_rules}.py - docs/AppleAppStoreCompliance.md - frontend/input.css, package.json, package-lock.json, tailwind.config.js - frontend/static/js/{annotations,claim,comments,sharing}.js - frontend/templates/{admin_connections,file_annotations,file_summary}.html - tests/{test_api_files_comprehensive,test_auth_extended,test_sharing, test_comments,test_connections,test_imap_profiles,test_api_sessions, test_automation,test_classification_rules,test_api_advanced_filters, test_api_classification_rules,test_upload_rate_limit,test_api_dropbox, test_classify_document,test_comments_ui,test_upload_to_icloud, test_api_onedrive_comprehensive,test_frontend_build,test_sentry, test_diagnostic,test_database,test_views_dropbox,test_local_auth}.py Truncated files (content restored): - app/{auth,config,main,models,celery_worker,database}.py - app/api/{__init__,api_tokens,diagnostic,dropbox,files,google_drive, integrations,local_auth,mobile,onedrive,pipelines,qr_auth, settings,url_upload}.py - app/middleware/upload_rate_limit.py - app/tasks/upload_to_nextcloud.py - app/utils/{allowed_types,settings_service,settings_sync,user_scope,webhook}.py - app/views/{base,dropbox,files,google_drive,onedrive,settings}.py - docs/{API,AuthenticationSetup,ConfigurationGuide,DatabaseConfiguration, DeploymentGuide,DropboxSetup,GoogleDriveSetup,KubernetesDeployment, MobileApp,OneDriveSetup,ProductionReadiness,SentrySetup, SocialLoginSetup,UserGuide}.md - frontend/static/{js/upload.js,styles.css} - frontend/templates/{api_tokens,base,devices,dropbox,dropbox_callback, file_view,files,google_drive,onedrive,onedrive_callback, signup}.html - frontend/translations/en.json - migrations/env.py - tests/{conftest,test_api_integrations,test_api_mobile,test_api_settings, test_api_tokens,test_audit_logs,test_duplicates,test_imap_tasks, test_setup_wizard,test_views_files_comprehensive}.py Security fixes kept from post-d2217531 commits: - app/utils/network.py: DNS SSRF fail-secure fix (06b0fced) - app/utils/file_operations.py: path traversal fix (1018ea17) - tests/test_imap_tasks.py: re-applied 4 is_private_ip mock patches Co-authored-by: christianlouis <361235+christianlouis@users.noreply.github.com> Agent-Logs-Url: https://github.com/christianlouis/DocuElevate/sessions/51133dd8-9bec-41ab-aa10-3de753634187
131 lines
5.6 KiB
Python
131 lines
5.6 KiB
Python
"""
|
|
Worker settings synchronisation helper.
|
|
|
|
When an admin saves a configuration change through the UI, any running Celery
|
|
workers still hold the *old* values in their in-process ``settings`` singleton.
|
|
This module provides two complementary mechanisms to propagate the change:
|
|
|
|
1. **Publish** (API side): :func:`notify_settings_updated` writes a monotonically
|
|
increasing timestamp to a Redis key. This is called immediately after every
|
|
successful ``save_setting_to_db`` / ``delete_setting_from_db`` operation.
|
|
|
|
2. **Subscribe** (worker side): :func:`register_settings_reload_signal` installs
|
|
a Celery ``task_prerun`` signal handler. Before each task begins the handler
|
|
reads the Redis version key; if it has changed since the last reload it calls
|
|
:func:`~app.utils.config_loader.reload_settings_from_db` so the worker picks
|
|
up the new values *before* executing the task body.
|
|
|
|
The Redis key used is ``docuelevate:settings_version``. Workers cache the last
|
|
seen version in a module-level variable to avoid redundant DB round-trips when
|
|
nothing has changed.
|
|
"""
|
|
|
|
import logging
|
|
import time
|
|
from typing import Any
|
|
|
|
import redis
|
|
from celery.signals import task_prerun
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
#: Redis key that stores the current settings "version" (epoch timestamp string).
|
|
SETTINGS_VERSION_KEY = "docuelevate:settings_version"
|
|
|
|
#: Module-level cache: the settings version seen by *this* process on its last reload.
|
|
_last_seen_version: str = ""
|
|
|
|
|
|
def notify_settings_updated() -> None:
|
|
"""
|
|
Publish a settings-updated signal by updating the Redis version key, and
|
|
immediately reload the in-process ``settings`` singleton so the API
|
|
process serves fresh values without a restart.
|
|
|
|
Call this after every successful settings write so that all worker
|
|
processes know they need to reload their in-memory configuration.
|
|
|
|
Errors are caught and logged rather than raised so that a Redis
|
|
connectivity issue does not prevent the primary save from succeeding.
|
|
"""
|
|
try:
|
|
from app.config import settings
|
|
|
|
r = redis.from_url(settings.redis_url, socket_connect_timeout=2)
|
|
version = str(time.time())
|
|
r.set(SETTINGS_VERSION_KEY, version)
|
|
logger.debug(f"Settings version bumped to {version}")
|
|
except Exception as exc:
|
|
logger.warning(f"Could not publish settings update to Redis: {exc}")
|
|
|
|
# Reload the in-process settings singleton immediately so the API node
|
|
# returns updated values (e.g. oauth_provider_name on the login page)
|
|
# without needing a restart. Workers use the task_prerun signal handler
|
|
# instead, so this only affects the API/web process.
|
|
try:
|
|
from app.config import settings
|
|
from app.utils.config_loader import reload_settings_from_db
|
|
|
|
reload_settings_from_db(settings)
|
|
logger.debug("In-process settings reloaded after settings update")
|
|
except Exception as exc:
|
|
logger.warning(f"Could not reload in-process settings: {exc}")
|
|
|
|
# Re-register OAuth / social-login providers so that any provider whose
|
|
# credentials were just saved (or updated) in the database is active
|
|
# immediately on the login page — no restart required.
|
|
try:
|
|
from app.auth import refresh_social_providers
|
|
|
|
refresh_social_providers()
|
|
except Exception as exc:
|
|
logger.warning(f"Could not refresh social login providers after settings update: {exc}")
|
|
|
|
# Re-check OCR language availability in the background whenever settings
|
|
# are updated. This ensures that if a user changes tesseract_language or
|
|
# easyocr_languages via the UI, the new language data is downloaded without
|
|
# requiring a container restart.
|
|
try:
|
|
from app.utils.ocr_language_manager import ensure_ocr_languages_async
|
|
|
|
ensure_ocr_languages_async()
|
|
except Exception as exc:
|
|
logger.warning(f"Could not schedule OCR language check: {exc}")
|
|
|
|
|
|
def register_settings_reload_signal() -> None:
|
|
"""
|
|
Install a Celery ``task_prerun`` signal handler for worker processes.
|
|
|
|
This should be called once during Celery worker initialisation (e.g. from
|
|
``celery_worker.py``). After registration, every task will check the
|
|
settings version key in Redis before it starts and reload configuration
|
|
from the database if a newer version is detected.
|
|
"""
|
|
|
|
@task_prerun.connect(weak=False)
|
|
def _reload_if_stale(sender: Any, **kwargs: Any) -> None:
|
|
"""Reload settings from DB if the Redis version key has changed."""
|
|
global _last_seen_version
|
|
try:
|
|
from app.config import settings
|
|
from app.utils.config_loader import reload_settings_from_db
|
|
|
|
r = redis.from_url(settings.redis_url, socket_connect_timeout=2)
|
|
current_version = (r.get(SETTINGS_VERSION_KEY) or b"").decode()
|
|
if current_version and current_version != _last_seen_version:
|
|
reload_settings_from_db(settings)
|
|
_last_seen_version = current_version
|
|
logger.info(f"Worker settings reloaded (version={current_version})")
|
|
# Ensure OCR language data is up to date after a settings reload.
|
|
try:
|
|
from app.utils.ocr_language_manager import ensure_ocr_languages_async
|
|
|
|
ensure_ocr_languages_async()
|
|
except Exception as lang_exc:
|
|
logger.warning(f"Could not schedule OCR language check on worker: {lang_exc}")
|
|
except Exception as exc:
|
|
logger.debug(f"Settings version check skipped: {exc}")
|
|
|
|
logger.info("Settings reload signal handler registered on task_prerun")
|