diff --git a/cashu/core/crypto/keys.py b/cashu/core/crypto/keys.py index 9993a91..fcf8c9f 100644 --- a/cashu/core/crypto/keys.py +++ b/cashu/core/crypto/keys.py @@ -58,5 +58,5 @@ def derive_keyset_id(keys: Dict[int, PublicKey]): def random_hash() -> str: """Returns a base64-urlsafe encoded random hash.""" return base64.urlsafe_b64encode( - bytes([random.getrandbits(8) for i in range(32)]) + bytes([random.getrandbits(8) for i in range(30)]) ).decode() diff --git a/cashu/mint/app.py b/cashu/mint/app.py index 078a939..895945e 100644 --- a/cashu/mint/app.py +++ b/cashu/mint/app.py @@ -3,6 +3,10 @@ import sys from traceback import print_exception from fastapi import FastAPI, status +from fastapi.exception_handlers import ( + request_validation_exception_handler as _request_validation_exception_handler, +) +from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse # from fastapi_profiler import PyInstrumentProfilerMiddleware @@ -114,6 +118,12 @@ app = create_app() @app.middleware("http") async def catch_exceptions(request: Request, call_next): + CORS_HEADERS = { + "Access-Control-Allow-Origin": "*", + "Access-Control-Allow-Methods": "*", + "Access-Control-Allow-Headers": "*", + "Access-Control-Allow-Credentials": "true", + } try: return await call_next(request) except Exception as e: @@ -124,22 +134,44 @@ async def catch_exceptions(request: Request, call_next): if isinstance(e, CashuError): logger.error(f"CashuError: {err_message}") + # return with cors headers return JSONResponse( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + status_code=status.HTTP_400_BAD_REQUEST, content={"detail": err_message, "code": e.code}, + headers=CORS_HEADERS, ) logger.error(f"Exception: {err_message}") if settings.debug: print_exception(*sys.exc_info()) return JSONResponse( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + status_code=status.HTTP_400_BAD_REQUEST, content={"detail": err_message, "code": 0}, + headers=CORS_HEADERS, ) +async def request_validation_exception_handler( + request: Request, exc: RequestValidationError +) -> JSONResponse: + """ + This is a wrapper to the default RequestValidationException handler of FastAPI. + This function will be called when client input is not valid. + """ + query_params = request.query_params._dict + detail = { + "errors": exc.errors(), + "query_params": query_params, + } + # log the error + logger.error(detail) + # pass on + return await _request_validation_exception_handler(request, exc) + + @app.on_event("startup") async def startup_mint(): await start_mint_init() app.include_router(router=router) +app.add_exception_handler(RequestValidationError, request_validation_exception_handler)