Skip to content

Commit

Permalink
Merge pull request #88 from heurtematte/master
Browse files Browse the repository at this point in the history
Add ssl_verify to manage selfsigned certificate
  • Loading branch information
JOJ0 committed Mar 20, 2023
2 parents bda3057 + d53ccca commit 9c3b718
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 17 deletions.
33 changes: 24 additions & 9 deletions synadm/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ class ApiRequest:
This is subclassed by SynapseAdmin and Matrix
"""
def __init__(self, log, user, token, base_url, path, timeout, debug):
def __init__(self, log, user, token, base_url, path, timeout, debug,
verify=None):
"""Initialize an APIRequest object
Args:
Expand All @@ -55,6 +56,8 @@ def __init__(self, log, user, token, base_url, path, timeout, debug):
base_url to form the basis for all API endpoint paths
timeout (int): requests module timeout used in query method
debug (bool): enable/disable debugging in requests module
verify(bool): SSL verification is turned on by default
and can be turned off using this argument.
"""
self.log = log
self.user = user
Expand All @@ -68,9 +71,10 @@ def __init__(self, log, user, token, base_url, path, timeout, debug):
self.timeout = timeout
if debug:
HTTPConnection.debuglevel = 1
self.verify = verify

def query(self, method, urlpart, params=None, data=None, token=None,
base_url_override=None, verify=True):
base_url_override=None, verify=None):
"""Generic wrapper around requests methods.
Handles requests methods, logging and exceptions.
Expand Down Expand Up @@ -108,10 +112,14 @@ def query(self, method, urlpart, params=None, data=None, token=None,
self.log.debug("Token override! Adjusting headers.")
self.headers["Authorization"] = "Bearer " + token

override_verify = self.verify
if verify is not None:
override_verify = verify

try:
resp = getattr(requests, method)(
url, headers=self.headers, timeout=self.timeout,
params=params, json=data, verify=verify
params=params, json=data, verify=override_verify
)
if not resp.ok:
self.log.warning(f"{host_descr} returned status code "
Expand Down Expand Up @@ -196,19 +204,21 @@ class MiscRequest(ApiRequest):
ApiRequest (object): parent class containing general properties and
methods for requesting REST API's
"""
def __init__(self, log, timeout, debug):
def __init__(self, log, timeout, debug, verify=None):
"""Initialize the MiscRequest object
Args:
log (logger object): an already initialized logger object
timeout (int): requests module timeout used in ApiRequest.query
method
debug (bool): enable/disable debugging in requests module
verify(bool): SSL verification is turned on by default
and can be turned off using this method.
"""
super().__init__(
log, "", "", # Set user and token to empty string
"", "", # Set base_url and path to empty string
timeout, debug
timeout, debug, verify
)

def federation_uri_well_known(self, base_url):
Expand Down Expand Up @@ -243,7 +253,7 @@ class Matrix(ApiRequest):
methods for requesting REST API's
"""
def __init__(self, log, user, token, base_url, matrix_path,
timeout, debug):
timeout, debug, verify):
"""Initialize the Matrix API object
Args:
Expand All @@ -258,11 +268,13 @@ def __init__(self, log, user, token, base_url, matrix_path,
timeout (int): requests module timeout used in ApiRequest.query
method
debug (bool): enable/disable debugging in requests module
verify(bool): SSL verification is turned on by default
and can be turned off using this method.
"""
super().__init__(
log, user, token,
base_url, matrix_path,
timeout, debug
timeout, debug, verify
)
self.user = user

Expand Down Expand Up @@ -360,7 +372,8 @@ class SynapseAdmin(ApiRequest):
ApiRequest (object): parent class containing general properties and
methods for requesting REST API's
"""
def __init__(self, log, user, token, base_url, admin_path, timeout, debug):
def __init__(self, log, user, token, base_url, admin_path, timeout, debug,
verify):
"""Initialize the SynapseAdmin object
Args:
Expand All @@ -375,11 +388,13 @@ def __init__(self, log, user, token, base_url, admin_path, timeout, debug):
timeout (int): Requests module timeout used in ApiRequest.query
method
debug (bool): enable/disable debugging in requests module
verify(bool): SSL verification is turned on by default
and can be turned off using this argument.
"""
super().__init__(
log, user, token,
base_url, admin_path,
timeout, debug
timeout, debug, verify
)
self.user = user

Expand Down
37 changes: 29 additions & 8 deletions synadm/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,8 @@ class APIHelper:
"matrix_path": "/_matrix",
"timeout": 30,
"server_discovery": "well-known",
"homeserver": "auto-retrieval"
"homeserver": "auto-retrieval",
"ssl_verify": True
}

def __init__(self, config_path, verbose, no_confirm, output_format_cli):
Expand Down Expand Up @@ -139,8 +140,13 @@ def load(self):
except Exception as error:
self.log.error("%s while reading configuration file", error)
for key, value in self.config.items():
if not value:
self.log.error("Config entry missing: %s", key)

if key == "ssl_verify" and type(value) != bool:
self.log.error("Config value error: %s, %s must be boolean",
key, value)

if not value and type(value) != bool:
self.log.error("Config entry missing: %s, %s", key, value)
return False
else:
if key == "token":
Expand All @@ -155,17 +161,20 @@ def load(self):
self.log,
self.config["user"], self.config["token"],
self.config["base_url"], self.config["admin_path"],
self.config["timeout"], self.requests_debug
self.config["timeout"], self.requests_debug,
self.config["ssl_verify"]
)
self.matrix_api = api.Matrix(
self.log,
self.config["user"], self.config["token"],
self.config["base_url"], self.config["matrix_path"],
self.config["timeout"], self.requests_debug
self.config["timeout"], self.requests_debug,
self.config["ssl_verify"]
)
self.misc_request = api.MiscRequest(
self.log,
self.config["timeout"], self.requests_debug,
self.config["ssl_verify"]
)
return True

Expand Down Expand Up @@ -383,9 +392,14 @@ def root(ctx, verbose, no_confirm, output, config_file):
default value 'auto-retrieval' will try to discover the name using the
method set by --server-discovery."""
)
@click.option(
"--ssl-verify", "-i", is_flag=True, show_default=True,
help="""Whether or not SSL certificates should be verified. Set to False
to allow self-signed certifcates."""
)
@click.pass_obj
def config_cmd(helper, user_, token, base_url, admin_path, matrix_path,
output, timeout, server_discovery, homeserver):
output, timeout, server_discovery, homeserver, ssl_verify):
""" Modify synadm's configuration.
Configuration details are generally always asked interactively. Command
Expand All @@ -403,7 +417,8 @@ def get_redacted_token_prompt(cli_token):

if helper.no_confirm:
if not all([user, token, base_url, admin_path, matrix_path,
output, timeout, server_discovery, homeserver]):
output, timeout, server_discovery, homeserver,
ssl_verify]):
click.echo(
"Missing config options for non-interactive configuration!"
)
Expand All @@ -419,7 +434,8 @@ def get_redacted_token_prompt(cli_token):
"format": output,
"timeout": timeout,
"server_discovery": server_discovery,
"homeserver": homeserver
"homeserver": homeserver,
"ssl_verify": ssl_verify
}):
raise SystemExit(0)
else:
Expand Down Expand Up @@ -459,6 +475,11 @@ def get_redacted_token_prompt(cli_token):
"Homeserver name (auto-retrieval or matrix.DOMAIN)",
default=homeserver if homeserver else helper.config.get(
"homeserver", homeserver)),
"ssl_verify": click.prompt(
"Verify certificate",
type=bool,
default=ssl_verify if ssl_verify else helper.config.get(
"ssl_verify", ssl_verify)),
"server_discovery": click.prompt(
"Server discovery mode (used with homeserver name auto-retrieval)",
default=server_discovery if server_discovery else helper.config.get( # noqa: E501
Expand Down

0 comments on commit 9c3b718

Please sign in to comment.