1
0
mirror of https://github.com/mail-in-a-box/mailinabox.git synced 2024-11-24 02:37:05 +00:00

Fixed EM101 (raw-string-in-exception): Exception must not use a string literal, assign to variable first

This commit is contained in:
Teal Dulcet 2023-12-22 07:10:48 -08:00 committed by Joshua Tauberer
parent 49124cc9ca
commit dd61844ced
7 changed files with 42 additions and 21 deletions

View File

@ -49,10 +49,12 @@ class AuthService:
username, password = parse_http_authorization_basic(request.headers.get('Authorization', '')) username, password = parse_http_authorization_basic(request.headers.get('Authorization', ''))
if username in {None, ""}: if username in {None, ""}:
raise ValueError("Authorization header invalid.") msg = "Authorization header invalid."
raise ValueError(msg)
if username.strip() == "" and password.strip() == "": if username.strip() == "" and password.strip() == "":
raise ValueError("No email address, password, session key, or API key provided.") msg = "No email address, password, session key, or API key provided."
raise ValueError(msg)
# If user passed the system API key, grant administrative privs. This key # If user passed the system API key, grant administrative privs. This key
# is not associated with a user. # is not associated with a user.
@ -72,7 +74,8 @@ class AuthService:
# If no password was given, but a username was given, we're missing some information. # If no password was given, but a username was given, we're missing some information.
elif password.strip() == "": elif password.strip() == "":
raise ValueError("Enter a password.") msg = "Enter a password."
raise ValueError(msg)
else: else:
# The user is trying to log in with a username and a password # The user is trying to log in with a username and a password
@ -114,7 +117,8 @@ class AuthService:
]) ])
except: except:
# Login failed. # Login failed.
raise ValueError("Incorrect email address or password.") msg = "Incorrect email address or password."
raise ValueError(msg)
# If MFA is enabled, check that MFA passes. # If MFA is enabled, check that MFA passes.
status, hints = validate_auth_mfa(email, request, env) status, hints = validate_auth_mfa(email, request, env)

View File

@ -507,7 +507,8 @@ def list_target_files(config):
path = '' path = ''
if bucket == "": if bucket == "":
raise ValueError("Enter an S3 bucket name.") msg = "Enter an S3 bucket name."
raise ValueError(msg)
# connect to the region & bucket # connect to the region & bucket
try: try:
@ -535,7 +536,8 @@ def list_target_files(config):
b2_api.authorize_account("production", b2_application_keyid, b2_application_key) b2_api.authorize_account("production", b2_application_keyid, b2_application_key)
bucket = b2_api.get_bucket_by_name(b2_bucket) bucket = b2_api.get_bucket_by_name(b2_bucket)
except NonExistentBucket as e: except NonExistentBucket as e:
raise ValueError("B2 Bucket does not exist. Please double check your information!") msg = "B2 Bucket does not exist. Please double check your information!"
raise ValueError(msg)
return [(key.file_name, key.size) for key, _ in bucket.ls()] return [(key.file_name, key.size) for key, _ in bucket.ls()]
else: else:

View File

@ -919,7 +919,8 @@ def set_custom_dns_record(qname, rtype, value, action, env):
rtype = rtype.upper() rtype = rtype.upper()
if value is not None and qname != "_secondary_nameserver": if value is not None and qname != "_secondary_nameserver":
if not re.search(DOMAIN_RE, qname): if not re.search(DOMAIN_RE, qname):
raise ValueError("Invalid name.") msg = "Invalid name."
raise ValueError(msg)
if rtype in {"A", "AAAA"}: if rtype in {"A", "AAAA"}:
if value != "local": # "local" is a special flag for us if value != "local": # "local" is a special flag for us
@ -928,14 +929,16 @@ def set_custom_dns_record(qname, rtype, value, action, env):
if rtype == "AAAA" and not isinstance(v, ipaddress.IPv6Address): raise ValueError("That's an IPv4 address.") if rtype == "AAAA" and not isinstance(v, ipaddress.IPv6Address): raise ValueError("That's an IPv4 address.")
elif rtype in {"CNAME", "NS"}: elif rtype in {"CNAME", "NS"}:
if rtype == "NS" and qname == zone: if rtype == "NS" and qname == zone:
raise ValueError("NS records can only be set for subdomains.") msg = "NS records can only be set for subdomains."
raise ValueError(msg)
# ensure value has a trailing dot # ensure value has a trailing dot
if not value.endswith("."): if not value.endswith("."):
value = value + "." value = value + "."
if not re.search(DOMAIN_RE, value): if not re.search(DOMAIN_RE, value):
raise ValueError("Invalid value.") msg = "Invalid value."
raise ValueError(msg)
elif rtype in {"CNAME", "TXT", "SRV", "MX", "SSHFP", "CAA"}: elif rtype in {"CNAME", "TXT", "SRV", "MX", "SSHFP", "CAA"}:
# anything goes # anything goes
pass pass

View File

