|
| 1 | +"""Raw paths must never move the request off the authenticated API origin (#102). |
| 2 | +
|
| 3 | +Every assertion here is made on what reaches the transport, not on an internal |
| 4 | +flag: an off-origin path must produce ZERO outbound requests, so the customer's |
| 5 | +API key is never attached to a host that is not OilPriceAPI. |
| 6 | +""" |
| 7 | + |
| 8 | +import asyncio |
| 9 | + |
| 10 | +import httpx |
| 11 | +import pytest |
| 12 | + |
| 13 | +from oilpriceapi import AsyncOilPriceAPI, OilPriceAPI |
| 14 | +from oilpriceapi.exceptions import OilPriceAPIError |
| 15 | + |
| 16 | +# Not a credential: a fixture string used only against a mock transport. |
| 17 | +FIXTURE_KEY = "-".join(["fixture", "not", "a", "real", "key"]) |
| 18 | + |
| 19 | +FOREIGN_HOST = "fixture.invalid" |
| 20 | + |
| 21 | +# Raw paths a caller could build from untrusted input. Each one either moves the |
| 22 | +# origin outright or is normalized into an origin change by some parser in the |
| 23 | +# chain (scheme-relative, userinfo authority, backslash, absolute URL). |
| 24 | +OFF_ORIGIN_PATHS = [ |
| 25 | + "//fixture.invalid/v1/prices/latest", |
| 26 | + "///fixture.invalid/v1/prices/latest", |
| 27 | + "//user@fixture.invalid/v1/prices/latest", |
| 28 | + "//fixture.invalid:8443/v1/prices/latest", |
| 29 | + "/\\fixture.invalid/v1/prices/latest", |
| 30 | + "\\\\fixture.invalid/v1/prices/latest", |
| 31 | + "https://fixture.invalid/v1/prices/latest", |
| 32 | + "http://fixture.invalid/v1/prices/latest", |
| 33 | + "/v1/prices\nHost: fixture.invalid", |
| 34 | +] |
| 35 | + |
| 36 | +ON_ORIGIN_PATHS = [ |
| 37 | + "/v1/prices/latest", |
| 38 | + "v1/prices/latest", |
| 39 | + "/v1/prices/past_week", |
| 40 | + "/v1/commodities/BRENT%20CRUDE/summary", |
| 41 | + "/v1/subscriptions/9f3c1a2b-0000-4000-8000-000000000000", |
| 42 | +] |
| 43 | + |
| 44 | + |
| 45 | +class _Recorder: |
| 46 | + """Mock transport that records every request that actually goes out.""" |
| 47 | + |
| 48 | + def __init__(self): |
| 49 | + self.requests = [] |
| 50 | + |
| 51 | + def __call__(self, request): |
| 52 | + self.requests.append(request) |
| 53 | + return httpx.Response(200, json={"status": "success", "data": {}}) |
| 54 | + |
| 55 | + @property |
| 56 | + def hosts(self): |
| 57 | + return [r.url.host for r in self.requests] |
| 58 | + |
| 59 | + @property |
| 60 | + def authenticated_foreign_requests(self): |
| 61 | + return [ |
| 62 | + r |
| 63 | + for r in self.requests |
| 64 | + if r.url.host != "api.oilpriceapi.com" |
| 65 | + and (r.headers.get("authorization") or r.headers.get("Authorization")) |
| 66 | + ] |
| 67 | + |
| 68 | + |
| 69 | +def _sync_client(recorder, **kwargs): |
| 70 | + client = OilPriceAPI(api_key=FIXTURE_KEY, **kwargs) |
| 71 | + client._client = httpx.Client( |
| 72 | + base_url=client.base_url, |
| 73 | + headers=client.headers, |
| 74 | + transport=httpx.MockTransport(recorder), |
| 75 | + ) |
| 76 | + return client |
| 77 | + |
| 78 | + |
| 79 | +def _async_client(recorder, **kwargs): |
| 80 | + client = AsyncOilPriceAPI(api_key=FIXTURE_KEY, **kwargs) |
| 81 | + client._client = httpx.AsyncClient( |
| 82 | + base_url=client.base_url, |
| 83 | + headers=client.headers, |
| 84 | + transport=httpx.MockTransport(recorder), |
| 85 | + ) |
| 86 | + return client |
| 87 | + |
| 88 | + |
| 89 | +@pytest.mark.parametrize("path", OFF_ORIGIN_PATHS) |
| 90 | +def test_sync_request_sends_nothing_for_off_origin_path(path): |
| 91 | + recorder = _Recorder() |
| 92 | + client = _sync_client(recorder) |
| 93 | + |
| 94 | + with pytest.raises(OilPriceAPIError): |
| 95 | + client.request("GET", path) |
| 96 | + |
| 97 | + assert recorder.requests == [], ( |
| 98 | + f"path {path!r} reached the wire at {recorder.hosts}" |
| 99 | + ) |
| 100 | + |
| 101 | + |
| 102 | +@pytest.mark.parametrize("path", OFF_ORIGIN_PATHS) |
| 103 | +def test_sync_request_with_headers_sends_nothing_for_off_origin_path(path): |
| 104 | + recorder = _Recorder() |
| 105 | + client = _sync_client(recorder) |
| 106 | + |
| 107 | + with pytest.raises(OilPriceAPIError): |
| 108 | + client.request_with_headers("GET", path) |
| 109 | + |
| 110 | + assert recorder.requests == [] |
| 111 | + |
| 112 | + |
| 113 | +@pytest.mark.parametrize("path", OFF_ORIGIN_PATHS) |
| 114 | +def test_async_request_sends_nothing_for_off_origin_path(path): |
| 115 | + recorder = _Recorder() |
| 116 | + |
| 117 | + async def scenario(): |
| 118 | + client = _async_client(recorder) |
| 119 | + with pytest.raises(OilPriceAPIError): |
| 120 | + await client.request("GET", path) |
| 121 | + await client._client.aclose() |
| 122 | + |
| 123 | + asyncio.run(scenario()) |
| 124 | + assert recorder.requests == [] |
| 125 | + |
| 126 | + |
| 127 | +def test_api_key_never_reaches_a_foreign_host(): |
| 128 | + """The property that actually matters: the key stays on our origin.""" |
| 129 | + recorder = _Recorder() |
| 130 | + client = _sync_client(recorder) |
| 131 | + |
| 132 | + for path in OFF_ORIGIN_PATHS: |
| 133 | + try: |
| 134 | + client.request("GET", path) |
| 135 | + except OilPriceAPIError: |
| 136 | + pass |
| 137 | + |
| 138 | + assert recorder.authenticated_foreign_requests == [] |
| 139 | + assert FOREIGN_HOST not in recorder.hosts |
| 140 | + |
| 141 | + |
| 142 | +@pytest.mark.parametrize("path", ON_ORIGIN_PATHS) |
| 143 | +def test_valid_paths_still_reach_the_api_origin(path): |
| 144 | + recorder = _Recorder() |
| 145 | + client = _sync_client(recorder) |
| 146 | + |
| 147 | + client.request("GET", path, params={"by_code": "BRENT_CRUDE_USD"}) |
| 148 | + |
| 149 | + assert len(recorder.requests) == 1 |
| 150 | + sent = recorder.requests[0] |
| 151 | + assert sent.url.host == "api.oilpriceapi.com" |
| 152 | + assert sent.url.scheme == "https" |
| 153 | + assert sent.url.params.get("by_code") == "BRENT_CRUDE_USD" |
| 154 | + assert sent.headers["Authorization"].endswith(FIXTURE_KEY) |
| 155 | + |
| 156 | + |
| 157 | +def test_explicit_custom_base_url_is_preserved(): |
| 158 | + """Proxies and test servers stay supported — the guard pins to the CONFIGURED origin.""" |
| 159 | + recorder = _Recorder() |
| 160 | + client = _sync_client(recorder, base_url="https://proxy.internal.example:8443/api") |
| 161 | + |
| 162 | + client.request("GET", "/v1/prices/latest") |
| 163 | + |
| 164 | + assert len(recorder.requests) == 1 |
| 165 | + sent = recorder.requests[0] |
| 166 | + assert sent.url.host == "proxy.internal.example" |
| 167 | + assert sent.url.port == 8443 |
| 168 | + |
| 169 | + |
| 170 | +def test_off_origin_path_is_still_rejected_under_a_custom_base_url(): |
| 171 | + recorder = _Recorder() |
| 172 | + client = _sync_client(recorder, base_url="https://proxy.internal.example:8443/api") |
| 173 | + |
| 174 | + with pytest.raises(OilPriceAPIError): |
| 175 | + client.request("GET", "//fixture.invalid/v1/prices/latest") |
| 176 | + |
| 177 | + assert recorder.requests == [] |
| 178 | + |
| 179 | + |
| 180 | +def test_non_string_path_is_rejected_before_any_request(): |
| 181 | + recorder = _Recorder() |
| 182 | + client = _sync_client(recorder) |
| 183 | + |
| 184 | + with pytest.raises(OilPriceAPIError): |
| 185 | + client.request("GET", None) |
| 186 | + |
| 187 | + assert recorder.requests == [] |
| 188 | + |
| 189 | + |
| 190 | +def test_rejection_message_does_not_leak_the_api_key(): |
| 191 | + recorder = _Recorder() |
| 192 | + client = _sync_client(recorder) |
| 193 | + |
| 194 | + with pytest.raises(OilPriceAPIError) as excinfo: |
| 195 | + client.request("GET", "//fixture.invalid/v1/prices/latest") |
| 196 | + |
| 197 | + assert FIXTURE_KEY not in str(excinfo.value) |
0 commit comments