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",