fix(auth): use CHAINLIT_ROOT_PATH value as cookie path; constant-time OAuth state check
Summary
Two bugs in backend/chainlit/auth/cookie.py.
Bug 1 — Cookie path always "/" when CHAINLIT_ROOT_PATH is set
Root cause: Module-level initialisation used the value of CHAINLIT_ROOT_PATH as an environment variable key:
# Before (buggy)
if _cookie_root_path := os.environ.get("CHAINLIT_ROOT_PATH", None):
_cookie_path = os.environ.get(_cookie_root_path, "/")
# ^^^^^^^^^^^^^^^^
# This treats the value (e.g. "/myapp") as a key into os.environ,
# which always returns the default "/" since "/myapp" is not a valid
# env var name.
Impact: set_auth_cookie and clear_auth_cookie delete stale cookie chunks using path=_cookie_path. When an app is deployed under a sub-path and CHAINLIT_ROOT_PATH is configured, the path used for deletion is "/" instead of the intended path, so old chunks are never cleared after logout or token rotation.
Fix:
if _cookie_root_path := os.environ.get("CHAINLIT_ROOT_PATH", None):
_cookie_path = _cookie_root_path # use the value directly
Bug 2 — Non-constant-time OAuth state comparison
validate_oauth_state_cookie used a regular != comparison:
# Before
if oauth_state != state:
raise Exception("oauth state does not correspond")
String equality (!=) is not constant-time and can leak information about the expected state value through timing side-channels. While network jitter limits practical exploitability, the fix is trivial: use hmac.compare_digest, which is the standard Python idiom for comparing secrets. An explicit None guard was also added so a missing cookie is rejected before the digest call.
# After
if oauth_state is None or not hmac.compare_digest(oauth_state, state):
raise Exception("oauth state does not correspond")
Tests
Three new tests in tests/auth/test_cookie.py:
| Test | Covers |
|---|---|
test_cookie_path_uses_chainlit_root_path_value | Bug 1: _cookie_path equals CHAINLIT_ROOT_PATH value after reload |
test_validate_oauth_state_cookie_rejects_missing_state | Bug 2: absent state cookie raises exception |
test_validate_oauth_state_cookie_accepts_correct_state | Bug 2: matching state does not raise |
Summary by cubic
Sets auth cookies at the deployment sub-path by using the CHAINLIT_ROOT_PATH value as the cookie path. Also switches OAuth state checks to constant-time and rejects requests with a missing state cookie.
- Bug Fixes
- Pass path=_cookie_path to all auth set_cookie calls so creation and deletion hit the same path and stale chunks are cleared on logout/rotation.
- Compare OAuth state with hmac.compare_digest and raise when the oauth_state cookie is absent.