Repository navigation
fix(auth): extend Keycloak session lifetimes for long-running clusters - #1077
Conversation
Alan-Cha
left a comment
There was a problem hiding this comment.
This PR addresses a real pain point (Keycloak session expiration on dev clusters) with a well-thought-out solution. The configurable Helm values and realm update logic are solid architectural choices. However, there are 4 must-fix issues that block merge:
- CodeQL security alert (HIGH) - Certificate validation disabled in test
- Race condition in agent-oauth-secret realm update logic
- Race condition in ui-oauth-secret realm update logic
- Missing emoji prefix in commit message
The "Deploy & Test" CI failure (PostgreSQL duplicate key) is likely related to issues #2-3. The realm update logic needs to be idempotent and handle concurrent execution.
Inline Comments
Must-Fix Issues
1. test_keycloak_session_lifetimes.py:206 - CodeQL HIGH Security Alert: Setting verify_ssl = False disables certificate validation. This is flagged as a security vulnerability. Consider: (1) Always use verify=True and rely on the trusted CA bundle, (2) Use a more restrictive condition, or (3) Add a CodeQL suppression comment with justification.
2. agent_oauth_secret.py:99 - Race condition risk: The update_realm() call in the 409 path could be invoked by multiple job pods simultaneously if backoffLimit > 1. The "Deploy & Test" CI failure shows a PostgreSQL duplicate key error which may be related. Consider adding version checks or optimistic locking.
3. auth_secret.py:154 - Same race condition as agent_oauth_secret.py. The realm check and update are not atomic. If two job pods run concurrently, both could attempt to update the realm simultaneously.
4. Commit message - Missing emoji prefix per git:commit conventions (should be 🔧 or 🐛).
Suggestions
5. agent_oauth_secret.py:67-70 - Consider extracting session lifetime env var reads into a shared helper function to reduce duplication between agent_oauth_secret.py and auth_secret.py.
6. values.yaml:42-55 - Consider adding a stronger warning about security implications of 30-day sessions in production environments.
Praise
7. test_keycloak_session_lifetimes.py:225-243 - Excellent test coverage! The assertions and helpful print output make this very maintainable.
8. values.yaml:42-55 - Great documentation explaining why these values differ from Keycloak defaults.
Areas reviewed: Python, Helm/K8s, YAML, Security, Tests, CI
Commits: 1 commit, signed-off ✅ (missing emoji prefix ❌)
CI status: 2 failures (CodeQL HIGH, Deploy & Test)
Keycloak defaults (30min idle, 10h max session) cause "Signature has expired" errors on Kind/dev clusters after a few hours. Extend session lifetimes via configurable Helm values (7d idle, 30d max, 30min access token) and update existing realms on reinstall so the fix applies to clusters with a persisted Keycloak database. Closes rossoctl#1009 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
- Fix TOCTOU race in auth_secret.py: replace get_realms+create with create-first, catch-409-then-update pattern (matches agent_oauth_secret) - Wrap update_realm in try/except for idempotent concurrent execution - Fix CodeQL alert: use shared _keycloak_ssl_verify() in test instead of reimplementing SSL verification with verify=False - Extract get_session_lifetime_payload() into shared_utils.py to reduce duplication between agent_oauth_secret.py and auth_secret.py - Add production security warning for session lifetime values.yaml Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
b22f85e to
e7da558
Compare
Review feedback addressedRebased onto Must-fix
Suggestions
CI is running on the updated branch. |
Alan-Cha
left a comment
There was a problem hiding this comment.
This PR addresses a real pain point (Keycloak token expiration on dev clusters) and the second commit successfully fixed most of the prior review issues. However, there's a critical bug causing the CI failure: Helm's quote filter converts large integers to scientific notation, which Python's int() cannot parse.
Prior review issues addressed:
✅ CodeQL security alert fixed
✅ TOCTOU race conditions fixed
✅ Shared helper function extracted
✅ Production security warning added
❌ Emoji prefix still missing
New issues found:
🔴 CI failure: Helm quote filter produces scientific notation for large numbers (e.g., 2592000 → "2.592e+06")
Areas reviewed: Python, Helm/K8s, YAML, Security, Tests, CI logs
Commits: 2 commits, both signed-off ✅, missing emoji prefixes ❌
CI status: Deploy & Test failing due to Helm template bug
Fix: Remove | quote from the three session lifetime env vars in both job templates, or use printf "%d" to force decimal format.
| value: {{ .Values.agentOAuthSecret.spiffePrefix }} | ||
| - name: KEYCLOAK_SSO_SESSION_IDLE | ||
| value: {{ .Values.keycloak.sessionLifetimes.ssoSessionIdle | quote }} | ||
| - name: KEYCLOAK_SSO_SESSION_MAX |
There was a problem hiding this comment.
🔴 MUST-FIX - CI FAILURE ROOT CAUSE: Using | quote causes Helm to render large numbers in scientific notation (e.g., 2592000 → "2.592e+06"), which Python's int() cannot parse.
Error from CI: invalid literal for int() with base 10: '2.592e+06'
Fix: Remove the | quote filter:
value: {{ .Values.keycloak.sessionLifetimes.ssoSessionMax }}Or use printf to force decimal format:
value: {{ printf "%d" .Values.keycloak.sessionLifetimes.ssoSessionMax }}| {{- end }} | ||
| - name: KEYCLOAK_SSO_SESSION_IDLE | ||
| value: {{ .Values.keycloak.sessionLifetimes.ssoSessionIdle | quote }} | ||
| - name: KEYCLOAK_SSO_SESSION_MAX |
There was a problem hiding this comment.
🔴 MUST-FIX: Same | quote filter issue as agent-oauth-secret-job.yaml. Remove | quote from all three session lifetime env vars (lines 153, 155, 157).
| } | ||
| # Create-first, catch-409: avoids the TOCTOU race of | ||
| # get_realms → create when multiple job pods run concurrently. | ||
| keycloak_admin.create_realm(payload=realm_payload) |
There was a problem hiding this comment.
✅ PRAISE: Excellent fix for the TOCTOU race condition! The create-first, catch-409-then-update pattern is much safer than the previous get_realms check.
| realm_url, | ||
| headers={"Authorization": f"Bearer {access_token}"}, | ||
| timeout=10, | ||
| verify=_keycloak_ssl_verify(), |
There was a problem hiding this comment.
✅ PRAISE: Great fix - using _keycloak_ssl_verify() resolves the CodeQL security alert from the prior review.
| # Keycloak defaults (30min idle, 10h max) cause "Signature has expired" | ||
| # errors after a few hours. These values extend lifetimes for dev use. | ||
| # | ||
| # ⚠️ PRODUCTION WARNING: These defaults are intentionally permissive for |
There was a problem hiding this comment.
✅ PRAISE: Strong production warning - this is important context for operators who might deploy these dev-friendly defaults to production.
…tific notation
Helm's `quote` filter converts large integers like 2592000 to scientific
notation ("2.592e+06"), which Python's int() cannot parse. Use printf "%d"
with int conversion to force decimal format while keeping quoted string
output for valid YAML env var values.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Alan-Cha
left a comment
There was a problem hiding this comment.
Review Summary
Excellent work! This PR successfully addresses a real pain point (Keycloak session expiration on dev clusters) with a well-architected solution. All three prior review issues have been resolved:
✅ CodeQL security alert - Fixed (now uses _keycloak_ssl_verify())
✅ TOCTOU race conditions - Fixed (create-first, catch-409-then-update pattern)
✅ Scientific notation bug - Fixed (printf "%d" for Helm values)
✅ Shared helper function - Extracted (get_session_lifetime_payload())
✅ Production warning - Added to values.yaml
CI Status: All checks passing ✅
The implementation is clean, well-tested, and follows Kagenti patterns. The only remaining issue is the missing emoji prefix in commit messages (non-blocking nit).
Areas reviewed: Python, Helm/K8s, YAML, Security, Tests
Commits: 3 commits, all signed-off ✅, all missing emoji prefixes ❌
CI status: All passing ✅
Code Quality Highlights
✅ Race condition fix is excellent: The create-first, catch-409-then-update pattern in both agent_oauth_secret.py and auth_secret.py eliminates the TOCTOU race. The try/except wrapper around update_realm() ensures idempotent concurrent execution even with backoffLimit > 1.
✅ Shared helper reduces duplication: Extracting get_session_lifetime_payload() into shared_utils.py is the right architectural choice. Both job scripts now use the same env var reading logic.
✅ Helm template fix is correct: Using printf "%d" (int ...) solves the scientific notation issue (e.g., 2592000 → "2.592e+06") while keeping quoted output for valid YAML env var values.
✅ Test coverage is comprehensive: test_keycloak_session_lifetimes.py verifies realm settings via admin API and provides helpful output. Using _keycloak_ssl_verify() from conftest fixes the CodeQL HIGH security alert.
✅ Production warning: The values.yaml comment clearly warns about security implications of long-lived sessions and recommends shorter lifetimes for production.
Remaining Nits (non-blocking)
All commits and PR title are missing emoji prefixes per Kagenti git:commit conventions:
- Commit 1:
🐛 fix(auth): extend Keycloak... - Commit 2:
🐛 fix(auth): address PR review... - Commit 3:
🐛 fix(helm): use printf %d... - PR title:
🐛 fix(auth): extend Keycloak...
These are style nits that don't block merge.
Overall: This is production-ready code. The iterative fixes across three commits show excellent attention to detail. Ready to merge! 🚀
Summary
keycloak.sessionLifetimesHelm values (7d idle, 30d max session, 30min access token)Details
Keycloak defaults (30min idle timeout, 10h max session) cause token refresh failures after a few hours on dev clusters. The UI's
updateToken()call fails with "Signature has expired" and can't recover without clearing the Keycloak session. Reinstalling doesn't help because the realm persists in PostgreSQL.This fix:
agent_oauth_secret.py—create_realm()setsssoSessionIdleTimeout,ssoSessionMaxLifespan,accessTokenLifespanfrom env vars. On 409 (realm exists), updates the realm with new lifetimes.auth_secret.py— Bootstrap realm creation includes the same session lifetime settings, and updates existing realms.values.yaml— Newkeycloak.sessionLifetimessection with dev-friendly defaults.agent-oauth-secret-job.yamlandui-oauth-secret-job.yamlpass the env vars.Test plan
kind-full-test.shcurl .../admin/realms/kagenti | jq '{ssoSessionIdleTimeout, ssoSessionMaxLifespan, accessTokenLifespan}'pytest kagenti/tests/e2e/common/test_keycloak_session_lifetimes.py -vCloses #1009
🤖 Generated with Claude Code