tinyercot 0.2.2__tar.gz → 0.2.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tinyercot
3
- Version: 0.2.2
3
+ Version: 0.2.3
4
4
  Summary: Tiny fully-typed ERCOT API
5
5
  Author-email: Kevin Kenyon <kevin@poweredbylight.com>
6
6
  License-Expression: MIT
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "tinyercot"
3
- version = "0.2.2"
3
+ version = "0.2.3"
4
4
  description = "Tiny fully-typed ERCOT API"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -0,0 +1,157 @@
1
+ import asyncio
2
+ import logging
3
+ import unittest
4
+ from urllib.parse import parse_qs
5
+
6
+ import httpx
7
+
8
+ import tinyercot
9
+ from tinyercot import _client
10
+
11
+
12
+ class TestAuthFormBody(unittest.TestCase):
13
+ def setUp(self) -> None:
14
+ self._orig_client = _client._client
15
+ self._orig_async_client = _client._async_client
16
+ _client.configure(username=None, password=None, subscription_key=None)
17
+
18
+ def tearDown(self) -> None:
19
+ _client._client = self._orig_client
20
+ _client._async_client = self._orig_async_client
21
+ _client.configure(username=None, password=None, subscription_key=None)
22
+
23
+ def test_token_sends_credentials_in_form_body_not_url_or_httpx_logs(self) -> None:
24
+ captured: list[httpx.Request] = []
25
+ secret_user = "alice+ercot@example.com"
26
+ secret_pass = "p@ss&w0rd#100%+secret"
27
+
28
+ def handler(request: httpx.Request) -> httpx.Response:
29
+ captured.append(request)
30
+ return httpx.Response(200, json={"id_token": "tok-abc"})
31
+
32
+ _client._client = httpx.Client(transport=httpx.MockTransport(handler))
33
+ tinyercot.configure(
34
+ username=secret_user,
35
+ password=secret_pass,
36
+ subscription_key="sub-key-secret",
37
+ )
38
+
39
+ with self.assertLogs("httpx", level=logging.INFO) as logs:
40
+ token = _client._token()
41
+
42
+ self.assertEqual(token, "tok-abc")
43
+ self.assertEqual(len(captured), 1)
44
+ req = captured[0]
45
+
46
+ # URL must have no query string or credentials
47
+ self.assertEqual(req.method, "POST")
48
+ self.assertEqual(str(req.url), _client.TOKEN_URL)
49
+ self.assertEqual(req.url.query, b"")
50
+ self.assertNotIn(secret_user, str(req.url))
51
+ self.assertNotIn(secret_pass, str(req.url))
52
+
53
+ # Body must be application/x-www-form-urlencoded with expected OAuth2 ROPC fields
54
+ self.assertEqual(
55
+ req.headers["content-type"], "application/x-www-form-urlencoded"
56
+ )
57
+ form = parse_qs(req.content.decode("utf-8"), strict_parsing=True)
58
+ self.assertEqual(
59
+ form,
60
+ {
61
+ "username": [secret_user],
62
+ "password": [secret_pass],
63
+ "grant_type": ["password"],
64
+ "scope": [f"openid {_client.CLIENT_ID} offline_access"],
65
+ "client_id": [_client.CLIENT_ID],
66
+ "response_type": ["id_token"],
67
+ },
68
+ )
69
+
70
+ # httpx logs must not leak username, password, or subscription key
71
+ combined_logs = "\n".join(logs.output)
72
+ self.assertIn(_client.TOKEN_URL, combined_logs)
73
+ self.assertNotIn(secret_user, combined_logs)
74
+ self.assertNotIn(secret_pass, combined_logs)
75
+ self.assertNotIn("sub-key-secret", combined_logs)
76
+
77
+ def test_token_http_error_raises_without_leaking_credentials_or_caching_none(
78
+ self,
79
+ ) -> None:
80
+ secret_user = "bob@example.com"
81
+ secret_pass = "super-secret-password"
82
+ calls = 0
83
+
84
+ def handler(request: httpx.Request) -> httpx.Response:
85
+ nonlocal calls
86
+ calls += 1
87
+ return httpx.Response(400, json={"error": "invalid_grant"})
88
+
89
+ _client._client = httpx.Client(transport=httpx.MockTransport(handler))
90
+ tinyercot.configure(
91
+ username=secret_user,
92
+ password=secret_pass,
93
+ subscription_key="sub-key",
94
+ )
95
+
96
+ with self.assertRaises(httpx.HTTPStatusError) as ctx:
97
+ _client._token()
98
+
99
+ err_text = str(ctx.exception)
100
+ self.assertNotIn(secret_user, err_text)
101
+ self.assertNotIn(secret_pass, err_text)
102
+ self.assertEqual(len(_client._tok_cache), 0)
103
+ self.assertEqual(calls, 1)
104
+
105
+ def test_get_and_aget_send_auth_in_headers_only(self) -> None:
106
+ requests_seen: list[httpx.Request] = []
107
+
108
+ def handler(request: httpx.Request) -> httpx.Response:
109
+ requests_seen.append(request)
110
+ if request.url.host == "ercotb2c.b2clogin.com":
111
+ return httpx.Response(200, json={"id_token": "jwt-token-123"})
112
+ return httpx.Response(200, json={"data": [["HB_HOUSTON", 42.5]]})
113
+
114
+ _client._client = httpx.Client(transport=httpx.MockTransport(handler))
115
+ _client._async_client = httpx.AsyncClient(
116
+ transport=httpx.MockTransport(handler)
117
+ )
118
+ tinyercot.configure(
119
+ username="u@example.com",
120
+ password="p-secret",
121
+ subscription_key="sub-secret",
122
+ )
123
+
124
+ sync_resp = _client._get(
125
+ "np4-190-cd/dam_stlmnt_pnt_prices",
126
+ schema={"settlementPoint": "VARCHAR", "price": "DOUBLE"},
127
+ settlementPoint="HB_HOUSTON",
128
+ )
129
+ async_resp = asyncio.run(
130
+ _client._aget(
131
+ "np4-190-cd/dam_stlmnt_pnt_prices",
132
+ schema={"settlementPoint": "VARCHAR", "price": "DOUBLE"},
133
+ settlementPoint="HB_HOUSTON",
134
+ )
135
+ )
136
+
137
+ self.assertEqual(
138
+ sync_resp["data"], [{"settlementPoint": "HB_HOUSTON", "price": 42.5}]
139
+ )
140
+ self.assertEqual(async_resp["data"], sync_resp["data"])
141
+
142
+ # Token fetched once (cached), followed by sync GET and async GET
143
+ self.assertEqual(len(requests_seen), 3)
144
+ for req in requests_seen:
145
+ url_str = str(req.url)
146
+ self.assertNotIn("u@example.com", url_str)
147
+ self.assertNotIn("p-secret", url_str)
148
+ self.assertNotIn("sub-secret", url_str)
149
+ self.assertNotIn("jwt-token-123", url_str)
150
+
151
+ for api_req in requests_seen[1:]:
152
+ self.assertEqual(api_req.headers["authorization"], "Bearer jwt-token-123")
153
+ self.assertEqual(api_req.headers["ocp-apim-subscription-key"], "sub-secret")
154
+
155
+
156
+ if __name__ == "__main__":
157
+ unittest.main()
@@ -11,8 +11,12 @@ from pydantic import BaseModel, ConfigDict, Field
11
11
  T = TypeVar("T", bound=BaseModel)
