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
22 changes: 20 additions & 2 deletions marklogic/client.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Copyright (c) 2023-2025 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved.
# Copyright (c) 2023-2026 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved.


import json
Expand All @@ -7,6 +7,7 @@
from marklogic.cloud_auth import MarkLogicCloudAuth
from marklogic.documents import DocumentManager
from marklogic.internal.eval import process_multipart_mixed_response
from marklogic.internal.url import is_same_origin
from marklogic.rows import RowManager
from marklogic.transactions import TransactionManager, Transaction
from requests.auth import HTTPDigestAuth
Expand Down Expand Up @@ -70,9 +71,26 @@ def prepare_request(self, request, *args, **kwargs):
more information on prepared requests. Note that this is invoked after the
'request' method is invoked.
"""
request.url = urljoin(self.base_url, request.url)
request_url = urljoin(self.base_url, request.url)
if not is_same_origin(request_url, self.base_url):
Comment thread
jonmille marked this conversation as resolved.
Resolved
raise ValueError(
"Request URL must use the same origin as the configured base_url."
)
request.url = request_url
return super(Client, self).prepare_request(request, *args, **kwargs)

def should_strip_auth(self, old_url, new_url):
return not is_same_origin(old_url, new_url)

def rebuild_auth(self, prepared_request, response):
if not is_same_origin(prepared_request.url, self.base_url):
prepared_request.hooks["response"] = [
hook
for hook in prepared_request.hooks.get("response", [])
if getattr(hook, "__self__", None) is not self.auth
]
return super(Client, self).rebuild_auth(prepared_request, response)

@property
def documents(self):
if not hasattr(self, "_documents"):
Expand Down
10 changes: 8 additions & 2 deletions marklogic/cloud_auth.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Copyright (c) 2023-2025 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved.
# Copyright (c) 2023-2026 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved.


import logging
Expand All @@ -7,6 +7,8 @@
from requests.auth import AuthBase
from urllib.parse import urljoin

from marklogic.internal.url import is_same_origin

logger = logging.getLogger(__name__)


Expand Down Expand Up @@ -68,7 +70,11 @@ def _generate_token(self):
self._access_token = response.json()["access_token"]

def _renew_token_if_necessary(self, response: Response, *args, **kwargs):
if response.status_code == 401 and not self.resent_request_on_401:
request_url = response.request.url if response.request else None
is_unauthorized = response.status_code == 401
is_first_retry = not self.resent_request_on_401
matches_base_url = is_same_origin(request_url, self._base_url)
if is_unauthorized and is_first_retry and matches_base_url:
logger.debug("Received 401; will generate new token and try request again")
self.resent_request_on_401 = True
self._generate_token()
Expand Down
41 changes: 41 additions & 0 deletions marklogic/internal/url.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Copyright (c) 2023-2026 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved.


from urllib.parse import urlsplit
from requests.exceptions import RequestException
from requests.models import PreparedRequest


def is_same_origin(url: str, base_url: str) -> bool:
if not isinstance(url, str) or not isinstance(base_url, str):
return False

try:
url_request = PreparedRequest()
url_request.prepare_url(url, None)
base_request = PreparedRequest()
base_request.prepare_url(base_url, None)
url_parts = urlsplit(url_request.url)
base_parts = urlsplit(base_request.url)
url_port = url_parts.port
base_port = base_parts.port
except (RequestException, ValueError):
return False

url_scheme = url_parts.scheme.lower()
base_scheme = base_parts.scheme.lower()
url_host = url_parts.hostname
base_host = base_parts.hostname

if not url_scheme or not base_scheme or not url_host or not base_host:
return False

default_ports = {"http": 80, "https": 443}
if url_port is None:
url_port = default_ports.get(url_scheme)
if base_port is None:
base_port = default_ports.get(base_scheme)

url_origin = (url_scheme, url_host.lower(), url_port)
base_origin = (base_scheme, base_host.lower(), base_port)
return url_origin == base_origin
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,4 @@ build-backend = "poetry.core.masonry.api"
# Enables live logging; see https://docs.pytest.org/en/latest/how-to/logging.html#live-logs
log_cli = 1
log_cli_level = "DEBUG"
markers = ["unit: tests that do not require a MarkLogic server"]
13 changes: 9 additions & 4 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Copyright (c) 2023-2025 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved.
# Copyright (c) 2023-2026 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved.


import pytest
Expand Down Expand Up @@ -58,15 +58,20 @@ def cloud_config():


@pytest.fixture(autouse=True)
def prepare_test_database(admin_client: Client):
def prepare_test_database(admin_client: Client, request):
"""
Deletes any documents created by other tests to ensure a 'clean' database before a
test runs. Does not delete documents in the 'test-data' collection which is intended
to contain all the documents loaded by the test-app. A user with the 'admin' role
is used so that temporal documents can be deleted.
"""
query = "cts:uris((), (), cts:not-query(cts:collection-query('test-data'))) \
! xdmp:document-delete(.)"
if request.node.get_closest_marker("unit"):
return

query = (
"cts:uris((), (), cts:not-query(cts:collection-query('test-data'))) "
"! xdmp:document-delete(.)"
)
response = admin_client.post(
"v1/eval",
headers={"Content-type": "application/x-www-form-urlencoded"},
Expand Down
Loading
Loading