From 1782b69405e9820ed01c120c7d080943f975670f Mon Sep 17 00:00:00 2001 From: Teal Dulcet Date: Sun, 12 Jan 2025 06:07:00 -0800 Subject: [PATCH] Fixed PLC1901 (compare-to-empty-string) --- management/auth.py | 4 ++-- management/backup.py | 2 +- management/daemon.py | 14 +++++++------- management/dns_update.py | 4 ++-- management/email_administrator.py | 2 +- management/mailconfig.py | 18 +++++++++--------- management/mfa.py | 2 +- management/status_checks.py | 6 +++--- tools/readable_bash.py | 8 ++++---- 9 files changed, 30 insertions(+), 30 deletions(-) diff --git a/management/auth.py b/management/auth.py index 873047d5..66993506 100644 --- a/management/auth.py +++ b/management/auth.py @@ -52,7 +52,7 @@ class AuthService: msg = "Authorization header invalid." raise ValueError(msg) - if username.strip() == "" and password.strip() == "": + if not username.strip() and not password.strip(): msg = "No email address, password, session key, or API key provided." raise ValueError(msg) @@ -73,7 +73,7 @@ class AuthService: self.sessions[sessionid] = session # If no password was given, but a username was given, we're missing some information. - elif password.strip() == "": + elif not password.strip(): msg = "Enter a password." raise ValueError(msg) diff --git a/management/backup.py b/management/backup.py index b7a23c25..a47f54e8 100755 --- a/management/backup.py +++ b/management/backup.py @@ -511,7 +511,7 @@ def list_target_files(config): if path == '/': path = '' - if bucket == "": + if not bucket: msg = "Enter an S3 bucket name." raise ValueError(msg) diff --git a/management/daemon.py b/management/daemon.py index be67f409..046d5851 100755 --- a/management/daemon.py +++ b/management/daemon.py @@ -37,7 +37,7 @@ with contextlib.suppress(OSError): csr_country_codes = [] with open(os.path.join(os.path.dirname(me), "csr_country_codes.tsv"), encoding="utf-8") as f: for line in f: - if line.strip() == "" or line.startswith("#"): continue + if not line.strip() or line.startswith("#"): continue code, name = line.strip().split("\t")[0:2] csr_country_codes.append((code, name)) @@ -281,7 +281,7 @@ def dns_get_secondary_nameserver(): def dns_set_secondary_nameserver(): from dns_update import set_secondary_dns try: - return set_secondary_dns([ns.strip() for ns in re.split(r"[, ]+", request.form.get('hostnames') or "") if ns.strip() != ""], env) + return set_secondary_dns([ns.strip() for ns in re.split(r"[, ]+", request.form.get('hostnames') or "") if ns.strip()], env) except ValueError as e: return (str(e), 400) @@ -352,11 +352,11 @@ def dns_set_record(qname, rtype="A"): if request.method in {"POST", "PUT"}: # There is a default value for A/AAAA records. - if rtype in {"A", "AAAA"} and value == "": + if rtype in {"A", "AAAA"} and not value: value = request.environ.get("HTTP_X_FORWARDED_FOR") # normally REMOTE_ADDR but we're behind nginx as a reverse proxy # Cannot add empty records. - if value == '': + if not value: return ("No value for the record provided.", 400) if request.method == "POST": @@ -370,7 +370,7 @@ def dns_set_record(qname, rtype="A"): action = "set" elif request.method == "DELETE": - if value == '': + if not value: # Delete all records for this qname-type pair. value = None else: @@ -678,7 +678,7 @@ def authorized_personnel_only_via_cookie(f): @authorized_personnel_only_via_cookie def munin_static_file(filename=""): # Proxy the request to static files. - if filename == "": filename = "index.html" + if not filename: filename = "index.html" return send_from_directory("/var/cache/munin/www", filename) @app.route('/munin/cgi-graph/') @@ -707,7 +707,7 @@ def munin_cgi(filename): # -c "/usr/lib/munin/cgi/munin-cgi-graph" passes the command to run as munin # "%s" is a placeholder for where the request's querystring will be added - if filename == "": + if not filename: return ("a path must be specified", 404) query_str = request.query_string.decode("utf-8", 'ignore') diff --git a/management/dns_update.py b/management/dns_update.py index b874624e..104aa615 100755 --- a/management/dns_update.py +++ b/management/dns_update.py @@ -264,7 +264,7 @@ def build_zone(domain, domain_properties, additional_records, env, is_zone=True) (None, "AAAA", env.get('PUBLIC_IPV6'), f"Optional. Sets the IPv6 address that {domain} resolves to, e.g. for web hosting. (It is not necessary for receiving mail on this domain.)"), ] for qname, rtype, value, explanation in defaults: - if value is None or value.strip() == "": continue # skip IPV6 if not set + if value is None or not value.strip(): continue # skip IPV6 if not set if not is_zone and qname == "www": continue # don't create any default 'www' subdomains on what are themselves subdomains # Set the default record, but not if: # (1) there is not a user-set record of the same type already @@ -456,7 +456,7 @@ def build_sshfp_records(): keys = sorted(keys.split("\n")) for key in keys: - if key.strip() == "" or key[0] == "#": continue + if not key.strip() or key[0] == "#": continue try: _host, keytype, pubkey = key.split(" ") yield "%d %d ( %s )" % ( diff --git a/management/email_administrator.py b/management/email_administrator.py index e5307e32..0fea4ad9 100755 --- a/management/email_administrator.py +++ b/management/email_administrator.py @@ -28,7 +28,7 @@ admin_addr = "administrator@" + env['PRIMARY_HOSTNAME'] content = sys.stdin.read().strip() # If there's nothing coming in, just exit. -if content == "": +if not content: sys.exit(0) # create MIME message diff --git a/management/mailconfig.py b/management/mailconfig.py index 65bb4ad2..90e1cfdb 100755 --- a/management/mailconfig.py +++ b/management/mailconfig.py @@ -268,7 +268,7 @@ def get_mail_domains(env, filter_aliases=lambda alias : True, users_only=False): def add_mail_user(email, pw, privs, env): # validate email - if email.strip() == "": + if not email.strip(): return ("No email address provided.", 400) if not validate_email(email): return ("Invalid email address.", 400) @@ -284,7 +284,7 @@ def add_mail_user(email, pw, privs, env): validate_password(pw) # validate privileges - if privs is None or privs.strip() == "": + if privs is None or not privs.strip(): privs = [] else: privs = privs.split("\n") @@ -357,7 +357,7 @@ def remove_mail_user(email, env): return kick(env, "mail user removed") def parse_privs(value): - return [p for p in value.split("\n") if p.strip() != ""] + return [p for p in value.split("\n") if p.strip()] def get_mail_user_privileges(email, env, empty_on_error=False): # get privs @@ -370,7 +370,7 @@ def get_mail_user_privileges(email, env, empty_on_error=False): return parse_privs(rows[0][0]) def validate_privilege(priv): - if "\n" in priv or priv.strip() == "": + if "\n" in priv or not priv.strip(): return (f"That's not a valid privilege ({priv}).", 400) return None @@ -411,7 +411,7 @@ def add_mail_alias(address, forwards_to, permitted_senders, env, update_if_exist # validate address address = address.strip() - if address == "": + if not address: return ("No email address provided.", 400) if not validate_email(address, mode='alias'): return (f"Invalid email address ({address}).", 400) @@ -438,7 +438,7 @@ def add_mail_alias(address, forwards_to, permitted_senders, env, update_if_exist for line in forwards_to.split("\n"): for email in line.split(","): email = email.strip() - if email == "": continue + if not email: continue email = sanitize_idn_email_address(email) # Unicode => IDNA # Strip any +tag from email alias and check privileges privileged_email = re.sub(r"(?=\+)[^@]*(?=@)",'',email) @@ -461,7 +461,7 @@ def add_mail_alias(address, forwards_to, permitted_senders, env, update_if_exist for line in permitted_senders.split("\n"): for login in line.split(","): login = login.strip() - if login == "": continue + if not login: continue if login not in valid_logins: return (f"Invalid permitted sender: {login} is not a user on this system.", 400) validated_permitted_senders.append(login) @@ -598,11 +598,11 @@ def kick(env, mail_result=None): from web_update import do_web_update results.append( do_web_update(env) ) - return "".join(s for s in results if s != "") + return "".join(s for s in results if s) def validate_password(pw): # validate password - if pw.strip() == "": + if not pw.strip(): msg = "No password provided." raise ValueError(msg) if len(pw) < 8: diff --git a/management/mfa.py b/management/mfa.py index 6b56ad86..6deab5cf 100644 --- a/management/mfa.py +++ b/management/mfa.py @@ -68,7 +68,7 @@ def disable_mfa(email, mfa_id, env): return c.rowcount > 0 def validate_totp_secret(secret): - if not isinstance(secret, str) or secret.strip() == "": + if not isinstance(secret, str) or not secret.strip(): msg = "No secret provided." raise ValueError(msg) if len(secret) != 32: diff --git a/management/status_checks.py b/management/status_checks.py index bfc820df..d465a098 100755 --- a/management/status_checks.py +++ b/management/status_checks.py @@ -763,7 +763,7 @@ def check_mail_domain(domain, env, output): # Stop if the domain is listed in the Spamhaus Domain Block List. # The user might have chosen a domain that was previously in use by a spammer # and will not be able to reliably send mail. - + # See https://www.spamhaus.org/news/article/807/using-our-public-mirrors-check-your-return-codes-now. for # information on spamhaus return codes dbl = query_dns(domain+'.dbl.spamhaus.org', "A", nxdomain=None) @@ -918,7 +918,7 @@ def list_apt_updates(apt_update=True): simulated_install = shell("check_output", ["/usr/bin/apt-get", "-qq", "-s", "upgrade"]) pkgs = [] for line in simulated_install.split('\n'): - if line.strip() == "": + if not line.strip(): continue if re.match(r'^Conf .*', line): # remove these lines, not informative @@ -1082,7 +1082,7 @@ class FileOutput: print(file=self.buf) print(" ", end="", file=self.buf) linelen = 0 - if linelen == 0 and w.strip() == "": continue + if linelen == 0 and not w.strip(): continue print(w, end="", file=self.buf) linelen += len(w) print(file=self.buf) diff --git a/tools/readable_bash.py b/tools/readable_bash.py index a5e2b4ec..fe7a2c8a 100644 --- a/tools/readable_bash.py +++ b/tools/readable_bash.py @@ -171,7 +171,7 @@ def strip_indent(s): class Comment(Grammar): grammar = ONE_OR_MORE(ZERO_OR_MORE(SPACE), L('#'), REST_OF_LINE, EOL) def value(self): - if self.string.replace("#", "").strip() == "": + if not self.string.replace("#", "").strip(): return "\n" lines = [x[2].string for x in self[0]] content = "\n".join(lines) @@ -273,7 +273,7 @@ class RestartService(Grammar): class OtherLine(Grammar): grammar = (REST_OF_LINE, EOL) def value(self): - if self.string.strip() == "": return "" + if not self.string.strip(): return "" if "source setup/functions.sh" in self.string: return "" if "source /etc/mailinabox.conf" in self.string: return "" return "
" + recode_bash(self.string.strip()) + "
\n" @@ -417,7 +417,7 @@ class BashScript(Grammar): mode = 0 for item in result.value(): - if item.strip() == "": + if not item.strip(): pass elif item.startswith("