import time
from uuid import uuid4
from satosa.context import Context
from satosa.response import Response
from pyeudiw.jwt.jws_helper import JWSHelper
from pyeudiw.satosa.exceptions import InvalidRequestException
from pyeudiw.satosa.frontends.openid4vci.endpoints.vci_base_endpoint import (
POST_ACCEPTED_METHODS,
VCIBaseEndpoint,
)
from pyeudiw.satosa.frontends.openid4vci.models.nonce_response import NonceResponse
from pyeudiw.satosa.frontends.openid4vci.storage.engine import OpenId4VciDBEngineHandler
from pyeudiw.satosa.frontends.openid4vci.tools.exceptions import InvalidScopeException
from pyeudiw.satosa.utils.validation import (
validate_content_type,
validate_request_method,
)
from pyeudiw.tools.content_type import HTTP_CONTENT_TYPE_HEADER, FORM_URLENCODED
[docs]
class NonceHandler(VCIBaseEndpoint):
_DEFAULT_DURATION = 300
def __init__(
self,
config: dict,
internal_attributes: dict[str, dict[str, str | list[str]]],
base_url: str,
name: str,
*args,
**kwargs
):
"""
Initialize the nonce endpoint class.
Args:
config (dict): The configuration dictionary.
internal_attributes (dict): The internal attributes config.
base_url (str): The base URL of the service.
name (str): The name of the SATOSA module to append to the URL.
"""
super().__init__(config, internal_attributes, base_url, name)
self.jws_helper = JWSHelper(self.config["metadata_jwks"])
self.db_engine = OpenId4VciDBEngineHandler(config).db_engine
self.expired_sec = (
self.config["endpoints"]["nonce"].get("config", {}).get("nonce_duration") or
self._DEFAULT_DURATION
)
[docs]
def endpoint(self, context: Context) -> Response:
"""
Handle a POST request to the nonce endpoint.
Args:
context (Context): The SATOSA context.
Returns:
A Response object.
"""
try:
validate_request_method(context.request_method, POST_ACCEPTED_METHODS)
# OpenID4VCI nonce request is POST with an empty body and no
# Content-Type (Content-Length: 0). Validate only when present.
content_type = context.http_headers.get(HTTP_CONTENT_TYPE_HEADER)
if content_type:
validate_content_type(content_type, FORM_URLENCODED)
if self._get_body(context):
return self._handle_400(
context, "Request body must be empty for nonce endpoint"
)
c_nonce = str(uuid4())
ts = round(time.time() * 1000)
if self.db_engine.write("insert_nonce", nonce=c_nonce, created_at=ts, expires_in=self.expired_sec) < 1:
return self._handle_500(context, "error during nonce generating", Exception("Nonce error"))
return NonceResponse.to_response(c_nonce)
except (InvalidRequestException, InvalidScopeException) as e:
return self._handle_400(context, e.message, e)
except Exception as e:
self._log_error(
e.__class__.__name__, f"Error during invoke nonce endpoint: {e}"
)
return self._handle_500(context, "error during invoke nonce endpoint", e)