Merge pull request 'Corect code style for main Python module.' (#2) from bignose/ejabberd-auth-mastodon:wip/maintenance/code-style into master

Reviewed-on: #2
This commit is contained in:
Mike Barnes 2023-01-01 10:50:40 +00:00
commit c44e457fd0
3 changed files with 177 additions and 106 deletions

34
.editorconfig Normal file
View file

@ -0,0 +1,34 @@
# .editorconfig
# EditorConfig settings for this code base.
# See documentation at <URL:http://editorconfig.org/>.
# Is this the top-most EditorConfig config file in the code base?
root = true
# Match all file names, unless more specific match later.
[*]
# Text encoding name.
charset = utf-8
# Remove trailing whitespace on lines?
trim_trailing_whitespace = true
# End-of-line style (“lf”, “cr”, “crlf”).
end_of_line = lf
# Ensure file ends with a line break?
insert_final_newline = true
# Character to use for indentation (“tab“ for U+0009, “space“ for U+0020).
indent_style = space
# Number of columns for each indentation level.
indent_size = 4
# Local variables:
# coding: utf-8
# mode: conf
# End:
# vim: fileencoding=utf-8 filetype=dosini :

View file

@ -3,7 +3,7 @@ This is a Python script designed to run as an [ejabberd external auth](https://d
The code is derived from [ejabberd-auth-mysql](https://github.com/rankenstein/ejabberd-auth-mysql) and is licensed under the GNU GPLv3. The code is derived from [ejabberd-auth-mysql](https://github.com/rankenstein/ejabberd-auth-mysql) and is licensed under the GNU GPLv3.
It is used on [Chinwag Social](https://social.chinwag.org) to provide XMPP messaging functionality to every account. It is used on [Chinwag Social](https://social.chinwag.org) to provide XMPP messaging functionality to every account.
Discussion, questions and/or just saying hi in the [Chinwag Social Beergarden](xmpp:beergarden@rooms.chinwag.org?join) MUC (beergarden@rooms.chinwag.org) is welcomed! Discussion, questions and/or just saying hi in the [Chinwag Social Beergarden](xmpp:beergarden@rooms.chinwag.org?join) MUC (beergarden@rooms.chinwag.org) is welcomed!

View file

@ -1,165 +1,202 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import os, sys, logging, struct, psycopg2, bcrypt, random, atexit, time
# Database connection details. The credentials here need access to the Mastodon database, which "ejabberd" is unlikely import atexit
# to have on your system by default. You shoud grant SELECT privileges to ejabberd on the "accounts" and "users" tables, import logging
# to play it safe, or include the Mastodon DB user credentials here (don't). import struct
db_host="localhost" import sys
db_port=5432 import time
db_user="ejabberd"
db_pass=""
db_name="mastodon"
# This is the query that pulls the password hash for the given user. Mastodon doesn't store the domain for local accounts in import bcrypt
# the database, so we ignore the host component and try to match username where the domain is NULL. import psycopg2
db_query_getpass="select users.encrypted_password as password from accounts inner join users on accounts.id=users.account_id where lower(accounts.username) = %(user)s and accounts.domain is null"
# Database connection details. The credentials here need access to the
# Mastodon database, which "ejabberd" is unlikely to have on your system
# by default. You shoud grant SELECT privileges to ejabberd on the
# "accounts" and "users" tables, to play it safe, or include the
# Mastodon DB user credentials here (don't).
db_host = "localhost"
db_port = 5432
db_user = "ejabberd"
db_pass = ""
db_name = "mastodon"
# This is the query that pulls the password hash for the given user.
# Mastodon doesn't store the domain for local accounts in the database,
# so we ignore the host component and try to match username where the
# domain is NULL.
db_query_getpass = """
SELECT users.encrypted_password AS password
FROM accounts
INNER JOIN users
ON accounts.id = users.account_id
WHERE
lower(accounts.username) = %(user)s
AND accounts.domain IS NULL
"""
######################################################################## ########################################################################
#Setup # Setup
######################################################################## ########################################################################
sys.stderr = open('/var/log/ejabberd/extauth_err.log', 'a') sys.stderr = open('/var/log/ejabberd/extauth_err.log', 'a')
logging.basicConfig(level=logging.INFO, logging.basicConfig(
format='%(asctime)s %(levelname)s %(message)s', level=logging.INFO,
filename='/var/log/ejabberd/extauth.log', format='%(asctime)s %(levelname)s %(message)s',
filemode='a') filename='/var/log/ejabberd/extauth.log',
filemode='a',
)
try: try:
# Connect to the DB, set autocommit and readonly otherwise postgresql seems to have a # Connect to the DB, set autocommit and readonly otherwise
# tendency to keep things "idle in transaction" and table locks eventually grind # postgresql seems to have a tendency to keep things "idle in
# Mastodon to a halt. We don't make any changes anyway. # transaction" and table locks eventually grind Mastodon to a halt.
database=psycopg2.connect(host = db_host, user = db_user, password = db_pass, database = db_name, port = db_port) # We don't make any changes anyway.
database.set_session(readonly=True, autocommit=True) database = psycopg2.connect(
logging.debug(database.get_dsn_parameters()) host=db_host,
except: user=db_user,
logging.error("Unable to initialize database, check settings!") password=db_pass,
time.sleep(10) database=db_name,
sys.exit(1) port=db_port,
)
database.set_session(readonly=True, autocommit=True)
logging.debug(database.get_dsn_parameters())
except Exception:
logging.error("Unable to initialize database, check settings!")
time.sleep(10)
sys.exit(1)
@atexit.register @atexit.register
def close_db(): def close_db():
cursor.close() database.close()
database.close()
logging.info('auth-mastodon script started, waiting for ejabberd requests') logging.info('auth-mastodon script started, waiting for ejabberd requests')
class EjabberdInputError(Exception): class EjabberdInputError(Exception):
def __init__(self, value):
self.value = value def __init__(self, value):
def __str__(self): self.value = value
return repr(self.value)
def __str__(self):
return repr(self.value)
######################################################################## ########################################################################
#Declarations # Declarations
######################################################################## ########################################################################
def ejabberd_in(): def ejabberd_in():
logging.debug("trying to read 2 bytes from ejabberd:") logging.debug("trying to read 2 bytes from ejabberd:")
input_length = sys.stdin.buffer.read(2) input_length = sys.stdin.buffer.read(2)
if len(input_length) is not 2: if len(input_length) != 2:
logging.debug("ejabberd sent us wrong things!") logging.debug("ejabberd sent us wrong things!")
raise EjabberdInputError('Wrong input from ejabberd!') raise EjabberdInputError('Wrong input from ejabberd!')
logging.debug('got 2 bytes via stdin: %s'%input_length) logging.debug('got 2 bytes via stdin: %s' % input_length)
(size,) = struct.unpack('>h', input_length) (size,) = struct.unpack('>h', input_length)
logging.debug('size of data: %i'%size) logging.debug('size of data: %i' % size)
income=sys.stdin.read(size) income = sys.stdin.read(size)
logging.debug("incoming data: %s"%income) logging.debug("incoming data: %s" % income)
return income return income
def ejabberd_out(bool): def ejabberd_out(bool):
logging.debug("Ejabberd gets: %s" % bool) logging.debug("Ejabberd gets: %s" % bool)
token = genanswer(bool) token = genanswer(bool)
logging.debug("sent bytes: %#x %#x %#x %#x" % (token[0], token[1], token[2], token[3])) logging.debug(
"sent bytes: %#x %#x %#x %#x"
% (token[0], token[1], token[2], token[3]))
sys.stdout.buffer.write(token) sys.stdout.buffer.write(token)
sys.stdout.buffer.flush() sys.stdout.buffer.flush()
def genanswer(bool): def genanswer(bool):
answer = 0 answer = 0
if bool: if bool:
answer = 1 answer = 1
token = struct.pack('>hh', 2, answer) token = struct.pack('>hh', 2, answer)
return token return token
def get_password(user, host): def get_password(user, host):
# Right now we ignore the host component, as Mastodon doesn't store it for local accounts. # Right now we ignore the host component, as Mastodon doesn't store
# It may be required one day, so the code to handle passing it to the query is left in for now. # it for local accounts. It may be required one day, so the code to
cursor = database.cursor() # handle passing it to the query is left in for now.
cursor.execute(db_query_getpass, {"user": user.lower(), "host": host}) cursor = database.cursor()
data = cursor.fetchone() cursor.execute(db_query_getpass, {"user": user.lower(), "host": host})
cursor.close() data = cursor.fetchone()
return data[0] if data != None else None cursor.close()
return data[0] if data is not None else None
def isuser(user, host): def isuser(user, host):
return get_password(user, host) != None return get_password(user, host) is not None
def auth(user, host, password): def auth(user, host, password):
db_password = get_password(user, host) db_password = get_password(user, host)
if db_password == None: if db_password is None:
logging.debug("Wrong username: %s@%s" % (user, host)) logging.debug("Wrong username: %s@%s" % (user, host))
return False return False
else: else:
if bcrypt.checkpw(password.encode('utf8'), db_password.encode('utf8')): if bcrypt.checkpw(password.encode('utf8'), db_password.encode('utf8')):
logging.debug("Validated %s against hash %s" % (user, db_password)) logging.debug("Validated %s against hash %s" % (user, db_password))
return True return True
else: else:
logging.debug("Wrong password for user: %s@%s" % (user, host)) logging.debug("Wrong password for user: %s@%s" % (user, host))
return False return False
######################################################################## ########################################################################
#Main Loop # Main Loop
######################################################################## ########################################################################
exitcode=0 exitcode = 0
while True: while True:
logging.debug("start of infinite loop") logging.debug("start of infinite loop")
try: try:
ejab_request = ejabberd_in().split(':', 3) ejab_request = ejabberd_in().split(':', 3)
except EOFError: except EOFError:
break break
except Exception as e: except Exception:
logging.exception("Exception occured while reading stdin") logging.exception("Exception occured while reading stdin")
raise raise
op_result = False op_result = False
try: try:
# Only 'auth' and 'isuser' implemented, placeholders left to maybe # Only 'auth' and 'isuser' implemented, placeholders left to
# expose other functions later but for now let's not even think about # maybe expose other functions later but for now let's not even
# modifying the Mastodon DB # think about modifying the Mastodon DB
if ejab_request[0] == "auth": if ejab_request[0] == "auth":
op_result = auth(ejab_request[1], ejab_request[2], ejab_request[3]) op_result = auth(ejab_request[1], ejab_request[2], ejab_request[3])
elif ejab_request[0] == "isuser": elif ejab_request[0] == "isuser":
op_result = isuser(ejab_request[1], ejab_request[2]) op_result = isuser(ejab_request[1], ejab_request[2])
elif ejab_request[0] == "setpass": elif ejab_request[0] == "setpass":
op_result = False op_result = False
elif ejab_request[0] == "tryregister": elif ejab_request[0] == "tryregister":
op_result = False op_result = False
elif ejab_request[0] == "removeuser": elif ejab_request[0] == "removeuser":
op_result = False op_result = False
elif ejab_request[0] == "removeuser3": elif ejab_request[0] == "removeuser3":
op_result = False op_result = False
except Exception: except Exception:
logging.exception("Exception occured") logging.exception("Exception occured")
ejabberd_out(op_result) ejabberd_out(op_result)
logging.info("successful" if op_result else "unsuccessful") logging.info("successful" if op_result else "unsuccessful")
logging.debug("end of infinite loop") logging.debug("end of infinite loop")
logging.info('extauth script terminating') logging.info('extauth script terminating')