Repository: certbot/certbot

Issue:
Invalid warning about Apache redirect
With a fresh install of Apache on Debian Jessie, I created this vhost:

```
<VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        ServerName example.com
        ServerAlias www.example.com

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf
</VirtualHost>
```

This is the only vhost I had enabled. When running `letsencrypt run --redirect` I get the error message:

```
WARNING:letsencrypt.client:Enhancement redirect was already set.
```

Despite this error message, the redirect was correctly enabled. Are we trying to set up the redirect twice?



Discussion:
So, you've run the client exactly once and it produces that error?  That is a little weird.  I would expect the error if you re-ran things a second time (the client doesn't yet have a way of telling that it had already enabled redirects in the past).  But not for it to try twice in one run.

@sagi, any thoughts on this?

Yes. I got this error when running the client for the first time.

I couldn't reproduce it.

I tried to delete the renewal / archive / live files for a specific domain, then ran the `letsencrypt run --redirect`. 

In the first trial I selected only the ServerName from the domain list, and in the second trial (again deleting the renewal / archive / live) both the ServerName and the ServerAlias.

@sagi: Here's a [recording](https://asciinema.org/a/159cgn15k9oji4jjfsrcb1rif) of the problem. I hope this helps you repo it.

Awesome! Thanks! 

Since we don't have a PR for this, kicking it to 0.7.0!

Still can't reproduce it. Would appreciate if we can sit and talk about it @bmw.

@sagi, sure! I'm planning on working from home tomorrow, but I'm free to work with you on it on Wednesday if you're available.

Great! I'm available.


Resolving patch:
diff --git a/certbot-apache/certbot_apache/configurator.py b/certbot-apache/certbot_apache/configurator.py
--- a/certbot-apache/certbot_apache/configurator.py
+++ b/certbot-apache/certbot_apache/configurator.py
@@ -124,6 +124,8 @@ def __init__(self, *args, **kwargs):
         self.assoc = dict()
         # Outstanding challenges
         self._chall_out = set()
+        # Maps enhancements to vhosts we've enabled the enhancement for
+        self._enhanced_vhosts = defaultdict(set)
 
         # These will be set in the prepare function
         self.parser = None
@@ -1058,9 +1060,6 @@ def _enable_redirect(self, ssl_vhost, unused_options):
         :param unused_options: Not currently used
         :type unused_options: Not Available
 
-        :returns: Success, general_vhost (HTTP vhost)
-        :rtype: (bool, :class:`~certbot_apache.obj.VirtualHost`)
-
         :raises .errors.PluginError: If no viable HTTP host can be created or
             used for the redirect.
 
@@ -1083,6 +1082,10 @@ def _enable_redirect(self, ssl_vhost, unused_options):
                         "redirection")
             self._create_redirect_vhost(ssl_vhost)
         else:
+            if general_vh in self._enhanced_vhosts["redirect"]:
+                logger.debug("Already enabled redirect for this vhost")
+                return
+
             # Check if Certbot redirection already exists
             self._verify_no_certbot_redirect(general_vh)
 
@@ -1118,6 +1121,7 @@ def _enable_redirect(self, ssl_vhost, unused_options):
                                 (general_vh.filep, ssl_vhost.filep))
             self.save()
 
+            self._enhanced_vhosts["redirect"].add(general_vh)
             logger.info("Redirecting vhost in %s to ssl vhost in %s",
                         general_vh.filep, ssl_vhost.filep)
 
@@ -1206,6 +1210,7 @@ def _create_redirect_vhost(self, ssl_vhost):
         # Make a new vhost data structure and add it to the lists
         new_vhost = self._create_vhost(parser.get_aug_path(redirect_filepath))
         self.vhosts.append(new_vhost)
+        self._enhanced_vhosts["redirect"].add(new_vhost)
 
         # Finally create documentation for the change
         self.save_notes += ("Created a port 80 vhost, %s, for redirection to "


Test patch:
diff --git a/certbot-apache/certbot_apache/tests/configurator_test.py b/certbot-apache/certbot_apache/tests/configurator_test.py
--- a/certbot-apache/certbot_apache/tests/configurator_test.py
+++ b/certbot-apache/certbot_apache/tests/configurator_test.py
@@ -938,15 +938,31 @@ def test_redirect_with_conflict(self):
         self.assertRaises(
             errors.PluginError, self.config._enable_redirect, ssl_vh, "")
 
-    def test_redirect_twice(self):
+    def test_redirect_two_domains_one_vhost(self):
         # Skip the enable mod
         self.config.parser.modules.add("rewrite_module")
         self.config.get_version = mock.Mock(return_value=(2, 3, 9))
 
-        self.config.enhance("encryption-example.demo", "redirect")
+        self.config.enhance("red.blue.purple.com", "redirect")
+        verify_no_redirect = ("certbot_apache.configurator."
+                              "ApacheConfigurator._verify_no_certbot_redirect")
+        with mock.patch(verify_no_redirect) as mock_verify:
+            self.config.enhance("green.blue.purple.com", "redirect")
+        self.assertFalse(mock_verify.called)
+
+    def test_redirect_from_previous_run(self):
+        # Skip the enable mod
+        self.config.parser.modules.add("rewrite_module")
+        self.config.get_version = mock.Mock(return_value=(2, 3, 9))
+
+        self.config.enhance("red.blue.purple.com", "redirect")
+        # Clear state about enabling redirect on this run
+        # pylint: disable=protected-access
+        self.config._enhanced_vhosts["redirect"].clear()
+
         self.assertRaises(
             errors.PluginEnhancementAlreadyPresent,
-            self.config.enhance, "encryption-example.demo", "redirect")
+            self.config.enhance, "green.blue.purple.com", "redirect")
 
     def test_create_own_redirect(self):
         self.config.parser.modules.add("rewrite_module")