Skip to content
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
11 changes: 5 additions & 6 deletions src/auth/src/supabase_auth/helpers.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from __future__ import annotations

import base64
import binascii
import hashlib
import secrets
import string
Expand Down Expand Up @@ -206,15 +205,15 @@ def decode_jwt(token: str) -> DecodedJWT:
raise AuthInvalidJwtError("Invalid JWT structure")

try:
header = base64url_to_bytes(parts[0])
payload = base64url_to_bytes(parts[1])
header = JWTHeader.model_validate_json(base64url_to_bytes(parts[0]))
payload = JWTPayload.model_validate_json(base64url_to_bytes(parts[1]))
signature = base64url_to_bytes(parts[2])
except binascii.Error as e:
except ValueError as e:
raise AuthInvalidJwtError("Invalid JWT structure") from e

return DecodedJWT(
header=JWTHeader.model_validate_json(header),
payload=JWTPayload.model_validate_json(payload),
header=header,
payload=payload,
signature=signature,
raw_header=parts[0],
raw_payload=parts[1],
Expand Down
2 changes: 1 addition & 1 deletion src/auth/src/supabase_auth/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -1035,7 +1035,7 @@ class GenerateLinkResponse(BaseModel):

class JWTHeader(BaseModel, extra="allow"):
alg: Literal["RS256", "ES256", "HS256"]
typ: str
typ: str | None = None
kid: str | None = None


Expand Down
7 changes: 7 additions & 0 deletions src/auth/tests/_async/conftest.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import base64
import json
from collections.abc import AsyncGenerator
from dataclasses import dataclass
from random import random
Expand All @@ -19,6 +21,11 @@
from ..http_sessions import async_http_sessions as http_sessions


def base64url_segment(value: object) -> str:
raw = value if isinstance(value, bytes) else json.dumps(value).encode()
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()


def mock_access_token() -> str:
return encode(
{
Expand Down
43 changes: 43 additions & 0 deletions src/auth/tests/_async/test_get_claims.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import pytest
from httpx import AsyncClient, MockTransport, Request, Response
from supabase_utils.http.adapters.httpx import AsyncHttpxSession

from supabase_auth import AsyncSupabaseAuthClient
from supabase_auth.errors import AuthInvalidJwtError

from .conftest import base64url_segment

PAYLOAD = base64url_segment({"sub": "user", "exp": 9999999999})


def mock_client(requests: list[Request]) -> AsyncSupabaseAuthClient:
def handler(request: Request) -> Response:
requests.append(request)
return Response(500)

return AsyncSupabaseAuthClient(
url="http://localhost",
http_session=AsyncHttpxSession(
client=AsyncClient(transport=MockTransport(handler))
),
auto_refresh_token=False,
)


@pytest.mark.parametrize(
"token",
[
"opaque-token",
f"{base64url_segment({'typ': 'JWT'})}.{PAYLOAD}.sig",
"\u00e9.\u00e9.\u00e9",
],
ids=["opaque", "alg-missing", "non-ascii"],
)
async def test_get_claims_raises_auth_error_for_malformed_jwt(token: str) -> None:
requests: list[Request] = []
client = mock_client(requests)

with pytest.raises(AuthInvalidJwtError, match=r"Invalid JWT structure"):
await client.get_claims(token)

assert requests == []
39 changes: 28 additions & 11 deletions src/auth/tests/_async/test_set_session.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import base64
import json
import time
from typing import Any

import pytest
from httpx import AsyncClient, MockTransport, Request, Response
from supabase_utils.http.adapters.httpx import AsyncHttpxSession
from supabase_utils.types import JSON

from supabase_auth import AsyncSupabaseAuthClient
from supabase_auth.errors import AuthInvalidJwtError
from supabase_auth.types import AuthChangeEvent, AuthStateChange

from .conftest import base64url_segment

USER: dict[str, JSON] = {
"id": "11111111-1111-1111-1111-111111111111",
"aud": "authenticated",
Expand All @@ -20,15 +21,10 @@
}


def b64(value: dict[str, Any]) -> str:
raw = json.dumps(value, separators=(",", ":")).encode()
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()


def token(exp: int) -> str:
header = b64({"alg": "HS256", "typ": "JWT"})
payload = b64({"exp": exp, "sub": USER["id"]})
return f"{header}.{payload}.{b64({'sig': 1})}"
header = base64url_segment({"alg": "HS256", "typ": "JWT"})
payload = base64url_segment({"exp": exp, "sub": USER["id"]})
return f"{header}.{payload}.{base64url_segment({'sig': 1})}"


def mock_client(requests: list[Request] | None = None) -> AsyncSupabaseAuthClient:
Expand Down Expand Up @@ -101,3 +97,24 @@ async def test_set_session_stores_the_expiry_of_the_access_token() -> None:
assert session is not None
assert session.access_token == token(exp)
assert [request.url.path for request in requests] == ["/user"]


@pytest.mark.parametrize(
"access_token",
[
f"{base64url_segment({'typ': 'JWT'})}.{base64url_segment({'exp': 1})}.sig",
f"{base64url_segment({'alg': 'HS256'})}.{base64url_segment(b'not json')}.sig",
"\u00e9.\u00e9.\u00e9",
],
ids=["alg-missing", "payload-not-json", "non-ascii"],
)
async def test_set_session_raises_auth_error_for_malformed_jwt(
access_token: str,
) -> None:
requests: list[Request] = []
client = mock_client(requests)

with pytest.raises(AuthInvalidJwtError, match=r"Invalid JWT structure"):
await client.set_session(access_token, "refresh-token")

assert requests == []
7 changes: 7 additions & 0 deletions src/auth/tests/_sync/conftest.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import base64
import json
from collections.abc import Generator
from dataclasses import dataclass
from random import random
Expand All @@ -19,6 +21,11 @@
from ..http_sessions import sync_http_sessions as http_sessions


def base64url_segment(value: object) -> str:
raw = value if isinstance(value, bytes) else json.dumps(value).encode()
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()


def mock_access_token() -> str:
return encode(
{
Expand Down
41 changes: 41 additions & 0 deletions src/auth/tests/_sync/test_get_claims.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import pytest
from httpx import Client, MockTransport, Request, Response
from supabase_utils.http.adapters.httpx import HttpxSession

from supabase_auth import SyncSupabaseAuthClient
from supabase_auth.errors import AuthInvalidJwtError

from .conftest import base64url_segment

PAYLOAD = base64url_segment({"sub": "user", "exp": 9999999999})


def mock_client(requests: list[Request]) -> SyncSupabaseAuthClient:
def handler(request: Request) -> Response:
requests.append(request)
return Response(500)

return SyncSupabaseAuthClient(
url="http://localhost",
http_session=HttpxSession(client=Client(transport=MockTransport(handler))),
auto_refresh_token=False,
)


@pytest.mark.parametrize(
"token",
[
"opaque-token",
f"{base64url_segment({'typ': 'JWT'})}.{PAYLOAD}.sig",
"\u00e9.\u00e9.\u00e9",
],
ids=["opaque", "alg-missing", "non-ascii"],
)
def test_get_claims_raises_auth_error_for_malformed_jwt(token: str) -> None:
requests: list[Request] = []
client = mock_client(requests)

with pytest.raises(AuthInvalidJwtError, match=r"Invalid JWT structure"):
client.get_claims(token)

assert requests == []
39 changes: 28 additions & 11 deletions src/auth/tests/_sync/test_set_session.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import base64
import json
import time
from typing import Any

import pytest
from httpx import Client, MockTransport, Request, Response
from supabase_utils.http.adapters.httpx import HttpxSession
from supabase_utils.types import JSON

from supabase_auth import SyncSupabaseAuthClient
from supabase_auth.errors import AuthInvalidJwtError
from supabase_auth.types import AuthChangeEvent, AuthStateChange

from .conftest import base64url_segment

USER: dict[str, JSON] = {
"id": "11111111-1111-1111-1111-111111111111",
"aud": "authenticated",
Expand All @@ -20,15 +21,10 @@
}


def b64(value: dict[str, Any]) -> str:
raw = json.dumps(value, separators=(",", ":")).encode()
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()


def token(exp: int) -> str:
header = b64({"alg": "HS256", "typ": "JWT"})
payload = b64({"exp": exp, "sub": USER["id"]})
return f"{header}.{payload}.{b64({'sig': 1})}"
header = base64url_segment({"alg": "HS256", "typ": "JWT"})
payload = base64url_segment({"exp": exp, "sub": USER["id"]})
return f"{header}.{payload}.{base64url_segment({'sig': 1})}"


def mock_client(requests: list[Request] | None = None) -> SyncSupabaseAuthClient:
Expand Down Expand Up @@ -99,3 +95,24 @@ def test_set_session_stores_the_expiry_of_the_access_token() -> None:
assert session is not None
assert session.access_token == token(exp)
assert [request.url.path for request in requests] == ["/user"]


@pytest.mark.parametrize(
"access_token",
[
f"{base64url_segment({'typ': 'JWT'})}.{base64url_segment({'exp': 1})}.sig",
f"{base64url_segment({'alg': 'HS256'})}.{base64url_segment(b'not json')}.sig",
"\u00e9.\u00e9.\u00e9",
],
ids=["alg-missing", "payload-not-json", "non-ascii"],
)
def test_set_session_raises_auth_error_for_malformed_jwt(
access_token: str,
) -> None:
requests: list[Request] = []
client = mock_client(requests)

with pytest.raises(AuthInvalidJwtError, match=r"Invalid JWT structure"):
client.set_session(access_token, "refresh-token")

assert requests == []
55 changes: 55 additions & 0 deletions src/auth/tests/test_helpers.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import base64
import json
from datetime import UTC, datetime
from typing import Any
Expand Down Expand Up @@ -59,6 +60,60 @@ def test_decode_jwt() -> None:
assert exc.value is not None


def _segment(value: object) -> str:
raw = value if isinstance(value, bytes) else json.dumps(value).encode()
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()


def _token(header: object, payload: object) -> str:
return f"{_segment(header)}.{_segment(payload)}.{_segment(b'signature')}"


_HEADER = {"alg": "HS256", "typ": "JWT"}
_PAYLOAD = {"sub": "user", "exp": 9999999999}


@pytest.mark.parametrize(
"token",
[
_token(b"not json", _PAYLOAD),
_token(_HEADER, b"not json"),
_token({"alg": "none", "typ": "JWT"}, _PAYLOAD),
_token({"alg": "EdDSA", "typ": "JWT"}, _PAYLOAD),
_token({"typ": "JWT"}, _PAYLOAD),
_token([_HEADER], _PAYLOAD),
_token(_HEADER, {"sub": "user", "exp": "soon"}),
"a.b.c",
"\u00e9.\u00e9.\u00e9",
f"{_segment(_HEADER)}.{_segment(_PAYLOAD)}.a",
],
ids=[
"header-not-json",
"payload-not-json",
"alg-none",
"alg-eddsa",
"alg-missing",
"header-array",
"exp-string",
"undecodable-base64",
"non-ascii",
"undecodable-signature",
],
)
def test_decode_jwt_raises_auth_error_for_malformed_segments(token: str) -> None:
with pytest.raises(AuthInvalidJwtError, match=r"Invalid JWT structure"):
decode_jwt(token)


def test_decode_jwt_accepts_header_without_typ() -> None:
decoded = decode_jwt(_token({"alg": "HS256"}, _PAYLOAD))

assert decoded.header.alg == "HS256"
assert decoded.header.typ is None
assert decoded.payload.sub == "user"
assert decoded.payload.exp == 9999999999


def test_jwt_payload_parses_amr_entries_into_models() -> None:
payload = JWTPayload.model_validate(
{"amr": [{"method": "password", "timestamp": 1700000000}]}
Expand Down
Loading