csiapps 0.3.0__tar.gz → 0.3.2__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.
Files changed (62) hide show
  1. {csiapps-0.3.0 → csiapps-0.3.2}/PKG-INFO +3 -2
  2. {csiapps-0.3.0 → csiapps-0.3.2}/README.md +2 -1
  3. csiapps-0.3.2/dist-v0.3.1/.gitignore +1 -0
  4. csiapps-0.3.2/dist-v0.3.1/csiapps-0.3.1-py3-none-any.whl +0 -0
  5. csiapps-0.3.2/dist-v0.3.1/csiapps-0.3.1.tar.gz +0 -0
  6. csiapps-0.3.2/dist-v0.3.2/.gitignore +1 -0
  7. {csiapps-0.3.0 → csiapps-0.3.2}/pyproject.toml +1 -1
  8. {csiapps-0.3.0 → csiapps-0.3.2}/src/csiapps/__init__.py +1 -1
  9. {csiapps-0.3.0 → csiapps-0.3.2}/src/csiapps/chrome.py +6 -1
  10. {csiapps-0.3.0 → csiapps-0.3.2}/src/csiapps/config.py +4 -3
  11. {csiapps-0.3.0 → csiapps-0.3.2}/src/csiapps/dash.py +18 -18
  12. {csiapps-0.3.0 → csiapps-0.3.2}/tests/test_chrome.py +7 -2
  13. {csiapps-0.3.0 → csiapps-0.3.2}/tests/test_config.py +8 -0
  14. {csiapps-0.3.0 → csiapps-0.3.2}/tests/test_dash.py +82 -32
  15. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/launch.json +0 -0
  16. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/worktrees/awesome-cori-2da86f/.claude/launch.json +0 -0
  17. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/worktrees/awesome-cori-2da86f/.github/workflows/ci.yml +0 -0
  18. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/worktrees/awesome-cori-2da86f/.gitignore +0 -0
  19. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/worktrees/awesome-cori-2da86f/LICENSE +0 -0
  20. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/worktrees/awesome-cori-2da86f/README.md +0 -0
  21. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/worktrees/awesome-cori-2da86f/examples/app.py +0 -0
  22. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/worktrees/awesome-cori-2da86f/examples/dash_app.py +0 -0
  23. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/worktrees/awesome-cori-2da86f/examples/warehouse_ingest.py +0 -0
  24. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/worktrees/awesome-cori-2da86f/pyproject.toml +0 -0
  25. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/worktrees/awesome-cori-2da86f/src/csiapps/__init__.py +0 -0
  26. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/worktrees/awesome-cori-2da86f/src/csiapps/app.py +0 -0
  27. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/worktrees/awesome-cori-2da86f/src/csiapps/auth.py +0 -0
  28. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/worktrees/awesome-cori-2da86f/src/csiapps/chrome.py +0 -0
  29. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/worktrees/awesome-cori-2da86f/src/csiapps/client.py +0 -0
  30. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/worktrees/awesome-cori-2da86f/src/csiapps/config.py +0 -0
  31. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/worktrees/awesome-cori-2da86f/src/csiapps/dash.py +0 -0
  32. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/worktrees/awesome-cori-2da86f/src/csiapps/sandbox.py +0 -0
  33. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/worktrees/awesome-cori-2da86f/tests/conftest.py +0 -0
  34. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/worktrees/awesome-cori-2da86f/tests/test_app.py +0 -0
  35. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/worktrees/awesome-cori-2da86f/tests/test_auth.py +0 -0
  36. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/worktrees/awesome-cori-2da86f/tests/test_chrome.py +0 -0
  37. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/worktrees/awesome-cori-2da86f/tests/test_client.py +0 -0
  38. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/worktrees/awesome-cori-2da86f/tests/test_config.py +0 -0
  39. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/worktrees/awesome-cori-2da86f/tests/test_dash.py +0 -0
  40. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/worktrees/awesome-cori-2da86f/tests/test_packaging.py +0 -0
  41. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/worktrees/awesome-cori-2da86f/tests/test_sandbox.py +0 -0
  42. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/worktrees/awesome-cori-2da86f/tests/test_sandbox_registry.py +0 -0
  43. {csiapps-0.3.0 → csiapps-0.3.2}/.claude/worktrees/awesome-cori-2da86f/tests/test_token_resolution.py +0 -0
  44. {csiapps-0.3.0 → csiapps-0.3.2}/.github/workflows/ci.yml +0 -0
  45. {csiapps-0.3.0 → csiapps-0.3.2}/.gitignore +0 -0
  46. {csiapps-0.3.0 → csiapps-0.3.2}/CONTRIBUTING.md +0 -0
  47. {csiapps-0.3.0 → csiapps-0.3.2}/LICENSE +0 -0
  48. {csiapps-0.3.0 → csiapps-0.3.2}/examples/app.py +0 -0
  49. {csiapps-0.3.0 → csiapps-0.3.2}/examples/dash_app.py +0 -0
  50. {csiapps-0.3.0 → csiapps-0.3.2}/examples/warehouse_ingest.py +0 -0
  51. {csiapps-0.3.0 → csiapps-0.3.2}/src/csiapps/auth.py +0 -0
  52. {csiapps-0.3.0 → csiapps-0.3.2}/src/csiapps/client.py +0 -0
  53. {csiapps-0.3.0 → csiapps-0.3.2}/src/csiapps/sandbox.py +0 -0
  54. {csiapps-0.3.0 → csiapps-0.3.2}/src/csiapps/shiny.py +0 -0
  55. {csiapps-0.3.0 → csiapps-0.3.2}/tests/conftest.py +0 -0
  56. {csiapps-0.3.0 → csiapps-0.3.2}/tests/test_auth.py +0 -0
  57. {csiapps-0.3.0 → csiapps-0.3.2}/tests/test_client.py +0 -0
  58. {csiapps-0.3.0 → csiapps-0.3.2}/tests/test_packaging.py +0 -0
  59. {csiapps-0.3.0 → csiapps-0.3.2}/tests/test_sandbox.py +0 -0
  60. {csiapps-0.3.0 → csiapps-0.3.2}/tests/test_sandbox_registry.py +0 -0
  61. {csiapps-0.3.0 → csiapps-0.3.2}/tests/test_shiny.py +0 -0
  62. {csiapps-0.3.0 → csiapps-0.3.2}/tests/test_token_resolution.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: csiapps
