Skip to content

Commit

Permalink
Merge pull request #200 from anaconda/redirect-fix
Browse files Browse the repository at this point in the history
Fix handling of relative redirect URLs
  • Loading branch information
mcg1969 authored Oct 7, 2024
2 parents 3fa58e9 + b478eae commit 5176a41
Showing 1 changed file with 5 additions and 12 deletions.
17 changes: 5 additions & 12 deletions ae5_tools/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from http.cookiejar import LWPCookieJar
from os.path import abspath, basename, isdir, isfile, join
from tempfile import TemporaryDirectory
from urllib.parse import urljoin

import requests
from dateutil import parser
Expand Down Expand Up @@ -267,6 +268,7 @@ def __init__(self, hostname, username, password, prefix, persist):
self.password = password
self.persist = persist
self.prefix = prefix.lstrip("/")
self.base = f"https://{self.hostname}/{self.prefix}/"
self.session: Session = AESessionBase._build_requests_session()

# Cloudflare headers need to be present on all requests (even before auth can be start).
Expand Down Expand Up @@ -558,15 +560,8 @@ def _format_response(self, response, format, columns=None, record_type=None):
def _api(self, method, endpoint, **kwargs):
format = kwargs.pop("format", None)
subdomain = kwargs.pop("subdomain", None)
isabs, endpoint = endpoint.startswith("/"), endpoint.lstrip("/")
if subdomain:
subdomain += "."
isabs = True
else:
subdomain = ""
if not isabs:
endpoint = f"{self.prefix}/{endpoint}"
url = f"https://{subdomain}{self.hostname}/{endpoint}"
base = self.base.replace("//", f"//{subdomain}.") if subdomain else self.base
url = urljoin(base, endpoint)
do_save = False
allow_retry = True
if not self.connected:
Expand All @@ -584,9 +579,7 @@ def _api(self, method, endpoint, **kwargs):
if 300 <= response.status_code < 400:
# Redirection here happens for two reasons, described below. We
# handle them ourselves to provide better behavior than requests.
url2 = response.headers["location"].rstrip()
if url2.startswith("/"):
url2 = f"https://{subdomain}{self.hostname}{url2}"
url2 = urljoin(url, response.headers["location"].rstrip())
if url2 != url:
# In this case we are likely being redirected to auth to retrieve
# a cookie for the endpoint session itself. We will want to save
Expand Down

0 comments on commit 5176a41

Please sign in to comment.