Skip to content

Commit

Permalink
HH-235907 small fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
712u3 committed Oct 29, 2024
1 parent 809bbe0 commit 12b1543
Show file tree
Hide file tree
Showing 11 changed files with 44 additions and 44 deletions.
5 changes: 4 additions & 1 deletion examples/example_app/pages/example.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
from fastapi import APIRouter

from frontik.dependencies import HttpClient
from frontik.routing import router

router = APIRouter()


@router.get('/example')
Expand Down
7 changes: 4 additions & 3 deletions frontik/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,12 +196,13 @@ def __init__(self, frontik_app: FrontikApplication) -> None:
super().__init__()
self.router = router

for _router in routers:
if _router is not router:
self.include_router(_router)

if options.openapi_enabled:
self.setup()

for _router in routers:
self.include_router(_router)

self.config = frontik_app.config
self.get_current_status = frontik_app.get_current_status
self.get_frontik_and_apps_versions = frontik_app.get_frontik_and_apps_versions
Expand Down
8 changes: 4 additions & 4 deletions frontik/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,21 +26,21 @@ def passed_basic_auth(auth_header: Optional[str], login: Optional[str], passwd:

def check_debug_auth_by_headers(
headers: Union[Mapping, MutableMapping], login: Optional[str], password: Optional[str]
) -> Optional[str]:
) -> Optional[dict]:
debug_auth_header = headers.get(DEBUG_AUTH_HEADER_NAME)
if debug_auth_header is not None:
debug_access = debug_auth_header == f'{login}:{password}'
if not debug_access:
return f'{DEBUG_AUTH_HEADER_NAME}-Header realm="Secure Area"'
return {'WWW-Authenticate': f'{DEBUG_AUTH_HEADER_NAME}-Header realm="Secure Area"'}
else:
auth_header: Optional[str] = headers.get('Authorization')
debug_access = passed_basic_auth(auth_header, login, password)
if not debug_access:
return 'Basic realm="Secure Area"'
return {'WWW-Authenticate': 'Basic realm="Secure Area"'}
return None


def check_debug_auth(
tornado_request: httputil.HTTPServerRequest, login: Optional[str], password: Optional[str]
) -> Optional[str]:
) -> Optional[dict]:
return check_debug_auth_by_headers(tornado_request.headers, login, password)
6 changes: 2 additions & 4 deletions frontik/config_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,7 @@ def parse_configs(config_files: Optional[str]) -> None:
configs_to_read = options.config
else:
if config_files is None:
msg = 'Configs can not be None'
raise Exception(msg)
raise Exception('Configs can not be None')
configs_to_read = config_files