@ -608,9 +608,11 @@ def kick(env, mail_result=None):
def validate_password(pw): def validate_password(pw):
# validate password # validate password
if pw.strip() == "": if pw.strip() == "":
raise ValueError("No password provided.") msg = "No password provided."
raise ValueError(msg)
if len(pw) < 8: if len(pw) < 8:
raise ValueError("Passwords must be at least eight characters.") msg = "Passwords must be at least eight characters."
raise ValueError(msg)
if __name__ == "__main__": if __name__ == "__main__":
import sys import sys

View File

@ -41,9 +41,11 @@ def enable_mfa(email, type, secret, token, label, env):
# Sanity check with the provide current token. # Sanity check with the provide current token.
totp = pyotp.TOTP(secret) totp = pyotp.TOTP(secret)
if not totp.verify(token, valid_window=1): if not totp.verify(token, valid_window=1):
raise ValueError("Invalid token.") msg = "Invalid token."
raise ValueError(msg)
else: else:
raise ValueError("Invalid MFA type.") msg = "Invalid MFA type."
raise ValueError(msg)
conn, c = open_database(env, with_connection=True) conn, c = open_database(env, with_connection=True)
c.execute('INSERT INTO mfa (user_id, type, secret, label) VALUES (?, ?, ?, ?)', (get_user_id(email, c), type, secret, label)) c.execute('INSERT INTO mfa (user_id, type, secret, label) VALUES (?, ?, ?, ?)', (get_user_id(email, c), type, secret, label))
@ -67,9 +69,11 @@ def disable_mfa(email, mfa_id, env):
def validate_totp_secret(secret): def validate_totp_secret(secret):
if type(secret) != str or secret.strip() == "": if type(secret) != str or secret.strip() == "":
raise ValueError("No secret provided.") msg = "No secret provided."
raise ValueError(msg)
if len(secret) != 32: if len(secret) != 32:
raise ValueError("Secret should be a 32 characters base32 string") msg = "Secret should be a 32 characters base32 string"
raise ValueError(msg)
def provision_totp(email, env): def provision_totp(email, env):
# Make a new secret. # Make a new secret.

View File

@ -624,7 +624,8 @@ def load_cert_chain(pemfile):
pem = f.read() + b"\n" # ensure trailing newline pem = f.read() + b"\n" # ensure trailing newline
pemblocks = re.findall(re_pem, pem) pemblocks = re.findall(re_pem, pem)
if len(pemblocks) == 0: if len(pemblocks) == 0:
raise ValueError("File does not contain valid PEM data.") msg = "File does not contain valid PEM data."
raise ValueError(msg)
return pemblocks return pemblocks
def load_pem(pem): def load_pem(pem):
@ -635,7 +636,8 @@ def load_pem(pem):
from cryptography.hazmat.backends import default_backend from cryptography.hazmat.backends import default_backend
pem_type = re.match(b"-+BEGIN (.*?)-+[\r\n]", pem) pem_type = re.match(b"-+BEGIN (.*?)-+[\r\n]", pem)
if pem_type is None: if pem_type is None:
raise ValueError("File is not a valid PEM-formatted file.") msg = "File is not a valid PEM-formatted file."
raise ValueError(msg)
pem_type = pem_type.group(1) pem_type = pem_type.group(1)
if pem_type in {b"RSA PRIVATE KEY", b"PRIVATE KEY"}: if pem_type in {b"RSA PRIVATE KEY", b"PRIVATE KEY"}:
return serialization.load_pem_private_key(pem, password=None, backend=default_backend()) return serialization.load_pem_private_key(pem, password=None, backend=default_backend())

View File

@ -39,7 +39,8 @@ def smtp_test():
try: try:
server.login("fakeuser", "fakepassword") server.login("fakeuser", "fakepassword")
raise Exception("authentication didn't fail") msg = "authentication didn't fail"
raise Exception(msg)
except smtplib.SMTPAuthenticationError: except smtplib.SMTPAuthenticationError:
# athentication should fail # athentication should fail
pass pass
@ -61,7 +62,8 @@ def imap_test():
try: try:
M.login("fakeuser", "fakepassword") M.login("fakeuser", "fakepassword")
raise Exception("authentication didn't fail") msg = "authentication didn't fail"
raise Exception(msg)
except imaplib.IMAP4.error: except imaplib.IMAP4.error:
# authentication should fail # authentication should fail
pass pass
@ -85,7 +87,8 @@ def pop_test():
M = None # don't .quit() M = None # don't .quit()
return return
M.list() M.list()
raise Exception("authentication didn't fail") msg = "authentication didn't fail"
raise Exception(msg)
finally: finally:
if M: if M:
M.quit() M.quit()
@ -103,7 +106,8 @@ def managesieve_test():
try: try:
M.login("fakeuser", "fakepassword") M.login("fakeuser", "fakepassword")
raise Exception("authentication didn't fail") msg = "authentication didn't fail"
raise Exception(msg)
except imaplib.IMAP4.error: except imaplib.IMAP4.error:
# authentication should fail # authentication should fail
pass pass