Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Check if token is a JWT #159

Merged
merged 4 commits into from
Nov 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion supabase_functions/_async/functions_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from httpx import HTTPError, Response

from ..errors import FunctionsHttpError, FunctionsRelayError
from ..utils import AsyncClient, is_http_url, is_valid_str_arg
from ..utils import AsyncClient, is_http_url, is_valid_jwt, is_valid_str_arg
from ..version import __version__


Expand Down Expand Up @@ -60,6 +60,9 @@ def set_auth(self, token: str) -> None:
the new jwt token sent in the authorization header
"""

if not is_valid_jwt(token):
ValueError("token must be a valid JWT authorization token string.")

self.headers["Authorization"] = f"Bearer {token}"

async def invoke(
Expand Down
5 changes: 4 additions & 1 deletion supabase_functions/_sync/functions_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from httpx import HTTPError, Response

from ..errors import FunctionsHttpError, FunctionsRelayError
from ..utils import SyncClient, is_http_url, is_valid_str_arg
from ..utils import SyncClient, is_http_url, is_valid_jwt, is_valid_str_arg
from ..version import __version__


Expand Down Expand Up @@ -60,6 +60,9 @@ def set_auth(self, token: str) -> None:
the new jwt token sent in the authorization header
"""

if not is_valid_jwt(token):
ValueError("token must be a valid JWT authorization token string.")

self.headers["Authorization"] = f"Bearer {token}"

def invoke(
Expand Down
25 changes: 25 additions & 0 deletions supabase_functions/utils.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import re
from urllib.parse import urlparse

from httpx import AsyncClient as AsyncClient # noqa: F401
from httpx import Client as BaseClient

DEFAULT_FUNCTION_CLIENT_TIMEOUT = 5
BASE64URL_REGEX = r"^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$"


class SyncClient(BaseClient):
Expand All @@ -17,3 +19,26 @@ def is_valid_str_arg(target: str) -> bool:

def is_http_url(url: str) -> bool:
return urlparse(url).scheme in {"https", "http"}


def is_valid_jwt(value: str) -> bool:
"""Checks if value looks like a JWT, does not do any extra parsing."""
if not isinstance(value, str):
return False

# Remove trailing whitespaces if any.
value = value.strip()

# Remove "Bearer " prefix if any.
if value.startswith("Bearer "):
value = value[7:]

# Valid JWT must have 2 dots (Header.Paylod.Signature)
if value.count(".") != 2:
return False

for part in value.split("."):
if not re.search(BASE64URL_REGEX, part, re.IGNORECASE):
return False

return True