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

Fix mutable reference headers #1095 #1096

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
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
15 changes: 9 additions & 6 deletions supabase/_async/client.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio
import copy
import re
from typing import Any, Dict, List, Optional, Union

Expand Down Expand Up @@ -69,8 +70,9 @@ def __init__(

self.supabase_url = supabase_url
self.supabase_key = supabase_key
self.options = options
options.headers.update(self._get_auth_headers())
self.options = copy.deepcopy(options)
self.options.headers.update(self._get_auth_headers())

self.rest_url = f"{supabase_url}/rest/v1"
self.realtime_url = f"{supabase_url}/realtime/v1".replace("http", "ws")
self.auth_url = f"{supabase_url}/auth/v1"
Expand All @@ -80,12 +82,12 @@ def __init__(
# Instantiate clients.
self.auth = self._init_supabase_auth_client(
auth_url=self.auth_url,
client_options=options,
client_options=self.options,
)
self.realtime = self._init_realtime_client(
realtime_url=self.realtime_url,
supabase_key=self.supabase_key,
options=options.realtime if options else None,
options=self.options.realtime if self.options else None,
)
self._postgrest = None
self._storage = None
Expand Down Expand Up @@ -294,8 +296,9 @@ def _listen_to_auth_events(
self._storage = None
self._functions = None
access_token = session.access_token if session else self.supabase_key

self.options.headers["Authorization"] = self._create_auth_header(access_token)
auth_header = copy.deepcopy(self._create_auth_header(access_token))
self.options.headers["Authorization"] = auth_header
self.auth._headers["Authorization"] = auth_header
asyncio.create_task(self.realtime.set_auth(access_token))


Expand Down
6 changes: 3 additions & 3 deletions supabase/_sync/auth_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@


class SyncSupabaseAuthClient(SyncGoTrueClient):
"""Supabase Auth Client for synchronous operations."""
"""Supabase Auth Client for asynchronous operations."""

def __init__(
self,
Expand All @@ -35,8 +35,8 @@ def __init__(
storage_key (Optional[str]): Key to store session information.
auto_refresh_token (bool): Whether to automatically refresh the token. Defaults to True.
persist_session (bool): Whether to persist the session. Defaults to True.
storage (SyncSupportedStorage): Storage mechanism. Defaults to SyncMemoryStorage().
http_client (Optional[SyncClient]): HTTP client for making requests. Defaults to None.
storage (AsyncSupportedStorage): Storage mechanism. Defaults to AsyncMemoryStorage().
http_client (Optional[AsyncClient]): HTTP client for making requests. Defaults to None.
flow_type (AuthFlowType): Type of authentication flow. Defaults to "implicit".
verify (bool): Whether to verify SSL certificates. Defaults to True.
proxy (Optional[str]): Proxy URL. Defaults to None.
Expand Down
13 changes: 8 additions & 5 deletions supabase/_sync/client.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import copy
import re
from typing import Any, Dict, List, Optional, Union

Expand Down Expand Up @@ -68,8 +69,9 @@ def __init__(

self.supabase_url = supabase_url
self.supabase_key = supabase_key
self.options = options
options.headers.update(self._get_auth_headers())
self.options = copy.deepcopy(options)
self.options.headers.update(self._get_auth_headers())

self.rest_url = f"{supabase_url}/rest/v1"
self.realtime_url = f"{supabase_url}/realtime/v1".replace("http", "ws")
self.auth_url = f"{supabase_url}/auth/v1"
Expand All @@ -79,12 +81,12 @@ def __init__(
# Instantiate clients.
self.auth = self._init_supabase_auth_client(
auth_url=self.auth_url,
client_options=options,
client_options=self.options,
)
self.realtime = self._init_realtime_client(
realtime_url=self.realtime_url,
supabase_key=self.supabase_key,
options=options.realtime if options else None,
options=self.options.realtime if self.options else None,
)
self._postgrest = None
self._storage = None
Expand Down Expand Up @@ -293,8 +295,9 @@ def _listen_to_auth_events(
self._storage = None
self._functions = None
access_token = session.access_token if session else self.supabase_key
auth_header = copy.deepcopy(self._create_auth_header(access_token))

self.options.headers["Authorization"] = self._create_auth_header(access_token)
self.options.headers["Authorization"] = auth_header


def create_client(
Expand Down
49 changes: 47 additions & 2 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from unittest.mock import MagicMock

import pytest
from gotrue import SyncMemoryStorage

from supabase import Client, ClientOptions, SupabaseException, create_client

Expand Down Expand Up @@ -101,7 +102,6 @@ def test_updates_the_authorization_header_on_auth_events() -> None:
mock_session = MagicMock(access_token="secretuserjwt")
realtime_mock = MagicMock()
client.realtime = realtime_mock

client._listen_to_auth_events("SIGNED_IN", mock_session)

updated_authorization = f"Bearer {mock_session.access_token}"
Expand All @@ -113,9 +113,54 @@ def test_updates_the_authorization_header_on_auth_events() -> None:
assert (
client.postgrest.session.headers.get("Authorization") == updated_authorization
)

assert client.auth._headers.get("apiKey") == key
assert client.auth._headers.get("Authorization") == updated_authorization

assert client.storage.session.headers.get("apiKey") == key
assert client.storage.session.headers.get("Authorization") == updated_authorization


def test_mutable_headers_issue():
url = os.environ.get("SUPABASE_TEST_URL")
key = os.environ.get("SUPABASE_TEST_KEY")

shared_options = ClientOptions(
storage=SyncMemoryStorage(), headers={"Authorization": "Bearer initial-token"}
)

client1 = create_client(url, key, shared_options)

client2 = create_client(url, key, shared_options)

client1.options.headers["Authorization"] = "Bearer modified-token"

assert client2.options.headers["Authorization"] == "Bearer initial-token"


def test_global_authorization_header_issue():
url = os.environ.get("SUPABASE_TEST_URL")
key = os.environ.get("SUPABASE_TEST_KEY")

authorization = "Bearer secretuserjwt"
options = ClientOptions(headers={"Authorization": authorization})

client = create_client(url, key, options)

assert client.options.headers.get("apiKey") == key


def test_mutable_headers_issue():
url = os.environ.get("SUPABASE_TEST_URL")
key = os.environ.get("SUPABASE_TEST_KEY")

shared_options = ClientOptions(
headers={"Authorization": "Bearer initial-token", "x-site": "supanew.site"}
)

client1 = create_client(url, key, shared_options)
client2 = create_client(url, key, shared_options)
client1.options.replace({"headers": {"Authorization": "Bearer modified-token"}})

assert client2.options.headers["Authorization"] == "Bearer initial-token"
assert client2.options.headers["x-site"] == "supanew.site"
assert client1.options.headers["x-site"] == "supanew.site"