merge certbot-apache and certbot-nginx into certbot (#10522)

based on the suggestion @bmw made in #10484, this moves nearly
everything from `certbot-apache` and `certbot-nginx` into subdirectories
in `certbot/src/certbot/_internal`, and corresponding "extra"
dependencies are made for the certbot distribution. in their place,
entrypoint shims are made in the old distributions.

this way, installing `certbot[nginx]` will pull in the extra
dependencies needed for the nginx code, and also pull in the shim in
`certbot-nginx`, letting our plugin discovery system work just as it did
before. ditto for apache.

note that this doesn't yet deprecate anything, which was one of the
primary goals of the original issue -- i spun out that work into #10521

fixes #10484

---------

Co-authored-by: Brad Warren <bmw@users.noreply.github.com>
Co-authored-by: ohemorange <erica@eff.org>
This commit is contained in:
Will Greenberg
2026-03-23 18:09:04 -07:00
committed by GitHub
co-authored by Brad Warren ohemorange
parent 9599364837
commit 6f1c0b0abd
309 changed files with 700 additions and 648 deletions
-3
View File
@@ -1,8 +1,5 @@
include LICENSE.txt include LICENSE.txt
include README.rst include README.rst
recursive-include src/certbot_apache/_internal/augeas_lens *.aug
recursive-include src/certbot_apache/_internal/tls_configs *.conf
recursive-include src/certbot_apache/_internal/tests/testdata *
include src/certbot_apache/py.typed include src/certbot_apache/py.typed
global-exclude __pycache__ global-exclude __pycache__
global-exclude *.py[cod] global-exclude *.py[cod]
-8
View File
@@ -32,14 +32,6 @@ classifiers = [
"Topic :: Utilities", "Topic :: Utilities",
] ]
[project.optional-dependencies]
dev = [
"apacheconfig>=0.3.2",
]
test = [
"pytest",
]
[project.entry-points."certbot.plugins"] [project.entry-points."certbot.plugins"]
apache = "certbot_apache._internal.entrypoint:ENTRYPOINT" apache = "certbot_apache._internal.entrypoint:ENTRYPOINT"
+2 -4
View File
@@ -3,12 +3,10 @@ from setuptools import setup
version = '5.5.0.dev0' version = '5.5.0.dev0'
install_requires = [ install_requires = [
# We specify the minimum acme and certbot version as the current plugin # We specify the minimum certbot version as the current plugin
# version for simplicity. See # version for simplicity. See
# https://github.com/certbot/certbot/issues/8761 for more info. # https://github.com/certbot/certbot/issues/8761 for more info.
f'acme>={version}', f'certbot[apache]>={version}',
f'certbot>={version}',
'python-augeas',
] ]
setup( setup(
@@ -1,69 +1,6 @@
""" Entry point for Apache Plugin """ """ Entry point for Apache Plugin """
from certbot import util import certbot.plugins.apache
from certbot_apache._internal import configurator
from certbot_apache._internal import override_alpine
from certbot_apache._internal import override_arch
from certbot_apache._internal import override_centos
from certbot_apache._internal import override_darwin
from certbot_apache._internal import override_debian
from certbot_apache._internal import override_fedora
from certbot_apache._internal import override_gentoo
from certbot_apache._internal import override_suse
from certbot_apache._internal import override_void
OVERRIDE_CLASSES: dict[str, type[configurator.ApacheConfigurator]] = {
"alpine": override_alpine.AlpineConfigurator,
"arch": override_arch.ArchConfigurator,
"cloudlinux": override_centos.CentOSConfigurator,
"darwin": override_darwin.DarwinConfigurator,
"debian": override_debian.DebianConfigurator,
"ubuntu": override_debian.DebianConfigurator,
"centos": override_centos.CentOSConfigurator,
"centos linux": override_centos.CentOSConfigurator,
"fedora_old": override_centos.CentOSConfigurator,
"fedora": override_fedora.FedoraConfigurator,
"linuxmint": override_debian.DebianConfigurator,
"ol": override_centos.CentOSConfigurator,
"oracle": override_centos.CentOSConfigurator,
"redhatenterpriseserver": override_centos.CentOSConfigurator,
"red hat enterprise linux server": override_centos.CentOSConfigurator,
"rhel": override_centos.CentOSConfigurator,
"amazon": override_centos.CentOSConfigurator,
"gentoo": override_gentoo.GentooConfigurator,
"gentoo base system": override_gentoo.GentooConfigurator,
"opensuse": override_suse.OpenSUSEConfigurator,
"suse": override_suse.OpenSUSEConfigurator,
"sles": override_suse.OpenSUSEConfigurator,
"scientific": override_centos.CentOSConfigurator,
"scientific linux": override_centos.CentOSConfigurator,
"void": override_void.VoidConfigurator,
}
def get_configurator() -> type[configurator.ApacheConfigurator]: ENTRYPOINT = certbot.plugins.apache.ENTRYPOINT
""" Get correct configurator class based on the OS fingerprint """
os_name, os_version = util.get_os_info()
os_name = os_name.lower()
override_class = None
# Special case for older Fedora versions
min_version = util.parse_loose_version('29')
if os_name == 'fedora' and util.parse_loose_version(os_version) < min_version:
os_name = 'fedora_old'
try:
override_class = OVERRIDE_CLASSES[os_name]
except KeyError:
# OS not found in the list
os_like = util.get_systemd_os_like()
if os_like:
for os_name in os_like:
override_class = OVERRIDE_CLASSES.get(os_name)
if not override_class:
# No override class found, return the generic configurator
override_class = configurator.ApacheConfigurator
return override_class
ENTRYPOINT = get_configurator()
@@ -1 +0,0 @@
"""certbot-apache tests"""
@@ -2,10 +2,10 @@
# Avoid false warnings because certbot packages are not installed in the thread that executes # Avoid false warnings because certbot packages are not installed in the thread that executes
# the coverage: indeed, certbot is launched as a CLI from a subprocess. # the coverage: indeed, certbot is launched as a CLI from a subprocess.
disable_warnings = module-not-imported,no-data-collected disable_warnings = module-not-imported,no-data-collected
omit = **/*_test.py,**/tests/*,**/dns_common*,**/certbot_nginx/_internal/parser_obj.py omit = **/*_test.py,**/tests/*,**/dns_common*,**/certbot/_internal/plugins/nginx/parser_obj.py
patch = subprocess patch = subprocess
parallel = True parallel = True
[report] [report]
# Exclude unit tests in coverage during integration tests. # Exclude unit tests in coverage during integration tests.
omit = **/*_test.py,**/tests/*,**/dns_common*,**/certbot_nginx/_internal/parser_obj.py omit = **/*_test.py,**/tests/*,**/dns_common*,**/certbot/_internal/plugins/nginx/parser_obj.py
+1 -1
View File
@@ -4,7 +4,7 @@ Right now, this is data for the roundtrip test (checking that the parser
can parse each file and that the reserialized config file it generates is can parse each file and that the reserialized config file it generates is
identical to the original). identical to the original).
If run in a virtualenv or otherwise so that certbot_nginx can be imported, If run in a virtualenv or otherwise so that certbot can be imported,
the roundtrip test can run as the roundtrip test can run as
python roundtrip.py nginx-roundtrip-testdata python roundtrip.py nginx-roundtrip-testdata
@@ -3,7 +3,7 @@
import os import os
import sys import sys
from certbot_nginx._internal import nginxparser from certbot._internal.plugins.nginx import nginxparser
def roundtrip(stuff): def roundtrip(stuff):
@@ -24,7 +24,7 @@ class Proxy(configurators_common.Proxy):
self.modules = self.server_root = self.test_conf = self.version = None self.modules = self.server_root = self.test_conf = self.version = None
patch = mock.patch( patch = mock.patch(
"certbot_apache._internal.configurator.display_ops.select_vhost") "certbot._internal.plugins.apache.configurator.display_ops.select_vhost")
mock_display = patch.start() mock_display = patch.start()
mock_display.side_effect = le_errors.PluginError( mock_display.side_effect = le_errors.PluginError(
"Unable to determine vhost") "Unable to determine vhost")
@@ -4,11 +4,11 @@ import shutil
import subprocess import subprocess
from certbot import configuration from certbot import configuration
from certbot._internal.plugins.nginx import configurator
from certbot._internal.plugins.nginx import constants
from certbot_compatibility_test import errors from certbot_compatibility_test import errors
from certbot_compatibility_test import util from certbot_compatibility_test import util
from certbot_compatibility_test.configurators import common as configurators_common from certbot_compatibility_test.configurators import common as configurators_common
from certbot_nginx._internal import configurator
from certbot_nginx._internal import constants
class Proxy(configurators_common.Proxy): class Proxy(configurators_common.Proxy):
-2
View File
@@ -1,7 +1,5 @@
include LICENSE.txt include LICENSE.txt
include README.rst include README.rst
recursive-include src/certbot_nginx/_internal/tls_configs *.conf
recursive-include src/certbot_nginx/_internal/tests/testdata *
include src/certbot_nginx/py.typed include src/certbot_nginx/py.typed
global-exclude __pycache__ global-exclude __pycache__
global-exclude *.py[cod] global-exclude *.py[cod]
+1 -1
View File
@@ -38,7 +38,7 @@ test = [
] ]
[project.entry-points."certbot.plugins"] [project.entry-points."certbot.plugins"]
nginx = "certbot_nginx._internal.configurator:NginxConfigurator" nginx = "certbot_nginx._internal.entrypoint:ENTRYPOINT"
[project.urls] [project.urls]
Homepage = "https://github.com/certbot/certbot" Homepage = "https://github.com/certbot/certbot"
+2 -7
View File
@@ -3,15 +3,10 @@ from setuptools import setup
version = '5.5.0.dev0' version = '5.5.0.dev0'
install_requires = [ install_requires = [
# We specify the minimum acme and certbot version as the current plugin # We specify the minimum certbot version as the current plugin
# version for simplicity. See # version for simplicity. See
# https://github.com/certbot/certbot/issues/8761 for more info. # https://github.com/certbot/certbot/issues/8761 for more info.
f'acme>={version}', f'certbot[nginx]>={version}',
f'certbot>={version}',
# PyOpenSSL>=25.0.0 is just needed to satisfy mypy right now so this dependency can probably be
# relaxed to >=24.0.0 if needed.
'PyOpenSSL>=25.0.0',
'pyparsing>=3.0.0',
] ]
setup( setup(
@@ -0,0 +1,6 @@
""" Entry point for Nginx Plugin """
import certbot.plugins.nginx
ENTRYPOINT = certbot.plugins.nginx.ENTRYPOINT
@@ -1 +0,0 @@
"""certbot-nginx tests"""
+5
View File
@@ -4,6 +4,11 @@ include LICENSE.txt
recursive-include docs * recursive-include docs *
recursive-include examples * recursive-include examples *
recursive-include src/certbot/tests/testdata * recursive-include src/certbot/tests/testdata *
recursive-include src/certbot/_internal/plugins/nginx/tls_configs *.conf
recursive-include src/certbot/_internal/tests/plugins/nginx/testdata *
recursive-include src/certbot/_internal/plugins/apache/augeas_lens *.aug
recursive-include src/certbot/_internal/plugins/apache/tls_configs *.conf
recursive-include src/certbot/_internal/tests/plugins/apache/testdata *
include src/certbot/ssl-dhparams.pem include src/certbot/ssl-dhparams.pem
include src/certbot/py.typed include src/certbot/py.typed
global-exclude __pycache__ global-exclude __pycache__
+2 -2
View File
@@ -99,7 +99,7 @@ Apache
------ ------
The Apache plugin currently `supports The Apache plugin currently `supports
<https://github.com/certbot/certbot/blob/main/certbot-apache/src/certbot_apache/_internal/entrypoint.py>`_ <https://github.com/certbot/certbot/blob/main/certbot/src/certbot/_internal/plugins/apache/entrypoint.py>`_
modern OSes based on Debian, Fedora, SUSE, Gentoo, CentOS and Darwin. modern OSes based on Debian, Fedora, SUSE, Gentoo, CentOS and Darwin.
This automates both obtaining *and* installing certificates on an Apache This automates both obtaining *and* installing certificates on an Apache
webserver. To specify this plugin on the command line, simply include webserver. To specify this plugin on the command line, simply include
@@ -1248,7 +1248,7 @@ Configuration file
Certbot accepts a global configuration file that applies its options to all invocations Certbot accepts a global configuration file that applies its options to all invocations
of Certbot. Certificate-specific configuration choices are stored in the ``.conf`` of Certbot. Certificate-specific configuration choices are stored in the ``.conf``
files that can be found in ``/etc/letsencrypt/renewal``. See files that can be found in ``/etc/letsencrypt/renewal``. See
`Modifying the Renewal Configuration of Existing Certificates`_ for more information `Modifying the Renewal Configuration of Existing Certificates`_ for more information
about modifying certificate-specific options. Note that it is not recommended to modify about modifying certificate-specific options. Note that it is not recommended to modify
these certificate-specific renewal configuration files manually. these certificate-specific renewal configuration files manually.
+1 -46
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "certbot" name = "certbot"
dynamic = ["version", "dependencies"] dynamic = ["version", "dependencies", "optional-dependencies"]
description = "ACME client" description = "ACME client"
readme = "README.rst" readme = "README.rst"
license = "Apache-2.0" license = "Apache-2.0"
@@ -32,51 +32,6 @@ classifiers = [
"Topic :: Utilities", "Topic :: Utilities",
] ]
[project.optional-dependencies]
dev = [
"azure-devops",
"build",
"ipdb",
# allows us to use newer urllib3 https://github.com/python-poetry/poetry-plugin-export/issues/183
"poetry-plugin-export>=1.9.0",
# poetry 1.2.0+ is required for it to pin pip, setuptools, and wheel. See
# https://github.com/python-poetry/poetry/issues/1584.
"poetry>=1.2.0",
"towncrier",
"twine",
]
docs = [
# If you have Sphinx<1.5.1, you need docutils<0.13.1
# https://github.com/sphinx-doc/sphinx/issues/3212
"Sphinx>=1.2", # Annotation support
"sphinx_rtd_theme",
]
# Tools like pip, wheel, and tox are listed here to ensure they are properly
# pinned and installed during automated testing.
test = [
"coverage",
"mypy",
"pip",
"pylint",
"pytest",
"pytest-cov>=4.1.0", # https://github.com/pytest-dev/pytest-cov/pull/558
"pytest-xdist",
"ruff",
"setuptools",
"tox",
"types-httplib2",
"types-pyRFC3339",
"types-pywin32",
"types-requests",
"types-setuptools",
"uv",
"wheel",
]
all = [
"certbot[dev,docs,test]"
]
[project.scripts] [project.scripts]
certbot = "certbot.main:main" certbot = "certbot.main:main"
+60
View File
@@ -40,7 +40,67 @@ install_requires = [
'pywin32>=300 ; sys_platform == "win32"', 'pywin32>=300 ; sys_platform == "win32"',
] ]
extras_require = {
"dev": [
"apacheconfig>=0.3.2",
"azure-devops",
"build",
"ipdb",
# allows us to use newer urllib3 https://github.com/python-poetry/poetry-plugin-export/issues/183
"poetry-plugin-export>=1.9.0",
# poetry 1.2.0+ is required for it to pin pip, setuptools, and wheel. See
# https://github.com/python-poetry/poetry/issues/1584.
"poetry>=1.2.0",
"towncrier",
"twine",
],
"docs": [
# If you have Sphinx<1.5.1, you need docutils<0.13.1
# https://github.com/sphinx-doc/sphinx/issues/3212
"Sphinx>=1.2", # Annotation support
"sphinx_rtd_theme",
],
# Tools like pip, wheel, and tox are listed here to ensure they are properly
# pinned and installed during automated testing.
"test": [
"coverage",
"mypy",
"pip",
"pylint",
"pytest",
"pytest-cov>=4.1.0", # https://github.com/pytest-dev/pytest-cov/pull/558
"pytest-xdist",
"ruff",
"setuptools",
"tox",
"types-httplib2",
"types-pyRFC3339",
"types-pywin32",
"types-requests",
"types-setuptools",
"uv",
"wheel",
],
"apache": [
# If a user installs `certbot[apache]`, we want to include the shim
f'certbot-apache>={version}',
'python-augeas',
],
"nginx": [
# If a user installs `certbot[nginx]`, we want to include the shim
f'certbot-nginx>={version}',
# PyOpenSSL>=25.0.0 is just needed to satisfy mypy right now so this dependency can probably be
# relaxed to >=24.0.0 if needed.
'PyOpenSSL>=25.0.0',
'pyparsing>=3.0.0',
],
"all": [
"certbot[dev,docs,test,apache,nginx]"
],
}
setup( setup(
install_requires=install_requires, install_requires=install_requires,
extras_require=extras_require,
) )
@@ -248,6 +248,7 @@ def find_ssl_apache_conf(prefix: str) -> str:
""" """
file_manager = ExitStack() file_manager = ExitStack()
atexit.register(file_manager.close) atexit.register(file_manager.close)
ref = (importlib.resources.files("certbot_apache").joinpath("_internal") ref = (importlib.resources.files("certbot").joinpath("_internal")
.joinpath("tls_configs").joinpath("{0}-options-ssl-apache.conf".format(prefix))) .joinpath("plugins").joinpath("apache").joinpath("tls_configs")
.joinpath("{0}-options-ssl-apache.conf".format(prefix)))
return str(file_manager.enter_context(importlib.resources.as_file(ref))) return str(file_manager.enter_context(importlib.resources.as_file(ref)))
@@ -3,10 +3,10 @@ from typing import Any
from typing import Iterable from typing import Iterable
from typing import Optional from typing import Optional
from certbot_apache._internal import assertions from certbot._internal.plugins.apache import assertions
from certbot_apache._internal import interfaces from certbot._internal.plugins.apache import interfaces
from certbot_apache._internal import parsernode_util as util from certbot._internal.plugins.apache import parsernode_util as util
from certbot_apache._internal.interfaces import ParserNode from certbot._internal.plugins.apache.interfaces import ParserNode
class ApacheParserNode(interfaces.ParserNode): class ApacheParserNode(interfaces.ParserNode):
@@ -5,11 +5,11 @@ from typing import Iterable
from typing import Optional from typing import Optional
from typing import Union from typing import Union
from certbot_apache._internal import interfaces from certbot._internal.plugins.apache import interfaces
from certbot_apache._internal.interfaces import CommentNode from certbot._internal.plugins.apache.interfaces import CommentNode
from certbot_apache._internal.interfaces import DirectiveNode from certbot._internal.plugins.apache.interfaces import DirectiveNode
from certbot_apache._internal.interfaces import ParserNode from certbot._internal.plugins.apache.interfaces import ParserNode
from certbot_apache._internal.obj import VirtualHost from certbot._internal.plugins.apache.obj import VirtualHost
PASS = "CERTBOT_PASS_ASSERT" PASS = "CERTBOT_PASS_ASSERT"
@@ -72,11 +72,11 @@ from typing import Union
from certbot import errors from certbot import errors
from certbot.compat import os from certbot.compat import os
from certbot_apache._internal import apache_util from certbot._internal.plugins.apache import apache_util
from certbot_apache._internal import assertions from certbot._internal.plugins.apache import assertions
from certbot_apache._internal import interfaces from certbot._internal.plugins.apache import interfaces
from certbot_apache._internal import parser from certbot._internal.plugins.apache import parser
from certbot_apache._internal import parsernode_util as util from certbot._internal.plugins.apache import parsernode_util as util
class AugeasParserNode(interfaces.ParserNode): class AugeasParserNode(interfaces.ParserNode):
@@ -26,15 +26,15 @@ from certbot.interfaces import RenewableCert
from certbot.plugins import common from certbot.plugins import common
from certbot.plugins.enhancements import AutoHSTSEnhancement from certbot.plugins.enhancements import AutoHSTSEnhancement
from certbot.plugins.util import path_surgery from certbot.plugins.util import path_surgery
from certbot_apache._internal import apache_util from certbot._internal.plugins.apache import apache_util
from certbot_apache._internal import assertions from certbot._internal.plugins.apache import assertions
from certbot_apache._internal import constants from certbot._internal.plugins.apache import constants
from certbot_apache._internal import display_ops from certbot._internal.plugins.apache import display_ops
from certbot_apache._internal import dualparser from certbot._internal.plugins.apache import dualparser
from certbot_apache._internal import http_01 from certbot._internal.plugins.apache import http_01
from certbot_apache._internal import obj from certbot._internal.plugins.apache import obj
from certbot_apache._internal import parser from certbot._internal.plugins.apache import parser
from certbot_apache._internal.apacheparser import ApacheBlockNode from certbot._internal.plugins.apache.apacheparser import ApacheBlockNode
try: try:
import apacheconfig import apacheconfig
@@ -126,11 +126,11 @@ class ApacheConfigurator(common.Configurator):
:type config: certbot.configuration.NamespaceConfig :type config: certbot.configuration.NamespaceConfig
:ivar parser: Handles low level parsing :ivar parser: Handles low level parsing
:type parser: :class:`~certbot_apache._internal.parser` :type parser: :class:`~certbot._internal.plugins.apache.parser`
:ivar tup version: version of Apache :ivar tup version: version of Apache
:ivar list vhosts: All vhosts found in the configuration :ivar list vhosts: All vhosts found in the configuration
(:class:`list` of :class:`~certbot_apache._internal.obj.VirtualHost`) (:class:`list` of :class:`~certbot._internal.plugins.apache.obj.VirtualHost`)
:ivar dict assoc: Mapping between domains and vhosts :ivar dict assoc: Mapping between domains and vhosts
@@ -542,7 +542,7 @@ class ApacheConfigurator(common.Configurator):
counterpart, should one get created counterpart, should one get created
:returns: List of VirtualHosts or None :returns: List of VirtualHosts or None
:rtype: `list` of :class:`~certbot_apache._internal.obj.VirtualHost` :rtype: `list` of :class:`~certbot._internal.plugins.apache.obj.VirtualHost`
""" """
if util.is_wildcard_domain(domain): if util.is_wildcard_domain(domain):
@@ -720,7 +720,7 @@ class ApacheConfigurator(common.Configurator):
counterpart, should one get created counterpart, should one get created
:returns: vhost associated with name :returns: vhost associated with name
:rtype: :class:`~certbot_apache._internal.obj.VirtualHost` :rtype: :class:`~certbot._internal.plugins.apache.obj.VirtualHost`
:raises .errors.PluginError: If no vhost is available or chosen :raises .errors.PluginError: If no vhost is available or chosen
@@ -823,7 +823,8 @@ class ApacheConfigurator(common.Configurator):
:param str target_name: domain handled by the desired vhost :param str target_name: domain handled by the desired vhost
:param vhosts: vhosts to consider :param vhosts: vhosts to consider
:type vhosts: `collections.Iterable` of :class:`~certbot_apache._internal.obj.VirtualHost` :type vhosts: `collections.Iterable` of
:class:`~certbot._internal.plugins.apache.obj.VirtualHost`
:param bool filter_defaults: whether a vhost with a _default_ :param bool filter_defaults: whether a vhost with a _default_
addr is acceptable addr is acceptable
@@ -965,7 +966,7 @@ class ApacheConfigurator(common.Configurator):
"""Helper function for get_virtual_hosts(). """Helper function for get_virtual_hosts().
:param host: In progress vhost whose names will be added :param host: In progress vhost whose names will be added
:type host: :class:`~certbot_apache._internal.obj.VirtualHost` :type host: :class:`~certbot._internal.plugins.apache.obj.VirtualHost`
""" """
@@ -984,7 +985,7 @@ class ApacheConfigurator(common.Configurator):
:param str path: Augeas path to virtual host :param str path: Augeas path to virtual host
:returns: newly created vhost :returns: newly created vhost
:rtype: :class:`~certbot_apache._internal.obj.VirtualHost` :rtype: :class:`~certbot._internal.plugins.apache.obj.VirtualHost`
""" """
addrs: set[obj.Addr] = set() addrs: set[obj.Addr] = set()
@@ -1050,7 +1051,7 @@ class ApacheConfigurator(common.Configurator):
def get_virtual_hosts_v1(self) -> list[obj.VirtualHost]: def get_virtual_hosts_v1(self) -> list[obj.VirtualHost]:
"""Returns list of virtual hosts found in the Apache configuration. """Returns list of virtual hosts found in the Apache configuration.
:returns: List of :class:`~certbot_apache._internal.obj.VirtualHost` :returns: List of :class:`~certbot._internal.plugins.apache.obj.VirtualHost`
objects found in configuration objects found in configuration
:rtype: list :rtype: list
@@ -1103,7 +1104,7 @@ class ApacheConfigurator(common.Configurator):
def get_virtual_hosts_v2(self) -> list[obj.VirtualHost]: def get_virtual_hosts_v2(self) -> list[obj.VirtualHost]:
"""Returns list of virtual hosts found in the Apache configuration using """Returns list of virtual hosts found in the Apache configuration using
ParserNode interface. ParserNode interface.
:returns: List of :class:`~certbot_apache.obj.VirtualHost` :returns: List of :class:`~certbot._internal.plugins.apache.obj.VirtualHost`
objects found in configuration objects found in configuration
:rtype: list :rtype: list
""" """
@@ -1122,7 +1123,7 @@ class ApacheConfigurator(common.Configurator):
interfaces. interfaces.
:param ApacheBlockNode node: The BlockNode object of VirtualHost block :param ApacheBlockNode node: The BlockNode object of VirtualHost block
:returns: newly created vhost :returns: newly created vhost
:rtype: :class:`~certbot_apache.obj.VirtualHost` :rtype: :class:`~certbot._internal.plugins.apache.obj.VirtualHost`
""" """
addrs = set() addrs = set()
for param in node.parameters: for param in node.parameters:
@@ -1164,7 +1165,7 @@ class ApacheConfigurator(common.Configurator):
def _populate_vhost_names_v2(self, vhost: obj.VirtualHost) -> None: def _populate_vhost_names_v2(self, vhost: obj.VirtualHost) -> None:
"""Helper function that populates the VirtualHost names. """Helper function that populates the VirtualHost names.
:param host: In progress vhost whose names will be added :param host: In progress vhost whose names will be added
:type host: :class:`~certbot_apache.obj.VirtualHost` :type host: :class:`~certbot._internal.plugins.apache.obj.VirtualHost`
""" """
if not vhost.node: if not vhost.node:
raise errors.PluginError("Current VirtualHost has no node.") # pragma: no cover raise errors.PluginError("Current VirtualHost has no node.") # pragma: no cover
@@ -1352,10 +1353,10 @@ class ApacheConfigurator(common.Configurator):
.. note:: This function saves the configuration .. note:: This function saves the configuration
:param nonssl_vhost: Valid VH that doesn't have SSLEngine on :param nonssl_vhost: Valid VH that doesn't have SSLEngine on
:type nonssl_vhost: :class:`~certbot_apache._internal.obj.VirtualHost` :type nonssl_vhost: :class:`~certbot._internal.plugins.apache.obj.VirtualHost`
:returns: SSL vhost :returns: SSL vhost
:rtype: :class:`~certbot_apache._internal.obj.VirtualHost` :rtype: :class:`~certbot._internal.plugins.apache.obj.VirtualHost`
:raises .errors.PluginError: If more than one virtual host is in :raises .errors.PluginError: If more than one virtual host is in
the file or if plugin is unable to write/read vhost files. the file or if plugin is unable to write/read vhost files.
@@ -1720,7 +1721,7 @@ class ApacheConfigurator(common.Configurator):
:param str id_str: Id string for matching :param str id_str: Id string for matching
:returns: The matched VirtualHost :returns: The matched VirtualHost
:rtype: :class:`~certbot_apache._internal.obj.VirtualHost` :rtype: :class:`~certbot._internal.plugins.apache.obj.VirtualHost`
:raises .errors.PluginError: If no VirtualHost is found :raises .errors.PluginError: If no VirtualHost is found
""" """
@@ -1737,7 +1738,7 @@ class ApacheConfigurator(common.Configurator):
used for keeping track of VirtualHost directive over time. used for keeping track of VirtualHost directive over time.
:param vhost: Virtual host to add the id :param vhost: Virtual host to add the id
:type vhost: :class:`~certbot_apache._internal.obj.VirtualHost` :type vhost: :class:`~certbot._internal.plugins.apache.obj.VirtualHost`
:returns: The unique ID or None :returns: The unique ID or None
:rtype: str or None :rtype: str or None
@@ -1759,7 +1760,7 @@ class ApacheConfigurator(common.Configurator):
If ID already exists, returns that instead. If ID already exists, returns that instead.
:param vhost: Virtual host to add or find the id :param vhost: Virtual host to add or find the id
:type vhost: :class:`~certbot_apache._internal.obj.VirtualHost` :type vhost: :class:`~certbot._internal.plugins.apache.obj.VirtualHost`
:returns: The unique ID for vhost :returns: The unique ID for vhost
:rtype: str or None :rtype: str or None
@@ -1840,7 +1841,7 @@ class ApacheConfigurator(common.Configurator):
"""Increase the AutoHSTS max-age value """Increase the AutoHSTS max-age value
:param vhost: Virtual host object to modify :param vhost: Virtual host object to modify
:type vhost: :class:`~certbot_apache._internal.obj.VirtualHost` :type vhost: :class:`~certbot._internal.plugins.apache.obj.VirtualHost`
:param str id_str: The unique ID string of VirtualHost :param str id_str: The unique ID string of VirtualHost
@@ -1923,7 +1924,7 @@ class ApacheConfigurator(common.Configurator):
.. note:: This function saves the configuration .. note:: This function saves the configuration
:param ssl_vhost: Destination of traffic, an ssl enabled vhost :param ssl_vhost: Destination of traffic, an ssl enabled vhost
:type ssl_vhost: :class:`~certbot_apache._internal.obj.VirtualHost` :type ssl_vhost: :class:`~certbot._internal.plugins.apache.obj.VirtualHost`
:param unused_options: Not currently used :param unused_options: Not currently used
:type unused_options: Not Available :type unused_options: Not Available
@@ -1969,7 +1970,7 @@ class ApacheConfigurator(common.Configurator):
.. note:: This function saves the configuration .. note:: This function saves the configuration
:param ssl_vhost: Destination of traffic, an ssl enabled vhost :param ssl_vhost: Destination of traffic, an ssl enabled vhost
:type ssl_vhost: :class:`~certbot_apache._internal.obj.VirtualHost` :type ssl_vhost: :class:`~certbot._internal.plugins.apache.obj.VirtualHost`
:param header_substring: string that uniquely identifies a header. :param header_substring: string that uniquely identifies a header.
e.g: Strict-Transport-Security, Upgrade-Insecure-Requests. e.g: Strict-Transport-Security, Upgrade-Insecure-Requests.
@@ -2003,7 +2004,7 @@ class ApacheConfigurator(common.Configurator):
contains the string header_substring. contains the string header_substring.
:param ssl_vhost: vhost to check :param ssl_vhost: vhost to check
:type vhost: :class:`~certbot_apache._internal.obj.VirtualHost` :type vhost: :class:`~certbot._internal.plugins.apache.obj.VirtualHost`
:param header_substring: string that uniquely identifies a header. :param header_substring: string that uniquely identifies a header.
e.g: Strict-Transport-Security, Upgrade-Insecure-Requests. e.g: Strict-Transport-Security, Upgrade-Insecure-Requests.
@@ -2040,7 +2041,7 @@ class ApacheConfigurator(common.Configurator):
.. note:: This function saves the configuration .. note:: This function saves the configuration
:param ssl_vhost: Destination of traffic, an ssl enabled vhost :param ssl_vhost: Destination of traffic, an ssl enabled vhost
:type ssl_vhost: :class:`~certbot_apache._internal.obj.VirtualHost` :type ssl_vhost: :class:`~certbot._internal.plugins.apache.obj.VirtualHost`
:param unused_options: Not currently used :param unused_options: Not currently used
:type unused_options: Not Available :type unused_options: Not Available
@@ -2120,7 +2121,7 @@ class ApacheConfigurator(common.Configurator):
delete certbot's old rewrite rules and set the new one instead. delete certbot's old rewrite rules and set the new one instead.
:param vhost: vhost to check :param vhost: vhost to check
:type vhost: :class:`~certbot_apache._internal.obj.VirtualHost` :type vhost: :class:`~certbot._internal.plugins.apache.obj.VirtualHost`
:raises errors.PluginEnhancementAlreadyPresent: When the exact :raises errors.PluginEnhancementAlreadyPresent: When the exact
certbot redirection WriteRule exists in virtual host. certbot redirection WriteRule exists in virtual host.
@@ -2159,7 +2160,7 @@ class ApacheConfigurator(common.Configurator):
"""Checks if there exists a RewriteRule directive in vhost """Checks if there exists a RewriteRule directive in vhost
:param vhost: vhost to check :param vhost: vhost to check
:type vhost: :class:`~certbot_apache._internal.obj.VirtualHost` :type vhost: :class:`~certbot._internal.plugins.apache.obj.VirtualHost`
:returns: True if a RewriteRule directive exists. :returns: True if a RewriteRule directive exists.
:rtype: bool :rtype: bool
@@ -2173,7 +2174,7 @@ class ApacheConfigurator(common.Configurator):
"""Checks if a RewriteEngine directive is on """Checks if a RewriteEngine directive is on
:param vhost: vhost to check :param vhost: vhost to check
:type vhost: :class:`~certbot_apache._internal.obj.VirtualHost` :type vhost: :class:`~certbot._internal.plugins.apache.obj.VirtualHost`
""" """
rewrite_engine_path_list = self.parser.find_dir("RewriteEngine", "on", start=vhost.path) rewrite_engine_path_list = self.parser.find_dir("RewriteEngine", "on", start=vhost.path)
@@ -2189,7 +2190,7 @@ class ApacheConfigurator(common.Configurator):
"""Creates an http_vhost specifically to redirect for the ssl_vhost. """Creates an http_vhost specifically to redirect for the ssl_vhost.
:param ssl_vhost: ssl vhost :param ssl_vhost: ssl vhost
:type ssl_vhost: :class:`~certbot_apache._internal.obj.VirtualHost` :type ssl_vhost: :class:`~certbot._internal.plugins.apache.obj.VirtualHost`
""" """
text = self._get_redirect_config_str(ssl_vhost) text = self._get_redirect_config_str(ssl_vhost)
@@ -2308,7 +2309,7 @@ class ApacheConfigurator(common.Configurator):
of this method where available. of this method where available.
:param vhost: vhost to enable :param vhost: vhost to enable
:type vhost: :class:`~certbot_apache._internal.obj.VirtualHost` :type vhost: :class:`~certbot._internal.plugins.apache.obj.VirtualHost`
:raises .errors.NotSupportedError: If filesystem layout is not :raises .errors.NotSupportedError: If filesystem layout is not
supported. supported.
@@ -2569,7 +2570,7 @@ class ApacheConfigurator(common.Configurator):
"""Do the initial AutoHSTS deployment to a vhost """Do the initial AutoHSTS deployment to a vhost
:param ssl_vhost: The VirtualHost object to deploy the AutoHSTS :param ssl_vhost: The VirtualHost object to deploy the AutoHSTS
:type ssl_vhost: :class:`~certbot_apache._internal.obj.VirtualHost` or None :type ssl_vhost: :class:`~certbot._internal.plugins.apache.obj.VirtualHost` or None
:raises errors.PluginEnhancementAlreadyPresent: When already enhanced :raises errors.PluginEnhancementAlreadyPresent: When already enhanced
@@ -44,7 +44,8 @@ def _generate_augeas_lens_dir_static() -> str:
# Python process, and will be automatically cleaned up on exit. # Python process, and will be automatically cleaned up on exit.
file_manager = ExitStack() file_manager = ExitStack()
atexit.register(file_manager.close) atexit.register(file_manager.close)
augeas_lens_dir_ref = importlib.resources.files("certbot_apache") / "_internal" / "augeas_lens" augeas_lens_dir_ref = importlib.resources.files("certbot") / "_internal" \
/ "plugins" / "apache" / "augeas_lens"
return str(file_manager.enter_context(importlib.resources.as_file(augeas_lens_dir_ref))) return str(file_manager.enter_context(importlib.resources.as_file(augeas_lens_dir_ref)))
AUGEAS_LENS_DIR = _generate_augeas_lens_dir_static() AUGEAS_LENS_DIR = _generate_augeas_lens_dir_static()
@@ -7,7 +7,7 @@ from typing import Sequence
from certbot import errors from certbot import errors
from certbot.compat import os from certbot.compat import os
from certbot.display import util as display_util from certbot.display import util as display_util
from certbot_apache._internal.obj import VirtualHost from certbot._internal.plugins.apache.obj import VirtualHost
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -83,7 +83,7 @@ def _vhost_menu(domain: str, vhosts: Iterable[VirtualHost]) -> tuple[str, int]:
if free_chars < 2: if free_chars < 2:
logger.debug("Display size is too small for " logger.debug("Display size is too small for "
"certbot_apache._internal.display_ops._vhost_menu()") "certbot._internal.plugins.apache.display_ops._vhost_menu()")
# This runs the edge off the screen, but it doesn't cause an "error" # This runs the edge off the screen, but it doesn't cause an "error"
filename_size = 1 filename_size = 1
disp_name_size = 1 disp_name_size = 1
@@ -6,14 +6,14 @@ from typing import Optional
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from typing import TypeVar from typing import TypeVar
from certbot_apache._internal import apacheparser from certbot._internal.plugins.apache import apacheparser
from certbot_apache._internal import assertions from certbot._internal.plugins.apache import assertions
from certbot_apache._internal import augeasparser from certbot._internal.plugins.apache import augeasparser
from certbot_apache._internal import interfaces from certbot._internal.plugins.apache import interfaces
if TYPE_CHECKING: if TYPE_CHECKING:
from certbot_apache._internal.apacheparser import ApacheParserNode # pragma: no cover from certbot._internal.plugins.apache.apacheparser import ApacheParserNode # pragma: no cover
from certbot_apache._internal.augeasparser import AugeasParserNode # pragma: no cover from certbot._internal.plugins.apache.augeasparser import AugeasParserNode # pragma: no cover
GenericAugeasParserNode = TypeVar("GenericAugeasParserNode", bound="AugeasParserNode") GenericAugeasParserNode = TypeVar("GenericAugeasParserNode", bound="AugeasParserNode")
GenericApacheParserNode = TypeVar("GenericApacheParserNode", bound="ApacheParserNode") GenericApacheParserNode = TypeVar("GenericApacheParserNode", bound="ApacheParserNode")
@@ -0,0 +1,66 @@
""" Entry point for Apache Plugin """
from certbot import util
from certbot._internal.plugins.apache import configurator
from certbot._internal.plugins.apache import override_alpine
from certbot._internal.plugins.apache import override_arch
from certbot._internal.plugins.apache import override_centos
from certbot._internal.plugins.apache import override_darwin
from certbot._internal.plugins.apache import override_debian
from certbot._internal.plugins.apache import override_fedora
from certbot._internal.plugins.apache import override_gentoo
from certbot._internal.plugins.apache import override_suse
from certbot._internal.plugins.apache import override_void
OVERRIDE_CLASSES: dict[str, type[configurator.ApacheConfigurator]] = {
"alpine": override_alpine.AlpineConfigurator,
"arch": override_arch.ArchConfigurator,
"cloudlinux": override_centos.CentOSConfigurator,
"darwin": override_darwin.DarwinConfigurator,
"debian": override_debian.DebianConfigurator,
"ubuntu": override_debian.DebianConfigurator,
"centos": override_centos.CentOSConfigurator,
"centos linux": override_centos.CentOSConfigurator,
"fedora_old": override_centos.CentOSConfigurator,
"fedora": override_fedora.FedoraConfigurator,
"linuxmint": override_debian.DebianConfigurator,
"ol": override_centos.CentOSConfigurator,
"oracle": override_centos.CentOSConfigurator,
"redhatenterpriseserver": override_centos.CentOSConfigurator,
"red hat enterprise linux server": override_centos.CentOSConfigurator,
"rhel": override_centos.CentOSConfigurator,
"amazon": override_centos.CentOSConfigurator,
"gentoo": override_gentoo.GentooConfigurator,
"gentoo base system": override_gentoo.GentooConfigurator,
"opensuse": override_suse.OpenSUSEConfigurator,
"suse": override_suse.OpenSUSEConfigurator,
"sles": override_suse.OpenSUSEConfigurator,
"scientific": override_centos.CentOSConfigurator,
"scientific linux": override_centos.CentOSConfigurator,
"void": override_void.VoidConfigurator,
}
def get_configurator() -> type[configurator.ApacheConfigurator]:
""" Get correct configurator class based on the OS fingerprint """
os_name, os_version = util.get_os_info()
os_name = os_name.lower()
override_class = None
# Special case for older Fedora versions
min_version = util.parse_loose_version('29')
if os_name == 'fedora' and util.parse_loose_version(os_version) < min_version:
os_name = 'fedora_old'
try:
override_class = OVERRIDE_CLASSES[os_name]
except KeyError:
# OS not found in the list
os_like = util.get_systemd_os_like()
if os_like:
for os_name in os_like:
override_class = OVERRIDE_CLASSES.get(os_name)
if not override_class:
# No override class found, return the generic configurator
override_class = configurator.ApacheConfigurator
return override_class
@@ -10,11 +10,11 @@ from certbot.achallenges import KeyAuthorizationAnnotatedChallenge
from certbot.compat import filesystem from certbot.compat import filesystem
from certbot.compat import os from certbot.compat import os
from certbot.plugins import common from certbot.plugins import common
from certbot_apache._internal.obj import VirtualHost from certbot._internal.plugins.apache.obj import VirtualHost
from certbot_apache._internal.parser import get_aug_path from certbot._internal.plugins.apache.parser import get_aug_path
if TYPE_CHECKING: if TYPE_CHECKING:
from certbot_apache._internal.configurator import ApacheConfigurator # pragma: no cover from certbot._internal.plugins.apache.configurator import ApacheConfigurator # pragma: no cover
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -6,9 +6,9 @@ from typing import Optional
from typing import Union from typing import Union
from certbot.plugins import common from certbot.plugins import common
from certbot_apache._internal.apacheparser import ApacheBlockNode from certbot._internal.plugins.apache.apacheparser import ApacheBlockNode
from certbot_apache._internal.augeasparser import AugeasBlockNode from certbot._internal.plugins.apache.augeasparser import AugeasBlockNode
from certbot_apache._internal.dualparser import DualBlockNode from certbot._internal.plugins.apache.dualparser import DualBlockNode
class Addr(common.Addr): class Addr(common.Addr):
@@ -27,7 +27,7 @@ class Addr(common.Addr):
return False return False
def __repr__(self) -> str: def __repr__(self) -> str:
return f"certbot_apache._internal.obj.Addr({repr(self.tup)})" return f"certbot._internal.plugins.apache.obj.Addr({repr(self.tup)})"
def __hash__(self) -> int: # pylint: disable=useless-super-delegation def __hash__(self) -> int: # pylint: disable=useless-super-delegation
# Python 3 requires explicit overridden for __hash__ if __eq__ or # Python 3 requires explicit overridden for __hash__ if __eq__ or
@@ -1,6 +1,6 @@
""" Distribution specific override class for Alpine Linux """ """ Distribution specific override class for Alpine Linux """
from certbot_apache._internal import configurator from certbot._internal.plugins.apache import configurator
from certbot_apache._internal.configurator import OsOptions from certbot._internal.plugins.apache.configurator import OsOptions
class AlpineConfigurator(configurator.ApacheConfigurator): class AlpineConfigurator(configurator.ApacheConfigurator):
@@ -1,6 +1,6 @@
""" Distribution specific override class for Arch Linux """ """ Distribution specific override class for Arch Linux """
from certbot_apache._internal import configurator from certbot._internal.plugins.apache import configurator
from certbot_apache._internal.configurator import OsOptions from certbot._internal.plugins.apache.configurator import OsOptions
class ArchConfigurator(configurator.ApacheConfigurator): class ArchConfigurator(configurator.ApacheConfigurator):
@@ -4,10 +4,10 @@ from typing import Any
from certbot import errors from certbot import errors
from certbot import util from certbot import util
from certbot_apache._internal import apache_util from certbot._internal.plugins.apache import apache_util
from certbot_apache._internal import configurator from certbot._internal.plugins.apache import configurator
from certbot_apache._internal import parser from certbot._internal.plugins.apache import parser
from certbot_apache._internal.configurator import OsOptions from certbot._internal.plugins.apache.configurator import OsOptions
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -1,6 +1,6 @@
""" Distribution specific override class for macOS """ """ Distribution specific override class for macOS """
from certbot_apache._internal import configurator from certbot._internal.plugins.apache import configurator
from certbot_apache._internal.configurator import OsOptions from certbot._internal.plugins.apache.configurator import OsOptions
class DarwinConfigurator(configurator.ApacheConfigurator): class DarwinConfigurator(configurator.ApacheConfigurator):
@@ -5,10 +5,10 @@ from certbot import errors
from certbot import util from certbot import util
from certbot.compat import filesystem from certbot.compat import filesystem
from certbot.compat import os from certbot.compat import os
from certbot_apache._internal import apache_util from certbot._internal.plugins.apache import apache_util
from certbot_apache._internal import configurator from certbot._internal.plugins.apache import configurator
from certbot_apache._internal.configurator import OsOptions from certbot._internal.plugins.apache.configurator import OsOptions
from certbot_apache._internal.obj import VirtualHost from certbot._internal.plugins.apache.obj import VirtualHost
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -30,7 +30,7 @@ class DebianConfigurator(configurator.ApacheConfigurator):
modules are enabled appropriately. modules are enabled appropriately.
:param vhost: vhost to enable :param vhost: vhost to enable
:type vhost: :class:`~certbot_apache._internal.obj.VirtualHost` :type vhost: :class:`~certbot._internal.plugins.apache.obj.VirtualHost`
:raises .errors.NotSupportedError: If filesystem layout is not :raises .errors.NotSupportedError: If filesystem layout is not
supported. supported.
@@ -3,10 +3,10 @@ from typing import Any
from certbot import errors from certbot import errors
from certbot import util from certbot import util
from certbot_apache._internal import apache_util from certbot._internal.plugins.apache import apache_util
from certbot_apache._internal import configurator from certbot._internal.plugins.apache import configurator
from certbot_apache._internal import parser from certbot._internal.plugins.apache import parser
from certbot_apache._internal.configurator import OsOptions from certbot._internal.plugins.apache.configurator import OsOptions
class FedoraConfigurator(configurator.ApacheConfigurator): class FedoraConfigurator(configurator.ApacheConfigurator):
@@ -1,10 +1,10 @@
""" Distribution specific override class for Gentoo Linux """ """ Distribution specific override class for Gentoo Linux """
from typing import Any from typing import Any
from certbot_apache._internal import apache_util from certbot._internal.plugins.apache import apache_util
from certbot_apache._internal import configurator from certbot._internal.plugins.apache import configurator
from certbot_apache._internal import parser from certbot._internal.plugins.apache import parser
from certbot_apache._internal.configurator import OsOptions from certbot._internal.plugins.apache.configurator import OsOptions
class GentooConfigurator(configurator.ApacheConfigurator): class GentooConfigurator(configurator.ApacheConfigurator):
@@ -1,6 +1,6 @@
""" Distribution specific override class for OpenSUSE """ """ Distribution specific override class for OpenSUSE """
from certbot_apache._internal import configurator from certbot._internal.plugins.apache import configurator
from certbot_apache._internal.configurator import OsOptions from certbot._internal.plugins.apache.configurator import OsOptions
class OpenSUSEConfigurator(configurator.ApacheConfigurator): class OpenSUSEConfigurator(configurator.ApacheConfigurator):
@@ -1,6 +1,6 @@
""" Distribution specific override class for Void Linux """ """ Distribution specific override class for Void Linux """
from certbot_apache._internal import configurator from certbot._internal.plugins.apache import configurator
from certbot_apache._internal.configurator import OsOptions from certbot._internal.plugins.apache.configurator import OsOptions
class VoidConfigurator(configurator.ApacheConfigurator): class VoidConfigurator(configurator.ApacheConfigurator):
@@ -12,11 +12,11 @@ from typing import Union
from certbot import errors from certbot import errors
from certbot.compat import os from certbot.compat import os
from certbot_apache._internal import apache_util from certbot._internal.plugins.apache import apache_util
from certbot_apache._internal import constants from certbot._internal.plugins.apache import constants
if TYPE_CHECKING: if TYPE_CHECKING:
from certbot_apache._internal.configurator import ApacheConfigurator # pragma: no cover from certbot._internal.plugins.apache.configurator import ApacheConfigurator # pragma: no cover
try: try:
from augeas import Augeas from augeas import Augeas
@@ -3,7 +3,7 @@ from typing import Any
from typing import Iterable from typing import Iterable
from typing import Optional from typing import Optional
from certbot_apache._internal.interfaces import ParserNode from certbot._internal.plugins.apache.interfaces import ParserNode
def validate_kwargs(kwargs: dict[str, Any], required_names: Iterable[str]) -> dict[str, Any]: def validate_kwargs(kwargs: dict[str, Any], required_names: Iterable[str]) -> dict[str, Any]:
@@ -25,12 +25,12 @@ from certbot import util
from certbot.compat import os from certbot.compat import os
from certbot.display import util as display_util from certbot.display import util as display_util
from certbot.plugins import common from certbot.plugins import common
from certbot_nginx._internal import constants from certbot._internal.plugins.nginx import constants
from certbot_nginx._internal import display_ops from certbot._internal.plugins.nginx import display_ops
from certbot_nginx._internal import http_01 from certbot._internal.plugins.nginx import http_01
from certbot_nginx._internal import nginxparser from certbot._internal.plugins.nginx import nginxparser
from certbot_nginx._internal import obj from certbot._internal.plugins.nginx import obj
from certbot_nginx._internal import parser from certbot._internal.plugins.nginx import parser
NAME_RANK = 0 NAME_RANK = 0
START_WILDCARD_RANK = 1 START_WILDCARD_RANK = 1
@@ -52,7 +52,7 @@ class NginxConfigurator(common.Configurator):
:type config: certbot.configuration.NamespaceConfig :type config: certbot.configuration.NamespaceConfig
:ivar parser: Handles low level parsing :ivar parser: Handles low level parsing
:type parser: :class:`~certbot_nginx._internal.parser` :type parser: :class:`~certbot._internal.plugins.nginx.parser`
:ivar str save_notes: Human-readable config change notes :ivar str save_notes: Human-readable config change notes
@@ -173,8 +173,9 @@ class NginxConfigurator(common.Configurator):
file_manager = ExitStack() file_manager = ExitStack()
atexit.register(file_manager.close) atexit.register(file_manager.close)
ref = (importlib.resources.files("certbot_nginx").joinpath("_internal") ref = (importlib.resources.files("certbot").joinpath("_internal")
.joinpath("tls_configs").joinpath(config_filename)) .joinpath("plugins").joinpath("nginx").joinpath("tls_configs")
.joinpath(config_filename))
return str(file_manager.enter_context(importlib.resources.as_file(ref))) return str(file_manager.enter_context(importlib.resources.as_file(ref)))
@@ -348,7 +349,7 @@ class NginxConfigurator(common.Configurator):
:param str target_name: domain name :param str target_name: domain name
:returns: ssl vhosts associated with name :returns: ssl vhosts associated with name
:rtype: list of :class:`~certbot_nginx._internal.obj.VirtualHost` :rtype: list of :class:`~certbot._internal.plugins.nginx.obj.VirtualHost`
""" """
return [vhost for vhost in self._choose_vhosts_common(target_name) if vhost.ssl] return [vhost for vhost in self._choose_vhosts_common(target_name) if vhost.ssl]
@@ -369,7 +370,7 @@ class NginxConfigurator(common.Configurator):
:param str fullchain_path: certificates to use when creating SSL vhosts :param str fullchain_path: certificates to use when creating SSL vhosts
:returns: ssl vhosts associated with name :returns: ssl vhosts associated with name
:rtype: list of :class:`~certbot_nginx._internal.obj.VirtualHost` :rtype: list of :class:`~certbot._internal.plugins.nginx.obj.VirtualHost`
""" """
vhosts = self._choose_vhosts_common(target_name) vhosts = self._choose_vhosts_common(target_name)
@@ -478,7 +479,7 @@ class NginxConfigurator(common.Configurator):
:param list matches: list of dicts containing the vhost, the matching name, :param list matches: list of dicts containing the vhost, the matching name,
and the numerical rank and the numerical rank
:returns: the most matching vhost :returns: the most matching vhost
:rtype: :class:`~certbot_nginx._internal.obj.VirtualHost` :rtype: :class:`~certbot._internal.plugins.nginx.obj.VirtualHost`
""" """
if not matches: if not matches:
@@ -564,7 +565,7 @@ class NginxConfigurator(common.Configurator):
:param str port: port number :param str port: port number
:returns: vhosts associated with name :returns: vhosts associated with name
:rtype: list of :class:`~certbot_nginx._internal.obj.VirtualHost` :rtype: list of :class:`~certbot._internal.plugins.nginx.obj.VirtualHost`
""" """
if util.is_wildcard_domain(target_name): if util.is_wildcard_domain(target_name):
@@ -586,7 +587,7 @@ class NginxConfigurator(common.Configurator):
:param str target_name: non-wildcard domain name :param str target_name: non-wildcard domain name
:returns: tuple of HTTP and HTTPS virtualhosts :returns: tuple of HTTP and HTTPS virtualhosts
:rtype: tuple of :class:`~certbot_nginx._internal.obj.VirtualHost` :rtype: tuple of :class:`~certbot._internal.plugins.nginx.obj.VirtualHost`
""" """
vhosts = [m['vhost'] for m in self._get_ranked_matches(target_name) if m and 'vhost' in m] vhosts = [m['vhost'] for m in self._get_ranked_matches(target_name) if m and 'vhost' in m]
@@ -712,7 +713,7 @@ class NginxConfigurator(common.Configurator):
Make a server SSL by adding new listen and SSL directives. Make a server SSL by adding new listen and SSL directives.
:param vhost: The vhost to add SSL to. :param vhost: The vhost to add SSL to.
:type vhost: :class:`~certbot_nginx._internal.obj.VirtualHost` :type vhost: :class:`~certbot._internal.plugins.nginx.obj.VirtualHost`
:param str key_path: key to use for SSL :param str key_path: key to use for SSL
:param str fullchain_path: certificates to use for SSL :param str fullchain_path: certificates to use for SSL
@@ -868,9 +869,9 @@ class NginxConfigurator(common.Configurator):
:param vhost: The server block to break up into two. :param vhost: The server block to break up into two.
:param list only_directives: If this exists, only duplicate these directives :param list only_directives: If this exists, only duplicate these directives
when splitting the block. when splitting the block.
:type vhost: :class:`~certbot_nginx._internal.obj.VirtualHost` :type vhost: :class:`~certbot._internal.plugins.nginx.obj.VirtualHost`
:returns: tuple (http_vhost, https_vhost) :returns: tuple (http_vhost, https_vhost)
:rtype: tuple of type :class:`~certbot_nginx._internal.obj.VirtualHost` :rtype: tuple of type :class:`~certbot._internal.plugins.nginx.obj.VirtualHost`
""" """
http_vhost = self.parser.duplicate_vhost(vhost, only_directives=only_directives) http_vhost = self.parser.duplicate_vhost(vhost, only_directives=only_directives)
@@ -4,7 +4,7 @@ from typing import Iterable
from typing import Optional from typing import Optional
from certbot.display import util as display_util from certbot.display import util as display_util
from certbot_nginx._internal.obj import VirtualHost from certbot._internal.plugins.nginx.obj import VirtualHost
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -11,11 +11,11 @@ from certbot import errors
from certbot.achallenges import KeyAuthorizationAnnotatedChallenge from certbot.achallenges import KeyAuthorizationAnnotatedChallenge
from certbot.compat import os from certbot.compat import os
from certbot.plugins import common from certbot.plugins import common
from certbot_nginx._internal import nginxparser from certbot._internal.plugins.nginx import nginxparser
from certbot_nginx._internal.obj import Addr from certbot._internal.plugins.nginx.obj import Addr
if TYPE_CHECKING: if TYPE_CHECKING:
from certbot_nginx._internal.configurator import NginxConfigurator from certbot._internal.plugins.nginx.configurator import NginxConfigurator
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -146,7 +146,7 @@ class NginxHttp01(common.ChallengePerformer):
def _default_listen_addresses(self) -> list[Addr]: def _default_listen_addresses(self) -> list[Addr]:
"""Finds addresses for a challenge block to listen on. """Finds addresses for a challenge block to listen on.
:returns: list of :class:`certbot_nginx._internal.obj.Addr` to apply :returns: list of :class:`certbot._internal.plugins.nginx.obj.Addr` to apply
:rtype: list :rtype: list
""" """
addresses: list[Addr] = [] addresses: list[Addr] = []
@@ -136,7 +136,7 @@ class Addr(common.Addr):
def __hash__(self) -> int: # pylint: disable=useless-super-delegation def __hash__(self) -> int: # pylint: disable=useless-super-delegation
# Python 3 requires explicit overridden for __hash__ # Python 3 requires explicit overridden for __hash__
# See certbot-apache/src/certbot_apache/_internal/obj.py for more information # See certbot-apache/src/certbot._internal.plugins.apache/obj.py for more information
return super().__hash__() return super().__hash__()
def super_eq(self, other: "Addr") -> bool: def super_eq(self, other: "Addr") -> bool:
@@ -18,9 +18,9 @@ import pyparsing
from certbot import errors from certbot import errors
from certbot.compat import os from certbot.compat import os
from certbot_nginx._internal import nginxparser from certbot._internal.plugins.nginx import nginxparser
from certbot_nginx._internal import obj from certbot._internal.plugins.nginx import obj
from certbot_nginx._internal.nginxparser import UnspacedList from certbot._internal.plugins.nginx.nginxparser import UnspacedList
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -145,7 +145,7 @@ class NginxParser:
Technically this is a misnomer because Nginx does not have virtual Technically this is a misnomer because Nginx does not have virtual
hosts, it has 'server blocks'. hosts, it has 'server blocks'.
:returns: List of :class:`~certbot_nginx._internal.obj.VirtualHost` :returns: List of :class:`~certbot._internal.plugins.nginx.obj.VirtualHost`
objects found in configuration objects found in configuration
:rtype: list :rtype: list
@@ -286,7 +286,8 @@ class NginxParser:
def has_ssl_on_directive(self, vhost: obj.VirtualHost) -> bool: def has_ssl_on_directive(self, vhost: obj.VirtualHost) -> bool:
"""Does vhost have ssl on for all ports? """Does vhost have ssl on for all ports?
:param :class:`~certbot_nginx._internal.obj.VirtualHost` vhost: The vhost in question :param :class:`~certbot._internal.plugins.nginx.obj.VirtualHost`
vhost: The vhost in question
:returns: True if 'ssl on' directive is included :returns: True if 'ssl on' directive is included
:rtype: bool :rtype: bool
@@ -313,7 +314,7 @@ class NginxParser:
..todo :: Doesn't match server blocks whose server_name directives are ..todo :: Doesn't match server blocks whose server_name directives are
split across multiple conf files. split across multiple conf files.
:param :class:`~certbot_nginx._internal.obj.VirtualHost` vhost: The vhost :param :class:`~certbot._internal.plugins.nginx.obj.VirtualHost` vhost: The vhost
whose information we use to match on whose information we use to match on
:param list directives: The directives to add :param list directives: The directives to add
:param bool insert_at_top: True if the directives need to be inserted at the top :param bool insert_at_top: True if the directives need to be inserted at the top
@@ -336,7 +337,7 @@ class NginxParser:
..todo :: Doesn't match server blocks whose server_name directives are ..todo :: Doesn't match server blocks whose server_name directives are
split across multiple conf files. split across multiple conf files.
:param :class:`~certbot_nginx._internal.obj.VirtualHost` vhost: The vhost :param :class:`~certbot._internal.plugins.nginx.obj.VirtualHost` vhost: The vhost
whose information we use to match on whose information we use to match on
:param list directives: The directives to add :param list directives: The directives to add
:param bool insert_at_top: True if the directives need to be inserted at the top :param bool insert_at_top: True if the directives need to be inserted at the top
@@ -350,7 +351,7 @@ class NginxParser:
match_func: Optional[Callable[[Any], bool]] = None) -> None: match_func: Optional[Callable[[Any], bool]] = None) -> None:
"""Remove all directives of type directive_name. """Remove all directives of type directive_name.
:param :class:`~certbot_nginx._internal.obj.VirtualHost` vhost: The vhost :param :class:`~certbot._internal.plugins.nginx.obj.VirtualHost` vhost: The vhost
to remove directives from to remove directives from
:param string directive_name: The directive type to remove :param string directive_name: The directive type to remove
:param callable match_func: Function of the directive that returns true for directives :param callable match_func: Function of the directive that returns true for directives
@@ -389,7 +390,7 @@ class NginxParser:
only_directives: Optional[list[Any]] = None) -> obj.VirtualHost: only_directives: Optional[list[Any]] = None) -> obj.VirtualHost:
"""Duplicate the vhost in the configuration files. """Duplicate the vhost in the configuration files.
:param :class:`~certbot_nginx._internal.obj.VirtualHost` vhost_template: The vhost :param :class:`~certbot._internal.plugins.nginx.obj.VirtualHost` vhost_template: The vhost
whose information we copy whose information we copy
:param bool remove_singleton_listen_params: If we should remove parameters :param bool remove_singleton_listen_params: If we should remove parameters
from listen directives in the block that can only be used once per address from listen directives in the block that can only be used once per address
@@ -397,7 +398,7 @@ class NginxParser:
looks at first level of depth; does not expand includes. looks at first level of depth; does not expand includes.
:returns: A vhost object for the newly created vhost :returns: A vhost object for the newly created vhost
:rtype: :class:`~certbot_nginx._internal.obj.VirtualHost` :rtype: :class:`~certbot._internal.plugins.nginx.obj.VirtualHost`
""" """
# TODO: https://github.com/certbot/certbot/issues/5185 # TODO: https://github.com/certbot/certbot/issues/5185
# put it in the same file as the template, at the same level # put it in the same file as the template, at the same level
@@ -0,0 +1,7 @@
"""certbot-apache tests"""
import pytest
# Make sure we're only running these tests if our apache plugin dependencies are installed
pytest.importorskip("augeas")
@@ -5,9 +5,9 @@ from unittest import mock
import pytest import pytest
from certbot import errors from certbot import errors
from certbot_apache._internal import assertions from certbot._internal.plugins.apache import assertions
from certbot_apache._internal import augeasparser from certbot._internal.plugins.apache import augeasparser
from certbot_apache._internal.tests import util from certbot._internal.tests.plugins.apache import util
def _get_augeasnode_mock(filepath): def _get_augeasnode_mock(filepath):
@@ -28,7 +28,7 @@ class AugeasParserNodeTest(util.ApacheTest): # pylint: disable=too-many-public-
super().setUp() super().setUp()
with mock.patch( with mock.patch(
"certbot_apache._internal.configurator.ApacheConfigurator.get_parsernode_root" "certbot._internal.plugins.apache.configurator.ApacheConfigurator.get_parsernode_root"
) as mock_parsernode: ) as mock_parsernode:
mock_parsernode.side_effect = _get_augeasnode_mock( mock_parsernode.side_effect = _get_augeasnode_mock(
os.path.join(self.config_path, "apache2.conf")) os.path.join(self.config_path, "apache2.conf"))
@@ -40,19 +40,19 @@ class AugeasParserNodeTest(util.ApacheTest): # pylint: disable=too-many-public-
self.temp_dir, "debian_apache_2_4/multiple_vhosts") self.temp_dir, "debian_apache_2_4/multiple_vhosts")
def test_save(self): def test_save(self):
with mock.patch('certbot_apache._internal.parser.ApacheParser.save') as mock_save: with mock.patch('certbot._internal.plugins.apache.parser.ApacheParser.save') as mock_save:
self.config.parser_root.save("A save message") self.config.parser_root.save("A save message")
assert mock_save.called is True assert mock_save.called is True
assert mock_save.call_args[0][0] == "A save message" assert mock_save.call_args[0][0] == "A save message"
def test_unsaved_files(self): def test_unsaved_files(self):
with mock.patch('certbot_apache._internal.parser.ApacheParser.unsaved_files') as mock_uf: with mock.patch('certbot._internal.plugins.apache.parser.ApacheParser.unsaved_files') as mock_uf:
mock_uf.return_value = ["first", "second"] mock_uf.return_value = ["first", "second"]
files = self.config.parser_root.unsaved_files() files = self.config.parser_root.unsaved_files()
assert files == ["first", "second"] assert files == ["first", "second"]
def test_get_block_node_name(self): def test_get_block_node_name(self):
from certbot_apache._internal.augeasparser import AugeasBlockNode from certbot._internal.plugins.apache.augeasparser import AugeasBlockNode
block = AugeasBlockNode( block = AugeasBlockNode(
name=assertions.PASS, name=assertions.PASS,
ancestor=None, ancestor=None,
@@ -122,9 +122,9 @@ class AugeasParserNodeTest(util.ApacheTest): # pylint: disable=too-many-public-
assert "going_to_set_this" in names assert "going_to_set_this" in names
def test_set_parameters_atinit(self): def test_set_parameters_atinit(self):
from certbot_apache._internal.augeasparser import AugeasDirectiveNode from certbot._internal.plugins.apache.augeasparser import AugeasDirectiveNode
servernames = self.config.parser_root.find_directives("servername") servernames = self.config.parser_root.find_directives("servername")
setparam = "certbot_apache._internal.augeasparser.AugeasDirectiveNode.set_parameters" setparam = "certbot._internal.plugins.apache.augeasparser.AugeasDirectiveNode.set_parameters"
with mock.patch(setparam) as mock_set: with mock.patch(setparam) as mock_set:
AugeasDirectiveNode( AugeasDirectiveNode(
name=servernames[0].name, name=servernames[0].name,
@@ -252,7 +252,7 @@ class AugeasParserNodeTest(util.ApacheTest): # pylint: disable=too-many-public-
assert vh.metadata["augeaspath"].endswith("VirtualHost[2]") is True assert vh.metadata["augeaspath"].endswith("VirtualHost[2]") is True
def test_node_init_error_bad_augeaspath(self): def test_node_init_error_bad_augeaspath(self):
from certbot_apache._internal.augeasparser import AugeasBlockNode from certbot._internal.plugins.apache.augeasparser import AugeasBlockNode
parameters = { parameters = {
"name": assertions.PASS, "name": assertions.PASS,
"ancestor": None, "ancestor": None,
@@ -266,7 +266,7 @@ class AugeasParserNodeTest(util.ApacheTest): # pylint: disable=too-many-public-
AugeasBlockNode(**parameters) AugeasBlockNode(**parameters)
def test_node_init_error_missing_augeaspath(self): def test_node_init_error_missing_augeaspath(self):
from certbot_apache._internal.augeasparser import AugeasBlockNode from certbot._internal.plugins.apache.augeasparser import AugeasBlockNode
parameters = { parameters = {
"name": assertions.PASS, "name": assertions.PASS,
"ancestor": None, "ancestor": None,
@@ -1,5 +1,5 @@
# pylint: disable=too-many-lines # pylint: disable=too-many-lines
"""Test for certbot_apache._internal.configurator AutoHSTS functionality""" """Test for certbot._internal.plugins.apache.configurator AutoHSTS functionality"""
import re import re
import sys import sys
from unittest import mock from unittest import mock
@@ -7,8 +7,8 @@ from unittest import mock
import pytest import pytest
from certbot import errors from certbot import errors
from certbot_apache._internal import constants from certbot._internal.plugins.apache import constants
from certbot_apache._internal.tests import util from certbot._internal.tests.plugins.apache import util
class AutoHSTSTest(util.ApacheTest): class AutoHSTSTest(util.ApacheTest):
@@ -39,23 +39,23 @@ class AutoHSTSTest(util.ApacheTest):
head.replace("arg[3]", "arg[4]")) head.replace("arg[3]", "arg[4]"))
return None # pragma: no cover return None # pragma: no cover
@mock.patch("certbot_apache._internal.configurator.ApacheConfigurator.restart") @mock.patch("certbot._internal.plugins.apache.configurator.ApacheConfigurator.restart")
@mock.patch("certbot_apache._internal.configurator.ApacheConfigurator.enable_mod") @mock.patch("certbot._internal.plugins.apache.configurator.ApacheConfigurator.enable_mod")
def test_autohsts_enable_headers_mod(self, mock_enable, _restart): def test_autohsts_enable_headers_mod(self, mock_enable, _restart):
self.config.parser.modules.pop("headers_module", None) self.config.parser.modules.pop("headers_module", None)
self.config.parser.modules.pop("mod_header.c", None) self.config.parser.modules.pop("mod_header.c", None)
self.config.enable_autohsts(mock.MagicMock(), ["ocspvhost.com"]) self.config.enable_autohsts(mock.MagicMock(), ["ocspvhost.com"])
assert mock_enable.called is True assert mock_enable.called is True
@mock.patch("certbot_apache._internal.configurator.ApacheConfigurator.restart") @mock.patch("certbot._internal.plugins.apache.configurator.ApacheConfigurator.restart")
def test_autohsts_deploy_already_exists(self, _restart): def test_autohsts_deploy_already_exists(self, _restart):
self.config.enable_autohsts(mock.MagicMock(), ["ocspvhost.com"]) self.config.enable_autohsts(mock.MagicMock(), ["ocspvhost.com"])
with pytest.raises(errors.PluginEnhancementAlreadyPresent): with pytest.raises(errors.PluginEnhancementAlreadyPresent):
self.config.enable_autohsts(mock.MagicMock(), ["ocspvhost.com"]) self.config.enable_autohsts(mock.MagicMock(), ["ocspvhost.com"])
@mock.patch("certbot_apache._internal.constants.AUTOHSTS_FREQ", 0) @mock.patch("certbot._internal.plugins.apache.constants.AUTOHSTS_FREQ", 0)
@mock.patch("certbot_apache._internal.configurator.ApacheConfigurator.restart") @mock.patch("certbot._internal.plugins.apache.configurator.ApacheConfigurator.restart")
@mock.patch("certbot_apache._internal.configurator.ApacheConfigurator.prepare") @mock.patch("certbot._internal.plugins.apache.configurator.ApacheConfigurator.prepare")
def test_autohsts_increase(self, mock_prepare, _mock_restart): def test_autohsts_increase(self, mock_prepare, _mock_restart):
self.config._prepared = False self.config._prepared = False
maxage = "\"max-age={0}\"" maxage = "\"max-age={0}\""
@@ -73,8 +73,8 @@ class AutoHSTSTest(util.ApacheTest):
inc_val inc_val
assert mock_prepare.called is True assert mock_prepare.called is True
@mock.patch("certbot_apache._internal.configurator.ApacheConfigurator.restart") @mock.patch("certbot._internal.plugins.apache.configurator.ApacheConfigurator.restart")
@mock.patch("certbot_apache._internal.configurator.ApacheConfigurator._autohsts_increase") @mock.patch("certbot._internal.plugins.apache.configurator.ApacheConfigurator._autohsts_increase")
def test_autohsts_increase_noop(self, mock_increase, _restart): def test_autohsts_increase_noop(self, mock_increase, _restart):
maxage = "\"max-age={0}\"" maxage = "\"max-age={0}\""
initial_val = maxage.format(constants.AUTOHSTS_STEPS[0]) initial_val = maxage.format(constants.AUTOHSTS_STEPS[0])
@@ -88,8 +88,8 @@ class AutoHSTSTest(util.ApacheTest):
assert mock_increase.called is False assert mock_increase.called is False
@mock.patch("certbot_apache._internal.configurator.ApacheConfigurator.restart") @mock.patch("certbot._internal.plugins.apache.configurator.ApacheConfigurator.restart")
@mock.patch("certbot_apache._internal.constants.AUTOHSTS_FREQ", 0) @mock.patch("certbot._internal.plugins.apache.constants.AUTOHSTS_FREQ", 0)
def test_autohsts_increase_no_header(self, _restart): def test_autohsts_increase_no_header(self, _restart):
self.config.enable_autohsts(mock.MagicMock(), ["ocspvhost.com"]) self.config.enable_autohsts(mock.MagicMock(), ["ocspvhost.com"])
# Remove the header # Remove the header
@@ -100,8 +100,8 @@ class AutoHSTSTest(util.ApacheTest):
with pytest.raises(errors.PluginError): with pytest.raises(errors.PluginError):
self.config.update_autohsts(mock.MagicMock()) self.config.update_autohsts(mock.MagicMock())
@mock.patch("certbot_apache._internal.constants.AUTOHSTS_FREQ", 0) @mock.patch("certbot._internal.plugins.apache.constants.AUTOHSTS_FREQ", 0)
@mock.patch("certbot_apache._internal.configurator.ApacheConfigurator.restart") @mock.patch("certbot._internal.plugins.apache.configurator.ApacheConfigurator.restart")
def test_autohsts_increase_and_make_permanent(self, _mock_restart): def test_autohsts_increase_and_make_permanent(self, _mock_restart):
maxage = "\"max-age={0}\"" maxage = "\"max-age={0}\""
max_val = maxage.format(constants.AUTOHSTS_PERMANENT) max_val = maxage.format(constants.AUTOHSTS_PERMANENT)
@@ -127,7 +127,7 @@ class AutoHSTSTest(util.ApacheTest):
max_val max_val
def test_autohsts_update_noop(self): def test_autohsts_update_noop(self):
with mock.patch("certbot_apache._internal.configurator.time") as mock_time_module: with mock.patch("certbot._internal.plugins.apache.configurator.time") as mock_time_module:
# Time mock is used to make sure that the execution does not # Time mock is used to make sure that the execution does not
# continue when no autohsts entries exist in pluginstorage # continue when no autohsts entries exist in pluginstorage
self.config.update_autohsts(mock.MagicMock()) self.config.update_autohsts(mock.MagicMock())
@@ -139,16 +139,16 @@ class AutoHSTSTest(util.ApacheTest):
# Make sure that the execution does not continue when no entries in store # Make sure that the execution does not continue when no entries in store
assert self.config.storage.put.called is False assert self.config.storage.put.called is False
@mock.patch("certbot_apache._internal.display_ops.select_vhost") @mock.patch("certbot._internal.plugins.apache.display_ops.select_vhost")
def test_autohsts_no_ssl_vhost(self, mock_select): def test_autohsts_no_ssl_vhost(self, mock_select):
mock_select.return_value = self.vh_truth[0] mock_select.return_value = self.vh_truth[0]
with mock.patch("certbot_apache._internal.configurator.logger.error") as mock_log: with mock.patch("certbot._internal.plugins.apache.configurator.logger.error") as mock_log:
with pytest.raises(errors.PluginError): with pytest.raises(errors.PluginError):
self.config.enable_autohsts(mock.MagicMock(), "invalid.example.com") self.config.enable_autohsts(mock.MagicMock(), "invalid.example.com")
assert "Certbot was not able to find SSL" in mock_log.call_args[0][0] assert "Certbot was not able to find SSL" in mock_log.call_args[0][0]
@mock.patch("certbot_apache._internal.configurator.ApacheConfigurator.restart") @mock.patch("certbot._internal.plugins.apache.configurator.ApacheConfigurator.restart")
@mock.patch("certbot_apache._internal.configurator.ApacheConfigurator.add_vhost_id") @mock.patch("certbot._internal.plugins.apache.configurator.ApacheConfigurator.add_vhost_id")
def test_autohsts_dont_enhance_twice(self, mock_id, _restart): def test_autohsts_dont_enhance_twice(self, mock_id, _restart):
mock_id.return_value = "1234567" mock_id.return_value = "1234567"
self.config.enable_autohsts(mock.MagicMock(), ["ocspvhost.com", "ocspvhost.com"]) self.config.enable_autohsts(mock.MagicMock(), ["ocspvhost.com", "ocspvhost.com"])
@@ -172,7 +172,7 @@ class AutoHSTSTest(util.ApacheTest):
self.config._autohsts_fetch_state() self.config._autohsts_fetch_state()
self.config._autohsts["orphan_id"] = {"laststep": 999, "timestamp": 0} self.config._autohsts["orphan_id"] = {"laststep": 999, "timestamp": 0}
self.config._autohsts_save_state() self.config._autohsts_save_state()
with mock.patch("certbot_apache._internal.configurator.logger.error") as mock_log: with mock.patch("certbot._internal.plugins.apache.configurator.logger.error") as mock_log:
self.config.deploy_autohsts(mock.MagicMock()) self.config.deploy_autohsts(mock.MagicMock())
assert mock_log.called is True assert mock_log.called is True
assert "VirtualHost with id orphan_id was not" in mock_log.call_args[0][0] assert "VirtualHost with id orphan_id was not" in mock_log.call_args[0][0]
@@ -1,4 +1,4 @@
"""Test for certbot_apache._internal.configurator for Centos overrides""" """Test for certbot._internal.plugins.apache.configurator for Centos overrides"""
import sys import sys
from unittest import mock from unittest import mock
@@ -7,9 +7,9 @@ import pytest
from certbot import errors from certbot import errors
from certbot.compat import filesystem from certbot.compat import filesystem
from certbot.compat import os from certbot.compat import os
from certbot_apache._internal import obj from certbot._internal.plugins.apache import obj
from certbot_apache._internal import override_centos from certbot._internal.plugins.apache import override_centos
from certbot_apache._internal.tests import util from certbot._internal.tests.plugins.apache import util
def get_vh_truth(temp_dir, config_name): def get_vh_truth(temp_dir, config_name):
@@ -56,7 +56,7 @@ class FedoraRestartTest(util.ApacheTest):
self.config.config_test() self.config.config_test()
def test_non_fedora_error(self): def test_non_fedora_error(self):
c_test = "certbot_apache._internal.configurator.ApacheConfigurator.config_test" c_test = "certbot._internal.plugins.apache.configurator.ApacheConfigurator.config_test"
with mock.patch(c_test) as mock_test: with mock.patch(c_test) as mock_test:
mock_test.side_effect = errors.MisconfigurationError mock_test.side_effect = errors.MisconfigurationError
with mock.patch("certbot.util.get_os_info") as mock_info: with mock.patch("certbot.util.get_os_info") as mock_info:
@@ -65,7 +65,7 @@ class FedoraRestartTest(util.ApacheTest):
self.config.config_test() self.config.config_test()
def test_fedora_restart_error(self): def test_fedora_restart_error(self):
c_test = "certbot_apache._internal.configurator.ApacheConfigurator.config_test" c_test = "certbot._internal.plugins.apache.configurator.ApacheConfigurator.config_test"
with mock.patch(c_test) as mock_test: with mock.patch(c_test) as mock_test:
# First call raises error, second doesn't # First call raises error, second doesn't
mock_test.side_effect = [errors.MisconfigurationError, ''] mock_test.side_effect = [errors.MisconfigurationError, '']
@@ -75,7 +75,7 @@ class FedoraRestartTest(util.ApacheTest):
self._run_fedora_test() self._run_fedora_test()
def test_fedora_restart(self): def test_fedora_restart(self):
c_test = "certbot_apache._internal.configurator.ApacheConfigurator.config_test" c_test = "certbot._internal.plugins.apache.configurator.ApacheConfigurator.config_test"
with mock.patch(c_test) as mock_test: with mock.patch(c_test) as mock_test:
with mock.patch("certbot.util.run_script") as mock_run: with mock.patch("certbot.util.run_script") as mock_run:
# First call raises error, second doesn't # First call raises error, second doesn't
@@ -153,7 +153,7 @@ class MultipleVhostsTestCentOS(util.ApacheTest):
def test_get_parser(self): def test_get_parser(self):
assert isinstance(self.config.parser, override_centos.CentOSParser) assert isinstance(self.config.parser, override_centos.CentOSParser)
@mock.patch("certbot_apache._internal.apache_util._get_runtime_cfg") @mock.patch("certbot._internal.plugins.apache.apache_util._get_runtime_cfg")
def test_opportunistic_httpd_runtime_parsing(self, mock_get): def test_opportunistic_httpd_runtime_parsing(self, mock_get):
define_val = ( define_val = (
'Define: TEST1\n' 'Define: TEST1\n'
@@ -202,7 +202,7 @@ class MultipleVhostsTestCentOS(util.ApacheTest):
raise Exception("Missed: %s" % vhost) # pragma: no cover raise Exception("Missed: %s" % vhost) # pragma: no cover
assert found == 2 assert found == 2
@mock.patch("certbot_apache._internal.apache_util._get_runtime_cfg") @mock.patch("certbot._internal.plugins.apache.apache_util._get_runtime_cfg")
def test_get_sysconfig_vars(self, mock_cfg): def test_get_sysconfig_vars(self, mock_cfg):
"""Make sure we read the sysconfig OPTIONS variable correctly""" """Make sure we read the sysconfig OPTIONS variable correctly"""
# Return nothing for the process calls # Return nothing for the process calls
@@ -223,13 +223,13 @@ class MultipleVhostsTestCentOS(util.ApacheTest):
assert "MOCK_NOSEP" in self.config.parser.variables assert "MOCK_NOSEP" in self.config.parser.variables
assert "NOSEP_VAL" == self.config.parser.variables["NOSEP_TWO"] assert "NOSEP_VAL" == self.config.parser.variables["NOSEP_TWO"]
@mock.patch("certbot_apache._internal.configurator.util.run_script") @mock.patch("certbot._internal.plugins.apache.configurator.util.run_script")
def test_alt_restart_works(self, mock_run_script): def test_alt_restart_works(self, mock_run_script):
mock_run_script.side_effect = [None, errors.SubprocessError, None] mock_run_script.side_effect = [None, errors.SubprocessError, None]
self.config.restart() self.config.restart()
assert mock_run_script.call_count == 3 assert mock_run_script.call_count == 3
@mock.patch("certbot_apache._internal.configurator.util.run_script") @mock.patch("certbot._internal.plugins.apache.configurator.util.run_script")
def test_alt_restart_errors(self, mock_run_script): def test_alt_restart_errors(self, mock_run_script):
mock_run_script.side_effect = [None, mock_run_script.side_effect = [None,
errors.SubprocessError, errors.SubprocessError,
@@ -1,11 +1,11 @@
"""Tests for certbot_apache._internal.parser.""" """Tests for certbot._internal.plugins.apache.parser."""
import sys import sys
import pytest import pytest
from certbot import errors from certbot import errors
from certbot.compat import os from certbot.compat import os
from certbot_apache._internal.tests import util from certbot._internal.tests.plugins.apache import util
class ComplexParserTest(util.ParserTest): class ComplexParserTest(util.ParserTest):
@@ -80,7 +80,7 @@ class ComplexParserTest(util.ParserTest):
def verify_fnmatch(self, arg, hit=True): def verify_fnmatch(self, arg, hit=True):
"""Test if Include was correctly parsed.""" """Test if Include was correctly parsed."""
from certbot_apache._internal import parser from certbot._internal.plugins.apache import parser
self.parser.add_dir(parser.get_aug_path(self.parser.loc["default"]), self.parser.add_dir(parser.get_aug_path(self.parser.loc["default"]),
"Include", [arg]) "Include", [arg])
if hit: if hit:
@@ -1,11 +1,11 @@
"""Test for certbot_apache._internal.configurator implementations of reverter""" """Test for certbot._internal.plugins.apache.configurator implementations of reverter"""
import sys import sys
from unittest import mock from unittest import mock
import pytest import pytest
from certbot import errors from certbot import errors
from certbot_apache._internal.tests import util from certbot._internal.tests.plugins.apache import util
class ConfiguratorReverterTest(util.ApacheTest): class ConfiguratorReverterTest(util.ApacheTest):
@@ -1,5 +1,5 @@
# pylint: disable=too-many-lines # pylint: disable=too-many-lines
"""Test for certbot_apache._internal.configurator.""" """Test for certbot._internal.plugins.apache.configurator."""
import copy import copy
import shutil import shutil
import socket import socket
@@ -17,11 +17,11 @@ from certbot.compat import filesystem
from certbot.compat import os from certbot.compat import os
from certbot.tests import acme_util from certbot.tests import acme_util
from certbot.tests import util as certbot_util from certbot.tests import util as certbot_util
from certbot_apache._internal import apache_util from certbot._internal.plugins.apache import apache_util
from certbot_apache._internal import constants from certbot._internal.plugins.apache import constants
from certbot_apache._internal import obj from certbot._internal.plugins.apache import obj
from certbot_apache._internal import parser from certbot._internal.plugins.apache import parser
from certbot_apache._internal.tests import util from certbot._internal.tests.plugins.apache import util
class MultipleVhostsTest(util.ApacheTest): class MultipleVhostsTest(util.ApacheTest):
@@ -42,13 +42,13 @@ class MultipleVhostsTest(util.ApacheTest):
def mocked_deploy_cert(*args, **kwargs): def mocked_deploy_cert(*args, **kwargs):
"""a helper to mock a deployed cert""" """a helper to mock a deployed cert"""
g_mod = "certbot_apache._internal.configurator.ApacheConfigurator.enable_mod" g_mod = "certbot._internal.plugins.apache.configurator.ApacheConfigurator.enable_mod"
with mock.patch(g_mod): with mock.patch(g_mod):
config.real_deploy_cert(*args, **kwargs) config.real_deploy_cert(*args, **kwargs)
self.config.deploy_cert = mocked_deploy_cert self.config.deploy_cert = mocked_deploy_cert
return self.config return self.config
@mock.patch("certbot_apache._internal.configurator.path_surgery") @mock.patch("certbot._internal.plugins.apache.configurator.path_surgery")
def test_prepare_no_install(self, mock_surgery): def test_prepare_no_install(self, mock_surgery):
silly_path = {"PATH": "/tmp/nothingness2342"} silly_path = {"PATH": "/tmp/nothingness2342"}
mock_surgery.return_value = False mock_surgery.return_value = False
@@ -57,8 +57,8 @@ class MultipleVhostsTest(util.ApacheTest):
self.config.prepare() self.config.prepare()
assert mock_surgery.call_count == 1 assert mock_surgery.call_count == 1
@mock.patch("certbot_apache._internal.parser.ApacheParser") @mock.patch("certbot._internal.plugins.apache.parser.ApacheParser")
@mock.patch("certbot_apache._internal.configurator.util.exe_exists") @mock.patch("certbot._internal.plugins.apache.configurator.util.exe_exists")
def test_prepare_version(self, mock_exe_exists, _): def test_prepare_version(self, mock_exe_exists, _):
mock_exe_exists.return_value = True mock_exe_exists.return_value = True
self.config.version = None self.config.version = None
@@ -81,9 +81,9 @@ class MultipleVhostsTest(util.ApacheTest):
os.remove(os.path.join(server_root, ".certbot.lock")) os.remove(os.path.join(server_root, ".certbot.lock"))
certbot_util.lock_and_call(self._test_prepare_locked, server_root) certbot_util.lock_and_call(self._test_prepare_locked, server_root)
@mock.patch("certbot_apache._internal.parser.ApacheParser") @mock.patch("certbot._internal.plugins.apache.parser.ApacheParser")
@mock.patch("certbot_apache._internal.configurator.util.exe_exists") @mock.patch("certbot._internal.plugins.apache.configurator.util.exe_exists")
@mock.patch("certbot_apache._internal.configurator.ApacheConfigurator.get_parsernode_root") @mock.patch("certbot._internal.plugins.apache.configurator.ApacheConfigurator.get_parsernode_root")
def _test_prepare_locked(self, _node, _exists, _parser): def _test_prepare_locked(self, _node, _exists, _parser):
try: try:
self.config.prepare() self.config.prepare()
@@ -95,14 +95,14 @@ class MultipleVhostsTest(util.ApacheTest):
self.fail("Exception wasn't raised!") self.fail("Exception wasn't raised!")
def test_add_parser_arguments(self): # pylint: disable=no-self-use def test_add_parser_arguments(self): # pylint: disable=no-self-use
from certbot_apache._internal.configurator import ApacheConfigurator from certbot._internal.plugins.apache.configurator import ApacheConfigurator
# Weak test.. # Weak test..
ApacheConfigurator.add_parser_arguments(mock.MagicMock()) ApacheConfigurator.add_parser_arguments(mock.MagicMock())
def test_docs_parser_arguments(self): def test_docs_parser_arguments(self):
os.environ["CERTBOT_DOCS"] = "1" os.environ["CERTBOT_DOCS"] = "1"
from certbot_apache._internal.configurator import ApacheConfigurator from certbot._internal.plugins.apache.configurator import ApacheConfigurator
mock_add = mock.MagicMock() mock_add = mock.MagicMock()
ApacheConfigurator.add_parser_arguments(mock_add) ApacheConfigurator.add_parser_arguments(mock_add)
parserargs = ["server_root", "enmod", "dismod", "le_vhost_ext", parserargs = ["server_root", "enmod", "dismod", "le_vhost_ext",
@@ -129,13 +129,13 @@ class MultipleVhostsTest(util.ApacheTest):
del os.environ["CERTBOT_DOCS"] del os.environ["CERTBOT_DOCS"]
def test_add_parser_arguments_all_configurators(self): # pylint: disable=no-self-use def test_add_parser_arguments_all_configurators(self): # pylint: disable=no-self-use
from certbot_apache._internal.entrypoint import OVERRIDE_CLASSES from certbot._internal.plugins.apache.entrypoint import OVERRIDE_CLASSES
for cls in OVERRIDE_CLASSES.values(): for cls in OVERRIDE_CLASSES.values():
cls.add_parser_arguments(mock.MagicMock()) cls.add_parser_arguments(mock.MagicMock())
def test_all_configurators_defaults_defined(self): def test_all_configurators_defaults_defined(self):
from certbot_apache._internal.configurator import ApacheConfigurator from certbot._internal.plugins.apache.configurator import ApacheConfigurator
from certbot_apache._internal.entrypoint import OVERRIDE_CLASSES from certbot._internal.plugins.apache.entrypoint import OVERRIDE_CLASSES
parameters = set(ApacheConfigurator.OS_DEFAULTS.__dict__.keys()) parameters = set(ApacheConfigurator.OS_DEFAULTS.__dict__.keys())
for cls in OVERRIDE_CLASSES.values(): for cls in OVERRIDE_CLASSES.values():
assert parameters.issubset(set(cls.OS_DEFAULTS.__dict__.keys())) is True assert parameters.issubset(set(cls.OS_DEFAULTS.__dict__.keys())) is True
@@ -153,7 +153,7 @@ class MultipleVhostsTest(util.ApacheTest):
"duplicate.example.com"} "duplicate.example.com"}
@certbot_util.patch_display_util() @certbot_util.patch_display_util()
@mock.patch("certbot_apache._internal.configurator.socket.gethostbyaddr") @mock.patch("certbot._internal.plugins.apache.configurator.socket.gethostbyaddr")
def test_get_all_names_addrs(self, mock_gethost, mock_getutility): def test_get_all_names_addrs(self, mock_gethost, mock_getutility):
mock_gethost.side_effect = [("google.com", "", ""), socket.error] mock_gethost.side_effect = [("google.com", "", ""), socket.error]
mock_utility = mock_getutility() mock_utility = mock_getutility()
@@ -179,7 +179,7 @@ class MultipleVhostsTest(util.ApacheTest):
assert self.config._create_vhost("nonexistent") is None # pylint: disable=protected-access assert self.config._create_vhost("nonexistent") is None # pylint: disable=protected-access
def test_get_aug_internal_path(self): def test_get_aug_internal_path(self):
from certbot_apache._internal.apache_util import get_internal_aug_path from certbot._internal.plugins.apache.apache_util import get_internal_aug_path
internal_paths = [ internal_paths = [
"Virtualhost", "IfModule/VirtualHost", "VirtualHost", "VirtualHost", "Virtualhost", "IfModule/VirtualHost", "VirtualHost", "VirtualHost",
"Macro/VirtualHost", "IfModule/VirtualHost", "VirtualHost", "Macro/VirtualHost", "IfModule/VirtualHost", "VirtualHost",
@@ -221,25 +221,25 @@ class MultipleVhostsTest(util.ApacheTest):
# Handle case of non-debian layout get_virtual_hosts # Handle case of non-debian layout get_virtual_hosts
with mock.patch( with mock.patch(
"certbot_apache._internal.configurator.ApacheConfigurator.conf" "certbot._internal.plugins.apache.configurator.ApacheConfigurator.conf"
) as mock_conf: ) as mock_conf:
mock_conf.return_value = False mock_conf.return_value = False
vhs = self.config.get_virtual_hosts() vhs = self.config.get_virtual_hosts()
assert len(vhs) == 12 assert len(vhs) == 12
@mock.patch("certbot_apache._internal.display_ops.select_vhost") @mock.patch("certbot._internal.plugins.apache.display_ops.select_vhost")
def test_choose_vhost_none_avail(self, mock_select): def test_choose_vhost_none_avail(self, mock_select):
mock_select.return_value = None mock_select.return_value = None
with pytest.raises(errors.PluginError): with pytest.raises(errors.PluginError):
self.config.choose_vhost("none.com") self.config.choose_vhost("none.com")
@mock.patch("certbot_apache._internal.display_ops.select_vhost") @mock.patch("certbot._internal.plugins.apache.display_ops.select_vhost")
def test_choose_vhost_select_vhost_ssl(self, mock_select): def test_choose_vhost_select_vhost_ssl(self, mock_select):
mock_select.return_value = self.vh_truth[1] mock_select.return_value = self.vh_truth[1]
assert self.vh_truth[1] == self.config.choose_vhost("none.com") assert self.vh_truth[1] == self.config.choose_vhost("none.com")
@mock.patch("certbot_apache._internal.display_ops.select_vhost") @mock.patch("certbot._internal.plugins.apache.display_ops.select_vhost")
@mock.patch("certbot_apache._internal.obj.VirtualHost.conflicts") @mock.patch("certbot._internal.plugins.apache.obj.VirtualHost.conflicts")
def test_choose_vhost_select_vhost_non_ssl(self, mock_conf, mock_select): def test_choose_vhost_select_vhost_non_ssl(self, mock_conf, mock_select):
mock_select.return_value = self.vh_truth[0] mock_select.return_value = self.vh_truth[0]
mock_conf.return_value = False mock_conf.return_value = False
@@ -251,8 +251,8 @@ class MultipleVhostsTest(util.ApacheTest):
assert self.vh_truth[0].ssl is False assert self.vh_truth[0].ssl is False
assert chosen_vhost.ssl is True assert chosen_vhost.ssl is True
@mock.patch("certbot_apache._internal.configurator.ApacheConfigurator._find_best_vhost") @mock.patch("certbot._internal.plugins.apache.configurator.ApacheConfigurator._find_best_vhost")
@mock.patch("certbot_apache._internal.parser.ApacheParser.add_dir") @mock.patch("certbot._internal.plugins.apache.parser.ApacheParser.add_dir")
def test_choose_vhost_and_servername_addition(self, mock_add, mock_find): def test_choose_vhost_and_servername_addition(self, mock_add, mock_find):
ret_vh = self.vh_truth[8] ret_vh = self.vh_truth[8]
ret_vh.enabled = False ret_vh.enabled = False
@@ -260,13 +260,13 @@ class MultipleVhostsTest(util.ApacheTest):
self.config.choose_vhost("whatever.com") self.config.choose_vhost("whatever.com")
assert mock_add.called is True assert mock_add.called is True
@mock.patch("certbot_apache._internal.display_ops.select_vhost") @mock.patch("certbot._internal.plugins.apache.display_ops.select_vhost")
def test_choose_vhost_select_vhost_with_temp(self, mock_select): def test_choose_vhost_select_vhost_with_temp(self, mock_select):
mock_select.return_value = self.vh_truth[0] mock_select.return_value = self.vh_truth[0]
chosen_vhost = self.config.choose_vhost("none.com", create_if_no_ssl=False) chosen_vhost = self.config.choose_vhost("none.com", create_if_no_ssl=False)
assert self.vh_truth[0] == chosen_vhost assert self.vh_truth[0] == chosen_vhost
@mock.patch("certbot_apache._internal.display_ops.select_vhost") @mock.patch("certbot._internal.plugins.apache.display_ops.select_vhost")
def test_choose_vhost_select_vhost_conflicting_non_ssl(self, mock_select): def test_choose_vhost_select_vhost_conflicting_non_ssl(self, mock_select):
mock_select.return_value = self.vh_truth[3] mock_select.return_value = self.vh_truth[3]
conflicting_vhost = obj.VirtualHost( conflicting_vhost = obj.VirtualHost(
@@ -332,7 +332,7 @@ class MultipleVhostsTest(util.ApacheTest):
vhosts = self.config._non_default_vhosts(self.config.vhosts) vhosts = self.config._non_default_vhosts(self.config.vhosts)
assert len(vhosts) == 10 assert len(vhosts) == 10
@mock.patch('certbot_apache._internal.configurator.display_util.notify') @mock.patch('certbot._internal.plugins.apache.configurator.display_util.notify')
def test_deploy_cert_enable_new_vhost(self, unused_mock_notify): def test_deploy_cert_enable_new_vhost(self, unused_mock_notify):
# Create # Create
ssl_vhost = self.config.make_vhost_ssl(self.vh_truth[0]) ssl_vhost = self.config.make_vhost_ssl(self.vh_truth[0])
@@ -371,7 +371,7 @@ class MultipleVhostsTest(util.ApacheTest):
self.fail("Include shouldn't be added, as patched find_dir 'finds' existing one") \ self.fail("Include shouldn't be added, as patched find_dir 'finds' existing one") \
# pragma: no cover # pragma: no cover
@mock.patch('certbot_apache._internal.configurator.display_util.notify') @mock.patch('certbot._internal.plugins.apache.configurator.display_util.notify')
def test_deploy_cert(self, unused_mock_notify): def test_deploy_cert(self, unused_mock_notify):
self.config.parser.modules["ssl_module"] = None self.config.parser.modules["ssl_module"] = None
self.config.parser.modules["mod_ssl.c"] = None self.config.parser.modules["mod_ssl.c"] = None
@@ -480,7 +480,7 @@ class MultipleVhostsTest(util.ApacheTest):
call_found = True call_found = True
assert call_found is True assert call_found is True
@mock.patch("certbot_apache._internal.parser.ApacheParser.reset_modules") @mock.patch("certbot._internal.plugins.apache.parser.ApacheParser.reset_modules")
def test_prepare_server_https(self, mock_reset): def test_prepare_server_https(self, mock_reset):
mock_enable = mock.Mock() mock_enable = mock.Mock()
self.config.enable_mod = mock_enable self.config.enable_mod = mock_enable
@@ -507,7 +507,7 @@ class MultipleVhostsTest(util.ApacheTest):
assert mock_add_dir.call_count == 2 assert mock_add_dir.call_count == 2
@mock.patch("certbot_apache._internal.parser.ApacheParser.reset_modules") @mock.patch("certbot._internal.plugins.apache.parser.ApacheParser.reset_modules")
def test_prepare_server_https_named_listen(self, mock_reset): def test_prepare_server_https_named_listen(self, mock_reset):
mock_find = mock.Mock() mock_find = mock.Mock()
mock_find.return_value = ["test1", "test2", "test3"] mock_find.return_value = ["test1", "test2", "test3"]
@@ -545,7 +545,7 @@ class MultipleVhostsTest(util.ApacheTest):
# self.config.prepare_server_https("8080", temp=True) # self.config.prepare_server_https("8080", temp=True)
# self.assertEqual(self.listens, 0) # self.assertEqual(self.listens, 0)
@mock.patch("certbot_apache._internal.parser.ApacheParser.reset_modules") @mock.patch("certbot._internal.plugins.apache.parser.ApacheParser.reset_modules")
def test_prepare_server_https_needed_listen(self, mock_reset): def test_prepare_server_https_needed_listen(self, mock_reset):
mock_find = mock.Mock() mock_find = mock.Mock()
mock_find.return_value = ["test1", "test2"] mock_find.return_value = ["test1", "test2"]
@@ -562,7 +562,7 @@ class MultipleVhostsTest(util.ApacheTest):
self.config.prepare_server_https("443") self.config.prepare_server_https("443")
assert mock_add_dir.call_count == 1 assert mock_add_dir.call_count == 1
@mock.patch("certbot_apache._internal.parser.ApacheParser.reset_modules") @mock.patch("certbot._internal.plugins.apache.parser.ApacheParser.reset_modules")
def test_prepare_server_https_mixed_listen(self, mock_reset): def test_prepare_server_https_mixed_listen(self, mock_reset):
mock_find = mock.Mock() mock_find = mock.Mock()
mock_find.return_value = ["test1", "test2"] mock_find.return_value = ["test1", "test2"]
@@ -697,8 +697,8 @@ class MultipleVhostsTest(util.ApacheTest):
# pylint: disable=protected-access # pylint: disable=protected-access
assert self.config._get_ssl_vhost_path("example_path").endswith(".conf") is True assert self.config._get_ssl_vhost_path("example_path").endswith(".conf") is True
@mock.patch("certbot_apache._internal.configurator.http_01.ApacheHttp01.perform") @mock.patch("certbot._internal.plugins.apache.configurator.http_01.ApacheHttp01.perform")
@mock.patch("certbot_apache._internal.configurator.ApacheConfigurator.restart") @mock.patch("certbot._internal.plugins.apache.configurator.ApacheConfigurator.restart")
def test_perform(self, mock_restart, mock_http_perform): def test_perform(self, mock_restart, mock_http_perform):
# Only tests functionality specific to configurator.perform # Only tests functionality specific to configurator.perform
# Note: As more challenges are offered this will have to be expanded # Note: As more challenges are offered this will have to be expanded
@@ -714,8 +714,8 @@ class MultipleVhostsTest(util.ApacheTest):
assert mock_restart.call_count == 1 assert mock_restart.call_count == 1
@mock.patch("certbot_apache._internal.configurator.ApacheConfigurator.restart") @mock.patch("certbot._internal.plugins.apache.configurator.ApacheConfigurator.restart")
@mock.patch("certbot_apache._internal.apache_util._get_runtime_cfg") @mock.patch("certbot._internal.plugins.apache.apache_util._get_runtime_cfg")
def test_cleanup(self, mock_cfg, mock_restart): def test_cleanup(self, mock_cfg, mock_restart):
mock_cfg.return_value = "" mock_cfg.return_value = ""
_, achalls = self.get_key_and_achalls() _, achalls = self.get_key_and_achalls()
@@ -730,8 +730,8 @@ class MultipleVhostsTest(util.ApacheTest):
else: else:
assert mock_restart.called is False assert mock_restart.called is False
@mock.patch("certbot_apache._internal.configurator.ApacheConfigurator.restart") @mock.patch("certbot._internal.plugins.apache.configurator.ApacheConfigurator.restart")
@mock.patch("certbot_apache._internal.apache_util._get_runtime_cfg") @mock.patch("certbot._internal.plugins.apache.apache_util._get_runtime_cfg")
def test_cleanup_no_errors(self, mock_cfg, mock_restart): def test_cleanup_no_errors(self, mock_cfg, mock_restart):
mock_cfg.return_value = "" mock_cfg.return_value = ""
_, achalls = self.get_key_and_achalls() _, achalls = self.get_key_and_achalls()
@@ -771,11 +771,11 @@ class MultipleVhostsTest(util.ApacheTest):
with pytest.raises(errors.PluginError): with pytest.raises(errors.PluginError):
self.config.get_version() self.config.get_version()
@mock.patch("certbot_apache._internal.configurator.util.run_script") @mock.patch("certbot._internal.plugins.apache.configurator.util.run_script")
def test_restart(self, _): def test_restart(self, _):
self.config.restart() self.config.restart()
@mock.patch("certbot_apache._internal.configurator.util.run_script") @mock.patch("certbot._internal.plugins.apache.configurator.util.run_script")
def test_restart_bad_process(self, mock_run_script): def test_restart_bad_process(self, mock_run_script):
mock_run_script.side_effect = [None, errors.SubprocessError] mock_run_script.side_effect = [None, errors.SubprocessError]
@@ -819,8 +819,8 @@ class MultipleVhostsTest(util.ApacheTest):
assert self.vh_truth[0].name == res.name assert self.vh_truth[0].name == res.name
assert self.vh_truth[0].aliases == res.aliases assert self.vh_truth[0].aliases == res.aliases
@mock.patch("certbot_apache._internal.configurator.ApacheConfigurator._get_http_vhost") @mock.patch("certbot._internal.plugins.apache.configurator.ApacheConfigurator._get_http_vhost")
@mock.patch("certbot_apache._internal.display_ops.select_vhost") @mock.patch("certbot._internal.plugins.apache.display_ops.select_vhost")
@mock.patch("certbot.util.exe_exists") @mock.patch("certbot.util.exe_exists")
def test_enhance_unknown_vhost(self, mock_exe, mock_sel_vhost, mock_get): def test_enhance_unknown_vhost(self, mock_exe, mock_sel_vhost, mock_get):
self.config.parser.modules["rewrite_module"] = None self.config.parser.modules["rewrite_module"] = None
@@ -841,7 +841,7 @@ class MultipleVhostsTest(util.ApacheTest):
self.config.enhance("certbot.demo", "unknown_enhancement") self.config.enhance("certbot.demo", "unknown_enhancement")
def test_enhance_no_ssl_vhost(self): def test_enhance_no_ssl_vhost(self):
with mock.patch("certbot_apache._internal.configurator.logger.error") as mock_log: with mock.patch("certbot._internal.plugins.apache.configurator.logger.error") as mock_log:
with pytest.raises(errors.PluginError): with pytest.raises(errors.PluginError):
self.config.enhance("certbot.demo", "redirect") self.config.enhance("certbot.demo", "redirect")
# Check that correct logger.warning was printed # Check that correct logger.warning was printed
@@ -1130,7 +1130,7 @@ class MultipleVhostsTest(util.ApacheTest):
self.config.choose_vhost("red.blue.purple.com") self.config.choose_vhost("red.blue.purple.com")
self.config.enhance("red.blue.purple.com", "redirect") self.config.enhance("red.blue.purple.com", "redirect")
verify_no_redirect = ("certbot_apache._internal.configurator." verify_no_redirect = ("certbot._internal.plugins.apache.configurator."
"ApacheConfigurator._verify_no_certbot_redirect") "ApacheConfigurator._verify_no_certbot_redirect")
with mock.patch(verify_no_redirect) as mock_verify: with mock.patch(verify_no_redirect) as mock_verify:
self.config.enhance("green.blue.purple.com", "redirect") self.config.enhance("green.blue.purple.com", "redirect")
@@ -1223,7 +1223,7 @@ class MultipleVhostsTest(util.ApacheTest):
assert os.path.basename(inc_path) in self.config.parser.existing_paths[ assert os.path.basename(inc_path) in self.config.parser.existing_paths[
os.path.dirname(inc_path)] os.path.dirname(inc_path)]
@mock.patch('certbot_apache._internal.configurator.display_util.notify') @mock.patch('certbot._internal.plugins.apache.configurator.display_util.notify')
def test_deploy_cert_not_parsed_path(self, unused_mock_notify): def test_deploy_cert_not_parsed_path(self, unused_mock_notify):
# Make sure that we add include to root config for vhosts when # Make sure that we add include to root config for vhosts when
# handle-sites is false # handle-sites is false
@@ -1232,8 +1232,8 @@ class MultipleVhostsTest(util.ApacheTest):
self.config.parser.modules["socache_shmcb_module"] = None self.config.parser.modules["socache_shmcb_module"] = None
tmp_path = filesystem.realpath(tempfile.mkdtemp("vhostroot")) tmp_path = filesystem.realpath(tempfile.mkdtemp("vhostroot"))
filesystem.chmod(tmp_path, 0o755) filesystem.chmod(tmp_path, 0o755)
mock_p = "certbot_apache._internal.configurator.ApacheConfigurator._get_ssl_vhost_path" mock_p = "certbot._internal.plugins.apache.configurator.ApacheConfigurator._get_ssl_vhost_path"
mock_a = "certbot_apache._internal.parser.ApacheParser.add_include" mock_a = "certbot._internal.plugins.apache.parser.ApacheParser.add_include"
with mock.patch(mock_p) as mock_path: with mock.patch(mock_p) as mock_path:
mock_path.return_value = os.path.join(tmp_path, "whatever.conf") mock_path.return_value = os.path.join(tmp_path, "whatever.conf")
@@ -1256,7 +1256,7 @@ class MultipleVhostsTest(util.ApacheTest):
self.config.deploy_cert("encryption-example.demo", "example/cert.pem", "example/key.pem", self.config.deploy_cert("encryption-example.demo", "example/cert.pem", "example/key.pem",
"example/cert_chain.pem", "example/fullchain.pem") "example/cert_chain.pem", "example/fullchain.pem")
@mock.patch("certbot_apache._internal.parser.ApacheParser.parsed_in_original") @mock.patch("certbot._internal.plugins.apache.parser.ApacheParser.parsed_in_original")
def test_choose_vhost_and_servername_addition_parsed(self, mock_parsed): def test_choose_vhost_and_servername_addition_parsed(self, mock_parsed):
ret_vh = self.vh_truth[8] ret_vh = self.vh_truth[8]
ret_vh.enabled = True ret_vh.enabled = True
@@ -1270,7 +1270,7 @@ class MultipleVhostsTest(util.ApacheTest):
def test_choose_vhosts_wildcard(self): def test_choose_vhosts_wildcard(self):
# pylint: disable=protected-access # pylint: disable=protected-access
mock_path = "certbot_apache._internal.display_ops.select_vhost_multiple" mock_path = "certbot._internal.plugins.apache.display_ops.select_vhost_multiple"
with mock.patch(mock_path) as mock_select_vhs: with mock.patch(mock_path) as mock_select_vhs:
mock_select_vhs.return_value = [self.vh_truth[3]] mock_select_vhs.return_value = [self.vh_truth[3]]
vhs = self.config._choose_vhosts_wildcard("*.certbot.demo", vhs = self.config._choose_vhosts_wildcard("*.certbot.demo",
@@ -1286,10 +1286,10 @@ class MultipleVhostsTest(util.ApacheTest):
assert vhs[0] != self.vh_truth[3] assert vhs[0] != self.vh_truth[3]
@mock.patch("certbot_apache._internal.configurator.ApacheConfigurator.make_vhost_ssl") @mock.patch("certbot._internal.plugins.apache.configurator.ApacheConfigurator.make_vhost_ssl")
def test_choose_vhosts_wildcard_no_ssl(self, mock_makessl): def test_choose_vhosts_wildcard_no_ssl(self, mock_makessl):
# pylint: disable=protected-access # pylint: disable=protected-access
mock_path = "certbot_apache._internal.display_ops.select_vhost_multiple" mock_path = "certbot._internal.plugins.apache.display_ops.select_vhost_multiple"
with mock.patch(mock_path) as mock_select_vhs: with mock.patch(mock_path) as mock_select_vhs:
mock_select_vhs.return_value = [self.vh_truth[1]] mock_select_vhs.return_value = [self.vh_truth[1]]
vhs = self.config._choose_vhosts_wildcard("*.certbot.demo", vhs = self.config._choose_vhosts_wildcard("*.certbot.demo",
@@ -1297,13 +1297,13 @@ class MultipleVhostsTest(util.ApacheTest):
assert mock_makessl.called is False assert mock_makessl.called is False
assert vhs[0] == self.vh_truth[1] assert vhs[0] == self.vh_truth[1]
@mock.patch("certbot_apache._internal.configurator.ApacheConfigurator._vhosts_for_wildcard") @mock.patch("certbot._internal.plugins.apache.configurator.ApacheConfigurator._vhosts_for_wildcard")
@mock.patch("certbot_apache._internal.configurator.ApacheConfigurator.make_vhost_ssl") @mock.patch("certbot._internal.plugins.apache.configurator.ApacheConfigurator.make_vhost_ssl")
def test_choose_vhosts_wildcard_already_ssl(self, mock_makessl, mock_vh_for_w): def test_choose_vhosts_wildcard_already_ssl(self, mock_makessl, mock_vh_for_w):
# pylint: disable=protected-access # pylint: disable=protected-access
# Already SSL vhost # Already SSL vhost
mock_vh_for_w.return_value = [self.vh_truth[7]] mock_vh_for_w.return_value = [self.vh_truth[7]]
mock_path = "certbot_apache._internal.display_ops.select_vhost_multiple" mock_path = "certbot._internal.plugins.apache.display_ops.select_vhost_multiple"
with mock.patch(mock_path) as mock_select_vhs: with mock.patch(mock_path) as mock_select_vhs:
mock_select_vhs.return_value = [self.vh_truth[7]] mock_select_vhs.return_value = [self.vh_truth[7]]
vhs = self.config._choose_vhosts_wildcard("whatever", vhs = self.config._choose_vhosts_wildcard("whatever",
@@ -1318,13 +1318,13 @@ class MultipleVhostsTest(util.ApacheTest):
assert vhs[0].ssl is True assert vhs[0].ssl is True
assert vhs[0] == self.vh_truth[7] assert vhs[0] == self.vh_truth[7]
@mock.patch('certbot_apache._internal.configurator.display_util.notify') @mock.patch('certbot._internal.plugins.apache.configurator.display_util.notify')
def test_deploy_cert_wildcard(self, unused_mock_notify): def test_deploy_cert_wildcard(self, unused_mock_notify):
# pylint: disable=protected-access # pylint: disable=protected-access
mock_choose_vhosts = mock.MagicMock() mock_choose_vhosts = mock.MagicMock()
mock_choose_vhosts.return_value = [self.vh_truth[7]] mock_choose_vhosts.return_value = [self.vh_truth[7]]
self.config._choose_vhosts_wildcard = mock_choose_vhosts self.config._choose_vhosts_wildcard = mock_choose_vhosts
mock_d = "certbot_apache._internal.configurator.ApacheConfigurator._deploy_cert" mock_d = "certbot._internal.plugins.apache.configurator.ApacheConfigurator._deploy_cert"
with mock.patch(mock_d) as mock_dep: with mock.patch(mock_d) as mock_dep:
self.config.deploy_cert("*.wildcard.example.org", "/tmp/path", self.config.deploy_cert("*.wildcard.example.org", "/tmp/path",
"/tmp/path", "/tmp/path", "/tmp/path") "/tmp/path", "/tmp/path", "/tmp/path")
@@ -1332,7 +1332,7 @@ class MultipleVhostsTest(util.ApacheTest):
assert len(mock_dep.call_args_list) == 1 assert len(mock_dep.call_args_list) == 1
assert self.vh_truth[7] == mock_dep.call_args_list[0][0][0] assert self.vh_truth[7] == mock_dep.call_args_list[0][0][0]
@mock.patch("certbot_apache._internal.display_ops.select_vhost_multiple") @mock.patch("certbot._internal.plugins.apache.display_ops.select_vhost_multiple")
def test_deploy_cert_wildcard_no_vhosts(self, mock_dialog): def test_deploy_cert_wildcard_no_vhosts(self, mock_dialog):
# pylint: disable=protected-access # pylint: disable=protected-access
mock_dialog.return_value = [] mock_dialog.return_value = []
@@ -1340,7 +1340,7 @@ class MultipleVhostsTest(util.ApacheTest):
self.config.deploy_cert("*.wild.cat", "/tmp/path", "/tmp/path", self.config.deploy_cert("*.wild.cat", "/tmp/path", "/tmp/path",
"/tmp/path", "/tmp/path") "/tmp/path", "/tmp/path")
@mock.patch("certbot_apache._internal.configurator.ApacheConfigurator._choose_vhosts_wildcard") @mock.patch("certbot._internal.plugins.apache.configurator.ApacheConfigurator._choose_vhosts_wildcard")
def test_enhance_wildcard_after_install(self, mock_choose): def test_enhance_wildcard_after_install(self, mock_choose):
# pylint: disable=protected-access # pylint: disable=protected-access
self.config.parser.modules["mod_ssl.c"] = None self.config.parser.modules["mod_ssl.c"] = None
@@ -1351,7 +1351,7 @@ class MultipleVhostsTest(util.ApacheTest):
"Upgrade-Insecure-Requests") "Upgrade-Insecure-Requests")
assert mock_choose.called is False assert mock_choose.called is False
@mock.patch("certbot_apache._internal.configurator.ApacheConfigurator._choose_vhosts_wildcard") @mock.patch("certbot._internal.plugins.apache.configurator.ApacheConfigurator._choose_vhosts_wildcard")
def test_enhance_wildcard_no_install(self, mock_choose): def test_enhance_wildcard_no_install(self, mock_choose):
self.vh_truth[3].ssl = True self.vh_truth[3].ssl = True
mock_choose.return_value = [self.vh_truth[3]] mock_choose.return_value = [self.vh_truth[3]]
@@ -1427,7 +1427,7 @@ class AugeasVhostsTest(util.ApacheTest):
chosen_vhost = self.config._create_vhost(path) chosen_vhost = self.config._create_vhost(path)
assert chosen_vhost is None or chosen_vhost.path == path assert chosen_vhost is None or chosen_vhost.path == path
@mock.patch("certbot_apache._internal.configurator.ApacheConfigurator._create_vhost") @mock.patch("certbot._internal.plugins.apache.configurator.ApacheConfigurator._create_vhost")
def test_get_vhost_continue(self, mock_vhost): def test_get_vhost_continue(self, mock_vhost):
mock_vhost.return_value = None mock_vhost.return_value = None
vhs = self.config.get_virtual_hosts() vhs = self.config.get_virtual_hosts()
@@ -1440,18 +1440,18 @@ class AugeasVhostsTest(util.ApacheTest):
with self.subTest(name=name): with self.subTest(name=name):
assert name not in self.config.choose_vhost(name).aliases assert name not in self.config.choose_vhost(name).aliases
@mock.patch("certbot_apache._internal.obj.VirtualHost.conflicts") @mock.patch("certbot._internal.plugins.apache.obj.VirtualHost.conflicts")
def test_choose_vhost_without_matching_wildcard(self, mock_conflicts): def test_choose_vhost_without_matching_wildcard(self, mock_conflicts):
mock_conflicts.return_value = False mock_conflicts.return_value = False
mock_path = "certbot_apache._internal.display_ops.select_vhost" mock_path = "certbot._internal.plugins.apache.display_ops.select_vhost"
with mock.patch(mock_path, lambda _, vhosts: vhosts[0]): with mock.patch(mock_path, lambda _, vhosts: vhosts[0]):
for name in ("a.example.net", "other.example.net"): for name in ("a.example.net", "other.example.net"):
assert name in self.config.choose_vhost(name).aliases assert name in self.config.choose_vhost(name).aliases
@mock.patch("certbot_apache._internal.obj.VirtualHost.conflicts") @mock.patch("certbot._internal.plugins.apache.obj.VirtualHost.conflicts")
def test_choose_vhost_wildcard_not_found(self, mock_conflicts): def test_choose_vhost_wildcard_not_found(self, mock_conflicts):
mock_conflicts.return_value = False mock_conflicts.return_value = False
mock_path = "certbot_apache._internal.display_ops.select_vhost" mock_path = "certbot._internal.plugins.apache.display_ops.select_vhost"
names = ( names = (
"abc.example.net", "not.there.tld", "aa.wildcard.tld" "abc.example.net", "not.there.tld", "aa.wildcard.tld"
) )
@@ -1463,7 +1463,7 @@ class AugeasVhostsTest(util.ApacheTest):
assert mock_select.call_count - orig_cc == 1 assert mock_select.call_count - orig_cc == 1
def test_choose_vhost_wildcard_found(self): def test_choose_vhost_wildcard_found(self):
mock_path = "certbot_apache._internal.display_ops.select_vhost" mock_path = "certbot._internal.plugins.apache.display_ops.select_vhost"
names = ( names = (
"ab.example.net", "a.wildcard.tld", "yetanother.example.net" "ab.example.net", "a.wildcard.tld", "yetanother.example.net"
) )
@@ -1511,7 +1511,7 @@ class MultiVhostsTest(util.ApacheTest):
assert ssl_vhost.ssl is True assert ssl_vhost.ssl is True
assert ssl_vhost.enabled is False assert ssl_vhost.enabled is False
mock_path = "certbot_apache._internal.configurator.ApacheConfigurator._get_new_vh_path" mock_path = "certbot._internal.plugins.apache.configurator.ApacheConfigurator._get_new_vh_path"
with mock.patch(mock_path) as mock_getpath: with mock.patch(mock_path) as mock_getpath:
mock_getpath.return_value = None mock_getpath.return_value = None
with pytest.raises(errors.PluginError): with pytest.raises(errors.PluginError):
@@ -1527,7 +1527,7 @@ class MultiVhostsTest(util.ApacheTest):
both = with_index_1 + with_index_2 both = with_index_1 + with_index_2
assert self.config._get_new_vh_path(without_index, both) == with_index_2[0] assert self.config._get_new_vh_path(without_index, both) == with_index_2[0]
@mock.patch("certbot_apache._internal.configurator.display_util.notify") @mock.patch("certbot._internal.plugins.apache.configurator.display_util.notify")
def test_make_vhost_ssl_with_existing_rewrite_rule(self, mock_notify): def test_make_vhost_ssl_with_existing_rewrite_rule(self, mock_notify):
self.config.parser.modules["rewrite_module"] = None self.config.parser.modules["rewrite_module"] = None
@@ -1546,7 +1546,7 @@ class MultiVhostsTest(util.ApacheTest):
assert mock_notify.call_count == 1 assert mock_notify.call_count == 1
assert "Some rewrite rules" in mock_notify.call_args[0][0] assert "Some rewrite rules" in mock_notify.call_args[0][0]
@mock.patch("certbot_apache._internal.configurator.display_util.notify") @mock.patch("certbot._internal.plugins.apache.configurator.display_util.notify")
def test_make_vhost_ssl_with_existing_rewrite_conds(self, mock_notify): def test_make_vhost_ssl_with_existing_rewrite_conds(self, mock_notify):
self.config.parser.modules["rewrite_module"] = None self.config.parser.modules["rewrite_module"] = None
@@ -1611,7 +1611,7 @@ class InstallSslOptionsConfTest(util.ApacheTest):
self._assert_current_file() self._assert_current_file()
def test_prev_file_updates_to_current(self): def test_prev_file_updates_to_current(self):
from certbot_apache._internal.constants import ALL_SSL_OPTIONS_HASHES from certbot._internal.plugins.apache.constants import ALL_SSL_OPTIONS_HASHES
ALL_SSL_OPTIONS_HASHES.insert(0, "test_hash_does_not_match") ALL_SSL_OPTIONS_HASHES.insert(0, "test_hash_does_not_match")
with mock.patch('certbot.crypto_util.sha256sum') as mock_sha256: with mock.patch('certbot.crypto_util.sha256sum') as mock_sha256:
mock_sha256.return_value = ALL_SSL_OPTIONS_HASHES[0] mock_sha256.return_value = ALL_SSL_OPTIONS_HASHES[0]
@@ -1649,8 +1649,8 @@ class InstallSslOptionsConfTest(util.ApacheTest):
self._call() self._call()
assert mock_logger.warning.called is False assert mock_logger.warning.called is False
@mock.patch('certbot_apache._internal.configurator.logger.warning') @mock.patch('certbot._internal.plugins.apache.configurator.logger.warning')
@mock.patch('certbot_apache._internal.configurator.ApacheConfigurator.openssl_version') @mock.patch('certbot._internal.plugins.apache.configurator.ApacheConfigurator.openssl_version')
def test_pick_apache_config_versions_and_warnings(self, mock_openssl_version, mock_warning): def test_pick_apache_config_versions_and_warnings(self, mock_openssl_version, mock_warning):
def has_logged_warning(): def has_logged_warning():
"""Returns True if a warning was logged about updating Apache.""" """Returns True if a warning was logged about updating Apache."""
@@ -1702,9 +1702,9 @@ class InstallSslOptionsConfTest(util.ApacheTest):
""" """
import importlib.resources import importlib.resources
from certbot_apache._internal.constants import ALL_SSL_OPTIONS_HASHES from certbot._internal.plugins.apache.constants import ALL_SSL_OPTIONS_HASHES
ref = importlib.resources.files("certbot_apache") / "_internal" / "tls_configs" ref = importlib.resources.files("certbot") / "_internal" / "plugins" /"apache" / "tls_configs"
with importlib.resources.as_file(ref) as tls_configs_dir: with importlib.resources.as_file(ref) as tls_configs_dir:
all_files = [os.path.join(tls_configs_dir, name) for name in os.listdir(tls_configs_dir) all_files = [os.path.join(tls_configs_dir, name) for name in os.listdir(tls_configs_dir)
if name.endswith('options-ssl-apache.conf')] if name.endswith('options-ssl-apache.conf')]
@@ -1730,7 +1730,7 @@ class InstallSslOptionsConfTest(util.ApacheTest):
""" """
# ssl_module as a DSO # ssl_module as a DSO
self.config.parser.modules['ssl_module'] = '/fake/path' self.config.parser.modules['ssl_module'] = '/fake/path'
with mock.patch("certbot_apache._internal.configurator." with mock.patch("certbot._internal.plugins.apache.configurator."
"ApacheConfigurator._open_module_file") as mock_omf: "ApacheConfigurator._open_module_file") as mock_omf:
mock_omf.return_value = some_string_contents mock_omf.return_value = some_string_contents
assert self.config.openssl_version() == "1.0.2g" assert self.config.openssl_version() == "1.0.2g"
@@ -1739,7 +1739,7 @@ class InstallSslOptionsConfTest(util.ApacheTest):
self.config._openssl_version = None self.config._openssl_version = None
self.config.parser.modules['ssl_module'] = None self.config.parser.modules['ssl_module'] = None
self.config.options.bin = '/fake/path/to/httpd' self.config.options.bin = '/fake/path/to/httpd'
with mock.patch("certbot_apache._internal.configurator." with mock.patch("certbot._internal.plugins.apache.configurator."
"ApacheConfigurator._open_module_file") as mock_omf: "ApacheConfigurator._open_module_file") as mock_omf:
mock_omf.return_value = some_string_contents mock_omf.return_value = some_string_contents
assert self.config.openssl_version() == "1.0.2g" assert self.config.openssl_version() == "1.0.2g"
@@ -1749,14 +1749,14 @@ class InstallSslOptionsConfTest(util.ApacheTest):
assert self.config.openssl_version() == '1.0.2a' assert self.config.openssl_version() == '1.0.2a'
self.config._openssl_version = None self.config._openssl_version = None
with mock.patch("certbot_apache._internal.configurator.logger.warning") as mock_log: with mock.patch("certbot._internal.plugins.apache.configurator.logger.warning") as mock_log:
assert self.config.openssl_version() is None assert self.config.openssl_version() is None
assert "Could not find ssl_module" in mock_log.call_args[0][0] assert "Could not find ssl_module" in mock_log.call_args[0][0]
# When no ssl_module is present at all # When no ssl_module is present at all
self.config._openssl_version = None self.config._openssl_version = None
assert "ssl_module" not in self.config.parser.modules assert "ssl_module" not in self.config.parser.modules
with mock.patch("certbot_apache._internal.configurator.logger.warning") as mock_log: with mock.patch("certbot._internal.plugins.apache.configurator.logger.warning") as mock_log:
assert self.config.openssl_version() is None assert self.config.openssl_version() is None
assert "Could not find ssl_module" in mock_log.call_args[0][0] assert "Could not find ssl_module" in mock_log.call_args[0][0]
@@ -1764,21 +1764,21 @@ class InstallSslOptionsConfTest(util.ApacheTest):
self.config._openssl_version = None self.config._openssl_version = None
self.config.options.bin = None self.config.options.bin = None
self.config.parser.modules['ssl_module'] = None self.config.parser.modules['ssl_module'] = None
with mock.patch("certbot_apache._internal.configurator.logger.warning") as mock_log: with mock.patch("certbot._internal.plugins.apache.configurator.logger.warning") as mock_log:
assert self.config.openssl_version() is None assert self.config.openssl_version() is None
assert "ssl_module is statically linked but" in mock_log.call_args[0][0] assert "ssl_module is statically linked but" in mock_log.call_args[0][0]
self.config.parser.modules['ssl_module'] = "/fake/path" self.config.parser.modules['ssl_module'] = "/fake/path"
with mock.patch("certbot_apache._internal.configurator.logger.warning") as mock_log: with mock.patch("certbot._internal.plugins.apache.configurator.logger.warning") as mock_log:
# Check that correct logger.warning was printed # Check that correct logger.warning was printed
assert self.config.openssl_version() is None assert self.config.openssl_version() is None
assert "Unable to read" in mock_log.call_args[0][0] assert "Unable to read" in mock_log.call_args[0][0]
contents_missing_openssl = b"these contents won't match the regex" contents_missing_openssl = b"these contents won't match the regex"
with mock.patch("certbot_apache._internal.configurator." with mock.patch("certbot._internal.plugins.apache.configurator."
"ApacheConfigurator._open_module_file") as mock_omf: "ApacheConfigurator._open_module_file") as mock_omf:
mock_omf.return_value = contents_missing_openssl mock_omf.return_value = contents_missing_openssl
with mock.patch("certbot_apache._internal.configurator.logger.warning") as mock_log: with mock.patch("certbot._internal.plugins.apache.configurator.logger.warning") as mock_log:
# Check that correct logger.warning was printed # Check that correct logger.warning was printed
assert self.config.openssl_version() is None assert self.config.openssl_version() is None
assert "Could not find OpenSSL" in mock_log.call_args[0][0] assert "Could not find OpenSSL" in mock_log.call_args[0][0]

Some files were not shown because too many files have changed in this diff Show More