12
12
 
13
13
  BASE_URL = "https://api.ercot.com/api/public-reports"
14
+ TOKEN_URL = (
15
+ "https://ercotb2c.b2clogin.com/ercotb2c.onmicrosoft.com/"
16
+ "B2C_1_PUBAPI-ROPC-FLOW/oauth2/v2.0/token"
17
+ )
14
18
  CLIENT_ID = "fec253ea-0d06-4272-a5e6-b478baeecd70"
15
- SCOPE = f"openid+{CLIENT_ID}+offline_access"
19
+ SCOPE = f"openid {CLIENT_ID} offline_access"
16
20
 
17
21
  _username: str | None = None
18
22
  _password: str | None = None
@@ -52,15 +56,6 @@ def _resolve_creds() -> tuple[str, str, str]:
52
56
  return username, password, sub_key
53
57
 
54
58
 
55
- def _auth_url() -> str:
56
- username, password, _ = _resolve_creds()
57
- return (
58
- f"https://ercotb2c.b2clogin.com/ercotb2c.onmicrosoft.com/"
59
- f"B2C_1_PUBAPI-ROPC-FLOW/oauth2/v2.0/token"
60
- f"?username={username}&password={password}"
61
- f"&grant_type=password&scope={SCOPE}&client_id={CLIENT_ID}&response_type=id_token"
62
- )
63
-
64
59
  _rate_limiter = AsyncLimiter(20, 60)
65
60
  _async_client: httpx.AsyncClient | None = None
66
61
 
@@ -77,7 +72,20 @@ def _get_async_client() -> httpx.AsyncClient:
77
72
 
78
73
  @cached(_tok_cache)
79
74
  def _token() -> str:
80
- return _client.post(_auth_url()).json().get("id_token")
75
+ username, password, _ = _resolve_creds()
76
+ response = _client.post(
77
+ TOKEN_URL,
78
+ data={
79
+ "username": username,
80
+ "password": password,
81
+ "grant_type": "password",
82
+ "scope": SCOPE,
83
+ "client_id": CLIENT_ID,
84
+ "response_type": "id_token",
85
+ },
86
+ )
87
+ response.raise_for_status()
88
+ return response.json().get("id_token")
81
89
 
82
90
 
83
91
  def _get(path: str, schema: dict | None = None, **params) -> dict: # pyright: ignore
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tinyercot
3
- Version: 0.2.2
3
+ Version: 0.2.3
4
4
  Summary: Tiny fully-typed ERCOT API
5
5
  Author-email: Kevin Kenyon <kevin@poweredbylight.com>
6
6
  License-Expression: MIT
@@ -1,5 +1,6 @@
1
1
  README.md
2
2
  pyproject.toml
3
+ tests/test_auth.py
3
4
  tinyercot/__init__.py
4
5
  tinyercot/_client.py
5
6
  tinyercot/_generated.py
File without changes
File without changes