-
Notifications
You must be signed in to change notification settings - Fork 0
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
Logs middleware #116
Open
felipao-mx
wants to merge
13
commits into
main
Choose a base branch
from
logs
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+368
−10
Open
Logs middleware #116
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
2f8cabc
logs
felipao-mx 34afc5e
lint
felipao-mx e3044b6
concurrency
felipao-mx 0ccefc0
remove unused code
felipao-mx d30ef91
dev.a
felipao-mx 16e0494
0.7.0.dev0-a
felipao-mx b9d6327
version
felipao-mx a5ff6c0
fix import
felipao-mx 3fda520
version
felipao-mx 53dd2d6
fix url
felipao-mx 83027a6
remove binary data
felipao-mx 2768186
remove unnecesary await
felipao-mx 20e025f
Update version.py
pachCode File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,27 +1,42 @@ | ||
import datetime as dt | ||
from typing import Dict | ||
from fastapi import Request | ||
|
||
from fastapi.responses import JSONResponse as Response | ||
from fast_agave.filters import generic_query | ||
|
||
from ..models import Card as CardModel | ||
from ..validators import CardQuery | ||
from ..validators import CardQuery, CardUpdateRequest | ||
from .base import app | ||
|
||
|
||
@app.resource('/cards') | ||
class Card: | ||
model = CardModel | ||
query_validator = CardQuery | ||
update_validator = CardUpdateRequest | ||
get_query_filter = generic_query | ||
|
||
@staticmethod | ||
async def retrieve(card: CardModel) -> Response: | ||
data = card.to_dict() | ||
data['number'] = '*' * 16 | ||
data['last_four_digits'] = card.number[-4:] | ||
return Response(content=data) | ||
|
||
@staticmethod | ||
async def query(response: Dict): | ||
for item in response['items']: | ||
item['number'] = '*' * 16 | ||
item['last_four_digits'] = item['number'][-4:] | ||
return response | ||
|
||
@staticmethod | ||
async def update(card: CardModel, request: CardUpdateRequest) -> Response: | ||
card.status = request.status | ||
await card.async_save() | ||
return Response(content=card.to_dict(), status_code=200) | ||
|
||
@staticmethod | ||
async def delete(card: CardModel, _: Request) -> Response: | ||
card.deactivated_at = dt.datetime.utcnow() | ||
await card.async_save() | ||
return Response(content=card.to_dict(), status_code=200) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,4 @@ | ||
from .error_handlers import FastAgaveErrorHandler | ||
from .loggers import OpenSearchLog | ||
|
||
__all__ = ['FastAgaveErrorHandler'] | ||
__all__ = ['FastAgaveErrorHandler', 'OpenSearchLog'] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,167 @@ | ||
import asyncio | ||
import base64 | ||
import binascii | ||
import json | ||
import os | ||
import re | ||
from dataclasses import asdict | ||
from typing import Any, Optional | ||
|
||
from aiohttp import ClientSession | ||
from cuenca_validations.errors import CuencaError | ||
from cuenca_validations.typing import DictStrAny | ||
from fastapi import Request, Response | ||
from starlette.datastructures import Headers | ||
from starlette.middleware.base import ( | ||
BaseHTTPMiddleware, | ||
RequestResponseEndpoint, | ||
) | ||
|
||
from fast_agave.exc import FastAgaveError | ||
|
||
AUTHED_REQUIRED_HEADERS = { | ||
'x-cuenca-token', | ||
'x-cuenca-logintoken', | ||
'x-cuenca-loginid', | ||
'x-cuenca-sessionid', | ||
} | ||
|
||
SENSITIVE_DATA_FIELDS = { | ||
'number', | ||
'cvv2', | ||
'cvv', | ||
'icvv', | ||
'exp_month', | ||
'exp_year', | ||
'pin', | ||
'pin_block', | ||
'pin_block_switch', | ||
} | ||
|
||
NON_VALID_SCOPE_VALUES = [ | ||
'headers', | ||
'app', | ||
'extensions', | ||
'fastapi_astack', | ||
'app', | ||
'route_handler', | ||
'router', | ||
'endpoint', | ||
'raw_path', | ||
] | ||
|
||
|
||
def basic_auth_decode(basic: str) -> str: | ||
basic = re.sub(r'^Basic ', '', basic, flags=re.IGNORECASE) | ||
try: | ||
decoded = base64.b64decode(basic).decode('ascii') | ||
ak, _ = decoded.split(':') | ||
except (binascii.Error, UnicodeDecodeError, ValueError): | ||
# If `basic` value is not valid then it is not a sensitive data | ||
return basic | ||
return ak | ||
|
||
|
||
def mask_sensitive_headers(headers: Headers) -> DictStrAny: | ||
masked_dict = dict() | ||
for key, val in headers.items(): | ||
if key == 'authorization': | ||
masked_dict[key] = basic_auth_decode(val) | ||
elif key in AUTHED_REQUIRED_HEADERS: | ||
masked_dict[key] = val[0:5] + '*' * 5 if val else '' | ||
else: | ||
masked_dict[key] = val | ||
return masked_dict | ||
|
||
|
||
def mask_sensitive_data(data: Any) -> Any: | ||
if type(data) is dict: | ||
for key, val in data.items(): | ||
if type(val) is list: | ||
data[key] = [mask_sensitive_data(v) for v in val] | ||
elif key == 'number': | ||
data[key] = '*' * 12 + val[-4:] | ||
elif key in SENSITIVE_DATA_FIELDS and type(val) is int: | ||
data[key] = '***' | ||
elif key in SENSITIVE_DATA_FIELDS: | ||
data[key] = '*' * len(key) | ||
|
||
return data | ||
|
||
|
||
class OpenSearchLog(BaseHTTPMiddleware): | ||
async def dispatch( | ||
self, request: Request, call_next: RequestResponseEndpoint | ||
) -> Response: | ||
if not os.environ.get('LOGS_SERVER_URL', ''): | ||
return await call_next(request) | ||
|
||
request_data = dict(request.scope) | ||
|
||
request_headers = mask_sensitive_headers(request.headers) | ||
request_data['client'] = f'{request.client.host}:{request.client.port}' | ||
request_data['query_string'] = str(request.query_params) | ||
request_data['server'] = ':'.join( | ||
(str(v) for v in request.scope['server']) | ||
) | ||
|
||
for value in NON_VALID_SCOPE_VALUES: | ||
request_data.pop(value, None) | ||
|
||
response_body = {} | ||
|
||
try: | ||
response = await call_next(request) | ||
except FastAgaveError as exc: | ||
response_body = asdict(exc) | ||
raise | ||
except CuencaError as exc: | ||
response_body = dict(status_code=exc.status_code, code=str(exc)) | ||
raise | ||
else: | ||
# El objeto response es de tipo `starlette.responses.StreamingResponse` | ||
# por lo que sus datos vienen en binario, se deben obtener manualmente | ||
# y crear un custom Request | ||
# https://stackoverflow.com/questions/71882419/fastapi-how-to-get-the-response-body-in-middleware | ||
binary_response_body = b'' | ||
async for chunk in response.body_iterator: # type: ignore | ||
binary_response_body += chunk | ||
|
||
response_body = json.loads(binary_response_body.decode()) | ||
response = Response( | ||
content=binary_response_body, | ||
status_code=response.status_code, | ||
headers=dict(response.headers), | ||
media_type=response.media_type, | ||
) | ||
|
||
response_body = mask_sensitive_data(response_body) | ||
finally: | ||
asyncio.create_task( | ||
self.send_log_to_open_search( | ||
request.app.title, | ||
request_data, | ||
request_headers, | ||
response_body, | ||
) | ||
) | ||
return response | ||
|
||
@classmethod | ||
async def send_log_to_open_search( | ||
cls, | ||
app_name: str, | ||
request_data: DictStrAny, | ||
request_headers: DictStrAny, | ||
response_body: Optional[DictStrAny] = None, | ||
) -> None: | ||
log_server_url = os.environ.get('LOGS_SERVER_URL', '') | ||
data = dict( | ||
app=app_name, | ||
request_data=request_data, | ||
request_headers=request_headers, | ||
response_body=response_body, | ||
) | ||
async with ClientSession() as session: | ||
async with session.put(log_server_url, json=data): | ||
pass |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1 @@ | ||
__version__ = '0.6.0' | ||
__version__ = '0.7.0' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,5 @@ | ||
aiobotocore==2.1.0 | ||
aiohttp==3.7.4.post0 | ||
cuenca-validations==0.10.7 | ||
fastapi==0.68.2 | ||
mongoengine-plus==0.0.3 | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
import base64 | ||
from typing import Dict | ||
|
||
|
||
def auth_header(username: str, password: str = '') -> Dict: | ||
creds = base64.b64encode(f'{username}:{password}'.encode('ascii')).decode( | ||
'utf-8' | ||
) | ||
return {'Authorization': f'Basic {creds}'} |
Empty file.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
porque se manda a llamar dentro de la función y no como una variable global?