Skip to content

feat: end-to-end Keycloak authentication, RBAC, and Python SDK integration#367

Open
mahil-2040 wants to merge 14 commits into
volcano-sh:mainfrom
mahil-2040:feat/keycloak-deployment-realm-setup
Open

feat: end-to-end Keycloak authentication, RBAC, and Python SDK integration#367
mahil-2040 wants to merge 14 commits into
volcano-sh:mainfrom
mahil-2040:feat/keycloak-deployment-realm-setup

Conversation

@mahil-2040

@mahil-2040 mahil-2040 commented May 28, 2026

Copy link
Copy Markdown
Contributor

What type of PR is this?

/kind feature

What this PR does / why we need it:

This PR introduces end-to-end external user authentication and authorization using Keycloak as the identity provider. It expands the initial scope to include the complete flow in a single PR: Keycloak deployment, Router integration, Resource-Level Access Control (RLAC), Python SDK support, and the formal design proposal.

1. Design Proposal

  • Adds docs/design/keycloak-proposal.md detailing the architecture, request flow, and implementation decisions for the external authentication layer.

2. Keycloak Deployment

  • Declarative realm import with agentcube realm, role hierarchy (sandbox:invokesandbox:manageadmin), and OAuth2 clients.
  • Production-hardened Deployment with security contexts, health probes, and Helm validation guards.

