Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for authenticated HANA #537

Draft
wants to merge 5 commits into
base: dev
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions neon_utils/hana_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from _socket import gethostname
from datetime import datetime

import requests
import json
Expand All @@ -33,6 +35,7 @@
from os import makedirs
from os.path import join, isfile, isdir, dirname
from time import time

from ovos_utils.log import LOG
from ovos_utils.xdg_utils import xdg_cache_home

Expand Down Expand Up @@ -91,20 +94,22 @@ def _init_client(backend_address: str):
_headers = {"Authorization": f"Bearer {_client_config['access_token']}"}


def _get_token(backend_address: str, username: str = "guest",
password: str = "password"):
def _get_token(backend_address: str):
"""
Get new auth tokens from the specified server. This will cache the returned
token, overwriting any previous data at the cache path.
@param backend_address: Hana server URL to connect to
@param username: Username to authorize
@param password: Password for specified username
"""
from ovos_config.config import Configuration
global _client_config
# TODO: username/password from configuration
hana_config = Configuration().get('hana', {})
username = hana_config.get("username") or "guest"
password = hana_config.get("password") or "password"
token_name = f"{gethostname()}_{datetime.utcnow().isoformat()}"
resp = requests.post(f"{backend_address}/auth/login",
json={"username": username,
"password": password})
"password": password,
"token_name": token_name})
if not resp.ok:
raise ServerException(f"Error logging into {backend_address}. "
f"{resp.status_code}: {resp.text}")
Expand Down
11 changes: 7 additions & 4 deletions neon_utils/log_aggregators/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,13 @@ def init_log_aggregators(config: dict = None):
from ovos_config.config import Configuration
config = config or Configuration()
for service_name, handler in _service_name_to_handler.items():
service_config = _get_log_aggregator_config(config=config, name=service_name)
if bool(service_config.pop('enabled', False)):
service_module = importlib.import_module(f'.{service_name}', __name__)
getattr(service_module, handler)(config=service_config)
try:
service_config = _get_log_aggregator_config(config=config, name=service_name)
if bool(service_config.pop('enabled', False)):
service_module = importlib.import_module(f'.{service_name}', __name__)
getattr(service_module, handler)(config=service_config)
except Exception as e:
pass


def _get_log_aggregator_config(config: dict, name: str):
Expand Down
3 changes: 2 additions & 1 deletion neon_utils/log_aggregators/sentry.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,13 @@
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import sentry_sdk

SENTRY_SDK_REQUIRED_KEYS = {'dsn'}


def init_sentry(config: dict):
import sentry_sdk

missing_required_keys = SENTRY_SDK_REQUIRED_KEYS.difference(config.keys())
if missing_required_keys:
raise KeyError(f'Sentry SDK configuration missing required keys: {missing_required_keys}')
Expand Down
18 changes: 13 additions & 5 deletions tests/hana_util_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,18 +96,26 @@ def test_request_backend_refresh_token(self, refresh_token, config_path):
neon_utils.hana_utils._client_config = real_client_config

@patch("neon_utils.hana_utils._get_client_config_path")
def test_00_get_token(self, config_path):
@patch("ovos_config.config.Configuration")
def test_00_get_token(self, config, config_path):
config.return_value = {}
config_path.return_value = self.test_path
from neon_utils.hana_utils import _get_token

# Test valid request
# Test valid default request
_get_token(self.test_server)
from neon_utils.hana_utils import _client_config
self.assertTrue(isfile(self.test_path))
with open(self.test_path) as f:
credentials_on_disk = json.load(f)
self.assertEqual(credentials_on_disk, _client_config)
# TODO: Test invalid request, rate-limited request

# Test with configured invalid login
config.return_value = {"hana": {"username": "guest",
"password": "fake_password"}}
from neon_utils.hana_utils import ServerException
with self.assertRaises(ServerException):
_get_token(self.test_server)

@patch("neon_utils.hana_utils._get_client_config_path")
@patch("neon_utils.hana_utils._get_token")
Expand Down Expand Up @@ -144,8 +152,8 @@ def _write_token(*_, **__):
new_credentials['client_id'])
self.assertEqual(credentials_on_disk['username'],
new_credentials['username'])
self.assertGreater(new_credentials['expiration'],
credentials_on_disk['expiration'])
self.assertGreaterEqual(new_credentials['expiration'],
credentials_on_disk['expiration'])
self.assertNotEqual(credentials_on_disk['access_token'],
new_credentials['access_token'])
self.assertNotEqual(credentials_on_disk['refresh_token'],
Expand Down
Loading