Skip to content

feat: Check if token is a JWT #529

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

Merged
merged 2 commits into from
Nov 22, 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
4 changes: 3 additions & 1 deletion postgrest/base_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from httpx import BasicAuth, Timeout

from .utils import AsyncClient, SyncClient, is_http_url
from .utils import AsyncClient, SyncClient, is_http_url, is_valid_jwt


class BasePostgrestClient(ABC):
Expand Down Expand Up @@ -58,6 +58,8 @@ def auth(
Bearer token is preferred if both ones are provided.
"""
if token:
if not is_valid_jwt(token):
ValueError("token must be a valid JWT authorization token")
self.session.headers["Authorization"] = f"Bearer {token}"
elif username:
self.session.auth = BasicAuth(username, password)
Expand Down
26 changes: 26 additions & 0 deletions postgrest/utils.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
from __future__ import annotations

import re
from typing import Any, Type, TypeVar, cast, get_origin
from urllib.parse import urlparse

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

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


class SyncClient(BaseClient):
def aclose(self) -> None:
Expand Down Expand Up @@ -40,3 +43,26 @@ def get_origin_and_cast(typ: type[type[_T]]) -> type[_T]:

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