__init__.py 2.7 KB

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