3
- Version: 0.3.0
3
+ Version: 0.3.2
4
4
  Summary: Helper functions and utilities for CSI data warehouse ingestion and Shiny or Dash web applications (Python port of the csiapps R package).
5
5
  Project-URL: Homepage, https://github.com/CSIOntario/csiapps-py
6
6
  Project-URL: Issues, https://github.com/CSIOntario/csiapps-py/issues
@@ -145,7 +145,8 @@ def load(org): # no token handling; the helper resolves it
145
145
 
146
146
  In production set `CSIAPPS_CLIENT_ID`, `CSIAPPS_CLIENT_SECRET`,
147
147
  `CSIAPPS_REDIRECT_URI` (pointing at `/redirect`), and
148
- `CSIAPPS_SECRET_KEY` — a stable ≥32-character value that signs the session
148
+ `CSIAPPS_SECRET_KEY` — a stable ≥32-character value generated separately for
149
+ each deployed Dash app and shared by that app's workers. It signs the session
149
150
  cookie. `attach()` raises at startup if it is missing, since the alternative is
150
151
  an unexplained login loop.
151
152
 
@@ -104,7 +104,8 @@ def load(org): # no token handling; the helper resolves it
104
104
 
105
105
  In production set `CSIAPPS_CLIENT_ID`, `CSIAPPS_CLIENT_SECRET`,
106
106
  `CSIAPPS_REDIRECT_URI` (pointing at `/redirect`), and
107
- `CSIAPPS_SECRET_KEY` — a stable ≥32-character value that signs the session
107
+ `CSIAPPS_SECRET_KEY` — a stable ≥32-character value generated separately for
108
+ each deployed Dash app and shared by that app's workers. It signs the session
108
109
  cookie. `attach()` raises at startup if it is missing, since the alternative is
109
110
  an unexplained login loop.
110
111
 
@@ -0,0 +1 @@
1
+ *
@@ -0,0 +1 @@
1
+ *
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "csiapps"
3
- version = "0.3.0"
3
+ version = "0.3.2"
4
4
  description = "Helper functions and utilities for CSI data warehouse ingestion and Shiny or Dash web applications (Python port of the csiapps R package)."
5
5
  readme = "README.md"
6
6
  license = { file = "LICENSE" }
@@ -38,7 +38,7 @@ from .sandbox import (
38
38
  register_sandbox_schema,
39
39
  )
40
40
 
41
- __version__ = "0.3.0"
41
+ __version__ = "0.3.2"
42
42
 
43
43
  __all__ = [
44
44
  "__version__",
@@ -68,8 +68,13 @@ UNAUTHENTICATED_TEXT = (
68
68
  _LOGOS = {
69
69
  "csipacific": "https://www.csipacific.ca/wp-content/uploads/2024/05/csi-pacific-logo-main.png",
70
70
  "csiontario": "https://csiontario.ca/wp-content/uploads/2022/03/logo-csi-ontario.png",
71
+ "csiatlantic": "https://www.csiatlantic.ca/sites/default/files/logo-institute.png",
72
+ }
73
+ _DISPLAY_NAMES = {
74
+ "csipacific": "CSI Pacific",
75
+ "csiontario": "CSI Ontario",
76
+ "csiatlantic": "CSI Atlantic",
71
77
  }
72
- _DISPLAY_NAMES = {"csipacific": "CSI Pacific", "csiontario": "CSI Ontario"}
73
78
 
74
79
  LOGO_HEIGHT = "48px"
75
80
 
@@ -16,7 +16,7 @@ import sys
16
16
  SPORT_ORG_ENDPOINT = "/api/registration/organization/"
17
17
  PROFILE_ENDPOINT = "/api/registration/profile/"
18
18
 
19
- _VALID_INSTITUTES = ("csipacific", "csiontario")
19
+ _VALID_INSTITUTES = ("csipacific", "csiontario", "csiatlantic")
20
20
 
21
21
 
22
22
  def _message(text: str) -> None:
@@ -42,10 +42,11 @@ def set_institute(institute: str = "csipacific") -> None:
42
42
 
43
43
  Args:
44
44
  institute: Which CSI institute to target. Must be one of
45
- ``"csipacific"`` or ``"csiontario"``. Defaults to ``"csipacific"``.
45
+ ``"csipacific"``, ``"csiontario"``, or ``"csiatlantic"``.
46
+ Defaults to ``"csipacific"``.
46
47
 
47
48
  Raises:
48
- ValueError: If ``institute`` is not one of the two supported values.
49
+ ValueError: If ``institute`` is not one of the supported values.
49
50
 
50
51
  Example:
51
52
  ```python
@@ -30,6 +30,7 @@ PKCE helpers — is framework-independent and used unchanged.
30
30
  """
31
31
 
32
32
  import os
33
+ import secrets
33
34
  import warnings
34
35
  from collections.abc import Callable
35
36
  from urllib.parse import urlencode
@@ -65,10 +66,11 @@ CSS_ROUTE = f"{AUTH_PREFIX}/chrome.css"
65
66
 
66
67
  # Flask session keys. The token key is defined here (this module owns the Flask
67
68
  # side of token storage) and read back through the adapter below.
68
- FLASK_TOKEN_KEY = "csi_token"
69
- TOKEN_KEY = FLASK_TOKEN_KEY
69
+ TOKEN_KEY = "csi_token"
70
70
  USER_KEY = "csi_user"
71
71
  NEXT_KEY = "csi_next"
72
+ STATE_KEY = "csi_oauth_state"
73
+ VERIFIER_KEY = "csi_pkce_verifier"
72
74
 
73
75
 
74
76
  class _FlaskTokenAdapter:
@@ -84,7 +86,7 @@ class _FlaskTokenAdapter:
84
86
  if not has_request_context():
85
87
  return None
86
88
  try:
87
- return session.get(FLASK_TOKEN_KEY) or None
89
+ return session.get(TOKEN_KEY) or None
88
90
  except Exception:
89
91
  # An unreadable/tampered session cookie must not take the app down;
90
92
  # fall through to the env var and the normal unauthenticated gate.
@@ -209,6 +211,9 @@ class _CsiAuth(_DashAuth):
209
211
  # Remember where the user was headed so the redirect route can return
210
212
  # them there instead of dumping everyone on "/".
211
213
  session[NEXT_KEY] = request.full_path
214
+ state = secrets.token_urlsafe(32)
215
+ session[STATE_KEY] = state
216
+ session[VERIFIER_KEY] = pkce["verifier"]
212
217
  params = {
213
218
  "response_type": "code",
214
219
  "client_id": os.environ.get("CSIAPPS_CLIENT_ID", ""),
@@ -216,7 +221,7 @@ class _CsiAuth(_DashAuth):
216
221
  "scope": os.environ.get("CSIAPPS_SCOPE", "read write"),
217
222
  "code_challenge": pkce["challenge"],
218
223
  "code_challenge_method": pkce["method"],
219
- "state": auth.pkce_state_encode(pkce["verifier"]),
224
+ "state": state,
220
225
  }
221
226
  return redirect(config.auth_url() + "?" + urlencode(params))
222
227
 
@@ -235,26 +240,21 @@ def _register_css_route(server):
235
240
  def _register_auth_routes(server):
236
241
  @server.route(REDIRECT_ROUTE)
237
242
  def _csiapps_oauth_redirect():
238
- if request.args.get("error"):
243
+ code = request.args.get("code")
244
+ if request.args.get("error") or not code:
239
245
  session.clear()
240
246
  return redirect("/")
241
247
 
242
- code = request.args.get("code")
243
- if not code:
248
+ state = request.args.get("state", "")
249
+ expected_state = session.pop(STATE_KEY, "")
250
+ verifier = session.pop(VERIFIER_KEY, "")
251
+ if not (state and expected_state and verifier
252
+ and secrets.compare_digest(state, expected_state)):
253
+ # Reject callbacks not initiated by this browser session, including
254
+ # mismatches and replays, before sending anything to the token endpoint.
244
255
  session.clear()
245
256
  return redirect("/")
246
257
 
247
- state = request.args.get("state")
248
- verifier = None
249
- if state:
250
- try:
251
- verifier = auth.pkce_state_decode(state).get("v")
252
- except Exception:
253
- # A malformed/tampered state is not a crash: drop the session and
254
- # restart the flow from the guard.
255
- session.clear()
256
- return redirect("/")
257
-
258
258
  token = auth.exchange_code_for_token(code, verifier)
259
259
  access_token = token.get("access_token") if isinstance(token, dict) else None
260
260
  if not access_token:
@@ -21,12 +21,14 @@ def test_logo_follows_the_institute():
21
21
  assert "csi-pacific-logo" in chrome.logo_src()
22
22
  set_institute("csiontario")
23
23
  assert "logo-csi-ontario" in chrome.logo_src()
24
+ set_institute("csiatlantic")
25
+ assert "logo-institute.png" in chrome.logo_src()
24
26
 
25
27
 
26
28
  def test_logo_is_always_a_public_https_url():
27
29
  # Apps stop vendoring csi-pacific-logo-reverse.png and stop patching
28
30
  # server.static_folder; that only works if this is never a local path.
29
- for institute in ("csipacific", "csiontario"):
31
+ for institute in ("csipacific", "csiontario", "csiatlantic"):
30
32
  set_institute(institute)
31
33
  assert chrome.logo_src().startswith("https://")
32
34
 
@@ -37,6 +39,9 @@ def test_institute_name_and_footer():
37
39
  assert chrome.footer_text() == f"© {date.today().year} CSI Pacific"
38
40
  set_institute("csiontario")
39
41
  assert chrome.institute_name() == "CSI Ontario"
42
+ set_institute("csiatlantic")
43
+ assert chrome.institute_name() == "CSI Atlantic"
44
+ assert chrome.footer_text() == f"© {date.today().year} CSI Atlantic"
40
45
 
41
46
 
42
47
  @pytest.mark.parametrize(
@@ -100,7 +105,7 @@ def render_dash(**kwargs):
100
105
 
101
106
 
102
107
  def test_both_frameworks_use_the_same_logo():
103
- for institute in ("csipacific", "csiontario"):
108
+ for institute in ("csipacific", "csiontario", "csiatlantic"):
104
109
  set_institute(institute)
105
110
  assert chrome.logo_src() in str(ui_wrapper(sandbox=True))
106
111
  assert chrome.logo_src() in render_dash(sandbox=True)
@@ -55,6 +55,14 @@ def test_set_institute_valid_and_urls():
55
55
  assert config.userinfo_url() == "https://apps.csiontario.ca/api/csiauth/me/"
56
56
 
57
57
 
58
+ def test_set_institute_accepts_atlantic_and_builds_urls():
59
+ set_institute("csiatlantic")
60
+ assert config.site_url() == "https://apps.csiatlantic.ca"
61
+ assert config.auth_url() == "https://apps.csiatlantic.ca/o/authorize/"
62
+ assert config.token_url() == "https://apps.csiatlantic.ca/o/token/"
63
+ assert config.userinfo_url() == "https://apps.csiatlantic.ca/api/csiauth/me/"
64
+
65
+
58
66
  def test_set_institute_rejects_unknown():
59
67
  with pytest.raises(ValueError):
60
68
  set_institute("csiquebec")
@@ -8,6 +8,7 @@ with no credentials and no network.
8
8
  """
9
9
 
10
10
  import json
11
+ from urllib.parse import parse_qs, urlparse
11
12
 
12
13
  import httpx
13
14
  import pytest
@@ -49,6 +50,12 @@ def render(**kwargs):
49
50
  return str(csidash.layout_wrapper(**kwargs)())
50
51
 
51
52
 
53
+ def begin_login(client_, path="/"):
54
+ """Start the guarded login flow and return its session-bound OAuth state."""
55
+ resp = client_.get(path)
56
+ return parse_qs(urlparse(resp.headers["Location"]).query)["state"][0]
57
+
58
+
52
59
  # ---- attach: mode selection --------------------------------------------
53
60
 
54
61
 
@@ -100,8 +107,6 @@ def test_public_routes_bypass_the_guard(prod_env):
100
107
 
101
108
  def test_login_redirect_carries_pkce_and_client_config(prod_env):
102
109
  resp = make_app(sandbox=False).server.test_client().get("/")
103
- from urllib.parse import parse_qs, urlparse
104
-
105
110
  params = parse_qs(urlparse(resp.headers["Location"]).query)
106
111
  assert params["response_type"] == ["code"]
107
112
  assert params["client_id"] == ["test-client"]
@@ -111,23 +116,23 @@ def test_login_redirect_carries_pkce_and_client_config(prod_env):
111
116
  assert params["scope"] == ["read write"]
112
117
 
113
118
 
114
- def test_login_state_round_trips_to_the_verifier(prod_env):
115
- # The whole point of PKCE: the verifier the token exchange will send must be
116
- # recoverable from the state we put on the wire, and must match the
117
- # challenge. A silent break here yields "invalid_grant" only in production.
119
+ def test_login_state_and_verifier_are_bound_to_the_session(prod_env):
118
120
  import base64
119
121
  import hashlib
120
- from urllib.parse import parse_qs, urlparse
121
122
 
122
- resp = make_app(sandbox=False).server.test_client().get("/")
123
- params = parse_qs(urlparse(resp.headers["Location"]).query)
124
- verifier = auth.pkce_state_decode(params["state"][0])["v"]
125
- expected = (
126
- base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest())
127
- .rstrip(b"=")
128
- .decode()
129
- )
130
- assert params["code_challenge"][0] == expected
123
+ app = make_app(sandbox=False)
124
+ with app.server.test_client() as c:
125
+ resp = c.get("/")
126
+ params = parse_qs(urlparse(resp.headers["Location"]).query)
127
+ state = params["state"][0]
128
+ verifier = flask.session[csidash.VERIFIER_KEY]
129
+ assert flask.session[csidash.STATE_KEY] == state
130
+ expected = (
131
+ base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest())
132
+ .rstrip(b"=")
133
+ .decode()
134
+ )
135
+ assert params["code_challenge"][0] == expected
131
136
 
132
137
 
133
138
  def test_login_redirect_remembers_where_the_user_was_going(prod_env):
@@ -265,8 +270,8 @@ def logged_in(monkeypatch, prod_env):
265
270
 
266
271
  def test_callback_stores_token_and_user(logged_in):
267
272
  app = logged_in()
268
- state = auth.pkce_state_encode("verifier-123")
269
273
  with app.server.test_client() as c:
274
+ state = begin_login(c)
270
275
  resp = c.get(f"/redirect?code=abc&state={state}")
271
276
  assert resp.status_code == 302
272
277
  assert flask.session[csidash.TOKEN_KEY] == "granted-tok"
@@ -283,33 +288,36 @@ def test_callback_passes_the_verifier_to_the_exchange(monkeypatch, prod_env):
283
288
  )
284
289
  monkeypatch.setattr(csidash, "_load_userinfo", lambda tok: None)
285
290
  app = make_app(sandbox=False)
286
- state = auth.pkce_state_encode("verifier-xyz")
287
- app.server.test_client().get(f"/redirect?code=thecode&state={state}")
288
- assert seen == {"code": "thecode", "verifier": "verifier-xyz"}
291
+ with app.server.test_client() as c:
292
+ state = begin_login(c)
293
+ verifier = flask.session[csidash.VERIFIER_KEY]
294
+ c.get(f"/redirect?code=thecode&state={state}")
295
+ assert seen == {"code": "thecode", "verifier": verifier}
289
296
 
290
297
 
291
298
  def test_callback_returns_the_user_to_their_original_page(logged_in):
292
299
  app = logged_in()
293
300
  with app.server.test_client() as c:
294
- c.get("/reports?year=2026") # guard stores csi_next
295
- state = auth.pkce_state_encode("v")
301
+ state = begin_login(c, "/reports?year=2026")
296
302
  resp = c.get(f"/redirect?code=abc&state={state}")
297
303
  assert resp.headers["Location"].startswith("/reports")
298
304
 
299
305
 
300
306
  def test_callback_defaults_to_root_without_a_stored_next(logged_in):
301
307
  app = logged_in()
302
- state = auth.pkce_state_encode("v")
303
- resp = app.server.test_client().get(f"/redirect?code=abc&state={state}")
304
- assert resp.headers["Location"] == "/"
308
+ with app.server.test_client() as c:
309
+ state = begin_login(c)
310
+ flask.session.pop(csidash.NEXT_KEY)
311
+ resp = c.get(f"/redirect?code=abc&state={state}")
312
+ assert resp.headers["Location"] == "/"
305
313
 
306
314
 
307
315
  def test_callback_survives_a_failed_userinfo(logged_in):
308
316
  # A stale or scope-limited token must still log the user in; only the name
309
317
  # is lost. Mirrors server_wrapper's degrade-gracefully behaviour.
310
318
  app = logged_in(userinfo=None)
311
- state = auth.pkce_state_encode("v")
312
319
  with app.server.test_client() as c:
320
+ state = begin_login(c)
313
321
  c.get(f"/redirect?code=abc&state={state}")
314
322
  assert flask.session[csidash.TOKEN_KEY] == "granted-tok"
315
323
  assert csidash.USER_KEY not in flask.session
@@ -320,8 +328,6 @@ def test_callback_survives_a_failed_userinfo(logged_in):
320
328
  [
321
329
  ("error=access_denied", "provider returned an error"),
322
330
  ("", "no code at all"),
323
- ("code=abc&state=!!!not-base64!!!", "malformed state"),
324
- ("code=abc&state=" + auth.pkce_state_encode("v"), "exchange failed"),
325
331
  ],
326
332
  )
327
333
  def test_callback_failure_modes_do_not_500(monkeypatch, prod_env, query, label):
@@ -333,16 +339,60 @@ def test_callback_failure_modes_do_not_500(monkeypatch, prod_env, query, label):
333
339
  monkeypatch.setattr(csidash, "_load_userinfo", lambda tok: None)
334
340
  app = make_app(sandbox=False)
335
341
  with app.server.test_client() as c:
342
+ begin_login(c)
336
343
  resp = c.get(f"/redirect?{query}")
337
344
  assert resp.status_code == 302, label
338
345
  assert resp.headers["Location"] == "/", label
339
346
  assert csidash.TOKEN_KEY not in flask.session, label
340
347
 
341
348
 
349
+ def test_callback_rejects_missing_mismatched_or_replayed_state(monkeypatch, prod_env):
350
+ exchanges = []
351
+ monkeypatch.setattr(
352
+ auth,
353
+ "exchange_code_for_token",
354
+ lambda code, verifier=None: exchanges.append((code, verifier))
355
+ or {"access_token": "granted-tok"},
356
+ )
357
+ monkeypatch.setattr(csidash, "_load_userinfo", lambda tok: None)
358
+ app = make_app(sandbox=False)
359
+
360
+ with app.server.test_client() as c:
361
+ state = begin_login(c)
362
+ resp = c.get("/redirect?code=abc")
363
+ assert resp.status_code == 302
364
+ assert exchanges == []
365
+
366
+ state = begin_login(c)
367
+ resp = c.get("/redirect?code=abc&state=wrong")
368
+ assert resp.status_code == 302
369
+ assert exchanges == []
370
+
371
+ state = begin_login(c)
372
+ c.get(f"/redirect?code=abc&state={state}")
373
+ assert len(exchanges) == 1
374
+ c.get(f"/redirect?code=abc&state={state}")
375
+ assert len(exchanges) == 1
376
+ assert csidash.TOKEN_KEY not in flask.session
377
+
378
+
379
+ def test_callback_survives_a_failed_exchange(monkeypatch, prod_env):
380
+ monkeypatch.setattr(
381
+ auth, "exchange_code_for_token", lambda code, verifier=None: {"error": "invalid_grant"}
382
+ )
383
+ app = make_app(sandbox=False)
384
+ with app.server.test_client() as c:
385
+ state = begin_login(c)
386
+ resp = c.get(f"/redirect?code=abc&state={state}")
387
+ assert resp.status_code == 302
388
+ assert resp.headers["Location"] == "/"
389
+ assert csidash.TOKEN_KEY not in flask.session
390
+
391
+
342
392
  def test_logout_clears_the_session(logged_in):
343
393
  app = logged_in()
344
- state = auth.pkce_state_encode("v")
345
394
  with app.server.test_client() as c:
395
+ state = begin_login(c)
346
396
  c.get(f"/redirect?code=abc&state={state}")
347
397
  assert csidash.TOKEN_KEY in flask.session
348
398
  resp = c.get("/csi-auth/logout")
@@ -353,16 +403,16 @@ def test_logout_clears_the_session(logged_in):
353
403
 
354
404
  def test_authenticated_user_reaches_the_app(logged_in):
355
405
  app = logged_in()
356
- state = auth.pkce_state_encode("v")
357
406
  with app.server.test_client() as c:
407
+ state = begin_login(c)
358
408
  c.get(f"/redirect?code=abc&state={state}")
359
409
  assert c.get("/").status_code == 200 # guard now lets them through
360
410
 
361
411
 
362
412
  def test_logout_then_guard_bounces_again(logged_in):
363
413
  app = logged_in()
364
- state = auth.pkce_state_encode("v")
365
414
  with app.server.test_client() as c:
415
+ state = begin_login(c)
366
416
  c.get(f"/redirect?code=abc&state={state}")
367
417
  c.get("/csi-auth/logout")
368
418
  assert c.get("/").status_code == 302
@@ -480,8 +530,8 @@ def test_auth_status_signed_in_with_a_dev_token(monkeypatch):
480
530
 
481
531
  def test_auth_status_names_the_user_from_the_session(logged_in):
482
532
  app = logged_in()
483
- state = auth.pkce_state_encode("v")
484
533
  with app.server.test_client() as c:
534
+ state = begin_login(c)
485
535
  c.get(f"/redirect?code=abc&state={state}")
486
536
  # Inside the request context the layout sees the stored /me payload.
487
537
  assert "Signed in as Ada Lovelace" in str(csidash.layout_wrapper(sandbox=False)())
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes