internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: Mailu/Mailu

Issue:
CLI domain creation arguments bug
When creating a new domain using cli we have optional arguments that can be passed

```bash
$ docker-compose exec admin flask mailu domain --help
Usage: flask mailu domain [OPTIONS] DOMAIN_NAME

  Create a domain

Options:
  -u, --max-users TEXT
  -a, --max-aliases TEXT
  -q, --max-quota-bytes TEXT
  --help                      Show this message and exit.
```

Looks like we are passing only domain name, keeping the rest of variables to default
https://github.com/Mailu/Mailu/blob/626b8a9d05bed54777704124a77ef4a884a4d052/core/admin/mailu/manage.py#L97



Discussion:

Resolving patch:
diff --git a/core/admin/mailu/manage.py b/core/admin/mailu/manage.py
--- a/core/admin/mailu/manage.py
+++ b/core/admin/mailu/manage.py
@@ -94,7 +94,8 @@ def user(localpart, domain_name, password, hash_scheme=None):
 def domain(domain_name, max_users=-1, max_aliases=-1, max_quota_bytes=0):
     domain = models.Domain.query.get(domain_name)
     if not domain:
-        domain = models.Domain(name=domain_name)
+        domain = models.Domain(name=domain_name, max_users=max_users,
+                               max_aliases=max_aliases, max_quota_bytes=max_quota_bytes)
         db.session.add(domain)
         db.session.commit()
 


Test patch:
Repository: Mailu/Mailu

Issue:
Internal Error with setup
Hi,

Thanks for the work !

I want to try the new version with setup.mailu.io + Docker stack. However I have already this when I want to generate my compose:

> Internal Server Error
> The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

Is it normal?


Discussion:
Stack is experimental-ish. I hope you've seen the warning on setup?

>Setup is capable of generating a somewhat decent docker-compose.yml, for the docker stack flavor. However its usage is for advanced users an is experimental. Expect many challenges is shared mail storage and fail-over scenarios! Some user experiences have been shared on GitHub.

You kinda have to fiddle with the config to make it work. Or be more specific to us on the error, (like log output).
Hi, This is not only an issue with swarm. I got the same error generating a regular docker-compose.
![image](https://user-images.githubusercontent.com/16164175/53271141-462b9380-36cc-11e9-83f2-d47a81690294.png)


Resolving patch:
diff --git a/setup/server.py b/setup/server.py
--- a/setup/server.py
+++ b/setup/server.py
@@ -90,7 +90,10 @@ def submit_flavor():
     def submit():
         data = flask.request.form.copy()
         data['uid'] = str(uuid.uuid4())
-        data['dns'] = str(ipaddress.IPv4Network(data['subnet'])[-2])
+        try:
+            data['dns'] = str(ipaddress.IPv4Network(data['subnet'])[-2])
+        except ValueError as err:
+            return "Error while generating files: " + str(err)
         db.set(data['uid'], json.dumps(data))
         return flask.redirect(flask.url_for('.setup', uid=data['uid']))
 


Test patch:
Repository: Mailu/Mailu

Issue:
Should `antispam` be hardcoded?
I'm in a middle of setting up my own mailu instances, however I'm using namespaced container names (i.e. `mailu-admin`, `mailu-front` etc.). Everything works pretty well so far, however I have some problems with imap and antispam. After some investigation I noticed, that files `core/dovecot/conf/bin/ham` and `core/dovecot/conf/bin/spam` have antispam host hardcoded instead of using `HOST_ANTISPAM`. 

I'm happy to provide PR, but firstly want to be sure - is it in fact oversight, or is this by design?
Should `antispam` be hardcoded?
I'm in a middle of setting up my own mailu instances, however I'm using namespaced container names (i.e. `mailu-admin`, `mailu-front` etc.). Everything works pretty well so far, however I have some problems with imap and antispam. After some investigation I noticed, that files `core/dovecot/conf/bin/ham` and `core/dovecot/conf/bin/spam` have antispam host hardcoded instead of using `HOST_ANTISPAM`. 

I'm happy to provide PR, but firstly want to be sure - is it in fact oversight, or is this by design?


Discussion:
Nope, it should not be hardcoded, any PR on the matter is more than welcome :)
Nope, it should not be hardcoded, any PR on the matter is more than welcome :)

Resolving patch:
diff --git a/core/dovecot/start.py b/core/dovecot/start.py
--- a/core/dovecot/start.py
+++ b/core/dovecot/start.py
@@ -24,6 +24,7 @@ def start_podop():
 os.environ["FRONT_ADDRESS"] = system.resolve_address(os.environ.get("HOST_FRONT", "front"))
 os.environ["REDIS_ADDRESS"] = system.resolve_address(os.environ.get("HOST_REDIS", "redis"))
 os.environ["ADMIN_ADDRESS"] = system.resolve_address(os.environ.get("HOST_ADMIN", "admin"))
+os.environ["ANTISPAM_ADDRESS"] = system.resolve_address(os.environ.get("HOST_ANTISPAM", "antispam:11334"))
 if os.environ["WEBMAIL"] != "none":
     os.environ["WEBMAIL_ADDRESS"] = system.resolve_address(os.environ.get("HOST_WEBMAIL", "webmail"))
 
diff --git a/services/rspamd/start.py b/services/rspamd/start.py
--- a/services/rspamd/start.py
+++ b/services/rspamd/start.py
@@ -9,11 +9,14 @@
 log.basicConfig(stream=sys.stderr, level=os.environ.get("LOG_LEVEL", "WARNING"))
 
 # Actual startup script
+
 os.environ["FRONT_ADDRESS"] = system.resolve_address(os.environ.get("HOST_FRONT", "front"))
 
 if "HOST_REDIS" not in os.environ:
     os.environ["REDIS_ADDRESS"] = system.resolve_address(os.environ.get("HOST_REDIS", "redis"))
 
+if os.environ.get("ANTIVIRUS") == 'clamav':
+    os.environ["ANTIVIRUS_ADDRESS"] = system.resolve_address(os.environ.get("HOST_ANTIVIRUS", "antivirus:3310"))
 
 for rspamd_file in glob.glob("/conf/*"):
     conf.jinja(rspamd_file, os.environ, os.path.join("/etc/rspamd/local.d", os.path.basename(rspamd_file)))


Test patch:
Repository: Mailu/Mailu

Issue:
Regular alpine base-image update
To receive current updates for upstream projects, security fixes and new features such as mentioned in #1049 , let’s upgrade the alpine baseimage to latest 3.10


Discussion:

Resolving patch:
diff --git a/core/postfix/start.py b/core/postfix/start.py
--- a/core/postfix/start.py
+++ b/core/postfix/start.py
@@ -53,12 +53,7 @@ def start_podop():
     convert("/conf/sasl_passwd", path)
     os.system("postmap {}".format(path))
 
-convert("/conf/rsyslog.conf", "/etc/rsyslog.conf")
-
 # Run Podop and Postfix
 multiprocessing.Process(target=start_podop).start()
-if os.path.exists("/var/run/rsyslogd.pid"):
-    os.remove("/var/run/rsyslogd.pid")
-os.system("/usr/lib/postfix/post-install meta_directory=/etc/postfix create-missing")
-os.system("/usr/lib/postfix/master &")
-os.execv("/usr/sbin/rsyslogd", ["rsyslogd", "-n"])
+os.system("/usr/libexec/postfix/post-install meta_directory=/etc/postfix create-missing")
+os.system("postfix start-fg")


Test patch:
Repository: Mailu/Mailu

Issue:
Update user password in commandline
A feature request, the ability to set/reset a user's password from the Mailu command line. Similar to the [user](https://mailu.io/master/cli.html#user) command:

```
docker-compose exec admin flask mailu password myuser example.net 'password123'
```

My particular interest is for the Demo server, some people find it necessary to change the admin password from time to time. Executing a full reset takes over a minute, in which period the Demo is not available. I don't want to execute it more frequent than daily. It would be nice to can just call above command every few minutes and always override the admin's password with the correct one. See also #987.



Discussion:

Resolving patch:
diff --git a/core/admin/mailu/manage.py b/core/admin/mailu/manage.py
--- a/core/admin/mailu/manage.py
+++ b/core/admin/mailu/manage.py
@@ -85,6 +85,26 @@ def user(localpart, domain_name, password, hash_scheme=None):
     db.session.commit()
 
 