configs_to_read_filter = filter(
Expand Down Expand Up @@ -86,5 +85,4 @@ def parse_command_line(options: Options, allowed_options: Iterable) -> None:
elif option.type == str or get_args(option.type) == (str, type(None)):
setattr(options, name, value)
else:
msg = f'Complex types are not implemented {name!r}: {value!r} ({option.type})'
raise Exception(msg)
raise Exception(f'Complex types are not implemented {name!r}: {value!r} ({option.type})')
23 changes: 14 additions & 9 deletions frontik/debug.py
Original file line number Diff line number Diff line change
Expand Up @@ -402,7 +402,7 @@ def transform_chunk(
start_time = time.time()
handler_name = request_context.get_handler_name()

debug_log_data = request_context.get_log_handler().produce_all() # type: ignore
debug_log_data = request_context.get_debug_log_handler().produce_all() # type: ignore
debug_log_data.set('code', str(int(response.status_code)))
debug_log_data.set('handler-name', handler_name if handler_name else 'unknown handler')
debug_log_data.set('started', _format_number(tornado_request._start_time))
Expand Down Expand Up @@ -477,41 +477,46 @@ def __init__(self, tornado_request: HTTPServerRequest) -> None:
self.inherited = tornado_request.headers.get(DEBUG_HEADER_NAME, None)
self.pass_debug = False
self.enabled = False
self.debug_response = False
self.profile_xslt = False
self.failed_auth_header: Optional[str] = None
self.failed_auth_headers: Optional[dict] = None
self.need_auth = (
self.debug_value is not None
or self.inherited
or self.notpl is not None
or self.notrl is not None
or self.noxsl is not None
)
self.auth_failed: Optional[bool] = None

if self.inherited:
debug_log.debug('debug mode is inherited due to %s request header', DEBUG_HEADER_NAME)

def require_debug_access(self, tornado_request: HTTPServerRequest, auth_failed: Optional[bool] = None) -> None:
if auth_failed is True:
self.failed_auth_header = 'Basic realm="Secure Area"'
self.auth_failed = True
return

if options.debug or auth_failed is False:
self.auth_failed = False
self.on_auth_ok()
return

self.failed_auth_header = check_debug_auth(tornado_request, options.debug_login, options.debug_password)
if not self.failed_auth_header:
self.failed_auth_headers = check_debug_auth(tornado_request, options.debug_login, options.debug_password)
if self.failed_auth_headers is None:
self.auth_failed = False
self.on_auth_ok()
return

self.auth_failed = True

def on_auth_ok(self) -> None:
self.debug_response = self.debug_value is not None or self.inherited
self.enabled = True
self.pass_debug = 'nopass' not in self.mode_values or bool(self.inherited)
self.profile_xslt = 'xslt' in self.mode_values

request_context.set_log_handler(DebugBufferedHandler())
request_context.set_debug_log_handler(DebugBufferedHandler())

if self.pass_debug:
debug_log.debug('%s header will be passed to all requests', DEBUG_HEADER_NAME)

def auth_failed(self) -> bool:
return self.failed_auth_header is not None
11 changes: 4 additions & 7 deletions frontik/handler_asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,8 @@ async def process_request(
return FrontikResponse(status_code=http.client.SERVICE_UNAVAILABLE)

debug_mode = make_debug_mode(frontik_app, tornado_request)
if debug_mode.auth_failed():
assert debug_mode.failed_auth_header is not None
return FrontikResponse(
status_code=http.client.UNAUTHORIZED, headers={'WWW-Authenticate': debug_mode.failed_auth_header}
)
if debug_mode.auth_failed:
return FrontikResponse(status_code=http.client.UNAUTHORIZED, headers=debug_mode.failed_auth_headers)

assert tornado_request.method is not None

Expand All @@ -84,7 +81,7 @@ async def process_request(

response = await execute_asgi_page(frontik_app, asgi_app, tornado_request, scope, debug_mode, integrations)

if debug_mode.enabled and not response.headers_written:
if debug_mode.debug_response and not response.headers_written:
debug_transform = DebugTransform(frontik_app, debug_mode)
response = debug_transform.transform_chunk(tornado_request, response)

Expand Down Expand Up @@ -138,7 +135,7 @@ async def send(message):
response.headers.add(h[0].decode(CHARSET), h[1].decode(CHARSET))
elif message['type'] == 'http.response.body':
chunk = message['body']
if debug_mode.enabled or not message.get('more_body'):
if debug_mode.debug_response or not message.get('more_body'):
response.body += chunk
elif not response.headers_written:
for integration in integrations.values():
Expand Down
6 changes: 3 additions & 3 deletions frontik/loggers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,9 @@ def produce_all(self):
raise NotImplementedError() # pragma: no cover


class GlobalLogHandler(Handler):
class DebugLogHandler(Handler):
def handle(self, record):
handler = request_context.get_log_handler()
handler = request_context.get_debug_log_handler()
if handler is not None:
handler.handle(record)

Expand Down Expand Up @@ -171,7 +171,7 @@ def bootstrap_logger(
handler.setLevel(logger_level)
logger.addHandler(handler)

logger.addHandler(GlobalLogHandler())
logger.addHandler(DebugLogHandler())
logger.propagate = False

return logger
Expand Down
4 changes: 2 additions & 2 deletions frontik/request_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,9 @@ def set_handler_name(route: APIRoute) -> None:
_context.get().handler_name = f'{route.endpoint.__module__}.{route.endpoint.__name__}'


def get_log_handler() -> Optional[DebugBufferedHandler]:
def get_debug_log_handler() -> Optional[DebugBufferedHandler]:
return _context.get().log_handler


def set_log_handler(log_handler: DebugBufferedHandler) -> None:
def set_debug_log_handler(log_handler: DebugBufferedHandler) -> None:
_context.get().log_handler = log_handler
7 changes: 3 additions & 4 deletions frontik/routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,9 @@ def add_api_route(self, *args: Any, **kwargs: Any) -> None:


class FastAPIRouter(APIRouter):
def __init__(self, include_in_app: bool = True, **kwargs: Any) -> None:
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
if include_in_app:
routers.append(self)
routers.append(self)

async def __call__(self, scope, receive, send):
assert scope['type'] == 'http'
Expand Down Expand Up @@ -83,7 +82,7 @@ def import_all_pages(app_module: str) -> None:
raise RuntimeError('failed on import page %s %s', full_name, ex)


router = FastAPIRouter(include_in_app=False)
router = FastAPIRouter()
regex_router = FrontikRegexRouter()
not_found_router = APIRouter()
method_not_allowed_router = APIRouter()
Expand Down
3 changes: 1 addition & 2 deletions frontik/service_discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,7 @@ def _get_weight_or_default(value: Optional[dict]) -> int:

def _get_hostname_or_raise(node_name: str) -> str:
if not node_name:
msg = 'options node_name must be defined'
raise RuntimeError(msg)
raise RuntimeError('options node_name must be defined')
return node_name


Expand Down
8 changes: 3 additions & 5 deletions tests/test_no_debug_mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,9 @@ def check_debug_auth_or_finish(login: str, password: str) -> None:
return
_login: Optional[str] = login or options.debug_login
_password: Optional[str] = password or options.debug_password
fail_header = check_debug_auth_by_headers(request.headers, _login, _password)
if fail_header:
raise HTTPException(
status_code=http.client.UNAUTHORIZED, detail='Unauthorized', headers={'WWW-Authenticate': fail_header}
)
fail_headers = check_debug_auth_by_headers(request.headers, _login, _password)
if fail_headers:
raise HTTPException(status_code=http.client.UNAUTHORIZED, detail='Unauthorized', headers=fail_headers)

check_debug_auth_or_finish('user', 'god')
return {'authenticated': True}
Expand Down

0 comments on commit 12b1543

Please sign in to comment.