check command

This commit is contained in:
Éloi Rivard 2021-10-13 10:12:44 +02:00
parent 68c091da62
commit d95bde7b22
5 changed files with 126 additions and 27 deletions

View file

@ -1,4 +1,5 @@
import click
import sys
from canaille import create_app
from canaille.models import AuthorizationCode, Token
@ -30,3 +31,17 @@ def clean():
a.delete()
teardown_ldap_connection(current_app)
@cli.command()
@with_appcontext
def check():
"""
Check the configuration file.
"""
from canaille.configuration import validate, ConfigurationException
try:
validate(current_app.config, validate_remote=True)
except ConfigurationException as exc:
print(exc)
sys.exit(1)

View file

@ -1,40 +1,77 @@
import ldap
import smtplib
import os
import smtplib
import socket
from cryptography.hazmat.primitives import serialization as crypto_serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend as crypto_default_backend
class ConfigurationException(Exception):
pass
def validate(config, validate_remote=False):
if not os.path.exists(config["JWT"]["PUBLIC_KEY"]):
raise Exception(f'Public key does not exist {config["JWT"]["PUBLIC_KEY"]}')
raise ConfigurationException(
f'Public key does not exist {config["JWT"]["PUBLIC_KEY"]}'
)
if not os.path.exists(config["JWT"]["PRIVATE_KEY"]):
raise Exception(f'Private key does not exist {config["JWT"]["PRIVATE_KEY"]}')
raise ConfigurationException(
f'Private key does not exist {config["JWT"]["PRIVATE_KEY"]}'
)
if not validate_remote:
return
conn = ldap.initialize(config["LDAP"]["URI"])
if config["LDAP"].get("TIMEOUT"):
conn.set_option(ldap.OPT_NETWORK_TIMEOUT, config["LDAP"]["TIMEOUT"])
conn.simple_bind_s(config["LDAP"]["BIND_DN"], config["LDAP"]["BIND_PW"])
conn.unbind_s()
validate_ldap_configuration(config)
validate_smtp_configuration(config)
with smtplib.SMTP(
host=config["SMTP"]["HOST"],
port=config["SMTP"]["PORT"],
) as smtp:
if config["SMTP"].get("TLS"):
smtp.starttls()
if config["SMTP"].get("LOGIN"):
smtp.login(
user=config["SMTP"]["LOGIN"],
password=config["SMTP"].get("PASSWORD"),
)
def validate_ldap_configuration(config):
try:
conn = ldap.initialize(config["LDAP"]["URI"])
if config["LDAP"].get("TIMEOUT"):
conn.set_option(ldap.OPT_NETWORK_TIMEOUT, config["LDAP"]["TIMEOUT"])
conn.simple_bind_s(config["LDAP"]["BIND_DN"], config["LDAP"]["BIND_PW"])
conn.unbind_s()
except ldap.SERVER_DOWN as exc:
raise ConfigurationException(
f'Could not connect to the LDAP server \'{config["LDAP"]["URI"]}\''
) from exc
except ldap.INVALID_CREDENTIALS as exc:
raise ConfigurationException(
f'LDAP authentication failed with user \'{config["LDAP"]["BIND_DN"]}\''
) from exc
def validate_smtp_configuration(config):
try:
with smtplib.SMTP(
host=config["SMTP"]["HOST"],
port=config["SMTP"]["PORT"],
) as smtp:
if config["SMTP"].get("TLS"):
smtp.starttls()
if config["SMTP"].get("LOGIN"):
smtp.login(
user=config["SMTP"]["LOGIN"],
password=config["SMTP"].get("PASSWORD"),
)
except (socket.gaierror, ConnectionRefusedError) as exc:
raise ConfigurationException(
f'Could not connect to the SMTP server \'{config["SMTP"]["HOST"]}\''
) from exc
except smtplib.SMTPAuthenticationError as exc:
raise ConfigurationException(
f'SMTP authentication failed with user \'{config["SMTP"]["LOGIN"]}\''
) from exc
def setup_dev_keypair(config):

View file

@ -59,6 +59,13 @@ Choose a path to store your configuration, for instance `/etc/canaille` and then
sudo cp canaille/conf/config.sample.toml /etc/canaille/config.toml
sudo cp canaille/conf/openid-configuration.sample.json /etc/canaille/openid-configuration.json
Then check your configuration file with the following command:
.. code-block:: console
env CONFIG=/etc/canaille/config.toml FASK_APP=canaille /opt/canaille/bin/canaille check
Web interface
=============

View file

@ -152,6 +152,7 @@ def configuration(slapd_server, smtpd, keypair_path):
"GROUP_CLASS": "groupOfNames",
"GROUP_NAME_ATTRIBUTE": "cn",
"GROUP_USER_FILTER": "(member={user.dn})",
"TIMEOUT": 0.1,
},
"JWT": {
"PUBLIC_KEY": public_key_path,

View file

@ -1,37 +1,76 @@
import ldap
import pytest
import smtplib
import socket
from canaille.configuration import validate
from canaille.commands import cli
from canaille.configuration import validate, ConfigurationException
def test_ldap_connection_no_remote(configuration):
validate(configuration)
def test_no_private_key(configuration):
configuration["JWT"]["PRIVATE_KEY"] = "invalid-path"
with pytest.raises(
ConfigurationException,
match=r"Private key does not exist",
):
validate(configuration)
def test_no_public_key(configuration):
configuration["JWT"]["PUBLIC_KEY"] = "invalid-path"
with pytest.raises(
ConfigurationException,
match=r"Public key does not exist",
):
validate(configuration)
def test_ldap_connection_remote(configuration):
validate(configuration, validate_remote=True)
def test_ldap_connection_remote_ldap_unreachable(configuration):
configuration["LDAP"]["URI"] = "ldap://invalid-ldap.com"
with pytest.raises(ldap.SERVER_DOWN):
with pytest.raises(
ConfigurationException,
match=r"Could not connect to the LDAP server",
):
validate(configuration, validate_remote=True)
def test_ldap_connection_remote_ldap_wrong_credentials(configuration):
configuration["LDAP"]["BIND_PW"] = "invalid-password"
with pytest.raises(ldap.INVALID_CREDENTIALS):
with pytest.raises(
ConfigurationException,
match=r"LDAP authentication failed with user",
):
validate(configuration, validate_remote=True)
def test_smtp_connection_remote_smtp_unreachable(configuration):
configuration["SMTP"]["HOST"] = "smtp://invalid-smtp.com"
with pytest.raises(socket.gaierror):
with pytest.raises(
ConfigurationException,
match=r"Could not connect to the SMTP server",
):
validate(configuration, validate_remote=True)
def test_smtp_connection_remote_smtp_wrong_credentials(configuration):
configuration["SMTP"]["PASSWORD"] = "invalid-password"
with pytest.raises(smtplib.SMTPAuthenticationError):
with pytest.raises(
ConfigurationException,
match=r"SMTP authentication failed with user",
):
validate(configuration, validate_remote=True)
def test_check_command(testclient):
runner = testclient.app.test_cli_runner()
runner.invoke(cli, ["check"])
def test_check_command_fail(testclient):
testclient.app.config["LDAP"]["URI"] = "ldap://invalid-ldap.com"
runner = testclient.app.test_cli_runner()
runner.invoke(cli, ["check"])