3. Router OIDC Integration & RBAC

  • OIDC token validator using go-oidc with automatic JWKS key caching.
  • Authentication middleware validates Bearer JWT tokens from Keycloak.
  • RBAC middleware enforces sandbox:invoke realm role on all /v1/* endpoints.
  • Feature-gated behind --enable-external-auth (default: off, zero impact).

4. Downstream Identity Forwarding & RLAC

  • Router embeds user identity (sub) in internal PicoD JWT claims.
  • Router sends X-AgentCube-User-Id header to WorkloadManager.
  • WorkloadManager (RLAC): Tags newly created sandbox CRDs with the agentcube.io/owner: <user_id> label.
  • Router (RLAC): Verifies that the caller's JWT subject matches the sandbox's OwnerID before proxying requests.

5. Python SDK Auth Integration

  • Introduces pluggable auth provider pattern (AuthProvider protocol).
  • Adds ServiceAccountAuth for client_credentials flow with automatic token refresh.
  • Adds TokenAuth for static tokens.
  • Updates clients (Control Plane and Data Plane) to seamlessly handle token injection.

6. Testing

  • Unit tests for OIDC validator, auth middleware, RBAC, identity forwarding, and SDK auth.
  • E2E tests deploying real Keycloak in Kind cluster to validate unauthenticated rejection, invalid tokens, valid invocations, and RLAC ownership blocks.

Which issue(s) this PR fixes:
Fixes Part of #243

Special notes for your reviewer:

  • External auth is opt-in via keycloak.enabled=true. Existing deployments are unaffected.
  • Token Exchange (RFC 8693) is not used - the Router forwards the user identity directly since mTLS provides transport-level security between components.
  • New Go dependency: github.com/coreos/go-oidc/v3 (used by Kubernetes itself).

Does this PR introduce a user-facing change?:

yes

Add Keycloak OIDC authentication support, Resource-Level Access Control (RLAC), and Python SDK auth integration. When enabled via `keycloak.enabled=true`, the Router requires a valid Bearer token with the `sandbox:invoke` realm role, and users can only access sandboxes they created. The Python SDK now supports seamless `client_credentials` authentication with automatic token refresh.

Copilot AI review requested due to automatic review settings May 28, 2026 18:25
@volcano-sh-bot

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
Once this PR has been reviewed and has the lgtm label, please assign hzxuzhonghu for approval. For more information see the Kubernetes Code Review Process.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a Keycloak deployment, service, and realm configuration to the Helm chart for external user authentication. The reviewer identified several critical security and configuration issues: wildcard redirect URIs and web origins on the confidential SDK client should be configurable; the admin password should be sourced from a Kubernetes Secret instead of plaintext; production mode lacks support for external databases and proxy/HTTPS settings; SSL requirements should be dynamically enabled; and global image pull secrets need to be propagated to the Keycloak pod template.

Comment thread manifests/charts/base/templates/keycloak/keycloak-realm.yaml Outdated
Comment thread manifests/charts/base/templates/keycloak/keycloak.yaml Outdated
Comment thread manifests/charts/base/templates/keycloak/keycloak.yaml Outdated
Comment thread manifests/charts/base/templates/keycloak/keycloak-realm.yaml Outdated
Comment thread manifests/charts/base/templates/keycloak/keycloak.yaml Outdated

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

Adds an optional Keycloak deployment to the Helm base chart to support external user authentication, including default values, a Deployment/Service, and a realm-import ConfigMap.

Changes:

  • Introduces keycloak configuration block in chart values.
  • Adds Keycloak Deployment + Service template gated by keycloak.enabled.
  • Adds a realm JSON import ConfigMap template for bootstrapping clients/roles.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 10 comments.

File Description
manifests/charts/base/values.yaml Adds configurable values for enabling and running a Keycloak instance
manifests/charts/base/templates/keycloak/keycloak.yaml Adds Deployment/Service templates for Keycloak
manifests/charts/base/templates/keycloak/keycloak-realm.yaml Adds ConfigMap for importing an initial realm configuration

Comment thread manifests/charts/base/values.yaml Outdated
Comment thread manifests/charts/base/templates/keycloak/keycloak.yaml Outdated
Comment thread manifests/charts/base/templates/keycloak/keycloak.yaml Outdated
Comment thread manifests/charts/base/templates/keycloak/keycloak-realm.yaml Outdated
Comment thread manifests/charts/base/templates/keycloak/keycloak-realm.yaml Outdated
Comment thread manifests/charts/base/templates/keycloak/keycloak-realm.yaml Outdated
Comment thread manifests/charts/base/templates/keycloak/keycloak.yaml Outdated
Comment thread manifests/charts/base/templates/keycloak/keycloak.yaml Outdated
Comment thread manifests/charts/base/templates/keycloak/keycloak.yaml Outdated
Comment thread manifests/charts/base/templates/keycloak/keycloak.yaml Outdated
@codecov-commenter

codecov-commenter commented May 28, 2026

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 61.75549% with 122 lines in your changes missing coverage. Please review.
✅ Project coverage is 58.05%. Comparing base (524e55e) to head (7797846).
⚠️ Report is 119 commits behind head on main.

Files with missing lines Patch % Lines
pkg/router/auth.go 45.71% 36 Missing and 2 partials ⚠️
pkg/router/oidc.go 64.28% 21 Missing and 14 partials ⚠️
pkg/router/server.go 19.23% 17 Missing and 4 partials ⚠️
pkg/workloadmanager/identity.go 59.52% 13 Missing and 4 partials ⚠️
pkg/router/handlers.go 81.81% 5 Missing and 1 partial ⚠️
pkg/router/session_manager.go 85.00% 2 Missing and 1 partial ⚠️
pkg/workloadmanager/handlers.go 90.90% 1 Missing and 1 partial ⚠️
❗ Your organization needs to install the Codecov GitHub app to enable full functionality.
Additional details and impacted files
@@             Coverage Diff             @@
##             main     #367       +/-   ##
===========================================
+ Coverage   47.57%   58.05%   +10.48%     
===========================================
  Files          30       37        +7     
  Lines        2819     3474      +655     
===========================================
+ Hits         1341     2017      +676     
+ Misses       1338     1247       -91     
- Partials      140      210       +70     
Flag Coverage Δ
unittests 58.05% <61.75%> (+10.48%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Comment thread manifests/charts/addons/keycloak/templates/realm-config.yaml
Comment thread manifests/charts/base/templates/keycloak/keycloak.yaml Outdated
Comment thread manifests/charts/base/templates/keycloak/keycloak.yaml Outdated
Comment thread manifests/charts/base/templates/keycloak/keycloak.yaml Outdated

@hzxuzhonghu hzxuzhonghu left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

before adding a bunch of yamls, can you first add a docs exmplain about the proposal and the workflow

@mahil-2040

mahil-2040 commented May 30, 2026

Copy link
Copy Markdown
Contributor Author

before adding a bunch of yamls, can you first add a docs exmplain about the proposal and the workflow

@hzxuzhonghu @acsoto
Yeah sure, it's a good suggestion, so now should i delete this PR, and make a fresh PR in which i will first make a doc explaining about the proposal and the workflow, and when it is approved then only i will push the .yaml code, or should i continue with this only this time, and follow this approach of making a doc from next feature?

@mahil-2040 mahil-2040 requested a review from acsoto June 1, 2026 06:00
@acsoto

acsoto commented Jun 1, 2026

Copy link
Copy Markdown
Member

Either is ok

- Declarative Realm Import: Created a ConfigMap with the realm JSON defining
  clients (agentcube-sdk, agentcube-router, workloadmanager, agentcube-admin)
  and role hierarchy (sandbox:invoke -> sandbox:manage -> admin).
- Deployment & Service: Added Keycloak Deployment and Service manifests
  with management-port health probes and a 300s startupProbe window.
- Helm Integration: Added keycloak configuration values to values.yaml,
  gated behind 'keycloak.enabled: false' to ensure zero impact by default.

Signed-off-by: Mahil Patel <mahilpatel0808@gmail.com>
- Parameterized SDK redirect URIs with secure defaults, added support for secretKeyRef for admin/database credentials, and made sslRequired enforcement dynamic based on devMode.
- Added configuration blocks for external databases (PostgreSQL/MySQL) and reverse proxy settings (headers, hostname).
- Propagated global imagePullSecrets, decoupled Service targetPort by using the named 'http' port, and dynamically derived  the realm import filename from Helm values.

Signed-off-by: Mahil Patel <mahilpatel0808@gmail.com>
- Added fail-fast validation for database and proxy settings in production mode
- Decoupled credentials into chart-managed Secrets with required-value checks
- Added restricted securityContext for Keycloak pod and container
- Migrated realm configuration to Keycloak 26 default roles and client secrets

Signed-off-by: Mahil Patel <mahilpatel0808@gmail.com>
Copilot AI review requested due to automatic review settings June 2, 2026 17:43
@mahil-2040 mahil-2040 force-pushed the feat/keycloak-deployment-realm-setup branch from 5f5d385 to 9f8f5df Compare June 2, 2026 17:43
@mahil-2040

Copy link
Copy Markdown
Contributor Author

Either is ok

Okay i will continue in this one only for this time.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 4 out of 4 changed files in this pull request and generated 7 comments.

Comment thread manifests/charts/base/templates/keycloak/keycloak-secrets.yaml Outdated
Comment thread manifests/charts/base/values.yaml Outdated
Comment thread manifests/charts/base/values.yaml Outdated
Comment thread manifests/charts/base/templates/keycloak/keycloak.yaml Outdated
Comment thread manifests/charts/base/templates/keycloak/keycloak-realm.yaml Outdated
Comment thread manifests/charts/base/templates/keycloak/keycloak.yaml Outdated
Comment thread manifests/charts/base/templates/keycloak/keycloak.yaml Outdated
- Require explicit Keycloak admin and client credentials
- Enforced production Secret and external DB validation
- Fixed Secret key references and quote realm import filename

Signed-off-by: Mahil Patel <mahilpatel0808@gmail.com>
@hzxuzhonghu

Copy link
Copy Markdown
Member

@mahil-2040 I donot see your design

Signed-off-by: Mahil Patel <mahilpatel0808@gmail.com>
@mahil-2040 mahil-2040 changed the title feat: deployed Keycloak and configure agentcube feat: end-to-end Keycloak authentication, RLAC, and Python SDK integration Jun 3, 2026
Copilot AI review requested due to automatic review settings June 3, 2026 18:16

@hzxuzhonghu hzxuzhonghu left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would also suggest separating keycloack as a separate addon, not place it in agentcube chart

…sign

- Extracted Keycloak into a standalone addon chart (manifests/charts/addons/keycloak) to ensure the core AgentCube chart remains identity-provider agnostic.
- Added HA replica support and wildcard URI security validation to the Keycloak addon.
- Replaced keycloak.enabled in the base chart with generic OIDC configuration (router.oidc.issuerUrl, audience, and a required rolesClaim for dynamic role extraction).

Signed-off-by: Mahil Patel <mahilpatel0808@gmail.com>
Copilot AI review requested due to automatic review settings June 4, 2026 11:59

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated 6 comments.

Comment thread manifests/charts/base/templates/agentcube-router.yaml
Comment thread manifests/charts/addons/keycloak/values.yaml
Comment thread manifests/charts/addons/keycloak/Chart.yaml Outdated
Comment thread manifests/charts/addons/keycloak/templates/deployment.yaml
Comment thread manifests/charts/addons/keycloak/templates/deployment.yaml
Comment thread manifests/charts/addons/keycloak/templates/deployment.yaml
@mahil-2040

Copy link
Copy Markdown
Contributor Author

I would also suggest separating keycloack as a separate addon, not place it in agentcube chart

Yeah, This is a great suggestion, it makes sense to keep the core agentcube chart lightweight and identity-provider agnostic!

I have made the following changes to implement this:

  1. Moved all Keycloak templates out of the base chart into a new standalone addon chart (manifests/charts/addons/keycloak).
  2. Removed all keycloak configurations from the base values.yaml.

- Quoted OIDC flags in router deployment to prevent YAML parsing errors
- Fixed inaccurate existingSecret comment in values.yaml
- Upgraded Keycloak addon Chart.yaml to apiVersion v2 (Helm 3)
- Added validation to block scaling replicas when using embedded H2 database (devMode)

Signed-off-by: Mahil Patel <mahilpatel0808@gmail.com>
@mahil-2040

Copy link
Copy Markdown
Contributor Author

@hzxuzhonghu @acsoto Does the design look good? Should I start implementing now?

…values

Signed-off-by: Mahil Patel <mahilpatel0808@gmail.com>
- Implemented provider-agnostic OIDC authentication with JWKS caching and strict JWT algorithm validation.
- Added RBAC middleware to enforce configurable role-based access control.
- Enhanced SessionManager to securely forward verified external user identities to WorkloadManager.

Signed-off-by: Mahil Patel <mahilpatel0808@gmail.com>
Copilot AI review requested due to automatic review settings June 5, 2026 08:40

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 19 out of 20 changed files in this pull request and generated 9 comments.

Comment thread pkg/router/oidc.go
Comment thread pkg/router/session_manager.go
Comment thread pkg/router/session_manager.go
Comment thread pkg/router/oidc.go Outdated
Comment thread pkg/router/oidc.go Outdated
Comment thread pkg/router/oidc.go Outdated
Comment thread pkg/router/session_manager.go
Comment thread pkg/router/oidc_test.go Outdated
Comment thread pkg/router/oidc_test.go Outdated
…dentity header

Signed-off-by: Mahil Patel <mahilpatel0808@gmail.com>
…nforcement

- Enforced resource-level access control (RLAC) in backend and reject router JWTs missing sub claim.
- Added Python SDK pluggable auth providers and routed data plane traffic via Router proxy.
- Wired Keycloak realm imports, client secrets, and service account roles dynamically.
- Added OIDC E2E tests

Signed-off-by: Mahil Patel <mahilpatel0808@gmail.com>
Signed-off-by: Mahil Patel <mahilpatel0808@gmail.com>
Copilot AI review requested due to automatic review settings June 5, 2026 22:26

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 41 out of 42 changed files in this pull request and generated 4 comments.

Comments suppressed due to low confidence (3)

sdk-python/agentcube/auth.py:1

  • Two concrete failure modes here: (1) if access_token is missing, this raises KeyError or later returns "", which can silently produce Authorization: Bearer and hard-to-debug 401s; raise a clear exception when the token field is missing/empty. (2) if expires_in is less than the refresh buffer (30s), _expires_at becomes “in the past” and every get_token() call will refetch; clamp the computed expiry so it never goes backward (e.g., ensure at least a small positive TTL).
    test/e2e/run_e2e.sh:1
  • Token acquisition has no validation/retries: if the port-forward isn’t ready or Keycloak returns an error page, jq -r can produce null/empty, and the suite will proceed with invalid tokens (causing confusing downstream failures). Add a small retry loop (or explicit HTTP status checks) and fail fast if either token is empty/null.
    sdk-python/tests/test_auth.py:1
  • time is imported but not used in this test file. Removing it keeps the test module clean and avoids linter noise.

Comment thread pkg/router/session_manager.go
Comment thread pkg/workloadmanager/identity.go
Comment thread pkg/workloadmanager/workload_builder.go
Comment thread pkg/workloadmanager/workload_builder.go
…d fixed python lint issue

Signed-off-by: Mahil Patel <mahilpatel0808@gmail.com>
@mahil-2040 mahil-2040 requested a review from hzxuzhonghu June 6, 2026 05:26
@mahil-2040

Copy link
Copy Markdown
Contributor Author

@acsoto @hzxuzhonghu Please review this!!

Comment thread cmd/router/main.go
Comment on lines +50 to +53
oidcIssuerURL = flag.String("oidc-issuer-url", "", "OIDC provider issuer URL, enables external auth when set")
oidcAudience = flag.String("oidc-audience", "agentcube-api", "Expected audience (aud) claim in the access token")
oidcRolesClaim = flag.String("oidc-roles-claim", "", "JSON path to roles array in the JWT (e.g., realm_access.roles)")
oidcRequiredRole = flag.String("oidc-required-role", "", "Role required to access the API (e.g., sandbox:invoke)")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Prefer update to

oidc-issuer-url -> jwt-issuer-url
oidc-roles-claim -> jwt-role-claim
oidc-required-role -> jwt-required-role, this may need to be deleted, once we support authz, we can put iy in the api


## Before you begin

1. Follow the [Getting Started](../getting-started.md) guide to install

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Following the getstarted, it will not install spire as you showed in L33-L36


| Item | Details |
|---|---|
| **Roles** | `sandbox:invoke` (default for all users), `sandbox:manage` (inherits invoke), `admin` (inherits manage) |

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

elaborate a little bit more, what is the permission of each role

Comment on lines +41 to +49
existingSecretServiceKey: "client-service-secret"
existingSecretRouterKey: "client-router-secret"
existingSecretAdminKey: "client-admin-secret"
service:
secret: ""
router:
secret: ""
admin:
secret: ""

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please explain what's these secret are, and how to setup them

```bash
curl -s -w "\nHTTP Status: %{http_code}\n" \
-H "Authorization: Bearer $KEYCLOAK_TOKEN" \
http://localhost:8081/v1/namespaces/default/agent-runtimes/sample-agent/invocations/

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I doubt this is not actually run at all, the invocation is not complete


| Client ID | Type | Purpose |
|-----------|------|---------|
| `agentcube-service` | Confidential (`client_credentials`) | External backend applications and automated scripts using the Python SDK (Machine-to-Machine / M2M) |

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

confusing,
does it mean caller to agentcube-service?

Or agentcube-service is the client?

| `agentcube-service` | Confidential (`client_credentials`) | External backend applications and automated scripts using the Python SDK (Machine-to-Machine / M2M) |
| `agentcube-sdk` | Public (`authorization_code` + PKCE) | Human end users interacting via the CLI or browser (Interactive) |
| `agentcube-router` | Confidential (`client_credentials`) | Internal Router service identity |
| `agentcube-admin` | Confidential (`client_credentials`) | Administrative operations |

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

all these client-id need to be explained

Comment on lines +16 to +17
existingSecret: "" # Name of a pre-existing Secret containing admin credentials
existingSecretKey: "admin-password" # Key within the Secret holding the password

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

existingSecret is a bad name? Can you imagine how a user know the meaning of it from this name?

@hzxuzhonghu hzxuzhonghu left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have not read the implement, please address these comments first and help me understand some concepts. Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants