Skip to content

Commit

Permalink
Merge pull request #26 from daxxog/dv/secure_compare
Browse files Browse the repository at this point in the history
Refactor secret-based security to compare secrets using `secrets.compare_digest`
  • Loading branch information
mrtolkien committed Jul 18, 2023
2 parents 87fcf21 + f9c7972 commit 3f904ef
Showing 1 changed file with 16 additions and 13 deletions.
29 changes: 16 additions & 13 deletions fastapi_simple_security/_security_secret.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import os
import uuid
import warnings
from secrets import compare_digest
from typing import Optional

from fastapi import Security
from fastapi.security import APIKeyHeader
Expand Down Expand Up @@ -50,7 +52,7 @@ def get_secret_value(self):
)


async def secret_based_security(header_param: str = Security(secret_header)):
async def secret_based_security(header_param: Optional[str] = Security(secret_header)):
"""
Args:
header_param: parsed header field secret_header
Expand All @@ -62,20 +64,21 @@ async def secret_based_security(header_param: str = Security(secret_header)):
HTTPException if the authentication failed
"""

# We simply return True if the given secret-key has the right value
if header_param == secret.value:
return True
if header_param:
# We simply return True if the given secret-key has the right value
if compare_digest(header_param, secret.value):
return True

# Error text without header param
if not header_param:
error = "secret_key must be passed as a header field"
# Error text with wrong header param
else:
error = (
"Wrong secret key. If not set through environment variable \
'FASTAPI_SIMPLE_SECURITY_SECRET', it was "
"generated automatically at startup and appears in the server logs."
)

# Error text with wrong header param
# Error text without header param
else:
error = (
"Wrong secret key. If not set through environment variable \
'FASTAPI_SIMPLE_SECURITY_SECRET', it was "
"generated automatically at startup and appears in the server logs."
)
error = "secret_key must be passed as a header field"

raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail=error)

0 comments on commit 3f904ef

Please sign in to comment.