Skip to content
Draft
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
7 changes: 4 additions & 3 deletions automated_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@

# Fake modules to avoid import errors
requests = type(sys)("requests")
requests.__dict__["Response"] = type(
"Response", (), {"__module__": "requests"}
)
requests.__dict__.update({
name: type(name, (), {"__module__": "requests"})
for name in ("Response", "Session")
})
websocket = type(sys)("websocket")
websocket.__dict__.update({
name: type(name, (), {"__module__": "websocket"})
Expand Down
5 changes: 3 additions & 2 deletions ayon_api/server_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@
fill_own_attribs,
UserInfo,
get_user_info_by_token,
ServerSession,
)
from ._api_helpers import (
InstallersAPI,
Expand Down Expand Up @@ -1002,7 +1003,7 @@ def create_session(
session = self._validation_session
self._validation_session = None
if session is None:
session = requests.Session()
session = ServerSession()
session.cert = self._cert
session.verify = self._ssl_verify
session.headers.update(self.get_headers())
Expand Down Expand Up @@ -1042,7 +1043,7 @@ def _get_validation_session(self) -> requests.Session:

"""
if self._validation_session is None:
session = requests.Session()
session = ServerSession()
session.cert = self._cert
session.verify = self._ssl_verify
self._validation_session = session
Expand Down
22 changes: 22 additions & 0 deletions ayon_api/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -586,6 +586,28 @@ def prepare_entity_changes(
return changes


class ServerSession(requests.Session):
"""Session that does not send AYON auth headers to other hosts.

'requests' removes only 'Authorization' header when a redirect leads to
a different host. Service api key in 'X-Api-Key' would be sent e.g.
to cloud storage the server redirects file downloads to.

"""
# Headers used for authorization of service api key
redirect_strip_headers = ("X-Api-Key", "X-as-user")

def rebuild_auth(self, prepared_request, response) -> None:
headers = prepared_request.headers
if any(key in headers for key in self.redirect_strip_headers):
if self.should_strip_auth(
response.request.url, prepared_request.url
):
for key in self.redirect_strip_headers:
headers.pop(key, None)
super().rebuild_auth(prepared_request, response)


def _try_parse_url(url: str) -> ParseResult | None:
try:
return urlparse(url)
Expand Down
119 changes: 119 additions & 0 deletions tests/test_redirect_auth_headers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
"""Service api key headers are not sent to other host on redirect."""
import http.server
import json
import threading

import pytest

from ayon_api import ServerAPI

SERVICE_KEY = "s" * 32


class _Handler(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"

def _send(self, code, body=b"", headers=None):
self.send_response(code)
for key, value in (headers or {}).items():
self.send_header(key, value)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)

def do_GET(self):
path = self.path.split("?")[0]
# 'download_file' does not prepend '/api'
if path.startswith("/api/redirect/"):
path = path[len("/api"):]
if path.startswith("/redirect/"):
# '/redirect/<host>/<name>'
host, name = path[len("/redirect/"):].split("/", 1)
port = self.server.server_address[1]
self._send(302, headers={
"Location": f"http://{host}:{port}/echo/{name}"
})
return

if path.startswith("/echo/"):
self.server.received[path[len("/echo/"):]] = dict(self.headers)
self._send(200, b"content", {
"Content-Type": "application/octet-stream"
})
return

if path == "/api/users/me":
if self.headers.get("X-Api-Key") == SERVICE_KEY:
self._send(
200,
json.dumps({"name": "service"}).encode(),
{"Content-Type": "application/json"},
)
else:
self._send(401, b"{}", {"Content-Type": "application/json"})
return

self._send(
200,
json.dumps({"version": "1.17.3", "uptime": 1}).encode(),
{"Content-Type": "application/json"},
)

def log_message(self, *args):
pass


@pytest.fixture
def server():
httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
httpd.received = {}
thread = threading.Thread(target=httpd.serve_forever, daemon=True)
thread.start()
try:
yield httpd
finally:
httpd.shutdown()
httpd.server_close()


@pytest.fixture
def api(server, monkeypatch):
for key in ("AYON_CA_FILE", "AYON_CERT_FILE"):
monkeypatch.delenv(key, raising=False)
port = server.server_address[1]
con = ServerAPI(
f"http://localhost:{port}", token=SERVICE_KEY, max_retries=0
)
yield con
con.close_session()


def _api_key_headers(headers):
return {
key.lower()
for key in headers
if key.lower() in ("x-api-key", "x-as-user")
}


def test_other_host_redirect_strips_api_key(server, api):
with api.as_username("artist"):
api.get("redirect/127.0.0.1/other")
assert _api_key_headers(server.received["other"]) == set()


def test_same_host_redirect_keeps_api_key(server, api):
with api.as_username("artist"):
api.get("redirect/localhost/same")
assert _api_key_headers(server.received["same"]) == {
"x-api-key", "x-as-user"
}


def test_download_redirect_strips_api_key(server, api, tmp_path):
with api.as_username("artist"):
api.download_file(
"redirect/127.0.0.1/download", str(tmp_path / "file.bin")
)
assert _api_key_headers(server.received["download"]) == set()
assert (tmp_path / "file.bin").read_bytes() == b"content"
5 changes: 3 additions & 2 deletions tests/test_token_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from ayon_api import GlobalServerAPI
from ayon_api.constants import SERVER_API_ENV_KEY, SERVER_URL_ENV_KEY
from ayon_api.exceptions import ServerNotReached
from ayon_api import server_api
from ayon_api.server_api import ServerAPI
from ayon_api.utils import get_user_info_by_token

Expand Down Expand Up @@ -87,7 +88,7 @@ def _fail_request(*args, **kwargs):
@pytest.fixture
def server(monkeypatch):
server = FakeServer(user_tokens=[USER_TOKEN], api_keys=[API_KEY])
monkeypatch.setattr(requests, "Session", server.create_session)
monkeypatch.setattr(server_api, "ServerSession", server.create_session)
monkeypatch.setattr(requests, "get", _fail_request)
return server

Expand Down Expand Up @@ -190,7 +191,7 @@ def test_availability_without_token(server):

def test_url_of_other_server_is_not_available(monkeypatch):
server = FakeServer(api_keys=[API_KEY], is_ayon=False)
monkeypatch.setattr(requests, "Session", server.create_session)
monkeypatch.setattr(server_api, "ServerSession", server.create_session)
monkeypatch.setattr(requests, "get", _fail_request)

with pytest.raises(ServerNotReached):
Expand Down
Loading