From 6b50fd603cbb9caa9648ff35ffa364072ca0cd42 Mon Sep 17 00:00:00 2001 From: Ievgen Bondarenko Date: Mon, 18 May 2026 00:54:00 -0700 Subject: [PATCH] fix(openai-frontend): use hmac.compare_digest for restriction header value APIRestrictionMiddleware._check_authentication compares the incoming header value against the operator-configured expected value with !=, which short-circuits at the first byte mismatch. A caller that can issue many requests against a restricted endpoint can in principle infer the configured header value byte-by-byte via response-time differences. Switch the compare to hmac.compare_digest, the standard Python idiom for constant-time string equality. Signed-off-by: Ievgen Bondarenko --- .../frontend/fastapi/middleware/api_restriction.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/python/openai/openai_frontend/frontend/fastapi/middleware/api_restriction.py b/python/openai/openai_frontend/frontend/fastapi/middleware/api_restriction.py index 085434ad46..bd85f85ef3 100644 --- a/python/openai/openai_frontend/frontend/fastapi/middleware/api_restriction.py +++ b/python/openai/openai_frontend/frontend/fastapi/middleware/api_restriction.py @@ -24,6 +24,8 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import hmac + from fastapi import Request from fastapi.responses import JSONResponse from starlette.middleware.base import BaseHTTPMiddleware @@ -219,8 +221,11 @@ def _check_authentication(self, request: Request, auth_header: tuple[str, str]): # Get the actual header value from the request actual_value = request.headers.get(expected_key) - # Validate the header value matches the expected value - if not actual_value or actual_value != expected_value: + # Validate the header value matches the expected value. Use + # hmac.compare_digest so the compare runs in time that does not + # depend on the position of the first differing byte. The short + # circuit on `not actual_value` keeps None and empty values out. + if not actual_value or not hmac.compare_digest(actual_value, expected_value): return { "valid": False, "message": f"This API is restricted, expecting header '{expected_key}' with valid value",