Skip to content

Commit

Permalink
Merge pull request #12 from brighthive/secure-endpoints
Browse files Browse the repository at this point in the history
Secure endpoints
  • Loading branch information
reginafcompton committed Feb 27, 2020
2 parents 96f1106 + 107d5eb commit 8b822e9
Show file tree
Hide file tree
Showing 12 changed files with 171 additions and 37 deletions.
2 changes: 1 addition & 1 deletion .coveragec
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
[run]
omit = */.local/*, migrations/*, */tests/*, */__init__.py, */responses.py
omit = */.local/*, migrations/*, */tests/*, */__init__.py, */responses.py, */.virtualenvs/*
1 change: 1 addition & 0 deletions Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ sqlalchemy = "*"
psycopg2-binary = "*"
requests = "*"
gevent = "*"
brighthive-authlib = "*"

[requires]
python_version = "3.8"
105 changes: 89 additions & 16 deletions Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions data_trust_logger/api/health.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"""
import json

from brighthive_authlib import token_required
from flask import Blueprint, request
from flask_restful import Api, Resource
from sqlalchemy import create_engine
Expand All @@ -22,6 +23,7 @@ class HealthAuditResource(Resource):
def __init__(self):
self.response = resp.ResponseBody()

@token_required(config.oauth2_provider)
def get(self):
metrics_data = {}

Expand All @@ -31,6 +33,7 @@ def get(self):
return self.response.get_one_response(metrics_data)



health_bp = Blueprint('health_ep', __name__)
health_api = Api(health_bp)
health_api.add_resource(HealthAuditResource, '/health')
10 changes: 8 additions & 2 deletions data_trust_logger/api/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,18 @@
"""

import logging
import json
import logging
import sys

from brighthive_authlib import token_required
from flask import Blueprint, request
from flask_restful import Resource, Api
from flask_restful import Api, Resource

import data_trust_logger.utilities.responses as resp
from data_trust_logger.config import ConfigurationFactory

config = ConfigurationFactory.from_env()


class LogResource(Resource):
Expand All @@ -28,6 +33,7 @@ def __init__(self):

self.log.addHandler(log_handler)

@token_required(config.oauth2_provider)
def post(self):
try:
data = request.get_json(force=True)
Expand Down
19 changes: 18 additions & 1 deletion data_trust_logger/app/app.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,25 @@
"""Data Trust Logger Application."""
from flask import Flask
import brighthive_authlib
from brighthive_authlib import OAuth2ProviderError
from flask import Flask, jsonify
from flask_cors import CORS
from flask_restful import Api

from flask import Blueprint

from data_trust_logger.api import health_bp, log_bp


def handle_errors(e):
if isinstance(e, OAuth2ProviderError):
response = jsonify({'message': 'Access Denied'})
response.status_code = 401
return response
else:
response = jsonify({'error': 'An unknown error occurred'})
response.status_code = 400
return response

def create_app(environment: str = None):
"""Create the Flask application.
Expand All @@ -19,4 +34,6 @@ def create_app(environment: str = None):
app.register_blueprint(health_bp)
app.register_blueprint(log_bp)

app.register_error_handler(Exception, handle_errors)

return app
10 changes: 5 additions & 5 deletions data_trust_logger/config/config.example.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@
"ethnicity_race": "ethnicity"
}
},
"auth_access": {
"client_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"client_secret": "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"audience": "http://localhost:8000",
"oauth2_url": "https://<url_to_authserver>/oauth/token"
"oauth2": {
"client_id": "xxxxxxxxxx",
"client_secret": "xxxxxxxxxx",
"oauth2_url": "",
"oauth2_provider": ""
}
},
"development_testing": { },
Expand Down
38 changes: 31 additions & 7 deletions data_trust_logger/config/config.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import os
import json
import os

from brighthive_authlib import AuthLibConfiguration, OAuth2ProviderFactory


class ConfigurationError(Exception):
pass
Expand Down Expand Up @@ -77,11 +80,15 @@ def from_json(self, environment='local'):
self.mci_psql_database = fields['master_client_index']['mci_psql_database']
self.mci_mappings = fields['master_client_index']['table_to_ep_mappings']

self.client_id = fields['auth_access']['client_id']
self.client_secret = fields['auth_access']['client_secret']
self.audience = fields['auth_access']['audience']
self.oauth2_url = fields['auth_access']['oauth2_url']

self.client_id = fields['oauth2']['client_id']
self.client_secret = fields['oauth2']['client_secret']

self.oauth2_url_base = fields['oauth2']['oauth2_url']
self.oauth2_url = f"{self.oauth2_url_base}/oauth/token"
self.oauth2_audience = fields["oauth2"]["oauth2_audience"]
self.brighthive_auth_url = fields['brighthive_auth']['brighthive_auth_url']
self.brighthive_auth_provider = fields["brighthive_auth"]["brighthive_auth_provider"]

self.environment = environment
self.debug = True
self.testing = True
Expand All @@ -105,9 +112,26 @@ def from_json(self, environment='local'):
self.mci_psql_database
)

self.oauth2_provider = self.get_oauth2_provider()

else:
raise ConfigurationError(
'Cannot find environment \'{}\' in JSON configuration.')

def get_oauth2_provider(self):
"""Retrieve the OAuth 2.0 Provider.
Return:
object: The OAuth 2.0 Provider.
"""
auth_config = AuthLibConfiguration(
provider=self.brighthive_auth_provider,
base_url=self.brighthive_auth_url)

oauth2_provider = OAuth2ProviderFactory.get_provider(
self.brighthive_auth_provider, auth_config)

return oauth2_provider


class LocalConfiguration(Configuration):
"""Configuration class for local development."""
Expand Down Expand Up @@ -152,4 +176,4 @@ def from_env():
"""
environment = os.getenv('APP_ENV', 'LOCAL')

return ConfigurationFactory.get_config(environment)
return ConfigurationFactory.get_config(environment)
2 changes: 1 addition & 1 deletion data_trust_logger/utilities/secure_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def get_access_token():
data = {
'client_id': config.client_id,
'client_secret': config.client_secret,
'audience': config.audience,
'audience': config.oauth2_audience,
'grant_type': 'client_credentials'
}

Expand Down
4 changes: 2 additions & 2 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
version: '3'
services:
data-trust-logger:
image: brighthive/data-trust-logger:1.0.1-beta
image: brighthive/data-trust-logger:local
environment:
- APP_ENV=LOCAL
ports:
- 8002:8000
- 8002:8002
1 change: 1 addition & 0 deletions tests/test_health_resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@


def _healthcheck_response(client, metrics_blob, mocker):
mocker.patch('brighthive_authlib.providers.BrightHiveProvider.validate_token', return_value=True)
mocker.patch("json.load", return_value=metrics_blob)

response = client.get('/health')
Expand Down
Loading

0 comments on commit 8b822e9

Please sign in to comment.