|
| 1 | +# License: MIT |
| 2 | +# Copyright © 2025 Frequenz Energy-as-a-Service GmbH |
| 3 | + |
| 4 | +"""An Interceptor that adds HMAC signature of the metadata fields to a gRPC call.""" |
| 5 | + |
| 6 | +import dataclasses |
| 7 | +import hmac |
| 8 | +import logging |
| 9 | +import secrets |
| 10 | +import time |
| 11 | +from base64 import urlsafe_b64encode |
| 12 | +from typing import Any, Callable |
| 13 | + |
| 14 | +from grpc.aio import ( |
| 15 | + ClientCallDetails, |
| 16 | + UnaryUnaryCall, |
| 17 | + UnaryUnaryClientInterceptor, |
| 18 | +) |
| 19 | + |
| 20 | +_logger = logging.getLogger(__name__) |
| 21 | + |
| 22 | + |
| 23 | +@dataclasses.dataclass(frozen=True) |
| 24 | +class SigningOptions: |
| 25 | + """Options for message signing of messages.""" |
| 26 | + |
| 27 | + secret: str |
| 28 | + """The secret to sign the message with.""" |
| 29 | + |
| 30 | + |
| 31 | +# There is an issue in gRPC that causes the type to be unspecifieable correctly here. |
| 32 | +class SigningInterceptor(UnaryUnaryClientInterceptor): # type: ignore[type-arg] |
| 33 | + """An Interceptor that adds HMAC authentication of the metadata fields to a gRPC call.""" |
| 34 | + |
| 35 | + def __init__(self, options: SigningOptions): |
| 36 | + """Create an instance of the interceptor. |
| 37 | +
|
| 38 | + Args: |
| 39 | + options: The options for signing the message. |
| 40 | + """ |
| 41 | + self._secret = options.secret.encode() |
| 42 | + |
| 43 | + async def intercept_unary_unary( |
| 44 | + self, |
| 45 | + continuation: Callable[ |
| 46 | + [ClientCallDetails, object], UnaryUnaryCall[object, object] |
| 47 | + ], |
| 48 | + client_call_details: ClientCallDetails, |
| 49 | + request: object, |
| 50 | + ) -> object: |
| 51 | + """Intercept the call to add HMAC authentication to the metadata fields. |
| 52 | +
|
| 53 | + This is a known method from the base class that is overridden. |
| 54 | +
|
| 55 | + Args: |
| 56 | + continuation: The next interceptor in the chain. |
| 57 | + client_call_details: The call details. |
| 58 | + request: The request object. |
| 59 | +
|
| 60 | + Returns: |
| 61 | + The response object (this implementation does not modify the response). |
| 62 | + """ |
| 63 | + self.add_hmac( |
| 64 | + client_call_details, |
| 65 | + int(time.time()).to_bytes(8, "big"), |
| 66 | + secrets.token_bytes(16), |
| 67 | + ) |
| 68 | + return await continuation(client_call_details, request) |
| 69 | + |
| 70 | + def add_hmac( |
| 71 | + self, client_call_details: ClientCallDetails, ts: bytes, nonce: bytes |
| 72 | + ) -> None: |
| 73 | + """Add the HMAC authentication to the metadata fields of the call details. |
| 74 | +
|
| 75 | + The extra headers are directly added to the client_call details. |
| 76 | +
|
| 77 | + Args: |
| 78 | + client_call_details: The call details. |
| 79 | + ts: The timestamp to use for the HMAC. |
| 80 | + nonce: The nonce to use for the HMAC. |
| 81 | + """ |
| 82 | + if client_call_details.metadata is None: |
| 83 | + _logger.error( |
| 84 | + "No metadata found, cannot extract an api key. Therefore, cannot sign the request." |
| 85 | + ) |
| 86 | + return |
| 87 | + |
| 88 | + key: Any = client_call_details.metadata.get("x-key") |
| 89 | + if key is None: |
| 90 | + _logger.error("No key found in metadata, cannot sign the request.") |
| 91 | + return |
| 92 | + hmac_obj = hmac.new(self._secret, digestmod="sha256") |
| 93 | + hmac_obj.update(key.encode()) |
| 94 | + hmac_obj.update(ts) |
| 95 | + hmac_obj.update(nonce) |
| 96 | + |
| 97 | + hmac_obj.update(client_call_details.method.encode()) |
| 98 | + |
| 99 | + client_call_details.metadata["x-ts"] = ts |
| 100 | + client_call_details.metadata["x-nonce"] = nonce |
| 101 | + client_call_details.metadata["x-hmac"] = urlsafe_b64encode(hmac_obj.digest()) |
0 commit comments