Exemplo n.º 1
0
 def test_multiple_bad_keys(self):
     self.assertEqual(
         base.check_secret_key_fallbacks(None),
         [
             Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[1]", id=base.W025.id),
             Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[2]", id=base.W025.id),
         ],
     )
Exemplo n.º 2
0
 def test_insecure_secret_key_fallbacks(self):
     self.assertEqual(
         base.check_secret_key_fallbacks(None),
         [
             Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[0]", id=base.W025.id),
         ],
     )
Exemplo n.º 3
0
 def test_no_secret_key_fallbacks(self):
     with self.settings(SECRET_KEY_FALLBACKS=None):
         del settings.SECRET_KEY_FALLBACKS
         self.assertEqual(base.check_secret_key_fallbacks(None), [
             Warning(base.W025.msg % 'SECRET_KEY_FALLBACKS',
                     id=base.W025.id),
         ])
Exemplo n.º 4
0
 def test_low_length_secret_key_fallbacks(self):
     self.assertEqual(
         len(settings.SECRET_KEY_FALLBACKS[0]),
         base.SECRET_KEY_MIN_LENGTH - 1,
     )
     self.assertEqual(base.check_secret_key_fallbacks(None), [
         Warning(base.W025.msg % 'SECRET_KEY_FALLBACKS[0]',
                 id=base.W025.id),
     ])
Exemplo n.º 5
0
 def test_low_entropy_secret_key_fallbacks(self):
     self.assertGreater(
         len(settings.SECRET_KEY_FALLBACKS[0]),
         base.SECRET_KEY_MIN_LENGTH,
     )
     self.assertLess(
         len(set(settings.SECRET_KEY_FALLBACKS[0])),
         base.SECRET_KEY_MIN_UNIQUE_CHARACTERS,
     )
     self.assertEqual(base.check_secret_key_fallbacks(None), [
         Warning(base.W025.msg % 'SECRET_KEY_FALLBACKS[0]',
                 id=base.W025.id),
     ])
Exemplo n.º 6
0
    def add_handler(
        self, logger: str, filename: str, level: str = "WARN", formatter=None, **kwargs
    ):
        """Add a handler to a logger.
        The name of the added handler is unique, so the definition of the handler is also add if required.
        You can use "ROOT" as logger name to target the root logger.

        filename: can be a filename or one of the following special values: "stderr", "stdout", "logd", "syslog"
        """
        if filename == "stderr":
            handler_name = "%s.%s" % (filename, level.lower())
            if formatter in ("django.server", "colorized") and not self.stderr.isatty():
                formatter = None
            elif formatter:
                handler_name += ".%s" % formatter
            handler = {
                "class": "logging.StreamHandler",
                "level": level,
                "stream": "ext://sys.stderr",
                "formatter": formatter,
            }
        elif filename == "stdout":
            handler_name = "%s.%s" % (filename, level.lower())
            if formatter in ("django.server", "colorized") and not self.stdout.isatty():
                formatter = None
            elif formatter:
                handler_name += ".%s" % formatter
            handler = {
                "class": "logging.StreamHandler",
                "level": level,
                "stream": "ext://sys.stdout",
                "formatter": formatter,
            }
        elif filename == "syslog":
            handler_name = "%s.%s" % (filename, level.lower())
            handler = {"class": "logging.handlers.SysLogHandler", "level": level}
            handler.update(kwargs)
        elif filename == "logd":
            try:
                # noinspection PyUnresolvedReferences,PyPackageRequirements
                import systemd.journal
            except ImportError:
                warning = Warning(
                    "Unable to import systemd.journal (required to log with journlad)",
                    hint=None,
                    obj="configuration",
                )
                settings_check_results.append(warning)
                # replace logd by writing to a plain-text log
                self.add_handler(logger, level.lower(), level=level)
                return
            handler_name = "%s.%s" % (filename, level.lower())
            handler = {"class": "systemd.journal.JournalHandler", "level": level}
            handler.update(kwargs)
        else:  # basename of a plain-text log
            log_directory = os.path.normpath(self.log_directory)
            if not os.path.isdir(log_directory):
                if not self.log_directory_warning:
                    warning = Warning(
                        'Missing directory "%s"'
                        % log_directory,
                        hint=None,
                        obj=log_directory,
                    )
                    settings_check_results.append(warning)
                    self.log_directory_warning = True
                self.add_handler(logger, "stdout", level=level, **kwargs)
                return
            basename = "%s-%s.log" % (self.log_suffix, filename)
            log_filename = os.path.join(log_directory, basename)
            try:
                remove = not os.path.exists(log_filename)
                open(log_filename, "a").close()  # ok, we can write
                if (
                    remove
                ):  # but if this file did not exist, we remove it to avoid lot of empty log files...
                    os.remove(log_filename)
            except PermissionError:
                warning_ = Warning(
                    'Unable to write logs in "%s". Unsufficient rights?'
                    % log_directory,
                    hint=None,
                    obj=log_directory,
                )
                settings_check_results.append(warning_)
                self.add_handler(logger, "stdout", level=level, **kwargs)
                return
            handler_name = "%s.%s" % (self.log_suffix, filename)
            handler = {
                "class": "logging.handlers.RotatingFileHandler",
                "maxBytes": 1000000,
                "backupCount": 3,
                "formatter": "nocolor",
                "filename": log_filename,
                "level": level,
                "delay": True,
            }

        if not handler_name:
            return
        if handler_name not in self.handlers:
            self.handlers[handler_name] = handler
        if logger == "ROOT":
            target = self.root
        else:
            target = self.loggers[logger]
        if handler_name not in target["handlers"]:
            target["handlers"].append(handler_name)