+@mailu.command()
+@click.argument('localpart')
+@click.argument('domain_name')
+@click.argument('password')
+@click.argument('hash_scheme', required=False)
+@flask_cli.with_appcontext
+def password(localpart, domain_name, password, hash_scheme=None):
+    """ Change the password of an user
+    """
+    email = '{0}@{1}'.format(localpart, domain_name)
+    user   = models.User.query.get(email)
+    if hash_scheme is None:
+        hash_scheme = app.config['PASSWORD_SCHEME']
+    if user:
+        user.set_password(password, hash_scheme=hash_scheme)
+    else:
+        print("User " + email + " not found.")
+    db.session.commit()
+
+
 @mailu.command()
 @click.argument('domain_name')
 @click.option('-u', '--max-users')


Test patch:
Repository: Mailu/Mailu

Issue:
Setup error for incorrect docker network subnet
When entering an incorrect docker subnet (e.g. 172.168.0.1/16) the setup throws a 500 error -- without any reasons being given. 

If you run locally, the error is clearly reported in an ungraceful way.


Discussion:

Resolving patch:
diff --git a/setup/server.py b/setup/server.py
--- a/setup/server.py
+++ b/setup/server.py
@@ -91,7 +91,7 @@ def submit():
         data = flask.request.form.copy()
         data['uid'] = str(uuid.uuid4())
         try:
-            data['dns'] = str(ipaddress.IPv4Network(data['subnet'])[-2])
+            data['dns'] = str(ipaddress.IPv4Network(data['subnet'], strict=False)[-2])
         except ValueError as err:
             return "Error while generating files: " + str(err)
         db.set(data['uid'], json.dumps(data))


Test patch:
Repository: Mailu/Mailu

Issue:
Unnecessary assignment on `HOST_WEBMAIL`
We came across another piece of garbage:

https://github.com/Mailu/Mailu/blob/f3f0c3190be9ab9b53a29c5b0326fc9a4602df46/core/nginx/config.py#L19

https://github.com/Mailu/Mailu/blob/f3f0c3190be9ab9b53a29c5b0326fc9a4602df46/core/nginx/config.py#L22


Discussion:

Resolving patch:
diff --git a/core/nginx/config.py b/core/nginx/config.py
--- a/core/nginx/config.py
+++ b/core/nginx/config.py
@@ -16,12 +16,10 @@
 
 args["ADMIN_ADDRESS"] = system.resolve_address(args.get("HOST_ADMIN", "admin"))
 args["ANTISPAM_ADDRESS"] = system.resolve_address(args.get("HOST_ANTISPAM", "antispam:11334"))
-args["HOST_WEBMAIL"] = args.get("HOST_WEBMAIL", "webmail")
 if args["WEBMAIL"] != "none":
-    args["WEBMAIL_ADDRESS"] = system.resolve_address(args.get("HOST_WEBMAIL"))
-args["HOST_WEBDAV"] = args.get("HOST_WEBDAV", "webdav:5232")
+    args["WEBMAIL_ADDRESS"] = system.resolve_address(args.get("HOST_WEBMAIL", "webmail"))
 if args["WEBDAV"] != "none":
-    args["WEBDAV_ADDRESS"] = system.resolve_address(args.get("HOST_WEBDAV"))
+    args["WEBDAV_ADDRESS"] = system.resolve_address(args.get("HOST_WEBDAV", "webdav:5232"))
 
 # TLS configuration
 cert_name = os.getenv("TLS_CERT_FILENAME", default="cert.pem")


Test patch:
Repository: Mailu/Mailu

Issue:
Redis address parsing is done in init_app
This was added in #1107:

https://github.com/Mailu/Mailu/blob/f3f0c3190be9ab9b53a29c5b0326fc9a4602df46/core/admin/mailu/configuration.py#L11-L12

