__init__.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.security
  4. ~~~~~~~~~~~~~~~
  5. Module implementing the signing message serializer.
  6. """
  7. from __future__ import absolute_import
  8. from kombu.serialization import registry
  9. from celery import current_app
  10. from celery.exceptions import ImproperlyConfigured
  11. from .serialization import register_auth
  12. SSL_NOT_INSTALLED = """\
  13. You need to install the pyOpenSSL library to use the auth serializer.
  14. Please install by:
  15. $ pip install pyOpenSSL
  16. """
  17. SETTING_MISSING = """\
  18. Sorry, but you have to configure the
  19. * CELERY_SECURITY_KEY
  20. * CELERY_SECURITY_CERTIFICATE, and the
  21. * CELERY_SECURITY_CERT_STORE
  22. configuration settings to use the auth serializer.
  23. Please see the configuration reference for more information.
  24. """
  25. def disable_untrusted_serializers(whitelist=None):
  26. for name in set(registry._decoders) - set(whitelist or []):
  27. registry.disable(name)
  28. def setup_security(allowed_serializers=None, key=None, cert=None, store=None,
  29. digest='sha1', serializer='json'):
  30. """Setup the message-signing serializer.
  31. Disables untrusted serializers and if configured to use the ``auth``
  32. serializer will register the auth serializer with the provided settings
  33. into the Kombu serializer registry.
  34. :keyword allowed_serializers: List of serializer names, or content_types
  35. that should be exempt from being disabled.
  36. :keyword key: Name of private key file to use.
  37. Defaults to the :setting:`CELERY_SECURITY_KEY` setting.
  38. :keyword cert: Name of certificate file to use.
  39. Defaults to the :setting:`CELERY_SECURITY_CERTIFICATE` setting.
  40. :keyword store: Directory containing certificates.
  41. Defaults to the :setting:`CELERY_SECURITY_CERT_STORE` setting.
  42. :keyword digest: Digest algorithm used when signing messages.
  43. Default is ``sha1``.
  44. :keyword serializer: Serializer used to encode messages after
  45. they have been signed. See :setting:`CELERY_TASK_SERIALIZER` for
  46. the serializers supported.
  47. Default is ``json``.
  48. """
  49. disable_untrusted_serializers(allowed_serializers)
  50. conf = current_app.conf
  51. if conf.CELERY_TASK_SERIALIZER != 'auth':
  52. return
  53. try:
  54. from OpenSSL import crypto # noqa
  55. except ImportError:
  56. raise ImproperlyConfigured(SSL_NOT_INSTALLED)
  57. key = key or conf.CELERY_SECURITY_KEY
  58. cert = cert or conf.CELERY_SECURITY_CERTIFICATE
  59. store = store or conf.CELERY_SECURITY_CERT_STORE
  60. if not (key and cert and store):
  61. raise ImproperlyConfigured(SETTING_MISSING)
  62. with open(key) as kf:
  63. with open(cert) as cf:
  64. register_auth(kf.read(), cf.read(), store)