While, `REDIS_ADDRESS` is now only resolved in `init_app`. (#940). We took care of that in:

https://github.com/Mailu/Mailu/blob/f3f0c3190be9ab9b53a29c5b0326fc9a4602df46/core/admin/mailu/configuration.py#L116-L117

I believe DEFAULT_CONFIG should be like:

https://github.com/Mailu/Mailu/blob/4c25c83419be128fb12591721627a718ec23f69d/core/admin/mailu/configuration.py#L12-L13

We are now in the process of backporting #940 to 1.7. PR #1107 was not backported. Therefore 1.7 will look like the last snippet.

CC @mildred, @kaiyou 


Discussion:
I rebranched, so I'll provide a quick PR to fix this.

Resolving patch:
diff --git a/core/admin/mailu/configuration.py b/core/admin/mailu/configuration.py
--- a/core/admin/mailu/configuration.py
+++ b/core/admin/mailu/configuration.py
@@ -8,8 +8,8 @@
     'BABEL_DEFAULT_LOCALE': 'en',
     'BABEL_DEFAULT_TIMEZONE': 'UTC',
     'BOOTSTRAP_SERVE_LOCAL': True,
-    'RATELIMIT_STORAGE_URL': 'redis://%s/2' % (os.getenv("REDIS_ADDRESS", "redis")),
-    'QUOTA_STORAGE_URL': 'redis://%s/1' % (os.getenv("REDIS_ADDRESS", "redis")),
+    'RATELIMIT_STORAGE_URL': '',
+    'QUOTA_STORAGE_URL': '',
     'DEBUG': False,
     'DOMAIN_REGISTRATION': False,
     'TEMPLATES_AUTO_RELOAD': True,


Test patch:
Repository: Mailu/Mailu

Issue:
Make access logging of admin server dependent on log level
Currently, admin logs all access logs to the console, regardless of which log level is set.
This is caused by starting gunicorn with `--access-logfile -`. This should be switched dependent on the log level set, e.g. on for levels >= INFO and off for <=WARNING
 


Discussion:

Resolving patch:
diff --git a/core/admin/start.py b/core/admin/start.py
--- a/core/admin/start.py
+++ b/core/admin/start.py
@@ -1,6 +1,10 @@
 #!/usr/bin/python3
 
 import os
+import logging as log
+import sys
+
+log.basicConfig(stream=sys.stderr, level=os.environ.get("LOG_LEVEL", "INFO"))
 
 os.system("flask mailu advertise")
 os.system("flask db upgrade")
@@ -11,6 +15,14 @@
 
 if account is not None and domain is not None and password is not None:
     mode = os.environ.get("INITIAL_ADMIN_MODE", default="ifmissing")
+    log.info("Creating initial admin accout %s@%s with mode %s",account,domain,mode)
     os.system("flask mailu admin %s %s '%s' --mode %s" % (account, domain, password, mode))
 
-os.system("gunicorn -w 4 -b :80 --access-logfile - --error-logfile - --preload 'mailu:create_app()'")
+start_command="".join([
+    "gunicorn -w 4 -b :80 ",
+    "--access-logfile - " if (log.root.level<=log.INFO) else "",
+    "--error-logfile - ",
+    "--preload ",
+    "'mailu:create_app()'"])
+
+os.system(start_command)


Test patch:
Repository: Mailu/Mailu

Issue:
Make roundcube log to the console
Roundcube is currently hard to debug because it logs into a special folder (/var/www/html/logs). It should log to stdout/stderr instead.


Discussion:

Resolving patch:
diff --git a/webmails/roundcube/start.py b/webmails/roundcube/start.py
--- a/webmails/roundcube/start.py
+++ b/webmails/roundcube/start.py
@@ -4,16 +4,61 @@
 import logging as log
 import sys
 from socrate import conf
+import subprocess
 
 log.basicConfig(stream=sys.stderr, level=os.environ.get("LOG_LEVEL", "WARNING"))
 
 os.environ["MAX_FILESIZE"] = str(int(int(os.environ.get("MESSAGE_SIZE_LIMIT"))*0.66/1048576))
 
+db_flavor=os.environ.get("ROUNDCUBE_DB_FLAVOR",os.environ.get("DB_FLAVOR","sqlite"))
+if db_flavor=="sqlite":
+    os.environ["DB_DSNW"]="sqlite:////data/roundcube.db"
+elif db_flavor=="mysql":
+    os.environ["DB_DSNW"]="mysql://%s:%s@%s/%s" % (
+        os.environ.get("ROUNDCUBE_DB_USER","roundcube"),
+        os.environ.get("ROUNDCUBE_DB_PW"),
+        os.environ.get("ROUNDCUBE_DB_HOST",os.environ.get("DB_HOST","database")),
+        os.environ.get("ROUNDCUBE_DB_NAME","roundcube")
+        )
+elif db_flavor=="postgresql":
+    os.environ["DB_DSNW"]="pgsql://%s:%s@%s/%s" % (
+        os.environ.get("ROUNDCUBE_DB_USER","roundcube"),
+        os.environ.get("ROUNDCUBE_DB_PW"),
+        os.environ.get("ROUNDCUBE_DB_HOST",os.environ.get("DB_HOST","database")),
+        os.environ.get("ROUNDCUBE_DB_NAME","roundcube")
+        )
+else:
+    print("Unknown ROUNDCUBE_DB_FLAVOR: %s",db_flavor)
+    exit(1)
+
+
+
 conf.jinja("/php.ini", os.environ, "/usr/local/etc/php/conf.d/roundcube.ini")
 
 # Fix some permissions
-os.system("mkdir -p /data/gpg")
-os.system("chown -R www-data:www-data /data")
+os.system("mkdir -p /data/gpg /var/www/html/logs")
+os.system("touch /var/www/html/logs/errors")
+os.system("chown -R www-data:www-data /data /var/www/html/logs")
+
+try:
+    print("Initializing database")
+    result=subprocess.check_output(["/var/www/html/bin/initdb.sh","--dir","/var/www/html/SQL"],stderr=subprocess.STDOUT)
+    print(result.decode())
+except subprocess.CalledProcessError as e:
+    if "already exists" in e.stdout.decode():
+        print("Already initialzed")
+    else:
+        print(e.stdout.decode())
+        quit(1)
+
+try:
+    print("Upgrading database")
+    subprocess.check_call(["/var/www/html/bin/update.sh","--version=?","-y"],stderr=subprocess.STDOUT)
+except subprocess.CalledProcessError as e:
+    quit(1)
+
+# Tail roundcube logs
+subprocess.Popen(["tail","-f","-n","0","/var/www/html/logs/errors"])
 
 # Run apache
 os.execv("/usr/local/bin/apache2-foreground", ["apache2-foreground"])


Test patch:
Repository: Mailu/Mailu

Issue:
sieve filtering based on recipient_delimiter no longer works in 1.6
I have a sieve rule setup to automatically sort mails into folders based on the part after the recipient delimiter, so mail to `foo+bar@example.com` would get sorted into folder `bar` provided it exists.
The rule for this is as follows:
```
require ["envelope","fileinto","subaddress","variables"];
if envelope :detail :matches "to" "*"
{
	fileinto "${1}";
}
```

This worked fine in Mailu 1.5, but ever since upgrading to 1.6 all those mails get filed just into `INBOX`. Sieve evaluation itself is working, as other rules get applied properly.


Discussion:
I did some further digging and the recipient address in the envelope gets rewritten to the canonical user address when the mail is forwarded via LMTP to dovecot.

Relevant header in 1.5:
```
Received: from mail.example.com ([172.18.0.10])
        by mail.example.com with LMTP id mOZHIEl4i1zFRgAAkeXSCA
        for <foo+bar@example.com>; Fri, 15 Mar 2019 10:02:49 +0000
...
To: foo+bar@example.com
```

Header after the upgrade to 1.6:
```
Received: from mail.example.com ([172.18.0.12])
        by mail.example.com with LMTP
        id wG8HKAluj1zCXAAAfVZfzA
        (envelope-from <redacted>)
        for <foo@example.com>; Mon, 18 Mar 2019 10:08:09 +0000
...
To: foo+bar@example.com
```

I think that rewrite was introduced in #778 to fix #755. Is there a way to pass the envelope information to dovecot again to allow the aforementioned filtering based on the detail part?
I'm setting up a new Mailu installation (so running 1.7) and migrating over some Sieve scripts from a previous mail setup (not Mailu). And I still seem to be able to confirm this? At least it's not working and I'm seeing the same in the mail headers where the address extension / recipient delimiter is removed in the last part (LMTP delivery from Postfix to Dovecot).

Resolving patch:
diff --git a/core/admin/mailu/models.py b/core/admin/mailu/models.py
--- a/core/admin/mailu/models.py
+++ b/core/admin/mailu/models.py
@@ -277,12 +277,14 @@ def resolve_destination(cls, localpart, domain_name, ignore_forward_keep=False):
         if not user and localpart_stripped:
             user = User.query.get('{}@{}'.format(localpart_stripped, domain_name))
         if user:
+            email = '{}@{}'.format(localpart, domain_name)
+
             if user.forward_enabled:
                 destination = user.forward_destination
                 if user.forward_keep or ignore_forward_keep:
-                    destination.append(user.email)
+                    destination.append(email)
             else:
-                destination = [user.email]
+                destination = [email]
             return destination
 
         pure_alias = Alias.resolve(localpart, domain_name)


Test patch:
Repository: Mailu/Mailu

Issue:
Certwatcher does not work with symlinks (on Kubernetes)
I need to recheck this, but I just had this issue... Will report in 3 Months


Discussion:
I can confirm it, the certs in k8s are renewed but nginx is not reloaded. I did not restart it yet to have the option to debug it further
Looks like an issue in certwatcher, dealing with symlinks:

```
bash-5.0# ls -al /certs
total 4
drwxrwxrwt    3 root     root           120 Dec 30 07:21 .
drwxr-xr-x    1 root     root          4096 Nov 30 08:24 ..
drwxr-xr-x    2 root     root            80 Dec 30 07:21 ..2019_12_30_07_21_59.992633671
lrwxrwxrwx    1 root     root            31 Dec 30 07:21 ..data -> ..2019_12_30_07_21_59.992633671
lrwxrwxrwx    1 root     root            15 Nov 30 08:24 cert.pem -> ..data/cert.pem
lrwxrwxrwx    1 root     root            14 Nov 30 08:24 key.pem -> ..data/key.pem
```
We need to investigate in it, create a test case with symlinks, get it fixed.
I did some manual tests:

- Direct symlinks works (e.g. cert.pem linked to cert1.pem, then re-linked to cert2.pem triggers the reload/reconfig).
- Indirect symlinks (cert.pem linked to a symlink or symlinked directory which target is changed) are not detected

So the problem here is the way kubernetes changes the symlink.

Resolving patch:
diff --git a/core/nginx/certwatcher.py b/core/nginx/certwatcher.py
--- a/core/nginx/certwatcher.py
+++ b/core/nginx/certwatcher.py
@@ -8,7 +8,7 @@
 from os.path import exists, split as path_split
 from os import system
 import time
-from watchdog.observers import Observer
+from watchdog.observers.polling import PollingObserver
 from watchdog.events import FileSystemEventHandler, FileDeletedEvent, \
     FileCreatedEvent, FileModifiedEvent, FileMovedEvent
 
@@ -49,7 +49,7 @@ def on_any_event(self, event):
 
 
 if __name__ == '__main__':
-    observer = Observer()
+    observer = PollingObserver()
     handler = ChangeHandler()
     observer.schedule(handler, "/certs", recursive=False)
     observer.start()


Test patch:
Repository: Mailu/Mailu

Issue:
Rainloop Webmail - Authentication fails if you have a special character in your password
In the admin interface, you can define a new password and you can put a special character like `è`.

It works fine with admin interface but it doesn't work at all with the Rainloop webmail. If you try to log in, you will have a message to indicate that the authentication fails, see screenshoot in french:

![Capture d’écran de 2019-08-25 10-57-56](https://user-images.githubusercontent.com/21110485/63647853-904b0b80-c727-11e9-9938-d66a1e10ca4e.png)



Discussion:
Same for me with "password" ...
@fldu My issue is about the password with a special character not the username (even if hidden in my screenshot).

and if your password is "password" it should work afaik :)
@Angedestenebres no, i checked, but maybe a variable was added and I didn't set it... for the moment i rolled back and it works
Really, standard password should work, if they do not, then your setup is probably broken somewhere. Please open a separate issue if you struggle with it or come and discuss it on our matrix chan.

Resolving patch:
diff --git a/core/admin/mailu/internal/nginx.py b/core/admin/mailu/internal/nginx.py
--- a/core/admin/mailu/internal/nginx.py
+++ b/core/admin/mailu/internal/nginx.py
@@ -37,8 +37,14 @@ def handle_authentication(headers):
     # Authenticated user
     elif method == "plain":
         server, port = get_server(headers["Auth-Protocol"], True)
-        user_email = urllib.parse.unquote(headers["Auth-User"])
-        password = urllib.parse.unquote(headers["Auth-Pass"])
+        # According to RFC2616 section 3.7.1 and PEP 3333, HTTP headers should
+        # be ASCII and are generally considered ISO8859-1. However when passing
+        # the password, nginx does not transcode the input UTF string, thus
+        # we need to manually decode.
+        raw_user_email = urllib.parse.unquote(headers["Auth-User"])
+        user_email = raw_user_email.encode("iso8859-1").decode("utf8")
+        raw_password = urllib.parse.unquote(headers["Auth-Pass"])
+        password = raw_password.encode("iso8859-1").decode("utf8")
         ip = urllib.parse.unquote(headers["Client-Ip"])
         user = models.User.query.get(user_email)
         status = False


Test patch: